Skip to main content

store_api/
region_engine.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Region Engine's definition
16
17use std::any::Any;
18use std::collections::{BTreeSet, HashMap};
19use std::fmt::{Debug, Display};
20use std::pin::Pin;
21use std::sync::{Arc, Mutex};
22use std::time::Instant;
23
24use api::greptime_proto::v1::meta::{GrantedRegion as PbGrantedRegion, RegionRole as PbRegionRole};
25use api::region::RegionResponse;
26use async_trait::async_trait;
27use common_error::ext::BoxedError;
28use common_recordbatch::adapter::RegionQueryStatCounters;
29use common_recordbatch::{EmptyRecordBatchStream, QueryMemoryTracker, SendableRecordBatchStream};
30use common_time::Timestamp;
31use datafusion_execution::memory_pool::{MemoryPool, UnboundedMemoryPool};
32use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
33use datafusion_physical_plan::{DisplayAs, DisplayFormatType, PhysicalExpr};
34use datatypes::schema::SchemaRef;
35use datatypes::series::SeriesOrdering;
36use datatypes::series::frame::LabelDecodeSpec;
37use datatypes::series::raw::RawSeriesChunk;
38use datatypes::series::samples::SeriesSchema;
39use futures::FutureExt;
40use futures::Stream;
41use futures::future::{BoxFuture, join_all};
42use serde::{Deserialize, Serialize};
43use tokio::sync::Semaphore;
44
45use crate::logstore::entry;
46use crate::metadata::RegionMetadataRef;
47use crate::region_request::{
48    BatchRegionDdlRequest, RegionCatchupRequest, RegionOpenRequest, RegionPutRequest, RegionRequest,
49};
50use crate::storage::{ColumnId, FileId, RegionId, ScanRequest, SequenceNumber};
51
52/// The settable region role state.
53#[derive(Debug, PartialEq, Eq, Clone, Copy)]
54pub enum SettableRegionRoleState {
55    Follower,
56    DowngradingLeader,
57    /// Exit staging mode and return to normal leader state. Only allowed from staging state.
58    Leader,
59    /// Enter staging mode. Region remains writable but disables checkpoint, compaction and flush. Only allowed from normal leader state.
60    StagingLeader,
61}
62
63impl Display for SettableRegionRoleState {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self {
66            SettableRegionRoleState::Follower => write!(f, "Follower"),
67            SettableRegionRoleState::DowngradingLeader => write!(f, "Leader(Downgrading)"),
68            SettableRegionRoleState::Leader => write!(f, "Leader"),
69            SettableRegionRoleState::StagingLeader => write!(f, "Leader(Staging)"),
70        }
71    }
72}
73
74impl From<SettableRegionRoleState> for RegionRole {
75    fn from(value: SettableRegionRoleState) -> Self {
76        match value {
77            SettableRegionRoleState::Follower => RegionRole::Follower,
78            SettableRegionRoleState::DowngradingLeader => RegionRole::DowngradingLeader,
79            SettableRegionRoleState::Leader => RegionRole::Leader,
80            SettableRegionRoleState::StagingLeader => RegionRole::StagingLeader,
81        }
82    }
83}
84
85/// The request to set region role state.
86#[derive(Debug, PartialEq, Eq)]
87pub struct SetRegionRoleStateRequest {
88    region_id: RegionId,
89    region_role_state: SettableRegionRoleState,
90}
91
92/// The success response of setting region role state.
93#[derive(Debug, PartialEq, Eq)]
94pub enum SetRegionRoleStateSuccess {
95    File,
96    Relational,
97    Mito {
98        last_entry_id: entry::Id,
99    },
100    Metric {
101        last_entry_id: entry::Id,
102        metadata_last_entry_id: entry::Id,
103    },
104}
105
106impl SetRegionRoleStateSuccess {
107    /// Returns a [SetRegionRoleStateSuccess::File].
108    pub fn file() -> Self {
109        Self::File
110    }
111
112    /// Returns a [SetRegionRoleStateSuccess::Relational].
113    pub fn relational() -> Self {
114        Self::Relational
115    }
116
117    /// Returns a [SetRegionRoleStateSuccess::Mito] with the `last_entry_id`.
118    pub fn mito(last_entry_id: entry::Id) -> Self {
119        SetRegionRoleStateSuccess::Mito { last_entry_id }
120    }
121
122    /// Returns a [SetRegionRoleStateSuccess::Metric] with the `last_entry_id` and `metadata_last_entry_id`.
123    pub fn metric(last_entry_id: entry::Id, metadata_last_entry_id: entry::Id) -> Self {
124        SetRegionRoleStateSuccess::Metric {
125            last_entry_id,
126            metadata_last_entry_id,
127        }
128    }
129}
130
131impl SetRegionRoleStateSuccess {
132    /// Returns the last entry id of the region.
133    pub fn last_entry_id(&self) -> Option<entry::Id> {
134        match self {
135            SetRegionRoleStateSuccess::File | SetRegionRoleStateSuccess::Relational => None,
136            SetRegionRoleStateSuccess::Mito { last_entry_id } => Some(*last_entry_id),
137            SetRegionRoleStateSuccess::Metric { last_entry_id, .. } => Some(*last_entry_id),
138        }
139    }
140
141    /// Returns the last entry id of the metadata of the region.
142    pub fn metadata_last_entry_id(&self) -> Option<entry::Id> {
143        match self {
144            SetRegionRoleStateSuccess::File | SetRegionRoleStateSuccess::Relational => None,
145            SetRegionRoleStateSuccess::Mito { .. } => None,
146            SetRegionRoleStateSuccess::Metric {
147                metadata_last_entry_id,
148                ..
149            } => Some(*metadata_last_entry_id),
150        }
151    }
152}
153
154/// The response of setting region role state.
155#[derive(Debug)]
156pub enum SetRegionRoleStateResponse {
157    Success(SetRegionRoleStateSuccess),
158    NotFound,
159    InvalidTransition(BoxedError),
160}
161
162impl SetRegionRoleStateResponse {
163    /// Returns a [SetRegionRoleStateResponse::Success] with the `File` success.
164    pub fn success(success: SetRegionRoleStateSuccess) -> Self {
165        Self::Success(success)
166    }
167
168    /// Returns a [SetRegionRoleStateResponse::InvalidTransition] with the error.
169    pub fn invalid_transition(error: BoxedError) -> Self {
170        Self::InvalidTransition(error)
171    }
172
173    /// Returns true if the response is a [SetRegionRoleStateResponse::NotFound].
174    pub fn is_not_found(&self) -> bool {
175        matches!(self, SetRegionRoleStateResponse::NotFound)
176    }
177
178    /// Returns true if the response is a [SetRegionRoleStateResponse::InvalidTransition].
179    pub fn is_invalid_transition(&self) -> bool {
180        matches!(self, SetRegionRoleStateResponse::InvalidTransition(_))
181    }
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct GrantedRegion {
186    pub region_id: RegionId,
187    pub region_role: RegionRole,
188    /// A non-zero id the metadata plane attaches to the Follower leases of a region migration's
189    /// target before the route names that target, `None` for a lease without one. It reaches the
190    /// engine through [`RegionEngine::set_region_role_with_lease`]. An engine may keep it with the
191    /// lease, and may use its presence to keep such a lease from demoting a region that the
192    /// migration's catchup made writable and that still awaits a Leader or StagingLeader lease.
193    /// Engines must not interpret its value.
194    pub candidate_lease_id: Option<u64>,
195    pub extensions: HashMap<String, Vec<u8>>,
196}
197
198impl GrantedRegion {
199    pub fn new(region_id: RegionId, region_role: RegionRole) -> Self {
200        Self {
201            region_id,
202            region_role,
203            candidate_lease_id: None,
204            extensions: HashMap::new(),
205        }
206    }
207}
208
209impl From<GrantedRegion> for PbGrantedRegion {
210    fn from(value: GrantedRegion) -> Self {
211        PbGrantedRegion {
212            region_id: value.region_id.as_u64(),
213            role: PbRegionRole::from(value.region_role).into(),
214            candidate_lease_id: value.candidate_lease_id.unwrap_or_default(),
215            extensions: value.extensions,
216        }
217    }
218}
219
220impl From<PbGrantedRegion> for GrantedRegion {
221    fn from(value: PbGrantedRegion) -> Self {
222        GrantedRegion {
223            region_id: RegionId::from_u64(value.region_id),
224            region_role: value.role().into(),
225            // 0 means the lease carries no candidate lease id.
226            candidate_lease_id: (value.candidate_lease_id != 0).then_some(value.candidate_lease_id),
227            extensions: value.extensions,
228        }
229    }
230}
231
232/// The role of the region.
233/// TODO(weny): rename it to `RegionRoleState`
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
235pub enum RegionRole {
236    // Readonly region(mito2)
237    Follower,
238    // Writable region(mito2), Readonly region(file).
239    Leader,
240    // Leader is in staging mode.
241    //
242    // This is leader-like and writable, but it follows the staging workflow
243    // semantics instead of a normal leader's steady state.
244    StagingLeader,
245    // Leader is downgrading to follower.
246    //
247    // This state is used to prevent new write requests.
248    DowngradingLeader,
249}
250
251impl Display for RegionRole {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        match self {
254            RegionRole::Follower => write!(f, "Follower"),
255            RegionRole::Leader => write!(f, "Leader"),
256            RegionRole::StagingLeader => write!(f, "Leader(Staging)"),
257            RegionRole::DowngradingLeader => write!(f, "Leader(Downgrading)"),
258        }
259    }
260}
261
262impl RegionRole {
263    pub fn writable(&self) -> bool {
264        matches!(self, RegionRole::Leader | RegionRole::StagingLeader)
265    }
266}
267
268impl From<RegionRole> for PbRegionRole {
269    fn from(value: RegionRole) -> Self {
270        match value {
271            RegionRole::Follower => PbRegionRole::Follower,
272            RegionRole::Leader => PbRegionRole::Leader,
273            RegionRole::StagingLeader => PbRegionRole::StagingLeader,
274            RegionRole::DowngradingLeader => PbRegionRole::DowngradingLeader,
275        }
276    }
277}
278
279impl From<PbRegionRole> for RegionRole {
280    fn from(value: PbRegionRole) -> Self {
281        match value {
282            PbRegionRole::Leader => RegionRole::Leader,
283            PbRegionRole::StagingLeader => RegionRole::StagingLeader,
284            PbRegionRole::Follower => RegionRole::Follower,
285            PbRegionRole::DowngradingLeader => RegionRole::DowngradingLeader,
286        }
287    }
288}
289
290/// Output partition properties of the [RegionScanner].
291#[derive(Debug)]
292pub enum ScannerPartitioning {
293    /// Unknown partitioning scheme with a known number of partitions
294    Unknown(usize),
295}
296
297impl ScannerPartitioning {
298    /// Returns the number of partitions.
299    pub fn num_partitions(&self) -> usize {
300        match self {
301            ScannerPartitioning::Unknown(num_partitions) => *num_partitions,
302        }
303    }
304}
305
306/// Represents one data range within a partition
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct PartitionRange {
309    /// Start time of time index column. Inclusive.
310    pub start: Timestamp,
311    /// End time of time index column. Exclusive.
312    pub end: Timestamp,
313    /// Number of rows in this range. Is used to balance ranges between partitions.
314    pub num_rows: usize,
315    /// Identifier to this range. Assigned by storage engine.
316    pub identifier: usize,
317}
318
319/// Properties of the [RegionScanner].
320#[derive(Debug, Default)]
321pub struct ScannerProperties {
322    /// A 2-dim partition ranges.
323    ///
324    /// The first dim vector's length represents the output partition number. The second
325    /// dim is ranges within one partition.
326    pub partitions: Vec<Vec<PartitionRange>>,
327
328    /// Whether scanner is in append-only mode.
329    append_mode: bool,
330
331    /// Total rows that **may** return by scanner. This field is only read iff
332    /// [ScannerProperties::append_mode] is true.
333    total_rows: usize,
334
335    /// Whether total_rows is exact before applying query predicates.
336    total_rows_is_exact: bool,
337
338    /// Exact rows after static query predicates, prepared against the scanner's
339    /// read view. Unknown unless an engine has proved all visibility conditions.
340    exact_num_rows: Option<usize>,
341
342    /// Whether to yield an empty batch to distinguish partition ranges.
343    pub distinguish_partition_range: bool,
344
345    /// The target partitions of the scanner. 0 indicates using the number of partitions as target partitions.
346    target_partitions: usize,
347
348    /// Whether the scanner reads one logical metric region, including a physical
349    /// metric region constrained by a table-ID filter.
350    logical_region: bool,
351
352    /// Region id that should receive query-load metrics for this scanner.
353    query_load_region_id: Option<RegionId>,
354    /// Counters that should receive query-load metrics for this scanner.
355    query_stat_counters: Option<RegionQueryStatCounters>,
356}
357
358impl ScannerProperties {
359    /// Sets append mode for scanner.
360    pub fn with_append_mode(mut self, append_mode: bool) -> Self {
361        self.append_mode = append_mode;
362        self
363    }
364
365    /// Sets total rows for scanner.
366    pub fn with_total_rows(mut self, total_rows: usize) -> Self {
367        self.total_rows = total_rows;
368        self
369    }
370
371    /// Sets whether the source row count is exact before query predicates.
372    pub fn with_total_rows_is_exact(mut self, exact: bool) -> Self {
373        self.total_rows_is_exact = exact;
374        self
375    }
376
377    /// Sets an exact count for the complete scan, including static predicates.
378    pub fn with_exact_num_rows(mut self, rows: Option<usize>) -> Self {
379        self.exact_num_rows = rows;
380        self
381    }
382
383    /// Returns the prepared exact count after all static scan predicates.
384    pub fn exact_num_rows(&self) -> Option<usize> {
385        self.exact_num_rows
386    }
387
388    /// Invalidates prepared statistics when the scan gains a dynamic predicate.
389    pub fn clear_exact_num_rows(&mut self) {
390        self.exact_num_rows = None;
391    }
392
393    /// Creates a new [`ScannerProperties`] with the given partitioning.
394    pub fn new(partitions: Vec<Vec<PartitionRange>>, append_mode: bool, total_rows: usize) -> Self {
395        Self {
396            partitions,
397            append_mode,
398            total_rows,
399            total_rows_is_exact: false,
400            exact_num_rows: None,
401            distinguish_partition_range: false,
402            target_partitions: 0,
403            logical_region: false,
404            query_load_region_id: None,
405            query_stat_counters: None,
406        }
407    }
408
409    /// Updates the properties with the given [PrepareRequest].
410    pub fn prepare(&mut self, request: PrepareRequest) {
411        if let Some(ranges) = request.ranges {
412            if (self.exact_num_rows.is_some() || self.total_rows_is_exact)
413                && !same_partition_ranges(&self.partitions, &ranges)
414            {
415                self.exact_num_rows = None;
416                self.total_rows_is_exact = false;
417            }
418            self.partitions = ranges;
419        }
420        if let Some(distinguish_partition_range) = request.distinguish_partition_range {
421            self.distinguish_partition_range = distinguish_partition_range;
422        }
423        if let Some(target_partitions) = request.target_partitions {
424            self.target_partitions = target_partitions;
425        }
426    }
427
428    /// Returns the number of actual partitions.
429    pub fn num_partitions(&self) -> usize {
430        self.partitions.len()
431    }
432
433    pub fn append_mode(&self) -> bool {
434        self.append_mode
435    }
436
437    pub fn total_rows(&self) -> usize {
438        self.total_rows
439    }
440
441    /// Returns whether the source row count is exact before query predicates.
442    pub fn total_rows_is_exact(&self) -> bool {
443        self.total_rows_is_exact
444    }
445
446    /// Returns whether the scanner reads one logical metric region, including a
447    /// physical metric region constrained by a table-ID filter.
448    pub fn is_logical_region(&self) -> bool {
449        self.logical_region
450    }
451
452    /// Returns the target partitions of the scanner. If it is not set, returns the number of partitions.
453    pub fn target_partitions(&self) -> usize {
454        if self.target_partitions == 0 {
455            self.num_partitions()
456        } else {
457            self.target_partitions
458        }
459    }
460
461    /// Sets whether the scanner reads one logical metric region.
462    pub fn set_logical_region(&mut self, logical_region: bool) {
463        self.logical_region = logical_region;
464    }
465
466    /// Returns the region id that should receive query-load metrics.
467    pub fn query_load_region_id(&self) -> Option<RegionId> {
468        self.query_load_region_id
469    }
470
471    /// Returns the counters that should receive query-load metrics.
472    pub fn query_stat_counters(&self) -> Option<RegionQueryStatCounters> {
473        self.query_stat_counters.clone()
474    }
475
476    /// Sets the region id that should receive query-load metrics.
477    pub fn set_query_load_region_id(&mut self, region_id: RegionId) {
478        self.query_load_region_id = Some(region_id);
479    }
480
481    /// Sets the counters that should receive query-load metrics.
482    pub fn set_query_stat_counters(&mut self, counters: RegionQueryStatCounters) {
483        self.query_stat_counters = Some(counters);
484    }
485}
486
487/// Checks that range assignment only reordered or regrouped the original ranges.
488fn same_partition_ranges(left: &[Vec<PartitionRange>], right: &[Vec<PartitionRange>]) -> bool {
489    let mut left: Vec<_> = left.iter().flatten().collect();
490    let mut right: Vec<_> = right.iter().flatten().collect();
491    if left.len() != right.len() {
492        return false;
493    }
494    let key = |range: &&PartitionRange| (range.identifier, range.start, range.end, range.num_rows);
495    left.sort_unstable_by_key(key);
496    right.sort_unstable_by_key(key);
497    left == right
498}
499
500/// Request to override the scanner properties.
501#[derive(Default)]
502pub struct PrepareRequest {
503    /// Range assignment may reorder and regroup existing ranges. Exact row
504    /// counts require preserving each range unchanged with its original multiplicity.
505    pub ranges: Option<Vec<Vec<PartitionRange>>>,
506    /// Distringuishes partition range by empty batches.
507    pub distinguish_partition_range: Option<bool>,
508    /// The expected number of target partitions.
509    pub target_partitions: Option<usize>,
510}
511
512impl PrepareRequest {
513    /// Sets the ranges.
514    pub fn with_ranges(mut self, ranges: Vec<Vec<PartitionRange>>) -> Self {
515        self.ranges = Some(ranges);
516        self
517    }
518
519    /// Sets the distinguish partition range flag.
520    pub fn with_distinguish_partition_range(mut self, distinguish_partition_range: bool) -> Self {
521        self.distinguish_partition_range = Some(distinguish_partition_range);
522        self
523    }
524
525    /// Sets the target partitions.
526    pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
527        self.target_partitions = Some(target_partitions);
528        self
529    }
530}
531
532/// Necessary context of the query for the scanner.
533/// Direct callers should create one context per scan and reuse it across partitions.
534/// The default pool is unbounded; cloning the context shares its pool.
535#[derive(Clone)]
536pub struct QueryScanContext {
537    /// Whether the query is EXPLAIN ANALYZE VERBOSE.
538    pub explain_verbose: bool,
539    /// Executing node's query runtime pool, shared by all partitions of this scan.
540    pub memory_pool: Arc<dyn MemoryPool>,
541}
542
543impl Default for QueryScanContext {
544    fn default() -> Self {
545        Self {
546            explain_verbose: false,
547            memory_pool: Arc::new(UnboundedMemoryPool::default()),
548        }
549    }
550}
551
552/// A tag bound to a physical column in the scan's metadata snapshot.
553#[derive(Clone, Debug)]
554pub struct BoundTag {
555    /// Physical region column identifier for this logical tag.
556    pub column_id: ColumnId,
557    /// Logical tag name visible to the query.
558    pub name: Arc<str>,
559}
560
561/// Bound source for materializing labels from raw series chunks.
562#[derive(Clone, Debug)]
563pub enum RawLabelSource {
564    /// Scan-bound metadata for labels. A producer may expose encoded keys or
565    /// complete explicit labels; its stream decode specification distinguishes them.
566    PrimaryKey {
567        /// Metric name associated with the bound logical source.
568        metric_name: Arc<str>,
569        /// Physical metadata snapshot used to decode primary-key values.
570        physical_metadata: RegionMetadataRef,
571        /// Logical tag names mapped to physical column identifiers.
572        logical_tags: Arc<[BoundTag]>,
573    },
574    /// The stream supplies a complete metric name and label set in each chunk, not a partial
575    /// label projection; `Some(metric)` is a complete name/label set (the name itself may be
576    /// absent), or, for a stream that has no identity at all, see
577    /// [`NO_BOUND_LABEL_SOURCE`].
578    Explicit,
579}
580
581/// The identity a stream reports when no scan-bound label source was established for it.
582///
583/// [`RawLabelSource`] has no "absent" variant, and [`RawLabelSource::Explicit`] is the only one that
584/// carries no physical region key layout, so it stands in for "no identity" here. It is not a claim
585/// that the chunks carry labels: [`RawSeriesStream::label_decode_spec`] answers that, and a stream
586/// reporting this value can still return `Some` description and leave `metric` as `None` in every
587/// chunk. Decoding therefore asks the description, and only an identity check asks this.
588pub const NO_BOUND_LABEL_SOURCE: RawLabelSource = RawLabelSource::Explicit;
589
590/// A stream of raw series chunks with stable schema, label binding, and ordering.
591///
592/// Every series has strictly increasing timestamps within and across chunks; timestamps are
593/// unique per series. `Interleaved` permits a series to resume after another series; `Contiguous`
594/// and `KeyThenTime` guarantee each series' chunks are contiguous. `KeyThenTime` uses the complete
595/// stream identity compatible with its label binding, not just a TSID or hash. These are
596/// per-stream guarantees, not query-global order, partition ownership, or finality. `is_last`
597/// marks the last chunk of that series in this stream only; merging requires recomputing
598/// per-input-series finalization across all related inputs, not aggregate-group finality.
599/// Label interpretation is carried by the stream: [`RawSeriesStream::label_source`] states the
600/// scan-bound identity a producer read under, and [`RawSeriesStream::label_decode_spec`] states the
601/// label layout the stream's own chunks declare. Stream finality applies to all related input
602/// series, not aggregate groups or vector-match state.
603pub trait RawSeriesStream: Stream<Item = Result<RawSeriesChunk, BoxedError>> + Send {
604    /// Returns the schema shared by all chunks; raw schemas have no evaluation grid.
605    fn schema(&self) -> &Arc<SeriesSchema>;
606    /// Returns scan-bound label metadata. The binding does not dictate representation:
607    /// chunks with a decode specification leave `metric` as `None`; otherwise they
608    /// supply the complete explicit label set. The metric name itself may be absent.
609    ///
610    /// A stream that was decoded from a raw frame has no scan-bound identity and reports
611    /// [`NO_BOUND_LABEL_SOURCE`], which reads as `Explicit` while its chunks may still carry no
612    /// labels at all. That value therefore answers "is this the region I read under", never "are
613    /// these labels complete": [`Self::label_decode_spec`] is the stream's statement about its
614    /// encoding, and every consumer that decides whether to decode reads that instead.
615    fn label_source(&self) -> &RawLabelSource;
616    /// Returns the label decode description this stream declares for key-encoded labels.
617    ///
618    /// Every stream whose chunks carry key-encoded labels declares the description here, whether
619    /// it is a storage producer or a stream reassembled from a raw frame. A consumer holding only
620    /// that description can therefore decode labels without a scan-bound [`RawLabelSource`]: the
621    /// description, not the binding, describes the encoding, and a receiver reporting
622    /// [`NO_BOUND_LABEL_SOURCE`] still states through this description that its chunks are
623    /// undecoded key chunks. A stream that carries complete labels instead answers `None`. This is
624    /// the description the stream declares, not an authenticated statement about where the values
625    /// came from.
626    fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> {
627        None
628    }
629    /// Returns this stream's ordering guarantee.
630    fn ordering(&self) -> SeriesOrdering;
631}
632
633/// A pinned raw-series stream that can be sent between threads.
634pub type SendableRawSeriesStream = Pin<Box<dyn RawSeriesStream>>;
635
636/// Stable identity metadata for one ordinal in a prepared series source.
637#[derive(Clone, Debug)]
638pub struct SeriesInfo {
639    /// Complete source identity, not a TSID or hash alone. Every region holding a fragment of
640    /// one series reports the same identity, so it must not be qualified by region.
641    pub primary_key: datatypes::arrow::buffer::Buffer,
642    /// Complete explicit metric name and labels, not a partial label projection; or `None` for
643    /// primary-key label binding (undecoded, not nameless). The metric name itself may be absent.
644    pub metric: Option<datatypes::series::SeriesLabels>,
645}
646
647/// An immutable, finite selected set of series prepared for independent range reads.
648///
649/// The count may include series with no samples after filtering. Ordinals are stable local
650/// indexes, not protocol identifiers; each has exactly one complete identity returned by
651/// [`PreparedSeriesSource::series_info`], and that identity matches chunks for that ordinal.
652/// Every reader exposes the same fixed schema, label binding, and ordering before polling,
653/// including for an empty range, and describes labels independently of this source's lifetime.
654/// Key-encoded output has `metric: None`; explicit-label output has a complete
655/// `Some(metric)` matching each chunk, independently of its scan binding.
656/// Ordering describes the stream, not ordinal enumeration.
657///
658/// Preparation, identity lookup, and reader creation do not load sample payloads or perform
659/// hidden blocking I/O. The selected set is bound to the scanner's immutable MVCC view,
660/// predicates, authorization, projection, labels, and existing scan resources. Readers own
661/// resources needed to continue after this source or scanner is dropped. Dropping one reader
662/// does not cancel sibling readers; normal ownership cleanup applies without detached work.
663///
664/// A range must satisfy `start <= end <= num_series()`. Invalid ranges and invalid ordinals
665/// return errors; an empty in-bounds range returns an ordinary empty stream. Repeated and
666/// overlapping reads are independent and do not consume shared iteration state.
667pub trait PreparedSeriesSource: Send + Sync {
668    /// Returns the exact, stable number of selected local series ordinals.
669    fn num_series(&self) -> usize;
670
671    /// Returns label binding shared by series metadata and every reader, without opening or
672    /// polling a reader; the binding is self-contained for remote consumers.
673    fn label_source(&self) -> &RawLabelSource;
674
675    /// Returns identity metadata for an ordinal without polling sample data.
676    fn series_info(&self, ordinal: usize) -> Result<SeriesInfo, BoxedError>;
677
678    /// Creates an independent reader for the half-open ordinal range.
679    fn read_series(
680        &self,
681        range: std::ops::Range<usize>,
682    ) -> Result<SendableRawSeriesStream, BoxedError>;
683}
684
685/// A scanner that provides a way to scan the region concurrently.
686///
687/// The scanner splits the region into partitions so that each partition can be scanned concurrently.
688/// You can use this trait to implement an [`ExecutionPlan`](datafusion_physical_plan::ExecutionPlan).
689pub trait RegionScanner: Debug + DisplayAs + Send {
690    fn name(&self) -> &str;
691
692    /// Returns the properties of the scanner.
693    fn properties(&self) -> &ScannerProperties;
694
695    /// Returns the schema of the record batches.
696    fn schema(&self) -> SchemaRef;
697
698    /// Returns the metadata of the region.
699    fn metadata(&self) -> RegionMetadataRef;
700
701    /// Prepares the scanner with the given partition ranges.
702    ///
703    /// This method is for the planner to adjust the scanner's behavior based on the partition ranges.
704    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError>;
705
706    /// Scans the partition and returns a stream of record batches.
707    ///
708    /// # Panics
709    /// Panics if the `partition` is out of bound.
710    fn scan_partition(
711        &self,
712        ctx: &QueryScanContext,
713        metrics_set: &ExecutionPlanMetricsSet,
714        partition: usize,
715    ) -> Result<SendableRecordBatchStream, BoxedError>;
716
717    /// Checks whether this scanner can provide a raw-series scan for the given labels.
718    ///
719    /// This is a non-consuming preflight: it must not start a scan or otherwise consume
720    /// scanner state. It checks immutable label binding, schema, and typed residual-predicate
721    /// eligibility. Returning `Some` requires overriding `scan_series_partition` and
722    /// promises that it can execute with this label source. `None` means the raw path is
723    /// unsupported and an ordinary scan remains available. Execution must revalidate and
724    /// return errors rather than falling back if the binding or schema changed since preflight.
725    fn raw_series_schema(
726        &self,
727        _label_source: &RawLabelSource,
728    ) -> Result<Option<Arc<SeriesSchema>>, BoxedError> {
729        Ok(None)
730    }
731
732    /// Whether raw chunks carry complete explicit labels under this scan binding.
733    /// This non-consuming declaration must agree with the stream before its first poll.
734    /// Returning true does not replace the immutable source binding or authorization checks.
735    fn raw_series_has_explicit_labels(&self, _labels: &RawLabelSource) -> Result<bool, BoxedError> {
736        Ok(false)
737    }
738
739    /// Returns the guarantee for subsequent raw scans without consuming scanner state.
740    ///
741    /// Legacy raw sources have no ordering declaration, so `Contiguous` is the conservative
742    /// default; `Interleaved` is not representable on the raw frame wire.
743    fn raw_series_ordering(&self) -> Result<SeriesOrdering, BoxedError> {
744        Ok(SeriesOrdering::Contiguous)
745    }
746
747    /// Scans a partition as raw series when this source supports that path.
748    ///
749    /// `None` means raw capability is absent before execution and permits a legacy scan instead.
750    /// `Some` selects this entrypoint, including for an empty successful stream. Errors propagate;
751    /// callers must not replay a failed raw scan through the legacy path. Use only one entrypoint
752    /// for a given scanner partition per execution. The explicit label source is owned by the
753    /// returned stream and must be bound to this scanner's metadata snapshot.
754    ///
755    /// Output preserves the ordinary storage reader's pushdown and MVCC semantics. Inexact
756    /// pushed-down predicates can leave false-positive candidates, just as in `scan_partition`.
757    /// Implementations must preserve typed residual-predicate semantics before any lossy value
758    /// conversion, or return `None` before execution when they cannot. Callers must retain
759    /// residual predicate columns until those predicates are evaluated and apply the final
760    /// projection afterward; raw capability does not mean filtering is complete.
761    ///
762    /// # Panics
763    ///
764    /// The default implementation panics. Implementations must override this method to support
765    /// raw series scanning.
766    fn scan_series_partition(
767        &self,
768        _ctx: &QueryScanContext,
769        _metrics_set: &ExecutionPlanMetricsSet,
770        _partition: usize,
771        _label_source: &RawLabelSource,
772    ) -> Result<Option<SendableRawSeriesStream>, BoxedError> {
773        todo!()
774    }
775
776    /// Prepares scanner-wide candidates once for independent ordinal-range reads.
777    ///
778    /// Metadata I/O is asynchronous; sample payloads are loaded only by polling readers.
779    /// The owned future does not borrow the scanner. `None` means unsupported before
780    /// execution; errors must propagate without replay through a different scan path.
781    /// Implementations may share preparation with their raw partition adapter.
782    fn prepare_series(
783        &self,
784        _ctx: &QueryScanContext,
785        _metrics_set: &ExecutionPlanMetricsSet,
786        _label_source: &RawLabelSource,
787    ) -> futures::future::BoxFuture<
788        'static,
789        Result<Option<Arc<dyn PreparedSeriesSource>>, BoxedError>,
790    > {
791        Box::pin(async { Ok(None) })
792    }
793
794    /// Check if there is any predicate exclude region partition exprs that may be executed in this scanner.
795    fn has_predicate_without_region(&self) -> bool;
796
797    /// Add the given dynamic filter expressions to the predicate of the scanner.
798    /// Returns a vector of booleans indicating which filter expressions were applied.
799    /// true indicates the filter expression was applied(will be use by scanner to prune by stat for row group),
800    /// false otherwise.
801    fn add_dyn_filter_to_predicate(
802        &mut self,
803        filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
804    ) -> Vec<bool>;
805
806    /// Resets execution state after streams from the previous execution have been dropped.
807    ///
808    /// Callers must not concurrently execute, reset, or install filters through scanner aliases.
809    /// Implementations retaining dynamic predicates must discard them and derived pruning state,
810    /// while preserving static predicates, the source snapshot, and prepared properties.
811    /// The default is a no-op and does not make inherently one-shot sources replayable.
812    fn reset_state(&mut self) {}
813
814    /// Sets whether the scanner reads one logical metric region, including a
815    /// physical metric region constrained by a table-ID filter.
816    fn set_logical_region(&mut self, logical_region: bool);
817
818    /// Sets the region id that should receive query-load metrics.
819    fn set_query_load_region_id(&mut self, region_id: RegionId);
820
821    fn snapshot_sequence(&self) -> Option<SequenceNumber> {
822        None
823    }
824}
825
826pub type RegionScannerRef = Box<dyn RegionScanner>;
827
828pub type BatchResponses = Vec<(RegionId, Result<RegionResponse, BoxedError>)>;
829
830/// A response of [`RegionEngine::handle_batch_put_requests`] and the region of each put it
831/// answers for.
832pub type BatchPutResponse = (
833    Vec<RegionId>,
834    BoxFuture<'static, Result<RegionResponse, BoxedError>>,
835);
836
837/// Represents the statistics of a region.
838#[derive(Debug, Deserialize, Serialize, Default)]
839pub struct RegionStatistic {
840    /// The number of rows stored in SST files owned by this region plus rows in memtables.
841    ///
842    /// Rows from SST files referenced from other regions, for example after repartition,
843    /// are not counted to avoid table-level double counting when summing region statistics.
844    #[serde(default)]
845    pub num_rows: u64,
846    /// The size of memtable in bytes.
847    pub memtable_size: u64,
848    /// The size of WAL in bytes.
849    pub wal_size: u64,
850    /// Stored bytes of the latest observed manifest checkpoint and subsequent deltas,
851    /// compressed when enabled. Excludes staging manifests, `_last_checkpoint`, and
852    /// superseded files still present on disk. This is a logical recovery-size estimate,
853    /// not the physical directory usage; observation failures can leave it incomplete.
854    pub manifest_size: u64,
855    /// The size of SST data files owned by this region in bytes.
856    ///
857    /// SST files referenced from other regions, for example after repartition, are not counted.
858    pub sst_size: u64,
859    /// The number of SST files owned by this region.
860    ///
861    /// SST files referenced from other regions, for example after repartition, are not counted.
862    pub sst_num: u64,
863    /// The size of SST index files owned by this region in bytes.
864    ///
865    /// SST index files referenced from other regions, for example after repartition, are not counted.
866    #[serde(default)]
867    pub index_size: u64,
868    /// The details of the region.
869    #[serde(default)]
870    pub manifest: RegionManifestInfo,
871    #[serde(default)]
872    /// The total bytes written of the region since region opened.
873    pub written_bytes: u64,
874    /// Total ingested Parquet bytes since the region opened.
875    /// Currently counts only committed flush output.
876    ///
877    /// Excludes index files, compaction and imported SSTs.
878    /// Resets when the region instance is recreated; manifest replay does not increment it.
879    /// Accepts the legacy `flushed_parquet_bytes` key; upgrade metasrv before datanodes.
880    #[serde(default, alias = "flushed_parquet_bytes")]
881    pub ingested_parquet_bytes: u64,
882    /// The total query CPU time of the region since region opened.
883    ///
884    /// Unit: nanoseconds.
885    #[serde(default)]
886    pub query_cpu_time: u64,
887    /// The total scanned bytes of the region since region opened.
888    #[serde(default)]
889    pub query_scanned_bytes: u64,
890    /// The earliest timestamp of the region's current data, or `None` if it holds
891    /// none. Unlike the size and row counters this covers files referenced from
892    /// other regions too, since a time range cannot double count.
893    #[serde(default)]
894    pub min_timestamp: Option<Timestamp>,
895    /// The latest timestamp of the region's current data. See [`Self::min_timestamp`].
896    #[serde(default)]
897    pub max_timestamp: Option<Timestamp>,
898    /// The latest entry id of the region's remote WAL since last flush.
899    /// For metric engine, there're two latest entry ids, one for data and one for metadata.
900    /// TODO(weny): remove this two fields and use single instead.
901    #[serde(default)]
902    pub data_topic_latest_entry_id: u64,
903    #[serde(default)]
904    pub metadata_topic_latest_entry_id: u64,
905    /// Whether the region still has WAL ranges to recover. Omitted from the serialized form
906    /// when false.
907    #[serde(default, skip_serializing_if = "crate::is_false")]
908    pub has_pending_tails: bool,
909}
910
911/// The manifest info of a region.
912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
913pub enum RegionManifestInfo {
914    Mito {
915        manifest_version: u64,
916        flushed_entry_id: u64,
917        /// Number of files removed in the manifest's `removed_files` field.
918        file_removed_cnt: u64,
919    },
920    Metric {
921        data_manifest_version: u64,
922        data_flushed_entry_id: u64,
923        metadata_manifest_version: u64,
924        metadata_flushed_entry_id: u64,
925    },
926}
927
928impl RegionManifestInfo {
929    /// Creates a new [RegionManifestInfo] for mito2 engine.
930    pub fn mito(manifest_version: u64, flushed_entry_id: u64, file_removal_rate: u64) -> Self {
931        Self::Mito {
932            manifest_version,
933            flushed_entry_id,
934            file_removed_cnt: file_removal_rate,
935        }
936    }
937
938    /// Creates a new [RegionManifestInfo] for metric engine.
939    pub fn metric(
940        data_manifest_version: u64,
941        data_flushed_entry_id: u64,
942        metadata_manifest_version: u64,
943        metadata_flushed_entry_id: u64,
944    ) -> Self {
945        Self::Metric {
946            data_manifest_version,
947            data_flushed_entry_id,
948            metadata_manifest_version,
949            metadata_flushed_entry_id,
950        }
951    }
952
953    /// Returns true if the region is a mito2 region.
954    pub fn is_mito(&self) -> bool {
955        matches!(self, RegionManifestInfo::Mito { .. })
956    }
957
958    /// Returns true if the region is a metric region.
959    pub fn is_metric(&self) -> bool {
960        matches!(self, RegionManifestInfo::Metric { .. })
961    }
962
963    /// Returns the flushed entry id of the data region.
964    pub fn data_flushed_entry_id(&self) -> u64 {
965        match self {
966            RegionManifestInfo::Mito {
967                flushed_entry_id, ..
968            } => *flushed_entry_id,
969            RegionManifestInfo::Metric {
970                data_flushed_entry_id,
971                ..
972            } => *data_flushed_entry_id,
973        }
974    }
975
976    /// Returns the manifest version of the data region.
977    pub fn data_manifest_version(&self) -> u64 {
978        match self {
979            RegionManifestInfo::Mito {
980                manifest_version, ..
981            } => *manifest_version,
982            RegionManifestInfo::Metric {
983                data_manifest_version,
984                ..
985            } => *data_manifest_version,
986        }
987    }
988
989    /// Returns the manifest version of the metadata region.
990    pub fn metadata_manifest_version(&self) -> Option<u64> {
991        match self {
992            RegionManifestInfo::Mito { .. } => None,
993            RegionManifestInfo::Metric {
994                metadata_manifest_version,
995                ..
996            } => Some(*metadata_manifest_version),
997        }
998    }
999
1000    /// Returns the flushed entry id of the metadata region.
1001    pub fn metadata_flushed_entry_id(&self) -> Option<u64> {
1002        match self {
1003            RegionManifestInfo::Mito { .. } => None,
1004            RegionManifestInfo::Metric {
1005                metadata_flushed_entry_id,
1006                ..
1007            } => Some(*metadata_flushed_entry_id),
1008        }
1009    }
1010
1011    /// Encodes a list of ([RegionId], [RegionManifestInfo]) to a byte array.
1012    pub fn encode_list(manifest_infos: &[(RegionId, Self)]) -> serde_json::Result<Vec<u8>> {
1013        serde_json::to_vec(manifest_infos)
1014    }
1015
1016    /// Decodes a list of ([RegionId], [RegionManifestInfo]) from a byte array.
1017    pub fn decode_list(value: &[u8]) -> serde_json::Result<Vec<(RegionId, Self)>> {
1018        serde_json::from_slice(value)
1019    }
1020}
1021
1022impl Default for RegionManifestInfo {
1023    fn default() -> Self {
1024        Self::Mito {
1025            manifest_version: 0,
1026            flushed_entry_id: 0,
1027            file_removed_cnt: 0,
1028        }
1029    }
1030}
1031
1032impl RegionStatistic {
1033    /// Deserializes the region statistic to a byte array.
1034    ///
1035    /// Returns None if the deserialization fails.
1036    pub fn deserialize_from_slice(value: &[u8]) -> Option<RegionStatistic> {
1037        serde_json::from_slice(value).ok()
1038    }
1039
1040    /// Serializes the region statistic to a byte array.
1041    ///
1042    /// Returns None if the serialization fails.
1043    pub fn serialize_to_vec(&self) -> Option<Vec<u8>> {
1044        serde_json::to_vec(self).ok()
1045    }
1046}
1047
1048impl RegionStatistic {
1049    /// Returns the estimated disk size of the region.
1050    pub fn estimated_disk_size(&self) -> u64 {
1051        self.wal_size + self.sst_size + self.manifest_size + self.index_size
1052    }
1053}
1054
1055#[cfg(test)]
1056#[path = "region_engine/prepared_series_tests.rs"]
1057mod prepared_series_tests;
1058
1059#[cfg(test)]
1060mod tests {
1061    use common_recordbatch::{RecordBatch, RecordBatches};
1062    use datatypes::prelude::ConcreteDataType;
1063    use datatypes::schema::ColumnSchema;
1064    use datatypes::vectors::{Int32Vector, TimestampMillisecondVector, VectorRef};
1065    use futures::TryStreamExt;
1066    use serde_json::json;
1067
1068    use super::*;
1069
1070    #[test]
1071    fn test_metadata_aggr_partition_range_assignment() {
1072        let range = PartitionRange {
1073            start: Timestamp::new_millisecond(0),
1074            end: Timestamp::new_millisecond(1),
1075            num_rows: 5,
1076            identifier: 0,
1077        };
1078        let later = PartitionRange {
1079            start: range.end,
1080            end: Timestamp::new_millisecond(2),
1081            identifier: 1,
1082            ..range
1083        };
1084        let original = vec![vec![range, later]];
1085        for (replacement, exact) in [
1086            (vec![vec![later], vec![range]], true),
1087            (vec![vec![later]], false),
1088            (vec![vec![range, range]], false),
1089            (
1090                vec![vec![
1091                    PartitionRange {
1092                        num_rows: 4,
1093                        ..range
1094                    },
1095                    later,
1096                ]],
1097                false,
1098            ),
1099        ] {
1100            let mut properties = ScannerProperties::new(original.clone(), true, 10)
1101                .with_exact_num_rows(Some(10))
1102                .with_total_rows_is_exact(true);
1103            properties.prepare(PrepareRequest::default().with_ranges(replacement));
1104            assert_eq!(properties.exact_num_rows(), exact.then_some(10));
1105            assert_eq!(properties.total_rows_is_exact(), exact);
1106        }
1107    }
1108
1109    #[tokio::test]
1110    async fn single_partition_scanner_raw_scan_panics_and_preserves_legacy_read() {
1111        use std::panic::{AssertUnwindSafe, catch_unwind};
1112
1113        use api::v1::SemanticType;
1114        use datatypes::arrow::array::Int32Array;
1115        use datatypes::schema::Schema as ArrowSchema;
1116
1117        use crate::metadata::{ColumnMetadata, RegionMetadataBuilder};
1118
1119        let schema = Arc::new(ArrowSchema::new(vec![
1120            ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false),
1121            ColumnSchema::new(
1122                "ts",
1123                ConcreteDataType::timestamp_millisecond_datatype(),
1124                false,
1125            ),
1126        ]));
1127        let columns: Vec<VectorRef> = vec![
1128            Arc::new(Int32Vector::from_slice([42])),
1129            Arc::new(TimestampMillisecondVector::from_slice([7])),
1130        ];
1131        let batch = RecordBatch::new(schema.clone(), columns).unwrap();
1132        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1133        let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1234, 1));
1134        metadata_builder.push_column_metadata(ColumnMetadata {
1135            column_schema: ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false),
1136            semantic_type: SemanticType::Field,
1137            column_id: 1,
1138        });
1139        metadata_builder.push_column_metadata(ColumnMetadata {
1140            column_schema: ColumnSchema::new(
1141                "ts",
1142                ConcreteDataType::timestamp_millisecond_datatype(),
1143                false,
1144            ),
1145            semantic_type: SemanticType::Timestamp,
1146            column_id: 2,
1147        });
1148        let metadata = Arc::new(metadata_builder.build().unwrap());
1149        let scanner = SinglePartitionScanner::new(batches.as_stream(), false, metadata, None);
1150        let ctx = QueryScanContext::default();
1151        let metrics = ExecutionPlanMetricsSet::new();
1152
1153        // The default raw-scan preflight declines without consuming the legacy scan, and the
1154        // prepared-series entrypoint reports unsupported before consumption as well.
1155        assert!(
1156            scanner
1157                .raw_series_schema(&RawLabelSource::Explicit)
1158                .unwrap()
1159                .is_none()
1160        );
1161        assert!(
1162            scanner
1163                .prepare_series(&ctx, &metrics, &RawLabelSource::Explicit)
1164                .await
1165                .unwrap()
1166                .is_none()
1167        );
1168        assert_eq!(
1169            scanner.raw_series_ordering().unwrap(),
1170            SeriesOrdering::Contiguous
1171        );
1172
1173        // SinglePartitionScanner uses the default raw-scan implementation, which panics.
1174        let raw_scan = catch_unwind(AssertUnwindSafe(|| {
1175            scanner.scan_series_partition(&ctx, &metrics, 0, &RawLabelSource::Explicit)
1176        }));
1177        assert!(raw_scan.is_err());
1178        let legacy = scanner.scan_partition(&ctx, &metrics, 0).unwrap();
1179        let legacy_batches = legacy.try_collect::<Vec<_>>().await.unwrap();
1180        assert_eq!(legacy_batches.len(), 1);
1181        assert_eq!(legacy_batches[0].num_rows(), 1);
1182        assert_eq!(
1183            legacy_batches[0]
1184                .column(0)
1185                .as_ref()
1186                .as_any()
1187                .downcast_ref::<Int32Array>()
1188                .unwrap()
1189                .value(0),
1190            42
1191        );
1192    }
1193
1194    #[test]
1195    fn test_legacy_granted_region_wire() {
1196        use prost::Message;
1197
1198        let legacy_bytes: &[u8] = include_bytes!(
1199            "../../../tests/compatibility/wire/candidate_lease_id/legacy_granted_region.pb"
1200        );
1201        let granted = GrantedRegion::from(PbGrantedRegion::decode(legacy_bytes).unwrap());
1202        assert_eq!(
1203            granted,
1204            GrantedRegion {
1205                candidate_lease_id: None,
1206                extensions: HashMap::from([("plugin".to_string(), b"payload".to_vec())]),
1207                ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower)
1208            }
1209        );
1210
1211        assert_eq!(PbGrantedRegion::from(granted).encode_to_vec(), legacy_bytes);
1212    }
1213
1214    #[test]
1215    fn test_granted_region_candidate_lease_id_wire() {
1216        use prost::Message;
1217
1218        let granted = GrantedRegion {
1219            candidate_lease_id: Some(7),
1220            ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower)
1221        };
1222        // Region id (field 1), role Follower (field 2), then candidate_lease_id as a uint64
1223        // varint in field 3.
1224        let bytes: &[u8] = &[
1225            0x08, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01, 0x10, 0x01, 0x18, 0x07,
1226        ];
1227        assert_eq!(
1228            PbGrantedRegion::from(granted.clone()).encode_to_vec(),
1229            bytes
1230        );
1231        assert_eq!(
1232            GrantedRegion::from(PbGrantedRegion::decode(bytes).unwrap()),
1233            granted
1234        );
1235    }
1236
1237    #[test]
1238    fn region_statistic_flush_bytes_compatibility() {
1239        let legacy_bytes = br#"{
1240            "num_rows": 1,
1241            "memtable_size": 2,
1242            "wal_size": 3,
1243            "manifest_size": 4,
1244            "sst_size": 5,
1245            "sst_num": 6,
1246            "index_size": 7,
1247            "manifest": {
1248                "Mito": {
1249                    "manifest_version": 8,
1250                    "flushed_entry_id": 9,
1251                    "file_removed_cnt": 10
1252                }
1253            },
1254            "written_bytes": 11
1255        }"#;
1256        let mut statistic = RegionStatistic::deserialize_from_slice(legacy_bytes).unwrap();
1257        assert_eq!(statistic.ingested_parquet_bytes, 0);
1258        statistic.ingested_parquet_bytes = 1234;
1259        let encoded = statistic.serialize_to_vec().unwrap();
1260        let decoded = RegionStatistic::deserialize_from_slice(&encoded).unwrap();
1261        assert_eq!(decoded.ingested_parquet_bytes, 1234);
1262        let legacy: serde_json::Value = serde_json::from_slice(legacy_bytes).unwrap();
1263        let mut current: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
1264        assert_eq!(current["ingested_parquet_bytes"], 1234);
1265        assert!(current.get("flushed_parquet_bytes").is_none());
1266        let mut old_wire = current.clone();
1267        let bytes = old_wire
1268            .as_object_mut()
1269            .unwrap()
1270            .remove("ingested_parquet_bytes")
1271            .unwrap();
1272        old_wire["flushed_parquet_bytes"] = bytes;
1273        assert_eq!(
1274            serde_json::from_value::<RegionStatistic>(old_wire)
1275                .unwrap()
1276                .ingested_parquet_bytes,
1277            1234
1278        );
1279        for (key, value) in legacy.as_object().unwrap() {
1280            assert_eq!(&current[key], value);
1281        }
1282        current
1283            .as_object_mut()
1284            .unwrap()
1285            .remove("ingested_parquet_bytes");
1286        assert_eq!(
1287            serde_json::from_value::<RegionStatistic>(current)
1288                .unwrap()
1289                .ingested_parquet_bytes,
1290            0
1291        );
1292    }
1293
1294    #[test]
1295    fn region_statistic_deserializes_without_query_stats() {
1296        let statistic: RegionStatistic = serde_json::from_value(json!({
1297            "num_rows": 1,
1298            "memtable_size": 2,
1299            "wal_size": 3,
1300            "manifest_size": 4,
1301            "sst_size": 5,
1302            "sst_num": 6,
1303            "index_size": 7,
1304            "manifest": {
1305                "Mito": {
1306                    "manifest_version": 8,
1307                    "flushed_entry_id": 9,
1308                    "file_removed_cnt": 10
1309                }
1310            },
1311            "written_bytes": 11
1312        }))
1313        .unwrap();
1314
1315        assert_eq!(statistic.query_cpu_time, 0);
1316        assert_eq!(statistic.query_scanned_bytes, 0);
1317    }
1318}
1319
1320/// Request to sync the region from a manifest or a region.
1321#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1322pub enum SyncRegionFromRequest {
1323    /// Syncs the region using manifest information.
1324    /// Used in leader-follower manifest sync scenarios.
1325    FromManifest(RegionManifestInfo),
1326    /// Syncs the region from another region.
1327    ///
1328    /// Used by the metric engine to sync logical regions from a source physical region
1329    /// to a target physical region. This copies metadata region SST files and transforms
1330    /// logical region entries to use the target's region number.
1331    FromRegion {
1332        /// The [`RegionId`] of the source region.
1333        source_region_id: RegionId,
1334        /// The parallelism of the sync operation.
1335        parallelism: usize,
1336    },
1337}
1338
1339impl From<RegionManifestInfo> for SyncRegionFromRequest {
1340    fn from(manifest_info: RegionManifestInfo) -> Self {
1341        SyncRegionFromRequest::FromManifest(manifest_info)
1342    }
1343}
1344
1345impl SyncRegionFromRequest {
1346    /// Creates a new request from a manifest info.
1347    pub fn from_manifest(manifest_info: RegionManifestInfo) -> Self {
1348        SyncRegionFromRequest::FromManifest(manifest_info)
1349    }
1350
1351    /// Creates a new request from a region.
1352    pub fn from_region(source_region_id: RegionId, parallelism: usize) -> Self {
1353        SyncRegionFromRequest::FromRegion {
1354            source_region_id,
1355            parallelism,
1356        }
1357    }
1358
1359    /// Returns true if the request is from a manifest.
1360    pub fn is_from_manifest(&self) -> bool {
1361        matches!(self, SyncRegionFromRequest::FromManifest { .. })
1362    }
1363
1364    /// Converts the request to a region manifest info.
1365    ///
1366    /// Returns None if the request is not from a manifest.
1367    pub fn into_region_manifest_info(self) -> Option<RegionManifestInfo> {
1368        match self {
1369            SyncRegionFromRequest::FromManifest(manifest_info) => Some(manifest_info),
1370            SyncRegionFromRequest::FromRegion { .. } => None,
1371        }
1372    }
1373}
1374
1375/// The response of syncing the region.
1376#[derive(Debug)]
1377pub enum SyncRegionFromResponse {
1378    NotSupported,
1379    Mito {
1380        /// Indicates if the data region was synced.
1381        synced: bool,
1382    },
1383    Metric {
1384        /// Indicates if the metadata region was synced.
1385        metadata_synced: bool,
1386        /// Indicates if the data region was synced.
1387        data_synced: bool,
1388        /// The logical regions that were newly opened during the sync operation.
1389        /// This only occurs after the metadata region has been successfully synced.
1390        new_opened_logical_region_ids: Vec<RegionId>,
1391    },
1392}
1393
1394impl SyncRegionFromResponse {
1395    /// Returns true if data region is synced.
1396    pub fn is_data_synced(&self) -> bool {
1397        match self {
1398            SyncRegionFromResponse::NotSupported => false,
1399            SyncRegionFromResponse::Mito { synced } => *synced,
1400            SyncRegionFromResponse::Metric { data_synced, .. } => *data_synced,
1401        }
1402    }
1403
1404    /// Returns true if the engine is a mito2 engine.
1405    pub fn is_mito(&self) -> bool {
1406        matches!(self, SyncRegionFromResponse::Mito { .. })
1407    }
1408
1409    /// Returns true if the engine is a metric engine.
1410    pub fn is_metric(&self) -> bool {
1411        matches!(self, SyncRegionFromResponse::Metric { .. })
1412    }
1413
1414    /// Returns the new opened logical region ids.
1415    pub fn new_opened_logical_region_ids(self) -> Option<Vec<RegionId>> {
1416        match self {
1417            SyncRegionFromResponse::Metric {
1418                new_opened_logical_region_ids,
1419                ..
1420            } => Some(new_opened_logical_region_ids),
1421            _ => None,
1422        }
1423    }
1424}
1425
1426/// The source regions that publish their files into a target region another source publishes
1427/// into too.
1428///
1429/// This is the shape in which a repartition can publish one object twice: two distinct sources
1430/// hand their file sets to the same target, so a shared object and a materialized copy of it can
1431/// both become visible there. It is also the exact shape that the two ownership checks guard - the
1432/// pre-publication check of the repartition procedure, which asks [`Self`] which sources to
1433/// validate, and the remap-time guard
1434/// (`mito2::remap_manifest::RemapManifest::is_split`), which exempts the other shapes.
1435///
1436/// The predicate is deliberately stated per *target*, not per source count: whether one source
1437/// feeds one target or several says nothing about combining file sets. A one-to-many mapping
1438/// hands each child its own part of every object, and a one-to-one mapping hands the object to
1439/// the only target, so neither combines two sources' copies. Only a target fed by two or more
1440/// distinct sources does.
1441///
1442/// Returned in ascending region id order, so a message that names them is stable.
1443pub fn sources_sharing_a_target(mapping: &HashMap<RegionId, Vec<RegionId>>) -> Vec<RegionId> {
1444    let mut sources_per_target: HashMap<RegionId, BTreeSet<RegionId>> = HashMap::new();
1445    for (source, targets) in mapping {
1446        for target in targets {
1447            sources_per_target
1448                .entry(*target)
1449                .or_default()
1450                .insert(*source);
1451        }
1452    }
1453    let mut shared: BTreeSet<RegionId> = BTreeSet::new();
1454    for sources in sources_per_target
1455        .values()
1456        .filter(|sources| sources.len() > 1)
1457    {
1458        shared.extend(sources.iter().copied());
1459    }
1460    shared.into_iter().collect()
1461}
1462
1463/// Whether every target region receives files from at most one source region, i.e. whether
1464/// no repartition in this mapping can publish an object twice.
1465///
1466/// The negation of [`sources_sharing_a_target`] being empty.
1467pub fn every_target_has_a_single_source(mapping: &HashMap<RegionId, Vec<RegionId>>) -> bool {
1468    sources_sharing_a_target(mapping).is_empty()
1469}
1470
1471/// Request to remap manifests from old regions to new regions.
1472#[derive(Debug, Clone, Default)]
1473pub struct RemapManifestsRequest {
1474    /// The [`RegionId`] of a staging region used to obtain table directory and storage configuration for the remap operation.
1475    ///
1476    /// For a [`Self::validate_only`] request this is the region the check reads, which is an
1477    /// ordinary (not staging) region.
1478    pub region_id: RegionId,
1479    /// Regions to remap manifests from.
1480    pub input_regions: Vec<RegionId>,
1481    /// For each old region, which new regions should receive its files
1482    pub region_mapping: HashMap<RegionId, Vec<RegionId>>,
1483    /// New partition expressions for the new regions.
1484    pub new_partition_exprs: HashMap<RegionId, String>,
1485    /// Only verify that the request would be accepted, without remapping anything.
1486    ///
1487    /// A validate-only request reads the persisted manifest of [`Self::region_id`] and reports
1488    /// whether the region holds a file it did not create itself; it does not require staging, does
1489    /// not write and returns no manifest paths. `false` (the [`Default`]) keeps the ordinary
1490    /// remapping behaviour, so an older caller is unaffected.
1491    pub validate_only: bool,
1492}
1493
1494/// Response to remap manifests from old regions to new regions.
1495#[derive(Debug, Clone)]
1496pub struct RemapManifestsResponse {
1497    /// Maps region id to its staging manifest path.
1498    ///
1499    /// These paths are relative paths within the central region's staging blob storage,
1500    /// and should be passed to [`ApplyStagingManifestRequest`](RegionRequest::ApplyStagingManifest) to finalize the repartition.
1501    pub manifest_paths: HashMap<RegionId, String>,
1502}
1503
1504/// Request to copy files from a source region to a target region.
1505#[derive(Debug, Clone)]
1506pub struct MitoCopyRegionFromRequest {
1507    /// The [`RegionId`] of the source region.
1508    pub source_region_id: RegionId,
1509    /// The parallelism of the copy operation.
1510    pub parallelism: usize,
1511}
1512
1513#[derive(Debug, Clone)]
1514pub struct MitoCopyRegionFromResponse {
1515    /// Source SST IDs installed in the target by this copy. Shared references may
1516    /// be installed without copying their physical objects. If no new references
1517    /// need installation, returns the source IDs already present in the target.
1518    /// This is not a count or inventory of physical object transfers.
1519    pub copied_file_ids: Vec<FileId>,
1520}
1521
1522#[async_trait]
1523pub trait RegionEngine: Send + Sync {
1524    /// Name of this engine
1525    fn name(&self) -> &str;
1526
1527    /// Handles batch open region requests.
1528    async fn handle_batch_open_requests(
1529        &self,
1530        parallelism: usize,
1531        requests: Vec<(RegionId, RegionOpenRequest)>,
1532    ) -> Result<BatchResponses, BoxedError> {
1533        let semaphore = Arc::new(Semaphore::new(parallelism));
1534        let mut tasks = Vec::with_capacity(requests.len());
1535
1536        for (region_id, request) in requests {
1537            let semaphore_moved = semaphore.clone();
1538
1539            tasks.push(async move {
1540                // Safety: semaphore must exist
1541                let _permit = semaphore_moved.acquire().await.unwrap();
1542                let result = self
1543                    .handle_request(region_id, RegionRequest::Open(request))
1544                    .await;
1545                (region_id, result)
1546            });
1547        }
1548
1549        Ok(join_all(tasks).await)
1550    }
1551
1552    async fn handle_batch_catchup_requests(
1553        &self,
1554        parallelism: usize,
1555        requests: Vec<(RegionId, RegionCatchupRequest)>,
1556    ) -> Result<BatchResponses, BoxedError> {
1557        let semaphore = Arc::new(Semaphore::new(parallelism));
1558        let mut tasks = Vec::with_capacity(requests.len());
1559
1560        for (region_id, request) in requests {
1561            let semaphore_moved = semaphore.clone();
1562
1563            tasks.push(async move {
1564                // Safety: semaphore must exist
1565                let _permit = semaphore_moved.acquire().await.unwrap();
1566                let result = self
1567                    .handle_request(region_id, RegionRequest::Catchup(request))
1568                    .await;
1569                (region_id, result)
1570            });
1571        }
1572
1573        Ok(join_all(tasks).await)
1574    }
1575
1576    /// Handles the puts of one request into regions of this engine and returns the responses
1577    /// to await on their own, each with the region of every put it answers for: two puts to one
1578    /// region are two entries.
1579    ///
1580    /// The default handles each put with [`handle_request`](Self::handle_request) and answers
1581    /// each put on its own. An engine that writes several puts together may answer them with
1582    /// one response whose affected rows count all of them.
1583    fn handle_batch_put_requests(
1584        self: Arc<Self>,
1585        requests: Vec<(RegionId, RegionPutRequest)>,
1586    ) -> Vec<BatchPutResponse>
1587    where
1588        Self: 'static,
1589    {
1590        requests
1591            .into_iter()
1592            .map(|(region_id, request)| {
1593                let engine = self.clone();
1594                let response = async move {
1595                    engine
1596                        .handle_request(region_id, RegionRequest::Put(request))
1597                        .await
1598                }
1599                .boxed();
1600                (vec![region_id], response)
1601            })
1602            .collect()
1603    }
1604
1605    async fn handle_batch_ddl_requests(
1606        &self,
1607        request: BatchRegionDdlRequest,
1608    ) -> Result<RegionResponse, BoxedError> {
1609        let requests = request.into_region_requests();
1610
1611        let mut affected_rows = 0;
1612        let mut extensions = HashMap::new();
1613
1614        for (region_id, request) in requests {
1615            let result = self.handle_request(region_id, request).await?;
1616            affected_rows += result.affected_rows;
1617            extensions.extend(result.extensions);
1618        }
1619
1620        Ok(RegionResponse {
1621            affected_rows,
1622            extensions,
1623            metadata: Vec::new(),
1624        })
1625    }
1626
1627    /// Handles non-query request to the region. Returns the count of affected rows.
1628    async fn handle_request(
1629        &self,
1630        region_id: RegionId,
1631        request: RegionRequest,
1632    ) -> Result<RegionResponse, BoxedError>;
1633
1634    /// Returns the committed sequence (sequence of latest written data).
1635    async fn get_committed_sequence(
1636        &self,
1637        region_id: RegionId,
1638    ) -> Result<SequenceNumber, BoxedError>;
1639
1640    /// Handles query and return a scanner that can be used to scan the region concurrently.
1641    async fn handle_query(
1642        &self,
1643        region_id: RegionId,
1644        request: ScanRequest,
1645    ) -> Result<RegionScannerRef, BoxedError>;
1646
1647    /// Returns the query memory tracker for scan execution.
1648    fn query_memory_tracker(&self) -> Option<QueryMemoryTracker> {
1649        None
1650    }
1651
1652    /// Retrieves region's metadata.
1653    async fn get_metadata(&self, region_id: RegionId) -> Result<RegionMetadataRef, BoxedError>;
1654
1655    /// Retrieves region's statistic.
1656    fn region_statistic(&self, region_id: RegionId) -> Option<RegionStatistic>;
1657
1658    /// Stops the engine
1659    async fn stop(&self) -> Result<(), BoxedError>;
1660
1661    /// Sets [RegionRole] for a region.
1662    ///
1663    /// The engine checks whether the region is writable before writing to the region. Setting
1664    /// the region as readonly doesn't guarantee that write operations in progress will not
1665    /// take effect.
1666    fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>;
1667
1668    /// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`, in reply
1669    /// to a heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because
1670    /// the region was downgraded or (re)opened after `sent_at`, a catchup runs on it, or it waits
1671    /// for a reload.
1672    ///
1673    /// The region must not acknowledge a write whose WAL append completes at or after the
1674    /// deadline of its latest Leader or StagingLeader lease. Leases of other roles do not extend
1675    /// that deadline.
1676    ///
1677    /// `candidate_lease_id` is the lease's [GrantedRegion::candidate_lease_id]. A Follower lease
1678    /// that carries one may leave a region that a catchup made writable alone until its Leader or
1679    /// StagingLeader lease, see [`is_confirmed_leader`](Self::is_confirmed_leader).
1680    fn set_region_role_with_lease(
1681        &self,
1682        region_id: RegionId,
1683        role: RegionRole,
1684        sent_at: Instant,
1685        deadline: Instant,
1686        candidate_lease_id: Option<u64>,
1687    ) -> Result<bool, BoxedError>;
1688
1689    /// Syncs the region manifest to the given manifest version.
1690    async fn sync_region(
1691        &self,
1692        region_id: RegionId,
1693        request: SyncRegionFromRequest,
1694    ) -> Result<SyncRegionFromResponse, BoxedError>;
1695
1696    /// Remaps manifests from old regions to new regions.
1697    async fn remap_manifests(
1698        &self,
1699        request: RemapManifestsRequest,
1700    ) -> Result<RemapManifestsResponse, BoxedError>;
1701
1702    /// Sets region role state gracefully.
1703    ///
1704    /// After the call returns, the engine ensures no more write operations will succeed in the region.
1705    async fn set_region_role_state_gracefully(
1706        &self,
1707        region_id: RegionId,
1708        region_role_state: SettableRegionRoleState,
1709    ) -> Result<SetRegionRoleStateResponse, BoxedError>;
1710
1711    /// Indicates region role.
1712    ///
1713    /// Returns the `None` if the region is not found.
1714    fn role(&self, region_id: RegionId) -> Option<RegionRole>;
1715
1716    /// Returns whether the region is a leader that needs no catchup: `None` if the region is not
1717    /// found, `Some(false)` if it is a follower or, on a node that requires leases to confirm its
1718    /// leaders, a catchup made it a leader and no Leader or StagingLeader lease sent after that
1719    /// catchup, nor a direct promotion to Leader, has applied since, and `Some(true)` otherwise.
1720    /// The default answers from [`role`](Self::role) alone, which suits an engine that does not tie
1721    /// its commits to leases.
1722    ///
1723    /// An upgrade reports a region that answers `Some(true)` ready without a catchup, sends one
1724    /// that answers `Some(false)` a catchup with `set_writable`, and reports one that answers
1725    /// `None` missing.
1726    fn is_confirmed_leader(&self, region_id: RegionId) -> Option<bool> {
1727        self.role(region_id)
1728            .map(|role| role != RegionRole::Follower)
1729    }
1730
1731    fn as_any(&self) -> &dyn Any;
1732}
1733
1734pub type RegionEngineRef = Arc<dyn RegionEngine>;
1735
1736/// A [RegionScanner] that only scans a single partition.
1737pub struct SinglePartitionScanner {
1738    stream: Mutex<Option<SendableRecordBatchStream>>,
1739    schema: SchemaRef,
1740    properties: ScannerProperties,
1741    metadata: RegionMetadataRef,
1742    snapshot_sequence: Option<SequenceNumber>,
1743}
1744
1745impl SinglePartitionScanner {
1746    /// Creates a new [SinglePartitionScanner] with the given stream and metadata.
1747    pub fn new(
1748        stream: SendableRecordBatchStream,
1749        append_mode: bool,
1750        metadata: RegionMetadataRef,
1751        snapshot_sequence: Option<SequenceNumber>,
1752    ) -> Self {
1753        let schema = stream.schema();
1754        Self {
1755            stream: Mutex::new(Some(stream)),
1756            schema,
1757            properties: ScannerProperties::default().with_append_mode(append_mode),
1758            metadata,
1759            snapshot_sequence,
1760        }
1761    }
1762}
1763
1764impl Debug for SinglePartitionScanner {
1765    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1766        write!(f, "SinglePartitionScanner: <SendableRecordBatchStream>")
1767    }
1768}
1769
1770impl RegionScanner for SinglePartitionScanner {
1771    fn name(&self) -> &str {
1772        "SinglePartition"
1773    }
1774
1775    fn properties(&self) -> &ScannerProperties {
1776        &self.properties
1777    }
1778
1779    fn schema(&self) -> SchemaRef {
1780        self.schema.clone()
1781    }
1782
1783    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
1784        self.properties.prepare(request);
1785        Ok(())
1786    }
1787
1788    fn scan_partition(
1789        &self,
1790        _ctx: &QueryScanContext,
1791        _metrics_set: &ExecutionPlanMetricsSet,
1792        _partition: usize,
1793    ) -> Result<SendableRecordBatchStream, BoxedError> {
1794        let mut stream = self.stream.lock().unwrap();
1795        let result = stream
1796            .take()
1797            .or_else(|| Some(Box::pin(EmptyRecordBatchStream::new(self.schema.clone()))));
1798        Ok(result.unwrap())
1799    }
1800
1801    fn has_predicate_without_region(&self) -> bool {
1802        false
1803    }
1804
1805    fn add_dyn_filter_to_predicate(
1806        &mut self,
1807        filter_exprs: Vec<Arc<dyn datafusion_physical_plan::PhysicalExpr>>,
1808    ) -> Vec<bool> {
1809        vec![false; filter_exprs.len()]
1810    }
1811
1812    fn metadata(&self) -> RegionMetadataRef {
1813        self.metadata.clone()
1814    }
1815
1816    fn set_logical_region(&mut self, logical_region: bool) {
1817        self.properties.set_logical_region(logical_region);
1818    }
1819
1820    fn set_query_load_region_id(&mut self, region_id: RegionId) {
1821        self.properties.set_query_load_region_id(region_id);
1822    }
1823
1824    fn snapshot_sequence(&self) -> Option<SequenceNumber> {
1825        self.snapshot_sequence
1826    }
1827}
1828
1829impl DisplayAs for SinglePartitionScanner {
1830    fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1831        write!(f, "{:?}", self)
1832    }
1833}