From 879b0a612f3fb96faf83c12cedf111238af93eed Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 25 Nov 2026 13:58:36 +0800 Subject: [PATCH] fix(mito2): read a memtable row by the cursor of its piece MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A memtable scan filtered rows by one floor for the whole read — the least advanced of the region's slices — which is exact only while every slice carries one cursor value. The flow model this serves keys progress per (region, piece) and evaluates it pointwise, so after a repartition leaves two slices at different cursors the higher one replays its rows. Carry the region's own slices into the memtable read and resolve a row's piece once per batch (one batch is one series) against the decoded primary key, then keep the row only when its sequence is above that piece's cursor. A batch no slice selects, an unreadable key and a failed evaluation fall back to the least advanced cursor, and equal cursors skip the evaluation entirely, so a region with one cursor value delivers exactly what it delivered before. The bulk memtable still applies the region floor. Signed-off-by: discord9 --- src/mito2/src/engine/scan_test.rs | 81 ++++++ src/mito2/src/memtable.rs | 26 ++ .../src/memtable/simple_bulk_memtable.rs | 7 + src/mito2/src/memtable/time_series.rs | 147 ++++++++++- src/mito2/src/read.rs | 240 ++++++++++++++++-- src/mito2/src/read/scan_region.rs | 50 ++++ 6 files changed, 529 insertions(+), 22 deletions(-) diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 2c2cb18ba32..020149ae72c 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -6738,6 +6738,87 @@ async fn test_read_row_sequence_splits_one_file_by_the_expression_of_each_row() ); } +/// The same per-row rule for a **memtable** of this region: a memtable row is filtered by +/// the cursor of the piece its own tag values fall into, not by the single floor of the +/// region. +/// +/// The region's own pieces are the only candidates, because a memtable holds the rows this +/// region allocated. The rows of the piece consumed up to 5 (the rows at 3, 4 and 5) are +/// not delivered again, and the row at 6 of the piece consumed up to 2 still is. +#[tokio::test] +async fn test_read_row_sequence_splits_memtable_rows_by_the_expression_of_each_row() { + let mut env = + TestEnv::with_prefix("test_read_row_sequence_splits_memtable_rows_by_expression").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + // Five rows of the left expression (numbers 1..5) and one row of the right one + // (number 6), all of them in the memtable: no flush, so no file takes part in the read. + // The primary-key SST format keeps the time-series memtable (the flat format would put + // the rows in the bulk memtable, which does not apply the per-piece rule), and + // `preserve_row_sequence` keeps the exact `(C, H]` delta admissible. + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .insert_option("sst_format", "primary_key") + .build(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(region, RegionRequest::Create(request)) + .await + .unwrap(); + let mut rows = test_util::build_rows_for_key("1", 0, 5, 0); + rows.extend(test_util::build_rows_for_key("6", 5, 6, 0)); + test_util::put_rows(&engine, region, Rows { schema, rows }).await; + + // One cursor value for every piece: the delivered rows are exactly the rows above the + // region-level floor 2, which is what the read delivered before the per-row rule. + let mut rows = scan_flat_row_sequences( + &engine, + region, + creator_cursor_scan( + region, + vec![ + partition_str_slice_cursor("0", "5", 2), + partition_str_slice_cursor("5", "9", 2), + ], + 2, + 20, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(2000, 3), (3000, 4), (4000, 5), (5000, 6)], + rows, + "one cursor value for every piece is the region-level floor of the whole read" + ); + + // The pieces advanced differently: the rows of the left one (3, 4 and 5) are consumed, + // the row at 6 belongs to the right one and stays live. + let mut rows = scan_flat_row_sequences( + &engine, + region, + creator_cursor_scan( + region, + vec![ + partition_str_slice_cursor("0", "5", 5), + partition_str_slice_cursor("5", "9", 2), + ], + 2, + 20, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(5000, 6)], + rows, + "each memtable row is filtered by the cursor of the piece it belongs to: the rows at \ + 3, 4 and 5 were consumed by the piece advanced to 5, the row at 6 was not" + ); +} + /// A row whose number a substitution produced is hidden **and reported** by the substitution /// rule (`SubstitutedRowRanges`), so per-row slice selection must leave it to that rule /// instead of dropping it silently: its number says nothing about progress. diff --git a/src/mito2/src/memtable.rs b/src/mito2/src/memtable.rs index a63423cc92d..637e0d89007 100644 --- a/src/mito2/src/memtable.rs +++ b/src/mito2/src/memtable.rs @@ -28,6 +28,7 @@ use datatypes::arrow::record_batch::RecordBatch; use mito_codec::key_values::KeyValue; pub use mito_codec::key_values::KeyValues; use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec}; +use partition::expr::PartitionExpr; use snafu::ensure; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::{RegionMetadata, RegionMetadataRef}; @@ -106,6 +107,16 @@ pub struct RangesOptions { pub predicate: PredicateGroup, /// Sequence range to filter the data. pub sequence: Option, + /// The cursor of each piece a row of this memtable may belong to, as + /// `(partition expression, last consumed sequence)` pairs. + /// + /// When present, a row is delivered only when `seq > cursor(piece of the row)`: the + /// cursor of the piece replaces the single floor [`Self::sequence`] states, which is the + /// minimum of the pieces and therefore cannot tell a row of a more advanced piece from a + /// consumed one. The maximum of [`Self::sequence`] still bounds every row. + /// + /// `None` (or an empty vector) keeps the region-level floor as the whole rule. + pub creator_slices: Option>>, /// Maximum number of rows readers should produce in one batch. pub batch_size: usize, } @@ -117,6 +128,7 @@ impl Default for RangesOptions { pre_filter_mode: PreFilterMode::All, predicate: PredicateGroup::default(), sequence: None, + creator_slices: None, batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE, } } @@ -130,6 +142,7 @@ impl RangesOptions { pre_filter_mode: PreFilterMode::All, predicate: PredicateGroup::default(), sequence: None, + creator_slices: None, batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE, } } @@ -155,6 +168,19 @@ impl RangesOptions { self } + /// Sets the cursor of each piece a row may belong to. + /// + /// See [`Self::creator_slices`]: the cursor of the piece a row belongs to replaces the + /// single floor of [`Self::sequence`], the maximum of it still applies. + #[must_use] + pub fn with_creator_slices( + mut self, + creator_slices: Option>>, + ) -> Self { + self.creator_slices = creator_slices; + self + } + /// Sets the maximum number of rows readers should produce in one batch. #[must_use] pub fn with_batch_size(mut self, batch_size: usize) -> Self { diff --git a/src/mito2/src/memtable/simple_bulk_memtable.rs b/src/mito2/src/memtable/simple_bulk_memtable.rs index 89c22f5e69c..827b54fa3c2 100644 --- a/src/mito2/src/memtable/simple_bulk_memtable.rs +++ b/src/mito2/src/memtable/simple_bulk_memtable.rs @@ -226,6 +226,7 @@ impl Memtable for SimpleBulkMemtable { ) -> error::Result { let predicate = options.predicate; let sequence = options.sequence; + let creator_slices = options.creator_slices; let start_time = Instant::now(); let read_column_ids = read_column_ids_from_projection(&self.region_metadata, projection); let projection = Arc::new(self.build_projection(projection)); @@ -256,11 +257,17 @@ impl Memtable for SimpleBulkMemtable { let contexts = values .into_par_iter() .filter_map(|v| { + // This memtable holds one series for the whole region and keeps no + // primary key, so a row cannot be attributed to a piece: the per-piece + // filter falls back to the least advanced cursor of the set, which is the + // region-level floor. let filtered = match v.to_batch( &[], &self.region_metadata, &projection, sequence, + creator_slices.as_deref().map(Vec::as_slice), + None, self.dedup, self.merge_mode, ) { diff --git a/src/mito2/src/memtable/time_series.rs b/src/mito2/src/memtable/time_series.rs index 1fa6cb24b15..876c997b909 100644 --- a/src/mito2/src/memtable/time_series.rs +++ b/src/mito2/src/memtable/time_series.rs @@ -37,7 +37,8 @@ use datatypes::vectors::{ TimestampNanosecondVector, TimestampSecondVector, UInt8Vector, UInt64Vector, }; use mito_codec::key_values::KeyValue; -use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodecExt}; +use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodec, PrimaryKeyCodecExt}; +use partition::expr::PartitionExpr; use snafu::{OptionExt, ResultExt, ensure}; use store_api::metadata::RegionMetadataRef; use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; @@ -370,6 +371,7 @@ impl Memtable for TimeSeriesMemtable { ) -> Result { let predicate = options.predicate; let sequence = options.sequence; + let creator_slices = options.creator_slices; let read_column_ids = read_column_ids_from_projection(&self.region_metadata, projection); let projection = if let Some(projection) = projection { projection.iter().copied().collect() @@ -390,6 +392,7 @@ impl Memtable for TimeSeriesMemtable { dedup: self.dedup, merge_mode: self.merge_mode, sequence, + creator_slices, batch_to_record_batch, }); let context = Arc::new(MemtableRangeContext::new(self.id, builder, predicate)); @@ -546,6 +549,7 @@ impl SeriesSet { } /// Iterates all series in [SeriesSet]. + #[allow(clippy::too_many_arguments)] fn iter_series( &self, projection: HashSet, @@ -553,6 +557,7 @@ impl SeriesSet { dedup: bool, merge_mode: MergeMode, sequence: Option, + creator_slices: Option>>, mem_scan_metrics: Option, ) -> Result { let primary_key_schema = primary_key_schema(&self.region_metadata); @@ -573,6 +578,7 @@ impl SeriesSet { dedup, merge_mode, sequence, + creator_slices, mem_scan_metrics, ) } @@ -623,6 +629,9 @@ struct Iter { dedup: bool, merge_mode: MergeMode, sequence: Option, + /// The cursor of each piece a row may belong to, when this read states them + /// ([`RangesOptions::creator_slices`]). + creator_slices: Option>>, metrics: Metrics, mem_scan_metrics: Option, } @@ -640,6 +649,7 @@ impl Iter { dedup: bool, merge_mode: MergeMode, sequence: Option, + creator_slices: Option>>, mem_scan_metrics: Option, ) -> Result { let predicate = predicate @@ -669,6 +679,7 @@ impl Iter { dedup, merge_mode, sequence, + creator_slices, metrics: Metrics::default(), mem_scan_metrics, }) @@ -742,12 +753,15 @@ impl Iterator for Iter { self.last_key = Some(primary_key.clone()); let values = series.compact(&self.metadata); + let creator_slices = self.creator_slices.as_deref().map(Vec::as_slice); let batch = values.and_then(|v| { v.to_batch( primary_key, &self.metadata, &self.projection, self.sequence, + creator_slices, + Some(self.codec.as_ref()), self.dedup, self.merge_mode, ) @@ -1221,12 +1235,21 @@ pub struct Values { impl Values { /// Converts [Values] to `Batch`, applies the optional sequence filter, sorts the batch /// according to `timestamp, sequence` desc, and applies dedup/merge according to `merge_mode`. + /// + /// `creator_slices` is the cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`]): when present, a row is additionally kept only + /// when its sequence is above the cursor of the piece its tag values fall into, which + /// replaces the single floor `sequence` states. `codec` decodes the primary key the + /// piece is resolved from. + #[allow(clippy::too_many_arguments)] pub fn to_batch( &self, primary_key: &[u8], metadata: &RegionMetadataRef, projection: &HashSet, sequence: Option, + creator_slices: Option<&[(PartitionExpr, SequenceNumber)]>, + codec: Option<&dyn PrimaryKeyCodec>, dedup: bool, merge_mode: MergeMode, ) -> Result { @@ -1253,6 +1276,10 @@ impl Values { // - avoid dropping a timestamp when the newest row is out of range // - avoid filling null fields from rows that should be excluded by the sequence filter. batch.filter_by_sequence(sequence)?; + // The cursor of the piece this series belongs to replaces the single floor of + // `sequence`: the floor is the least advanced piece of the region, so it cannot tell + // a row of a more advanced piece from a consumed one. + batch.filter_by_creator_slices(creator_slices, metadata, codec)?; match (dedup, merge_mode) { // append-only, keep duplicate rows. @@ -1357,6 +1384,9 @@ struct TimeSeriesIterBuilder { predicate: PredicateGroup, dedup: bool, sequence: Option, + /// The cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`]). + creator_slices: Option>>, merge_mode: MergeMode, batch_to_record_batch: Arc, } @@ -1369,6 +1399,7 @@ impl IterBuilder for TimeSeriesIterBuilder { self.dedup, self.merge_mode, self.sequence, + self.creator_slices.clone(), metrics, )?; if self.merge_mode == MergeMode::LastNonNull { @@ -1611,6 +1642,8 @@ mod tests { &schema, &[0, 1, 2, 3, 4].into_iter().collect(), None, + None, + None, true, MergeMode::LastRow, ) @@ -1681,6 +1714,8 @@ mod tests { &schema, &projection, Some(SequenceRange::LtEq { max: 2 }), + None, + None, true, MergeMode::LastNonNull, ) @@ -1728,6 +1763,8 @@ mod tests { &schema, &projection, Some(SequenceRange::Gt { min: 1 }), + None, + None, true, MergeMode::LastNonNull, ) @@ -2001,6 +2038,113 @@ mod tests { assert_eq!((0..100i64).collect::>(), v0_all); } + /// A memtable row is filtered by the cursor of the piece it belongs to, never by the + /// single floor of the region: the floor is the least advanced piece, so it delivers the + /// rows a more advanced piece already consumed. + #[test] + fn test_memtable_filters_rows_by_creator_slice_cursor() { + use partition::expr::{Operand, col}; + + let schema = schema_for_test(); + let memtable = TimeSeriesMemtable::new(schema.clone(), 1, None, false, MergeMode::LastRow); + + let column_schema = schema + .column_metadatas + .iter() + .map(|c| api::v1::ColumnSchema { + column_name: c.column_schema.name.clone(), + datatype: ColumnDataTypeWrapper::try_from(c.column_schema.data_type.clone()) + .unwrap() + .datatype() as i32, + semantic_type: c.semantic_type as i32, + ..Default::default() + }) + .collect::>(); + // Writes one row per call with an explicit sequence, so the rows of one series can + // be numbered independently of the others. + let write_row = |k0: &str, ts: i64, sequence: u64| { + let mutation = Mutation { + op_type: 1, + sequence, + rows: Some(Rows { + schema: column_schema.clone(), + rows: vec![row(vec![ + ValueData::StringValue(k0.to_string()), + ValueData::I64Value(0), + ValueData::TimestampMillisecondValue(ts), + ValueData::I64Value(ts), + ValueData::F64Value(0.0), + ])], + }), + write_hint: None, + }; + let kvs = KeyValues::new(schema.as_ref(), mutation).unwrap(); + memtable.write(&kvs).unwrap(); + }; + + // `k0 < "m"` is the piece consumed up to 5, `k0 >= "m"` the one consumed up to 2. + write_row("a", 0, 3); + write_row("a", 1, 4); + write_row("z", 2, 6); + + let read = |slices: Vec<(partition::expr::PartitionExpr, SequenceNumber)>| { + let options = RangesOptions::default() + .with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 })) + .with_creator_slices(Some(Arc::new(slices))); + let mut iter = memtable.ranges(None, options).unwrap().build(None).unwrap(); + let mut rows = Vec::new(); + for batch in iter.by_ref() { + let batch = batch.unwrap(); + let timestamps = batch.timestamps().to_arrow_array(); + let timestamps = timestamps + .as_any() + .downcast_ref::() + .unwrap(); + for (idx, sequence) in batch.sequences().iter_data().enumerate() { + rows.push((timestamps.value(idx), sequence.unwrap())); + } + } + rows.sort_unstable(); + rows + }; + + let slice_lt = || col("k0").lt(Operand::Value(Value::String("m".into()))); + let slice_ge = || col("k0").gt_eq(Operand::Value(Value::String("m".into()))); + + // The region-level floor (2) keeps the rows at 3, 4 and 6, but the piece of the + // first two is consumed up to 5: only the row of the piece consumed up to 2 is + // delivered. + assert_eq!( + vec![(2, 6)], + read(vec![(slice_lt(), 5), (slice_ge(), 2)]), + "the rows at 3 and 4 belong to the piece consumed up to 5 and are not delivered \ + again, the row at 6 belongs to the piece consumed up to 2 and is" + ); + + // One cursor value for every piece is the region-level floor: the delivered rows are + // exactly the rows above the floor, whatever piece they belong to. + assert_eq!( + vec![(0, 3), (1, 4), (2, 6)], + read(vec![(slice_lt(), 2), (slice_ge(), 2)]), + "with one cursor value the rows are exactly the rows above the region floor" + ); + + // A series no candidate expression selects is bounded by the least advanced cursor + // of the set (2), not by the most advanced one (5), so its live row is not dropped. + assert_eq!( + vec![(0, 3), (1, 4), (2, 6)], + read(vec![ + (col("k0").lt(Operand::Value(Value::String("a".into()))), 5), + ( + col("k0").gt_eq(Operand::Value(Value::String("z".into()))), + 2 + ), + ]), + "a row no slice explains is attributed to the least advanced candidate, which \ + delivers every row above the region floor" + ); + } + #[test] fn test_memtable_concurrent_write_read() { common_telemetry::init_default_ut_logging(); @@ -2211,6 +2355,7 @@ mod tests { dedup, merge_mode, sequence, + creator_slices: None, batch_to_record_batch: adapter_context, } } diff --git a/src/mito2/src/read.rs b/src/mito2/src/read.rs index c1d70c66613..17d7abb3088 100644 --- a/src/mito2/src/read.rs +++ b/src/mito2/src/read.rs @@ -40,17 +40,21 @@ pub mod stream; pub(crate) mod substituted_rows; pub(crate) mod unordered_scan; -use std::collections::HashMap; +use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::time::Duration; use api::v1::OpType; use arrow_schema::SchemaRef; +use common_telemetry::debug; use common_time::Timestamp; +use datafusion::physical_plan::PhysicalExpr; use datafusion_common::arrow::array::UInt8Array; use datatypes::arrow; -use datatypes::arrow::array::{Array, ArrayRef}; +use datatypes::arrow::array::{Array, ArrayRef, BooleanArray}; use datatypes::arrow::compute::SortOptions; +use datatypes::arrow::datatypes::{Field, Schema}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::arrow::row::{RowConverter, SortField}; use datatypes::prelude::{ConcreteDataType, DataType, ScalarVector}; @@ -66,12 +70,14 @@ use datatypes::vectors::{ use futures::TryStreamExt; use futures::stream::BoxStream; use mito_codec::row_converter::{CompositeValues, DensePrimaryKeyCodec, PrimaryKeyCodec}; +use partition::expr::PartitionExpr; use snafu::{OptionExt, ResultExt, ensure}; +use store_api::metadata::RegionMetadataRef; use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; use crate::error::{ - ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, InvalidBatchSnafu, - Result, + ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, + EvalPartitionFilterSnafu, InvalidBatchSnafu, Result, }; use crate::memtable::BoxedRecordBatchIterator; @@ -144,6 +150,82 @@ struct DensePkCache { values: Vec>, } +/// Builds the one-row batch of tag values the primary key of a batch states, holding the +/// columns the candidate creator cursor slices reference. +/// +/// A time-series memtable batch is one series, so the tag values of the whole batch are the +/// values of that series and one row is enough to decide which piece it belongs to. The +/// values are extracted from the decoded primary key, which is how the memtable states its +/// tags. +/// +/// `None` means the piece cannot be decided: a referenced column is missing from the region +/// or is not part of its primary key, or a value does not convert to the column's type. The +/// caller then keeps the conservative floor of the whole set. +fn creator_slice_probe_batch( + metadata: &RegionMetadataRef, + slices: &[(PartitionExpr, SequenceNumber)], + pk_values: &CompositeValues, +) -> Option { + let mut referenced = HashSet::new(); + for (expr, _) in slices { + expr.collect_column_names(&mut referenced); + } + + let mut fields = Vec::with_capacity(referenced.len()); + let mut columns = Vec::with_capacity(referenced.len()); + for column_metadata in &metadata.column_metadatas { + let name = &column_metadata.column_schema.name; + if !referenced.remove(name) { + continue; + } + let column_id = column_metadata.column_id; + // Only a primary-key column carries a value the memtable batch states. + let pk_index = metadata.primary_key_index(column_id)?; + let value = match pk_values { + CompositeValues::Dense(values) => &values.get(pk_index)?.1, + CompositeValues::Sparse(values) => values.get_or_null(column_id), + }; + let data_type = &column_metadata.column_schema.data_type; + let scalar = value.try_to_scalar_value(data_type).ok()?; + let array = Helper::try_from_scalar_value(scalar, 1, Some(data_type)) + .ok()? + .to_arrow_array(); + fields.push(Field::new( + name, + data_type.as_arrow_type(), + column_metadata.column_schema.is_nullable(), + )); + columns.push(array); + } + if !referenced.is_empty() { + // A referenced column this region does not have cannot be evaluated. + return None; + } + + RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).ok() +} + +/// Evaluates a partition expression against the single row of a probe batch, treating a +/// null result as "not selected" (the same rule the region partition filter applies). +fn evaluate_partition_filter(filter: &dyn PhysicalExpr, probe: &RecordBatch) -> Result { + let columnar_value = filter.evaluate(probe).context(EvalPartitionFilterSnafu)?; + let array = columnar_value + .into_array(probe.num_rows()) + .context(EvalPartitionFilterSnafu)?; + let boolean = + array + .as_any() + .downcast_ref::() + .context(crate::error::UnexpectedSnafu { + reason: format!( + "a partition expression must evaluate to a boolean array, got {:?}", + array.data_type() + ), + })?; + + Ok(boolean.is_valid(0) && boolean.value(0)) +} + impl Batch { /// Creates a new batch. pub fn new( @@ -417,24 +499,140 @@ impl Batch { /// Filters rows by the given `sequence`. Only preserves rows with sequence less than or equal to `sequence`. pub fn filter_by_sequence(&mut self, sequence: Option) -> Result<()> { - let seq_range = match sequence { - None => return Ok(()), - Some(seq_range) => { - let (Some(first), Some(last)) = (self.first_sequence(), self.last_sequence()) - else { - return Ok(()); - }; - let is_subset = match seq_range { - SequenceRange::Gt { min } => min < first, - SequenceRange::LtEq { max } => max >= last, - SequenceRange::GtLtEq { min, max } => min < first && max >= last, - }; - if is_subset { - return Ok(()); - } - seq_range - } + match sequence { + None => Ok(()), + Some(seq_range) => self.filter_by_sequence_range(seq_range), + } + } + + /// Filters rows by the cursor of the piece each row belongs to. + /// + /// One [`Batch`] of a time-series memtable holds one series, so every row of it belongs + /// to the same piece and the piece is resolved once for the whole batch: the partition + /// expression of each candidate slice is evaluated against the batch's primary-key (tag) + /// values, and the rows are kept when their own sequence is above that slice's cursor. + /// This is the memtable counterpart of the per-row slice selection of a physical- + /// sequence read of an SST: a region whose pieces advanced independently delivers + /// neither a row a more advanced piece consumed again nor drops a row a less advanced + /// one still holds. + /// + /// A batch no candidate expression selects is filtered by the **least** advanced cursor + /// of the set, which is the floor of the whole region: re-reading a consumed row is + /// recoverable, dropping a live one is not. + /// + /// `None` or an empty set applies no filter, and a set whose cursors all carry one value + /// needs no evaluation at all — that value is the region's floor and the outcome is + /// exactly [`Self::filter_by_sequence`] with that floor. + pub fn filter_by_creator_slices( + &mut self, + slices: Option<&[(PartitionExpr, SequenceNumber)]>, + metadata: &RegionMetadataRef, + codec: Option<&dyn PrimaryKeyCodec>, + ) -> Result<()> { + let Some(slices) = slices.filter(|slices| !slices.is_empty()) else { + return Ok(()); }; + let Some(&(_, first)) = slices.first() else { + return Ok(()); + }; + // A single cursor value is the floor of the region: which piece a row belongs to + // cannot change the outcome, so the batch needs no evaluation. + let cursor = if slices.iter().all(|(_, seq)| *seq == first) { + first + } else { + self.creator_slice_cursor(slices, metadata, codec)? + }; + + self.filter_by_sequence_range(SequenceRange::Gt { min: cursor }) + } + + /// Returns the cursor of the piece the rows of `self` belong to, or the least advanced + /// cursor of `slices` when the piece cannot be resolved. + /// + /// The candidate expressions are the pieces a row may belong to; they are disjoint, so + /// at most one of them selects a series. If more than one does (a domain that was not + /// split cleanly), the least advanced cursor among them is used, which never drops a row + /// a conservatively bounded read would have delivered. + fn creator_slice_cursor( + &self, + slices: &[(PartitionExpr, SequenceNumber)], + metadata: &RegionMetadataRef, + codec: Option<&dyn PrimaryKeyCodec>, + ) -> Result { + // A row no slice explains is attributed to the least advanced candidate. + let fallback = slices + .iter() + .map(|(_, cursor)| *cursor) + .min() + .unwrap_or_default(); + let Some(codec) = codec else { + // Without a primary key the pieces cannot be told apart. + return Ok(fallback); + }; + let pk_values = match self.pk_values() { + Some(pk_values) => Cow::Borrowed(pk_values), + None => match codec.decode(self.primary_key()) { + Ok(pk_values) => Cow::Owned(pk_values), + Err(e) => { + debug!( + "Cannot decode the primary key of a batch to resolve its creator cursor slice, bounding it by {}: {}", + fallback, e + ); + return Ok(fallback); + } + }, + }; + let Some(probe) = creator_slice_probe_batch(metadata, slices, &pk_values) else { + return Ok(fallback); + }; + + let mut matched: Option = None; + for (expr, cursor) in slices { + let selected = match expr.try_as_physical_expr(&probe.schema()) { + Ok(filter) => match evaluate_partition_filter(filter.as_ref(), &probe) { + Ok(selected) => selected, + Err(e) => { + // Deciding a piece by guesswork would drop rows: keep the floor. + debug!( + "Cannot evaluate a creator cursor slice expression, bounding the batch by {}: {}", + fallback, e + ); + return Ok(fallback); + } + }, + Err(e) => { + debug!( + "Cannot plan a creator cursor slice expression, bounding the batch by {}: {}", + fallback, e + ); + return Ok(fallback); + } + }; + if selected { + // Disjoint expressions match at most once; a domain that was not split + // cleanly is bounded by its least advanced piece. + matched = + Some(matched.map_or(*cursor, |current: SequenceNumber| current.min(*cursor))); + } + } + + Ok(matched.unwrap_or(fallback)) + } + + /// Applies `seq_range` to the rows of the batch, skipping the mask when every row + /// already satisfies it. + fn filter_by_sequence_range(&mut self, seq_range: SequenceRange) -> Result<()> { + let (Some(first), Some(last)) = (self.first_sequence(), self.last_sequence()) else { + return Ok(()); + }; + let is_subset = match seq_range { + SequenceRange::Gt { min } => min < first, + SequenceRange::LtEq { max } => max >= last, + SequenceRange::GtLtEq { min, max } => min < first && max >= last, + }; + if is_subset { + return Ok(()); + } let seqs = self.sequences.as_arrow(); let predicate = seq_range.filter(seqs).context(ComputeArrowSnafu)?; diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 05733ec5fac..8711be9d3b2 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -572,6 +572,52 @@ impl ScanRegion { creators } + /// The cursor of each piece a memtable row of **this region** may belong to. + /// + /// A memtable holds the rows this region allocated, so the candidates are the region's + /// own slices: every one of them may hold a row, and no file metadata narrows the set the + /// way it does for the cursor slices of an SST. A row is then compared against the cursor + /// of the piece its tag values fall into instead of against the single floor of the + /// region, which is only the least advanced piece. + /// + /// `None` when there is no per-piece rule to state: the scan is not a physical-sequence + /// read, it may cross an invalid boundary (which applies no lower bound at all), the + /// region states one whole-domain cursor, or a stated expression cannot be read back. + /// The region-level floor then stays the whole rule. + fn memtable_creator_slices(&self) -> Option>> { + if !self.request.read_row_sequence || self.request.read_across_invalid_boundary { + return None; + } + let shards = self + .request + .creator_cursor_shards + .as_ref()? + .get(&self.region_id().as_u64())?; + let mut slices = Vec::with_capacity(shards.len()); + for shard in shards { + let Some(identity) = shard.partition_expr.as_deref() else { + // A whole-domain cursor applies to every row of the region: the + // region-level floor is the exact rule and no evaluation is needed. + return None; + }; + let Ok(Some(expr)) = PartitionExpr::from_json_str(identity) else { + // An identity this build cannot read back cannot decide a row's piece; + // approximating it would be guesswork, so keep the conservative floor. + debug!( + "Cannot read back creator cursor slice expression {}; keeping the region-level floor", + identity + ); + return None; + }; + slices.push((expr, shard.seq)); + } + if slices.is_empty() { + return None; + } + + Some(Arc::new(slices)) + } + /// Creates a scan input. #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))] async fn scan_input(mut self) -> Result { @@ -651,6 +697,9 @@ impl ScanRegion { } else { self.request.memtable_min_sequence }; + // The per-piece cursors of this region's own slices: they replace the single floor + // `memtable_min_sequence` states (the least advanced piece) while the maximum stays. + let memtable_creator_slices = self.memtable_creator_slices(); for m in memtables { // check if memtable is empty by reading stats. @@ -670,6 +719,7 @@ impl ScanRegion { memtable_min_sequence, self.request.memtable_max_sequence, )) + .with_creator_slices(memtable_creator_slices.clone()) .with_pre_filter_mode(filter_mode), )?; mem_range_builders.extend(ranges_in_memtable.ranges.into_values().map(|v| {