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::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    /// Whether to yield an empty batch to distinguish partition ranges.
339    pub distinguish_partition_range: bool,
340
341    /// The target partitions of the scanner. 0 indicates using the number of partitions as target partitions.
342    target_partitions: usize,
343
344    /// Whether the scanner reads one logical metric region, including a physical
345    /// metric region constrained by a table-ID filter.
346    logical_region: bool,
347
348    /// Region id that should receive query-load metrics for this scanner.
349    query_load_region_id: Option<RegionId>,
350    /// Counters that should receive query-load metrics for this scanner.
351    query_stat_counters: Option<RegionQueryStatCounters>,
352}
353
354impl ScannerProperties {
355    /// Sets append mode for scanner.
356    pub fn with_append_mode(mut self, append_mode: bool) -> Self {
357        self.append_mode = append_mode;
358        self
359    }
360
361    /// Sets total rows for scanner.
362    pub fn with_total_rows(mut self, total_rows: usize) -> Self {
363        self.total_rows = total_rows;
364        self
365    }
366
367    /// Sets whether the source row count is exact before query predicates.
368    pub fn with_total_rows_is_exact(mut self, exact: bool) -> Self {
369        self.total_rows_is_exact = exact;
370        self
371    }
372
373    /// Creates a new [`ScannerProperties`] with the given partitioning.
374    pub fn new(partitions: Vec<Vec<PartitionRange>>, append_mode: bool, total_rows: usize) -> Self {
375        Self {
376            partitions,
377            append_mode,
378            total_rows,
379            total_rows_is_exact: false,
380            distinguish_partition_range: false,
381            target_partitions: 0,
382            logical_region: false,
383            query_load_region_id: None,
384            query_stat_counters: None,
385        }
386    }
387
388    /// Updates the properties with the given [PrepareRequest].
389    pub fn prepare(&mut self, request: PrepareRequest) {
390        if let Some(ranges) = request.ranges {
391            self.partitions = ranges;
392        }
393        if let Some(distinguish_partition_range) = request.distinguish_partition_range {
394            self.distinguish_partition_range = distinguish_partition_range;
395        }
396        if let Some(target_partitions) = request.target_partitions {
397            self.target_partitions = target_partitions;
398        }
399    }
400
401    /// Returns the number of actual partitions.
402    pub fn num_partitions(&self) -> usize {
403        self.partitions.len()
404    }
405
406    pub fn append_mode(&self) -> bool {
407        self.append_mode
408    }
409
410    pub fn total_rows(&self) -> usize {
411        self.total_rows
412    }
413
414    /// Returns whether the source row count is exact before query predicates.
415    pub fn total_rows_is_exact(&self) -> bool {
416        self.total_rows_is_exact
417    }
418
419    /// Returns whether the scanner reads one logical metric region, including a
420    /// physical metric region constrained by a table-ID filter.
421    pub fn is_logical_region(&self) -> bool {
422        self.logical_region
423    }
424
425    /// Returns the target partitions of the scanner. If it is not set, returns the number of partitions.
426    pub fn target_partitions(&self) -> usize {
427        if self.target_partitions == 0 {
428            self.num_partitions()
429        } else {
430            self.target_partitions
431        }
432    }
433
434    /// Sets whether the scanner reads one logical metric region.
435    pub fn set_logical_region(&mut self, logical_region: bool) {
436        self.logical_region = logical_region;
437    }
438
439    /// Returns the region id that should receive query-load metrics.
440    pub fn query_load_region_id(&self) -> Option<RegionId> {
441        self.query_load_region_id
442    }
443
444    /// Returns the counters that should receive query-load metrics.
445    pub fn query_stat_counters(&self) -> Option<RegionQueryStatCounters> {
446        self.query_stat_counters.clone()
447    }
448
449    /// Sets the region id that should receive query-load metrics.
450    pub fn set_query_load_region_id(&mut self, region_id: RegionId) {
451        self.query_load_region_id = Some(region_id);
452    }
453
454    /// Sets the counters that should receive query-load metrics.
455    pub fn set_query_stat_counters(&mut self, counters: RegionQueryStatCounters) {
456        self.query_stat_counters = Some(counters);
457    }
458}
459
460/// Request to override the scanner properties.
461#[derive(Default)]
462pub struct PrepareRequest {
463    /// Assigned partition ranges.
464    pub ranges: Option<Vec<Vec<PartitionRange>>>,
465    /// Distringuishes partition range by empty batches.
466    pub distinguish_partition_range: Option<bool>,
467    /// The expected number of target partitions.
468    pub target_partitions: Option<usize>,
469}
470
471impl PrepareRequest {
472    /// Sets the ranges.
473    pub fn with_ranges(mut self, ranges: Vec<Vec<PartitionRange>>) -> Self {
474        self.ranges = Some(ranges);
475        self
476    }
477
478    /// Sets the distinguish partition range flag.
479    pub fn with_distinguish_partition_range(mut self, distinguish_partition_range: bool) -> Self {
480        self.distinguish_partition_range = Some(distinguish_partition_range);
481        self
482    }
483
484    /// Sets the target partitions.
485    pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
486        self.target_partitions = Some(target_partitions);
487        self
488    }
489}
490
491/// Necessary context of the query for the scanner.
492/// Direct callers should create one context per scan and reuse it across partitions.
493/// The default pool is unbounded; cloning the context shares its pool.
494#[derive(Clone)]
495pub struct QueryScanContext {
496    /// Whether the query is EXPLAIN ANALYZE VERBOSE.
497    pub explain_verbose: bool,
498    /// Executing node's query runtime pool, shared by all partitions of this scan.
499    pub memory_pool: Arc<dyn MemoryPool>,
500}
501
502impl Default for QueryScanContext {
503    fn default() -> Self {
504        Self {
505            explain_verbose: false,
506            memory_pool: Arc::new(UnboundedMemoryPool::default()),
507        }
508    }
509}
510
511/// A tag bound to a physical column in the scan's metadata snapshot.
512#[derive(Clone, Debug)]
513pub struct BoundTag {
514    /// Physical region column identifier for this logical tag.
515    pub column_id: ColumnId,
516    /// Logical tag name visible to the query.
517    pub name: Arc<str>,
518}
519
520/// Bound source for materializing labels from raw series chunks.
521#[derive(Clone, Debug)]
522pub enum RawLabelSource {
523    /// Scan-bound metadata for labels. A producer may expose encoded keys or
524    /// complete explicit labels; its stream decode specification distinguishes them.
525    PrimaryKey {
526        /// Metric name associated with the bound logical source.
527        metric_name: Arc<str>,
528        /// Physical metadata snapshot used to decode primary-key values.
529        physical_metadata: RegionMetadataRef,
530        /// Logical tag names mapped to physical column identifiers.
531        logical_tags: Arc<[BoundTag]>,
532    },
533    /// The stream supplies a complete metric name and label set in each chunk, not a partial
534    /// label projection; `Some(metric)` is a complete name/label set (the name itself may be
535    /// absent), or, for a stream that has no identity at all, see
536    /// [`NO_BOUND_LABEL_SOURCE`].
537    Explicit,
538}
539
540/// The identity a stream reports when no scan-bound label source was established for it.
541///
542/// [`RawLabelSource`] has no "absent" variant, and [`RawLabelSource::Explicit`] is the only one that
543/// carries no physical region key layout, so it stands in for "no identity" here. It is not a claim
544/// that the chunks carry labels: [`RawSeriesStream::label_decode_spec`] answers that, and a stream
545/// reporting this value can still return `Some` description and leave `metric` as `None` in every
546/// chunk. Decoding therefore asks the description, and only an identity check asks this.
547pub const NO_BOUND_LABEL_SOURCE: RawLabelSource = RawLabelSource::Explicit;
548
549/// A stream of raw series chunks with stable schema, label binding, and ordering.
550///
551/// Every series has strictly increasing timestamps within and across chunks; timestamps are
552/// unique per series. `Interleaved` permits a series to resume after another series; `Contiguous`
553/// and `KeyThenTime` guarantee each series' chunks are contiguous. `KeyThenTime` uses the complete
554/// stream identity compatible with its label binding, not just a TSID or hash. These are
555/// per-stream guarantees, not query-global order, partition ownership, or finality. `is_last`
556/// marks the last chunk of that series in this stream only; merging requires recomputing
557/// per-input-series finalization across all related inputs, not aggregate-group finality.
558/// Label interpretation is carried by the stream: [`RawSeriesStream::label_source`] states the
559/// scan-bound identity a producer read under, and [`RawSeriesStream::label_decode_spec`] states the
560/// label layout the stream's own chunks declare. Stream finality applies to all related input
561/// series, not aggregate groups or vector-match state.
562pub trait RawSeriesStream: Stream<Item = Result<RawSeriesChunk, BoxedError>> + Send {
563    /// Returns the schema shared by all chunks; raw schemas have no evaluation grid.
564    fn schema(&self) -> &Arc<SeriesSchema>;
565    /// Returns scan-bound label metadata. The binding does not dictate representation:
566    /// chunks with a decode specification leave `metric` as `None`; otherwise they
567    /// supply the complete explicit label set. The metric name itself may be absent.
568    ///
569    /// A stream that was decoded from a raw frame has no scan-bound identity and reports
570    /// [`NO_BOUND_LABEL_SOURCE`], which reads as `Explicit` while its chunks may still carry no
571    /// labels at all. That value therefore answers "is this the region I read under", never "are
572    /// these labels complete": [`Self::label_decode_spec`] is the stream's statement about its
573    /// encoding, and every consumer that decides whether to decode reads that instead.
574    fn label_source(&self) -> &RawLabelSource;
575    /// Returns the label decode description this stream declares for key-encoded labels.
576    ///
577    /// Every stream whose chunks carry key-encoded labels declares the description here, whether
578    /// it is a storage producer or a stream reassembled from a raw frame. A consumer holding only
579    /// that description can therefore decode labels without a scan-bound [`RawLabelSource`]: the
580    /// description, not the binding, describes the encoding, and a receiver reporting
581    /// [`NO_BOUND_LABEL_SOURCE`] still states through this description that its chunks are
582    /// undecoded key chunks. A stream that carries complete labels instead answers `None`. This is
583    /// the description the stream declares, not an authenticated statement about where the values
584    /// came from.
585    fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> {
586        None
587    }
588    /// Returns this stream's ordering guarantee.
589    fn ordering(&self) -> SeriesOrdering;
590}
591
592/// A pinned raw-series stream that can be sent between threads.
593pub type SendableRawSeriesStream = Pin<Box<dyn RawSeriesStream>>;
594
595/// Stable identity metadata for one ordinal in a prepared series source.
596#[derive(Clone, Debug)]
597pub struct SeriesInfo {
598    /// Complete source identity, not a TSID or hash alone. Explicit-label sources
599    /// may use an opaque domain-qualified identity instead of a label-bearing key.
600    pub primary_key: datatypes::arrow::buffer::Buffer,
601    /// Complete explicit metric name and labels, not a partial label projection; or `None` for
602    /// primary-key label binding (undecoded, not nameless). The metric name itself may be absent.
603    pub metric: Option<datatypes::series::SeriesLabels>,
604}
605
606/// An immutable, finite selected set of series prepared for independent range reads.
607///
608/// The count may include series with no samples after filtering. Ordinals are stable local
609/// indexes, not protocol identifiers; each has exactly one complete identity returned by
610/// [`PreparedSeriesSource::series_info`], and that identity matches chunks for that ordinal.
611/// Every reader exposes the same fixed schema, label binding, and ordering before polling,
612/// including for an empty range, and describes labels independently of this source's lifetime.
613/// Key-encoded output has `metric: None`; explicit-label output has a complete
614/// `Some(metric)` matching each chunk, independently of its scan binding.
615/// Ordering describes the stream, not ordinal enumeration.
616///
617/// Preparation, identity lookup, and reader creation do not load sample payloads or perform
618/// hidden blocking I/O. The selected set is bound to the scanner's immutable MVCC view,
619/// predicates, authorization, projection, labels, and existing scan resources. Readers own
620/// resources needed to continue after this source or scanner is dropped. Dropping one reader
621/// does not cancel sibling readers; normal ownership cleanup applies without detached work.
622///
623/// A range must satisfy `start <= end <= num_series()`. Invalid ranges and invalid ordinals
624/// return errors; an empty in-bounds range returns an ordinary empty stream. Repeated and
625/// overlapping reads are independent and do not consume shared iteration state.
626pub trait PreparedSeriesSource: Send + Sync {
627    /// Returns the exact, stable number of selected local series ordinals.
628    fn num_series(&self) -> usize;
629
630    /// Returns label binding shared by series metadata and every reader, without opening or
631    /// polling a reader; the binding is self-contained for remote consumers.
632    fn label_source(&self) -> &RawLabelSource;
633
634    /// Returns identity metadata for an ordinal without polling sample data.
635    fn series_info(&self, ordinal: usize) -> Result<SeriesInfo, BoxedError>;
636
637    /// Creates an independent reader for the half-open ordinal range.
638    fn read_series(
639        &self,
640        range: std::ops::Range<usize>,
641    ) -> Result<SendableRawSeriesStream, BoxedError>;
642}
643
644/// A scanner that provides a way to scan the region concurrently.
645///
646/// The scanner splits the region into partitions so that each partition can be scanned concurrently.
647/// You can use this trait to implement an [`ExecutionPlan`](datafusion_physical_plan::ExecutionPlan).
648pub trait RegionScanner: Debug + DisplayAs + Send {
649    fn name(&self) -> &str;
650
651    /// Returns the properties of the scanner.
652    fn properties(&self) -> &ScannerProperties;
653
654    /// Returns the schema of the record batches.
655    fn schema(&self) -> SchemaRef;
656
657    /// Returns the metadata of the region.
658    fn metadata(&self) -> RegionMetadataRef;
659
660    /// Prepares the scanner with the given partition ranges.
661    ///
662    /// This method is for the planner to adjust the scanner's behavior based on the partition ranges.
663    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError>;
664
665    /// Scans the partition and returns a stream of record batches.
666    ///
667    /// # Panics
668    /// Panics if the `partition` is out of bound.
669    fn scan_partition(
670        &self,
671        ctx: &QueryScanContext,
672        metrics_set: &ExecutionPlanMetricsSet,
673        partition: usize,
674    ) -> Result<SendableRecordBatchStream, BoxedError>;
675
676    /// Checks whether this scanner can provide a raw-series scan for the given labels.
677    ///
678    /// This is a non-consuming preflight: it must not start a scan or otherwise consume
679    /// scanner state. It checks immutable label binding, schema, and typed residual-predicate
680    /// eligibility. Returning `Some` requires overriding `scan_series_partition` and
681    /// promises that it can execute with this label source. `None` means the raw path is
682    /// unsupported and an ordinary scan remains available. Execution must revalidate and
683    /// return errors rather than falling back if the binding or schema changed since preflight.
684    fn raw_series_schema(
685        &self,
686        _label_source: &RawLabelSource,
687    ) -> Result<Option<Arc<SeriesSchema>>, BoxedError> {
688        Ok(None)
689    }
690
691    /// Whether raw chunks carry complete explicit labels under this scan binding.
692    /// This non-consuming declaration must agree with the stream before its first poll.
693    /// Returning true does not replace the immutable source binding or authorization checks.
694    fn raw_series_has_explicit_labels(&self, _labels: &RawLabelSource) -> Result<bool, BoxedError> {
695        Ok(false)
696    }
697
698    /// Returns the guarantee for subsequent raw scans without consuming scanner state.
699    ///
700    /// Legacy raw sources have no ordering declaration, so `Contiguous` is the conservative
701    /// default; `Interleaved` is not representable on the raw frame wire.
702    fn raw_series_ordering(&self) -> Result<SeriesOrdering, BoxedError> {
703        Ok(SeriesOrdering::Contiguous)
704    }
705
706    /// Scans a partition as raw series when this source supports that path.
707    ///
708    /// `None` means raw capability is absent before execution and permits a legacy scan instead.
709    /// `Some` selects this entrypoint, including for an empty successful stream. Errors propagate;
710    /// callers must not replay a failed raw scan through the legacy path. Use only one entrypoint
711    /// for a given scanner partition per execution. The explicit label source is owned by the
712    /// returned stream and must be bound to this scanner's metadata snapshot.
713    ///
714    /// Output preserves the ordinary storage reader's pushdown and MVCC semantics. Inexact
715    /// pushed-down predicates can leave false-positive candidates, just as in `scan_partition`.
716    /// Implementations must preserve typed residual-predicate semantics before any lossy value
717    /// conversion, or return `None` before execution when they cannot. Callers must retain
718    /// residual predicate columns until those predicates are evaluated and apply the final
719    /// projection afterward; raw capability does not mean filtering is complete.
720    ///
721    /// # Panics
722    ///
723    /// The default implementation panics. Implementations must override this method to support
724    /// raw series scanning.
725    fn scan_series_partition(
726        &self,
727        _ctx: &QueryScanContext,
728        _metrics_set: &ExecutionPlanMetricsSet,
729        _partition: usize,
730        _label_source: &RawLabelSource,
731    ) -> Result<Option<SendableRawSeriesStream>, BoxedError> {
732        todo!()
733    }
734
735    /// Prepares scanner-wide candidates once for independent ordinal-range reads.
736    ///
737    /// Metadata I/O is asynchronous; sample payloads are loaded only by polling readers.
738    /// The owned future does not borrow the scanner. `None` means unsupported before
739    /// execution; errors must propagate without replay through a different scan path.
740    /// Implementations may share preparation with their raw partition adapter.
741    fn prepare_series(
742        &self,
743        _ctx: &QueryScanContext,
744        _metrics_set: &ExecutionPlanMetricsSet,
745        _label_source: &RawLabelSource,
746    ) -> futures::future::BoxFuture<
747        'static,
748        Result<Option<Arc<dyn PreparedSeriesSource>>, BoxedError>,
749    > {
750        Box::pin(async { Ok(None) })
751    }
752
753    /// Check if there is any predicate exclude region partition exprs that may be executed in this scanner.
754    fn has_predicate_without_region(&self) -> bool;
755
756    /// Add the given dynamic filter expressions to the predicate of the scanner.
757    /// Returns a vector of booleans indicating which filter expressions were applied.
758    /// true indicates the filter expression was applied(will be use by scanner to prune by stat for row group),
759    /// false otherwise.
760    fn add_dyn_filter_to_predicate(
761        &mut self,
762        filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
763    ) -> Vec<bool>;
764
765    /// Resets execution state after streams from the previous execution have been dropped.
766    ///
767    /// Callers must not concurrently execute, reset, or install filters through scanner aliases.
768    /// Implementations retaining dynamic predicates must discard them and derived pruning state,
769    /// while preserving static predicates, the source snapshot, and prepared properties.
770    /// The default is a no-op and does not make inherently one-shot sources replayable.
771    fn reset_state(&mut self) {}
772
773    /// Sets whether the scanner reads one logical metric region, including a
774    /// physical metric region constrained by a table-ID filter.
775    fn set_logical_region(&mut self, logical_region: bool);
776
777    /// Sets the region id that should receive query-load metrics.
778    fn set_query_load_region_id(&mut self, region_id: RegionId);
779
780    fn snapshot_sequence(&self) -> Option<SequenceNumber> {
781        None
782    }
783}
784
785pub type RegionScannerRef = Box<dyn RegionScanner>;
786
787pub type BatchResponses = Vec<(RegionId, Result<RegionResponse, BoxedError>)>;
788
789/// A response of [`RegionEngine::handle_batch_put_requests`] and the region of each put it
790/// answers for.
791pub type BatchPutResponse = (
792    Vec<RegionId>,
793    BoxFuture<'static, Result<RegionResponse, BoxedError>>,
794);
795
796/// Represents the statistics of a region.
797#[derive(Debug, Deserialize, Serialize, Default)]
798pub struct RegionStatistic {
799    /// The number of rows stored in SST files owned by this region plus rows in memtables.
800    ///
801    /// Rows from SST files referenced from other regions, for example after repartition,
802    /// are not counted to avoid table-level double counting when summing region statistics.
803    #[serde(default)]
804    pub num_rows: u64,
805    /// The size of memtable in bytes.
806    pub memtable_size: u64,
807    /// The size of WAL in bytes.
808    pub wal_size: u64,
809    /// Stored bytes of the latest observed manifest checkpoint and subsequent deltas,
810    /// compressed when enabled. Excludes staging manifests, `_last_checkpoint`, and
811    /// superseded files still present on disk. This is a logical recovery-size estimate,
812    /// not the physical directory usage; observation failures can leave it incomplete.
813    pub manifest_size: u64,
814    /// The size of SST data files owned by this region in bytes.
815    ///
816    /// SST files referenced from other regions, for example after repartition, are not counted.
817    pub sst_size: u64,
818    /// The number of SST files owned by this region.
819    ///
820    /// SST files referenced from other regions, for example after repartition, are not counted.
821    pub sst_num: u64,
822    /// The size of SST index files owned by this region in bytes.
823    ///
824    /// SST index files referenced from other regions, for example after repartition, are not counted.
825    #[serde(default)]
826    pub index_size: u64,
827    /// The details of the region.
828    #[serde(default)]
829    pub manifest: RegionManifestInfo,
830    #[serde(default)]
831    /// The total bytes written of the region since region opened.
832    pub written_bytes: u64,
833    /// Total ingested Parquet bytes since the region opened.
834    /// Currently counts only committed flush output.
835    ///
836    /// Excludes index files, compaction and imported SSTs.
837    /// Resets when the region instance is recreated; manifest replay does not increment it.
838    /// Accepts the legacy `flushed_parquet_bytes` key; upgrade metasrv before datanodes.
839    #[serde(default, alias = "flushed_parquet_bytes")]
840    pub ingested_parquet_bytes: u64,
841    /// The total query CPU time of the region since region opened.
842    ///
843    /// Unit: nanoseconds.
844    #[serde(default)]
845    pub query_cpu_time: u64,
846    /// The total scanned bytes of the region since region opened.
847    #[serde(default)]
848    pub query_scanned_bytes: u64,
849    /// The earliest timestamp of the region's current data, or `None` if it holds
850    /// none. Unlike the size and row counters this covers files referenced from
851    /// other regions too, since a time range cannot double count.
852    #[serde(default)]
853    pub min_timestamp: Option<Timestamp>,
854    /// The latest timestamp of the region's current data. See [`Self::min_timestamp`].
855    #[serde(default)]
856    pub max_timestamp: Option<Timestamp>,
857    /// The latest entry id of the region's remote WAL since last flush.
858    /// For metric engine, there're two latest entry ids, one for data and one for metadata.
859    /// TODO(weny): remove this two fields and use single instead.
860    #[serde(default)]
861    pub data_topic_latest_entry_id: u64,
862    #[serde(default)]
863    pub metadata_topic_latest_entry_id: u64,
864    /// Whether the region still has WAL ranges to recover. Omitted from the serialized form
865    /// when false.
866    #[serde(default, skip_serializing_if = "crate::is_false")]
867    pub has_pending_tails: bool,
868}
869
870/// The manifest info of a region.
871#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
872pub enum RegionManifestInfo {
873    Mito {
874        manifest_version: u64,
875        flushed_entry_id: u64,
876        /// Number of files removed in the manifest's `removed_files` field.
877        file_removed_cnt: u64,
878    },
879    Metric {
880        data_manifest_version: u64,
881        data_flushed_entry_id: u64,
882        metadata_manifest_version: u64,
883        metadata_flushed_entry_id: u64,
884    },
885}
886
887impl RegionManifestInfo {
888    /// Creates a new [RegionManifestInfo] for mito2 engine.
889    pub fn mito(manifest_version: u64, flushed_entry_id: u64, file_removal_rate: u64) -> Self {
890        Self::Mito {
891            manifest_version,
892            flushed_entry_id,
893            file_removed_cnt: file_removal_rate,
894        }
895    }
896
897    /// Creates a new [RegionManifestInfo] for metric engine.
898    pub fn metric(
899        data_manifest_version: u64,
900        data_flushed_entry_id: u64,
901        metadata_manifest_version: u64,
902        metadata_flushed_entry_id: u64,
903    ) -> Self {
904        Self::Metric {
905            data_manifest_version,
906            data_flushed_entry_id,
907            metadata_manifest_version,
908            metadata_flushed_entry_id,
909        }
910    }
911
912    /// Returns true if the region is a mito2 region.
913    pub fn is_mito(&self) -> bool {
914        matches!(self, RegionManifestInfo::Mito { .. })
915    }
916
917    /// Returns true if the region is a metric region.
918    pub fn is_metric(&self) -> bool {
919        matches!(self, RegionManifestInfo::Metric { .. })
920    }
921
922    /// Returns the flushed entry id of the data region.
923    pub fn data_flushed_entry_id(&self) -> u64 {
924        match self {
925            RegionManifestInfo::Mito {
926                flushed_entry_id, ..
927            } => *flushed_entry_id,
928            RegionManifestInfo::Metric {
929                data_flushed_entry_id,
930                ..
931            } => *data_flushed_entry_id,
932        }
933    }
934
935    /// Returns the manifest version of the data region.
936    pub fn data_manifest_version(&self) -> u64 {
937        match self {
938            RegionManifestInfo::Mito {
939                manifest_version, ..
940            } => *manifest_version,
941            RegionManifestInfo::Metric {
942                data_manifest_version,
943                ..
944            } => *data_manifest_version,
945        }
946    }
947
948    /// Returns the manifest version of the metadata region.
949    pub fn metadata_manifest_version(&self) -> Option<u64> {
950        match self {
951            RegionManifestInfo::Mito { .. } => None,
952            RegionManifestInfo::Metric {
953                metadata_manifest_version,
954                ..
955            } => Some(*metadata_manifest_version),
956        }
957    }
958
959    /// Returns the flushed entry id of the metadata region.
960    pub fn metadata_flushed_entry_id(&self) -> Option<u64> {
961        match self {
962            RegionManifestInfo::Mito { .. } => None,
963            RegionManifestInfo::Metric {
964                metadata_flushed_entry_id,
965                ..
966            } => Some(*metadata_flushed_entry_id),
967        }
968    }
969
970    /// Encodes a list of ([RegionId], [RegionManifestInfo]) to a byte array.
971    pub fn encode_list(manifest_infos: &[(RegionId, Self)]) -> serde_json::Result<Vec<u8>> {
972        serde_json::to_vec(manifest_infos)
973    }
974
975    /// Decodes a list of ([RegionId], [RegionManifestInfo]) from a byte array.
976    pub fn decode_list(value: &[u8]) -> serde_json::Result<Vec<(RegionId, Self)>> {
977        serde_json::from_slice(value)
978    }
979}
980
981impl Default for RegionManifestInfo {
982    fn default() -> Self {
983        Self::Mito {
984            manifest_version: 0,
985            flushed_entry_id: 0,
986            file_removed_cnt: 0,
987        }
988    }
989}
990
991impl RegionStatistic {
992    /// Deserializes the region statistic to a byte array.
993    ///
994    /// Returns None if the deserialization fails.
995    pub fn deserialize_from_slice(value: &[u8]) -> Option<RegionStatistic> {
996        serde_json::from_slice(value).ok()
997    }
998
999    /// Serializes the region statistic to a byte array.
1000    ///
1001    /// Returns None if the serialization fails.
1002    pub fn serialize_to_vec(&self) -> Option<Vec<u8>> {
1003        serde_json::to_vec(self).ok()
1004    }
1005}
1006
1007impl RegionStatistic {
1008    /// Returns the estimated disk size of the region.
1009    pub fn estimated_disk_size(&self) -> u64 {
1010        self.wal_size + self.sst_size + self.manifest_size + self.index_size
1011    }
1012}
1013
1014#[cfg(test)]
1015#[path = "region_engine/prepared_series_tests.rs"]
1016mod prepared_series_tests;
1017
1018#[cfg(test)]
1019mod tests {
1020    use common_recordbatch::{RecordBatch, RecordBatches};
1021    use datatypes::prelude::ConcreteDataType;
1022    use datatypes::schema::ColumnSchema;
1023    use datatypes::vectors::{Int32Vector, TimestampMillisecondVector, VectorRef};
1024    use futures::TryStreamExt;
1025    use serde_json::json;
1026
1027    use super::*;
1028
1029    #[tokio::test]
1030    async fn single_partition_scanner_raw_scan_panics_and_preserves_legacy_read() {
1031        use std::panic::{AssertUnwindSafe, catch_unwind};
1032
1033        use api::v1::SemanticType;
1034        use datatypes::arrow::array::Int32Array;
1035        use datatypes::schema::Schema as ArrowSchema;
1036
1037        use crate::metadata::{ColumnMetadata, RegionMetadataBuilder};
1038
1039        let schema = Arc::new(ArrowSchema::new(vec![
1040            ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false),
1041            ColumnSchema::new(
1042                "ts",
1043                ConcreteDataType::timestamp_millisecond_datatype(),
1044                false,
1045            ),
1046        ]));
1047        let columns: Vec<VectorRef> = vec![
1048            Arc::new(Int32Vector::from_slice([42])),
1049            Arc::new(TimestampMillisecondVector::from_slice([7])),
1050        ];
1051        let batch = RecordBatch::new(schema.clone(), columns).unwrap();
1052        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1053        let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1234, 1));
1054        metadata_builder.push_column_metadata(ColumnMetadata {
1055            column_schema: ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false),
1056            semantic_type: SemanticType::Field,
1057            column_id: 1,
1058        });
1059        metadata_builder.push_column_metadata(ColumnMetadata {
1060            column_schema: ColumnSchema::new(
1061                "ts",
1062                ConcreteDataType::timestamp_millisecond_datatype(),
1063                false,
1064            ),
1065            semantic_type: SemanticType::Timestamp,
1066            column_id: 2,
1067        });
1068        let metadata = Arc::new(metadata_builder.build().unwrap());
1069        let scanner = SinglePartitionScanner::new(batches.as_stream(), false, metadata, None);
1070        let ctx = QueryScanContext::default();
1071        let metrics = ExecutionPlanMetricsSet::new();
1072
1073        // The default raw-scan preflight declines without consuming the legacy scan, and the
1074        // prepared-series entrypoint reports unsupported before consumption as well.
1075        assert!(
1076            scanner
1077                .raw_series_schema(&RawLabelSource::Explicit)
1078                .unwrap()
1079                .is_none()
1080        );
1081        assert!(
1082            scanner
1083                .prepare_series(&ctx, &metrics, &RawLabelSource::Explicit)
1084                .await
1085                .unwrap()
1086                .is_none()
1087        );
1088        assert_eq!(
1089            scanner.raw_series_ordering().unwrap(),
1090            SeriesOrdering::Contiguous
1091        );
1092
1093        // SinglePartitionScanner uses the default raw-scan implementation, which panics.
1094        let raw_scan = catch_unwind(AssertUnwindSafe(|| {
1095            scanner.scan_series_partition(&ctx, &metrics, 0, &RawLabelSource::Explicit)
1096        }));
1097        assert!(raw_scan.is_err());
1098        let legacy = scanner.scan_partition(&ctx, &metrics, 0).unwrap();
1099        let legacy_batches = legacy.try_collect::<Vec<_>>().await.unwrap();
1100        assert_eq!(legacy_batches.len(), 1);
1101        assert_eq!(legacy_batches[0].num_rows(), 1);
1102        assert_eq!(
1103            legacy_batches[0]
1104                .column(0)
1105                .as_ref()
1106                .as_any()
1107                .downcast_ref::<Int32Array>()
1108                .unwrap()
1109                .value(0),
1110            42
1111        );
1112    }
1113
1114    #[test]
1115    fn test_legacy_granted_region_wire() {
1116        use prost::Message;
1117
1118        let legacy_bytes: &[u8] = include_bytes!(
1119            "../../../tests/compatibility/wire/candidate_lease_id/legacy_granted_region.pb"
1120        );
1121        let granted = GrantedRegion::from(PbGrantedRegion::decode(legacy_bytes).unwrap());
1122        assert_eq!(
1123            granted,
1124            GrantedRegion {
1125                candidate_lease_id: None,
1126                extensions: HashMap::from([("plugin".to_string(), b"payload".to_vec())]),
1127                ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower)
1128            }
1129        );
1130
1131        assert_eq!(PbGrantedRegion::from(granted).encode_to_vec(), legacy_bytes);
1132    }
1133
1134    #[test]
1135    fn test_granted_region_candidate_lease_id_wire() {
1136        use prost::Message;
1137
1138        let granted = GrantedRegion {
1139            candidate_lease_id: Some(7),
1140            ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower)
1141        };
1142        // Region id (field 1), role Follower (field 2), then candidate_lease_id as a uint64
1143        // varint in field 3.
1144        let bytes: &[u8] = &[
1145            0x08, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01, 0x10, 0x01, 0x18, 0x07,
1146        ];
1147        assert_eq!(
1148            PbGrantedRegion::from(granted.clone()).encode_to_vec(),
1149            bytes
1150        );
1151        assert_eq!(
1152            GrantedRegion::from(PbGrantedRegion::decode(bytes).unwrap()),
1153            granted
1154        );
1155    }
1156
1157    #[test]
1158    fn region_statistic_flush_bytes_compatibility() {
1159        let legacy_bytes = br#"{
1160            "num_rows": 1,
1161            "memtable_size": 2,
1162            "wal_size": 3,
1163            "manifest_size": 4,
1164            "sst_size": 5,
1165            "sst_num": 6,
1166            "index_size": 7,
1167            "manifest": {
1168                "Mito": {
1169                    "manifest_version": 8,
1170                    "flushed_entry_id": 9,
1171                    "file_removed_cnt": 10
1172                }
1173            },
1174            "written_bytes": 11
1175        }"#;
1176        let mut statistic = RegionStatistic::deserialize_from_slice(legacy_bytes).unwrap();
1177        assert_eq!(statistic.ingested_parquet_bytes, 0);
1178        statistic.ingested_parquet_bytes = 1234;
1179        let encoded = statistic.serialize_to_vec().unwrap();
1180        let decoded = RegionStatistic::deserialize_from_slice(&encoded).unwrap();
1181        assert_eq!(decoded.ingested_parquet_bytes, 1234);
1182        let legacy: serde_json::Value = serde_json::from_slice(legacy_bytes).unwrap();
1183        let mut current: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
1184        assert_eq!(current["ingested_parquet_bytes"], 1234);
1185        assert!(current.get("flushed_parquet_bytes").is_none());
1186        let mut old_wire = current.clone();
1187        let bytes = old_wire
1188            .as_object_mut()
1189            .unwrap()
1190            .remove("ingested_parquet_bytes")
1191            .unwrap();
1192        old_wire["flushed_parquet_bytes"] = bytes;
1193        assert_eq!(
1194            serde_json::from_value::<RegionStatistic>(old_wire)
1195                .unwrap()
1196                .ingested_parquet_bytes,
1197            1234
1198        );
1199        for (key, value) in legacy.as_object().unwrap() {
1200            assert_eq!(&current[key], value);
1201        }
1202        current
1203            .as_object_mut()
1204            .unwrap()
1205            .remove("ingested_parquet_bytes");
1206        assert_eq!(
1207            serde_json::from_value::<RegionStatistic>(current)
1208                .unwrap()
1209                .ingested_parquet_bytes,
1210            0
1211        );
1212    }
1213
1214    #[test]
1215    fn region_statistic_deserializes_without_query_stats() {
1216        let statistic: RegionStatistic = serde_json::from_value(json!({
1217            "num_rows": 1,
1218            "memtable_size": 2,
1219            "wal_size": 3,
1220            "manifest_size": 4,
1221            "sst_size": 5,
1222            "sst_num": 6,
1223            "index_size": 7,
1224            "manifest": {
1225                "Mito": {
1226                    "manifest_version": 8,
1227                    "flushed_entry_id": 9,
1228                    "file_removed_cnt": 10
1229                }
1230            },
1231            "written_bytes": 11
1232        }))
1233        .unwrap();
1234
1235        assert_eq!(statistic.query_cpu_time, 0);
1236        assert_eq!(statistic.query_scanned_bytes, 0);
1237    }
1238}
1239
1240/// Request to sync the region from a manifest or a region.
1241#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1242pub enum SyncRegionFromRequest {
1243    /// Syncs the region using manifest information.
1244    /// Used in leader-follower manifest sync scenarios.
1245    FromManifest(RegionManifestInfo),
1246    /// Syncs the region from another region.
1247    ///
1248    /// Used by the metric engine to sync logical regions from a source physical region
1249    /// to a target physical region. This copies metadata region SST files and transforms
1250    /// logical region entries to use the target's region number.
1251    FromRegion {
1252        /// The [`RegionId`] of the source region.
1253        source_region_id: RegionId,
1254        /// The parallelism of the sync operation.
1255        parallelism: usize,
1256    },
1257}
1258
1259impl From<RegionManifestInfo> for SyncRegionFromRequest {
1260    fn from(manifest_info: RegionManifestInfo) -> Self {
1261        SyncRegionFromRequest::FromManifest(manifest_info)
1262    }
1263}
1264
1265impl SyncRegionFromRequest {
1266    /// Creates a new request from a manifest info.
1267    pub fn from_manifest(manifest_info: RegionManifestInfo) -> Self {
1268        SyncRegionFromRequest::FromManifest(manifest_info)
1269    }
1270
1271    /// Creates a new request from a region.
1272    pub fn from_region(source_region_id: RegionId, parallelism: usize) -> Self {
1273        SyncRegionFromRequest::FromRegion {
1274            source_region_id,
1275            parallelism,
1276        }
1277    }
1278
1279    /// Returns true if the request is from a manifest.
1280    pub fn is_from_manifest(&self) -> bool {
1281        matches!(self, SyncRegionFromRequest::FromManifest { .. })
1282    }
1283
1284    /// Converts the request to a region manifest info.
1285    ///
1286    /// Returns None if the request is not from a manifest.
1287    pub fn into_region_manifest_info(self) -> Option<RegionManifestInfo> {
1288        match self {
1289            SyncRegionFromRequest::FromManifest(manifest_info) => Some(manifest_info),
1290            SyncRegionFromRequest::FromRegion { .. } => None,
1291        }
1292    }
1293}
1294
1295/// The response of syncing the region.
1296#[derive(Debug)]
1297pub enum SyncRegionFromResponse {
1298    NotSupported,
1299    Mito {
1300        /// Indicates if the data region was synced.
1301        synced: bool,
1302    },
1303    Metric {
1304        /// Indicates if the metadata region was synced.
1305        metadata_synced: bool,
1306        /// Indicates if the data region was synced.
1307        data_synced: bool,
1308        /// The logical regions that were newly opened during the sync operation.
1309        /// This only occurs after the metadata region has been successfully synced.
1310        new_opened_logical_region_ids: Vec<RegionId>,
1311    },
1312}
1313
1314impl SyncRegionFromResponse {
1315    /// Returns true if data region is synced.
1316    pub fn is_data_synced(&self) -> bool {
1317        match self {
1318            SyncRegionFromResponse::NotSupported => false,
1319            SyncRegionFromResponse::Mito { synced } => *synced,
1320            SyncRegionFromResponse::Metric { data_synced, .. } => *data_synced,
1321        }
1322    }
1323
1324    /// Returns true if the engine is a mito2 engine.
1325    pub fn is_mito(&self) -> bool {
1326        matches!(self, SyncRegionFromResponse::Mito { .. })
1327    }
1328
1329    /// Returns true if the engine is a metric engine.
1330    pub fn is_metric(&self) -> bool {
1331        matches!(self, SyncRegionFromResponse::Metric { .. })
1332    }
1333
1334    /// Returns the new opened logical region ids.
1335    pub fn new_opened_logical_region_ids(self) -> Option<Vec<RegionId>> {
1336        match self {
1337            SyncRegionFromResponse::Metric {
1338                new_opened_logical_region_ids,
1339                ..
1340            } => Some(new_opened_logical_region_ids),
1341            _ => None,
1342        }
1343    }
1344}
1345
1346/// Request to remap manifests from old regions to new regions.
1347#[derive(Debug, Clone)]
1348pub struct RemapManifestsRequest {
1349    /// The [`RegionId`] of a staging region used to obtain table directory and storage configuration for the remap operation.
1350    pub region_id: RegionId,
1351    /// Regions to remap manifests from.
1352    pub input_regions: Vec<RegionId>,
1353    /// For each old region, which new regions should receive its files
1354    pub region_mapping: HashMap<RegionId, Vec<RegionId>>,
1355    /// New partition expressions for the new regions.
1356    pub new_partition_exprs: HashMap<RegionId, String>,
1357}
1358
1359/// Response to remap manifests from old regions to new regions.
1360#[derive(Debug, Clone)]
1361pub struct RemapManifestsResponse {
1362    /// Maps region id to its staging manifest path.
1363    ///
1364    /// These paths are relative paths within the central region's staging blob storage,
1365    /// and should be passed to [`ApplyStagingManifestRequest`](RegionRequest::ApplyStagingManifest) to finalize the repartition.
1366    pub manifest_paths: HashMap<RegionId, String>,
1367}
1368
1369/// Request to copy files from a source region to a target region.
1370#[derive(Debug, Clone)]
1371pub struct MitoCopyRegionFromRequest {
1372    /// The [`RegionId`] of the source region.
1373    pub source_region_id: RegionId,
1374    /// The parallelism of the copy operation.
1375    pub parallelism: usize,
1376}
1377
1378#[derive(Debug, Clone)]
1379pub struct MitoCopyRegionFromResponse {
1380    /// Source SST IDs installed in the target by this copy. Shared references may
1381    /// be installed without copying their physical objects. If no new references
1382    /// need installation, returns the source IDs already present in the target.
1383    /// This is not a count or inventory of physical object transfers.
1384    pub copied_file_ids: Vec<FileId>,
1385}
1386
1387#[async_trait]
1388pub trait RegionEngine: Send + Sync {
1389    /// Name of this engine
1390    fn name(&self) -> &str;
1391
1392    /// Handles batch open region requests.
1393    async fn handle_batch_open_requests(
1394        &self,
1395        parallelism: usize,
1396        requests: Vec<(RegionId, RegionOpenRequest)>,
1397    ) -> Result<BatchResponses, BoxedError> {
1398        let semaphore = Arc::new(Semaphore::new(parallelism));
1399        let mut tasks = Vec::with_capacity(requests.len());
1400
1401        for (region_id, request) in requests {
1402            let semaphore_moved = semaphore.clone();
1403
1404            tasks.push(async move {
1405                // Safety: semaphore must exist
1406                let _permit = semaphore_moved.acquire().await.unwrap();
1407                let result = self
1408                    .handle_request(region_id, RegionRequest::Open(request))
1409                    .await;
1410                (region_id, result)
1411            });
1412        }
1413
1414        Ok(join_all(tasks).await)
1415    }
1416
1417    async fn handle_batch_catchup_requests(
1418        &self,
1419        parallelism: usize,
1420        requests: Vec<(RegionId, RegionCatchupRequest)>,
1421    ) -> Result<BatchResponses, BoxedError> {
1422        let semaphore = Arc::new(Semaphore::new(parallelism));
1423        let mut tasks = Vec::with_capacity(requests.len());
1424
1425        for (region_id, request) in requests {
1426            let semaphore_moved = semaphore.clone();
1427
1428            tasks.push(async move {
1429                // Safety: semaphore must exist
1430                let _permit = semaphore_moved.acquire().await.unwrap();
1431                let result = self
1432                    .handle_request(region_id, RegionRequest::Catchup(request))
1433                    .await;
1434                (region_id, result)
1435            });
1436        }
1437
1438        Ok(join_all(tasks).await)
1439    }
1440
1441    /// Handles the puts of one request into regions of this engine and returns the responses
1442    /// to await on their own, each with the region of every put it answers for: two puts to one
1443    /// region are two entries.
1444    ///
1445    /// The default handles each put with [`handle_request`](Self::handle_request) and answers
1446    /// each put on its own. An engine that writes several puts together may answer them with
1447    /// one response whose affected rows count all of them.
1448    fn handle_batch_put_requests(
1449        self: Arc<Self>,
1450        requests: Vec<(RegionId, RegionPutRequest)>,
1451    ) -> Vec<BatchPutResponse>
1452    where
1453        Self: 'static,
1454    {
1455        requests
1456            .into_iter()
1457            .map(|(region_id, request)| {
1458                let engine = self.clone();
1459                let response = async move {
1460                    engine
1461                        .handle_request(region_id, RegionRequest::Put(request))
1462                        .await
1463                }
1464                .boxed();
1465                (vec![region_id], response)
1466            })
1467            .collect()
1468    }
1469
1470    async fn handle_batch_ddl_requests(
1471        &self,
1472        request: BatchRegionDdlRequest,
1473    ) -> Result<RegionResponse, BoxedError> {
1474        let requests = request.into_region_requests();
1475
1476        let mut affected_rows = 0;
1477        let mut extensions = HashMap::new();
1478
1479        for (region_id, request) in requests {
1480            let result = self.handle_request(region_id, request).await?;
1481            affected_rows += result.affected_rows;
1482            extensions.extend(result.extensions);
1483        }
1484
1485        Ok(RegionResponse {
1486            affected_rows,
1487            extensions,
1488            metadata: Vec::new(),
1489        })
1490    }
1491
1492    /// Handles non-query request to the region. Returns the count of affected rows.
1493    async fn handle_request(
1494        &self,
1495        region_id: RegionId,
1496        request: RegionRequest,
1497    ) -> Result<RegionResponse, BoxedError>;
1498
1499    /// Returns the committed sequence (sequence of latest written data).
1500    async fn get_committed_sequence(
1501        &self,
1502        region_id: RegionId,
1503    ) -> Result<SequenceNumber, BoxedError>;
1504
1505    /// Handles query and return a scanner that can be used to scan the region concurrently.
1506    async fn handle_query(
1507        &self,
1508        region_id: RegionId,
1509        request: ScanRequest,
1510    ) -> Result<RegionScannerRef, BoxedError>;
1511
1512    /// Returns the query memory tracker for scan execution.
1513    fn query_memory_tracker(&self) -> Option<QueryMemoryTracker> {
1514        None
1515    }
1516
1517    /// Retrieves region's metadata.
1518    async fn get_metadata(&self, region_id: RegionId) -> Result<RegionMetadataRef, BoxedError>;
1519
1520    /// Retrieves region's statistic.
1521    fn region_statistic(&self, region_id: RegionId) -> Option<RegionStatistic>;
1522
1523    /// Stops the engine
1524    async fn stop(&self) -> Result<(), BoxedError>;
1525
1526    /// Sets [RegionRole] for a region.
1527    ///
1528    /// The engine checks whether the region is writable before writing to the region. Setting
1529    /// the region as readonly doesn't guarantee that write operations in progress will not
1530    /// take effect.
1531    fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>;
1532
1533    /// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`, in reply
1534    /// to a heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because
1535    /// the region was downgraded or (re)opened after `sent_at`, a catchup runs on it, or it waits
1536    /// for a reload.
1537    ///
1538    /// The region must not acknowledge a write whose WAL append completes at or after the
1539    /// deadline of its latest Leader or StagingLeader lease. Leases of other roles do not extend
1540    /// that deadline.
1541    ///
1542    /// `candidate_lease_id` is the lease's [GrantedRegion::candidate_lease_id]. A Follower lease
1543    /// that carries one may leave a region that a catchup made writable alone until its Leader or
1544    /// StagingLeader lease, see [`is_confirmed_leader`](Self::is_confirmed_leader).
1545    fn set_region_role_with_lease(
1546        &self,
1547        region_id: RegionId,
1548        role: RegionRole,
1549        sent_at: Instant,
1550        deadline: Instant,
1551        candidate_lease_id: Option<u64>,
1552    ) -> Result<bool, BoxedError>;
1553
1554    /// Syncs the region manifest to the given manifest version.
1555    async fn sync_region(
1556        &self,
1557        region_id: RegionId,
1558        request: SyncRegionFromRequest,
1559    ) -> Result<SyncRegionFromResponse, BoxedError>;
1560
1561    /// Remaps manifests from old regions to new regions.
1562    async fn remap_manifests(
1563        &self,
1564        request: RemapManifestsRequest,
1565    ) -> Result<RemapManifestsResponse, BoxedError>;
1566
1567    /// Sets region role state gracefully.
1568    ///
1569    /// After the call returns, the engine ensures no more write operations will succeed in the region.
1570    async fn set_region_role_state_gracefully(
1571        &self,
1572        region_id: RegionId,
1573        region_role_state: SettableRegionRoleState,
1574    ) -> Result<SetRegionRoleStateResponse, BoxedError>;
1575
1576    /// Indicates region role.
1577    ///
1578    /// Returns the `None` if the region is not found.
1579    fn role(&self, region_id: RegionId) -> Option<RegionRole>;
1580
1581    /// Returns whether the region is a leader that needs no catchup: `None` if the region is not
1582    /// found, `Some(false)` if it is a follower or, on a node that requires leases to confirm its
1583    /// leaders, a catchup made it a leader and no Leader or StagingLeader lease sent after that
1584    /// catchup, nor a direct promotion to Leader, has applied since, and `Some(true)` otherwise.
1585    /// The default answers from [`role`](Self::role) alone, which suits an engine that does not tie
1586    /// its commits to leases.
1587    ///
1588    /// An upgrade reports a region that answers `Some(true)` ready without a catchup, sends one
1589    /// that answers `Some(false)` a catchup with `set_writable`, and reports one that answers
1590    /// `None` missing.
1591    fn is_confirmed_leader(&self, region_id: RegionId) -> Option<bool> {
1592        self.role(region_id)
1593            .map(|role| role != RegionRole::Follower)
1594    }
1595
1596    fn as_any(&self) -> &dyn Any;
1597}
1598
1599pub type RegionEngineRef = Arc<dyn RegionEngine>;
1600
1601/// A [RegionScanner] that only scans a single partition.
1602pub struct SinglePartitionScanner {
1603    stream: Mutex<Option<SendableRecordBatchStream>>,
1604    schema: SchemaRef,
1605    properties: ScannerProperties,
1606    metadata: RegionMetadataRef,
1607    snapshot_sequence: Option<SequenceNumber>,
1608}
1609
1610impl SinglePartitionScanner {
1611    /// Creates a new [SinglePartitionScanner] with the given stream and metadata.
1612    pub fn new(
1613        stream: SendableRecordBatchStream,
1614        append_mode: bool,
1615        metadata: RegionMetadataRef,
1616        snapshot_sequence: Option<SequenceNumber>,
1617    ) -> Self {
1618        let schema = stream.schema();
1619        Self {
1620            stream: Mutex::new(Some(stream)),
1621            schema,
1622            properties: ScannerProperties::default().with_append_mode(append_mode),
1623            metadata,
1624            snapshot_sequence,
1625        }
1626    }
1627}
1628
1629impl Debug for SinglePartitionScanner {
1630    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1631        write!(f, "SinglePartitionScanner: <SendableRecordBatchStream>")
1632    }
1633}
1634
1635impl RegionScanner for SinglePartitionScanner {
1636    fn name(&self) -> &str {
1637        "SinglePartition"
1638    }
1639
1640    fn properties(&self) -> &ScannerProperties {
1641        &self.properties
1642    }
1643
1644    fn schema(&self) -> SchemaRef {
1645        self.schema.clone()
1646    }
1647
1648    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
1649        self.properties.prepare(request);
1650        Ok(())
1651    }
1652
1653    fn scan_partition(
1654        &self,
1655        _ctx: &QueryScanContext,
1656        _metrics_set: &ExecutionPlanMetricsSet,
1657        _partition: usize,
1658    ) -> Result<SendableRecordBatchStream, BoxedError> {
1659        let mut stream = self.stream.lock().unwrap();
1660        let result = stream
1661            .take()
1662            .or_else(|| Some(Box::pin(EmptyRecordBatchStream::new(self.schema.clone()))));
1663        Ok(result.unwrap())
1664    }
1665
1666    fn has_predicate_without_region(&self) -> bool {
1667        false
1668    }
1669
1670    fn add_dyn_filter_to_predicate(
1671        &mut self,
1672        filter_exprs: Vec<Arc<dyn datafusion_physical_plan::PhysicalExpr>>,
1673    ) -> Vec<bool> {
1674        vec![false; filter_exprs.len()]
1675    }
1676
1677    fn metadata(&self) -> RegionMetadataRef {
1678        self.metadata.clone()
1679    }
1680
1681    fn set_logical_region(&mut self, logical_region: bool) {
1682        self.properties.set_logical_region(logical_region);
1683    }
1684
1685    fn set_query_load_region_id(&mut self, region_id: RegionId) {
1686        self.properties.set_query_load_region_id(region_id);
1687    }
1688
1689    fn snapshot_sequence(&self) -> Option<SequenceNumber> {
1690        self.snapshot_sequence
1691    }
1692}
1693
1694impl DisplayAs for SinglePartitionScanner {
1695    fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1696        write!(f, "{:?}", self)
1697    }
1698}