From 1eda17429db0acc1d7e17db195ef874bf604bc4f Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 25 Nov 2026 22:46:08 +0800 Subject: [PATCH] fix(mito2): fail the read when a piece cannot be resolved and the pieces disagree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bounding an unresolved row (or batch) by the least advanced cursor is exact only while every candidate carries that cursor. Once the pieces disagree, that floor delivers rows a more advanced piece has already consumed — a duplicate, not a replay — so the read now states SEQUENCE_RANGE_UNSUPPORTED instead of degrading silently. One rule, four sites: the file-level candidate selection, the parquet slice filter, the time-series batch filter and the bulk part mask; a single cursor value keeps today's behaviour and does no extra work. Signed-off-by: discord9 --- src/mito2/src/engine/scan_test.rs | 238 +++++++++++++++++++++ src/mito2/src/memtable/bulk/part_reader.rs | 232 ++++++++++++++++++-- src/mito2/src/memtable/time_series.rs | 136 +++++++++++- src/mito2/src/read.rs | 128 ++++++++--- src/mito2/src/read/scan_region.rs | 167 ++++++++++++--- src/mito2/src/sst/parquet/reader.rs | 64 +++++- 6 files changed, 884 insertions(+), 81 deletions(-) diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index bd76c58f891..f3f6d389e3e 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -6819,6 +6819,100 @@ async fn test_read_row_sequence_splits_memtable_rows_by_the_expression_of_each_r ); } +/// The same rule at the memtable end of a scan: the per-piece rule of this region's own +/// memtable is built from the region's own cursor slices, so a slice set the read cannot +/// apply per row (a slice covering the whole value domain, or an identity this build cannot +/// read back) keeps the region-level floor only while every candidate carries it. With +/// several cursor values the floor delivers the rows a more advanced piece consumed, so the +/// read fails just like it does for a file of an adopted creator. +#[tokio::test] +async fn test_read_row_sequence_fails_closed_when_memtable_pieces_are_unresolved() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed_memtable_pieces").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + // Five rows in the time-series memtable (numbers 1..5): no flush, so no file takes part + // in the read. + 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(); + test_util::put_rows( + &engine, + region, + Rows { + schema, + rows: test_util::build_rows_for_key("1", 0, 5, 0), + }, + ) + .await; + + // A whole-domain slice at 3 next to a piece slice at 1: no row of the memtable can be + // attributed to a piece, and the region-level floor (1) would deliver the rows 2 and 3 + // the more advanced piece has already consumed. + let err = match engine + .scan_batch( + region, + creator_cursor_scan( + region, + vec![ + CursorShard::whole_domain(3), + partition_str_slice_cursor("0", "5", 1), + ], + 1, + 20, + ), + true, + ) + .await + { + Err(err) => err, + Ok(mut stream) => match stream.try_next().await { + Err(err) => err, + Ok(_) => panic!("an unresolvable memtable piece with disagreeing cursors must fail"), + }, + }; + let message = format!("{err}"); + assert!( + message.contains("exact sequence range unavailable"), + "the shared exact-range contract prefix must reach the caller: {message}" + ); + assert!( + message.contains("the memtable of region") + && message.contains("covers the whole value domain"), + "the failure must name the memtable and say what could not be resolved: {message}" + ); + + // One cursor value for every candidate: the region-level floor is the per-row answer, so + // the rows above 1 are delivered exactly as before. + let mut rows = scan_flat_row_sequences( + &engine, + region, + creator_cursor_scan( + region, + vec![ + CursorShard::whole_domain(1), + partition_str_slice_cursor("0", "5", 1), + ], + 1, + 20, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "one cursor value for every piece is the region-level floor of the whole read" + ); +} + /// The same per-row rule for a **bulk** memtable: 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 there too, instead of by the single floor of the region. @@ -7596,6 +7690,150 @@ async fn test_read_row_sequence_fails_closed_without_creator_cursor() { ); } +/// The `Display` of `err` and of every cause below it, one per line. +/// +/// A file-level decision is taken while the file is pruned, and the pruner reports a failed +/// file through a wrapper whose own `Display` does not repeat the cause, so the failure is +/// found in the chain. +fn error_chain(err: &Error) -> String { + let mut text = format!("{err}"); + let mut source = std::error::Error::source(err); + while let Some(cause) = source { + text.push('\n'); + text.push_str(&format!("{cause}")); + source = cause.source(); + } + text +} + +/// The counterexample to the file-level fallback of a physical-sequence read: when the +/// per-row rule of a file cannot be applied, the file is bounded by the **least** advanced +/// candidate. That floor is exact only while every candidate carries it — with several cursor +/// values it re-delivers the rows a more advanced piece has already consumed, so the read +/// fails instead of degrading an exact read into a duplicate. +/// +/// Two shapes the per-row rule cannot apply, both on a file of an adopted creator: a slice +/// identity this build cannot read back, and a slice covering the whole value domain. +#[tokio::test] +async fn test_read_row_sequence_fails_closed_when_pieces_disagree_and_piece_is_unresolved() { + let mut env = + TestEnv::with_prefix("test_read_row_sequence_fails_closed_disagreeing_pieces").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // One file stating no expression, so every slice of the creator is a candidate for it. + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + assert_eq!(None, source_file.partition_expr); + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + // The JSON `"MaxValue"` is a partition *bound*, not an expression: this build cannot read + // it back, so the file cannot be split per row. The two candidates carry different + // cursors, so the file-level floor (1) would deliver the rows 2 and 3 a piece consumed up + // to 3 again. + let unreadable = |cursor| CursorShard::new(Some("\"MaxValue\"".to_string()), cursor); + let mut stream = engine + .scan_batch( + target, + creator_cursor_scan( + source, + vec![partition_str_slice_cursor("0", "5", 1), unreadable(3)], + 0, + 10, + ), + true, + ) + .await + .unwrap(); + let err = match stream.try_next().await { + Err(err) => err, + Ok(_) => { + panic!("an unreadable slice identity with disagreeing cursors must fail the read") + } + }; + let message = error_chain(&err); + assert!( + message.contains("exact sequence range unavailable"), + "the shared exact-range contract prefix must reach the caller: {message}" + ); + assert!( + message.contains("cannot resolve a per-piece cursor"), + "the failure must say what could not be resolved: {message}" + ); + + // One cursor value for every candidate: the file-level floor *is* the per-row answer, so + // the unreadable identity keeps today's fallback and the rows above it are delivered. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![partition_str_slice_cursor("0", "5", 1), unreadable(1)], + 0, + 10, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "with one cursor value the file-level floor is exact and nothing is dropped" + ); + + // A whole-domain slice cannot be evaluated per row either: it applies to every row, so no + // slice expression can tell which piece a row belongs to. With disagreeing cursors the + // same rule applies. + let mut stream = engine + .scan_batch( + target, + creator_cursor_scan( + source, + vec![ + CursorShard::whole_domain(3), + partition_str_slice_cursor("0", "5", 1), + ], + 0, + 10, + ), + true, + ) + .await + .unwrap(); + let err = match stream.try_next().await { + Err(err) => err, + Ok(_) => panic!("a whole-domain slice with disagreeing cursors must fail the read"), + }; + let message = error_chain(&err); + assert!( + message.contains("cannot resolve a per-piece cursor") + && message.contains("covers the whole value domain"), + "the failure must say that the slice covers the whole domain: {message}" + ); + + // The same whole-domain read with one cursor value for every candidate keeps the + // file-level floor, exactly as before. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + CursorShard::whole_domain(1), + partition_str_slice_cursor("0", "5", 1), + ], + 0, + 10, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "one cursor value for every piece is the file-level floor of the whole file" + ); +} + /// The creator's cursor and the holder's snapshot are two different sequence domains, so a /// foreign file is filtered by the creator's cursor alone — never by the holder's `(C, H]`, /// which is what bounds the rows of every *local* file of the same scan. diff --git a/src/mito2/src/memtable/bulk/part_reader.rs b/src/mito2/src/memtable/bulk/part_reader.rs index f301ba7ebc0..d14c33dae0b 100644 --- a/src/mito2/src/memtable/bulk/part_reader.rs +++ b/src/mito2/src/memtable/bulk/part_reader.rs @@ -33,7 +33,7 @@ use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; use crate::error::{ self, ComputeArrowSnafu, DecodeArrowRowGroupSnafu, EvalPartitionFilterSnafu, - SerializePartitionExprSnafu, UnexpectedSnafu, + SequenceRangeUnsupportedSnafu, SerializePartitionExprSnafu, UnexpectedSnafu, }; use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef}; use crate::memtable::bulk::part::EncodedBulkPart; @@ -532,11 +532,11 @@ fn and_mask(current: Option, next: BooleanArray) -> error::Result< /// memtable counterpart of the per-row slice selection a physical-sequence read of an SST /// applies (`FileRangeContext::evaluate_creator_slices`). /// -/// A row no candidate selects is bounded 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. The same bound applies when the expressions cannot be resolved, -/// planned or evaluated, and when several candidates select one row the least advanced of -/// them decides. +/// 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. /// /// `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. @@ -572,12 +572,14 @@ fn creator_slice_mask( let selected = match creator_slice_selection(context, slices, record_batch) { Ok(selected) => selected, Err(e) => { - // Deciding a row's piece by guesswork would drop rows: keep the floor. - debug!( - "Cannot resolve the creator cursor slices of a bulk part, bounding every row by {}: {}", - fallback, e + // Deciding a row's piece by guesswork would drop rows, and the least advanced + // cursor only answers for the pieces that carry it. + return unresolved_creator_slices( + context, + slices, + fallback_mask, + &format!("the slice expressions cannot be resolved: {e}"), ); - return Ok(Some(fallback_mask)); } }; // Per candidate, the rows whose own sequence is above its cursor. @@ -613,14 +615,68 @@ fn creator_slice_mask( } if unmatched > 0 { debug!( - "{} of {} rows of a bulk part match no creator cursor slice; bounding them by the least advanced cursor {}", + "{} of {} rows of a bulk part match no creator cursor slice (least advanced cursor {})", unmatched, num_rows, fallback ); + return unresolved_creator_slices( + context, + slices, + fallback_mask, + &format!( + "{unmatched} of {num_rows} rows of the part match no candidate expression, so \ + the piece they belong to cannot be resolved" + ), + ); } Ok(Some(BooleanArray::from(kept.finish()))) } +/// The mask of rows an unresolvable piece of a bulk part is bounded by, or a failure when the +/// candidate cursors disagree. +/// +/// This is the one rule for every row of a bulk part whose piece cannot be resolved — no +/// candidate expression selects it, or one cannot be resolved, planned or evaluated. When the +/// candidates all carry the **same** cursor value, that value is the least advanced one and +/// the mask is exact: it keeps exactly the rows the per-row rule keeps, so the fallback stays, +/// silently and without any evaluation of its own. When they carry several values, the least +/// advanced one keeps the rows a more advanced piece has already consumed: that is a +/// **duplicate**, not a replay, and an exact read must not degrade that way without saying so. +/// The bounds the error reports are the cursors' own span, which is the disagreement the read +/// cannot resolve. +fn unresolved_creator_slices( + context: &BulkIterContext, + slices: &[(PartitionExpr, SequenceNumber)], + fallback_mask: BooleanArray, + detail: &str, +) -> error::Result> { + let Some(min) = slices.iter().map(|(_, cursor)| *cursor).min() else { + return Ok(Some(fallback_mask)); + }; + let max = slices + .iter() + .map(|(_, cursor)| *cursor) + .max() + .unwrap_or(min); + if min == max { + return Ok(Some(fallback_mask)); + } + let region_id = context.read_format().metadata().region_id; + SequenceRangeUnsupportedSnafu { + region_id, + min_seq: min, + max_seq: max, + reason: format!( + "the per-piece cursor of a bulk memtable part of region {} cannot be resolved while \ + the pieces of the region disagree on the last consumed sequence ({}..={}): bounding \ + every row by the least advanced cursor {} would deliver the rows a more advanced \ + piece has already consumed. {}", + region_id, min, max, min, detail + ), + } + .fail() +} + /// Evaluates the candidate creator cursor slice expressions against the tag columns of /// `record_batch` and returns the mask of rows each expression selects. /// @@ -1065,4 +1121,156 @@ mod tests { let result: Vec<_> = iter.map(|rb| rb.unwrap()).collect(); assert_eq!(expect_batches, result); } + + /// A bulk part resolves the piece of every row from its own tag columns, so a slice + /// expression over a column the part neither carries nor encodes in its primary key + /// cannot be evaluated. Bounding the part by the least advanced cursor is exact only while + /// every candidate carries it: with several cursor values it re-delivers the rows a more + /// advanced piece has already consumed, so the read fails instead. + #[test] + fn test_bulk_part_fails_closed_when_slices_disagree_and_probe_is_unresolved() { + 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), + ])); + + // Three rows of two series, numbered 3, 4 and 6. + let keys = ["key1", "key1", "key2"]; + let key1 = Arc::new(StringArray::from_iter_values(keys)); + let field1 = Arc::new(Int64Array::from(vec![0, 0, 0])); + let timestamp = Arc::new(datatypes::arrow::array::TimestampMillisecondArray::from( + vec![0, 1000, 2000], + )); + 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, 1]), + values, + )); + let sequence = Arc::new(UInt64Array::from(vec![3, 4, 6])); + let op_type = Arc::new(UInt8Array::from(vec![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]); + // The projection drops `field1`, so the batch carries no value of it, and it is not a + // primary-key column either: the probe of a slice over it cannot be built. + let context = Arc::new( + BulkIterContext::new( + Arc::new(builder.build().unwrap()), + Some(&[0, 2]), + None, + false, + crate::sst::parquet::DEFAULT_READ_BATCH_SIZE, + ) + .unwrap(), + ); + + // Two candidate pieces over the column the part cannot state. + let slices = |left: u64, right: u64| { + let slices = vec![ + ( + partition::expr::col("field1").gt_eq(Operand::Value(Value::Int64(0))), + left, + ), + ( + partition::expr::col("field1").lt(Operand::Value(Value::Int64(0))), + right, + ), + ]; + Some(Arc::new(slices)) + }; + let sequence_filter = Some(SequenceRange::GtLtEq { min: 2, max: 100 }); + + // Cursors 5 and 2: the least advanced one (2) would deliver the rows 3 and 4 the piece + // consumed up to 5 has already consumed. + let mut iter = BulkPartBatchIter::from_single( + record_batch.clone(), + context.clone(), + sequence_filter, + 0, + None, + ) + .with_creator_slices(slices(5, 2)); + let err = match iter.next() { + Some(Err(err)) => err, + Some(Ok(_)) => panic!("an unresolvable piece with disagreeing cursors must fail"), + None => panic!("the read must fail instead of yielding no batch at all"), + }; + let message = format!("{err}"); + assert!( + message.contains("exact sequence range unavailable"), + "the shared exact-range contract prefix must reach the caller: {message}" + ); + assert!( + message.contains("cannot be resolved while the pieces"), + "the failure must say that the pieces disagree: {message}" + ); + + // Both cursors 2: one cursor value for every piece is the region floor, so every row + // above it is delivered without any evaluation of the expressions, exactly as before. + let iter = + BulkPartBatchIter::from_single(record_batch.clone(), context, sequence_filter, 0, None) + .with_creator_slices(slices(2, 2)); + let result: Vec<_> = iter.map(|rb| rb.unwrap()).collect(); + assert_eq!(1, result.len()); + let sequences = result[0] + .column(result[0].num_columns() - 2) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + vec![3, 4, 6], + sequences.values().to_vec(), + "one cursor value for every piece keeps the part-level floor of the whole region" + ); + } } diff --git a/src/mito2/src/memtable/time_series.rs b/src/mito2/src/memtable/time_series.rs index 876c997b909..4affcc474de 100644 --- a/src/mito2/src/memtable/time_series.rs +++ b/src/mito2/src/memtable/time_series.rs @@ -2129,19 +2129,137 @@ mod tests { "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![ + // A series no candidate expression selects cannot be attributed to a piece while the + // candidates disagree: bounding it by the least advanced cursor (2) would deliver the + // rows the piece at 5 already consumed, so the read fails instead of replaying them. + 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").gt_eq(Operand::Value(Value::String("z".into()))), - 2 + 2, ), - ]), - "a row no slice explains is attributed to the least advanced candidate, which \ - delivers every row above the region floor" + ]))); + let mut iter = memtable.ranges(None, options).unwrap().build(None).unwrap(); + let err = iter + .find_map(|batch| batch.err()) + .expect("a row no candidate explains fails the read while the cursors disagree"); + assert!( + err.to_string().contains("cannot be resolved while the pieces"), + "the failure names the unresolved piece: {err}" + ); + } + + /// A batch whose piece cannot be resolved is bounded by the least advanced cursor only + /// while every candidate carries it. With several cursor values that floor re-delivers + /// the rows a more advanced piece has already consumed — a duplicate, not a replay — so + /// the read fails instead of degrading silently. + /// + /// The piece is unresolvable here because the slice expressions reference `v0`, a *field* + /// column: a memtable batch states the tags of its series only, so the probe batch of the + /// piece cannot be built. + #[test] + fn test_memtable_fails_closed_when_slices_disagree_and_piece_is_unresolved() { + 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::>(); + // Rows 3 and 4 belong to the series `a`, row 6 to the series `z`. + for (k0, ts, sequence) in [("a", 0, 3), ("a", 1, 4), ("z", 2, 6)] { + 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, + }; + memtable + .write(&KeyValues::new(schema.as_ref(), mutation).unwrap()) + .unwrap(); + } + + // 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), + ] + }; + let options = |pieces| { + RangesOptions::default() + .with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 })) + .with_creator_slices(Some(Arc::new(pieces))) + }; + + // Cursors 5 and 2: the least advanced one (2) would deliver the rows 3 and 4 again, + // which the piece consumed up to 5 already consumed. + let mut iter = memtable + .ranges(None, options(slices(5, 2))) + .unwrap() + .build(None) + .unwrap(); + let err = match iter.next() { + Some(Err(err)) => err, + Some(Ok(_)) => panic!("an unresolvable piece with disagreeing cursors must fail"), + None => panic!("the read must fail instead of yielding no batch at all"), + }; + let message = format!("{err}"); + assert!( + message.contains("exact sequence range unavailable"), + "the shared exact-range contract prefix must reach the caller: {message}" + ); + assert!( + message.contains("cannot be resolved while the pieces"), + "the failure must say that the pieces disagree: {message}" + ); + + // Both cursors 2: one cursor value for every piece is the region floor, so the batch + // is bounded by it without any evaluation of its own and the rows above 2 are + // delivered exactly as before. + let mut iter = memtable + .ranges(None, options(slices(2, 2))) + .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(); + assert_eq!( + vec![(0, 3), (1, 4), (2, 6)], + rows, + "one cursor value for every piece keeps the batch-level floor of the whole region" ); } diff --git a/src/mito2/src/read.rs b/src/mito2/src/read.rs index 17d7abb3088..7f5d09eb031 100644 --- a/src/mito2/src/read.rs +++ b/src/mito2/src/read.rs @@ -77,7 +77,7 @@ use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; use crate::error::{ ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, - EvalPartitionFilterSnafu, InvalidBatchSnafu, Result, + EvalPartitionFilterSnafu, InvalidBatchSnafu, Result, SequenceRangeUnsupportedSnafu, }; use crate::memtable::BoxedRecordBatchIterator; @@ -160,7 +160,7 @@ struct DensePkCache { /// /// `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. +/// caller then applies [`Batch::unresolved_creator_cursor`] to the candidate cursors. fn creator_slice_probe_batch( metadata: &RegionMetadataRef, slices: &[(PartitionExpr, SequenceNumber)], @@ -205,6 +205,26 @@ fn creator_slice_probe_batch( RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).ok() } +/// The least and the greatest cursor value of a candidate slice set. +/// +/// 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) { + let min = slices + .iter() + .map(|(_, cursor)| *cursor) + .min() + .unwrap_or_default(); + let max = slices + .iter() + .map(|(_, cursor)| *cursor) + .max() + .unwrap_or(min); + (min, max) +} + /// 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 { @@ -516,9 +536,10 @@ impl Batch { /// 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. + /// 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 @@ -546,8 +567,9 @@ impl Batch { 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. + /// 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 + /// ([`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 @@ -559,31 +581,35 @@ impl Batch { 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); + return Self::unresolved_creator_cursor( + metadata, + slices, + "the batch states no primary key codec, so its tag values are unknown", + ); }; 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 Self::unresolved_creator_cursor( + metadata, + slices, + &format!("the primary key of the batch cannot be decoded: {e}"), ); - return Ok(fallback); } }, }; let Some(probe) = creator_slice_probe_batch(metadata, slices, &pk_values) else { - return Ok(fallback); + return Self::unresolved_creator_cursor( + metadata, + slices, + "the probe batch of the series' tag values cannot be built: a slice expression \ + references a column that is not part of this region's primary key, or a value \ + does not convert to the column's type", + ); }; let mut matched: Option = None; @@ -592,20 +618,19 @@ impl Batch { 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 Self::unresolved_creator_cursor( + metadata, + slices, + &format!("a slice expression cannot be evaluated: {e}"), ); - return Ok(fallback); } }, Err(e) => { - debug!( - "Cannot plan a creator cursor slice expression, bounding the batch by {}: {}", - fallback, e + return Self::unresolved_creator_cursor( + metadata, + slices, + &format!("a slice expression cannot be planned: {e}"), ); - return Ok(fallback); } }; if selected { @@ -616,7 +641,52 @@ impl Batch { } } - Ok(matched.unwrap_or(fallback)) + match matched { + Some(matched) => Ok(matched), + None => Self::unresolved_creator_cursor( + metadata, + slices, + "no candidate expression selects the series of the batch", + ), + } + } + + /// The floor to bound a batch by when the piece its rows belong to cannot be resolved. + /// + /// 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 + /// 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)], + detail: &str, + ) -> Result { + let (min, max) = creator_cursor_range(slices); + 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); + } + SequenceRangeUnsupportedSnafu { + region_id: metadata.region_id, + min_seq: min, + max_seq: max, + reason: format!( + "the per-piece cursor of a time-series memtable batch of region {} cannot be \ + resolved while the pieces of the region disagree on the last consumed \ + sequence ({}..={}): bounding the batch by the least advanced cursor {} would \ + deliver the rows a more advanced piece has already consumed. {}", + metadata.region_id, min, max, min, detail + ), + } + .fail() } /// Applies `seq_range` to the rows of the batch, skipping the mask when every row diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 8711be9d3b2..ed6360e095f 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -97,6 +97,11 @@ use crate::sst::parquet::file_range::{CreatorSliceCursors, PreFilterMode}; 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>; + /// A scanner scans a region and returns a [SendableRecordBatchStream]. pub(crate) enum Scanner { /// Sequential scan. @@ -106,7 +111,6 @@ pub(crate) enum Scanner { /// Per-series scan. Series(SeriesScan), } - impl Scanner { /// Returns a [SendableRecordBatchStream] to retrieve scan results from all partitions. #[tracing::instrument(level = tracing::Level::DEBUG, skip_all)] @@ -580,42 +584,65 @@ 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. /// - /// `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>> { + /// `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 + /// read back. The last two keep the region-level floor only while the candidates agree on + /// it ([`reject_disagreeing_creator_cursors`]); otherwise the read fails closed + /// instead of delivering the rows of a more advanced piece again. + fn memtable_creator_slices(&self) -> Result> { if !self.request.read_row_sequence || self.request.read_across_invalid_boundary { - return None; + return Ok(None); } - let shards = self + let Some(shards) = self .request .creator_cursor_shards - .as_ref()? - .get(&self.region_id().as_u64())?; + .as_ref() + .and_then(|shards| shards.get(&self.region_id().as_u64())) + else { + return Ok(None); + }; 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; + // A whole-domain cursor applies to every row of the region, so no slice + // expression can tell which piece a row belongs to: only the region-level + // floor is left, and it is the least advanced candidate. + reject_disagreeing_creator_cursors( + self.region_id(), + &format!("the memtable of region {}", self.region_id()), + &shards.iter().collect::>(), + "one cursor slice of the region covers the whole value domain, so no row \ + of the memtable can be attributed to a piece", + )?; + return Ok(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. + // approximating it would be guesswork, so only the region-level floor is left. debug!( "Cannot read back creator cursor slice expression {}; keeping the region-level floor", identity ); - return None; + reject_disagreeing_creator_cursors( + self.region_id(), + &format!("the memtable of region {}", self.region_id()), + &shards.iter().collect::>(), + &format!( + "the slice expression {} cannot be read back by this build, so no row \ + of the memtable can be attributed to a piece", + identity + ), + )?; + return Ok(None); }; slices.push((expr, shard.seq)); } if slices.is_empty() { - return None; + return Ok(None); } - Some(Arc::new(slices)) + Ok(Some(Arc::new(slices))) } /// Creates a scan input. @@ -699,7 +726,7 @@ impl ScanRegion { }; // 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(); + let memtable_creator_slices = self.memtable_creator_slices()?; for m in memtables { // check if memtable is empty by reading stats. @@ -2295,6 +2322,13 @@ impl ScanInput { /// same way — the candidates are then this region's own pieces — so that a row is /// compared against the cursor of the piece it belongs to rather than against one floor /// for the whole region. + /// + /// `Ok(None)` means the per-row rule cannot narrow the file's floor any further: no cursor + /// of the file's region is known, no candidate may hold a row of it, or one candidate + /// covers the whole value domain. The first two are "no cursor to resolve", and the last + /// one keeps the file-level floor only while the candidates agree on it + /// ([`reject_disagreeing_creator_cursors`]); otherwise an exact read fails closed + /// rather than re-delivering the rows a more advanced piece has already consumed. fn creator_slice_cursors(&self, file: &FileHandle) -> Result> { if !self.read_row_sequence { return Ok(None); @@ -2305,22 +2339,42 @@ impl ScanInput { .as_ref() .and_then(|shards| shards.get(&meta.region_id.as_u64())) else { + // No cursor of the file's creator region is known: there is no per-piece cursor + // to resolve (`row_sequence_filter` still fails an adopted file closed). return Ok(None); }; - let mut cursors = Vec::new(); + // The candidate set first. A whole-domain slice is a candidate of every file, so its + // own early return cannot stand in for the whole set: whether the *other* candidates + // carry its cursor is exactly what decides if the file-level floor is exact. + let mut candidates = Vec::with_capacity(shards.len()); for shard in shards { - let Some(identity) = shard.partition_expr.as_ref() else { - // A whole-domain cursor applies to every row: the file-level bound is the - // most precise answer available. - return Ok(None); - }; if cursor_slice_may_hold_file_rows(shard, meta)? { - cursors.push((identity.clone(), shard.seq)); + candidates.push(shard); } } - if cursors.is_empty() { + if candidates.is_empty() { + // No slice may hold a row of the file, so no piece's cursor is attributable to one + // of its rows: there is nothing to decide, and the file keeps its current bound + // (`row_sequence_filter` still fails an adopted file closed). return Ok(None); } + let mut cursors = Vec::with_capacity(candidates.len()); + for shard in &candidates { + let Some(identity) = shard.partition_expr.as_ref() else { + // A whole-domain cursor applies to every row, so no slice expression can tell + // which piece a row belongs to: only the file-level floor is left, and it is + // the least advanced candidate. + reject_disagreeing_creator_cursors( + self.region_metadata().region_id, + &format!("file {} of region {}", meta.file_id, meta.region_id), + &candidates, + "one cursor slice of its region covers the whole value domain, so no row of \ + the file can be attributed to a piece", + )?; + return Ok(None); + }; + cursors.push((identity.clone(), shard.seq)); + } Ok(Some(Arc::new(cursors))) } @@ -2509,6 +2563,67 @@ fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode { } } +/// Fails when the candidate cursor slices of one region disagree on the last consumed +/// sequence, and succeeds when they all carry the same value. +/// +/// This is the one rule for every case in which the per-row rule of a physical-sequence read +/// cannot be applied — a file of an adopted creator, this region's own memtable, or a +/// memtable part. When the candidates all carry the **same** cursor value, that value is the +/// least advanced one and the bound the fallback states is exact: it delivers exactly the rows +/// the per-row rule delivers, so the fallback stays, silently and without any evaluation of +/// its own. When they carry several values, the least advanced one re-delivers the rows of the +/// slices a more advanced piece has already consumed: that is a **duplicate**, not a replay, +/// and an exact read must not degrade that way without saying so, so the read fails with +/// [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported). +/// +/// The bounds the error reports are the cursors' own span, which is the disagreement the read +/// cannot resolve. `target` names what could not be resolved. +fn reject_disagreeing_creator_cursors( + region_id: RegionId, + target: &str, + candidates: &[&CursorShard], + detail: &str, +) -> Result<()> { + let Some((min, max)) = candidate_cursor_bounds(candidates) else { + return Ok(()); + }; + if min == max { + return Ok(()); + } + SequenceRangeUnsupportedSnafu { + region_id, + min_seq: min, + max_seq: max, + reason: format!( + "the physical-sequence read of {} cannot resolve a per-piece cursor while the \ + candidate slices of the region that allocated its numbers disagree on the last \ + consumed sequence ({}..={}): bounding it by the least advanced cursor {} would \ + deliver the rows a more advanced piece has already consumed. {}", + target, min, max, min, detail + ), + } + .fail() +} + +/// The least and the greatest cursor value of a candidate slice set, or `None` when the set +/// is empty. +/// +/// Equal bounds mean every candidate carries the same cursor value — the only case in which +/// the least advanced cursor answers an unresolvable piece exactly +/// ([`reject_disagreeing_creator_cursors`]). +fn candidate_cursor_bounds( + candidates: &[&CursorShard], +) -> Option<(SequenceNumber, SequenceNumber)> { + let mut bounds: Option<(SequenceNumber, SequenceNumber)> = None; + for shard in candidates { + bounds = Some(match bounds { + None => (shard.seq, shard.seq), + Some((min, max)) => (min.min(shard.seq), max.max(shard.seq)), + }); + } + bounds +} + /// Whether `meta` may hold rows of the value domain the cursor slice `shard` was consumed in, /// i.e. whether `shard.seq` is one of the candidate cursors of this file. /// diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index ad7d7c7c1d5..7085152cd2f 100644 --- a/src/mito2/src/sst/parquet/reader.rs +++ b/src/mito2/src/sst/parquet/reader.rs @@ -49,7 +49,7 @@ use partition::expr::PartitionExpr; use snafu::{OptionExt, ResultExt}; use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef}; use store_api::region_request::PathType; -use store_api::storage::{ColumnId, FileId}; +use store_api::storage::{ColumnId, FileId, RegionId, SequenceNumber}; use table::predicate::Predicate; use crate::cache::index::result_cache::PredicateKey; @@ -59,7 +59,7 @@ use crate::cache::{ }; use crate::error::{ InvalidPartitionExprSnafu, ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, - SerializePartitionExprSnafu, UnexpectedSnafu, + SequenceRangeUnsupportedSnafu, SerializePartitionExprSnafu, UnexpectedSnafu, }; use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED}; use crate::read::prune::FlatPruneReader; @@ -784,6 +784,53 @@ impl ParquetReaderBuilder { Ok((region_partition_expr, is_same)) } + /// Fails when the candidate creator cursor slices of `file` disagree on the last consumed + /// sequence, and succeeds when they all carry the same value. + /// + /// The one caller is the per-row rule of a physical-sequence read: an identity this build + /// cannot read back cannot be evaluated, and approximating it would decide a row's domain + /// by guesswork, so the file is left with its file-level bound — the least advanced + /// candidate. That floor is exact while every candidate carries it; once they differ, it + /// delivers the rows a more advanced piece has already consumed again, so the read fails + /// with [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported) + /// instead of degrading an exact read into a duplicate. + /// + /// The bounds the error reports are the cursors' own span, which is the disagreement the + /// read cannot resolve. + fn reject_disagreeing_slice_cursors( + &self, + file: &FileHandle, + region_id: RegionId, + slice_cursors: &[(String, SequenceNumber)], + ) -> Result<()> { + let Some(min) = slice_cursors.iter().map(|(_, cursor)| *cursor).min() else { + return Ok(()); + }; + let max = slice_cursors + .iter() + .map(|(_, cursor)| *cursor) + .max() + .unwrap_or(min); + if min == max { + return Ok(()); + } + let meta = file.meta_ref(); + SequenceRangeUnsupportedSnafu { + region_id, + min_seq: min, + max_seq: max, + reason: format!( + "the physical-sequence read of file {} of region {} cannot resolve a per-piece \ + cursor: it cannot read back the partition expression of its candidate slice, \ + while the candidate slices of that region disagree on the last consumed \ + sequence ({}..={}), so bounding the file by the least advanced cursor {} would \ + deliver the rows a more advanced piece has already consumed", + meta.file_id, meta.region_id, min, max, min + ), + } + .fail() + } + /// Builds the dependency-only schema for row-level partition evaluation. /// Its indices are independent of both Parquet and converted batch projections; /// precise filtering gathers these columns temporarily before compatibility. @@ -835,12 +882,19 @@ impl ParquetReaderBuilder { .context(InvalidPartitionExprSnafu { expr: identity })? else { // An identity this build cannot read back cannot be evaluated, and - // approximating it would decide a row's domain by guesswork: leave the - // whole context out so the caller keeps the conservative file-level bound. + // approximating it would decide a row's domain by guesswork. Only an + // unresolvable piece leaves the file-level bound, and that bound is the least + // advanced candidate: exact while every candidate carries it, a duplicate of + // the rows a more advanced piece consumed otherwise. debug!( - "Cannot read back creator cursor slice expression {}; falling back to the file-level bound", + "Cannot read back creator cursor slice expression {}; bounding the file by its least advanced candidate", identity ); + self.reject_disagreeing_slice_cursors( + &self.file_handle, + read_format.metadata().region_id, + slice_cursors, + )?; return Ok(None); }; expr.collect_column_names(&mut referenced_columns);