From 26508dcada8ef2b326d595cd9033357717d0ef36 Mon Sep 17 00:00:00 2001 From: discord9 Date: Thu, 26 Nov 2026 16:22:25 +0800 Subject: [PATCH] fix(mito2): key a range-cache entry by the creator slices it was read under A physical-sequence read selects rows by each creator piece's cursor and until, but the range-cache fingerprint carried only the region-level range, so a result built under one set of piece cursors was replayed under another: rows the new range requires were omitted and rows above its until were returned. Put the per-file candidate slices (identity, cursor, until) and read_row_sequence into the key; a slice set that cannot be stated makes the range uncacheable instead of caching under an incomplete key. Also take the least cursor among every candidate that selects a row, where the SST path took the first match: a row a lower-cursor piece also claims must be delivered, as the memtable and bulk paths already do. Signed-off-by: discord9 --- src/mito2/src/engine/scan_test.rs | 200 ++++++++++++++++++++++++ src/mito2/src/read/range_cache.rs | 50 +++++- src/mito2/src/read/scan_region.rs | 60 ++++++- src/mito2/src/sst/parquet/file_range.rs | 30 +++- 4 files changed, 336 insertions(+), 4 deletions(-) diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index cb1d8635431..f7c1229f52b 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -5455,6 +5455,131 @@ async fn test_range_cache_key_separates_sequence_ranges() { ); } +/// A range result is only reusable for a read whose **per-piece** selection is the same. +/// +/// A physical-sequence read decides each row of an adopted file by the creator cursor slice +/// that selects it, and bounds the file by `(least advanced cursor, least until]`. Neither is +/// stated by the file, so two reads of the same file under the same region-level `(C, H]` +/// deliver different rows once a piece cursor or an `until` advances; a cache key that only +/// records `(C, H]` replays the first read's rows to all of them. +/// +/// The counterexample this pins: `(cursor 0, until 6]` caches the rows 1..6, `(cursor 3, +/// until 8]` requires the rows 4..8, and `(cursor 0, until 2]` requires the rows 1..2 and +/// nothing above its `until`. Replaying the first result delivers the rows 1..6 to all three: +/// rows an advanced piece already consumed, rows the new range requires that are missing, and +/// rows above the new `until`. +/// +/// The `LastRow` selector is what puts this read on the sequential scan, the only path that +/// fills the range result cache: without it an append-only region reads through the unordered +/// scan, which bypasses the cache entirely. +#[tokio::test] +async fn test_range_cache_never_replays_a_range_read_under_other_creator_cursors() { + let mut env = TestEnv::with_prefix("test_range_cache_creator_cursor_slices").await; + let engine = env + .create_engine(MitoConfig { + // The flat format is the one the range result cache covers. + default_flat_format: true, + range_result_cache_size: ReadableSize::mb(64), + ..Default::default() + }) + .await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // Eight rows numbered 1..8, one per series, all of them in one file of the creator. The + // holder adopts that file as a foreign file. + let create = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(source, RegionRequest::Create(create)) + .await + .unwrap(); + let mut rows = Vec::new(); + for series in 0..8_usize { + rows.extend(test_util::build_rows_for_key( + &series.to_string(), + series, + series + 1, + 0, + )); + } + test_util::put_rows(&engine, source, Rows { schema, rows }).await; + test_util::flush_region(&engine, source, None).await; + let source_file = manifest_files(&engine, source) + .await + .into_values() + .next() + .expect("flushed file"); + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 20, true, None); + + // The `(cursor, until]` of the one piece the rows of the adopted file belong to. The + // region-level `(0, 20]` is the same in every read, so only the slice separates them; the + // tag filter is what makes the range eligible for the cache. + let request = |cursor: u64, until: u64| { + let mut request = creator_cursor_scan( + source, + vec![partition_str_slice_cursor("0", "9", cursor).with_until(until)], + 0, + 20, + ); + request.filters = vec![col("tag_0").gt_eq(lit(ScalarValue::Utf8(Some("0".to_string()))))]; + request.series_row_selector = Some(TimeSeriesRowSelector::LastRow { after_merge: false }); + request + }; + + let first = scan_partition_rows_and_foreign_creators(&engine, target, request(0, 6)) + .await + .0; + assert_eq!( + vec![0, 1000, 2000, 3000, 4000, 5000], + first, + "the first read delivers the rows above its cursor and up to its `until`" + ); + + // Wait for the completed range result: the same read then replays it, which it reports by + // saying that the files its rows came from are not readable from that call. + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let (rows, creators) = + scan_partition_rows_and_foreign_creators(&engine, target, request(0, 6)).await; + assert_eq!(first, rows, "a replay delivers the rows it replayed"); + if creators.is_none() { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the range result cache did not replay the range within the timeout"); + + // An advanced piece cursor with a higher `until`: the rows 4..8 are what this range + // requires, and the rows 1..3 are already consumed. + let advanced = scan_partition_rows_and_foreign_creators(&engine, target, request(3, 8)) + .await + .0; + assert_eq!( + vec![3000, 4000, 5000, 6000, 7000], + advanced, + "a read under an advanced piece cursor must not replay the rows of the earlier read: \ + only its own `(cursor, until]` decides" + ); + + // A narrower `until`: no row above it may be delivered, whatever an earlier read of the + // same files cached. + let bounded = scan_partition_rows_and_foreign_creators(&engine, target, request(0, 2)) + .await + .0; + assert_eq!( + vec![0, 1000], + bounded, + "a range result must never deliver a row above the `until` of the read it serves" + ); +} + #[tokio::test] async fn test_single_source_ranges_preserve_batches() { for (file_count, row_group_size) in [(1, 64), (1, 16), (2, 16)] { @@ -6738,6 +6863,81 @@ async fn test_read_row_sequence_splits_one_file_by_the_expression_of_each_row() ); } +/// Several candidate slices may select one row, and then the **least advanced** of their +/// cursors decides it — exactly like the time-series and bulk memtable filters +/// (`Batch::filter_by_creator_slices`, `creator_slice_mask`), which take the minimum over the +/// candidates that select a row. Taking the first match instead drops the rows a less advanced +/// piece still holds. +/// +/// The counterexample this pins: the retired records `A = [0,8): 1` and `B = [5,9): 0` — the +/// domain was not split cleanly, so both select a row at `k0 = 7` — and a merged holder file +/// holding one row at `k0 = 7, sequence = 1`. The row is required because +/// `1 > min(1, 0) = 0`; taking `A` first, as the reader did, drops it. It matches candidates, +/// so the fail-closed rule for a row no candidate selects does not apply. +#[tokio::test] +async fn test_read_row_sequence_takes_the_least_cursor_when_several_slices_select_a_row() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_least_cursor_of_several").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // One file of the creator holding one row of the series `k0 = "7"`, numbered 1, under a + // coarse statement (`k0 >= "0" AND k0 < "9"`) that covers both retired records: the file + // merges the rows of both pieces. The bounds are single characters, so their lexicographic + // order (the order of the string tag column) is the numeric order of the tag values. + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(source, RegionRequest::Create(request)) + .await + .unwrap(); + test_util::put_rows( + &engine, + source, + Rows { + schema, + rows: test_util::build_rows_for_key("7", 0, 1, 0), + }, + ) + .await; + test_util::flush_region(&engine, source, None).await; + + let mut source_file = manifest_files(&engine, source) + .await + .into_values() + .next() + .expect("flushed file"); + source_file.partition_expr = Some(partition_str_slice("0", "9").into()); + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 2, true, None); + + // `A` is consumed up to 1, `B` only up to 0, and the row at 7 falls into both domains. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + partition_str_slice_cursor("0", "8", 1), + partition_str_slice_cursor("5", "9", 0), + ], + 0, + 10, + ), + ) + .await; + + assert_eq!( + vec![(0, 1)], + rows, + "the row at sequence 1 is above the least advanced of the slices that select it (0), so \ + it must be delivered even though the first matching slice is consumed up to 1" + ); +} + /// The same per-row rule for a **memtable** of this region: a memtable row is filtered by /// the cursor of the piece its own tag values fall into, not by the single floor of the /// region. diff --git a/src/mito2/src/read/range_cache.rs b/src/mito2/src/read/range_cache.rs index 679663480f6..954ff421fee 100644 --- a/src/mito2/src/read/range_cache.rs +++ b/src/mito2/src/read/range_cache.rs @@ -33,7 +33,7 @@ use datatypes::value::scalar_value_to_timestamp; #[cfg(any(test, feature = "test"))] use futures::TryStreamExt; use store_api::region_engine::PartitionRange; -use store_api::storage::{FileId, RegionId, SequenceRange, TimeSeriesRowSelector}; +use store_api::storage::{FileId, RegionId, SequenceNumber, SequenceRange, TimeSeriesRowSelector}; use table::predicate::is_string_timestamp_literal; use crate::cache::CacheStrategy; @@ -139,6 +139,24 @@ impl ScanRequestFingerprintBuilder { } } +/// One candidate creator cursor slice of a file, as the range-cache key records it. +/// +/// A physical-sequence read decides each row of the file by the cursor of the slice that +/// selects it, and bounds the whole file by the least advanced cursor and the least upper bound +/// of the same candidates. Both outcomes depend on the candidate set, which the file itself +/// does not state: after a piece cursor advances or an `until` changes, the same files under +/// the same region-level `(C, H]` deliver different rows. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct CreatorCursorSlice { + /// Identity of the slice's partition expression (`None` = the whole value domain). + pub(crate) partition_expr: Option, + /// Last sequence consumed in the slice's domain (exclusive lower bound). + pub(crate) cursor: SequenceNumber, + /// Last sequence the read's delta covers in that domain + /// ([`CursorShard::until`](store_api::storage::CursorShard::until)). + pub(crate) until: Option, +} + /// Inputs affecting a file read's output. #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct FileReadFingerprint { @@ -148,6 +166,14 @@ struct FileReadFingerprint { preserve_row_sequence: bool, snapshot_sequence: Option, pre_filter_mode: PreFilterMode, + /// Whether this read keeps the file's own `__sequence` and splits its rows by creator + /// cursor slices (`ScanInput::read_row_sequence`), instead of virtualizing the sequence at + /// the file's admission barrier. + read_row_sequence: bool, + /// The candidate creator cursor slices this read decides the file's rows by, in a stable + /// order; `None` when it applies no per-piece rule to the file + /// (`ScanInput::creator_cursor_slices`). + creator_slices: Option>>, } /// Non-copiable struct of the fingerprint. @@ -236,6 +262,19 @@ impl ScanRequestFingerprint { + self.file_reads.as_ref().map_or(0, |files| { mem::size_of::>() + files.capacity() * mem::size_of::() + + files + .iter() + .filter_map(|file| file.creator_slices.as_ref()) + .map(|slices| { + mem::size_of::>() + + slices.capacity() * mem::size_of::() + + slices + .iter() + .filter_map(|slice| slice.partition_expr.as_ref()) + .map(String::capacity) + .sum::() + }) + .sum::() }) + self.inner.read_columns.estimated_size() + self.inner.read_column_types.capacity() * mem::size_of::>() @@ -524,6 +563,13 @@ fn build_range_cache_key_inner( } let handle = stream_ctx.input.file_from_index(*index); let file = handle.meta_ref(); + // The per-piece rule of a physical-sequence read decides this file's rows from a set + // the file itself does not state (`ScanInput::creator_cursor_slices`), so a result + // built under one set must never be replayed under another. A set that cannot be + // stated makes the range uncacheable; the read itself reports the same failure. + let Ok(creator_slices) = stream_ctx.input.creator_cursor_slices(handle) else { + return None; + }; files.push(( (handle.file_id().file_id(), index.row_group_index), FileReadFingerprint { @@ -536,6 +582,8 @@ fn build_range_cache_key_inner( || stream_ctx.range_pre_filter_mode(part_range), |pruner| pruner.pre_filter_mode(index.index - stream_ctx.input.num_memtables()), ), + read_row_sequence: stream_ctx.input.read_row_sequence, + creator_slices, }, )); } diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index ed6360e095f..987ccd38135 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -70,7 +70,9 @@ use crate::metrics::READ_SST_COUNT; use crate::read::compat::{self, FlatCompatBatch}; use crate::read::flat_projection::FlatProjectionMapper; use crate::read::range::{FileRangeBuilder, MemRangeBuilder, RangeMeta, RowGroupIndex}; -use crate::read::range_cache::{ScanRequestFingerprint, implied_time_range_from_exprs}; +use crate::read::range_cache::{ + CreatorCursorSlice, ScanRequestFingerprint, implied_time_range_from_exprs, +}; use crate::read::read_columns::ReadColumns; use crate::read::seq_scan::SeqScan; use crate::read::series_scan::SeriesScan; @@ -2378,6 +2380,62 @@ impl ScanInput { Ok(Some(Arc::new(cursors))) } + /// The candidate creator cursor slices of `file` as a **range-cache key** has to record + /// them: the same candidates [`Self::creator_slice_cursors`] compiles into row filters, + /// each with the `until` bound [`Self::creator_domain_sequence_range`] derives from it. + /// + /// The set decides two things the file itself does not state: the file-level bound + /// `(least advanced cursor, least until]` and the per-row cursor of every piece. A cached + /// range result built under one set therefore cannot be replayed under another — a piece + /// cursor that advanced would replay rows the new range requires and rows above its + /// `until`. + /// + /// `Ok(None)` means this read applies no per-piece rule to the file (it is not a + /// physical-sequence read, or no cursor of the file's creator region is known). + pub(crate) fn creator_cursor_slices( + &self, + file: &FileHandle, + ) -> Result>>> { + if !self.read_row_sequence { + return Ok(None); + } + let meta = file.meta_ref(); + let Some(shards) = self + .creator_cursor_shards + .as_ref() + .and_then(|shards| shards.get(&meta.region_id.as_u64())) + else { + return Ok(None); + }; + let mut slices = Vec::with_capacity(shards.len()); + for shard in shards { + // A slice that cannot hold a row of this file is not one of its candidates, so its + // cursor and its `until` do not bound it. + if !cursor_slice_may_hold_file_rows(shard, meta)? { + continue; + } + slices.push(CreatorCursorSlice { + partition_expr: shard.partition_expr.clone(), + cursor: shard.seq, + until: shard.until, + }); + } + if slices.is_empty() { + return Ok(None); + } + // The outcome is decided by the set, not by its order (a row is bounded by the least + // advanced candidate that selects it, the file by the least advanced candidate), so + // one set must yield one key however the producer ordered it. + slices.sort_unstable_by(|a, b| { + a.partition_expr + .cmp(&b.partition_expr) + .then(a.cursor.cmp(&b.cursor)) + .then(a.until.cmp(&b.until)) + }); + slices.dedup(); + Ok(Some(Arc::new(slices))) + } + /// Whether `file` was created by another region, i.e. its rows carry a number this /// region never allocated. pub(crate) fn is_foreign_file(&self, file: &FileHandle) -> bool { diff --git a/src/mito2/src/sst/parquet/file_range.rs b/src/mito2/src/sst/parquet/file_range.rs index 23a34350222..858acb88518 100644 --- a/src/mito2/src/sst/parquet/file_range.rs +++ b/src/mito2/src/sst/parquet/file_range.rs @@ -1000,6 +1000,13 @@ impl RangeBase { /// into narrower ones whose cursors advanced differently, and free of lost rows when /// the file's own expression is narrower than the rows it holds. /// + /// When several candidates select one row — a domain that was not split cleanly, whose + /// expressions overlap — the **least advanced** of their cursors decides: the row is kept + /// when any of them has not consumed it, which is the conservative direction and the one + /// the time-series and bulk memtable filters already take + /// (`Batch::filter_by_creator_slices` and `creator_slice_mask`). Letting the first + /// matching candidate decide would drop a row a less advanced piece still holds. + /// /// A row no slice expression selects has no piece to attribute it to, so only the least /// advanced candidate ([`PartitionFilterContext::fallback_cursor`]) can bound it. That /// bound is exact while every candidate carries the same cursor value — it then *is* the @@ -1064,8 +1071,27 @@ impl RangeBase { kept.append(true); continue; } - let keep = match selected.iter().position(|mask| mask.value(row)) { - Some(index) => not_consumed[index].value(row), + // Disjoint slice expressions match a row at most once, which is the common case: + // one bit test answers it. A domain that was not split cleanly can match several, + // and their cursors may differ — the least advanced of them is the only bound that + // is exact for every candidate, so the first match must not decide the row. The + // memtable filters take the same minimum (`Batch::filter_by_creator_slices` and + // the bulk `creator_slice_mask`), i.e. they OR the candidates' `not_consumed` + // masks, which is the same row decision. + let mut selecting = selected + .iter() + .enumerate() + .filter(|(_, mask)| mask.value(row)); + let keep = match selecting.next() { + Some((first, _)) => { + let mut least = first; + for (index, _) in selecting { + if slices[index].cursor < slices[least].cursor { + least = index; + } + } + not_consumed[least].value(row) + } None => { unmatched += 1; let (min, max) =