diff --git a/src/mito2/src/memtable.rs b/src/mito2/src/memtable.rs index 637e0d89007..104fb98a457 100644 --- a/src/mito2/src/memtable.rs +++ b/src/mito2/src/memtable.rs @@ -96,6 +96,16 @@ pub(crate) fn group_by_sequence( /// Should be unique under the same region. pub type MemtableId = u32; +/// The cursor of one piece a memtable row may belong to, as +/// [`RangesOptions::creator_slices`] takes it: the partition expression selecting the piece, +/// the last sequence consumed inside it, and — when the producer states one — the last +/// sequence the delta of the piece covers. +pub type CreatorSliceCursor = (PartitionExpr, SequenceNumber, Option); + +/// The cursor of each piece a memtable row may belong to +/// ([`RangesOptions::creator_slices`]). +pub type CreatorSliceCursors = Arc>; + /// Options for querying ranges from a memtable. #[derive(Clone)] pub struct RangesOptions { @@ -108,15 +118,19 @@ pub struct RangesOptions { /// 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. + /// [`CreatorSliceCursor`] triples: `(partition expression, last consumed sequence, last + /// sequence the piece's delta covers)`. /// - /// 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. + /// When present, a row is delivered only when its own sequence is above the cursor of + /// the piece it belongs to: 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 piece's `until` narrows + /// the upper end [`Self::sequence`] states, so a row numbered above the piece's delta is + /// not delivered by a read of this one; a piece that states no `until` keeps that end + /// alone. /// /// `None` (or an empty vector) keeps the region-level floor as the whole rule. - pub creator_slices: Option>>, + pub creator_slices: Option, /// Maximum number of rows readers should produce in one batch. pub batch_size: usize, } @@ -171,12 +185,10 @@ impl RangesOptions { /// 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. + /// single floor of [`Self::sequence`], and the `until` of that piece narrows the upper + /// end of it. #[must_use] - pub fn with_creator_slices( - mut self, - creator_slices: Option>>, - ) -> Self { + pub fn with_creator_slices(mut self, creator_slices: Option) -> Self { self.creator_slices = creator_slices; self } @@ -189,6 +201,55 @@ impl RangesOptions { } } +/// Returns the inclusive upper end `range` states, when it states one. +pub(crate) fn sequence_range_upper(range: Option<&SequenceRange>) -> Option { + match range { + Some(SequenceRange::LtEq { max } | SequenceRange::GtLtEq { max, .. }) => Some(*max), + _ => None, + } +} + +/// The sequence range the rows of one creator cursor slice are read with: above the slice's +/// cursor and at or below `min(read_fence, until)`. +/// +/// `until` is the last sequence the slice's delta covers ([`CreatorSliceCursor`]); +/// `read_fence` is the upper end the read's own sequence range states. The slice's bound +/// narrows the fence and never widens it — the fence is what the snapshot allows — while a +/// slice that states no bound keeps the fence alone, exactly as before the bound existed. +pub(crate) fn creator_slice_sequence_range( + cursor: SequenceNumber, + until: Option, + read_fence: Option, +) -> SequenceRange { + match (read_fence, until) { + (Some(fence), Some(until)) => SequenceRange::GtLtEq { + min: cursor, + max: fence.min(until), + }, + (Some(fence), None) => SequenceRange::GtLtEq { + min: cursor, + max: fence, + }, + (None, Some(until)) => SequenceRange::GtLtEq { + min: cursor, + max: until, + }, + (None, None) => SequenceRange::Gt { min: cursor }, + } +} + +/// The **least** inclusive upper bound a set of candidate slices states, or `None` when none +/// of them states one. +/// +/// A slice that states no bound is unbounded above and never narrows the set; a row whose +/// piece is one of several candidates is bounded by the least bound among them, the only +/// bound every candidate proves. +pub(crate) fn least_slice_until<'a>( + untils: impl Iterator>, +) -> Option { + untils.filter_map(|until| *until).min() +} + #[derive(Debug, Default, Clone)] pub struct MemtableStats { /// The estimated bytes allocated by this memtable from heap. diff --git a/src/mito2/src/memtable/bulk.rs b/src/mito2/src/memtable/bulk.rs index 0c1478c428c..44f1bd5ddfc 100644 --- a/src/mito2/src/memtable/bulk.rs +++ b/src/mito2/src/memtable/bulk.rs @@ -36,7 +36,6 @@ fn env_usize(name: &str, default: usize) -> usize { use common_time::Timestamp; use datatypes::arrow::datatypes::SchemaRef; use mito_codec::key_values::KeyValue; -use partition::expr::PartitionExpr; use rayon::prelude::*; use serde::{Deserialize, Serialize}; use serde_with::{DisplayFromStr, serde_as}; @@ -59,10 +58,10 @@ use crate::memtable::bulk::part::{ use crate::memtable::bulk::part_reader::BulkPartBatchIter; use crate::memtable::stats::WriteMetrics; use crate::memtable::{ - AllocTracker, BoxedBatchIterator, BoxedRecordBatchIterator, EncodedBulkPart, EncodedRange, - IterBuilder, KeyValues, MemScanMetrics, Memtable, MemtableBuilder, MemtableId, MemtableRange, - MemtableRangeContext, MemtableRanges, MemtableRef, MemtableStats, RangesOptions, - group_by_sequence, + AllocTracker, BoxedBatchIterator, BoxedRecordBatchIterator, CreatorSliceCursors, + EncodedBulkPart, EncodedRange, IterBuilder, KeyValues, MemScanMetrics, Memtable, + MemtableBuilder, MemtableId, MemtableRange, MemtableRangeContext, MemtableRanges, MemtableRef, + MemtableStats, RangesOptions, group_by_sequence, }; use crate::read::flat_dedup::{FlatDedupIterator, FlatLastNonNull, FlatLastRow}; use crate::read::flat_merge::FlatMergeIterator; @@ -909,7 +908,7 @@ pub struct BulkRangeIterBuilder { pub context: Arc, pub sequence: Option, /// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]). - pub creator_slices: Option>>, + pub creator_slices: Option, } /// Iterator builder for multi bulk range @@ -918,7 +917,7 @@ struct MultiBulkRangeIterBuilder { context: Arc, sequence: Option, /// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]). - creator_slices: Option>>, + creator_slices: Option, } impl IterBuilder for BulkRangeIterBuilder { @@ -1010,7 +1009,7 @@ struct EncodedBulkRangeIterBuilder { context: Arc, sequence: Option, /// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]). - creator_slices: Option>>, + creator_slices: Option, } impl IterBuilder for EncodedBulkRangeIterBuilder { diff --git a/src/mito2/src/memtable/bulk/part.rs b/src/mito2/src/memtable/bulk/part.rs index 587f8168d18..483050ad80d 100644 --- a/src/mito2/src/memtable/bulk/part.rs +++ b/src/mito2/src/memtable/bulk/part.rs @@ -51,7 +51,6 @@ use parquet::arrow::ArrowWriter; use parquet::basic::{Compression, ZstdLevel}; use parquet::file::metadata::ParquetMetaData; use parquet::file::properties::WriterProperties; -use partition::expr::PartitionExpr; use smallvec::SmallVec; use snafu::{OptionExt, ResultExt, ensure}; use store_api::codec::PrimaryKeyEncoding; @@ -69,7 +68,9 @@ use crate::error::{ use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef}; use crate::memtable::bulk::part_reader::EncodedBulkPartIter; use crate::memtable::time_series::{ValueBuilder, Values}; -use crate::memtable::{BoxedRecordBatchIterator, MemScanMetrics, MemtableStats}; +use crate::memtable::{ + BoxedRecordBatchIterator, CreatorSliceCursors, MemScanMetrics, MemtableStats, +}; use crate::sst::SeriesEstimator; use crate::sst::index::IndexOutput; use crate::sst::parquet::flat_format::primary_key_column_index; @@ -1344,7 +1345,7 @@ impl EncodedBulkPart { &self, context: BulkIterContextRef, sequence: Option, - creator_slices: Option>>, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result> { // Compute skip_fields for row group pruning from the configured pre-filter mode. @@ -1921,7 +1922,7 @@ impl MultiBulkPart { &self, context: BulkIterContextRef, sequence: Option, - creator_slices: Option>>, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result> { if self.batches.is_empty() { diff --git a/src/mito2/src/memtable/bulk/part_reader.rs b/src/mito2/src/memtable/bulk/part_reader.rs index d14c33dae0b..0428d3e8973 100644 --- a/src/mito2/src/memtable/bulk/part_reader.rs +++ b/src/mito2/src/memtable/bulk/part_reader.rs @@ -26,7 +26,6 @@ use datatypes::data_type::DataType; use mito_codec::row_converter::PrimaryKeyFilter; use parquet::arrow::ProjectionMask; use parquet::arrow::arrow_reader::ParquetRecordBatchReader; -use partition::expr::PartitionExpr; use snafu::ResultExt; use store_api::codec::PrimaryKeyEncoding; use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; @@ -38,7 +37,10 @@ use crate::error::{ use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef}; use crate::memtable::bulk::part::EncodedBulkPart; use crate::memtable::bulk::row_group_reader::MemtableRowGroupReaderBuilder; -use crate::memtable::{MemScanMetrics, MemScanMetricsData}; +use crate::memtable::{ + CreatorSliceCursor, CreatorSliceCursors, MemScanMetrics, MemScanMetricsData, + creator_slice_sequence_range, least_slice_until, sequence_range_upper, +}; use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED}; use crate::sst::parquet::file_range::TagDecodeState; use crate::sst::parquet::flat_format::{ @@ -57,7 +59,7 @@ pub struct EncodedBulkPartIter { sequence: Option, /// Cursor of each piece a row of this part may belong to /// ([`crate::memtable::RangesOptions::creator_slices`]). - creator_slices: Option>>, + creator_slices: Option, /// Cached skip_fields for current row group. current_skip_fields: bool, /// Primary key filter for prefiltering before convert_batch. @@ -127,10 +129,7 @@ impl EncodedBulkPartIter { } /// Sets the cursor of each piece a row of this part may belong to. - pub fn with_creator_slices( - mut self, - creator_slices: Option>>, - ) -> Self { + pub fn with_creator_slices(mut self, creator_slices: Option) -> Self { self.creator_slices = creator_slices; self } @@ -253,7 +252,7 @@ pub struct BulkPartBatchIter { sequence: Option, /// Cursor of each piece a row of this part may belong to /// ([`crate::memtable::RangesOptions::creator_slices`]). - creator_slices: Option>>, + creator_slices: Option, /// Primary key filter for prefiltering before convert_batch. pk_filter: Option, /// Metrics for this iterator. @@ -305,10 +304,7 @@ impl BulkPartBatchIter { } /// Sets the cursor of each piece a row of this part may belong to. - pub fn with_creator_slices( - mut self, - creator_slices: Option>>, - ) -> Self { + pub fn with_creator_slices(mut self, creator_slices: Option) -> Self { self.creator_slices = creator_slices; self } @@ -421,15 +417,16 @@ impl Drop for BulkPartBatchIter { /// /// `sequence` bounds every row by the region-level sequence range and /// `creator_slices` bounds each row by the cursor of the piece it belongs to -/// (`RangesOptions::creator_slices`); the two are combined so the per-piece rule only -/// replaces the lower floor of the region-level range. +/// (`RangesOptions::creator_slices`); the two are combined so the per-piece rule replaces the +/// lower floor of the region-level range and narrows its upper end by the bound the piece +/// states. /// /// # Panics /// Panics if the format is not flat. fn apply_combined_filters( context: &BulkIterContext, sequence: &Option, - creator_slices: Option<&[(PartitionExpr, SequenceNumber)]>, + creator_slices: Option<&[CreatorSliceCursor]>, record_batch: RecordBatch, skip_fields: bool, pk_filter: Option<&mut dyn PrimaryKeyFilter>, @@ -488,8 +485,12 @@ fn apply_combined_filters( combined_filter = Some(and_mask(combined_filter, sequence_filter)?); } - // Filters rows by the cursor of the piece each row belongs to. - if let Some(creator_mask) = creator_slice_mask(context, creator_slices, &record_batch)? { + // Filters rows by the cursor of the piece each row belongs to. A piece that states an + // upper bound narrows the read's fence, which is the upper end `sequence` states. + let read_fence = sequence_range_upper(sequence.as_ref()); + if let Some(creator_mask) = + creator_slice_mask(context, creator_slices, read_fence, &record_batch)? + { combined_filter = Some(and_mask(combined_filter, creator_mask)?); } @@ -528,46 +529,56 @@ fn and_mask(current: Option, next: BooleanArray) -> error::Result< /// A bulk part keeps the tag columns and the physical sequence of every row as real /// columns, so the piece a row belongs to is resolved per row: the candidate partition /// expressions are evaluated over the whole batch, and a row is kept only when its own -/// `__sequence` is above the cursor of the candidate that selects it. This is the bulk -/// memtable counterpart of the per-row slice selection a physical-sequence read of an SST -/// applies (`FileRangeContext::evaluate_creator_slices`). +/// `__sequence` is above the cursor of the candidate that selects it and at or below +/// `min(read_fence, until)` of that candidate — `read_fence` being the upper end the read's +/// own sequence range states and `until` the last sequence the piece's delta covers. This is +/// the bulk memtable counterpart of the per-row slice selection a physical-sequence read of an +/// SST applies (`FileRangeContext::evaluate_creator_slices`). /// /// A row whose piece cannot be decided is answered by [`unresolved_creator_slices`]: the /// least advanced cursor is exact while every candidate carries it, and the read fails /// otherwise. That covers a row no candidate selects and an expression that cannot be -/// resolved, planned or evaluated. When several candidates select one row the least advanced -/// of them decides. +/// resolved, planned or evaluated. When several candidates select one row, the least advanced +/// of their cursors and the least of the bounds they state decide: the row is kept when it is +/// above one of them and below all of them. /// /// `None` or an empty set applies no filter, and so does a set whose cursors all carry one -/// value: that value is the region-level floor the read already states. +/// value and state no bound: that value is the region-level floor the read already states. fn creator_slice_mask( context: &BulkIterContext, - slices: Option<&[(PartitionExpr, SequenceNumber)]>, + slices: Option<&[CreatorSliceCursor]>, + read_fence: Option, record_batch: &RecordBatch, ) -> error::Result> { let Some(slices) = slices.filter(|slices| !slices.is_empty()) else { return Ok(None); }; - let Some(&(_, first)) = slices.first() else { - return Ok(None); - }; - // 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. - if slices.iter().all(|(_, cursor)| *cursor == first) { - return Ok(None); - } + let sequence_column = record_batch.column(sequence_column_index(record_batch.num_columns())); - // A row no slice explains is attributed to the least advanced candidate. + // A row no slice explains is attributed to the least advanced candidate, bounded by the + // least bound the candidates state: the only bound every one of them proves. let fallback = slices .iter() - .map(|(_, cursor)| *cursor) + .map(|(_, cursor, _)| *cursor) .min() .unwrap_or_default(); - let sequence_column = record_batch.column(sequence_column_index(record_batch.num_columns())); - let fallback_mask = SequenceRange::Gt { min: fallback } + let fallback_until = least_slice_until(slices.iter().map(|(_, _, until)| until)); + let fallback_mask = creator_slice_sequence_range(fallback, fallback_until, read_fence) .filter(sequence_column) .context(ComputeArrowSnafu)?; + // One cursor value for every piece is the floor of the region: which piece a row belongs + // to cannot change the outcome, so the batch needs no evaluation. A stated bound still + // narrows every row alike, and the fallback mask above is exactly that rule. + if slices.iter().all(|(_, cursor, _)| *cursor == fallback) { + // Without a stated bound the read's own range is the whole rule, as it always was. + return if fallback_until.is_none() { + Ok(None) + } else { + Ok(Some(fallback_mask)) + }; + } + // Per row, the candidate slice whose expression holds. let selected = match creator_slice_selection(context, slices, record_batch) { Ok(selected) => selected, @@ -582,14 +593,26 @@ fn creator_slice_mask( ); } }; - // Per candidate, the rows whose own sequence is above its cursor. + // Per candidate, the rows whose own sequence is above its cursor, and the rows at or below + // the bound it states (`None` = unbounded above, so the read's fence is the only end). let mut not_consumed = Vec::with_capacity(slices.len()); - for (_, cursor) in slices { + let mut within_bound = Vec::with_capacity(slices.len()); + for (_, cursor, until) in slices { not_consumed.push( SequenceRange::Gt { min: *cursor } .filter(sequence_column) .context(ComputeArrowSnafu)?, ); + let bound = until.map(|until| read_fence.map_or(until, |fence| fence.min(until))); + within_bound.push( + bound + .map(|max| { + SequenceRange::LtEq { max } + .filter(sequence_column) + .context(ComputeArrowSnafu) + }) + .transpose()?, + ); } let num_rows = record_batch.num_rows(); @@ -598,15 +621,21 @@ fn creator_slice_mask( for row in 0..num_rows { let mut matched = false; let mut keep = false; + let mut within = true; // The slices are disjoint, so at most one expression selects a row. If more than one // does (a domain that was not split cleanly), any candidate above its cursor keeps - // the row, which is the least advanced cursor among them. + // the row — the least advanced cursor among them — while every one of them must + // still cover the row with the bound it states. for (index, mask) in selected.iter().enumerate() { if mask.value(row) { matched = true; keep |= not_consumed[index].value(row); + if let Some(bound) = &within_bound[index] { + within &= bound.value(row); + } } } + keep &= within; if !matched { unmatched += 1; keep = fallback_mask.value(row); @@ -646,16 +675,16 @@ fn creator_slice_mask( /// cannot resolve. fn unresolved_creator_slices( context: &BulkIterContext, - slices: &[(PartitionExpr, SequenceNumber)], + slices: &[CreatorSliceCursor], fallback_mask: BooleanArray, detail: &str, ) -> error::Result> { - let Some(min) = slices.iter().map(|(_, cursor)| *cursor).min() else { + let Some(min) = slices.iter().map(|(_, cursor, _)| *cursor).min() else { return Ok(Some(fallback_mask)); }; let max = slices .iter() - .map(|(_, cursor)| *cursor) + .map(|(_, cursor, _)| *cursor) .max() .unwrap_or(min); if min == max { @@ -686,12 +715,12 @@ fn unresolved_creator_slices( /// when an expression cannot be planned or evaluated. fn creator_slice_selection( context: &BulkIterContext, - slices: &[(PartitionExpr, SequenceNumber)], + slices: &[CreatorSliceCursor], record_batch: &RecordBatch, ) -> error::Result> { let metadata = context.read_format().metadata(); let mut referenced = HashSet::new(); - for (expr, _) in slices { + for (expr, ..) in slices { expr.collect_column_names(&mut referenced); } @@ -731,7 +760,7 @@ fn creator_slice_selection( let probe = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).context(ComputeArrowSnafu)?; let mut selected = Vec::with_capacity(slices.len()); - for (expr, _) in slices { + for (expr, ..) in slices { let filter = expr .try_as_physical_expr(probe.schema_ref()) .context(SerializePartitionExprSnafu)?; @@ -1220,10 +1249,12 @@ mod tests { ( partition::expr::col("field1").gt_eq(Operand::Value(Value::Int64(0))), left, + None, ), ( partition::expr::col("field1").lt(Operand::Value(Value::Int64(0))), right, + None, ), ]; Some(Arc::new(slices)) @@ -1273,4 +1304,144 @@ mod tests { "one cursor value for every piece keeps the part-level floor of the whole region" ); } + + /// A row numbered above the upper bound of its own slice belongs to a later delta: the + /// bulk part resolves the piece of every row from its tag columns and narrows the read's + /// fence by the bound that piece states, so the row is not delivered. A slice that states + /// no bound keeps the fence alone, exactly as before the bound existed. + #[test] + fn test_bulk_part_does_not_deliver_rows_above_the_creator_slice_upper_bound() { + use datatypes::value::Value; + use partition::expr::Operand; + + let schema = Arc::new(Schema::new(vec![ + Field::new("key1", DataType::Utf8, false), + Field::new("field1", DataType::Int64, false), + Field::new( + "timestamp", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Millisecond, None), + false, + ), + Field::new( + "__primary_key", + DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)), + false, + ), + Field::new("__sequence", DataType::UInt64, false), + Field::new("__op_type", DataType::UInt8, false), + ])); + + // Two series, numbered 3, 4 and 6 for the first and 7 for the second. + let keys = ["a", "a", "a", "z"]; + let key1 = Arc::new(StringArray::from_iter_values(keys)); + let field1 = Arc::new(Int64Array::from(vec![0, 0, 0, 0])); + let timestamp = Arc::new(datatypes::arrow::array::TimestampMillisecondArray::from( + vec![0, 1000, 2000, 3000], + )); + let values = Arc::new(BinaryArray::from_iter_values( + keys.iter().map(|key| new_primary_key(&[*key])), + )); + let primary_key = Arc::new(DictionaryArray::new( + UInt32Array::from(vec![0, 0, 0, 1]), + values, + )); + let sequence = Arc::new(UInt64Array::from(vec![3, 4, 6, 7])); + let op_type = Arc::new(UInt8Array::from(vec![1, 1, 1, 1])); + let record_batch = RecordBatch::try_new( + schema, + vec![key1, field1, timestamp, primary_key, sequence, op_type], + ) + .unwrap(); + + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "key1", + ConcreteDataType::string_datatype(), + false, + ), + semantic_type: SemanticType::Tag, + column_id: 0, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "field1", + ConcreteDataType::int64_datatype(), + false, + ), + semantic_type: SemanticType::Field, + column_id: 1, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "timestamp", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 2, + }) + .primary_key(vec![0]); + + let context = Arc::new( + BulkIterContext::new(Arc::new(builder.build().unwrap()), None, None, false, 1).unwrap(), + ); + // The read's own fence is 10: it admits every row of the part, so only the per-piece + // rule can hold the row at 7 back. + let sequence_filter = Some(SequenceRange::GtLtEq { min: 4, max: 10 }); + let slice_lt = + || partition::expr::col("key1").lt(Operand::Value(Value::String("m".into()))); + let slice_ge = + || partition::expr::col("key1").gt_eq(Operand::Value(Value::String("m".into()))); + let read = |slices: Vec<( + partition::expr::PartitionExpr, + SequenceNumber, + Option, + )>| { + let iter = BulkPartBatchIter::from_single( + record_batch.clone(), + context.clone(), + sequence_filter, + 0, + None, + ) + .with_creator_slices(Some(Arc::new(slices))); + let batches: Vec<_> = iter.map(|rb| rb.unwrap()).collect(); + let mut sequences = Vec::new(); + for batch in batches { + let column = batch + .column(batch.num_columns() - 2) + .as_any() + .downcast_ref::() + .unwrap(); + sequences.extend_from_slice(column.values()); + } + sequences + }; + + // Both slices state the same delta end, 6. The row at 6 belongs to the piece consumed + // up to 4 and is owed; the row at 7 belongs to the other piece, whose bound it is + // above, so it is left to the delta that covers it. + assert_eq!( + vec![6], + read(vec![(slice_lt(), 4, Some(6)), (slice_ge(), 5, Some(6)),]), + "a row above its piece's upper bound is not part of this delta" + ); + + // Without a stated bound the fence is the whole rule, as it always was: the row at 7 + // is above the cursor of its piece (5) and at or below the fence, so it is delivered. + assert_eq!( + vec![6, 7], + read(vec![(slice_lt(), 4, None), (slice_ge(), 5, None)]), + "without a bound every row above the piece's cursor is still owed" + ); + + // A bound at or above the fence changes nothing: the fence is the tighter end. + assert_eq!( + vec![6, 7], + read(vec![(slice_lt(), 4, Some(10)), (slice_ge(), 5, Some(10)),]), + "the bound narrows the fence, it never widens it" + ); + } } diff --git a/src/mito2/src/memtable/time_series.rs b/src/mito2/src/memtable/time_series.rs index 3a9d4934aaa..8bf748601bf 100644 --- a/src/mito2/src/memtable/time_series.rs +++ b/src/mito2/src/memtable/time_series.rs @@ -38,7 +38,6 @@ use datatypes::vectors::{ }; use mito_codec::key_values::KeyValue; 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}; @@ -54,9 +53,9 @@ use crate::memtable::simple_bulk_memtable::SimpleBulkMemtable; use crate::memtable::stats::WriteMetrics; use crate::memtable::{ AllocTracker, BatchToRecordBatchContext, BoxedBatchIterator, BoxedRecordBatchIterator, - IterBuilder, KeyValues, MemScanMetrics, Memtable, MemtableBuilder, MemtableId, MemtableRange, - MemtableRangeContext, MemtableRanges, MemtableRef, MemtableStats, RangesOptions, - read_column_ids_from_projection, + CreatorSliceCursor, CreatorSliceCursors, IterBuilder, KeyValues, MemScanMetrics, Memtable, + MemtableBuilder, MemtableId, MemtableRange, MemtableRangeContext, MemtableRanges, MemtableRef, + MemtableStats, RangesOptions, read_column_ids_from_projection, sequence_range_upper, }; use crate::metrics::{ MEMTABLE_ACTIVE_FIELD_BUILDER_COUNT, MEMTABLE_ACTIVE_SERIES_COUNT, READ_ROWS_TOTAL, @@ -557,7 +556,7 @@ impl SeriesSet { dedup: bool, merge_mode: MergeMode, sequence: Option, - creator_slices: Option>>, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result { let primary_key_schema = primary_key_schema(&self.region_metadata); @@ -631,7 +630,7 @@ struct Iter { sequence: Option, /// The cursor of each piece a row may belong to, when this read states them /// ([`RangesOptions::creator_slices`]). - creator_slices: Option>>, + creator_slices: Option, metrics: Metrics, mem_scan_metrics: Option, } @@ -649,7 +648,7 @@ impl Iter { dedup: bool, merge_mode: MergeMode, sequence: Option, - creator_slices: Option>>, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result { let predicate = predicate @@ -1248,7 +1247,7 @@ impl Values { metadata: &RegionMetadataRef, projection: &HashSet, sequence: Option, - creator_slices: Option<&[(PartitionExpr, SequenceNumber)]>, + creator_slices: Option<&[CreatorSliceCursor]>, codec: Option<&dyn PrimaryKeyCodec>, dedup: bool, merge_mode: MergeMode, @@ -1278,8 +1277,10 @@ impl Values { 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)?; + // a row of a more advanced piece from a consumed one. The piece's own upper bound + // narrows the read's fence, which is the upper end `sequence` states. + let read_fence = sequence_range_upper(sequence.as_ref()); + batch.filter_by_creator_slices(creator_slices, read_fence, metadata, codec)?; match (dedup, merge_mode) { // append-only, keep duplicate rows. @@ -1386,7 +1387,7 @@ struct TimeSeriesIterBuilder { sequence: Option, /// The cursor of each piece a row may belong to /// ([`RangesOptions::creator_slices`]). - creator_slices: Option>>, + creator_slices: Option, merge_mode: MergeMode, batch_to_record_batch: Arc, } @@ -2087,7 +2088,11 @@ mod tests { write_row("a", 1, 4); write_row("z", 2, 6); - let read = |slices: Vec<(partition::expr::PartitionExpr, SequenceNumber)>| { + let read = |slices: Vec<( + partition::expr::PartitionExpr, + SequenceNumber, + Option, + )>| { let options = RangesOptions::default() .with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 })) .with_creator_slices(Some(Arc::new(slices))); @@ -2116,7 +2121,7 @@ mod tests { // delivered. assert_eq!( vec![(2, 6)], - read(vec![(slice_lt(), 5), (slice_ge(), 2)]), + read(vec![(slice_lt(), 5, None), (slice_ge(), 2, None)]), "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" ); @@ -2125,7 +2130,7 @@ mod tests { // 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)]), + read(vec![(slice_lt(), 2, None), (slice_ge(), 2, None)]), "with one cursor value the rows are exactly the rows above the region floor" ); @@ -2135,10 +2140,15 @@ mod tests { let options = RangesOptions::default() .with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 })) .with_creator_slices(Some(Arc::new(vec![ - (col("k0").lt(Operand::Value(Value::String("a".into()))), 5), + ( + col("k0").lt(Operand::Value(Value::String("a".into()))), + 5, + None, + ), ( col("k0").gt_eq(Operand::Value(Value::String("z".into()))), 2, + None, ), ]))); let mut iter = memtable.ranges(None, options).unwrap().build(None).unwrap(); @@ -2204,8 +2214,8 @@ mod tests { // Two candidate pieces over a column the batch states no value for. let slices = |left: u64, right: u64| { vec![ - (col("v0").gt_eq(Operand::Value(Value::Int64(0))), left), - (col("v0").lt(Operand::Value(Value::Int64(0))), right), + (col("v0").gt_eq(Operand::Value(Value::Int64(0))), left, None), + (col("v0").lt(Operand::Value(Value::Int64(0))), right, None), ] }; let options = |pieces| { @@ -2264,6 +2274,116 @@ mod tests { ); } + /// A row numbered above the upper bound of its own slice belongs to a later delta: the + /// piece's bound narrows the read's fence, so the memtable does not deliver it. A slice + /// that states no bound keeps the fence alone, exactly as before the bound existed. + #[test] + fn test_memtable_does_not_deliver_rows_above_the_creator_slice_upper_bound() { + 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::>(); + 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 4, `k0 >= "m"` the one consumed up to 5. + write_row("a", 0, 3); + write_row("a", 1, 4); + write_row("a", 2, 6); + write_row("z", 3, 7); + + 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()))); + let read = |slices: Vec<( + partition::expr::PartitionExpr, + SequenceNumber, + Option, + )>| { + // The read's own fence is 10: it admits every row of the memtable, so only the + // per-piece rule can hold the row at 7 back. + let options = RangesOptions::default() + .with_sequence(Some(SequenceRange::GtLtEq { min: 4, max: 10 })) + .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 + }; + + // Both slices state the same delta end, 6. The row at 6 belongs to the piece consumed + // up to 4 and is owed; the row at 7 belongs to the other piece, whose bound it is + // above, so it is left to the delta that covers it. + assert_eq!( + vec![(2, 6)], + read(vec![(slice_lt(), 4, Some(6)), (slice_ge(), 5, Some(6)),]), + "a row above its piece's upper bound is not part of this delta" + ); + + // The same rows with the bounds the defect report states: a piece already consumed up + // to 9 whose delta ends at 6 still cannot deliver the row at 7. + assert_eq!( + vec![(2, 6)], + read(vec![(slice_lt(), 4, Some(6)), (slice_ge(), 9, Some(6)),]), + "a bound below the piece's cursor states no window at all, and delivers nothing" + ); + + // Without a stated bound the fence is the whole rule, as it always was: the row at 7 + // is above the cursor of its piece (5) and at or below the fence, so it is delivered. + assert_eq!( + vec![(2, 6), (3, 7)], + read(vec![(slice_lt(), 4, None), (slice_ge(), 5, None)]), + "without a bound every row above the piece's cursor is still owed" + ); + + // A bound at or above the fence changes nothing: the fence is the tighter end. + assert_eq!( + vec![(2, 6), (3, 7)], + read(vec![(slice_lt(), 4, Some(10)), (slice_ge(), 5, Some(10)),]), + "the bound narrows the fence, it never widens it" + ); + } + #[test] fn test_memtable_concurrent_write_read() { common_telemetry::init_default_ut_logging(); diff --git a/src/mito2/src/read.rs b/src/mito2/src/read.rs index 7f5d09eb031..1a167b355a1 100644 --- a/src/mito2/src/read.rs +++ b/src/mito2/src/read.rs @@ -70,7 +70,6 @@ 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}; @@ -79,7 +78,9 @@ use crate::error::{ ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, EvalPartitionFilterSnafu, InvalidBatchSnafu, Result, SequenceRangeUnsupportedSnafu, }; -use crate::memtable::BoxedRecordBatchIterator; +use crate::memtable::{ + BoxedRecordBatchIterator, CreatorSliceCursor, creator_slice_sequence_range, least_slice_until, +}; pub(crate) fn timestamp_array_to_i64_slice(arr: &ArrayRef) -> &[i64] { use datatypes::arrow::array::{ @@ -163,11 +164,11 @@ struct DensePkCache { /// caller then applies [`Batch::unresolved_creator_cursor`] to the candidate cursors. fn creator_slice_probe_batch( metadata: &RegionMetadataRef, - slices: &[(PartitionExpr, SequenceNumber)], + slices: &[CreatorSliceCursor], pk_values: &CompositeValues, ) -> Option { let mut referenced = HashSet::new(); - for (expr, _) in slices { + for (expr, ..) in slices { expr.collect_column_names(&mut referenced); } @@ -209,22 +210,33 @@ fn creator_slice_probe_batch( /// /// Equal bounds mean every candidate carries the same cursor value — the only case in which /// the least advanced cursor is exact for a piece that cannot be resolved. -fn creator_cursor_range( - slices: &[(PartitionExpr, SequenceNumber)], -) -> (SequenceNumber, SequenceNumber) { +fn creator_cursor_range(slices: &[CreatorSliceCursor]) -> (SequenceNumber, SequenceNumber) { let min = slices .iter() - .map(|(_, cursor)| *cursor) + .map(|(_, cursor, _)| *cursor) .min() .unwrap_or_default(); let max = slices .iter() - .map(|(_, cursor)| *cursor) + .map(|(_, cursor, _)| *cursor) .max() .unwrap_or(min); (min, max) } +/// The least of two slices' upper bounds: a slice that states none is unbounded above, so it +/// never narrows the pair, and two slices that state none stay unbounded. +fn least_until( + left: Option, + right: Option, +) -> Option { + match (left, right) { + (Some(left), Some(right)) => Some(left.min(right)), + (Some(bound), None) | (None, Some(bound)) => Some(bound), + (None, None) => None, + } +} + /// 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 { @@ -530,57 +542,65 @@ impl Batch { /// 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. + /// values, and the rows are kept when their own sequence is above that slice's cursor and + /// at or below `min(read_fence, until)`, where `read_fence` is the upper end of the read's + /// own sequence range ([`Self::filter_by_sequence`]) and `until` is the last sequence the + /// piece's delta covers. 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, and a row numbered above its own piece's bound is left to the + /// delta that covers it. /// /// A batch whose piece **cannot be resolved** is decided by /// [`Self::unresolved_creator_cursor`]: the least advanced cursor is exact when every /// candidate carries it, and the read fails otherwise, because that floor re-delivers /// the rows a more advanced piece has already consumed. /// - /// `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. + /// `None` or an empty set applies no filter, and a set whose cursors and bounds all agree + /// needs no evaluation at all — they are the region's floor and ceiling, and the outcome is + /// exactly [`Self::filter_by_sequence`] with them. pub fn filter_by_creator_slices( &mut self, - slices: Option<&[(PartitionExpr, SequenceNumber)]>, + slices: Option<&[CreatorSliceCursor]>, + read_fence: Option, 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 { + let Some(&(_, first, first_until)) = 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 + // One cursor value and one bound for every piece is the rule of the region: which + // piece a row belongs to cannot change the outcome, so the batch needs no evaluation. + let (cursor, until) = if slices + .iter() + .all(|(_, seq, until)| *seq == first && *until == first_until) + { + (first, first_until) } else { self.creator_slice_cursor(slices, metadata, codec)? }; - self.filter_by_sequence_range(SequenceRange::Gt { min: cursor }) + self.filter_by_sequence_range(creator_slice_sequence_range(cursor, until, read_fence)) } - /// Returns the cursor of the piece the rows of `self` belong to, or the floor the batch - /// must be bounded by when the piece cannot be resolved + /// Returns the cursor and the upper bound of the piece the rows of `self` belong to, or + /// the floor the batch must be bounded by when the piece cannot be resolved /// ([`Self::unresolved_creator_cursor`]). /// /// 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. + /// split cleanly), the least advanced cursor among them is used — it never drops a row a + /// conservatively bounded read would have delivered — together with the least upper bound + /// among them, the only bound every one of the matching pieces proves. fn creator_slice_cursor( &self, - slices: &[(PartitionExpr, SequenceNumber)], + slices: &[CreatorSliceCursor], metadata: &RegionMetadataRef, codec: Option<&dyn PrimaryKeyCodec>, - ) -> Result { + ) -> Result<(SequenceNumber, Option)> { let Some(codec) = codec else { // Without a primary key the pieces cannot be told apart. return Self::unresolved_creator_cursor( @@ -612,8 +632,8 @@ impl Batch { ); }; - let mut matched: Option = None; - for (expr, cursor) in slices { + let mut matched: Option<(SequenceNumber, Option)> = None; + for (expr, cursor, until) 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, @@ -635,9 +655,13 @@ impl Batch { }; 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))); + // cleanly is bounded by its least advanced piece, in both ends. + matched = Some(match matched { + None => (*cursor, *until), + Some((cursor_now, until_now)) => { + (cursor_now.min(*cursor), least_until(until_now, *until)) + } + }); } } @@ -656,23 +680,26 @@ impl Batch { /// One rule decides every such case. When the candidate slices of the region all carry /// the **same** cursor value, that value is the least advanced one and bounding the batch /// by it delivers exactly the rows the per-piece rule delivers: the floor stays, silent - /// and without any evaluation of its own. When they carry several values, the least + /// and without any evaluation of its own. The upper end is then the least bound the + /// candidates state, the only one every candidate proves — a candidate that states none is + /// unbounded above and narrows nothing. When they carry several cursor values, the least /// advanced one is not exact — it delivers the rows a more advanced piece has already /// consumed, so the batch would be *duplicated*, not merely replayed — and an exact read /// must not degrade that way without saying so, so the read fails with /// [`crate::error::Error::SequenceRangeUnsupported`]. fn unresolved_creator_cursor( metadata: &RegionMetadataRef, - slices: &[(PartitionExpr, SequenceNumber)], + slices: &[CreatorSliceCursor], detail: &str, - ) -> Result { + ) -> Result<(SequenceNumber, Option)> { let (min, max) = creator_cursor_range(slices); + let until = least_slice_until(slices.iter().map(|(_, _, until)| until)); debug!( "Cannot resolve the creator cursor slice of a batch of region {} (candidate cursors {}..={}), detail: {}", metadata.region_id, min, max, detail ); if min == max { - return Ok(min); + return Ok((min, until)); } SequenceRangeUnsupportedSnafu { region_id: metadata.region_id, diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 987ccd38135..73b4a395455 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -100,9 +100,9 @@ use crate::sst::parquet::reader::ReaderMetrics; use crate::sst::primary_key::PrimaryKeyRangeMapper; /// The cursor of each piece a row of this region's own data may belong to, as the read -/// compiles them: `(partition expression, last consumed sequence)` pairs -/// (`RangesOptions::creator_slices`). -type RegionCreatorSlices = Arc>; +/// compiles them: `(partition expression, last consumed sequence, last sequence the piece's +/// delta covers)` triples (`RangesOptions::creator_slices`). +type RegionCreatorSlices = crate::memtable::CreatorSliceCursors; /// A scanner scans a region and returns a [SendableRecordBatchStream]. pub(crate) enum Scanner { @@ -586,6 +586,10 @@ impl ScanRegion { /// of the piece its tag values fall into instead of against the single floor of the /// region, which is only the least advanced piece. /// + /// Each slice carries the last sequence its delta covers ([`CursorShard::until`]) along + /// with its cursor, so the memtable bounds the rows of a piece from above as well: a row + /// numbered above that bound belongs to a later delta and is not delivered by this one. + /// /// `Ok(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 @@ -638,7 +642,7 @@ impl ScanRegion { )?; return Ok(None); }; - slices.push((expr, shard.seq)); + slices.push((expr, shard.seq, shard.until)); } if slices.is_empty() { return Ok(None); @@ -727,7 +731,8 @@ impl ScanRegion { 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. + // `memtable_min_sequence` states (the least advanced piece), and the bound a slice + // states narrows the read's maximum for the rows of that piece. let memtable_creator_slices = self.memtable_creator_slices()?; for m in memtables { diff --git a/src/query/src/options.rs b/src/query/src/options.rs index bcf3a893c0e..a13ecb726cb 100644 --- a/src/query/src/options.rs +++ b/src/query/src/options.rs @@ -600,7 +600,9 @@ fn parse_expression_keyed_shards( /// /// `until` is read under either version: a bound is a bound, and a payload that states one /// (this build's version [`CURSOR_SHARD_VERSION_BOUNDED`], or an intermediate build that put -/// it under version [`CURSOR_SHARD_VERSION`]) must not lose it here. +/// it under version [`CURSOR_SHARD_VERSION`]) must not lose it here. A bound below the +/// slice's own `seq` states an empty delta (a slice covers `seq < number <= until`) and is +/// refused instead of being clamped or swapped. fn parse_cursor_shard(region_id: u64, shard: &serde_json::Value) -> Result { let serde_json::Value::Object(fields) = shard else { return Err(invalid_query_context_extension(format!( @@ -643,6 +645,24 @@ fn parse_cursor_shard(region_id: u64, shard: &serde_json::Value) -> Result Some(parse_cursor_seq(region_id, raw)?), }; + // A slice covers `seq < number <= until`, so an `until` below its own `seq` states an + // empty window. Refusing it is the only reading that keeps the producer's statement + // intact: clamping or swapping would silently deliver a delta it never asked for. A + // lower bound is also worse than a no-op downstream — a read bounds a file with + // `GtLtEq { min, max }` and `max < min` selects no row at all, while a file several + // slices match can still admit rows through another slice's smaller minimum, so the + // read would answer with a plain wrong result instead of failing. + if let Some(until) = until + && until < seq + { + return Err(invalid_query_context_extension(format!( + "Invalid cursor slice in {} for region {}: the upper bound {} is below the slice's \ + own consumed sequence {} (a slice covers seq < number <= until, so its until must \ + be at least its seq)", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, until, seq + ))); + } + Ok(match until { Some(until) => CursorShard::new(partition_expr, seq).with_until(until), None => CursorShard::new(partition_expr, seq), @@ -1341,6 +1361,76 @@ mod flow_extension_tests { } } + /// A slice covers `seq < number <= until`, so an `until` below its own `seq` states an + /// empty delta and is refused at the boundary instead of being clamped or swapped: a read + /// bounds a file with `GtLtEq { min, max }` and `max < min` selects no row at all, while a + /// file several slices match can still admit rows through another slice's smaller minimum, + /// so the wrong slice would look like a plausible but wrong answer instead of a failure. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_upper_bound_below_cursor() { + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":3,"shards":[{"expr":null,"seq":10,"until":9}]}}"#.to_string(), + )]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + let message = format!("{err}"); + assert!( + message.contains("region 7"), + "the failure names the region: {message}" + ); + assert!( + message.contains("upper bound 9"), + "the failure names the stated bound: {message}" + ); + assert!( + message.contains("consumed sequence 10"), + "the failure names the slice's own cursor: {message}" + ); + assert!( + message.contains("at least its seq"), + "the failure names the ordering rule: {message}" + ); + + // The bound is refused under either version, and whatever the distance is. + for (value, region) in [ + ( + r#"{"8":{"version":2,"shards":[{"expr":null,"seq":10,"until":9}]}}"#, + "region 8", + ), + ( + r#"{"9":{"version":3,"shards":[{"expr":null,"seq":5,"until":0}]}}"#, + "region 9", + ), + ] { + let exts = + HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value.to_string())]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + let message = format!("{err}"); + assert!( + message.contains(region) && message.contains("at least its seq"), + "{value}: {message}" + ); + } + + // `until == seq` is the boundary the rule allows: the slice states the bound it + // covers, and no row of it is above the cursor. + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":3,"shards":[{"expr":null,"seq":10,"until":10}]}}"#.to_string(), + )]); + let parsed = FlowQueryExtensions::parse_flow_extensions(&exts) + .unwrap() + .unwrap(); + assert_eq!( + parsed.incremental_after_seqs, + Some(HashMap::from([( + 7, + vec![CursorShard::whole_domain(10).with_until(10)] + )])), + "a bound equal to the cursor states an empty window and is not a contradiction" + ); + } + /// An expression this build cannot read back is rejected at the boundary rather than /// silently widened to the whole domain by the scan that receives it. #[test]