diff --git a/src/mito2/src/cache/range_cache.rs b/src/mito2/src/cache/range_cache.rs index 7c58c18cc99..b332dc8e3c9 100644 --- a/src/mito2/src/cache/range_cache.rs +++ b/src/mito2/src/cache/range_cache.rs @@ -39,6 +39,7 @@ use crate::error::{ComputeArrowSnafu, Result}; use crate::metrics::{CACHE_BYTES, CACHE_EVICTION, RANGE_CACHE_WORKER_EVENTS}; use crate::read::BoxedRecordBatchStream; use crate::read::range_cache::RangeScanCacheKey; +use crate::read::substituted_rows::ForeignFileRowCreators; use crate::sst::file::FileHandle; use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE; @@ -140,6 +141,10 @@ impl RangeResultCache { } /// Replays a cached result or subscribes to one reader-owned streaming scan. + /// + /// `replay_evidence` is the reading scan's `ForeignFileRowCreators`, which is told when the + /// result this call returns did not decode the files of the caller's own scan: the creators + /// of the rows such a result delivers are then not recoverable from this call. #[tracing::instrument(name = "range_result_lookup", skip_all)] pub(crate) async fn read( self: &Arc, @@ -147,6 +152,7 @@ impl RangeResultCache { part_metrics: Arc, files: Vec, scope: RangeCacheScope, + replay_evidence: Option<&ForeignFileRowCreators>, build: F, ) -> Result<(BoxedRecordBatchStream, usize)> where @@ -157,6 +163,12 @@ impl RangeResultCache { let load = match cache.get_or_register(key, files, scope) { RangeCacheLookup::Hit(value) => { part_metrics.inc_range_cache_hit(); + // The rows of a completed range were decoded by whichever scan built it: the + // files they came from are not read again, so their creators cannot be named + // from this call. + if let Some(creators) = replay_evidence { + creators.record_replay_unknown(); + } let batch_size = value.value().estimated_batch_size; return Ok((cached_flat_range_stream(value), batch_size)); } @@ -190,7 +202,19 @@ impl RangeResultCache { let batch_size = *batch_size; let cursor = match owner_cursor { Some(cursor) => Some(cursor), - None => shared.subscribe().await, + None => { + let cursor = shared.subscribe().await; + // Another caller built this range, so the rows come from its source. Its files + // were decoded there, and whether that source recorded them into this scan's + // `ForeignFileRowCreators` is not knowable here, so this call cannot state an + // answer for the rows it delivers. + if cursor.is_some() + && let Some(creators) = replay_evidence + { + creators.record_replay_unknown(); + } + cursor + } }; let Some(mut cursor) = cursor else { // An oversized range has closed admission. This caller has not emitted diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 7291d18fa19..809ae62d362 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -74,6 +74,14 @@ mod row_selector_test; #[cfg(test)] mod scan_corrupt; #[cfg(test)] +mod scan_slice_bounds_test; +#[cfg(test)] +mod scan_slice_cache_test; +#[cfg(test)] +mod scan_slice_fail_closed_test; +#[cfg(test)] +mod scan_slice_test; +#[cfg(test)] mod scan_test; #[cfg(test)] mod sequence_test; @@ -1528,6 +1536,14 @@ fn validate_sequence_fences( exact_sequence_range_available: bool, extension_provider_blocks_exact: bool, ) -> Result<()> { + // A read that may cross a boundary a stale cursor can no longer explain prunes at file + // granularity and reads no row-level sequence range, so the sequence fences below do not + // apply: the caller only needs the timestamps of the surviving rows, and rejecting the + // request would deadlock recovery. + if request.read_across_invalid_boundary { + return Ok(()); + } + if request.exact_sequence_range { // Exact `sequence_range` mode: when the capability is available the // requested (C, H] delta is enforced row-level on memtables and every @@ -1568,7 +1584,11 @@ fn validate_sequence_fences( region_id, min_seq: request.memtable_min_sequence.unwrap_or_default(), max_seq: request.memtable_max_sequence.unwrap_or_default(), - reason: sequence_range_unsupported_reason(version, extension_provider_blocks_exact), + reason: sequence_range_unsupported_reason( + request, + version, + extension_provider_blocks_exact, + ), } .fail(); } @@ -1613,15 +1633,22 @@ fn validate_sequence_fences( } fn sequence_range_unsupported_reason( + request: &ScanRequest, version: &crate::region::version::Version, extension_provider_blocks_exact: bool, ) -> String { if extension_provider_blocks_exact { "region is a follower with an extension range provider, whose streams cannot be filtered by sequence".to_string() - } else if version.options.preserve_row_sequence { - "region has files without preserved per-row sequences".to_string() - } else { + } else if !version.options.preserve_row_sequence { "region does not preserve per-row sequences (preserve_row_sequence is off)".to_string() + } else if request.read_row_sequence { + // A file that states a substituted cut is attributable (its substituted rows are + // hidden and reported, the rest keep this region's numbering), so the remaining + // case is a local file with neither the preserved-sequence marker nor a cut. + "region has files without preserved per-row sequences and without a substituted cut, so a physical-sequence read cannot attribute their rows" + .to_string() + } else { + "region has files without preserved per-row sequences".to_string() } } diff --git a/src/mito2/src/engine/scan_slice_bounds_test.rs b/src/mito2/src/engine/scan_slice_bounds_test.rs new file mode 100644 index 00000000000..8a9a77fae46 --- /dev/null +++ b/src/mito2/src/engine/scan_slice_bounds_test.rs @@ -0,0 +1,142 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use store_api::storage::{CursorShard, RegionId}; + +use super::scan_test::{ + adopt_foreign_file, build_foreign_source_file, create_foreign_target, creator_cursor_scan, + partition_str_slice_cursor, scan_flat_row_sequences, +}; +use crate::config::MitoConfig; +use crate::test_util::TestEnv; + +/// A creator slice that states the last sequence its delta covers bounds an adopted file from +/// above as well: a row above that bound was numbered after the delta this read stands for, +/// so delivering it here reports identity the caller has not consumed yet while its marker +/// stays below the row's number. +#[tokio::test] +async fn test_read_row_sequence_drops_adopted_rows_above_creator_upper_bound() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_creator_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // The creator's file states the numbers 1..5 and no cut, so the cursor decides alone. + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + // The delta is `(1, 3]`: rows 4 and 5 carry numbers the creator's cursor did not consume + // and its bound does not cover, so this round must not read them. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![CursorShard::whole_domain(1).with_until(3)], + 0, + 10, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "the rows above the creator's upper bound belong to a later delta, not to this read" + ); + + // The bound is a filter on the creator's domain, not a change of the cursor: stating a + // bound that covers every row delivers every row above the cursor, as before. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![CursorShard::whole_domain(1).with_until(5)], + 0, + 10, + ), + ) + .await; + assert_eq!(vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], rows); +} + +/// A slice that states no upper bound keeps the unbounded `(cursor, +inf)` filter it always +/// had: the bound is optional evidence, and a read that lacks it must not lose a row that no +/// bound excludes. +#[tokio::test] +async fn test_read_row_sequence_reads_above_cursor_without_creator_upper_bound() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_without_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 0, 10), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "without a bound every row above the creator's cursor is still owed" + ); +} + +/// Several candidate slices: the file-level upper bound is the **least** bound any of them +/// states, because the file-level filter cannot tell which slice a row belongs to. The +/// counterexample this pins: the slice holding the file's rows proves the delta ends at 3 +/// while another candidate's bound reaches 9, and reading up to 9 delivers rows 4 and 5, +/// which no slice yields this round. +#[tokio::test] +async fn test_read_row_sequence_takes_the_least_creator_upper_bound() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_least_upper_bound").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. + // Its five rows carry the tag `0`, i.e. they all fall in the `[0, 5)` slice. + 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); + + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + // The slice the file's rows belong to: consumed up to 1, delta ends at 3. + partition_str_slice_cursor("0", "5", 1).with_until(3), + // A candidate that overlaps no row of this file, with a looser bound. + partition_str_slice_cursor("5", "9", 3).with_until(9), + ], + 0, + 10, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "the file-level bound is the least bound of the candidates, so row 4 is left out" + ); +} diff --git a/src/mito2/src/engine/scan_slice_cache_test.rs b/src/mito2/src/engine/scan_slice_cache_test.rs new file mode 100644 index 00000000000..f1f1c8a8cdf --- /dev/null +++ b/src/mito2/src/engine/scan_slice_cache_test.rs @@ -0,0 +1,156 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::time::Duration; + +use api::v1::Rows; +use common_base::readable_size::ReadableSize; +use datafusion_common::ScalarValue; +use datafusion_expr::{col, lit}; +use store_api::region_engine::RegionEngine; +use store_api::region_request::RegionRequest; +use store_api::storage::{RegionId, TimeSeriesRowSelector}; + +use super::scan_test::{ + adopt_foreign_file, create_foreign_target, creator_cursor_scan, manifest_files, + partition_str_slice_cursor, scan_partition_rows_and_foreign_creators, +}; +use crate::config::MitoConfig; +use crate::test_util; +use crate::test_util::{CreateRequestBuilder, TestEnv}; + +/// 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" + ); +} diff --git a/src/mito2/src/engine/scan_slice_fail_closed_test.rs b/src/mito2/src/engine/scan_slice_fail_closed_test.rs new file mode 100644 index 00000000000..863cd9ec6ad --- /dev/null +++ b/src/mito2/src/engine/scan_slice_fail_closed_test.rs @@ -0,0 +1,401 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use api::v1::Rows; +use futures::TryStreamExt; +use store_api::region_engine::RegionEngine; +use store_api::region_request::RegionRequest; +use store_api::storage::{CursorShard, RegionId}; + +use super::scan_test::{ + adopt_foreign_file, build_foreign_source_file, create_foreign_target, creator_cursor_scan, + manifest_files, partition_str_slice_cursor, physical_sequence_scan, scan_flat_row_sequences, +}; +use crate::config::MitoConfig; +use crate::error::Error; +use crate::test_util; +use crate::test_util::{CreateRequestBuilder, TestEnv}; + +/// 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" + ); +} + +/// A creator this scan has no cursor slice for fails closed. Reading the file against this +/// region's own `(C, H]` compares two sequence domains, and reading it unfiltered delivers +/// every already consumed row again on every round; the scan reports the shared +/// "exact range unavailable" contract instead of choosing one of them. +#[tokio::test] +async fn test_read_row_sequence_fails_closed_without_creator_cursor() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 4, true, None); + + // No creator slice, and no cut either: the file states nothing this scan can filter + // with. + let mut stream = engine + .scan_batch(target, physical_sequence_scan(true), true) + .await + .unwrap(); + let err = match stream.try_next().await { + Err(err) => err, + Ok(_) => panic!("a foreign file without a creator cursor must fail closed"), + }; + 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("no cursor slice of its creator region"), + "the failure must say what is missing: {message}" + ); +} + +/// 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 third shape the per-row rule cannot answer: a row of the file that **no** candidate +/// expression selects, i.e. a row outside the value domain of every piece of the creator. +/// +/// Such a row has no piece to attribute it to, so only the least advanced candidate is left. +/// That floor is exact while every candidate carries the same cursor value — it then *is* what +/// the row's own piece states — and says nothing once they differ: it delivers the rows a more +/// advanced piece already consumed, so the read fails instead of replaying them. +#[tokio::test] +async fn test_read_row_sequence_fails_closed_when_no_piece_selects_a_row() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed_unselected_row").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: four rows of the series `k0 = "1"`, inside the domain of the + // left piece (`k0 < "5"`), and one row of `k0 = "9"`, outside the domain of both candidates. + 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(); + let mut rows = test_util::build_rows_for_key("1", 0, 4, 0); + rows.extend(test_util::build_rows_for_key("9", 4, 5, 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, 6, true, None); + + // The candidates carry 5 and 2. The row at 5 (`k0 = "9"`) belongs to no piece, and the + // least advanced cursor (2) does not stand for the pieces: it would deliver the rows 3 and + // 4 the left piece already consumed up to 5. + let mut stream = engine + .scan_batch( + target, + creator_cursor_scan( + source, + vec![ + partition_str_slice_cursor("0", "5", 5), + partition_str_slice_cursor("5", "9", 2), + ], + 0, + 10, + ), + true, + ) + .await + .unwrap(); + let err = match stream.try_next().await { + Err(err) => err, + Ok(_) => panic!("a row no candidate selects 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}" + ); + assert!( + message.contains("match no candidate creator cursor slice") && message.contains("(2..=5)"), + "the failure must name the unselected row and the cursors' own span: {message}" + ); + + // One cursor value for every candidate: the least advanced cursor is then every piece's + // cursor, so the row outside both domains keeps today's treatment and nothing is dropped. + let mut rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + partition_str_slice_cursor("0", "5", 2), + partition_str_slice_cursor("5", "9", 2), + ], + 0, + 10, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(2000, 3), (3000, 4), (4000, 5)], + rows, + "with one cursor value the row no candidate selects is bounded by it exactly, so the \ + rows above 2 are delivered and the rows at or below it are not" + ); +} diff --git a/src/mito2/src/engine/scan_slice_test.rs b/src/mito2/src/engine/scan_slice_test.rs new file mode 100644 index 00000000000..c7d2f671c58 --- /dev/null +++ b/src/mito2/src/engine/scan_slice_test.rs @@ -0,0 +1,551 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use api::v1::Rows; +use store_api::region_engine::RegionEngine; +use store_api::region_request::RegionRequest; +use store_api::storage::{CursorShard, RegionId}; + +use super::scan_test::{ + adopt_foreign_file, build_foreign_source_file, create_foreign_target, creator_cursor_scan, + manifest_files, partition_slice, partition_slice_cursor, partition_str_slice, + partition_str_slice_cursor, scan_flat_row_sequences, +}; +use crate::config::MitoConfig; +use crate::test_util; +use crate::test_util::{CreateRequestBuilder, TestEnv}; + +/// The cursor is keyed by `(region, expression slice)`: a file is filtered by the slice it +/// belongs to, not by the region projection of the creator's slices. +#[tokio::test] +async fn test_read_row_sequence_picks_the_intersecting_creator_slice() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_picks_intersecting_slice").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // The creator's file states the numbers 1..12 and belongs to its `[50, 100)` slice; the + // cut 3 says a substitution produced the first three of them. + let (_, mut source_file) = build_foreign_source_file(&engine, source, 12, true).await; + source_file.partition_expr = Some(partition_slice(50, 100).into()); + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 4, true, Some(3)); + + // `[0, 50)` is at 3 and the file's own `[50, 100)` at 10: the lower bound is 10, so only + // the rows 11 and 12 are delivered. The region projection of the same cursor (`min` = 3) + // would deliver the rows 4..12 again, which is exactly the duplication this keying + // removes. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + partition_slice_cursor(0, 50, 3), + partition_slice_cursor(50, 100, 10), + ], + 1, + 20, + ), + ) + .await; + assert_eq!(vec![(10_000, 11), (11_000, 12)], rows); + + // The mirror image: `[0, 50)` at 10 and the file's own `[50, 100)` at 3. The lower bound + // is the file's slice, so the rows 4..12 are delivered — the other slice's cursor must + // not be applied to a file it does not cover. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + partition_slice_cursor(0, 50, 10), + partition_slice_cursor(50, 100, 3), + ], + 1, + 20, + ), + ) + .await; + let expected = (4_u64..=12) + .map(|seq| (((seq - 1) * 1000) as i64, seq)) + .collect::>(); + assert_eq!(expected, rows); +} + +/// Two files of **one** creator region, each stating a different expression of its domain, +/// with different consumed progress on the two expressions: a merged read delivers exactly +/// the rows above the cursor of the expression each file states. +/// +/// The numbers are allocated in write order, so the slices are cross-wired on purpose: the +/// right slice (`k0 >= 50`) holds the *older* numbers (1..6) while the left slice +/// (`k0 < 50`) holds the newer ones (7..12). A read that applied the left cursor to both +/// files would lose the right slice's rows 3..6 (the left cursor is higher than the right +/// one), and a read that applied the region projection (`min` = 2) to both would deliver +/// the left slice's 7..10 again. Only selecting the slice each file belongs to delivers +/// both correctly. +#[tokio::test] +async fn test_read_row_sequence_filters_each_creator_expression_by_its_own_cursor() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_each_expression").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + 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: schema.clone(), + rows: test_util::build_rows_for_key("0", 0, 6, 0), + }, + ) + .await; + test_util::flush_region(&engine, source, None).await; + let mut right_file = manifest_files(&engine, source) + .await + .into_values() + .next() + .expect("first flushed file"); + assert_eq!(None, right_file.partition_expr); + right_file.partition_expr = Some(partition_slice(50, 100).into()); + + test_util::put_rows( + &engine, + source, + Rows { + schema, + rows: test_util::build_rows_for_key("0", 6, 12, 0), + }, + ) + .await; + test_util::flush_region(&engine, source, None).await; + let mut left_file = manifest_files(&engine, source) + .await + .into_values() + .find(|file| file.file_id != right_file.file_id) + .expect("second flushed file"); + assert_eq!(None, left_file.partition_expr); + left_file.partition_expr = Some(partition_slice(0, 50).into()); + + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, right_file, 13, true, None); + adopt_foreign_file(&engine, target, left_file, 14, true, None); + + // The left expression was consumed up to 10, the right one only up to 2. + let mut rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + partition_slice_cursor(0, 50, 10), + partition_slice_cursor(50, 100, 2), + ], + 1, + 20, + ), + ) + .await; + rows.sort_unstable(); + + assert_eq!( + vec![ + (2000, 3), + (3000, 4), + (4000, 5), + (5000, 6), + (10000, 11), + (11000, 12) + ], + rows, + "each file is filtered by the cursor of the expression it states: the right slice \ + keeps the rows above 2 (no loss) and the left slice starts above 10 (no duplicate)" + ); +} + +/// The counterexample per-row selection exists for: **one** file of one creator holds rows +/// of two of its expressions, and the two cursors advanced differently. +/// +/// The file was written under the coarse expression `k0 >= "0" AND k0 < "9"`, which the +/// creator's domain has since been split out of. Its rows belong to `k0 < "5"` (consumed up +/// to 5) and to `k0 >= "5"` (consumed up to 2). The least advanced cursor of the file is 2, +/// so a file-level bound would deliver the already consumed rows 3, 4 and 5 again; the most +/// advanced one (5) would drop the live row 6. Only splitting the rows by the expression +/// each of them satisfies delivers the row at 6 and nothing else. +#[tokio::test] +async fn test_read_row_sequence_splits_one_file_by_the_expression_of_each_row() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_by_row_expression").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: five rows of the left expression (numbers 1..5) and one row + // of the right one (number 6). + 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(); + let mut rows = test_util::build_rows_for_key("1", 0, 5, 0); + rows.extend(test_util::build_rows_for_key("6", 5, 6, 0)); + test_util::put_rows(&engine, source, Rows { schema, rows }).await; + test_util::flush_region(&engine, source, None).await; + + let mut source_file = manifest_files(&engine, source) + .await + .into_values() + .next() + .expect("flushed file"); + // The coarse expression the file was written under: it holds rows of both slices. + source_file.partition_expr = Some(partition_str_slice("0", "9").into()); + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 7, true, None); + + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + partition_str_slice_cursor("0", "5", 5), + partition_str_slice_cursor("5", "9", 2), + ], + 1, + 20, + ), + ) + .await; + + assert_eq!( + vec![(5000, 6)], + rows, + "the row at 6 belongs to the slice consumed up to 2 and must be delivered; the rows \ + at 3, 4 and 5 belong to the slice consumed up to 5 and must not be delivered again" + ); + + // The same read with only `field_0` projected: the tag column the slice expressions + // reference is added to the read columns as an internal column, so the per-row decision + // still works and the output schema stays the projected one. + let mut request = creator_cursor_scan( + source, + vec![ + partition_str_slice_cursor("0", "5", 5), + partition_str_slice_cursor("5", "9", 2), + ], + 1, + 20, + ); + request.projection = Some(vec![1]); + let rows = scan_flat_row_sequences(&engine, target, request).await; + assert_eq!( + vec![(5000, 6)], + rows, + "the partition column is read even though the scan does not project it" + ); +} + +/// 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. +/// +/// The region's own pieces are the only candidates, because a memtable holds the rows this +/// region allocated. The rows of the piece consumed up to 5 (the rows at 3, 4 and 5) are +/// not delivered again, and the row at 6 of the piece consumed up to 2 still is. +#[tokio::test] +async fn test_read_row_sequence_splits_memtable_rows_by_the_expression_of_each_row() { + let mut env = + TestEnv::with_prefix("test_read_row_sequence_splits_memtable_rows_by_expression").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + // Five rows of the left expression (numbers 1..5) and one row of the right one + // (number 6), all of them in the memtable: no flush, so no file takes part in the read. + // The primary-key SST format keeps the time-series memtable (the flat format would put + // the rows in the bulk memtable, which does not apply the per-piece rule), and + // `preserve_row_sequence` keeps the exact `(C, H]` delta admissible. + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .insert_option("sst_format", "primary_key") + .build(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(region, RegionRequest::Create(request)) + .await + .unwrap(); + let mut rows = test_util::build_rows_for_key("1", 0, 5, 0); + rows.extend(test_util::build_rows_for_key("6", 5, 6, 0)); + test_util::put_rows(&engine, region, Rows { schema, rows }).await; + + // One cursor value for every piece: the delivered rows are exactly the rows above the + // region-level floor 2, which is what the read delivered before the per-row rule. + let mut rows = scan_flat_row_sequences( + &engine, + region, + creator_cursor_scan( + region, + vec![ + partition_str_slice_cursor("0", "5", 2), + partition_str_slice_cursor("5", "9", 2), + ], + 2, + 20, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(2000, 3), (3000, 4), (4000, 5), (5000, 6)], + rows, + "one cursor value for every piece is the region-level floor of the whole read" + ); + + // The pieces advanced differently: the rows of the left one (3, 4 and 5) are consumed, + // the row at 6 belongs to the right one and stays live. + let mut rows = scan_flat_row_sequences( + &engine, + region, + creator_cursor_scan( + region, + vec![ + partition_str_slice_cursor("0", "5", 5), + partition_str_slice_cursor("5", "9", 2), + ], + 2, + 20, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(5000, 6)], + rows, + "each memtable row is filtered by the cursor of the piece it belongs to: the rows at \ + 3, 4 and 5 were consumed by the piece advanced to 5, the row at 6 was not" + ); +} + +/// 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. +/// +/// As above, the rows of the piece consumed up to 5 (3, 4 and 5) are not delivered again +/// while the row at 6 of the piece consumed up to 2 still is. +#[tokio::test] +async fn test_read_row_sequence_splits_bulk_memtable_rows_by_the_expression_of_each_row() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_bulk_memtable_rows").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + // Five rows of the left expression (numbers 1..5) and one row of the right one + // (number 6), all of them in the bulk memtable: no flush, so no file takes part in the + // read, and `preserve_row_sequence` keeps the exact `(C, H]` delta admissible. + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .insert_option("memtable.type", "bulk") + .build(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(region, RegionRequest::Create(request)) + .await + .unwrap(); + let mut rows = test_util::build_rows_for_key("1", 0, 5, 0); + rows.extend(test_util::build_rows_for_key("6", 5, 6, 0)); + test_util::put_rows(&engine, region, Rows { schema, rows }).await; + + // The rows really are in a bulk memtable, so the read below goes through a bulk part + // and the per-row rule there, not through the time-series memtable. + assert!( + matches!( + engine + .get_region(region) + .unwrap() + .version_control + .current() + .version + .options + .memtable, + Some(crate::region::options::MemtableOptions::Bulk(_)) + ), + "the region must hold the bulk memtable" + ); + + // One cursor value for every piece: the delivered rows are exactly the rows above the + // region-level floor 2, which is what the read delivered before the per-row rule. + let mut rows = scan_flat_row_sequences( + &engine, + region, + creator_cursor_scan( + region, + vec![ + partition_str_slice_cursor("0", "5", 2), + partition_str_slice_cursor("5", "9", 2), + ], + 2, + 20, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(2000, 3), (3000, 4), (4000, 5), (5000, 6)], + rows, + "one cursor value for every piece is the region-level floor of the whole read" + ); + + // The pieces advanced differently: the rows of the left one (3, 4 and 5) are consumed, + // the row at 6 belongs to the right one and stays live. + let mut rows = scan_flat_row_sequences( + &engine, + region, + creator_cursor_scan( + region, + vec![ + partition_str_slice_cursor("0", "5", 5), + partition_str_slice_cursor("5", "9", 2), + ], + 2, + 20, + ), + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![(5000, 6)], + rows, + "each bulk memtable row is filtered by the cursor of the piece it belongs to: the \ + rows at 3, 4 and 5 were consumed by the piece advanced to 5, the row at 6 was not" + ); +} + +/// A `cut = None` adopted file is filtered by the creator's cursor exactly like one that +/// states a cut. Its numbers were allocated in the creator's domain whether or not a +/// substitution touched them, so the holder's own `(C, H]` neither bounds them nor may +/// replace the creator's slice. +#[tokio::test] +async fn test_read_row_sequence_filters_adopted_file_without_cut_by_creator_cursor() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_adopted_without_cut").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + // The creator consumed up to 3, so only its rows 4 and 5 are still owed. The holder's + // own cursor (0 in this scan) would deliver all five again. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(3)], 0, 10), + ) + .await; + assert_eq!( + vec![(3000, 4), (4000, 5)], + rows, + "an adopted file without a cut is still bounded by the creator's cursor" + ); +} diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 129de154faa..329465e0ba8 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -60,7 +60,7 @@ use store_api::region_request::{ }; use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME; use store_api::storage::{ - FileId, RegionId, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector, + CursorShard, FileId, RegionId, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector, }; use crate::config::MitoConfig; @@ -1105,9 +1105,12 @@ async fn test_flush_aligns_different_json2_layouts() -> WhateverResult<()> { Ok(()) } +/// A cursor below the flushed frontier is rejected by the **flushed-frontier fence**, not by +/// an edit boundary: `last_invalid_seq` is gone, so the `min_readable_seq` the error reports +/// is `flushed_sequence`. An incremental read at the frontier serves the rows above it. #[tokio::test] -async fn test_incremental_query_stale_error() { - let mut env = TestEnv::with_prefix("test_incremental_query_stale_error").await; +async fn test_incremental_read_below_flushed_frontier_is_rejected_by_the_frontier() { + let mut env = TestEnv::with_prefix("test_incremental_read_below_flushed_frontier").await; let engine = env.create_engine(MitoConfig::default()).await; let region_id = RegionId::new(1, 1); @@ -1126,6 +1129,14 @@ async fn test_incremental_query_stale_error() { test_util::put_rows(&engine, region_id, rows).await; test_util::flush_region(&engine, region_id, None).await; + // A cursor at 0 is below the flushed frontier (3), so the frontier fence rejects it and + // names the frontier as the minimum readable sequence. + let flushed = engine + .get_region(region_id) + .unwrap() + .version() + .flushed_sequence; + assert_eq!(3, flushed); let err = engine .scanner( region_id, @@ -1136,40 +1147,32 @@ async fn test_incremental_query_stale_error() { ) .await .err() - .expect("expect stale incremental error"); - - let min_readable_seq = match &err { - Error::IncrementalQueryStale { - region_id: err_region_id, - given_seq, - min_readable_seq, - .. - } => { - assert_eq!(*err_region_id, region_id); - assert_eq!(*given_seq, 0); - assert!(*min_readable_seq > 0); - *min_readable_seq - } - _ => panic!("unexpected err: {err}"), - }; + .expect("a cursor below the flushed frontier is rejected by the frontier fence"); + assert!( + matches!( + err, + Error::IncrementalQueryStale { + given_seq: 0, + min_readable_seq, + .. + } if min_readable_seq == flushed + ), + "the fence reports the flushed frontier, not an edit boundary: {err}" + ); assert_eq!(StatusCode::RequestOutdated, err.status_code()); - let err_msg = err.to_string(); - assert!(err_msg.contains("STALE_CURSOR")); - assert!(err_msg.contains(®ion_id.to_string())); - assert!(err_msg.contains("given_seq: 0")); - assert!(err_msg.contains(&format!("min_readable_seq: {min_readable_seq}"))); - let incremental_rows = Rows { + let memtable_only_rows = Rows { schema: column_schemas, rows: test_util::build_rows(3, 5), }; - test_util::put_rows(&engine, region_id, incremental_rows).await; + test_util::put_rows(&engine, region_id, memtable_only_rows).await; + // An incremental read above the flushed frontier serves exactly the rows above it. let scanner = engine .scanner( region_id, ScanRequest { - memtable_min_sequence: Some(min_readable_seq), + memtable_min_sequence: Some(flushed), skip_sst_files: true, ..Default::default() }, @@ -1247,6 +1250,165 @@ async fn test_full_snapshot_upper_bound_returns_outdated_after_late_flush() { assert!(err_msg.contains(&format!("given_seq: {snapshot_upper_bound}"))); } +/// A scan states the creators of the files another region left in its file list: a read that +/// prunes every file away still says which regions' rows the region may hold, and says the empty +/// set when every visible file is its own. +#[tokio::test] +async fn test_snapshot_identity_states_visible_foreign_file_creators() { + let mut env = TestEnv::with_prefix("test_snapshot_identity_file_creators").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let region_id = RegionId::new(1, 1); + let foreign_creator = RegionId::new(1, 2); + let request = CreateRequestBuilder::new().build(); + let column_schemas = test_util::rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + test_util::put_rows( + &engine, + region_id, + Rows { + schema: column_schemas, + rows: test_util::build_rows(0, 3), + }, + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + + // Every visible file was created by the region itself: a positive "nothing foreign" answer. + let own = engine + .handle_query(region_id, ScanRequest::default()) + .await + .unwrap() + .snapshot_identity() + .expect("a mito scan states its snapshot identity"); + assert_eq!(Some(Vec::new()), own.visible_foreign_file_creators); + + // Publish a file another region created into this region's file list, which is what a + // repartition leaves behind. + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![FileMeta { + region_id: foreign_creator, + file_id: FileId::random(), + time_range: ( + Timestamp::new_millisecond(0), + Timestamp::new_millisecond(1000), + ), + level: 0, + file_size: 0, + max_row_group_uncompressed_size: 0, + available_indexes: Default::default(), + indexes: vec![], + index_file_size: 0, + index_version: 0, + num_rows: 0, + num_row_groups: 0, + sequence: None, + partition_expr: None, + num_series: 0, + preserve_row_sequence: true, + ..Default::default() + }], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + ..Default::default() + }, + ) + .await + .unwrap(); + + // A read whose time range prunes everything still states the creator: the file list is read + // from the version in memory, before any pruning. + let pruned = engine + .handle_query( + region_id, + ScanRequest { + filters: vec![col("ts").gt(lit(Timestamp::new_millisecond(i64::MAX / 2).value()))], + ..Default::default() + }, + ) + .await + .unwrap() + .snapshot_identity() + .expect("a mito scan states its snapshot identity"); + assert_eq!( + Some(vec![foreign_creator.as_u64()]), + pruned.visible_foreign_file_creators + ); +} + +/// A scan states the partition expression of the **one** version whose `committed_sequence` it +/// bound as its upper bound, in the canonical form a flow cursor entry is keyed by - and states +/// the region's whole domain as `None` when that version has no expression. +#[tokio::test] +async fn test_snapshot_identity_states_the_partition_expr_of_the_bound_version() { + let mut env = TestEnv::with_prefix("test_snapshot_identity_partition_expr").await; + let engine = env.create_engine(MitoConfig::default()).await; + + // Value-first shape: the identity a cursor entry keys must be canonicalized before it is + // stated, or the same slice would be keyed two ways. + let expr_json = + r#"{"Expr":{"lhs":{"Value":{"String":"k5"}},"op":"Gt","rhs":{"Column":"tag_0"}}}"#; + let partitioned = RegionId::new(1, 1); + let unpartitioned = RegionId::new(1, 2); + for (region_id, request) in [ + ( + partitioned, + CreateRequestBuilder::new() + .partition_expr_json(Some(expr_json.to_string())) + .build(), + ), + (unpartitioned, CreateRequestBuilder::new().build()), + ] { + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + } + + let expected_snapshot = engine.get_committed_sequence(partitioned).await.unwrap(); + let scanner = engine + .handle_query( + partitioned, + ScanRequest { + snapshot_on_scan: true, + ..Default::default() + }, + ) + .await + .unwrap(); + let identity = scanner + .snapshot_identity() + .expect("a mito scan states its snapshot identity"); + let expected_identity = partition::expr::PartitionExpr::from_json_str(expr_json) + .unwrap() + .unwrap() + .as_json_str() + .unwrap(); + assert_eq!(Some(expected_snapshot), identity.bound_sequence); + assert_eq!(Some(expected_identity), identity.partition_expr); + + // One version, both fields: the sequence the trait reports is the identity's bound. + assert_eq!(scanner.snapshot_sequence(), identity.bound_sequence); + + let whole_domain = engine + .handle_query(unpartitioned, ScanRequest::default()) + .await + .unwrap() + .snapshot_identity() + .expect("a mito scan states its snapshot identity"); + assert_eq!(None, whole_domain.partition_expr); +} + #[tokio::test] async fn test_snapshot_bound_query_binds_memtable_upper_bound_at_scan_open() { let mut env = @@ -3182,7 +3344,12 @@ async fn test_exact_sequence_range_unsupported_when_legacy_file() { committed_sequence: None, ..Default::default() }; - engine.edit_region(region_id, edit).await.unwrap(); + // Absorb the file through a flush-shaped edit, which is how a legacy unmarked + // SST appears. + let region = engine.get_region(region_id).unwrap(); + region + .version_control + .apply_edit(Some(edit), &[], region.file_purger.clone()); let err = engine .scanner( @@ -3206,12 +3373,12 @@ async fn test_exact_sequence_range_unsupported_when_legacy_file() { /// Region edit assigns a target-local barrier to an imported foreign SST, so /// exact sequence-range capability can admit it without trusting its source -/// region marker. +/// region marker: below the barrier the edit layer cannot disprove that the rows +/// were renumbered, so the read stays unsupported; at the barrier the file is +/// provably consumed. #[tokio::test] -async fn test_exact_sequence_range_accepts_foreign_file_with_target_barrier() { - let mut env = - TestEnv::with_prefix("test_exact_sequence_range_accepts_foreign_file_with_target_barrier") - .await; +async fn test_exact_sequence_range_gates_foreign_file_with_barrier() { + let mut env = TestEnv::with_prefix("test_exact_sequence_range_gates_foreign_file").await; let engine = env.create_engine(MitoConfig::default()).await; let region_id = RegionId::new(1, 1); @@ -3287,18 +3454,44 @@ async fn test_exact_sequence_range_accepts_foreign_file_with_target_barrier() { "region edit must assign a target-local barrier" ); + // The edit allocated `last_sequence + 1` = 4 as the file barrier: a cursor at 3 + // cannot prove the adopted rows are consumed. + let boundary = foreign_file + .meta_ref() + .sequence + .map(|sequence| sequence.get()) + .expect("region edit assigned the barrier"); + assert_eq!(4, boundary); engine .scanner( region_id, ScanRequest { - memtable_min_sequence: Some(3), - memtable_max_sequence: Some(4), + memtable_min_sequence: Some(boundary - 1), + memtable_max_sequence: Some(boundary), exact_sequence_range: true, ..Default::default() }, ) .await - .expect("foreign file with target barrier should be exact-capable"); + .expect("a cursor below the file barrier is served by row-level filtering"); + // The stale-cursor rejection went away with `last_invalid_seq`: the adopted file's own + // barrier keeps the exact range available, so the rows are filtered row by row instead + // of the whole read being refused. + + // At the boundary the foreign file is provably fully consumed, so it cannot + // break the exact capability even though its source marker is foreign. + engine + .scanner( + region_id, + ScanRequest { + memtable_min_sequence: Some(boundary), + memtable_max_sequence: Some(boundary + 1), + exact_sequence_range: true, + ..Default::default() + }, + ) + .await + .expect("foreign file with target barrier should be exact-capable at the boundary"); } /// Exact sequence-range reads only require preserved row sequences in the @@ -4524,10 +4717,22 @@ async fn test_compaction_output_non_preserve_not_laundered_from_legacy_input( "unexpected error: {err:?}" ); } else { + // No flush after the edit, so the flushed frontier cannot fire. The + // edit-boundary rejection went away with `last_invalid_seq`; what is left + // is the exact-sequence rule: the adopted files carry no trusted per-row + // numbering, so the range stays unproven and the read fails closed. assert!( - matches!(err, Error::SequenceRangeUnsupported { .. }), + matches!( + err, + Error::SequenceRangeUnsupported { + min_seq: 6, + max_seq: 7, + .. + } + ), "unexpected error: {err:?}" ); + assert_eq!(StatusCode::Unsupported, err.status_code()); } // Once C reaches the barrier the untrusted file is skipped, so exact @@ -5514,6 +5719,1649 @@ fn scan_field_values(batches: &[common_recordbatch::RecordBatch]) -> Vec { .collect() } +/// A read that may cross an invalid boundary virtualizes every selected file's rows at +/// the file's own admission barrier, even for a local file whose +/// `preserve_row_sequence` marker is off: such a read must not depend on the file's +/// row-level sequences being trusted. +#[tokio::test] +async fn test_read_across_invalid_boundary_forces_sequence_override() { + let mut env = + TestEnv::with_prefix("test_read_across_invalid_boundary_forces_sequence_override").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + let column_schemas = test_util::rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + + test_util::put_rows( + &engine, + region_id, + Rows { + schema: column_schemas, + rows: test_util::build_rows(0, 3), + }, + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + + // Re-admit the same file id unmarked: the edit clears `preserve_row_sequence` + // and moves the barrier to the next sequence. + let region = engine.get_region(region_id).unwrap(); + let file_meta = region + .version() + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .next() + .expect("flushed SST") + .meta_ref() + .clone(); + let mut readmit = file_meta; + readmit.preserve_row_sequence = false; + readmit.sequence = None; + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![readmit], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + ..Default::default() + }, + ) + .await + .unwrap(); + let version = engine.get_region(region_id).unwrap().version(); + let file_barrier = version + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .next() + .expect("admitted SST") + .meta_ref() + .sequence + .expect("edit assigns a barrier") + .get(); + assert!(file_barrier > 0); + assert!( + !version + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .all(|file| file.meta_ref().preserve_row_sequence) + ); + + // Discovery reads the file anyway and every row's sequence is the barrier. + let stream = engine + .scan_to_stream( + region_id, + ScanRequest { + memtable_min_sequence: Some(file_barrier - 1), + exact_sequence_range: true, + read_across_invalid_boundary: true, + ..Default::default() + }, + ) + .await + .expect("a read across an invalid boundary must admit an unmarked file"); + let batches = RecordBatches::try_collect(stream).await.unwrap(); + assert_eq!( + 3, + batches.iter().map(|batch| batch.num_rows()).sum::(), + "a read across an invalid boundary reads every row of the unmarked file instead of failing closed" + ); +} + +/// A read that may cross an invalid boundary must report an empty candidate set instead +/// of silently reporting "no window"; the caller decides whether to accept it or advance +/// the cursor instead. +#[tokio::test] +async fn test_read_across_invalid_boundary_reports_empty_candidates() { + let mut env = + TestEnv::with_prefix("test_read_across_invalid_boundary_reports_empty_candidates").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + + let err = engine + .scanner( + region_id, + ScanRequest { + memtable_min_sequence: Some(0), + exact_sequence_range: true, + read_across_invalid_boundary: true, + ..Default::default() + }, + ) + .await + .err() + .expect("an empty candidate set must be reported"); + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "unexpected err: {err}" + ); + let msg = err.to_string(); + assert!( + msg.starts_with("exact sequence range unavailable:"), + "unexpected err msg: {msg}" + ); + assert!(msg.contains("no candidate file above the cursor"), "{msg}"); +} + +/// A discovery read (`read_across_invalid_boundary`) applies no lower sequence bound to +/// memtables, while an ordinary incremental read keeps its own. +/// +/// This is the shape a merge of regions produces: the merged region admits rows that the +/// old cursor cannot explain (staging writes that the old partition expression does not +/// select, or rows whose numbers the region can no longer vouch for). A lower bound of +/// `C` would hide exactly those rows, so their windows would never be reported and a +/// repair would advance the cursor past them. Discovery therefore reads them; the +/// ordinary delta keeps hiding everything at or below its cursor. +#[tokio::test] +async fn test_read_across_invalid_boundary_reads_memtable_rows_below_cursor() { + let mut env = TestEnv::with_prefix("test_read_across_invalid_boundary_memtable").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .build(); + let column_schemas = test_util::rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + + // Rows 0..3 are flushed (their numbers are 1..3), rows 3..5 stay in the memtable + // with the numbers 4 and 5. + test_util::put_rows( + &engine, + region_id, + Rows { + schema: column_schemas.clone(), + rows: test_util::build_rows(0, 3), + }, + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + test_util::put_rows( + &engine, + region_id, + Rows { + schema: column_schemas, + rows: test_util::build_rows(3, 5), + }, + ) + .await; + + // The cursor is at 5: every memtable row is at or below it. + let ordinary = engine + .scanner( + region_id, + ScanRequest { + memtable_min_sequence: Some(5), + skip_sst_files: true, + ..Default::default() + }, + ) + .await + .unwrap(); + let batches = RecordBatches::try_collect(ordinary.scan().await.unwrap()) + .await + .unwrap(); + assert_eq!( + 0, + batches.iter().map(|batch| batch.num_rows()).sum::(), + "an ordinary delta must not deliver rows its cursor already consumed" + ); + + // The same cursor as a discovery read: the memtable rows are exactly the rows whose + // windows the cursor can no longer explain, so they must be visible. + let discovery = engine + .scanner( + region_id, + ScanRequest { + memtable_min_sequence: Some(5), + skip_sst_files: true, + read_across_invalid_boundary: true, + ..Default::default() + }, + ) + .await + .unwrap(); + let batches = RecordBatches::try_collect(discovery.scan().await.unwrap()) + .await + .unwrap(); + assert_eq!( + vec![("3", 3.0), ("4", 4.0)], + batches + .iter() + .flat_map(|batch| { + let tags = batch.column_by_name("tag_0").unwrap().as_string::(); + let fields = batch + .column_by_name("field_0") + .unwrap() + .as_primitive::(); + (0..batch.num_rows()) + .map(|row| (tags.value(row), fields.value(row))) + .collect::>() + }) + .collect::>(), + "discovery must see the rows at or below the cursor, or their windows are never reported" + ); +} + +/// A fenced repair DML has no incremental lower bound and no exact sequence-range +/// mode, so `H` bounds memtables only. If `H` is behind the flushed frontier, a +/// flush that landed after `H` was frozen would be aggregated into the repaired +/// window and counted again by the next round; the SST upper-bound fence must stay +/// in force. +#[tokio::test] +async fn test_fenced_repair_rejects_upper_bound_behind_flushed_frontier() { + let mut env = + TestEnv::with_prefix("test_fenced_repair_rejects_upper_bound_behind_flushed").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + let column_schemas = test_util::rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + + // A high watermark frozen before the write, then the write is flushed. + test_util::put_rows( + &engine, + region_id, + Rows { + schema: column_schemas.clone(), + rows: test_util::build_rows(0, 3), + }, + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + let frozen_high = 2; + let flushed_sequence = engine + .get_region(region_id) + .unwrap() + .version() + .flushed_sequence; + assert!(flushed_sequence > frozen_high); + + let err = engine + .scanner( + region_id, + ScanRequest { + memtable_max_sequence: Some(frozen_high), + ..Default::default() + }, + ) + .await + .err() + .expect("a fenced repair behind the flushed frontier must be rejected"); + assert!( + matches!( + err, + Error::SnapshotFenceStale { + given_seq, + min_enforceable_seq, + .. + } if given_seq == frozen_high && min_enforceable_seq == flushed_sequence + ), + "unexpected err: {err}" + ); + assert_eq!(StatusCode::RequestOutdated, err.status_code()); +} + +/// A scan whose cursor sits exactly on an SST's admission barrier keeps that file: without an +/// exact sequence range there is no file-granularity pruning by the cursor (even when a file's +/// own barrier is at or below it) and no row-level sequence range at all. Only a read that may +/// cross a boundary a stale cursor can no longer explain forces a row-sequence override, so this +/// read reports the numbers its writer allocated instead of virtualizing every row at the file's +/// barrier, and the rows below the barrier are read instead of being cut by a region-level +/// boundary. +#[tokio::test] +async fn test_scan_with_cursor_on_file_barrier_reads_the_complete_window() { + let mut env = + TestEnv::with_prefix("test_scan_with_cursor_on_file_barrier_reads_complete_window").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + let column_schemas = test_util::rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + + // Three rows land in an SST (sequences 1..=3, barrier 3) ... + test_util::put_rows( + &engine, + region_id, + Rows { + schema: column_schemas.clone(), + rows: test_util::build_rows(0, 3), + }, + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + // ... and three more stay in the memtable (sequences 4..=6). + test_util::put_rows( + &engine, + region_id, + Rows { + schema: column_schemas, + rows: test_util::build_rows(3, 6), + }, + ) + .await; + + let region = engine.get_region(region_id).unwrap(); + let file_barrier = region + .version() + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .next() + .expect("flushed SST") + .meta_ref() + .sequence + .expect("a flush admits its file") + .get(); + let frozen_high = region.version_control.current().last_sequence; + drop(region); + assert_eq!( + 3, file_barrier, + "the flush's barrier is the last number it wrote" + ); + assert!( + frozen_high > file_barrier, + "the memtable must hold rows above the file" + ); + + let mut rows = scan_flat_row_sequences( + &engine, + region_id, + ScanRequest { + // The cursor sits exactly on the file's barrier: an exact range would prune the + // whole file, while this plain scan keeps it. + memtable_min_sequence: Some(file_barrier), + memtable_max_sequence: Some(frozen_high), + ..Default::default() + }, + ) + .await; + rows.sort_unstable(); + assert_eq!( + vec![ + (0, 1), + (1_000, 2), + (2_000, 3), + (3_000, 4), + (4_000, 5), + (5_000, 6) + ], + rows, + "a plain scan keeps the rows below the cursor's barrier and reports the numbers their \ + writer allocated, not the file's barrier" + ); +} + +/// Creates a source region, writes `num_rows` rows of one series, flushes them, and returns the +/// flushed file plus its source file id. +/// +/// `preserve_row_sequence` selects the numbering the bytes carry: `true` gives every row the +/// number its writer allocated, `false` leaves the column at zero (a legacy import, which is +/// what a substituted cut of `Some(0)` describes). The returned handle is what a repartition +/// publishes in the target region: the bytes stay source-owned, so the target's reader has to +/// decide what to do with their sequence column. +pub(super) async fn build_foreign_source_file( + engine: &crate::engine::MitoEngine, + source: RegionId, + num_rows: usize, + preserve_row_sequence: bool, +) -> (FileId, FileMeta) { + let mut request_builder = CreateRequestBuilder::new().insert_option("append_mode", "true"); + if preserve_row_sequence { + request_builder = request_builder.insert_option("preserve_row_sequence", "true"); + } + let request = request_builder.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("0", 0, num_rows, 0), + }, + ) + .await; + test_util::flush_region(engine, source, None).await; + + let meta = engine + .get_region(source) + .unwrap() + .manifest_ctx + .manifest() + .await + .files + .values() + .next() + .expect("source file") + .as_ref() + .clone(); + assert_eq!( + preserve_row_sequence, meta.preserve_row_sequence, + "the source file must state the numbering its bytes carry" + ); + (meta.file_id, meta) +} + +/// Adopts `source_file` into `target` the way a repartition publishes it: still source-owned, +/// re-marked at the holder's admission barrier, with `cut` as the substituted bound of the +/// bytes and `preserve_row_sequence` as the design's supported marker. +pub(super) fn adopt_foreign_file( + engine: &crate::engine::MitoEngine, + target: RegionId, + source_file: FileMeta, + admission: u64, + preserve_row_sequence: bool, + cut: Option, +) -> FileHandle { + let region = engine.get_region(target).unwrap(); + let mut adopted = source_file; + adopted.sequence = std::num::NonZeroU64::new(admission); + adopted.preserve_row_sequence = preserve_row_sequence; + adopted.substituted_up_to = cut; + adopted.level = 0; + let handle = FileHandle::new(adopted.clone(), region.file_purger.clone()); + let edit = RegionEdit { + files_to_add: vec![adopted], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + ..Default::default() + }; + // Applied as a flush-shaped edit: the tests below exercise the reader, not the cursor. + region + .version_control + .apply_edit(Some(edit), &[], region.file_purger.clone()); + handle +} + +/// Creates the target region of a repartition with the same preserved-sequence option. +pub(super) async fn create_foreign_target(engine: &crate::engine::MitoEngine, target: RegionId) { + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + engine + .handle_request(target, RegionRequest::Create(request)) + .await + .unwrap(); +} + +/// Scans one partition through the region-scan path a datanode uses and returns the +/// timestamps of the surviving rows plus the substituted row ranges the scan reported. +/// +/// This is the path that carries proof with the result: `scan_partition`'s stream reports +/// its substituted ranges through `metrics()`, exactly like the snapshot watermark. +async fn scan_partition_substituted_row_ranges( + engine: &crate::engine::MitoEngine, + region_id: RegionId, + request: ScanRequest, +) -> ( + Vec, + Vec, +) { + use store_api::region_engine::QueryScanContext; + + let scanner = engine.handle_query(region_id, request).await.unwrap(); + let mut stream = scanner + .scan_partition( + &QueryScanContext::default(), + &ExecutionPlanMetricsSet::new(), + 0, + ) + .unwrap(); + let mut timestamps = Vec::new(); + while let Some(batch) = stream.try_next().await.unwrap() { + let column = batch + .column_by_name("ts") + .expect("time index column") + .clone(); + timestamps.extend_from_slice(crate::read::timestamp_array_to_i64_slice(&column)); + } + let substituted = stream + .metrics() + .map(|metrics| metrics.substituted_row_ranges) + .unwrap_or_default(); + (timestamps, substituted) +} + +/// Scans one partition and returns the `(region, expression slice)` pairs the scan +/// reported as read. +async fn scan_partition_observed_slices( + engine: &crate::engine::MitoEngine, + region_id: RegionId, + request: ScanRequest, +) -> Vec { + use store_api::region_engine::QueryScanContext; + + let scanner = engine.handle_query(region_id, request).await.unwrap(); + let mut stream = scanner + .scan_partition( + &QueryScanContext::default(), + &ExecutionPlanMetricsSet::new(), + 0, + ) + .unwrap(); + while stream.try_next().await.unwrap().is_some() {} + stream + .metrics() + .map(|metrics| metrics.observed_slices) + .unwrap_or_default() +} + +/// Scans every partition through the batch path, whose flat batches still carry the +/// physical `__sequence` column, and returns `(timestamp, sequence)` per surviving row. +pub(super) async fn scan_flat_row_sequences( + engine: &crate::engine::MitoEngine, + region_id: RegionId, + request: ScanRequest, +) -> Vec<(i64, u64)> { + use crate::read::stream::ScanBatch; + + let mut stream = engine.scan_batch(region_id, request, true).await.unwrap(); + let mut rows = Vec::new(); + while let Some(batch) = stream.try_next().await.unwrap() { + let ScanBatch::RecordBatch(batch) = batch else { + panic!("a flat scan yields record batches"); + }; + let num_columns = batch.num_columns(); + let timestamps = crate::read::timestamp_array_to_i64_slice(batch.column(num_columns - 4)); + let sequences = batch + .column(num_columns - 2) + .as_any() + .downcast_ref::() + .expect("sequence column"); + for (idx, sequence) in sequences.values().iter().enumerate() { + rows.push((timestamps[idx], *sequence)); + } + } + rows +} + +/// The exact `(C, H]` delta a physical-sequence read asks for: it needs a lower bound to +/// select files and an upper bound to prove the range. +/// +/// A physical-sequence read of a *foreign* file must carry the creator's cursor slices +/// ([`creator_cursor_scan`]); without them the read fails closed, because this region's +/// own bound does not describe the numbers in that file. +pub(super) fn physical_sequence_scan(read_row_sequence: bool) -> ScanRequest { + ScanRequest { + exact_sequence_range: true, + read_row_sequence, + memtable_min_sequence: Some(0), + memtable_max_sequence: Some(4), + ..Default::default() + } +} + +/// The exact `(creator cursor, H]` delta a physical-sequence read of an adopted file asks +/// for: the lower bound comes from the slices the *creator* region allocated, the upper +/// bound is this scan's own snapshot. +pub(super) fn creator_cursor_scan( + creator: RegionId, + shards: Vec, + min: u64, + max: u64, +) -> ScanRequest { + ScanRequest { + exact_sequence_range: true, + read_row_sequence: true, + memtable_min_sequence: Some(min), + memtable_max_sequence: Some(max), + creator_cursor_shards: Some(Arc::new(BTreeMap::from([(creator.as_u64(), shards)]))), + ..Default::default() + } +} + +/// The same read with a creator cursor that consumed nothing yet: what a scan of adopted +/// files carries, and what makes their rows comparable with the creator's domain at all. +fn adopted_physical_sequence_scan(creator: RegionId) -> ScanRequest { + creator_cursor_scan(creator, vec![CursorShard::whole_domain(0)], 0, 4) +} + +/// The partition expression a file states: `tag_0 >= lo AND tag_0 < hi`. +/// +/// The bounds are zero padded so that their lexicographic order (the order the string tag +/// column has) is their numeric order: the expression comparison normalizes each column's +/// values in that order, and `"100" < "50"` would otherwise make the range inverted. +pub(super) fn partition_slice(lo: u64, hi: u64) -> partition::expr::PartitionExpr { + partition_str_slice(&format!("{lo:03}"), &format!("{hi:03}")) +} + +/// The partition expression `tag_0 >= lo AND tag_0 < hi` over the string tag column of the +/// test schema. +/// +/// The bounds are strings because the reader compiles a partition expression into a row +/// filter of the column's own type: the tag column `k0` of the test schema is a string, so a +/// numeric bound would not be evaluable at all. +pub(super) fn partition_str_slice(lo: &str, hi: &str) -> partition::expr::PartitionExpr { + use datatypes::value::Value; + use partition::expr::{Operand, col as partition_col}; + + // `tag_0` is the string tag of the test schema (`[tag_0, field_0, ts]`). + partition_col("tag_0") + .gt_eq(Operand::Value(Value::String(lo.into()))) + .and(partition_col("tag_0").lt(Operand::Value(Value::String(hi.into())))) +} + +/// The identity a cursor slice carries for the expression `partition_slice(lo, hi)`. +fn partition_slice_identity(lo: u64, hi: u64) -> String { + partition_slice(lo, hi).as_json_str().unwrap() +} + +/// The cursor slice of `partition_slice(lo, hi)` consumed up to `seq`. +pub(super) fn partition_slice_cursor(lo: u64, hi: u64, seq: u64) -> CursorShard { + CursorShard::new(Some(partition_slice_identity(lo, hi)), seq) +} + +/// The cursor slice of `partition_str_slice(lo, hi)` consumed up to `seq`. +pub(super) fn partition_str_slice_cursor(lo: &str, hi: &str, seq: u64) -> CursorShard { + CursorShard::new( + Some(partition_str_slice(lo, hi).as_json_str().unwrap()), + seq, + ) +} + +/// An adopted file is filtered by the cursor of the region that allocated its numbers, not +/// by this region's own `(C, H]`: the numbers in its column never belonged to this region's +/// sequence space. Without that filter the file would be read whole and every row above its +/// substituted cut delivered again on every round. +#[tokio::test] +async fn test_read_row_sequence_filters_adopted_rows_by_creator_cursor() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_by_creator_cursor").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // The creator's file states the numbers 1, 2 and 3, and the cut 2 says a substitution + // produced the first two of them, so only the third is this file's own. + let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 4, true, Some(2)); + + // The region-keyed form of the cursor (one whole-domain slice) with cursor 1: every row + // the cut leaves is above it, so the cut alone decides what is delivered. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 1, 10), + ) + .await; + assert_eq!( + vec![(2000, 3)], + rows, + "the substituted rows are dropped and the row above the cursor is delivered" + ); + + // A cursor at 3 consumes the only row above the cut: the file delivers nothing. The + // reader before this change could not express that at all — it skipped the row filter + // of every adopted file because the holder's cursor does not bound these numbers. + let (timestamps, substituted) = scan_partition_substituted_row_ranges( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(3)], 1, 10), + ) + .await; + assert!( + timestamps.is_empty(), + "a row at or below the creator's cursor is already consumed" + ); + assert_eq!( + vec![common_recordbatch::adapter::SubstitutedRowRanges { + region_id: target.as_u64(), + ranges: vec![common_recordbatch::adapter::SubstitutedRange { + start_millis: 0, + end_millis: 1000, + }], + }], + substituted, + "the rows the cut hides are still reported for recomputation" + ); + + // Without a creator cursor the read fails closed instead of falling back to this + // region's own `(C, H]`: comparing the creator's numbers with a bound of another domain + // silently drops live rows, and reading the file unfiltered delivers every consumed row + // again. `test_read_row_sequence_fails_closed_without_creator_cursor` covers the error. +} + +/// Reads the manifest files of `region`. +pub(super) async fn manifest_files( + engine: &crate::engine::MitoEngine, + region: RegionId, +) -> HashMap { + engine + .get_region(region) + .unwrap() + .manifest_ctx + .manifest() + .await + .files + .iter() + .map(|(id, file)| (*id, file.as_ref().clone())) + .collect() +} + +/// A row whose number a substitution produced is hidden **and reported** by the substitution +/// rule (`SubstitutedRowRanges`), so per-row slice selection must leave it to that rule +/// instead of dropping it silently: its number says nothing about progress. +#[tokio::test] +async fn test_read_row_sequence_leaves_substituted_rows_to_the_cut() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_leaves_substituted_rows").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // Numbers 1..6, all in the left expression's domain, and the cut 3 says a substitution + // produced the first three of them. + let (_, source_file) = build_foreign_source_file(&engine, source, 6, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 7, true, Some(3)); + + // The left slice is consumed up to 2, so only the rows 4, 5 and 6 are above it; the + // substituted rows 1..3 are dropped by the cut and their window is reported. + let (timestamps, substituted) = scan_partition_substituted_row_ranges( + &engine, + target, + creator_cursor_scan( + source, + vec![ + partition_str_slice_cursor("", "5", 2), + partition_str_slice_cursor("5", "z", 0), + ], + 1, + 20, + ), + ) + .await; + assert_eq!( + vec![3000, 4000, 5000], + timestamps, + "the substituted rows are hidden by the cut, the rest is above the slice cursor" + ); + assert_eq!( + vec![common_recordbatch::adapter::SubstitutedRowRanges { + region_id: target.as_u64(), + ranges: vec![common_recordbatch::adapter::SubstitutedRange { + start_millis: 0, + end_millis: 2_000, + }], + }], + substituted, + "the substituted rows are still reported for recomputation" + ); +} + +/// A physical-sequence read keeps an adopted file's own column: with the switch on, the rows +/// carry the numbers their writer allocated (1, 2, 3), not the holder's admission barrier +/// (4). With the switch off the reader virtualizes every row at the barrier, which is the +/// behavior compaction and ordinary queries depend on. +#[tokio::test] +async fn test_read_row_sequence_keeps_physical_column_of_foreign_file() { + let mut env = + TestEnv::with_prefix("test_read_row_sequence_keeps_physical_column_of_foreign_file").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await; + create_foreign_target(&engine, target).await; + // The bytes carry no substitution, so nothing is substituted either way. + adopt_foreign_file(&engine, target, source_file, 4, true, None); + + let rows = + scan_flat_row_sequences(&engine, target, adopted_physical_sequence_scan(source)).await; + assert_eq!( + vec![(0, 1), (1000, 2), (2000, 3)], + rows, + "a physical-sequence read must keep the source's own numbering" + ); + + // The default reader substitutes the handle's barrier, which is why the design needs + // the switch: every row looks published by the import. + let rows = scan_flat_row_sequences(&engine, target, physical_sequence_scan(false)).await; + assert_eq!(vec![(0, 4), (1000, 4), (2000, 4)], rows); +} + +/// Rows whose number a substitution produced are substituted, and the ranges they occupy +/// are reported, so Flow recomputes them instead of counting them again. +#[tokio::test] +async fn test_read_row_sequence_hides_rows_below_substituted_cut() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_hides_rows_below_cut").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await; + create_foreign_target(&engine, target).await; + // Rows at or below 2 carry a substituted number; only the row at 3 is this file's own. + adopt_foreign_file(&engine, target, source_file, 4, true, Some(2)); + + let (timestamps, substituted) = scan_partition_substituted_row_ranges( + &engine, + target, + adopted_physical_sequence_scan(source), + ) + .await; + assert_eq!( + vec![2000], + timestamps, + "the two substituted rows must not reach the caller" + ); + assert_eq!( + vec![common_recordbatch::adapter::SubstitutedRowRanges { + region_id: target.as_u64(), + ranges: vec![common_recordbatch::adapter::SubstitutedRange { + start_millis: 0, + end_millis: 1000, + }], + }], + substituted, + "the ranges of the substituted rows must travel with the result" + ); + + // The surviving row carries its own number, not the barrier. + let rows = + scan_flat_row_sequences(&engine, target, adopted_physical_sequence_scan(source)).await; + assert_eq!(vec![(2000, 3)], rows); + + // With the switch off nothing is substituted and no range is reported: the query keeps + // today's substitution, which is what compaction and ordinary reads see. + let (timestamps, substituted) = + scan_partition_substituted_row_ranges(&engine, target, physical_sequence_scan(false)).await; + assert_eq!(vec![0, 1000, 2000], timestamps); + assert!(substituted.is_empty()); +} + +/// A legacy import states `Some(0)`: the column carries no per-row numbering at all, so every +/// row is substituted and the whole time range is reported. +#[tokio::test] +async fn test_read_row_sequence_hides_all_rows_of_legacy_cut() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_hides_all_rows_legacy_cut").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // A legacy file: its `__sequence` column carries no per-row numbering at all, which is + // exactly what the substituted cut `Some(0)` states. The import still re-marks the handle + // as trusted, so the physical read is admissible and every row is substituted. + let (_, source_file) = build_foreign_source_file(&engine, source, 3, false).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 4, true, Some(0)); + + let (timestamps, substituted) = scan_partition_substituted_row_ranges( + &engine, + target, + adopted_physical_sequence_scan(source), + ) + .await; + assert!(timestamps.is_empty(), "a legacy cut hides every row"); + assert_eq!( + vec![common_recordbatch::adapter::SubstitutedRowRanges { + region_id: target.as_u64(), + ranges: vec![common_recordbatch::adapter::SubstitutedRange { + start_millis: 0, + end_millis: 2000, + }], + }], + substituted, + "every substituted row is inside the reported range" + ); +} + +/// Raises the region's committed watermark to `sequence`, which is what an admission does: the +/// manifest handler stamps the imported files with `last_sequence + 1` and sets +/// `committed_sequence` to it in the same action list (`worker/handle_manifest.rs`). Local writes +/// that follow are therefore numbered above the constant the holder substitutes for the imported +/// rows, which is the state the reader below is written for. +fn raise_committed_watermark( + engine: &crate::engine::MitoEngine, + region_id: RegionId, + sequence: u64, +) { + let region = engine.get_region(region_id).unwrap(); + let edit = RegionEdit { + files_to_add: vec![], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: Some(sequence), + ..Default::default() + }; + region + .version_control + .apply_edit(Some(edit), &[], region.file_purger.clone()); +} + +/// A compaction output is a **local** file, and a local file states a substituted cut too: the +/// merge substitutes the handle bound of every foreign input for its rows and the output states +/// the bound the merge produced (`sst/file.rs::substituted_up_to_after_merge`). Those rows carry +/// a number this region never allocated, so the cut has to hide them here as well — a reader +/// that trusts "local means nothing is substituted" delivers them again on every round, and Flow +/// counts the same rows twice. +#[tokio::test] +async fn test_read_row_sequence_hides_substituted_rows_of_local_compaction_output() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_hides_local_compaction_cut").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await; + + // The holder of the repartition target, created the way `create_foreign_target` creates it. + // The request is kept because the test has to write a local row of the same schema. + 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(target, RegionRequest::Create(request)) + .await + .unwrap(); + // Admitted at barrier 4, with the cut 2 the bytes of the imported file carry. + adopt_foreign_file(&engine, target, source_file, 4, true, Some(2)); + raise_committed_watermark(&engine, target, 4); + + // One local row of the holder itself: the region numbers it 5, above the constant the + // reader substitutes for the imported rows. + test_util::put_rows( + &engine, + target, + Rows { + schema: schema.clone(), + rows: test_util::build_rows_for_key("0", 3, 4, 0), + }, + ) + .await; + test_util::flush_region(&engine, target, None).await; + + // Merge the imported and the local file, as a background compaction of the target would. + engine + .handle_request( + target, + RegionRequest::Compact(RegionCompactRequest { + options: compact_request::Options::StrictWindow(StrictWindow { + window_seconds: 60, + }), + parallelism: None, + time_range: None, + }), + ) + .await + .unwrap(); + + let version = engine.get_region(target).unwrap().version(); + let outputs = version + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .collect::>(); + assert_eq!(1, outputs.len(), "both input files are merged into one"); + let output = outputs[0].meta_ref(); + assert_eq!(target, output.region_id, "the output is a local file"); + // The merge read the imported rows at this region's own barrier (4), so that number is what + // they now carry, and the local row kept the number the region gave it (5). + assert_eq!(Some(4), output.substituted_up_to); + + // A cursor below the cut (0 < 4) must not be handed the rows the merge substituted: they are + // hidden and their time range is reported, so the caller recomputes exactly that window + // instead of receiving the rows a second time. + let (timestamps, substituted) = scan_partition_substituted_row_ranges( + &engine, + target, + ScanRequest { + exact_sequence_range: true, + read_row_sequence: true, + memtable_min_sequence: Some(0), + memtable_max_sequence: Some(5), + ..Default::default() + }, + ) + .await; + assert_eq!( + vec![3000], + timestamps, + "the three substituted rows must not be delivered again: only the local row survives" + ); + assert_eq!( + vec![common_recordbatch::adapter::SubstitutedRowRanges { + region_id: target.as_u64(), + ranges: vec![common_recordbatch::adapter::SubstitutedRange { + start_millis: 0, + end_millis: 2000, + }], + }], + substituted, + "the rows the cut of the local output hides are still reported for recomputation" + ); +} + +/// An exact `(C, H]` read of a region measured only by this request: both bounds are this +/// region's own numbers and the read keeps the physical sequence column. +fn local_exact_scan(min: u64, max: u64) -> ScanRequest { + ScanRequest { + exact_sequence_range: true, + read_row_sequence: true, + memtable_min_sequence: Some(min), + memtable_max_sequence: Some(max), + ..Default::default() + } +} + +/// A **local** file states a substitution as well: a merge substitutes a file-level constant +/// for the rows of its foreign inputs and records the bound it produced +/// (`sst/file.rs::substituted_up_to_after_merge`), so a local file may carry +/// `preserve_row_sequence = false` **and** a substituted cut. +/// +/// Such a file is attributable. The physical-sequence read hides the rows at or below the cut +/// and reports their time windows, and every row above the cut carries a number this region +/// allocated, which the scan's own `(C, H]` bounds row by row — so the region keeps serving +/// its exact range instead of failing every later delta closed. A local file with no marker +/// **and** no cut has nothing to attribute its rows with, and still fails closed. +#[tokio::test] +async fn test_read_row_sequence_keeps_exact_sequence_range_of_local_file_with_cut() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_local_file_with_cut").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + 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(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + test_util::put_rows( + &engine, + region_id, + Rows { + schema, + rows: test_util::build_rows_for_key("0", 0, 3, 0), + }, + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + + let file = engine + .get_region(region_id) + .unwrap() + .version() + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .next() + .expect("flushed file") + .meta_ref() + .clone(); + assert_eq!(region_id, file.region_id); + assert!(file.preserve_row_sequence); + + // The merge that produced this file substituted the constant 2 for the rows it took + // from a foreign input: those bytes carry 2, the row that stayed local carries 3. + let mut substituted = file.clone(); + substituted.preserve_row_sequence = false; + substituted.substituted_up_to = Some(2); + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![substituted.clone()], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + ..Default::default() + }, + ) + .await + .unwrap(); + + // The rows at or below the cut are hidden and reported, so the caller recomputes them + // instead of counting them again; the row above it is delivered. + let (timestamps, substituted_ranges) = + scan_partition_substituted_row_ranges(&engine, region_id, local_exact_scan(0, 4)).await; + assert_eq!(vec![2000], timestamps); + assert_eq!( + vec![common_recordbatch::adapter::SubstitutedRowRanges { + region_id: region_id.as_u64(), + ranges: vec![common_recordbatch::adapter::SubstitutedRange { + start_millis: 0, + end_millis: 1000, + }], + }], + substituted_ranges, + "the rows the cut hides are reported for recomputation" + ); + + // What remains is filtered by this region's own `(C, H]`: a cursor that already consumed + // the row above the cut receives nothing, which is the exactness the range promises. + let (timestamps, _) = + scan_partition_substituted_row_ranges(&engine, region_id, local_exact_scan(3, 4)).await; + assert!( + timestamps.is_empty(), + "a local file's rows above its cut are filtered by (C, H]" + ); + + // Without the cut the same file has nothing that attributes its rows, so the region + // refuses the exact range instead of delivering rows outside `(C, H]`. + let mut unmarked = substituted; + unmarked.substituted_up_to = None; + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![unmarked], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + ..Default::default() + }, + ) + .await + .unwrap(); + // The same request that was served above now has no evidence left: both bounds are still + // enforceable against the flushed frontier, so the capability check is what rejects it. + let err = engine + .scanner(region_id, local_exact_scan(3, 4)) + .await + .err() + .expect("a local file with no marker and no cut must deny the exact range"); + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "unexpected error: {err:?}" + ); +} + +/// An import re-marks an adopted file with `preserve_row_sequence = false` and copies its bytes +/// verbatim, so the column still carries the creator's numbers and the file's cut still says +/// which of them a substitution produced. A physical-sequence read must therefore ignore the +/// marker: it keeps the physical column and hides the rows the cut covers, and its own +/// substituted cut stays the only thing that decides what a Flow cursor may compare. +#[tokio::test] +async fn test_read_row_sequence_splits_imported_file_without_marker() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_imported_file").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await; + create_foreign_target(&engine, target).await; + // What an import of a file whose bytes already carry a substitution publishes: the handle + // is re-marked as marking nothing, holds barrier 4, and states the cut 2 the bytes carry. + adopt_foreign_file(&engine, target, source_file, 4, false, Some(2)); + + let (timestamps, substituted) = scan_partition_substituted_row_ranges( + &engine, + target, + adopted_physical_sequence_scan(source), + ) + .await; + assert_eq!( + vec![2000], + timestamps, + "the two substituted rows must not reach the caller even though the marker is off" + ); + assert_eq!( + vec![common_recordbatch::adapter::SubstitutedRowRanges { + region_id: target.as_u64(), + ranges: vec![common_recordbatch::adapter::SubstitutedRange { + start_millis: 0, + end_millis: 1000, + }], + }], + substituted, + "the ranges of the substituted rows must travel with the result" + ); + + // The surviving row carries the creator's number the bytes hold, not the barrier. + let rows = + scan_flat_row_sequences(&engine, target, adopted_physical_sequence_scan(source)).await; + assert_eq!(vec![(2000, 3)], rows); + + // With the switch off nothing changes: the reader substitutes the handle's barrier for + // every row and reports no window, which is what compaction and ordinary reads depend on. + let (timestamps, substituted) = + scan_partition_substituted_row_ranges(&engine, target, physical_sequence_scan(false)).await; + assert_eq!(vec![0, 1000, 2000], timestamps); + assert!(substituted.is_empty()); + let rows = scan_flat_row_sequences(&engine, target, physical_sequence_scan(false)).await; + assert_eq!(vec![(0, 4), (1000, 4), (2000, 4)], rows); +} + +/// 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. +/// +/// The counterexample this pins: the creator published the rows `10..=12` while its cursor +/// sits at 9, and the holder admitted the file at barrier 6 with its own cursor at 6. The +/// holder's range is then empty (`(6, 6]`) and its cursor stands exactly at the file's +/// admission barrier, so a filter or a file-pruning rule that uses either of them drops all +/// three live rows — for good, because both repeat on every round. +#[tokio::test] +async fn test_read_row_sequence_ignores_holder_bounds_for_foreign_file() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_foreign_bounds").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 12, true).await; + create_foreign_target(&engine, target).await; + // Admitted at barrier 6: below the numbers its bytes carry, which is the whole point. + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + // The creator consumed up to 9; the holder is caught up, so its cursor *and* its + // snapshot bound both stand at the file's admission barrier. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(9)], 6, 6), + ) + .await; + assert_eq!( + vec![(9000, 10), (10_000, 11), (11_000, 12)], + rows, + "the rows above the creator's cursor must be delivered although the holder's own \ + range is empty and the file sits at its admission barrier" + ); + + // The same file selected by a scan whose holder range is *not* empty: the creator's + // cursor still decides, so the holder's upper end must not truncate the file either. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(9)], 6, 7), + ) + .await; + assert_eq!( + vec![(9000, 10), (10_000, 11), (11_000, 12)], + rows, + "a holder bound above the barrier must not cut the creator's rows" + ); + + // A creator cursor below every row still filters: what the creator consumed is not + // delivered again, whether or not it is above the holder's bound. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(11)], 6, 6), + ) + .await; + assert_eq!( + vec![(11_000, 12)], + rows, + "row 11 is at the cursor, row 12 above it" + ); +} + +/// A physical row-sequence read needs the creator's cursor slice and the adopted file's +/// substituted cut, and the `PerSeries` distribution applies neither: its per-series readers +/// bound a file by this region's own `(C, H]` only, and its legacy distributor reads the +/// same files through the plain flat reader. The combination is therefore refused with the +/// shared "exactness is not provable" contract instead of being silently approximated. A +/// plain `PerSeries` read is unaffected. +#[tokio::test] +async fn test_read_row_sequence_rejects_per_series_distribution() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_rejects_per_series").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 4, true, Some(2)); + + // Every other reader of the same rows is untouched: an ordinary `PerSeries` read reads + // the file (substituted rows and all) through the per-series path. + let request = ScanRequest { + distribution: Some(TimeSeriesDistribution::PerSeries), + ..Default::default() + }; + let mut stream = engine.scan_batch(target, request, true).await.unwrap(); + let mut num_rows = 0; + while let Some(batch) = stream.try_next().await.unwrap() { + num_rows += match batch { + crate::read::stream::ScanBatch::RecordBatch(batch) => batch.num_rows(), + crate::read::stream::ScanBatch::Series(series) => series.num_rows(), + }; + } + assert_eq!(3, num_rows, "a plain PerSeries read must keep working"); + + // The physical-sequence read asks for the same distribution: refused at construction, + // before any file is opened. + let rejected = ScanRequest { + distribution: Some(TimeSeriesDistribution::PerSeries), + ..creator_cursor_scan(source, vec![CursorShard::whole_domain(0)], 0, 10) + }; + let err = match engine.scan_batch(target, rejected, true).await { + Ok(_) => panic!("read_row_sequence + PerSeries must be refused"), + Err(err) => err, + }; + 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 PerSeries distribution cannot carry a physical row-sequence read"), + "the refusal must name the combination: {message}" + ); +} + +/// The read reports which `(region, expression slice)` pairs it observed, so the owner of a +/// `(region, slice)` cursor can split a whole-domain entry and advance only the slices this +/// round actually read. A file whose expression cannot be read back states the region's +/// complete domain. +#[tokio::test] +async fn test_read_row_sequence_reports_observed_slices() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_observed_slices").await; + let engine = env.create_engine(MitoConfig::default()).await; + let narrow = RegionId::new(1, 2); + let coarse = RegionId::new(1, 3); + let target = RegionId::new(1, 1); + + // One creator's file states `[50, 100)`. + let (_, mut narrow_file) = build_foreign_source_file(&engine, narrow, 3, true).await; + narrow_file.partition_expr = Some(partition_slice(50, 100).into()); + // The other states no expression at all, so it can only be reported as the complete + // domain. + let (_, coarse_file) = build_foreign_source_file(&engine, coarse, 2, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, narrow_file, 4, true, None); + adopt_foreign_file(&engine, target, coarse_file, 5, true, None); + + let request = ScanRequest { + exact_sequence_range: true, + read_row_sequence: true, + memtable_min_sequence: Some(0), + memtable_max_sequence: Some(10), + creator_cursor_shards: Some(Arc::new(BTreeMap::from([ + (narrow.as_u64(), vec![CursorShard::whole_domain(0)]), + (coarse.as_u64(), vec![CursorShard::whole_domain(0)]), + ]))), + ..Default::default() + }; + let observed = scan_partition_observed_slices(&engine, target, request).await; + + let mut expected = vec![ + common_recordbatch::adapter::ObservedPartitionExpr::new( + narrow.as_u64(), + Some(partition_slice_identity(50, 100)), + ), + common_recordbatch::adapter::ObservedPartitionExpr::whole_domain(coarse.as_u64()), + ]; + expected.sort_unstable(); + assert_eq!( + expected, observed, + "every file the scan read reports its creator and the value domain it states" + ); +} + +/// Scans one partition the way a datanode does and returns the timestamps it delivered together +/// with the adopted files' creators its terminal metrics report. +pub(super) async fn scan_partition_rows_and_foreign_creators( + engine: &crate::engine::MitoEngine, + region_id: RegionId, + request: ScanRequest, +) -> (Vec, Option>) { + use store_api::region_engine::QueryScanContext; + + let scanner = engine.handle_query(region_id, request).await.unwrap(); + let mut stream = scanner + .scan_partition( + &QueryScanContext::default(), + &ExecutionPlanMetricsSet::new(), + 0, + ) + .unwrap(); + let mut timestamps = Vec::new(); + while let Some(batch) = stream.try_next().await.unwrap() { + let column = batch + .column_by_name("ts") + .expect("time index column") + .clone(); + timestamps.extend_from_slice(crate::read::timestamp_array_to_i64_slice(&column)); + } + let creators = stream + .metrics() + .and_then(|metrics| metrics.foreign_file_row_creators); + (timestamps, creators) +} + +/// A read of an adopted file names the region that created it, so a caller that must not count +/// a row above its creator's proved watermark learns that this read could have delivered one. +#[tokio::test] +async fn test_read_row_sequence_reports_foreign_file_row_creators() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_foreign_row_creators").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + let (timestamps, creators) = scan_partition_rows_and_foreign_creators( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 0, 10), + ) + .await; + + assert_eq!(vec![1000, 2000, 3000, 4000], timestamps); + assert_eq!( + Some(vec![source.as_u64()]), + creators, + "the rows of the adopted file reached the output, so its creator is named" + ); +} + +/// The base read of a repair is a **full** read: it carries no creator cursor and reads every +/// row of the adopted file. It still has to report that it did. +#[tokio::test] +async fn test_read_row_sequence_reports_foreign_file_row_creators_on_a_full_read() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_foreign_rows_full_read").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + // No `read_row_sequence`, no creator cursors: nothing filters the adopted file. + let (timestamps, creators) = + scan_partition_rows_and_foreign_creators(&engine, target, ScanRequest::default()).await; + + assert_eq!(vec![0, 1000, 2000, 3000, 4000], timestamps); + assert_eq!( + Some(vec![source.as_u64()]), + creators, + "a full read reads every row of the adopted file and says so" + ); +} + +/// A read that delivers no adopted row answers "none" instead of saying nothing: a caller can +/// tell the two apart only because the empty answer is stated, never defaulted. +#[tokio::test] +async fn test_read_row_sequence_reports_no_foreign_file_row_creators_for_a_local_read() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_no_foreign_row_creators").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + // A cursor of the creator's domain that has consumed every row the file states: the read + // opens the file and delivers nothing. + let (timestamps, creators) = scan_partition_rows_and_foreign_creators( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(5)], 0, 10), + ) + .await; + + assert!(timestamps.is_empty(), "{timestamps:?}"); + assert_eq!( + Some(Vec::new()), + creators, + "an opened file that delivered no row is not evidence of a delivered row, and the \ + answer is still stated" + ); +} + +/// A read that replays a cached range result does not open the files that produced its rows, so +/// it cannot say which other regions created them: it must answer "unknown" instead of the +/// "delivered none" an empty recorded set would say. +#[tokio::test] +async fn test_range_cache_replay_reports_unknown_foreign_file_row_creators() { + use std::time::Duration; + + let mut env = + TestEnv::with_prefix("test_range_cache_replay_unknown_foreign_row_creators").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); + + // A source region that is not in append mode: its reads go through the ordered scan, which + // is the one that reads and fills the range cache. + let request = CreateRequestBuilder::new().build(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(source, RegionRequest::Create(request.clone())) + .await + .unwrap(); + test_util::put_rows( + &engine, + source, + Rows { + schema, + rows: test_util::build_rows_for_key("0", 0, 5, 0), + }, + ) + .await; + test_util::flush_region(&engine, source, None).await; + let source_file = engine + .get_region(source) + .unwrap() + .manifest_ctx + .manifest() + .await + .files + .values() + .next() + .expect("source file") + .as_ref() + .clone(); + engine + .handle_request(target, RegionRequest::Create(request)) + .await + .unwrap(); + adopt_foreign_file(&engine, target, source_file, 6, false, None); + + // A tag filter selects every row of the file and makes the range eligible for the cache. + let scan = || ScanRequest { + filters: vec![col("tag_0").eq(lit(ScalarValue::Utf8(Some("0".to_string()))))], + ..Default::default() + }; + + // The first read opens the adopted file and names its creator. + let (cold_rows, cold_creators) = + scan_partition_rows_and_foreign_creators(&engine, target, scan()).await; + assert_eq!(vec![0, 1000, 2000, 3000, 4000], cold_rows); + assert_eq!(Some(vec![source.as_u64()]), cold_creators); + + // A later read of the same range replays the completed result once the publisher ran. It + // delivers the same rows without reading the file, so it states no creator at all. + let warm_creators = tokio::time::timeout(Duration::from_secs(10), async { + loop { + let (rows, creators) = + scan_partition_rows_and_foreign_creators(&engine, target, scan()).await; + assert_eq!(cold_rows, rows, "a replay delivers the rows it replayed"); + if creators.is_none() { + return creators; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the range result cache did not replay the range within the timeout"); + assert_eq!( + None, warm_creators, + "a replayed range did not open the files its rows came from, so its creators are \ + unknown rather than none" + ); +} + /// Raw Mito output contains candidates after projection, filtering, and MVCC read processing. #[tokio::test] async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 62efaf25b9d..295efd9530f 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -347,8 +347,13 @@ pub enum Error { location: Location, }, + /// The caller's incremental cursor cannot be trusted any more. + /// + /// The message keeps the stable `sequence range cursor invalid:` prefix the + /// enterprise incremental flow matches on to fall back to a full rebuild, + /// and the historical `STALE_CURSOR` token for existing log matchers. #[snafu(display( - "STALE_CURSOR: incremental query stale, region: {}, given_seq: {}, min_readable_seq: {}, retry_hint: FALLBACK_FULL_RECOMPUTE", + "sequence range cursor invalid: STALE_CURSOR: incremental query stale, region: {}, given_seq: {}, min_readable_seq: {}, retry_hint: FALLBACK_FULL_RECOMPUTE", region_id, given_seq, min_readable_seq @@ -375,8 +380,15 @@ pub enum Error { location: Location, }, + /// The region cannot prove that an exact `(min, max]` sequence read is + /// possible over its current files. + /// + /// Shares the stable `exact sequence range unavailable:` prefix with + /// [Self::RegionSequenceDomainBroken]; both mean "exactness is not + /// provable" to callers that must fall back, even though they keep + /// different status codes. #[snafu(display( - "SEQUENCE_RANGE_UNSUPPORTED: exact sequence-range read unsupported, region: {}, min_seq: {}, max_seq: {}, reason: {}, retry_hint: FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE", + "exact sequence range unavailable: SEQUENCE_RANGE_UNSUPPORTED: exact sequence-range read unsupported, region: {}, min_seq: {}, max_seq: {}, reason: {}, retry_hint: FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE", region_id, min_seq, max_seq, @@ -391,8 +403,14 @@ pub enum Error { location: Location, }, + /// A selected file carries rows from a foreign sequence domain and has no + /// admission barrier, so exactness cannot be proven at all. + /// + /// Shares the stable `exact sequence range unavailable:` prefix with + /// [Self::SequenceRangeUnsupported] so a caller can classify it without + /// depending on the (unchanged) status code. #[snafu(display( - "region {} is unusable for sequence reads: file {} declares region {}", + "exact sequence range unavailable: region {} cannot prove exact sequence-range reads: file {} declares region {} and carries no admission barrier, retry_hint: FALLBACK_FULL_RECOMPUTE", region_id, file_id, file_region_id diff --git a/src/mito2/src/memtable.rs b/src/mito2/src/memtable.rs index a63423cc92d..104fb98a457 100644 --- a/src/mito2/src/memtable.rs +++ b/src/mito2/src/memtable.rs @@ -28,6 +28,7 @@ use datatypes::arrow::record_batch::RecordBatch; use mito_codec::key_values::KeyValue; pub use mito_codec::key_values::KeyValues; use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec}; +use partition::expr::PartitionExpr; use snafu::ensure; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::{RegionMetadata, RegionMetadataRef}; @@ -95,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 { @@ -106,6 +117,20 @@ pub struct RangesOptions { pub predicate: PredicateGroup, /// Sequence range to filter the data. pub sequence: Option, + /// The cursor of each piece a row of this memtable may belong to, as + /// [`CreatorSliceCursor`] triples: `(partition expression, last consumed sequence, last + /// sequence the piece's delta covers)`. + /// + /// 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, /// Maximum number of rows readers should produce in one batch. pub batch_size: usize, } @@ -117,6 +142,7 @@ impl Default for RangesOptions { pre_filter_mode: PreFilterMode::All, predicate: PredicateGroup::default(), sequence: None, + creator_slices: None, batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE, } } @@ -130,6 +156,7 @@ impl RangesOptions { pre_filter_mode: PreFilterMode::All, predicate: PredicateGroup::default(), sequence: None, + creator_slices: None, batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE, } } @@ -155,6 +182,17 @@ impl RangesOptions { self } + /// Sets the cursor of each piece a row may belong to. + /// + /// See [`Self::creator_slices`]: the cursor of the piece a row belongs to replaces the + /// single floor of [`Self::sequence`], 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 { + self.creator_slices = creator_slices; + self + } + /// Sets the maximum number of rows readers should produce in one batch. #[must_use] pub fn with_batch_size(mut self, batch_size: usize) -> Self { @@ -163,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 25a7e428ac9..44f1bd5ddfc 100644 --- a/src/mito2/src/memtable/bulk.rs +++ b/src/mito2/src/memtable/bulk.rs @@ -58,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; @@ -535,6 +535,7 @@ impl Memtable for BulkMemtable { ) -> Result { let predicate = options.predicate; let sequence = options.sequence; + let creator_slices = options.creator_slices; let mut ranges = BTreeMap::new(); let mut range_id = 0; @@ -565,6 +566,7 @@ impl Memtable for BulkMemtable { part: unordered_bulk_part, context: context.clone(), sequence, + creator_slices: creator_slices.clone(), }), predicate.clone(), )), @@ -587,11 +589,13 @@ impl Memtable for BulkMemtable { part: part.clone(), context: context.clone(), sequence, + creator_slices: creator_slices.clone(), }), PartToMerge::Multi { part, .. } => Box::new(MultiBulkRangeIterBuilder { part: part.clone(), context: context.clone(), sequence, + creator_slices: creator_slices.clone(), }), PartToMerge::Encoded { part, file_id } => { Box::new(EncodedBulkRangeIterBuilder { @@ -599,6 +603,7 @@ impl Memtable for BulkMemtable { part: part.clone(), context: context.clone(), sequence, + creator_slices: creator_slices.clone(), }) } }; @@ -902,6 +907,8 @@ pub struct BulkRangeIterBuilder { pub part: BulkPart, pub context: Arc, pub sequence: Option, + /// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]). + pub creator_slices: Option, } /// Iterator builder for multi bulk range @@ -909,6 +916,8 @@ struct MultiBulkRangeIterBuilder { part: MultiBulkPart, context: Arc, sequence: Option, + /// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]). + creator_slices: Option, } impl IterBuilder for BulkRangeIterBuilder { @@ -940,7 +949,8 @@ impl IterBuilder for BulkRangeIterBuilder { self.sequence, series_count, metrics, - ); + ) + .with_creator_slices(self.creator_slices.clone()); Ok(Box::new(iter)) } @@ -971,10 +981,12 @@ impl IterBuilder for MultiBulkRangeIterBuilder { _time_range: Option<(Timestamp, Timestamp)>, metrics: Option, ) -> Result { - match self - .part - .read(self.context.clone(), self.sequence, metrics)? - { + match self.part.read( + self.context.clone(), + self.sequence, + self.creator_slices.clone(), + metrics, + )? { Some(iter) => Ok(iter), // All batches were pruned by the predicate. Return an empty iterator. None => Ok(Box::new(std::iter::empty())), @@ -996,6 +1008,8 @@ struct EncodedBulkRangeIterBuilder { part: EncodedBulkPart, context: Arc, sequence: Option, + /// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]). + creator_slices: Option, } impl IterBuilder for EncodedBulkRangeIterBuilder { @@ -1015,10 +1029,12 @@ impl IterBuilder for EncodedBulkRangeIterBuilder { _time_range: Option<(Timestamp, Timestamp)>, metrics: Option, ) -> Result { - if let Some(iter) = self - .part - .read(self.context.clone(), self.sequence, metrics)? - { + if let Some(iter) = self.part.read( + self.context.clone(), + self.sequence, + self.creator_slices.clone(), + metrics, + )? { Ok(iter) } else { // Return an empty iterator if no data to read @@ -1222,8 +1238,8 @@ impl PartToMerge { ); Some(Box::new(iter) as BoxedRecordBatchIterator) } - PartToMerge::Multi { part, .. } => part.read(context, None, None)?, - PartToMerge::Encoded { part, .. } => part.read(context, None, None)?, + PartToMerge::Multi { part, .. } => part.read(context, None, None, None)?, + PartToMerge::Encoded { part, .. } => part.read(context, None, None, None)?, }; if plans.is_empty() { Ok(iter) diff --git a/src/mito2/src/memtable/bulk/part.rs b/src/mito2/src/memtable/bulk/part.rs index 4b4fd626fb8..483050ad80d 100644 --- a/src/mito2/src/memtable/bulk/part.rs +++ b/src/mito2/src/memtable/bulk/part.rs @@ -68,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; @@ -1343,6 +1345,7 @@ impl EncodedBulkPart { &self, context: BulkIterContextRef, sequence: Option, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result> { // Compute skip_fields for row group pruning from the configured pre-filter mode. @@ -1363,7 +1366,8 @@ impl EncodedBulkPart { row_groups_to_read, sequence, mem_scan_metrics, - )?; + )? + .with_creator_slices(creator_slices); Ok(Some(Box::new(iter) as BoxedRecordBatchIterator)) } } @@ -1918,6 +1922,7 @@ impl MultiBulkPart { &self, context: BulkIterContextRef, sequence: Option, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result> { if self.batches.is_empty() { @@ -1936,7 +1941,8 @@ impl MultiBulkPart { sequence, self.series_count, mem_scan_metrics, - ); + ) + .with_creator_slices(creator_slices); Ok(Some(Box::new(iter) as BoxedRecordBatchIterator)) } @@ -2241,6 +2247,7 @@ mod tests { ), None, None, + None, ) .unwrap() .expect("expect at least one row group"); @@ -2301,7 +2308,7 @@ mod tests { .unwrap(), ); let reader = part - .read(context, None, None) + .read(context, None, None, None) .unwrap() .expect("expect at least one row group"); let mut total_rows_read = 0; @@ -2335,7 +2342,7 @@ mod tests { ) .unwrap(), ); - assert!(part.read(context, None, None).unwrap().is_none()); + assert!(part.read(context, None, None, None).unwrap().is_none()); check_prune_row_group(&part, None, 310); @@ -3584,7 +3591,7 @@ mod tests { .unwrap(), ); let reader = multi - .read(context, None, None) + .read(context, None, None, None) .unwrap() .expect("should have results"); let total_rows: usize = reader.map(|r| r.unwrap().num_rows()).sum(); @@ -3603,7 +3610,7 @@ mod tests { ) .unwrap(), ); - assert!(multi.read(context, None, None).unwrap().is_none()); + assert!(multi.read(context, None, None, None).unwrap().is_none()); // No predicate => all 6 rows. let context = Arc::new( @@ -3617,7 +3624,7 @@ mod tests { .unwrap(), ); let reader = multi - .read(context, None, None) + .read(context, None, None, None) .unwrap() .expect("should have results"); let total_rows: usize = reader.map(|r| r.unwrap().num_rows()).sum(); diff --git a/src/mito2/src/memtable/bulk/part_reader.rs b/src/mito2/src/memtable/bulk/part_reader.rs index b6da514e625..0428d3e8973 100644 --- a/src/mito2/src/memtable/bulk/part_reader.rs +++ b/src/mito2/src/memtable/bulk/part_reader.rs @@ -12,26 +12,42 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::VecDeque; +use std::collections::{HashSet, VecDeque}; +use std::ops::BitAnd; +use std::sync::Arc; use std::time::Instant; -use datatypes::arrow::array::BooleanArray; +use common_telemetry::debug; +use datatypes::arrow::array::{Array, ArrayRef, BooleanArray, BooleanBufferBuilder}; +use datatypes::arrow::buffer::BooleanBuffer; +use datatypes::arrow::datatypes::{Field, Schema}; use datatypes::arrow::record_batch::RecordBatch; +use datatypes::data_type::DataType; use mito_codec::row_converter::PrimaryKeyFilter; use parquet::arrow::ProjectionMask; use parquet::arrow::arrow_reader::ParquetRecordBatchReader; use snafu::ResultExt; -use store_api::storage::SequenceRange; +use store_api::codec::PrimaryKeyEncoding; +use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; -use crate::error::{self, ComputeArrowSnafu, DecodeArrowRowGroupSnafu}; +use crate::error::{ + self, ComputeArrowSnafu, DecodeArrowRowGroupSnafu, EvalPartitionFilterSnafu, + SequenceRangeUnsupportedSnafu, SerializePartitionExprSnafu, UnexpectedSnafu, +}; 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::{primary_key_column_index, sequence_column_index}; +use crate::sst::parquet::flat_format::{ + DecodedPrimaryKeys, decode_primary_keys, primary_key_column_index, sequence_column_index, +}; use crate::sst::parquet::prefilter::{CachedPrimaryKeyFilter, prefilter_flat_batch_by_primary_key}; +use crate::sst::tag_maybe_to_dictionary_field; /// Iterator for reading data inside a bulk part. pub struct EncodedBulkPartIter { @@ -41,6 +57,9 @@ pub struct EncodedBulkPartIter { builder: MemtableRowGroupReaderBuilder, /// Sequence number filter. sequence: Option, + /// Cursor of each piece a row of this part may belong to + /// ([`crate::memtable::RangesOptions::creator_slices`]). + creator_slices: Option, /// Cached skip_fields for current row group. current_skip_fields: bool, /// Primary key filter for prefiltering before convert_batch. @@ -92,6 +111,7 @@ impl EncodedBulkPartIter { current_reader: init_reader, builder, sequence, + creator_slices: None, current_skip_fields, pk_filter, metrics: MemScanMetricsData { @@ -108,6 +128,12 @@ 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 { + self.creator_slices = creator_slices; + self + } + /// Fetches next non-empty record batch. pub(crate) fn next_record_batch(&mut self) -> error::Result> { let start = Instant::now(); @@ -123,6 +149,7 @@ impl EncodedBulkPartIter { if let Some(batch) = apply_combined_filters( &self.context, &self.sequence, + self.creator_slices.as_deref().map(Vec::as_slice), batch, self.current_skip_fields, self.pk_filter @@ -151,6 +178,7 @@ impl EncodedBulkPartIter { if let Some(batch) = apply_combined_filters( &self.context, &self.sequence, + self.creator_slices.as_deref().map(Vec::as_slice), batch, self.current_skip_fields, self.pk_filter @@ -222,6 +250,9 @@ pub struct BulkPartBatchIter { context: BulkIterContextRef, /// Sequence number filter. sequence: Option, + /// Cursor of each piece a row of this part may belong to + /// ([`crate::memtable::RangesOptions::creator_slices`]). + creator_slices: Option, /// Primary key filter for prefiltering before convert_batch. pk_filter: Option, /// Metrics for this iterator. @@ -245,6 +276,7 @@ impl BulkPartBatchIter { batches: VecDeque::from(batches), context, sequence, + creator_slices: None, pk_filter, metrics: MemScanMetricsData { total_series: series_count, @@ -271,6 +303,12 @@ 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 { + self.creator_slices = creator_slices; + self + } + fn report_mem_scan_metrics(&mut self) { if let Some(mem_scan_metrics) = self.mem_scan_metrics.take() { mem_scan_metrics.merge_inner(&self.metrics); @@ -305,6 +343,7 @@ impl BulkPartBatchIter { let Some(filtered_batch) = apply_combined_filters( &self.context, &self.sequence, + self.creator_slices.as_deref().map(Vec::as_slice), projected_batch, skip_fields, self.pk_filter @@ -373,14 +412,21 @@ impl Drop for BulkPartBatchIter { } } -/// Applies both predicate filtering and sequence filtering in a single pass. +/// Applies the predicate, sequence and creator-cursor filtering in a single pass. /// Returns None if the filtered batch is empty. /// +/// `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 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<&[CreatorSliceCursor]>, record_batch: RecordBatch, skip_fields: bool, pk_filter: Option<&mut dyn PrimaryKeyFilter>, @@ -436,15 +482,16 @@ fn apply_combined_filters( let sequence_filter = sequence .filter(&sequence_column) .context(ComputeArrowSnafu)?; - // Combine with existing filter using AND operation - combined_filter = match combined_filter { - None => Some(sequence_filter), - Some(existing_filter) => { - let and_result = datatypes::arrow::compute::and(&existing_filter, &sequence_filter) - .context(ComputeArrowSnafu)?; - Some(and_result) - } - }; + combined_filter = Some(and_mask(combined_filter, sequence_filter)?); + } + + // 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)?); } // Apply the combined filter if any filters were applied @@ -466,6 +513,336 @@ fn apply_combined_filters( Ok(Some(filtered_batch)) } +/// Combines `next` into the mask accumulated so far with a logical AND. +fn and_mask(current: Option, next: BooleanArray) -> error::Result { + match current { + None => Ok(next), + Some(existing) => { + datatypes::arrow::compute::and(&existing, &next).context(ComputeArrowSnafu) + } + } +} + +/// Computes the mask of rows of `record_batch` a physical-sequence read has **not** consumed +/// yet, or `None` when the region-level bound is the whole rule. +/// +/// 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 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 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 and state no bound: that value is the region-level floor the read already states. +fn creator_slice_mask( + context: &BulkIterContext, + 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 sequence_column = record_batch.column(sequence_column_index(record_batch.num_columns())); + + // 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) + .min() + .unwrap_or_default(); + 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, + Err(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}"), + ); + } + }; + // 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()); + 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(); + let mut kept = BooleanBufferBuilder::new(num_rows); + let mut unmatched = 0; + 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 — 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); + } + kept.append(keep); + } + if unmatched > 0 { + debug!( + "{} 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: &[CreatorSliceCursor], + 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. +/// +/// The expressions are planned against a probe batch holding only the columns they +/// reference, the same way a physical-sequence read of an SST compiles them. Fails when a +/// referenced column is neither carried by the batch nor decodable from its primary key, or +/// when an expression cannot be planned or evaluated. +fn creator_slice_selection( + context: &BulkIterContext, + slices: &[CreatorSliceCursor], + record_batch: &RecordBatch, +) -> error::Result> { + let metadata = context.read_format().metadata(); + let mut referenced = HashSet::new(); + for (expr, ..) in slices { + expr.collect_column_names(&mut referenced); + } + + let mut fields = Vec::with_capacity(referenced.len()); + let mut columns = Vec::with_capacity(referenced.len()); + let mut decoded_pks: Option = None; + for column_metadata in &metadata.column_metadatas { + let name = &column_metadata.column_schema.name; + if !referenced.remove(name) { + continue; + } + let column_id = column_metadata.column_id; + let Some((field, column)) = + creator_slice_probe_column(context, column_id, record_batch, &mut decoded_pks)? + else { + return UnexpectedSnafu { + reason: format!( + "a creator cursor slice references column '{}' (id {}), which the bulk part batch neither carries nor encodes in its primary key", + name, column_id + ), + } + .fail(); + }; + fields.push(field); + columns.push(column); + } + if let Some(missing) = referenced.into_iter().next() { + return UnexpectedSnafu { + reason: format!( + "a creator cursor slice references column '{}', which this region does not have", + missing + ), + } + .fail(); + } + + 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 { + let filter = expr + .try_as_physical_expr(probe.schema_ref()) + .context(SerializePartitionExprSnafu)?; + let columnar_value = filter.evaluate(&probe).context(EvalPartitionFilterSnafu)?; + let array = columnar_value + .into_array(probe.num_rows()) + .context(EvalPartitionFilterSnafu)?; + let boolean = array + .as_any() + .downcast_ref::() + .ok_or_else(|| { + UnexpectedSnafu { + reason: format!( + "a partition expression must evaluate to a boolean array, got {:?}", + array.data_type() + ), + } + .build() + })?; + // A null result is "not selected", the same rule the region partition filter applies. + let mut mask = boolean.values().clone(); + if let Some(nulls) = boolean.nulls() { + mask = mask.bitand(nulls.inner()); + } + selected.push(mask); + } + + Ok(selected) +} + +/// Returns the field and the array of `column_id` for the rows of `record_batch`. +/// +/// The column is taken from the batch when the projection carries it, and otherwise decoded +/// from the primary key the batch states, the way the predicate filters resolve a tag +/// outside the projection. `None` means the column cannot be resolved at all. +fn creator_slice_probe_column( + context: &BulkIterContext, + column_id: ColumnId, + record_batch: &RecordBatch, + decoded_pks: &mut Option, +) -> error::Result, ArrayRef)>> { + if let Some(index) = context.read_format().projected_index_by_id(column_id) { + let Some(field) = record_batch.schema_ref().fields().get(index).cloned() else { + return Ok(None); + }; + + return Ok(Some((field, record_batch.column(index).clone()))); + } + + let metadata = context.read_format().metadata(); + let (Some(pk_index), Some(column_metadata)) = ( + metadata.primary_key_index(column_id), + metadata.column_by_id(column_id), + ) else { + return Ok(None); + }; + let decoded = match decoded_pks { + Some(decoded) => decoded, + None => decoded_pks.insert(decode_primary_keys( + context.base.codec.as_ref(), + record_batch, + )?), + }; + let pk_index = if context.base.codec.encoding() == PrimaryKeyEncoding::Sparse { + None + } else { + Some(pk_index) + }; + let data_type = &column_metadata.column_schema.data_type; + let column = decoded.get_tag_column(column_id, pk_index, data_type)?; + let field = tag_maybe_to_dictionary_field( + data_type, + &Arc::new(Field::new( + &column_metadata.column_schema.name, + data_type.as_arrow_type(), + column_metadata.column_schema.is_nullable(), + )), + ); + + Ok(Some((field, column))) +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -773,4 +1150,298 @@ 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, + None, + ), + ( + partition::expr::col("field1").lt(Operand::Value(Value::Int64(0))), + right, + None, + ), + ]; + 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" + ); + } + + /// 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/simple_bulk_memtable.rs b/src/mito2/src/memtable/simple_bulk_memtable.rs index 89c22f5e69c..827b54fa3c2 100644 --- a/src/mito2/src/memtable/simple_bulk_memtable.rs +++ b/src/mito2/src/memtable/simple_bulk_memtable.rs @@ -226,6 +226,7 @@ impl Memtable for SimpleBulkMemtable { ) -> error::Result { let predicate = options.predicate; let sequence = options.sequence; + let creator_slices = options.creator_slices; let start_time = Instant::now(); let read_column_ids = read_column_ids_from_projection(&self.region_metadata, projection); let projection = Arc::new(self.build_projection(projection)); @@ -256,11 +257,17 @@ impl Memtable for SimpleBulkMemtable { let contexts = values .into_par_iter() .filter_map(|v| { + // This memtable holds one series for the whole region and keeps no + // primary key, so a row cannot be attributed to a piece: the per-piece + // filter falls back to the least advanced cursor of the set, which is the + // region-level floor. let filtered = match v.to_batch( &[], &self.region_metadata, &projection, sequence, + creator_slices.as_deref().map(Vec::as_slice), + None, self.dedup, self.merge_mode, ) { diff --git a/src/mito2/src/memtable/time_series.rs b/src/mito2/src/memtable/time_series.rs index 1fa6cb24b15..8bf748601bf 100644 --- a/src/mito2/src/memtable/time_series.rs +++ b/src/mito2/src/memtable/time_series.rs @@ -37,7 +37,7 @@ use datatypes::vectors::{ TimestampNanosecondVector, TimestampSecondVector, UInt8Vector, UInt64Vector, }; use mito_codec::key_values::KeyValue; -use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodecExt}; +use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodec, PrimaryKeyCodecExt}; use snafu::{OptionExt, ResultExt, ensure}; use store_api::metadata::RegionMetadataRef; use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; @@ -53,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, @@ -370,6 +370,7 @@ impl Memtable for TimeSeriesMemtable { ) -> Result { let predicate = options.predicate; let sequence = options.sequence; + let creator_slices = options.creator_slices; let read_column_ids = read_column_ids_from_projection(&self.region_metadata, projection); let projection = if let Some(projection) = projection { projection.iter().copied().collect() @@ -390,6 +391,7 @@ impl Memtable for TimeSeriesMemtable { dedup: self.dedup, merge_mode: self.merge_mode, sequence, + creator_slices, batch_to_record_batch, }); let context = Arc::new(MemtableRangeContext::new(self.id, builder, predicate)); @@ -546,6 +548,7 @@ impl SeriesSet { } /// Iterates all series in [SeriesSet]. + #[allow(clippy::too_many_arguments)] fn iter_series( &self, projection: HashSet, @@ -553,6 +556,7 @@ impl SeriesSet { dedup: bool, merge_mode: MergeMode, sequence: Option, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result { let primary_key_schema = primary_key_schema(&self.region_metadata); @@ -573,6 +577,7 @@ impl SeriesSet { dedup, merge_mode, sequence, + creator_slices, mem_scan_metrics, ) } @@ -623,6 +628,9 @@ struct Iter { dedup: bool, merge_mode: MergeMode, sequence: Option, + /// The cursor of each piece a row may belong to, when this read states them + /// ([`RangesOptions::creator_slices`]). + creator_slices: Option, metrics: Metrics, mem_scan_metrics: Option, } @@ -640,6 +648,7 @@ impl Iter { dedup: bool, merge_mode: MergeMode, sequence: Option, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result { let predicate = predicate @@ -669,6 +678,7 @@ impl Iter { dedup, merge_mode, sequence, + creator_slices, metrics: Metrics::default(), mem_scan_metrics, }) @@ -742,12 +752,15 @@ impl Iterator for Iter { self.last_key = Some(primary_key.clone()); let values = series.compact(&self.metadata); + let creator_slices = self.creator_slices.as_deref().map(Vec::as_slice); let batch = values.and_then(|v| { v.to_batch( primary_key, &self.metadata, &self.projection, self.sequence, + creator_slices, + Some(self.codec.as_ref()), self.dedup, self.merge_mode, ) @@ -1221,12 +1234,21 @@ pub struct Values { impl Values { /// Converts [Values] to `Batch`, applies the optional sequence filter, sorts the batch /// according to `timestamp, sequence` desc, and applies dedup/merge according to `merge_mode`. + /// + /// `creator_slices` is the cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`]): when present, a row is additionally kept only + /// when its sequence is above the cursor of the piece its tag values fall into, which + /// replaces the single floor `sequence` states. `codec` decodes the primary key the + /// piece is resolved from. + #[allow(clippy::too_many_arguments)] pub fn to_batch( &self, primary_key: &[u8], metadata: &RegionMetadataRef, projection: &HashSet, sequence: Option, + creator_slices: Option<&[CreatorSliceCursor]>, + codec: Option<&dyn PrimaryKeyCodec>, dedup: bool, merge_mode: MergeMode, ) -> Result { @@ -1253,6 +1275,12 @@ impl Values { // - avoid dropping a timestamp when the newest row is out of range // - avoid filling null fields from rows that should be excluded by the sequence filter. batch.filter_by_sequence(sequence)?; + // The cursor of the piece this series belongs to replaces the single floor of + // `sequence`: the floor is the least advanced piece of the region, so it cannot tell + // a row of a more advanced piece from a consumed one. 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. @@ -1357,6 +1385,9 @@ struct TimeSeriesIterBuilder { predicate: PredicateGroup, dedup: bool, sequence: Option, + /// The cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`]). + creator_slices: Option, merge_mode: MergeMode, batch_to_record_batch: Arc, } @@ -1369,6 +1400,7 @@ impl IterBuilder for TimeSeriesIterBuilder { self.dedup, self.merge_mode, self.sequence, + self.creator_slices.clone(), metrics, )?; if self.merge_mode == MergeMode::LastNonNull { @@ -1611,6 +1643,8 @@ mod tests { &schema, &[0, 1, 2, 3, 4].into_iter().collect(), None, + None, + None, true, MergeMode::LastRow, ) @@ -1681,6 +1715,8 @@ mod tests { &schema, &projection, Some(SequenceRange::LtEq { max: 2 }), + None, + None, true, MergeMode::LastNonNull, ) @@ -1728,6 +1764,8 @@ mod tests { &schema, &projection, Some(SequenceRange::Gt { min: 1 }), + None, + None, true, MergeMode::LastNonNull, ) @@ -2001,6 +2039,351 @@ mod tests { assert_eq!((0..100i64).collect::>(), v0_all); } + /// A memtable row is filtered by the cursor of the piece it belongs to, never by the + /// single floor of the region: the floor is the least advanced piece, so it delivers the + /// rows a more advanced piece already consumed. + #[test] + fn test_memtable_filters_rows_by_creator_slice_cursor() { + use partition::expr::{Operand, col}; + + let schema = schema_for_test(); + let memtable = TimeSeriesMemtable::new(schema.clone(), 1, None, false, MergeMode::LastRow); + + let column_schema = schema + .column_metadatas + .iter() + .map(|c| api::v1::ColumnSchema { + column_name: c.column_schema.name.clone(), + datatype: ColumnDataTypeWrapper::try_from(c.column_schema.data_type.clone()) + .unwrap() + .datatype() as i32, + semantic_type: c.semantic_type as i32, + ..Default::default() + }) + .collect::>(); + // Writes one row per call with an explicit sequence, so the rows of one series can + // be numbered independently of the others. + let write_row = |k0: &str, ts: i64, sequence: u64| { + let mutation = Mutation { + op_type: 1, + sequence, + rows: Some(Rows { + schema: column_schema.clone(), + rows: vec![row(vec![ + ValueData::StringValue(k0.to_string()), + ValueData::I64Value(0), + ValueData::TimestampMillisecondValue(ts), + ValueData::I64Value(ts), + ValueData::F64Value(0.0), + ])], + }), + write_hint: None, + }; + let kvs = KeyValues::new(schema.as_ref(), mutation).unwrap(); + memtable.write(&kvs).unwrap(); + }; + + // `k0 < "m"` is the piece consumed up to 5, `k0 >= "m"` the one consumed up to 2. + write_row("a", 0, 3); + write_row("a", 1, 4); + write_row("z", 2, 6); + + let read = |slices: Vec<( + partition::expr::PartitionExpr, + SequenceNumber, + Option, + )>| { + let options = RangesOptions::default() + .with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 })) + .with_creator_slices(Some(Arc::new(slices))); + let mut iter = memtable.ranges(None, options).unwrap().build(None).unwrap(); + let mut rows = Vec::new(); + for batch in iter.by_ref() { + let batch = batch.unwrap(); + let timestamps = batch.timestamps().to_arrow_array(); + let timestamps = timestamps + .as_any() + .downcast_ref::() + .unwrap(); + for (idx, sequence) in batch.sequences().iter_data().enumerate() { + rows.push((timestamps.value(idx), sequence.unwrap())); + } + } + rows.sort_unstable(); + rows + }; + + let slice_lt = || col("k0").lt(Operand::Value(Value::String("m".into()))); + let slice_ge = || col("k0").gt_eq(Operand::Value(Value::String("m".into()))); + + // The region-level floor (2) keeps the rows at 3, 4 and 6, but the piece of the + // first two is consumed up to 5: only the row of the piece consumed up to 2 is + // delivered. + assert_eq!( + vec![(2, 6)], + read(vec![(slice_lt(), 5, 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" + ); + + // One cursor value for every piece is the region-level floor: the delivered rows are + // exactly the rows above the floor, whatever piece they belong to. + assert_eq!( + vec![(0, 3), (1, 4), (2, 6)], + read(vec![(slice_lt(), 2, None), (slice_ge(), 2, None)]), + "with one cursor value the rows are exactly the rows above the region floor" + ); + + // 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, + None, + ), + ( + col("k0").gt_eq(Operand::Value(Value::String("z".into()))), + 2, + None, + ), + ]))); + 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, None), + (col("v0").lt(Operand::Value(Value::Int64(0))), right, None), + ] + }; + 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" + ); + } + + /// 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(); @@ -2211,6 +2594,7 @@ mod tests { dedup, merge_mode, sequence, + creator_slices: None, batch_to_record_batch: adapter_context, } } diff --git a/src/mito2/src/read.rs b/src/mito2/src/read.rs index c1d70c66613..1a167b355a1 100644 --- a/src/mito2/src/read.rs +++ b/src/mito2/src/read.rs @@ -40,17 +40,21 @@ pub mod stream; pub(crate) mod substituted_rows; pub(crate) mod unordered_scan; -use std::collections::HashMap; +use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::time::Duration; use api::v1::OpType; use arrow_schema::SchemaRef; +use common_telemetry::debug; use common_time::Timestamp; +use datafusion::physical_plan::PhysicalExpr; use datafusion_common::arrow::array::UInt8Array; use datatypes::arrow; -use datatypes::arrow::array::{Array, ArrayRef}; +use datatypes::arrow::array::{Array, ArrayRef, BooleanArray}; use datatypes::arrow::compute::SortOptions; +use datatypes::arrow::datatypes::{Field, Schema}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::arrow::row::{RowConverter, SortField}; use datatypes::prelude::{ConcreteDataType, DataType, ScalarVector}; @@ -67,13 +71,16 @@ use futures::TryStreamExt; use futures::stream::BoxStream; use mito_codec::row_converter::{CompositeValues, DensePrimaryKeyCodec, PrimaryKeyCodec}; use snafu::{OptionExt, ResultExt, ensure}; +use store_api::metadata::RegionMetadataRef; use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; use crate::error::{ - ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, InvalidBatchSnafu, - Result, + ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, + EvalPartitionFilterSnafu, InvalidBatchSnafu, Result, SequenceRangeUnsupportedSnafu, +}; +use crate::memtable::{ + BoxedRecordBatchIterator, CreatorSliceCursor, creator_slice_sequence_range, least_slice_until, }; -use crate::memtable::BoxedRecordBatchIterator; pub(crate) fn timestamp_array_to_i64_slice(arr: &ArrayRef) -> &[i64] { use datatypes::arrow::array::{ @@ -144,6 +151,113 @@ struct DensePkCache { values: Vec>, } +/// Builds the one-row batch of tag values the primary key of a batch states, holding the +/// columns the candidate creator cursor slices reference. +/// +/// A time-series memtable batch is one series, so the tag values of the whole batch are the +/// values of that series and one row is enough to decide which piece it belongs to. The +/// values are extracted from the decoded primary key, which is how the memtable states its +/// tags. +/// +/// `None` means the piece cannot be decided: a referenced column is missing from the region +/// or is not part of its primary key, or a value does not convert to the column's type. The +/// caller then applies [`Batch::unresolved_creator_cursor`] to the candidate cursors. +fn creator_slice_probe_batch( + metadata: &RegionMetadataRef, + slices: &[CreatorSliceCursor], + pk_values: &CompositeValues, +) -> Option { + let mut referenced = HashSet::new(); + for (expr, ..) in slices { + expr.collect_column_names(&mut referenced); + } + + let mut fields = Vec::with_capacity(referenced.len()); + let mut columns = Vec::with_capacity(referenced.len()); + for column_metadata in &metadata.column_metadatas { + let name = &column_metadata.column_schema.name; + if !referenced.remove(name) { + continue; + } + let column_id = column_metadata.column_id; + // Only a primary-key column carries a value the memtable batch states. + let pk_index = metadata.primary_key_index(column_id)?; + let value = match pk_values { + CompositeValues::Dense(values) => &values.get(pk_index)?.1, + CompositeValues::Sparse(values) => values.get_or_null(column_id), + }; + let data_type = &column_metadata.column_schema.data_type; + let scalar = value.try_to_scalar_value(data_type).ok()?; + let array = Helper::try_from_scalar_value(scalar, 1, Some(data_type)) + .ok()? + .to_arrow_array(); + fields.push(Field::new( + name, + data_type.as_arrow_type(), + column_metadata.column_schema.is_nullable(), + )); + columns.push(array); + } + if !referenced.is_empty() { + // A referenced column this region does not have cannot be evaluated. + return None; + } + + RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).ok() +} + +/// 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: &[CreatorSliceCursor]) -> (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) +} + +/// 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 { + let columnar_value = filter.evaluate(probe).context(EvalPartitionFilterSnafu)?; + let array = columnar_value + .into_array(probe.num_rows()) + .context(EvalPartitionFilterSnafu)?; + let boolean = + array + .as_any() + .downcast_ref::() + .context(crate::error::UnexpectedSnafu { + reason: format!( + "a partition expression must evaluate to a boolean array, got {:?}", + array.data_type() + ), + })?; + + Ok(boolean.is_valid(0) && boolean.value(0)) +} + impl Batch { /// Creates a new batch. pub fn new( @@ -417,24 +531,205 @@ impl Batch { /// Filters rows by the given `sequence`. Only preserves rows with sequence less than or equal to `sequence`. pub fn filter_by_sequence(&mut self, sequence: Option) -> Result<()> { - let seq_range = match sequence { - None => return Ok(()), - Some(seq_range) => { - let (Some(first), Some(last)) = (self.first_sequence(), self.last_sequence()) - else { - return Ok(()); - }; - let is_subset = match seq_range { - SequenceRange::Gt { min } => min < first, - SequenceRange::LtEq { max } => max >= last, - SequenceRange::GtLtEq { min, max } => min < first && max >= last, - }; - if is_subset { - return Ok(()); - } - seq_range - } + match sequence { + None => Ok(()), + Some(seq_range) => self.filter_by_sequence_range(seq_range), + } + } + + /// Filters rows by the cursor of the piece each row belongs to. + /// + /// One [`Batch`] of a time-series memtable holds one series, so every row of it belongs + /// to the same piece and the piece is resolved once for the whole batch: the partition + /// expression of each candidate slice is evaluated against the batch's primary-key (tag) + /// values, and the rows are kept when their own sequence is above that slice's cursor 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 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<&[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, first_until)) = slices.first() else { + return Ok(()); + }; + // 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(creator_slice_sequence_range(cursor, until, read_fence)) + } + + /// 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 — 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: &[CreatorSliceCursor], + metadata: &RegionMetadataRef, + codec: Option<&dyn PrimaryKeyCodec>, + ) -> Result<(SequenceNumber, Option)> { + let Some(codec) = codec else { + // Without a primary key the pieces cannot be told apart. + 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) => { + return Self::unresolved_creator_cursor( + metadata, + slices, + &format!("the primary key of the batch cannot be decoded: {e}"), + ); + } + }, + }; + let Some(probe) = creator_slice_probe_batch(metadata, slices, &pk_values) else { + 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<(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, + Err(e) => { + return Self::unresolved_creator_cursor( + metadata, + slices, + &format!("a slice expression cannot be evaluated: {e}"), + ); + } + }, + Err(e) => { + return Self::unresolved_creator_cursor( + metadata, + slices, + &format!("a slice expression cannot be planned: {e}"), + ); + } + }; + if selected { + // Disjoint expressions match at most once; a domain that was not split + // 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)) + } + }); + } + } + + 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. 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: &[CreatorSliceCursor], + detail: &str, + ) -> 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, until)); + } + 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 + /// already satisfies it. + fn filter_by_sequence_range(&mut self, seq_range: SequenceRange) -> Result<()> { + let (Some(first), Some(last)) = (self.first_sequence(), self.last_sequence()) else { + return Ok(()); + }; + let is_subset = match seq_range { + SequenceRange::Gt { min } => min < first, + SequenceRange::LtEq { max } => max >= last, + SequenceRange::GtLtEq { min, max } => min < first && max >= last, + }; + if is_subset { + return Ok(()); + } let seqs = self.sequences.as_arrow(); let predicate = seq_range.filter(seqs).context(ComputeArrowSnafu)?; diff --git a/src/mito2/src/read/range_cache.rs b/src/mito2/src/read/range_cache.rs index 4caf4636695..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; @@ -47,6 +47,7 @@ use crate::read::read_columns::ReadColumns; use crate::read::scan_region::StreamContext; use crate::read::scan_util::PartitionMetrics; use crate::read::series_reader::SeriesRange; +use crate::read::substituted_rows::ForeignFileRowCreators; use crate::region::options::MergeMode; #[cfg(any(test, feature = "test"))] use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE; @@ -138,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 { @@ -147,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. @@ -235,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::>() @@ -523,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 { @@ -535,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, }, )); } @@ -647,6 +696,7 @@ impl CachedRangeReader<'_> { self.metrics, files, scope, + self.stream_ctx.input.foreign_file_row_creators(), build, ) .await @@ -689,7 +739,7 @@ where F: FnOnce() -> Fut, Fut: Future>, { - load_shared_range(strategy, key, part_metrics, Vec::new(), scope, build).await + load_shared_range(strategy, key, part_metrics, Vec::new(), scope, None, build).await } async fn load_shared_range( @@ -698,6 +748,7 @@ async fn load_shared_range( part_metrics: &PartitionMetrics, files: Vec, scope: RangeCacheScope, + replay_evidence: Option<&ForeignFileRowCreators>, build: F, ) -> Result<(BoxedRecordBatchStream, usize)> where @@ -713,6 +764,7 @@ where part_metrics.range_cache_metrics_reporter(), files, scope, + replay_evidence, build, ) .await diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index ba1784923ad..73b4a395455 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -43,13 +43,14 @@ use datatypes::value::timestamp_to_scalar_value; use futures::StreamExt; use mito_codec::row_converter::{SortField, build_primary_key_codec_with_fields}; use partition::expr::PartitionExpr; +use partition::overlap::associate_from_to; use smallvec::SmallVec; use snafu::{OptionExt, ResultExt, ensure}; use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef}; -use store_api::region_engine::{PartitionRange, RegionScannerRef}; +use store_api::region_engine::{PartitionRange, RegionScannerRef, ScanSnapshotIdentity}; use store_api::storage::{ - ColumnId, RegionId, ScanRequest, SequenceNumber, SequenceRange, TimeSeriesDistribution, - TimeSeriesRowSelector, + ColumnId, CursorShard, RegionId, ScanRequest, SequenceNumber, SequenceRange, + TimeSeriesDistribution, TimeSeriesRowSelector, }; use table::predicate::{Predicate, build_time_range_predicate, extract_time_range_from_expr}; use tokio::sync::{Semaphore, mpsc}; @@ -69,12 +70,17 @@ 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; use crate::read::stream::ScanBatchStream; -use crate::read::substituted_rows::{SubstitutedRowsAccumulator, SubstitutedRowsAccumulatorRef}; +use crate::read::substituted_rows::{ + ForeignFileRowCreators, ForeignFileRowCreatorsRef, ObservedPartitionExprs, + ObservedPartitionExprsRef, SubstitutedRowsAccumulator, SubstitutedRowsAccumulatorRef, +}; use crate::read::unordered_scan::UnorderedScan; use crate::read::{BoxedRecordBatchStream, RecordBatch}; use crate::region::options::MergeMode; @@ -89,10 +95,15 @@ use crate::sst::index::fulltext_index::applier::builder::FulltextIndexApplierBui use crate::sst::index::inverted_index::applier::InvertedIndexApplierRef; use crate::sst::index::inverted_index::applier::builder::InvertedIndexApplierBuilder; use crate::sst::parquet::Json2RewriteTargets; -use crate::sst::parquet::file_range::PreFilterMode; +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, 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 { /// Sequential scan. @@ -102,7 +113,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)] @@ -475,9 +485,9 @@ impl ScanRegion { /// Scans by series. /// /// A physical row-sequence read is refused here: neither the per-series readers nor the - /// legacy distributor (`SeqScan::build_flat_partition_range_read`) applies the file's - /// substituted cut, so the read fails closed with the shared "exactness is not provable" - /// error. + /// legacy distributor (`SeqScan::build_flat_partition_range_read`) applies the creator's + /// cursor slice or the file's substituted cut, so the read fails closed with the shared + /// "exactness is not provable" error. #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))] pub(crate) async fn series_scan(self) -> Result { if self.request.read_row_sequence { @@ -486,9 +496,10 @@ impl ScanRegion { min_seq: self.request.memtable_min_sequence.unwrap_or_default(), max_seq: self.request.memtable_max_sequence.unwrap_or_default(), reason: "the PerSeries distribution cannot carry a physical row-sequence read: \ - its series readers do not apply the substituted cut of a file, so rows \ - a substitution produced would be delivered as if this region \ - allocated them; plan the incremental delta as a flat ordered read" + its series readers apply neither the creator's cursor slice nor the \ + substituted cut of an adopted file, so rows the caller already consumed \ + would be delivered again and a foreign sequence domain would be compared \ + with this region's bounds; plan the incremental delta as a flat ordered read" .to_string(), } .fail(); @@ -517,9 +528,135 @@ impl ScanRegion { self.request.distribution == Some(TimeSeriesDistribution::PerSeries) } + /// The region's partition-expression identity at this scan's version snapshot. + /// + /// [`Self::version`] is the `Version` whose `committed_sequence` the engine bound as this + /// scan's `memtable_max_sequence` (see `EngineHandle::scan_region`), so the identity read + /// here and that watermark describe one snapshot: a repartition that gives the region + /// another expression publishes a new `Version`, which this scan never consults again. + /// + /// The expression is reported in the canonical `PartitionExpr::as_json_str()` form an + /// observed slice and a cursor entry carry, so `(region, expression)` from this scan keys + /// the same slice as they do. `None` - no expression, or the explicit empty designation - + /// states the region's complete value domain. + fn snapshot_partition_expr(&self) -> Result> { + let Some(expr) = + crate::region::parse_partition_expr(self.version.metadata.partition_expr.as_deref())? + else { + return Ok(None); + }; + let identity = expr + .canonicalize() + .as_json_str() + .context(crate::error::SerializePartitionExprSnafu)?; + Ok(Some(identity)) + } + + /// The creators of the files this scan's version snapshot has visible, excluding the region + /// itself, sorted and deduplicated. + /// + /// This reads the version's file list in memory - no manifest read, no file open - so it is + /// what the region held **when the scan opened**, before any predicate prunes a file away. A + /// consumer that enumerates the regions a flow's rows can come from needs exactly this: the + /// regions whose rows are sitting in this region's files, which a pruned read never delivers + /// and therefore never reports. + /// + /// The region's own files are its own rows, so its own id is not listed. + fn visible_foreign_file_creators(&self) -> Vec { + let region_id = self.region_id(); + let mut creators = self + .version + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .map(|file| file.meta_ref().region_id.as_u64()) + .filter(|creator| *creator != region_id) + .collect::>(); + creators.sort_unstable(); + creators.dedup(); + creators + } + + /// The cursor of each piece a memtable row of **this region** may belong to. + /// + /// A memtable holds the rows this region allocated, so the candidates are the region's + /// own slices: every one of them may hold a row, and no file metadata narrows the set the + /// way it does for the cursor slices of an SST. A row is then compared against the cursor + /// of the piece its tag values fall into instead of against the single floor of the + /// region, which is only the least advanced piece. + /// + /// 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 + /// 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 Ok(None); + } + let Some(shards) = self + .request + .creator_cursor_shards + .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, 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 only the region-level floor is left. + debug!( + "Cannot read back creator cursor slice expression {}; keeping the region-level floor", + identity + ); + 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, shard.until)); + } + if slices.is_empty() { + return Ok(None); + } + + Ok(Some(Arc::new(slices))) + } + /// Creates a scan input. #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))] async fn scan_input(mut self) -> Result { + // Pinned together with `snapshot_sequence` below, all from `self.version`. + let snapshot_partition_expr = self.snapshot_partition_expr()?; + let visible_foreign_file_creators = self.visible_foreign_file_creators(); let metadata = &self.version.metadata; let sst_min_sequence = self.request.sst_min_sequence.and_then(NonZeroU64::new); let time_range = self.build_time_range_predicate(); @@ -585,6 +722,19 @@ impl ScanRegion { self.version.options.merge_mode(), ); + // A read that may cross an invalid boundary applies no lower bound to memtables: the + // rows at or below the cursor are exactly the windows it rediscover. The frozen `H` + // upper bound stays. + let memtable_min_sequence = if self.request.read_across_invalid_boundary { + None + } else { + self.request.memtable_min_sequence + }; + // The per-piece cursors of this region's own slices: they replace the single floor + // `memtable_min_sequence` states (the least advanced piece), 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 { // check if memtable is empty by reading stats. let Some((start, end)) = m.stats().time_range() else { @@ -600,9 +750,10 @@ impl ScanRegion { RangesOptions::default() .with_predicate(predicate.clone()) .with_sequence(SequenceRange::new( - self.request.memtable_min_sequence, + memtable_min_sequence, self.request.memtable_max_sequence, )) + .with_creator_slices(memtable_creator_slices.clone()) .with_pre_filter_mode(filter_mode), )?; mem_range_builders.extend(ranges_in_memtable.ranges.into_values().map(|v| { @@ -666,8 +817,12 @@ impl ScanRegion { .then_some(self.request.memtable_max_sequence) .flatten(), ) + .with_snapshot_partition_expr(snapshot_partition_expr) + .with_visible_foreign_file_creators(visible_foreign_file_creators) .with_sequence_range(sequence_range) + .with_read_across_invalid_boundary(self.request.read_across_invalid_boundary) .with_read_row_sequence(self.request.read_row_sequence) + .with_creator_cursor_shards(self.request.creator_cursor_shards.clone()) .with_query_stat_counters(self.query_stat_counters); #[cfg(feature = "enterprise")] let input = if !self.request.skip_sst_files @@ -763,6 +918,26 @@ impl ScanRegion { expr.collect_column_names(&mut extra_col_names); } + // A physical-sequence read evaluates the creator cursor slices of an adopted file + // row by row, so the columns those expressions reference must be read too. They are + // internal: the output projection happens after the flat batch + // (`ConvertBatchStream::convert`), so adding them does not change the result schema. + if self.request.read_row_sequence + && let Some(shards) = &self.request.creator_cursor_shards + { + for shard in shards.values().flatten() { + let Some(identity) = shard.partition_expr.as_deref() else { + continue; + }; + let Ok(Some(expr)) = PartitionExpr::from_json_str(identity) else { + // An unreadable identity keeps the conservative file-level bound; the + // reader reports the same conclusion when it compiles the slices. + continue; + }; + expr.collect_column_names(&mut extra_col_names); + } + } + if !extra_col_names.is_empty() { for col in &metadata.column_metadatas { if extra_col_names.remove(&col.column_schema.name) && !seen.contains(&col.column_id) @@ -1038,16 +1213,44 @@ pub struct ScanInput { explain_flat_format: bool, /// Snapshot upper bound bound at scan open and propagated back to the caller. pub(crate) snapshot_sequence: Option, + /// The region's partition expression stated by the same version snapshot as + /// [`Self::snapshot_sequence`] (`None` = the region's complete value domain), read once at + /// scan open and propagated back to the caller. + /// + /// Set for every query scan, not only for one that bound a sequence: a caller that reads at + /// a bound it supplied itself still reports the expression the read happened under. Both + /// fields come from [`ScanRegion::version`], the version whose `committed_sequence` the + /// engine bound as `memtable_max_sequence` (`EngineHandle::scan_region`). + pub(crate) snapshot_partition_expr: Option, + /// The creators of the files the same version snapshot had visible, excluding this region + /// (`Some(vec![])` = the region held no file of another region), read once at scan open and + /// propagated back to the caller. + pub(crate) visible_foreign_file_creators: Option>, /// Set only when the region preserves per-row sequences /// (`preserve_row_sequence` on an append-only table) and the scan /// carries an explicit exact range. When set, SST readers apply the same /// `(checkpoint, upper_bound]` row-level filter as memtables. pub(crate) sequence_range: Option, - /// Whether this scan reads the physical `__sequence` column of a foreign file and hides the - /// rows a substitution produced ([`ScanRequest::read_row_sequence`]). + /// Whether this read may cross an invalid boundary: every selected SST's rows + /// are virtualized at the file's admission barrier. + pub(crate) read_across_invalid_boundary: bool, + /// Whether this scan reads the physical `__sequence` of a foreign file and hides + /// the rows a substitution produced ([`ScanRequest::read_row_sequence`]). pub(crate) read_row_sequence: bool, + /// Cursor slices of every region a file of this one may hold rows of + /// ([`ScanRequest::creator_cursor_shards`]): each file is bounded by the least advanced + /// slice of the region that allocated its numbers that may hold its rows — this region's + /// own slices for a file it created itself, a creator's for an adopted one. + creator_cursor_shards: Option>>>, /// Collects the timestamp ranges of the rows this scan substituted; `None` turns it off. pub(crate) substituted_row_ranges: Option, + /// Collects the `(region, partition expression)` pairs this scan read; `None` turns it off, + /// like [`Self::substituted_row_ranges`]. + pub(crate) observed_slices: Option, + /// Collects the creator regions of the files this scan delivered rows from; `None` turns + /// it off. Created for every query scan, not just a physical-sequence read: a full read + /// (`read_row_sequence` off) is exactly the read that has to report it. + pub(crate) foreign_file_row_creators: Option, /// Whether this scan is for compaction. pub(crate) compaction: bool, /// Max number of compaction inputs decoded concurrently ahead of the merge. @@ -1117,9 +1320,15 @@ impl ScanInput { distribution: None, explain_flat_format: false, snapshot_sequence: None, + snapshot_partition_expr: None, + visible_foreign_file_creators: None, sequence_range: None, + read_across_invalid_boundary: false, read_row_sequence: false, + creator_cursor_shards: None, substituted_row_ranges: None, + observed_slices: None, + foreign_file_row_creators: None, compaction: false, compaction_read_parallelism: 1, json2_rewrite_targets: Arc::default(), @@ -1204,6 +1413,12 @@ impl ScanInputBuilder { if self.input.compaction { self.input.scan_memory_tracker = None; } + // A compaction read has no caller to report to. Every other scan states which other + // regions' files it delivered rows from — including a full read, which is the read + // that has no creator cursor to filter with. + if !self.input.compaction { + self.input.foreign_file_row_creators = Some(Arc::new(ForeignFileRowCreators::new())); + } let input = &self.input; let eligible = !input.compaction && !input.files.is_empty() @@ -1476,19 +1691,59 @@ impl ScanInputBuilder { self } + #[must_use] + pub(crate) fn with_visible_foreign_file_creators( + mut self, + visible_foreign_file_creators: Vec, + ) -> Self { + self.input.visible_foreign_file_creators = Some(visible_foreign_file_creators); + self + } + + #[must_use] + pub(crate) fn with_snapshot_partition_expr( + mut self, + snapshot_partition_expr: Option, + ) -> Self { + self.input.snapshot_partition_expr = snapshot_partition_expr; + self + } + #[must_use] pub(crate) fn with_sequence_range(mut self, sequence_range: Option) -> Self { self.input.sequence_range = sequence_range; self } + #[must_use] + pub(crate) fn with_read_across_invalid_boundary( + mut self, + read_across_invalid_boundary: bool, + ) -> Self { + self.input.read_across_invalid_boundary = read_across_invalid_boundary; + self + } + /// Sets whether this scan reads physical row sequences and hides substituted rows. It turns - /// the substituted-row collector on with it. + /// the substituted-row and observed-partition-expression collectors on with it. #[must_use] pub(crate) fn with_read_row_sequence(mut self, read_row_sequence: bool) -> Self { self.input.read_row_sequence = read_row_sequence; self.input.substituted_row_ranges = read_row_sequence.then(|| Arc::new(SubstitutedRowsAccumulator::new())); + self.input.observed_slices = + read_row_sequence.then(|| Arc::new(ObservedPartitionExprs::new())); + self + } + + /// Sets the cursor slices of the regions that created this region's files; only a + /// physical-sequence read uses them. + #[must_use] + pub(crate) fn with_creator_cursor_shards( + mut self, + creator_cursor_shards: Option>>>, + ) -> Self { + self.input.creator_cursor_shards = creator_cursor_shards; self } @@ -1731,7 +1986,12 @@ impl ScanInput { }; let res = reader .expected_metadata(Some(self.mapper.metadata().clone())) + .force_sequence_override(self.read_across_invalid_boundary) .read_row_sequence(self.read_row_sequence) + // Only the slices whose expression may hold rows of this file are passed on; a file + // no slice covers keeps the file-level bound, and only a file of another region fails + // closed. + .creator_slice_cursors(self.creator_slice_cursors(file)?) .compaction(self.compaction) .pre_filter_mode(pre_filter_mode) .enable_predicate_prefilter(enable_predicate_prefilter) @@ -1930,6 +2190,314 @@ impl ScanInput { self.mapper.metadata() } + /// The snapshot this scan pinned: the bound it set itself (if any) and the + /// partition-expression identity of the same version, in the canonical + /// `PartitionExpr::as_json_str()` form a cursor entry carries. + pub(crate) fn snapshot_identity(&self) -> ScanSnapshotIdentity { + ScanSnapshotIdentity { + bound_sequence: self.snapshot_sequence, + partition_expr: self.snapshot_partition_expr.clone(), + visible_foreign_file_creators: self.visible_foreign_file_creators.clone(), + } + } + + pub(crate) fn substituted_row_ranges(&self) -> Option<&SubstitutedRowsAccumulator> { + self.substituted_row_ranges.as_deref() + } + + pub(crate) fn substituted_row_ranges_ref(&self) -> Option { + self.substituted_row_ranges.clone() + } + + pub(crate) fn observed_slices(&self) -> Option<&ObservedPartitionExprs> { + self.observed_slices.as_deref() + } + + pub(crate) fn observed_slices_ref(&self) -> Option { + self.observed_slices.clone() + } + + pub(crate) fn foreign_file_row_creators(&self) -> Option<&ForeignFileRowCreators> { + self.foreign_file_row_creators.as_deref() + } + + pub(crate) fn foreign_file_row_creators_ref(&self) -> Option { + self.foreign_file_row_creators.clone() + } + + /// Returns the substituted cut `file` states for its own bytes, when this scan reads + /// physical row sequences. + /// + /// The cut describes the file's bytes, not who allocated the numbers in them, so it applies + /// to every file that states one, local files included + /// ([`crate::sst::file::substituted_up_to_after_merge`]). The file's + /// `preserve_row_sequence` marker takes no part. + pub(crate) fn substituted_sequence_cut(&self, file: &FileHandle) -> Option { + if !self.read_row_sequence { + return None; + } + // `None` means no row of the column was substituted; `Some(0)` means the column + // carries no per-row numbering at all, so every row is substituted. + file.meta_ref().substituted_up_to + } + + /// The row filter of a physical-sequence read of `file`: + /// `(candidate cursor, candidate bound]`, or `(candidate cursor, +inf)` when no candidate + /// slice states an upper bound. + /// + /// This is the candidate selection of [`cursor_slice_may_hold_file_rows`] followed by one + /// sequence range for the whole file, so a file whose expressions advanced differently is + /// read from the least advanced of them: the lower end is the *minimum* of the candidates' + /// cursors, and the upper end the *minimum* of the upper bounds they state + /// ([`CursorShard::until`]). The file-level filter cannot tell which slice a row belongs + /// to, so it may only prove what the least bound proves: a row above it may belong to the + /// slice whose delta ends exactly there, and delivering it would report progress this read + /// does not stand for. + /// + /// A region's **own** files are bounded the same way: the cursors are keyed by + /// `(region, piece)` and the map is keyed by the region that allocated the numbers, which + /// for such a file is this region, so the candidates are this region's own pieces. The one + /// difference is the upper end: own rows carry this region's numbers, so the scan's own `H` + /// bounds them whenever no candidate states a bound, instead of leaving the file unbounded + /// above. When a region's pieces carry one cursor value, that value is the minimum, so the + /// result is exactly the region-level floor `(C, H]` this read applied before. + /// + /// `None` means this scan has no cursor of the file's region (or is not a + /// physical-sequence read at all). + pub(crate) fn creator_domain_sequence_range( + &self, + file: &FileHandle, + ) -> Result> { + if !self.read_row_sequence { + return Ok(None); + } + // A physical-sequence read only exists inside an exact `(C, H]` delta. If this + // scan could not prove one at all (`sequence_range` is `None`, e.g. a local file + // whose barrier cannot be trusted), a foreign file fails closed like every other + // uncertain case — but neither `C` nor `H` bounds *that* file's numbers, so the + // range itself is not reused below. + if self.sequence_range.is_none() { + return Ok(None); + } + let meta = file.meta_ref(); + // Whose numbers the file carries: its own region's, or a creator's this read has to + // compare against the creator's cursors. + let own_numbers = meta.region_id == self.region_metadata().region_id; + 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 cursor: Option = None; + let mut until: Option = None; + for shard in shards { + if cursor_slice_may_hold_file_rows(shard, meta)? { + cursor = Some(cursor.map_or(shard.seq, |current| current.min(shard.seq))); + if let Some(shard_until) = shard.until { + until = Some(until.map_or(shard_until, |current| current.min(shard_until))); + } + } + } + // Own rows carry this region's numbers, so the scan's own `H` bounds them even when + // every candidate piece is open-ended above. A creator's numbers no bound of this + // region states anything about, so an adopted file stays unbounded above instead. + let own_upper = if own_numbers { + match self.sequence_range { + Some(SequenceRange::GtLtEq { max, .. } | SequenceRange::LtEq { max }) => Some(max), + _ => None, + } + } else { + None + }; + let until = until.or(own_upper); + Ok(cursor.map(|min| match until { + // `min < number <= max`: the rows of the delta, neither re-read nor read ahead. + Some(max) => SequenceRange::GtLtEq { min, max }, + None => SequenceRange::Gt { min }, + })) + } + + /// The candidate cursor slices of `file`, as the reader compiles them: + /// `(partition expression identity, last consumed sequence)` pairs whose expression + /// may select a row of the file. + /// + /// This is the same candidate selection as [`Self::creator_domain_sequence_range`]: + /// the file-level bound it produces stays, and the reader uses the candidates to decide + /// per row which cursor applies. A file carrying this region's own numbers is read the + /// 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); + } + 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 { + // 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); + }; + // 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 { + if cursor_slice_may_hold_file_rows(shard, meta)? { + candidates.push(shard); + } + } + 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))) + } + + /// 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 { + file.meta_ref().region_id != self.region_metadata().region_id + } + + /// The row filter a physical-sequence read applies to `file`: every row of it is compared + /// against the cursor of the **piece it belongs to**, never against one floor for a whole + /// region. + /// + /// The cursors are keyed by `(region, piece)`, so a file is filtered by the slices of the + /// region that allocated its numbers — `(cursor, until]`, or `(cursor, +inf)` when no + /// candidate states a bound ([`Self::creator_domain_sequence_range`]) — with or without a + /// substituted cut. A file carrying this region's own numbers gets the same treatment: its + /// rows were allocated by this region's own pieces, and dropping the pointwise comparison + /// assumed a region has a single cursor value, which the flow model this serves does not + /// guarantee. When a region's pieces carry one cursor value, that value is the minimum, so + /// the outcome is exactly the region-level floor `(C, H]` of before. + /// + /// `Ok(None)` means no slice of the file's region applies (or this scan is not a + /// physical-sequence read at all). For a file of **this** region that is not a failure: rows + /// carrying this region's numbers are bounded by the scan's own `(C, H]`, which the caller + /// applies, exactly as before. For a file of another region it fails closed instead: the + /// holder's `(C, H]` states nothing about a number another region allocated. + /// [`exact_sequence_range`] never prunes such a file by this region's cursor. + pub(crate) fn row_sequence_filter(&self, file: &FileHandle) -> Result> { + if !self.read_row_sequence { + return Ok(None); + } + if let Some(range) = self.creator_domain_sequence_range(file)? { + return Ok(Some(range)); + } + if !self.is_foreign_file(file) { + // Every row of the file carries this region's own numbering, which its own + // `(C, H]` bounds, and no slice of the region narrowed it further: keep the + // region-level floor instead of failing a read of our own data closed. + return Ok(None); + } + let (min_seq, max_seq) = match self.sequence_range { + Some(SequenceRange::GtLtEq { min, max }) => (min, max), + Some(SequenceRange::Gt { min }) => (min, 0), + Some(SequenceRange::LtEq { max }) => (0, max), + None => (0, 0), + }; + let meta = file.meta_ref(); + SequenceRangeUnsupportedSnafu { + region_id: self.region_metadata().region_id, + min_seq, + max_seq, + reason: format!( + "the physical-sequence read of adopted file {} has no cursor slice of its creator region {}, so its rows cannot be split into consumed and live ones", + meta.file_id, meta.region_id + ), + } + .fail() + } + fn range_pre_filter_mode(&self, source_count: usize) -> PreFilterMode { if source_count <= 1 { // Duplicated rows in the same source is not a normal case and we don't provide @@ -2035,33 +2603,6 @@ impl PruningStatistics for FileLevelPruningStats<'_> { } } -impl ScanInput { - /// The timestamp ranges the rows this scan substituted occupy. - pub(crate) fn substituted_row_ranges(&self) -> Option<&SubstitutedRowsAccumulator> { - self.substituted_row_ranges.as_deref() - } - - pub(crate) fn substituted_row_ranges_ref(&self) -> Option { - self.substituted_row_ranges.clone() - } - - /// Returns the substituted cut `file` states for its own bytes, when this scan reads - /// physical row sequences. - /// - /// The cut describes the file's bytes, not who allocated the numbers in them, so it applies - /// to every file that states one, local files included - /// ([`crate::sst::file::substituted_up_to_after_merge`]). The file's - /// `preserve_row_sequence` marker takes no part. - pub(crate) fn substituted_sequence_cut(&self, file: &FileHandle) -> Option { - if !self.read_row_sequence { - return None; - } - // `None` means no row of the column was substituted; `Some(0)` means the column - // carries no per-row numbering at all, so every row is substituted. - file.meta_ref().substituted_up_to - } -} - #[cfg(test)] impl ScanInput { /// Returns SST file ids to scan. @@ -2085,6 +2626,108 @@ 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. +/// +/// This is a file-level selection: the caller bounds the whole file with the least advanced +/// candidate ([`ScanInput::creator_domain_sequence_range`]). +/// +/// * a whole-domain slice (`partition_expr: None`) is a candidate for every file; +/// * a file that states no expression covers its region's complete value domain, so every +/// slice of the region is a candidate; +/// * otherwise the slice is a candidate when both expressions can be satisfied by a common +/// row, which is the overlap question of `partition::overlap::associate_from_to`; +/// * an expression that cannot be analysed is a candidate as well. +fn cursor_slice_may_hold_file_rows( + shard: &CursorShard, + meta: &crate::sst::file::FileMeta, +) -> crate::error::Result { + let Some(shard_expr) = shard.partition_expr.as_deref() else { + return Ok(true); + }; + // Decoding can only fail for a cursor this build did not produce (the query layer + // validates the identity before it hands it to a scan), and the conservative reading + // of an unknown domain is the creator's whole value domain. + let Some(shard_expr) = + PartitionExpr::from_json_str(shard_expr).context(InvalidPartitionExprSnafu { + expr: shard_expr.to_string(), + })? + else { + return Ok(true); + }; + let Some(file_expr) = meta.partition_expr.as_ref() else { + return Ok(true); + }; + + let shard_exprs = [shard_expr]; + let file_exprs = [file_expr.as_ref().clone()]; + match associate_from_to(&shard_exprs, &file_exprs) { + Ok(assoc) => Ok(assoc.first().is_some_and(|overlaps| !overlaps.is_empty())), + Err(_) => Ok(true), + } +} + /// Selects the SST files for a scan and, when requested, determines whether /// the selected files support an exact sequence-range scan. /// @@ -2104,15 +2747,21 @@ fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode { /// file without a barrier fails closed. /// /// A physical-sequence read (`read_row_sequence`) keeps the file's own numbers instead, so a -/// foreign file is never excluded here: its numbers are the creator's, which the barrier does -/// not bound. +/// foreign file is never excluded here and is filtered by the creator's cursor +/// ([`ScanInput::row_sequence_filter`]). +/// +/// That filter bounds every file by the cursor of the piece each row belongs to, this region's +/// own files included, but the exclusion above still uses the request's region-level floor `C` +/// only: `C` is the least of a region's cursors, so a file is excluded only when every piece has +/// consumed it whole. A file whose piece cursors differ is therefore kept — the conservative +/// direction — and decided row by row instead. /// /// A **local** file may state a substitution as well: a merge substitutes a file-level constant /// for the rows of its foreign inputs and records the bound /// ([`crate::sst::file::substituted_up_to_after_merge`]). Such a file is attributable — the read -/// hides the rows at or below the cut ([`ScanInput::substituted_sequence_cut`]) and the rest -/// carries this region's numbering — and keeps the region's exact range. A local file with -/// neither the marker nor a cut keeps failing closed. +/// hides the rows at or below the cut ([`ScanInput::substituted_sequence_cut`]) and the cursors +/// of this region's pieces bound the rest — and keeps the region's exact range. A local file with +/// neither the marker nor a cut, or a cut outside a physical-sequence read, keeps failing closed. pub(crate) fn exact_sequence_range( request: &ScanRequest, version: &crate::region::version::Version, @@ -2121,6 +2770,69 @@ pub(crate) fn exact_sequence_range( return Ok((Vec::new(), None)); } + if request.read_across_invalid_boundary { + // A read that may cross an invalid boundary prunes at file granularity only: a file + // whose admission barrier is at or below the cursor was fully consumed, and a file + // without a barrier is kept. No `SequenceRange` is returned, so the result is a + // superset of the affected windows. + let after = request.memtable_min_sequence; + let time_index = version.metadata.time_index_column(); + let unit = time_index + .column_schema + .data_type + .as_timestamp() + .expect("Time index must have timestamp-compatible type") + .unit(); + let time_range = + build_time_range_predicate(&time_index.column_schema.name, unit, &request.filters); + let files = version + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .filter(|file| file_in_range(file, &time_range)) + .filter(|file| match (after, file.meta_ref().sequence) { + (Some(after), Some(sequence)) => sequence.get() > after, + _ => true, + }) + .cloned() + .collect::>(); + // A file without an admission barrier cannot be pruned, so the candidate set is + // reported as incomplete instead of degrading into a full scan. + let unprunable = files + .iter() + .filter(|file| file.meta_ref().sequence.is_none()) + .count(); + if unprunable > 0 { + return SequenceRangeUnsupportedSnafu { + region_id: version.metadata.region_id, + min_seq: after.unwrap_or_default(), + max_seq: after.unwrap_or_default(), + reason: format!( + "recovery discovery cannot prove its candidate file set is complete: {unprunable} of {} selected files carry no admission barrier, so it would read the whole region", + files.len() + ), + } + .fail(); + } + if files.is_empty() && version.memtables.is_empty() { + // An empty candidate set is reported, never silently treated as "no + // window": the caller decides whether to accept it or advance instead. + // A non-empty memtable is a candidate too: its rows carry sequences the + // region itself assigned, so discovery must read it (the scan keeps no + // row-level range here, which only widens the discovered window set). + return SequenceRangeUnsupportedSnafu { + region_id: version.metadata.region_id, + min_seq: after.unwrap_or_default(), + max_seq: after.unwrap_or_default(), + reason: "recovery discovery found no candidate file above the cursor, so it cannot report an empty window set as complete" + .to_string(), + } + .fail(); + } + return Ok((files, None)); + } + let time_index = version.metadata.time_index_column(); let unit = time_index .column_schema @@ -2145,7 +2857,7 @@ pub(crate) fn exact_sequence_range( { let meta = file.meta_ref(); // A physical-sequence read keeps the creator's numbers, which the barrier does not - // bound: the file is kept and its substituted rows are hidden by the read. + // bound: the file is kept and filtered by the creator's cursor. let keeps_foreign_sequence_domain = request.read_row_sequence && meta.region_id != version.metadata.region_id; let selected = (!request.exact_sequence_range @@ -3923,6 +4635,101 @@ mod tests { assert!(exact_sequence_range(&request, &version).is_err()); } + /// A physical-sequence read admits an imported file whatever its `preserve_row_sequence` + /// marker says: an import (a repartition's staging apply included) only re-marks the + /// handle and copies the bytes, so the column and the file's own cut still describe the + /// rows. The missing-barrier error stays, and the marker keeps gating ordinary reads. + #[test] + fn test_exact_sequence_selection_admits_imported_file_for_physical_read() { + use std::num::NonZeroU64; + + use crate::test_util::new_noop_file_purger; + + let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false)); + let mutable = crate::memtable::time_partition::TimePartitions::new( + metadata.clone(), + Arc::new(crate::test_util::memtable_util::EmptyMemtableBuilder::default()), + 0, + None, + ); + let request = ScanRequest { + exact_sequence_range: true, + read_row_sequence: true, + memtable_min_sequence: Some(5), + memtable_max_sequence: Some(10), + ..Default::default() + }; + + for (sequence, marked, expected_range, expected_error) in [ + (NonZeroU64::new(6), false, true, false), + (NonZeroU64::new(6), true, true, false), + (None, false, false, true), + (None, true, false, true), + ] { + let version = crate::region::version::VersionBuilder::new( + metadata.clone(), + mutable.new_with_part_duration(None, None), + ) + .options(crate::region::options::RegionOptions { + preserve_row_sequence: true, + ..Default::default() + }) + .add_files( + new_noop_file_purger(), + [FileMeta { + region_id: RegionId::new(1, 2), + sequence, + preserve_row_sequence: marked, + ..Default::default() + }] + .into_iter(), + ) + .build(); + let result = exact_sequence_range(&request, &version); + if expected_error { + assert!( + matches!( + result, + Err(crate::error::Error::RegionSequenceDomainBroken { .. }) + ), + "a foreign file without an admission barrier must stay failed closed" + ); + } else { + let (files, range) = result.unwrap(); + assert_eq!(1, files.len()); + assert_eq!(expected_range, range.is_some()); + } + } + + // A region whose option is off cannot serve an exact range at all, so the excluded + // plateau (a source file with `preserve_row_sequence = false` and no cut) still fails + // closed there instead of being read as an ordinary file. + let version = crate::region::version::VersionBuilder::new( + metadata, + mutable.new_with_part_duration(None, None), + ) + .options(crate::region::options::RegionOptions { + preserve_row_sequence: false, + ..Default::default() + }) + .add_files( + new_noop_file_purger(), + [FileMeta { + region_id: RegionId::new(1, 2), + sequence: NonZeroU64::new(6), + ..Default::default() + }] + .into_iter(), + ) + .build(); + let (files, range) = exact_sequence_range(&request, &version).unwrap(); + assert_eq!(1, files.len()); + assert_eq!( + None, range, + "a region that does not preserve row sequences keeps denying the exact range" + ); + } + #[tokio::test] async fn test_parallel_flat_source_stops_after_receiver_dropped() { use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/src/mito2/src/read/scan_util.rs b/src/mito2/src/read/scan_util.rs index 9712a8dbef2..8ac0aacf7c2 100644 --- a/src/mito2/src/read/scan_util.rs +++ b/src/mito2/src/read/scan_util.rs @@ -1622,23 +1622,42 @@ pub fn build_flat_file_range_scan_stream( .substituted_sequence_cut(range.file_handle()) .map(|cut| (cut, windows)) }); - let file_sequence_trusted = range - .file_handle() - .is_effective_target_sequence_trusted(stream_ctx.input.region_metadata().region_id) - // A local file whose marker is unset is attributable above its substituted cut, - // which is applied just below. - || substituted_cut.is_some(); + // Which rows of this file this round has already consumed: whichever region + // allocated a row's number decides, through the cursor of the piece the row + // belongs to (with or without the cut above). Only a file whose region states no + // cursor this scan can use falls back to the scan's own `(C, H]`, which bounds a + // local file's numbering, and fails closed for a foreign one. + let (file_sequence_range, file_sequence_trusted) = + match stream_ctx.input.row_sequence_filter(range.file_handle())? { + Some(creator_range) => (Some(creator_range), true), + None => ( + stream_ctx.input.sequence_range, + // A local file whose marker is unset is attributable above its + // substituted cut, which was applied just above. + range + .file_handle() + .is_effective_target_sequence_trusted( + stream_ctx.input.region_metadata().region_id, + ) + || substituted_cut.is_some(), + ), + }; + + // Which `(region, partition expression)` this read observed. Local files are + // reported too, so a region's own slices stay observable after compaction rewrote + // adopted rows into local ones. + if let Some(observed) = stream_ctx.input.observed_slices() { + let meta = range.file_handle().meta_ref(); + observed.record(meta.region_id.as_u64(), meta.partition_expr.as_deref())?; + } while let Some(record_batch) = reader.next_batch().await? { - // Hides the rows a substitution produced and reports the windows they occupy, - // so the caller recomputes exactly those windows. + // Hides the rows a substitution produced and reports the windows they + // occupy, so the caller recomputes exactly those windows. let record_batch = match substituted_cut { Some((cut, windows)) => { - let Some(record_batch) = filter_flat_batch_by_substituted_sequence( - record_batch, - Some(cut), - windows, - )? + let Some(record_batch) = + filter_flat_batch_by_substituted_sequence(record_batch, Some(cut), windows)? else { continue; }; @@ -1648,12 +1667,24 @@ pub fn build_flat_file_range_scan_stream( }; let Some(record_batch) = filter_flat_batch_by_sequence( record_batch, - stream_ctx.input.sequence_range, + file_sequence_range, file_sequence_trusted, )? else { continue; }; + // Evidence for the caller: rows of a file another region created are reaching + // this read's output. Recorded after this region's own row filters, so a file + // opened, pruned or filtered down to nothing is not reported; a later stage of + // the same query may still drop these rows, which makes the answer an + // over-approximation rather than a claim about the final result. + if let Some(creators) = stream_ctx.input.foreign_file_row_creators() + && record_batch.num_rows() > 0 + && stream_ctx.input.is_foreign_file(range.file_handle()) + { + creators.record(range.file_handle().meta_ref().region_id.as_u64()); + } + if let Some(flat_compat) = may_compat { let batch = flat_compat.compat(record_batch)?; yield batch; diff --git a/src/mito2/src/read/seq_scan.rs b/src/mito2/src/read/seq_scan.rs index 027d5bd12c1..982e880e00c 100644 --- a/src/mito2/src/read/seq_scan.rs +++ b/src/mito2/src/read/seq_scan.rs @@ -30,7 +30,8 @@ use futures::{StreamExt, TryStreamExt}; use snafu::ensure; use store_api::metadata::RegionMetadataRef; use store_api::region_engine::{ - PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties, + PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScanSnapshotIdentity, + ScannerProperties, }; use store_api::storage::TimeSeriesRowSelector; use tokio::sync::Semaphore; @@ -419,11 +420,15 @@ impl SeqScan { input.mapper.output_schema(), Box::pin(record_batch_stream), )); - // The rows this scan hid (a physical-sequence read only) travel with the result, so the - // caller learns which time windows it has to recompute. + // The rows this scan hid, the slices it read (both a physical-sequence read only) and + // the other regions' files it delivered rows from travel with the result, so the + // caller learns which windows it has to recompute, which cursor slices it consumed + // and which adopted files reached its output. Ok(SubstitutedRowRangesStream::wrap( stream, input.substituted_row_ranges_ref(), + input.observed_slices_ref(), + input.foreign_file_row_creators_ref(), input.region_metadata().region_id.as_u64(), )) } @@ -671,8 +676,8 @@ impl RegionScanner for SeqScan { self.properties.set_query_load_region_id(region_id); } - fn snapshot_sequence(&self) -> Option { - self.stream_ctx.input.snapshot_sequence + fn snapshot_identity(&self) -> Option { + Some(self.stream_ctx.input.snapshot_identity()) } } diff --git a/src/mito2/src/read/series_reader.rs b/src/mito2/src/read/series_reader.rs index 3d5e3137c55..fed0ab4eda7 100644 --- a/src/mito2/src/read/series_reader.rs +++ b/src/mito2/src/read/series_reader.rs @@ -465,6 +465,11 @@ async fn build_uncached_series_partition_range( continue; } + // Only this region's own `(C, H]` and the file's trust decision bound these + // rows: a physical row-sequence read needs the creator's cursor slice and the + // substituted cut of an adopted file as well, which this per-series path cannot + // apply, so such a read is refused when the scan is built + // (`ScanRegion::series_scan`) instead of being approximated here. let stream = scan_series_file_ranges( part_metrics.clone(), ranges, diff --git a/src/mito2/src/read/series_scan.rs b/src/mito2/src/read/series_scan.rs index fa851f5cc59..eb2c920afb5 100644 --- a/src/mito2/src/read/series_scan.rs +++ b/src/mito2/src/read/series_scan.rs @@ -51,7 +51,7 @@ use store_api::metadata::RegionMetadataRef; use store_api::metric_engine_consts::is_metric_engine_internal_column; use store_api::region_engine::{ PartitionRange, PrepareRequest, QueryScanContext, RawLabelSource, RegionScanner, - ScannerProperties, SendableRawSeriesStream, + ScanSnapshotIdentity, ScannerProperties, SendableRawSeriesStream, }; use store_api::storage::consts::{ReservedColumnId, is_internal_column}; use table::predicate::Predicate; @@ -668,10 +668,14 @@ impl SeriesScan { metrics, ); - Ok(Box::pin(RecordBatchStreamWrapper::new( + let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamWrapper::new( input.mapper.output_schema(), Box::pin(record_batch_stream), - ))) + )); + // No substitution and no observed slices travel with this result: the per-series + // path never reads physical row sequences (`ScanRegion::series_scan` refuses + // `ScanRequest::read_row_sequence`), so there is no proof to carry. + Ok(stream) } #[tracing::instrument( @@ -1189,8 +1193,8 @@ impl RegionScanner for SeriesScan { self.properties.set_query_load_region_id(region_id); } - fn snapshot_sequence(&self) -> Option { - self.stream_ctx.input.snapshot_sequence + fn snapshot_identity(&self) -> Option { + Some(self.stream_ctx.input.snapshot_identity()) } } diff --git a/src/mito2/src/read/substituted_rows.rs b/src/mito2/src/read/substituted_rows.rs index 0bdc2a6d131..bb13abda889 100644 --- a/src/mito2/src/read/substituted_rows.rs +++ b/src/mito2/src/read/substituted_rows.rs @@ -17,13 +17,20 @@ //! A physical-sequence read (`ScanRequest::read_row_sequence`) drops every row whose number is //! at or below the file's own substituted cut //! ([`FileMeta::substituted_up_to`](crate::sst::file::FileMeta::substituted_up_to)) and records -//! the timestamps of the dropped rows here, so the caller recomputes those windows. +//! the timestamps of the dropped rows here, so the caller recomputes those windows. The same +//! read records which `(region, partition expression)` pairs it read +//! ([`ObservedPartitionExprs`]). Every read — physical-sequence or full — records which other +//! regions' files it delivered rows from ([`ForeignFileRowCreators`]). +use std::collections::BTreeSet; use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; -use common_recordbatch::adapter::{RecordBatchMetrics, SubstitutedRange, SubstitutedRowRanges}; +use common_recordbatch::adapter::{ + ObservedPartitionExpr, RecordBatchMetrics, SubstitutedRange, SubstitutedRowRanges, +}; use common_recordbatch::{OrderOption, RecordBatchStream, SendableRecordBatchStream}; use common_time::Timestamp; use common_time::timestamp::TimeUnit; @@ -32,10 +39,11 @@ use datatypes::arrow::compute::filter_record_batch; use datatypes::arrow::record_batch::RecordBatch; use datatypes::schema::SchemaRef; use futures::Stream; +use partition::expr::PartitionExpr; use snafu::ResultExt; use store_api::storage::SequenceNumber; -use crate::error::{ComputeArrowSnafu, Result}; +use crate::error::{ComputeArrowSnafu, Result, SerializePartitionExprSnafu}; use crate::read::timestamp_array_to_i64_slice; use crate::sst::parquet::flat_format::{sequence_column_index, time_index_column_index}; @@ -99,6 +107,120 @@ impl SubstitutedRowsAccumulator { } } +/// Accumulates the partition expressions of the regions a physical-sequence read observed, one +/// [`ObservedPartitionExpr`] per `(region, partition expression)` pair. +/// +/// Shared by every reader of one scan and deduplicated on insert. +#[derive(Debug, Default)] +pub(crate) struct ObservedPartitionExprs { + slices: Mutex>, +} + +pub(crate) type ObservedPartitionExprsRef = Arc; + +impl ObservedPartitionExprs { + pub(crate) fn new() -> Self { + Self::default() + } + + /// Records that rows of `(region_id, partition_expr)` were read. + /// + /// The expression is stored as its canonical identity (`PartitionExpr::as_json_str()`), + /// which is the form a cursor entry carries. `None` is the region's complete value domain. + pub(crate) fn record( + &self, + region_id: u64, + partition_expr: Option<&PartitionExpr>, + ) -> Result<()> { + let partition_expr = partition_expr + .map(|expr| expr.clone().canonicalize().as_json_str()) + .transpose() + .context(SerializePartitionExprSnafu)?; + // A poisoned lock cannot leave the set inconsistent (an insert is the only + // mutation), so it is recovered instead of failing the scan. + self.slices + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(ObservedPartitionExpr::new(region_id, partition_expr)); + Ok(()) + } + + /// Returns the observed pairs, sorted and deduplicated. + pub(crate) fn entries(&self) -> Vec { + self.slices + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .cloned() + .collect() + } +} + +/// Accumulates the creator regions of the adopted files this scan delivered rows from, i.e. +/// the regions that created a file whose rows reached this scan's output. +/// +/// Shared by every reader of one scan and deduplicated on insert. +#[derive(Debug, Default)] +pub(crate) struct ForeignFileRowCreators { + creators: Mutex>, + /// Set when rows reached this scan's output without passing a reader that records them, + /// so the recorded set does not describe everything the scan delivered. + replay_unknown: AtomicBool, +} + +pub(crate) type ForeignFileRowCreatorsRef = Arc; + +impl ForeignFileRowCreators { + pub(crate) fn new() -> Self { + Self::default() + } + + /// Records that at least one row of a file `creator_region_id` created survived this + /// region's own row filters and entered the scan's output. + /// + /// The evidence is reported per creator region rather than per file because a caller can + /// only act on the creator: the numbers in the row are the creator's, and it is the + /// creator's watermark that has to cover them. + pub(crate) fn record(&self, creator_region_id: u64) { + // A poisoned lock cannot leave the set inconsistent (an insert is the only + // mutation), so it is recovered instead of failing the scan. + self.creators + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(creator_region_id); + } + + /// Records that this scan delivered rows this accumulator cannot speak for, so its answer + /// is unknown instead of "delivered none". + /// + /// A range result replayed from the range cache, or read from a range another scan's + /// source produced, was decoded by a reader of that other scan: no file of this scan's + /// read was opened, so nothing here names the creators of the rows it delivered. The rows + /// are real, and a consumer must not hear that none of them came from another region. + pub(crate) fn record_replay_unknown(&self) { + self.replay_unknown.store(true, Ordering::Relaxed); + } + + /// Returns the recorded creator regions, sorted and deduplicated. + pub(crate) fn entries(&self) -> Vec { + self.creators + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .copied() + .collect() + } + + /// Returns the answer this scan states: the creator regions whose rows it delivered, or + /// `None` when it cannot say which those were. + pub(crate) fn answer(&self) -> Option> { + if self.replay_unknown.load(Ordering::Relaxed) { + return None; + } + Some(self.entries()) + } +} + /// Drops the rows of `record_batch` whose physical sequence is at or below `cut`. /// /// The batch must still carry the flat format's internal columns, i.e. this runs before @@ -207,7 +329,8 @@ fn to_time_unit(unit: datatypes::arrow::datatypes::TimeUnit) -> TimeUnit { } } -/// Wraps a scan stream so its terminal metrics carry what the scan substituted. +/// Wraps a scan stream so its terminal metrics carry what the scan substituted and read, and +/// which adopted files it delivered rows from. /// /// Mirrors how a region reports its snapshot watermark: the proof travels with the /// result instead of a side channel, so a caller that stops reading early never @@ -215,22 +338,28 @@ fn to_time_unit(unit: datatypes::arrow::datatypes::TimeUnit) -> TimeUnit { pub(crate) struct SubstitutedRowRangesStream { stream: SendableRecordBatchStream, ranges: Option, + observed_slices: Option, + foreign_file_row_creators: Option, region_id: u64, } impl SubstitutedRowRangesStream { - /// Wraps `stream`, or returns it unchanged when the scan reports no range. + /// Wraps `stream`, or returns it unchanged when the scan reports none of the three. pub(crate) fn wrap( stream: SendableRecordBatchStream, ranges: Option, + observed_slices: Option, + foreign_file_row_creators: Option, region_id: u64, ) -> SendableRecordBatchStream { - if ranges.is_none() { + if ranges.is_none() && observed_slices.is_none() && foreign_file_row_creators.is_none() { return stream; } Box::pin(Self { stream, ranges, + observed_slices, + foreign_file_row_creators, region_id, }) } @@ -257,6 +386,19 @@ impl RecordBatchStream for SubstitutedRowRangesStream { metrics.substituted_row_ranges = substituted; } } + if let Some(observed) = &self.observed_slices { + let slices = observed.entries(); + if !slices.is_empty() { + metrics.observed_slices = slices; + } + } + // An answer, not an absence: this read states which adopted files it delivered rows + // from even when that is none, so the caller can tell "delivered none" from the + // unknown an earlier build's payload states. A read that replayed a range states + // nothing, because it did not open the files that produced the rows. + if let Some(creators) = &self.foreign_file_row_creators { + metrics.foreign_file_row_creators = creators.answer(); + } Some(metrics) } } diff --git a/src/mito2/src/read/unordered_scan.rs b/src/mito2/src/read/unordered_scan.rs index 0d251456113..1b97daf12cd 100644 --- a/src/mito2/src/read/unordered_scan.rs +++ b/src/mito2/src/read/unordered_scan.rs @@ -30,7 +30,7 @@ use futures::{Stream, StreamExt}; use snafu::ensure; use store_api::metadata::RegionMetadataRef; use store_api::region_engine::{ - PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties, + PrepareRequest, QueryScanContext, RegionScanner, ScanSnapshotIdentity, ScannerProperties, }; use crate::error::{PartitionOutOfRangeSnafu, Result}; @@ -244,11 +244,15 @@ impl UnorderedScan { input.mapper.output_schema(), Box::pin(record_batch_stream), )); - // The rows this scan hid (a physical-sequence read only) travel with the result, so the - // caller learns which time windows it has to recompute. + // The rows this scan hid, the slices it read (both a physical-sequence read only) and + // the other regions' files it delivered rows from travel with the result, so the + // caller learns which windows it has to recompute, which cursor slices it consumed + // and which adopted files reached its output. Ok(SubstitutedRowRangesStream::wrap( stream, input.substituted_row_ranges_ref(), + input.observed_slices_ref(), + input.foreign_file_row_creators_ref(), input.region_metadata().region_id.as_u64(), )) } @@ -390,8 +394,8 @@ impl RegionScanner for UnorderedScan { self.properties.set_query_load_region_id(region_id); } - fn snapshot_sequence(&self) -> Option { - self.stream_ctx.input.snapshot_sequence + fn snapshot_identity(&self) -> Option { + Some(self.stream_ctx.input.snapshot_identity()) } } diff --git a/src/mito2/src/sst/parquet/file_range.rs b/src/mito2/src/sst/parquet/file_range.rs index cd529cc6c7d..858acb88518 100644 --- a/src/mito2/src/sst/parquet/file_range.rs +++ b/src/mito2/src/sst/parquet/file_range.rs @@ -20,10 +20,10 @@ use std::ops::{BitAnd, Range}; use std::sync::Arc; use api::v1::{OpType, SemanticType}; -use common_telemetry::error; +use common_telemetry::{debug, error}; use datafusion::physical_plan::PhysicalExpr; use datafusion::physical_plan::expressions::DynamicFilterPhysicalExpr; -use datatypes::arrow::array::{Array as _, ArrayRef, BooleanArray}; +use datatypes::arrow::array::{Array as _, ArrayRef, BooleanArray, BooleanBufferBuilder}; use datatypes::arrow::buffer::BooleanBuffer; use datatypes::arrow::record_batch::RecordBatch; use datatypes::schema::Schema; @@ -36,14 +36,15 @@ use parquet::file::statistics::Statistics; use snafu::{OptionExt, ResultExt, ensure}; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::RegionMetadataRef; -use store_api::storage::{ColumnId, TimeSeriesRowSelector}; +use store_api::storage::{ColumnId, SequenceNumber, SequenceRange, TimeSeriesRowSelector}; use table::predicate::Predicate; use tokio::sync::OnceCell; use crate::cache::CacheStrategy; use crate::error::{ ComputeArrowSnafu, DecodeStatsSnafu, EvalPartitionFilterSnafu, InvalidRecordBatchSnafu, - NewRecordBatchSnafu, RecordBatchSnafu, Result, StatsNotPresentSnafu, UnexpectedSnafu, + NewRecordBatchSnafu, RecordBatchSnafu, Result, SequenceRangeUnsupportedSnafu, + StatsNotPresentSnafu, UnexpectedSnafu, }; use crate::read::compat::FlatCompatBatch; use crate::read::last_row::FlatRowGroupLastRowCachedReader; @@ -51,7 +52,7 @@ use crate::read::prune::FlatPruneReader; use crate::sst::file::FileHandle; use crate::sst::parquet::flat_format::{ DecodedPrimaryKeys, FlatReadFormat, decode_primary_keys, primary_key_column_index, - time_index_column_index, + sequence_column_index, time_index_column_index, }; use crate::sst::parquet::json_align::ProjectedRecordBatchStream; use crate::sst::parquet::prefilter::primary_key_filter_mask; @@ -592,10 +593,64 @@ impl PreFilterMode { /// Context for partition expression filtering. pub(crate) struct PartitionFilterContext { - pub(crate) region_partition_physical_expr: Arc, - /// Schema containing only columns referenced by the partition expression. + /// Physical expression that selects the rows belonging to this region, or `None` when + /// the file states this region's own expression (every row of it belongs here). + pub(crate) region_partition_physical_expr: Option>, + /// Schema containing only the columns referenced by the expressions of this context. /// This is used to build a minimal RecordBatch for partition filter evaluation. pub(crate) partition_schema: Arc, + /// The creator's cursor slices a physical-sequence read of an adopted file may hold + /// rows of, compiled for per-row evaluation + /// ([`ScanRequest::creator_cursor_shards`](store_api::storage::ScanRequest)). + /// + /// The slices are the creator's own partition expressions, so they do not overlap and + /// at most one of them selects a given row. Empty for every other read. + pub(crate) creator_slices: Vec, + /// Cursor applied to a row of the creator's domain that no slice expression selects. + /// `None` when [`Self::creator_slices`] is empty. + /// + /// A row no slice explains is bounded by the least advanced candidate. That bound is the + /// row's own piece's answer only while every candidate carries it: when the candidates + /// disagree, the read fails with + /// [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported) instead of + /// delivering the rows a more advanced piece has already consumed. + pub(crate) fallback_cursor: Option, + /// The file's own substituted cut + /// (`FileMeta::substituted_up_to`), when it states one. + /// + /// A row at or below the cut carries a sequence a substitution produced, so its number + /// says nothing about progress. Such a row is left for the substitution rule, which + /// hides it **and** reports its time range for recomputation; deciding it here instead + /// would drop it without that report. + pub(crate) substituted_cut: Option, +} + +/// Candidate creator cursor slices of one adopted file, as the scan side selects them: +/// `(partition expression identity, last consumed sequence)` pairs. +pub(crate) type CreatorSliceCursors = Arc>; + +/// One candidate creator-cursor slice, compiled for per-row evaluation. +pub(crate) struct CreatorSliceFilter { + /// The slice's partition expression. + pub(crate) filter: Arc, + /// Last sequence consumed in that slice: a row this expression selects is delivered + /// only when its own sequence is above this value. + pub(crate) cursor: SequenceNumber, +} + +/// 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 +/// [`PartitionFilterContext::fallback_cursor`] bounds a row no candidate selects exactly. +fn creator_cursor_span(slices: &[CreatorSliceFilter]) -> (SequenceNumber, SequenceNumber) { + let mut span: Option<(SequenceNumber, SequenceNumber)> = None; + for slice in slices { + span = Some(match span { + None => (slice.cursor, slice.cursor), + Some((min, max)) => (min.min(slice.cursor), max.max(slice.cursor)), + }); + } + span.unwrap_or_default() } /// Common fields for a range to read and filter batches. @@ -660,14 +715,29 @@ impl RangeBase { }; // Apply partition filter - if let Some(partition_filter) = &self.partition_filter { + if let Some(partition_filter) = &self.partition_filter + && (partition_filter.region_partition_physical_expr.is_some() + || !partition_filter.creator_slices.is_empty()) + { let record_batch = self.project_record_batch_for_pruning_flat( &input, &partition_filter.partition_schema, &mut tag_decode_state, )?; - let partition_mask = self.evaluate_partition_filter(&record_batch, partition_filter)?; - mask = mask.bitand(&partition_mask); + if let Some(region_partition_physical_expr) = + &partition_filter.region_partition_physical_expr + { + let partition_mask = + self.evaluate_partition_filter(&record_batch, region_partition_physical_expr)?; + mask = mask.bitand(&partition_mask); + } + // Which rows of the file this round has already consumed: decided per row by + // the creator slice the row belongs to, not by one bound for the whole file. + if !partition_filter.creator_slices.is_empty() { + let sequence_mask = + self.evaluate_creator_slices(&input, &record_batch, partition_filter)?; + mask = mask.bitand(&sequence_mask); + } } let num_selected = mask.count_set_bits(); @@ -895,10 +965,9 @@ impl RangeBase { fn evaluate_partition_filter( &self, record_batch: &RecordBatch, - partition_filter: &PartitionFilterContext, + region_partition_physical_expr: &Arc, ) -> Result { - let columnar_value = partition_filter - .region_partition_physical_expr + let columnar_value = region_partition_physical_expr .evaluate(record_batch) .context(EvalPartitionFilterSnafu)?; let array = columnar_value @@ -921,6 +990,145 @@ impl RangeBase { Ok(mask) } + /// Computes the mask of rows a physical-sequence read of an adopted file has **not** + /// consumed yet. + /// + /// A row is delivered only when its own sequence is above the cursor of the creator + /// slice whose expression selects it: the slice the row belongs to decides, not one + /// bound for the whole file. That keeps the read free of re-reads when the file was + /// written under one coarse expression while the creator's domain has since been split + /// 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 + /// row's own piece's answer — and states nothing about the row once the candidates differ: + /// it delivers the rows a more advanced piece has already consumed, which is a duplicate, + /// not a replay, so the read fails with + /// [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported) instead. + fn evaluate_creator_slices( + &self, + input: &RecordBatch, + record_batch: &RecordBatch, + partition_filter: &PartitionFilterContext, + ) -> Result { + let num_rows = record_batch.num_rows(); + let slices = &partition_filter.creator_slices; + + // Per slice, the rows whose own sequence is above that slice's cursor. + let sequence_column = input.column(sequence_column_index(input.num_columns())); + let fallback_cursor = partition_filter.fallback_cursor.unwrap_or_default(); + let mut not_consumed = Vec::with_capacity(slices.len() + 1); + for slice in slices { + let mask = SequenceRange::Gt { min: slice.cursor } + .filter(sequence_column) + .context(ComputeArrowSnafu)?; + not_consumed.push(mask); + } + let fallback_mask = SequenceRange::Gt { + min: fallback_cursor, + } + .filter(sequence_column) + .context(ComputeArrowSnafu)?; + + // Per row, the slice whose expression selects it. + let mut selected = Vec::with_capacity(slices.len()); + for slice in slices { + selected.push(self.evaluate_partition_filter(record_batch, &slice.filter)?); + } + + let substituted_mask = match partition_filter.substituted_cut { + // Rows at or below the cut are the substitution rule's business. + Some(cut) => Some( + SequenceRange::LtEq { max: cut } + .filter(sequence_column) + .context(ComputeArrowSnafu)?, + ), + None => None, + }; + + let mut kept = BooleanBufferBuilder::new(num_rows); + let mut unmatched = 0; + // The candidates' own span, resolved on the first row no candidate selects: while + // every candidate carries the same value the fallback below is that row's answer and + // the span is never asked for. + let mut cursor_span: Option<(SequenceNumber, SequenceNumber)> = None; + for row in 0..num_rows { + // A row at or below the substituted cut is re-read on purpose by the substitution + // rule, so no cursor decision — and no disagreement — applies to it. + if substituted_mask + .as_ref() + .is_some_and(|mask| mask.value(row)) + { + kept.append(true); + continue; + } + // 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) = + *cursor_span.get_or_insert_with(|| creator_cursor_span(slices)); + if min != max { + let region_id = self.read_format.metadata().region_id; + return SequenceRangeUnsupportedSnafu { + region_id, + min_seq: min, + max_seq: max, + reason: format!( + "the physical-sequence read of a file of region {} cannot \ + resolve a per-piece cursor: {} of {} rows of the file match no \ + candidate creator cursor slice, while the candidate slices of \ + that region disagree on the last consumed sequence ({}..={}), \ + so bounding those rows by the least advanced cursor {} would \ + deliver the rows a more advanced piece has already consumed", + region_id, unmatched, num_rows, min, max, min + ), + } + .fail(); + } + fallback_mask.value(row) + } + }; + kept.append(keep); + } + if unmatched > 0 { + debug!( + "{} of {} rows of an adopted file match no creator cursor slice; bounding them by the least advanced cursor {}, which every candidate carries", + unmatched, num_rows, fallback_cursor + ); + } + + Ok(kept.finish()) + } + /// Projects the input `RecordBatch` to match the given schema. /// /// This is used for partition expression evaluation. The schema should only contain @@ -1176,7 +1384,10 @@ mod tests { pre_filter_mode: PreFilterMode::All, partition_filter: Some(PartitionFilterContext { partition_schema: partition_schema.clone(), - region_partition_physical_expr: partition_expr.clone(), + region_partition_physical_expr: Some(partition_expr.clone()), + creator_slices: Vec::new(), + fallback_cursor: None, + substituted_cut: None, }), }; for (skip_fields, skip_tags, expected) in [ @@ -1266,11 +1477,16 @@ mod tests { true, )])); base.partition_filter = Some(PartitionFilterContext { - region_partition_physical_expr: partition_col("tag_0") - .eq(Value::String("".into())) - .try_as_physical_expr(schema.arrow_schema()) - .unwrap(), + region_partition_physical_expr: Some( + partition_col("tag_0") + .eq(Value::String("".into())) + .try_as_physical_expr(schema.arrow_schema()) + .unwrap(), + ), partition_schema: schema.clone(), + creator_slices: Vec::new(), + fallback_cursor: None, + substituted_cut: None, }); let temporary = base .project_record_batch_for_pruning_flat(&batch, &schema, &mut TagDecodeState::new()) @@ -1332,10 +1548,15 @@ mod tests { .gt_eq(Value::String("a".into())) .and(partition_col("tag_0").lt(Value::String("c".into()))); base.partition_filter = Some(PartitionFilterContext { - region_partition_physical_expr: partition_expr - .try_as_physical_expr(partition_schema.arrow_schema()) - .unwrap(), + region_partition_physical_expr: Some( + partition_expr + .try_as_physical_expr(partition_schema.arrow_schema()) + .unwrap(), + ), partition_schema, + creator_slices: Vec::new(), + fallback_cursor: None, + substituted_cut: None, }); let filtered = base diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index ca4d7352bc9..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; @@ -58,8 +58,8 @@ use crate::cache::{ prepare_sst_meta, }; use crate::error::{ - ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, SerializePartitionExprSnafu, - UnexpectedSnafu, + InvalidPartitionExprSnafu, ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, + SequenceRangeUnsupportedSnafu, SerializePartitionExprSnafu, UnexpectedSnafu, }; use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED}; use crate::read::prune::FlatPruneReader; @@ -76,7 +76,8 @@ use crate::sst::index::inverted_index::applier::{ InvertedIndexApplierRef, InvertedIndexApplyMetrics, }; use crate::sst::parquet::file_range::{ - FileRangeContext, FileRangeContextRef, PartitionFilterContext, PreFilterMode, RangeBase, + CreatorSliceCursors, CreatorSliceFilter, FileRangeContext, FileRangeContextRef, + PartitionFilterContext, PreFilterMode, RangeBase, }; use crate::sst::parquet::flat_format::{FlatReadFormat, primary_key_column_index}; use crate::sst::parquet::format::{INTERNAL_COLUMN_NUM, need_override_sequence}; @@ -214,6 +215,13 @@ pub struct ParquetReaderBuilder { expected_metadata: Option, /// Whether this reader is for compaction. compaction: bool, + /// Force every row's sequence to the file's admission barrier, whatever the + /// file's own sequence column and trust markers say. + /// + /// Used only by Flow recovery window discovery, which needs the timestamps of + /// the rows a harness cannot trust row by row; ordinary reads leave it `false` + /// and keep the foreign/legacy conditional override. + force_sequence_override: bool, /// Keep the physical `__sequence` column of a foreign file instead of virtualizing /// it at the handle's barrier. /// @@ -230,6 +238,13 @@ pub struct ParquetReaderBuilder { postpone_time_index_filter: bool, /// Whether to decode primary key values eagerly when reading primary key format SSTs. decode_primary_key_values: bool, + /// Candidate creator-cursor slices of a physical-sequence read of an adopted file: + /// `(partition expression identity, last consumed sequence)` pairs + /// ([`ScanRequest::creator_cursor_shards`](store_api::storage::ScanRequest)). + /// + /// The scan side has already dropped the slices whose expression cannot hold rows of + /// this file. Every reader but that one leaves it `None`. + creator_slice_cursors: Option, page_index_policy: PageIndexPolicy, defer_optional_page_index: bool, /// Scan-wide hint for rows in a decoded batch. @@ -268,11 +283,13 @@ impl ParquetReaderBuilder { fulltext_index_appliers: [None, None], expected_metadata: None, compaction: false, + force_sequence_override: false, read_row_sequence: false, pre_filter_mode: PreFilterMode::All, enable_predicate_prefilter: true, postpone_time_index_filter: false, decode_primary_key_values: false, + creator_slice_cursors: None, page_index_policy: Default::default(), defer_optional_page_index: false, batch_size: DEFAULT_READ_BATCH_SIZE, @@ -367,6 +384,30 @@ impl ParquetReaderBuilder { self } + /// Forces the row-level sequence override to the file's admission barrier. + /// + /// Only Flow recovery window discovery sets this: it needs the timestamps of + /// every selected file's rows and must not depend on the file's sequence column + /// or on its trust markers. + #[must_use] + pub fn force_sequence_override(mut self, force_sequence_override: bool) -> Self { + self.force_sequence_override = force_sequence_override; + self + } + + /// Sets the candidate creator-cursor slices of a physical-sequence read of an adopted + /// file: `(partition expression identity, last consumed sequence)` pairs. + /// + /// The reader compiles each identity into a row filter and keeps a row only when its + /// own sequence is above the cursor of the slice whose expression selects it + /// (`PartitionFilterContext::creator_slices`), so the file's rows are split by the + /// domain they belong to instead of by one bound for the whole file. + #[must_use] + pub(crate) fn creator_slice_cursors(mut self, cursors: Option) -> Self { + self.creator_slice_cursors = cursors; + self + } + /// Reads the physical `__sequence` of a foreign file instead of substituting the /// handle's barrier for every row. /// @@ -534,7 +575,13 @@ impl ParquetReaderBuilder { ); } let file_meta = self.file_handle.meta_ref(); - let override_sequence = if self.read_row_sequence && is_foreign { + let override_sequence = if self.force_sequence_override { + // Recovery discovery: virtualize every row at the file's own admission + // barrier. The rows may carry a foreign or legacy sequence column, and + // discovery only needs their timestamps, so the barrier is the only + // sequence that can be trusted. + file_meta.sequence.map(|sequence| sequence.get()) + } else if self.read_row_sequence && is_foreign { // A physical-sequence read keeps an adopted file's own column instead of the // substitution below. `preserve_row_sequence` takes no part: an import only // re-marks the handle and copies the bytes, and the file's own @@ -737,11 +784,62 @@ 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. /// Compare partition expressions from expected metadata and file metadata, /// and build a partition filter if they differ. + /// + /// It also compiles the candidate creator-cursor slices of a physical-sequence read + /// (`Self::creator_slice_cursors`) into row filters: both are per-row expressions over + /// the same minimal schema, so one projection of the batch serves all of them. fn build_partition_filter( &self, read_format: &FlatReadFormat, @@ -756,17 +854,52 @@ impl ParquetReaderBuilder { let (region_partition_expr, is_same_region_partition) = Self::is_same_region_partition(region_partition_expr_str, file_partition_expr_ref)?; - if is_same_region_partition { + // A file stating this region's own expression holds only this region's rows, so it + // needs no region filter; the creator slices below are independent of that. + let region_partition_expr = if is_same_region_partition { + None + } else { + region_partition_expr + }; + + let slice_cursors = self + .creator_slice_cursors + .as_deref() + .map(Vec::as_slice) + .unwrap_or_default(); + if region_partition_expr.is_none() && slice_cursors.is_empty() { return Ok(None); } - let Some(region_partition_expr) = region_partition_expr else { - return Ok(None); - }; - - // Collect columns referenced by the partition expression. + // Collect columns referenced by every expression this context evaluates. let mut referenced_columns = HashSet::new(); - region_partition_expr.collect_column_names(&mut referenced_columns); + if let Some(expr) = ®ion_partition_expr { + expr.collect_column_names(&mut referenced_columns); + } + let mut creator_slices = Vec::with_capacity(slice_cursors.len()); + for (identity, cursor) in slice_cursors { + let Some(expr) = PartitionExpr::from_json_str(identity) + .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. 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 {}; 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); + creator_slices.push((expr, *cursor)); + } // Build a partition_schema containing only referenced columns. let partition_schema = Arc::new(datatypes::schema::Schema::new( @@ -797,12 +930,28 @@ impl ParquetReaderBuilder { )); let region_partition_physical_expr = region_partition_expr - .try_as_physical_expr(partition_schema.arrow_schema()) + .map(|expr| expr.try_as_physical_expr(partition_schema.arrow_schema())) + .transpose() .context(SerializePartitionExprSnafu)?; + let creator_slices = creator_slices + .into_iter() + .map(|(expr, cursor)| { + Ok(CreatorSliceFilter { + filter: expr + .try_as_physical_expr(partition_schema.arrow_schema()) + .context(SerializePartitionExprSnafu)?, + cursor, + }) + }) + .collect::>>()?; + let fallback_cursor = creator_slices.iter().map(|slice| slice.cursor).min(); Ok(Some(PartitionFilterContext { region_partition_physical_expr, partition_schema, + creator_slices, + fallback_cursor, + substituted_cut: self.file_handle.meta_ref().substituted_up_to, })) }