diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index a63c44adae9..70d128e83d7 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -76,6 +76,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; diff --git a/src/mito2/src/engine/copy_region_from_test.rs b/src/mito2/src/engine/copy_region_from_test.rs index ec8ff8a292c..39bb14a8414 100644 --- a/src/mito2/src/engine/copy_region_from_test.rs +++ b/src/mito2/src/engine/copy_region_from_test.rs @@ -253,9 +253,13 @@ async fn test_copy_shared_reference_contract( } /// A physical copy relabels the bytes under a new creator, so the target inherits no proof of the -/// numbers inside them: the copy states nothing about the numbering it carries. +/// numbers inside them: an exact physical read refuses the copied file instead of replaying the +/// source's numbering as this region's. #[tokio::test] async fn test_copy_region_from_drops_the_row_sequence_proof() { + use store_api::storage::CursorShard; + + use crate::engine::scan_slice_test::{piece_scan, scan_error}; use crate::test_util::{build_rows_for_key, flush_region}; let mut env = TestEnv::with_prefix("copy-region-row-sequence-proof").await; @@ -324,6 +328,17 @@ async fn test_copy_region_from_drops_the_row_sequence_proof() { None, manifest.files[&source_file.file_id].row_sequence_provenance ); + + let err = scan_error( + &engine, + target_id, + piece_scan(source_id, vec![CursorShard::whole_domain(0)], 0, 10), + ) + .await; + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "a copied file states nothing about its numbers, so the exact read must refuse it: {err}" + ); } /// A copy keeps the source's `FileId` but names itself the creator. Re-importing the source's own 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..97b52a33fb4 --- /dev/null +++ b/src/mito2/src/engine/scan_slice_bounds_test.rs @@ -0,0 +1,419 @@ +// 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::storage::{CursorShard, RegionId}; + +use super::scan_slice_test::{ + create_region, piece_cursor, piece_scan, put_two_pieces, scan_error, scan_row_sequences, +}; +use crate::config::MitoConfig; +use crate::test_util; +use crate::test_util::TestEnv; + +/// Writes five rows of the series `1`, all of them inside the piece `[0, 5)`. +async fn put_left_piece_only( + engine: &crate::engine::MitoEngine, + region: RegionId, + schema: &[api::v1::ColumnSchema], +) { + test_util::put_rows( + engine, + region, + Rows { + schema: schema.to_vec(), + rows: test_util::build_rows_for_key("1", 0, 5, 0), + }, + ) + .await; +} + +/// A piece that states the last sequence its delta covers bounds the file from above as well: a +/// row above that bound was numbered after the delta this read stands for, so delivering it here +/// would report progress the caller has not made. +#[tokio::test] +async fn test_piece_scan_drops_rows_above_the_piece_upper_bound() { + let mut env = TestEnv::with_prefix("test_piece_scan_piece_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_left_piece_only(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + // The delta is `(1, 3]`: the rows 4 and 5 carry numbers the cursor did not consume and the + // bound does not cover. + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![CursorShard::whole_domain(1).with_until(3)], + 0, + 20, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "the rows above the piece's own upper bound belong to a later delta" + ); +} + +/// A piece 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 no bound excludes. +#[tokio::test] +async fn test_piece_scan_reads_above_the_cursor_without_an_upper_bound() { + let mut env = TestEnv::with_prefix("test_piece_scan_without_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_left_piece_only(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let rows = scan_row_sequences( + &engine, + region, + piece_scan(region, vec![CursorShard::whole_domain(1)], 0, 20), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "without a bound every row above the cursor is still owed" + ); +} + +/// Several candidate pieces: each row is bounded by the upper bound of the piece it belongs to, +/// never by one bound for the whole file. The counterexample this pins: the piece holding the +/// rows 3, 4 and 5 proves its delta ends at 3 while the other piece's reaches 9, so bounding the +/// whole file by the least bound would drop the row 6 that its own piece still owes. +#[tokio::test] +async fn test_piece_scan_bounds_each_piece_by_its_own_upper_bound() { + let mut env = TestEnv::with_prefix("test_piece_scan_piece_own_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_two_pieces(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![ + piece_cursor("0", "5", 2).with_until(3), + piece_cursor("5", "9", 2).with_until(9), + ], + 1, + 20, + ), + ) + .await; + assert_eq!( + vec![(2000, 3), (5000, 6)], + rows, + "the row at 6 belongs to the piece whose delta reaches 9, and the rows 4 and 5 to the \ + piece whose delta ends at 3" + ); +} + +/// Both bounds of a read that has not flushed yet: the piece cursor bounds the memtable rows from +/// below and the scan's own upper bound from above. +#[tokio::test] +async fn test_piece_scan_memtable_applies_both_bounds() { + let mut env = TestEnv::with_prefix("test_piece_scan_memtable_both_bounds").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_left_piece_only(&engine, region, &schema).await; + + // `(3, 4]`: the piece consumed up to 3, and the scan's own bound excludes the row at 5. + let rows = scan_row_sequences( + &engine, + region, + piece_scan(region, vec![piece_cursor("0", "5", 3)], 1, 4), + ) + .await; + assert_eq!( + vec![(3000, 4)], + rows, + "the time-series memtable owes row 4 only" + ); + + // The same bounds for the bulk memtable. + let bulk_region = RegionId::new(1, 2); + let schema = create_region(&engine, bulk_region, "flat").await; + put_left_piece_only(&engine, bulk_region, &schema).await; + let rows = scan_row_sequences( + &engine, + bulk_region, + piece_scan(bulk_region, vec![piece_cursor("0", "5", 3)], 1, 4), + ) + .await; + assert_eq!(vec![(3000, 4)], rows, "the bulk memtable owes row 4 only"); +} + +/// A shard that names no expression selects the whole domain, and its range still bounds every +/// row: skipping the expression evaluation must not fall back to the region-level floor. +/// +/// Request `(0, 10]` with the whole-domain shard `(1, 3]`: the rows 2 and 3 are owed, and both +/// memtable kinds and a flushed file must deliver exactly them. +#[tokio::test] +async fn test_piece_scan_whole_domain_shard_bounds_every_source() { + let mut env = TestEnv::with_prefix("test_piece_scan_whole_domain_shard").await; + let engine = env.create_engine(MitoConfig::default()).await; + + for (region, format, flush) in [ + (RegionId::new(1, 1), "primary_key", false), + (RegionId::new(1, 2), "flat", false), + (RegionId::new(1, 3), "primary_key", true), + ] { + let schema = create_region(&engine, region, format).await; + put_left_piece_only(&engine, region, &schema).await; + if flush { + test_util::flush_region(&engine, region, None).await; + } + + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![CursorShard::whole_domain(1).with_until(3)], + 0, + 10, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "region {region} ({format}, flushed: {flush}): a whole-domain shard still bounds the \ + rows it owes" + ); + } +} + +/// The read's own snapshot `H` caps every effective bound of this region's rows: a row this +/// region numbered above `H` does not exist yet in this read, so no piece owes it. A shard that +/// states a looser bound (`(1, 6]` with `H = 4`) must not deliver the row at 5. +#[tokio::test] +async fn test_piece_scan_caps_own_upper_bound_by_the_snapshot() { + let mut env = TestEnv::with_prefix("test_piece_scan_caps_by_snapshot").await; + let engine = env.create_engine(MitoConfig::default()).await; + + for (region, format, flush) in [ + (RegionId::new(1, 1), "primary_key", false), + (RegionId::new(1, 2), "flat", false), + (RegionId::new(1, 3), "primary_key", true), + ] { + let schema = create_region(&engine, region, format).await; + put_left_piece_only(&engine, region, &schema).await; + if flush { + test_util::flush_region(&engine, region, None).await; + } + + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![CursorShard::whole_domain(1).with_until(6)], + 0, + 4, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4)], + rows, + "region {region} ({format}, flushed: {flush}): the read's own snapshot caps what its \ + pieces may owe" + ); + } +} + +/// The request floor is the region-level lower bound used to prune files, so it is conservative +/// only while it does not exceed a shard's own floor: a shard consumed up to 2 still owes the +/// rows above it, and pruning them away would truncate the delta. The read is refused instead. +#[tokio::test] +async fn test_piece_scan_rejects_a_request_floor_above_a_piece_floor() { + let mut env = TestEnv::with_prefix("test_piece_scan_floor_above_piece").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_left_piece_only(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let err = scan_error( + &engine, + region, + piece_scan(region, vec![piece_cursor("0", "5", 2)], 5, 10), + ) + .await; + assert!( + matches!(err, crate::error::Error::SequenceRangeUnsupported { .. }), + "a request floor above a shard's own floor must not prune that shard's rows: {err}" + ); +} + +/// A shard whose upper bound sits below its own cursor owes no row at all, so it is an invalid +/// request rather than an empty range. +#[tokio::test] +async fn test_piece_scan_rejects_an_inverted_piece_bound() { + let mut env = TestEnv::with_prefix("test_piece_scan_inverted_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_left_piece_only(&engine, region, &schema).await; + + let err = scan_error( + &engine, + region, + piece_scan( + region, + vec![CursorShard::whole_domain(3).with_until(2)], + 0, + 10, + ), + ) + .await; + assert!( + matches!(err, crate::error::Error::InvalidRequest { .. }), + "an upper bound below the shard's own cursor is an invalid request: {err}" + ); +} + +/// Runs the mixed-shard read of `region` twice: the whole-domain shard owes the rows 2 and 3 +/// while the partial shard `[0, 5)` owes them nothing, and then the partial shard consumed up to +/// 2 owes the rows 3, 4 and 5, so the union of both pieces is exactly what the read delivers. +async fn scan_whole_domain_with_a_partial_shard( + engine: &crate::engine::MitoEngine, + region: RegionId, +) -> (Vec<(i64, u64)>, Vec<(i64, u64)>) { + let rows = scan_row_sequences( + engine, + region, + piece_scan( + region, + vec![ + piece_cursor("0", "5", 5), + CursorShard::whole_domain(1).with_until(3), + ], + 0, + 10, + ), + ) + .await; + let lagging = scan_row_sequences( + engine, + region, + piece_scan( + region, + vec![ + piece_cursor("0", "5", 2), + CursorShard::whole_domain(1).with_until(3), + ], + 0, + 10, + ), + ) + .await; + (rows, lagging) +} + +/// A whole-domain shard and a partial shard state different ranges for the same rows, which is +/// no reason to refuse: the whole-domain piece selects every row and owes 2 and 3, and the rows +/// it does not owe are still decided by the partial piece's own cursor. A time-series memtable +/// resolves the piece of its whole batch once, from the tag values of its series. +#[tokio::test] +async fn test_piece_scan_whole_domain_shard_with_a_partial_shard_time_series_memtable() { + let mut env = TestEnv::with_prefix("test_piece_scan_whole_domain_with_partial_series").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_left_piece_only(&engine, region, &schema).await; + + let (rows, lagging) = scan_whole_domain_with_a_partial_shard(&engine, region).await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "the whole-domain piece owes the rows 2 and 3, and the piece consumed up to 5 owes none \ + of them" + ); + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + lagging, + "the partial piece consumed up to 2 owes the rows 3, 4 and 5 on top of the whole-domain \ + piece's 2 and 3" + ); +} + +/// The same mixed shards over a bulk memtable, which decides each row of a batch on its own from +/// the tag columns it keeps. +#[tokio::test] +async fn test_piece_scan_whole_domain_shard_with_a_partial_shard_bulk_memtable() { + let mut env = TestEnv::with_prefix("test_piece_scan_whole_domain_with_partial_bulk").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "flat").await; + put_left_piece_only(&engine, region, &schema).await; + + let (rows, lagging) = scan_whole_domain_with_a_partial_shard(&engine, region).await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "a bulk memtable keeps the rows the whole-domain piece owes" + ); + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + lagging, + "a bulk memtable keeps the union of what each selecting piece owes" + ); +} + +/// The same mixed shards over a flushed file, whose per-row rule compiles the whole-domain shard +/// into a filter selecting every row instead of refusing the file. +#[tokio::test] +async fn test_piece_scan_whole_domain_shard_with_a_partial_shard_flushed_sst() { + let mut env = TestEnv::with_prefix("test_piece_scan_whole_domain_with_partial_sst").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_left_piece_only(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let (rows, lagging) = scan_whole_domain_with_a_partial_shard(&engine, region).await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "a file keeps the rows the whole-domain piece owes" + ); + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + lagging, + "a file keeps the union of what each selecting piece owes" + ); +} 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..da5ebc794a2 --- /dev/null +++ b/src/mito2/src/engine/scan_slice_cache_test.rs @@ -0,0 +1,103 @@ +// 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 common_base::readable_size::ReadableSize; +use datafusion_expr::{col, lit}; +use store_api::storage::{RegionId, ScanRequest}; + +use super::scan_slice_test::{ + create_region, legacy_scan, piece_cursor, piece_scan, put_two_pieces, scan_row_sequences, +}; +use crate::config::MitoConfig; +use crate::test_util; +use crate::test_util::TestEnv; + +/// Restricts the scan to the rows of the series `1`, which is what makes its range result +/// cacheable at all. +fn tag_filtered(request: &mut ScanRequest) { + request.filters = vec![col("tag_0").eq(lit("1"))]; +} + +/// A range-cache entry produced by a legacy read must not answer a physical-sequence read: the +/// merged batch set carries no record of which piece produced a row, so replaying it would hand +/// the caller rows the read has already consumed. The two scans below state the same filter and +/// the same exact range over the same file, so only the missing opt-in keeps them apart. +#[tokio::test] +async fn test_piece_scan_does_not_replay_a_legacy_cached_range() { + let mut env = TestEnv::with_prefix("test_piece_scan_not_replay_legacy_cache").await; + let engine = env + .create_engine(MitoConfig { + range_result_cache_size: ReadableSize::mb(64), + ..Default::default() + }) + .await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_two_pieces(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + // Warms the range cache with the legacy read of the rows above the floor 1. + let mut warm = legacy_scan(1, 20); + tag_filtered(&mut warm); + let rows = scan_row_sequences(&engine, region, warm).await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "the legacy read delivers every row above its floor" + ); + + // The same filter and range, decided per piece: the rows 2 and 3 were consumed by the piece + // the remaining rows belong to, so the cached legacy answer must not be replayed. + let mut exact = piece_scan(region, vec![piece_cursor("0", "5", 3)], 1, 20); + tag_filtered(&mut exact); + let rows = scan_row_sequences(&engine, region, exact).await; + assert_eq!( + vec![(3000, 4), (4000, 5)], + rows, + "a physical-sequence read must not be answered by a range-cache entry of another intent" + ); +} + +/// The other direction: a physical-sequence read keeps no range-cache entry, so the legacy read +/// that follows it still sees every row above its own floor instead of the exact read's answer. +#[tokio::test] +async fn test_piece_scan_does_not_fill_the_range_cache() { + let mut env = TestEnv::with_prefix("test_piece_scan_does_not_fill_cache").await; + let engine = env + .create_engine(MitoConfig { + range_result_cache_size: ReadableSize::mb(64), + ..Default::default() + }) + .await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_two_pieces(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let mut exact = piece_scan(region, vec![piece_cursor("0", "5", 3)], 1, 20); + tag_filtered(&mut exact); + let rows = scan_row_sequences(&engine, region, exact).await; + assert_eq!(vec![(3000, 4), (4000, 5)], rows); + + let mut legacy = legacy_scan(1, 20); + tag_filtered(&mut legacy); + let rows = scan_row_sequences(&engine, region, legacy).await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "the legacy read must not inherit the rows a physical-sequence read delivered" + ); +} 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..ccd050202fa --- /dev/null +++ b/src/mito2/src/engine/scan_slice_fail_closed_test.rs @@ -0,0 +1,560 @@ +// 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::collections::BTreeMap; +use std::sync::Arc; + +use api::v1::Rows; +use store_api::region_engine::RegionEngine; +use store_api::region_request::{AlterKind, RegionAlterRequest, RegionRequest, SetRegionOption}; +use store_api::storage::{CursorShard, RegionId, ScanRequest}; + +use super::scan_slice_test::{ + create_region, legacy_scan, piece_cursor, piece_scan, scan_error, scan_row_sequences, +}; +use crate::config::MitoConfig; +use crate::engine::MitoEngine; +use crate::error::Error; +use crate::manifest::action::RegionEdit; +use crate::request::{RegionEditRequest, WorkerRequest}; +use crate::test_util; +use crate::test_util::{CreateRequestBuilder, TestEnv}; + +/// Creates an append-only source region that keeps the per-row sequences, writes `num_rows` rows +/// of one series and flushes them. +/// +/// Returns the flushed file's metadata, which is what a repartition publishes in the target +/// region: the bytes keep the numbers their writer allocated, while the handle is re-marked at the +/// holder's barrier. +async fn build_source_file( + engine: &MitoEngine, + source: RegionId, + num_rows: usize, +) -> crate::sst::file::FileMeta { + 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("1", 0, num_rows, 0), + }, + ) + .await; + test_util::flush_region(engine, source, None).await; + + let meta = engine + .get_region(source) + .unwrap() + .version() + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .next() + .expect("source file") + .meta_ref() + .clone(); + assert!( + meta.preserve_row_sequence, + "the source file must state the numbering its bytes carry" + ); + meta +} + +/// Creates an append-only source region that keeps **no** per-row sequence: its flush stamps one +/// uniform number on every row, so the file cannot state which number was assigned to which row. +/// +/// Returns the flushed file's metadata, whose bytes a repartition may still adopt unchanged. +async fn build_unproved_source_file( + engine: &MitoEngine, + source: RegionId, + num_rows: usize, +) -> crate::sst::file::FileMeta { + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "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("1", 0, num_rows, 0), + }, + ) + .await; + test_util::flush_region(engine, source, None).await; + + let meta = engine + .get_region(source) + .unwrap() + .version() + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .next() + .expect("source file") + .meta_ref() + .clone(); + assert!( + !meta.has_original_row_sequences(), + "a flush that stamps one number on every row cannot prove an allocator's numbering" + ); + meta +} + +/// Returns the region's single flushed file. +fn only_file(engine: &MitoEngine, region: RegionId) -> crate::sst::file::FileMeta { + engine + .get_region(region) + .unwrap() + .version() + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .next() + .expect("a flushed file") + .meta_ref() + .clone() +} + +/// Adopts `source_file` into `target` the way a repartition publishes it: the bytes stay +/// source-owned and the holder re-marks the handle at its own admission barrier. +/// +/// The edit takes the copy-reference lane the production copy path uses: it keeps whatever proof +/// the source's flush stated, while an external edit would drop it. +async fn adopt_file( + engine: &MitoEngine, + target: RegionId, + source_file: crate::sst::file::FileMeta, +) { + let provenance = source_file.row_sequence_provenance; + let (tx, rx) = tokio::sync::oneshot::channel(); + let request = RegionEditRequest::new( + target, + RegionEdit { + files_to_add: vec![source_file], + ..Default::default() + }, + false, + tx, + ) + .for_copy_region(); + engine + .inner + .workers + .submit_to_worker(target, WorkerRequest::EditRegion(request)) + .await + .unwrap(); + rx.await.unwrap().unwrap(); + + assert_eq!( + provenance, + only_file(engine, target).row_sequence_provenance, + "the holder keeps exactly the proof the source states, and states none of its own" + ); +} + +/// Creates the target region of a repartition, with the same preserved-sequence option. +async fn create_target(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(); +} + +/// A row no candidate piece selects cannot be attributed to a piece, and the least advanced +/// cursor only answers for the pieces that carry it: with the candidates disagreeing, delivering +/// the row would duplicate the rows a more advanced piece has already consumed. +#[tokio::test] +async fn test_piece_scan_fails_when_no_piece_selects_a_row() { + let mut env = TestEnv::with_prefix("test_piece_scan_fails_unattributed_row").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + // The rows of the pieces `[0, 5)` and `[5, 9)`, plus one series outside both of them. + let schema = create_region(&engine, region, "primary_key").await; + 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)); + rows.extend(test_util::build_rows_for_key("z", 6, 7, 0)); + test_util::put_rows( + &engine, + region, + Rows { + schema: schema.clone(), + rows, + }, + ) + .await; + test_util::flush_region(&engine, region, None).await; + + let err = scan_error( + &engine, + region, + piece_scan( + region, + vec![piece_cursor("0", "5", 5), piece_cursor("5", "9", 2)], + 1, + 20, + ), + ) + .await; + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "an unattributed row of disagreeing pieces must fail the read: {err}" + ); +} + +/// An adopted file's numbers belong to the region that allocated them, so a read that knows no +/// cursor of that region cannot split its rows into consumed and live ones and must fail rather +/// than deliver them whole. +#[tokio::test] +async fn test_piece_scan_fails_for_adopted_rows_without_a_creator_cursor() { + let mut env = TestEnv::with_prefix("test_piece_scan_fails_adopted_without_cursor").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_source_file(&engine, source, 3).await; + create_target(&engine, target).await; + adopt_file(&engine, target, source_file).await; + + // The only cursor this read states belongs to the holder, which allocated none of the file's + // numbers. + let mut request = piece_scan(target, vec![CursorShard::whole_domain(0)], 0, 10); + request.creator_cursor_shards = Some(Arc::new(BTreeMap::from([( + target.as_u64(), + vec![CursorShard::whole_domain(0)], + )]))); + let err = scan_error(&engine, target, request).await; + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "an adopted file without a cursor of its creator must fail the read: {err}" + ); + assert!( + err.to_string() + .contains("has no cursor of its creator region"), + "the read must refuse the file for its missing creator cursor, not for its proof: {err}" + ); +} + +/// An adopted file is compared against the numbers its creator allocated, never against the +/// admission barrier the holder virtualizes every row to: the barrier says when the file was +/// admitted, so it cannot tell a consumed row from a live one. +#[tokio::test] +async fn test_piece_scan_reads_the_creator_numbers_not_the_barrier() { + let mut env = TestEnv::with_prefix("test_piece_scan_creator_numbers").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..3. + let source_file = build_source_file(&engine, source, 3).await; + create_target(&engine, target).await; + adopt_file(&engine, target, source_file).await; + + // A cursor of 0 owes every row, and the numbers that reach the caller are the creator's own. + let rows = scan_row_sequences( + &engine, + target, + piece_scan(source, vec![CursorShard::whole_domain(0)], 0, 10), + ) + .await; + assert_eq!( + vec![(0, 1), (1000, 2), (2000, 3)], + rows, + "an adopted file's rows carry the creator's numbers, not one barrier value" + ); + + // A cursor of 2 owes the row the creator numbered 3 and nothing below it. + let rows = scan_row_sequences( + &engine, + target, + piece_scan(source, vec![CursorShard::whole_domain(2)], 0, 10), + ) + .await; + assert_eq!( + vec![(2000, 3)], + rows, + "the rows the creator numbered at or below the cursor are already consumed" + ); + + // The legacy read keeps virtualizing those rows at the holder's barrier, which is why the + // exact read cannot reuse its answer. + let rows = scan_row_sequences(&engine, target, legacy_scan(0, 10)).await; + assert_eq!( + 3, + rows.len(), + "the legacy read keeps the barrier substitution" + ); +} + +/// A piece expression this build cannot read back cannot decide a row's piece, and guessing would +/// drop rows, so the read fails instead of falling back to a bound of another domain. +/// +/// The two pieces carry the same cursor so the memtable side has nothing to reject and the file +/// side is the one that has to refuse the identity. +#[tokio::test] +async fn test_piece_scan_fails_on_an_unreadable_piece_expression() { + let mut env = TestEnv::with_prefix("test_piece_scan_unreadable_expression").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + test_util::put_rows( + &engine, + region, + Rows { + schema, + rows: test_util::build_rows_for_key("1", 0, 3, 0), + }, + ) + .await; + test_util::flush_region(&engine, region, None).await; + + 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([( + region.as_u64(), + vec![ + CursorShard::new(Some("not-a-partition-expression".to_string()), 5), + CursorShard::new(Some("neither-is-this".to_string()), 5), + ], + )]))), + ..Default::default() + }; + let err = scan_error(&engine, region, request).await; + assert!( + matches!(err, Error::InvalidPartitionExpr { .. }), + "a piece expression that cannot be read back must fail the read: {err}" + ); +} + +/// The read's own snapshot `H` is a statement about the numbers **this** region allocated, so it +/// caps only its own rows: an adopted file's numbers belong to its creator's domain, and a bound +/// the creator's shard states above the holder's `H` still holds. Capping such a file with the +/// holder's `H` would silently drop rows the creator numbered above it. +#[tokio::test] +async fn test_piece_scan_does_not_cap_adopted_rows_by_the_holder_snapshot() { + let mut env = TestEnv::with_prefix("test_piece_scan_adopted_holder_snapshot").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. + let source_file = build_source_file(&engine, source, 5).await; + create_target(&engine, target).await; + adopt_file(&engine, target, source_file).await; + + // The read's own snapshot is 4, while the creator's shard owes up to 6. + let rows = scan_row_sequences( + &engine, + target, + piece_scan( + source, + vec![CursorShard::whole_domain(1).with_until(6)], + 0, + 4, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "the holder's snapshot caps none of the creator's rows" + ); +} + +/// An adopted file whose bytes stamp one uniform number on every row has no per-row number a +/// creator cursor can bound: comparing the constant with the creator's `(0, 2]` would drop every +/// row of it and report the delta as complete, while the caller may still owe them. The read +/// refuses the file instead of ending empty. +#[tokio::test] +async fn test_piece_scan_refuses_an_adopted_file_without_original_numbers() { + let mut env = TestEnv::with_prefix("test_piece_scan_adopted_without_original_numbers").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_unproved_source_file(&engine, source, 3).await; + create_target(&engine, target).await; + adopt_file(&engine, target, source_file).await; + + // The creator consumed nothing at or below 0, and its delta owes nothing above 2. + let err = scan_error( + &engine, + target, + piece_scan( + source, + vec![CursorShard::whole_domain(0).with_until(2)], + 0, + 2, + ), + ) + .await; + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "an adopted file without proof of the allocator's numbers must fail the read: {err}" + ); + assert!( + err.to_string() + .contains("cannot prove that its bytes carry the numbers"), + "the read must refuse the file for its missing proof: {err}" + ); + + // The unopted read is unaffected: it virtualizes every row at the holder's barrier. + let rows = scan_row_sequences(&engine, target, ScanRequest::default()).await; + assert_eq!( + 3, + rows.len(), + "the unopted read keeps reading the file, at the barrier" + ); +} + +/// A local file this region flushed while it kept no per-row sequence cannot be split by a +/// creator cursor either. Enabling the option afterwards documents what later files carry, but +/// cannot make the old file's bytes state the number each row was allocated, so the read must +/// refuse it rather than prune it at its barrier and report the delta as complete. +#[tokio::test] +async fn test_piece_scan_refuses_a_local_file_without_original_numbers() { + let mut env = TestEnv::with_prefix("test_piece_scan_local_without_original_numbers").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .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, 3, 0), + }, + ) + .await; + test_util::flush_region(&engine, region, None).await; + + engine + .handle_request( + region, + RegionRequest::Alter(RegionAlterRequest { + kind: AlterKind::SetRegionOptions { + options: vec![SetRegionOption::PreserveRowSequence(true)], + }, + }), + ) + .await + .unwrap(); + + let version = engine.get_region(region).unwrap().version(); + assert!( + version.options.preserve_row_sequence, + "the region keeps row sequences from now on" + ); + let file = only_file(&engine, region); + assert!( + !file.has_original_row_sequences(), + "the file written before the option was enabled carries no allocator numbering" + ); + + // The cursor reads as "everything the file holds is consumed", which is exactly the + // conclusion an unproved file cannot support. + let err = scan_error( + &engine, + region, + piece_scan(region, vec![CursorShard::whole_domain(3)], 3, 20), + ) + .await; + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "a local file without proof of the allocator's numbers must fail the read: {err}" + ); + assert!( + err.to_string() + .contains("cannot prove that its bytes carry the numbers"), + "the read must refuse the file for its missing proof: {err}" + ); + + // The unopted read still returns the rows. + let rows = scan_row_sequences(&engine, region, ScanRequest::default()).await; + assert_eq!(3, rows.len(), "the unopted read keeps reading the file"); +} + +/// Adding up the candidate ranges and filtering the rows afterwards would deliver a row none of +/// the pieces selects: the union of `(5, +inf)` and `(0, +inf)` covers the number 7, but the row +/// carrying it belongs to neither piece's value domain. A file must still refuse to report such a +/// row as owed, so the per-row rule keeps failing closed instead of delivering it. +#[tokio::test] +async fn test_piece_scan_refuses_an_unattributed_row_inside_the_union_of_the_ranges() { + let mut env = TestEnv::with_prefix("test_piece_scan_unattributed_in_union").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + // The rows of the pieces `[0, 5)` and `[5, 9)`, plus one series outside both of them, flushed + // so that a file is the only source of the read. + let schema = create_region(&engine, region, "primary_key").await; + 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)); + rows.extend(test_util::build_rows_for_key("z", 6, 7, 0)); + test_util::put_rows(&engine, region, Rows { schema, rows }).await; + test_util::flush_region(&engine, region, None).await; + + let err = scan_error( + &engine, + region, + piece_scan( + region, + vec![piece_cursor("0", "5", 5), piece_cursor("5", "9", 0)], + 0, + 20, + ), + ) + .await; + assert!( + matches!(err, Error::SequenceRangeUnsupported { .. }), + "the row of a series no candidate piece selects must fail the read: {err}" + ); + assert!( + err.to_string().contains("a file of region"), + "the file's per-row rule is the one that must refuse the row: {err}" + ); +} 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..6b2e2ebd6f3 --- /dev/null +++ b/src/mito2/src/engine/scan_slice_test.rs @@ -0,0 +1,448 @@ +// 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::collections::BTreeMap; +use std::sync::Arc; + +use api::v1::{ColumnSchema, Row, Rows}; +use datatypes::arrow::array::UInt64Array; +use datatypes::value::Value; +use futures::TryStreamExt; +use partition::expr::{Operand, PartitionExpr, col as partition_col}; +use store_api::region_engine::RegionEngine; +use store_api::region_request::RegionRequest; +use store_api::storage::{CursorShard, RegionId, ScanRequest}; + +use crate::config::MitoConfig; +use crate::engine::MitoEngine; +use crate::error::Error; +use crate::read::stream::ScanBatch; +use crate::test_util; +use crate::test_util::{CreateRequestBuilder, TestEnv}; + +/// The piece `tag_0 >= lo AND tag_0 < hi` of the test schema. +/// +/// The bounds are the tag column's own strings: the reader compiles a piece expression into a +/// row filter of that column's type, so a numeric bound would not be evaluable at all. +pub(crate) fn piece(lo: &str, hi: &str) -> PartitionExpr { + 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 piece cursor carries for [`piece`]. +pub(crate) fn piece_identity(lo: &str, hi: &str) -> String { + piece(lo, hi).as_json_str().unwrap() +} + +/// The cursor of the piece `tag_0 in [lo, hi)` consumed up to `seq`. +pub(crate) fn piece_cursor(lo: &str, hi: &str, seq: u64) -> CursorShard { + CursorShard::new(Some(piece_identity(lo, hi)), seq) +} + +/// A physical-sequence read of `region` filtered by the pieces of `creator`'s domain, bounded by +/// the exact range `(min, max]`. +pub(crate) fn piece_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 exact range without the physical-sequence opt-in: the legacy read every other caller +/// keeps using. +pub(crate) fn legacy_scan(min: u64, max: u64) -> ScanRequest { + ScanRequest { + exact_sequence_range: true, + memtable_min_sequence: Some(min), + memtable_max_sequence: Some(max), + ..Default::default() + } +} + +/// Creates an append-only region that keeps the per-row sequences, with `sst_format` selecting +/// the memtable kind (`primary_key` keeps the time-series memtable, `flat` the bulk one). +pub(crate) async fn create_region( + engine: &MitoEngine, + region: RegionId, + sst_format: &str, +) -> Vec { + let request = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .insert_option("sst_format", sst_format) + .build(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(region, RegionRequest::Create(request)) + .await + .unwrap(); + schema +} + +/// Writes five rows of the series `1` (the piece `[0, 5)`) and one row of the series `6` (the +/// piece `[5, 9)`), so the numbers 1..5 belong to the left piece and 6 to the right one. +pub(crate) async fn put_two_pieces(engine: &MitoEngine, region: RegionId, schema: &[ColumnSchema]) { + let mut rows: Vec = 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: schema.to_vec(), + rows, + }, + ) + .await; +} + +/// Scans one region through the scanner a datanode uses and returns `(timestamp, sequence)` of +/// every surviving row, sorted. +pub(crate) async fn scan_row_sequences( + engine: &MitoEngine, + region: RegionId, + request: ScanRequest, +) -> Vec<(i64, u64)> { + let mut stream = engine.scan_batch(region, 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 time_index = batch.column(num_columns - 4).clone(); + let timestamps = crate::read::timestamp_array_to_i64_slice(&time_index); + 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.sort_unstable(); + rows +} + +/// Runs a scan that must not succeed and returns its error. +pub(crate) async fn scan_error( + engine: &MitoEngine, + region: RegionId, + request: ScanRequest, +) -> Error { + let mut stream = match engine.scan_batch(region, request, true).await { + Ok(stream) => stream, + Err(err) => return err, + }; + loop { + match stream.try_next().await { + Ok(Some(_)) => continue, + Ok(None) => panic!("an exact read that cannot prove its rows must fail"), + Err(err) => return err, + } + } +} + +/// A region's own file holding rows of two pieces is split by the expression each row satisfies: +/// the rows of the piece consumed up to 5 are not delivered again, and the row at 6 of the piece +/// consumed up to 2 still is. Bounding the whole file by one cursor cannot do that — the least +/// advanced one (2) re-delivers the rows 3, 4 and 5, the most advanced one (5) drops the row 6. +#[tokio::test] +async fn test_piece_scan_splits_own_file_rows_by_their_expression() { + let mut env = TestEnv::with_prefix("test_piece_scan_splits_own_file_rows").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_two_pieces(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![piece_cursor("0", "5", 5), piece_cursor("5", "9", 2)], + 1, + 20, + ), + ) + .await; + assert_eq!( + vec![(5000, 6)], + rows, + "the row at 6 belongs to the piece consumed up to 2 and must be delivered; the rows at \ + 3, 4 and 5 belong to the piece consumed up to 5 and must not be delivered again" + ); +} + +/// The same per-row rule for the rows this region has not flushed yet: a time-series memtable +/// batch is one series, so the piece of the whole batch is resolved once from its tag values. +#[tokio::test] +async fn test_piece_scan_splits_time_series_memtable_rows_by_their_expression() { + let mut env = TestEnv::with_prefix("test_piece_scan_splits_series_memtable_rows").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + // No flush, so no file takes part in the read. + let schema = create_region(&engine, region, "primary_key").await; + put_two_pieces(&engine, region, &schema).await; + + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![piece_cursor("0", "5", 5), piece_cursor("5", "9", 2)], + 1, + 20, + ), + ) + .await; + assert_eq!( + vec![(5000, 6)], + rows, + "a memtable row is filtered by the cursor of the piece its own tag values fall into" + ); +} + +/// The same per-row rule for the bulk memtable: its parts keep the tags and the physical sequence +/// of every row as columns, so each row of one batch is decided on its own. +#[tokio::test] +async fn test_piece_scan_splits_bulk_memtable_rows_by_their_expression() { + let mut env = TestEnv::with_prefix("test_piece_scan_splits_bulk_memtable_rows").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "flat").await; + put_two_pieces(&engine, region, &schema).await; + + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![piece_cursor("0", "5", 5), piece_cursor("5", "9", 2)], + 1, + 20, + ), + ) + .await; + assert_eq!( + vec![(5000, 6)], + rows, + "a bulk memtable row is filtered by the cursor of the piece it belongs to" + ); +} + +/// A scan that does not opt in keeps the region-level floor: every row above the cursor is +/// delivered, including the rows a more advanced piece has already consumed. +#[tokio::test] +async fn test_legacy_scan_keeps_the_region_floor() { + let mut env = TestEnv::with_prefix("test_legacy_scan_keeps_the_region_floor").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_two_pieces(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let rows = scan_row_sequences(&engine, region, legacy_scan(1, 20)).await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5), (5000, 6)], + rows, + "a read without the physical-sequence opt-in keeps bounding every row by one floor" + ); + + // The same floor bounds a time-series memtable. + let memtable_region = RegionId::new(1, 2); + let schema = create_region(&engine, memtable_region, "primary_key").await; + put_two_pieces(&engine, memtable_region, &schema).await; + let rows = scan_row_sequences(&engine, memtable_region, legacy_scan(1, 20)).await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5), (5000, 6)], + rows, + "the legacy memtable read keeps the region-level floor" + ); +} + +/// The per-row decision survives a projection that does not carry the tag column: the scan adds +/// the columns the piece expressions reference as internal columns, so the output schema stays the +/// projected one and the piece is still resolved. +#[tokio::test] +async fn test_piece_scan_reads_the_piece_column_without_projecting_it() { + let mut env = TestEnv::with_prefix("test_piece_scan_reads_piece_column").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region = RegionId::new(1, 1); + + let schema = create_region(&engine, region, "primary_key").await; + put_two_pieces(&engine, region, &schema).await; + test_util::flush_region(&engine, region, None).await; + + let mut request = piece_scan( + region, + vec![piece_cursor("0", "5", 5), piece_cursor("5", "9", 2)], + 1, + 20, + ); + // Only the field column: `tag_0` is not projected. + request.projection = Some(vec![1]); + let rows = scan_row_sequences(&engine, region, request).await; + assert_eq!(vec![(5000, 6)], rows); +} + +/// Two pieces of one domain may both select the same series while owing different rows. The row +/// is then kept when **at least one** selecting piece still owes it under that piece's own +/// range — the intervals are never merged into one across the gap between them, and one piece's +/// bound never decides another's row. +/// +/// The intervals `(0, 3]` and `(4, 8]` both select the series: the row at 6 belongs to the +/// second and must be delivered, and the row at 4 belongs to neither and must not. +#[tokio::test] +async fn test_piece_scan_keeps_a_row_owed_by_any_selecting_piece() { + let mut env = TestEnv::with_prefix("test_piece_scan_any_selecting_piece").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let shards = || { + vec![ + piece_cursor("0", "9", 0).with_until(3), + piece_cursor("0", "9", 4).with_until(8), + ] + }; + let expected = vec![ + (0, 1), + (1000, 2), + (2000, 3), + (4000, 5), + (5000, 6), + (6000, 7), + (7000, 8), + ]; + + for (region, format, flush) in [ + (RegionId::new(1, 1), "primary_key", false), + (RegionId::new(1, 2), "flat", false), + (RegionId::new(1, 3), "primary_key", true), + ] { + let schema = create_region(&engine, region, format).await; + test_util::put_rows( + &engine, + region, + Rows { + schema: schema.clone(), + rows: test_util::build_rows_for_key("1", 0, 8, 0), + }, + ) + .await; + if flush { + test_util::flush_region(&engine, region, None).await; + } + + let rows = scan_row_sequences(&engine, region, piece_scan(region, shards(), 0, 10)).await; + assert_eq!( + expected, rows, + "region {region} ({format}, flushed: {flush}): a row is owed by any selecting piece, \ + never by a range spanning the gap between two of them" + ); + } +} + +/// Two **distinct** expressions of one domain may overlap, so one physical row is attributed to +/// several pieces at once instead of to exactly one. The row is then delivered once when any +/// matching piece still owes it under that piece's own range, and omitted only when every +/// matching piece's range excludes it — no piece's cursor or upper bound decides another's row. +/// +/// The rows of tag `7` match both `[0, 8)` and `[5, 9)`. With `[0, 8)` consumed up to 1 and its +/// delta ending at 3, `[5, 9)` consumed up to 0 and its delta ending at 4, the row numbered 1 is +/// owed by `[5, 9)` alone, the rows 2 and 3 by both and delivered once, the row 4 by `[5, 9)` +/// alone because the other delta ends at 3, and the rows above 4 by neither. +#[tokio::test] +async fn test_piece_scan_keeps_a_row_matching_two_overlapping_expressions() { + let mut env = TestEnv::with_prefix("test_piece_scan_overlapping_expressions").await; + let engine = env.create_engine(MitoConfig::default()).await; + + let shards = || { + vec![ + piece_cursor("0", "8", 1).with_until(3), + piece_cursor("5", "9", 0).with_until(4), + ] + }; + let all_rows = vec![ + (0, 1), + (1000, 2), + (2000, 3), + (3000, 4), + (4000, 5), + (5000, 6), + (6000, 7), + (7000, 8), + ]; + let expected = vec![(0, 1), (1000, 2), (2000, 3), (3000, 4)]; + + for (region, format, flush) in [ + (RegionId::new(1, 1), "primary_key", false), + (RegionId::new(1, 2), "flat", false), + (RegionId::new(1, 3), "primary_key", true), + ] { + let schema = create_region(&engine, region, format).await; + test_util::put_rows( + &engine, + region, + Rows { + schema, + rows: test_util::build_rows_for_key("7", 0, 8, 0), + }, + ) + .await; + if flush { + test_util::flush_region(&engine, region, None).await; + } + + // Both pieces unbounded: every row exists, both expressions select it, and the rows are + // numbered 1..8 in timestamp order. + let rows = scan_row_sequences( + &engine, + region, + piece_scan( + region, + vec![piece_cursor("0", "8", 0), piece_cursor("5", "9", 0)], + 0, + 20, + ), + ) + .await; + assert_eq!( + all_rows, rows, + "region {region} ({format}, flushed: {flush}): every row of tag 7 is selected by both \ + expressions and numbered 1..8" + ); + + let rows = scan_row_sequences(&engine, region, piece_scan(region, shards(), 0, 20)).await; + assert_eq!( + expected, rows, + "region {region} ({format}, flushed: {flush}): a row two overlapping pieces select is \ + delivered once while either still owes it, and omitted once both ranges exclude it" + ); + } +} diff --git a/src/mito2/src/engine/table_compaction/tests.rs b/src/mito2/src/engine/table_compaction/tests.rs index 0b6bea5e789..83f3369ffeb 100644 --- a/src/mito2/src/engine/table_compaction/tests.rs +++ b/src/mito2/src/engine/table_compaction/tests.rs @@ -39,7 +39,10 @@ use crate::error::Error; use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; use crate::region::{MitoRegionRef, RegionLeaderState}; use crate::request::{RegionEditRequest, WorkerRequest}; -use crate::sst::file::{ColumnIndexMetadata, FileMeta, IndexType, LEVEL_SHARED, SHARED_LEVEL_SLOT}; +use crate::sst::file::{ + ColumnIndexMetadata, FileMeta, IndexType, LEVEL_SHARED, RowSequenceProvenance, + SHARED_LEVEL_SLOT, +}; use crate::sst::location; use crate::test_util::sst_util::new_sparse_primary_key; use crate::test_util::{ @@ -1547,3 +1550,445 @@ async fn test_publication_after_drop_field_and_option_changes() { ); engine.stop().await.unwrap(); } + +/// Publication keeps an unknown statement unknown: an unproved inventory still +/// publishes without a claim, and no replay can turn that into one. +#[tokio::test] +async fn test_unknown_row_sequence_provenance_is_never_promoted() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let region_id = RegionId::new(1, 1); + let (snapshot, output) = seed(&engine, region_id).await; + assert_eq!(None, output.row_sequence_provenance); + assert!(!snapshot.inputs[0].has_original_row_sequences()); + + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) + .await + .unwrap() + ); + let region = engine.get_region(region_id).unwrap(); + assert_eq!( + None, + region.manifest_ctx.manifest().await.files[&output.file_id].row_sequence_provenance + ); + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) + .await + .unwrap() + ); + assert_eq!( + None, + region.manifest_ctx.manifest().await.files[&output.file_id].row_sequence_provenance + ); + + let forged = FileMeta { + row_sequence_provenance: Some(RowSequenceProvenance::Original), + ..output.clone() + }; + assert_eq!( + PublicationOutcome::StaleInputs, + engine + .publish_table_compaction(region_id, snapshot, vec![forged]) + .await + .unwrap() + ); + assert_eq!( + None, + region.manifest_ctx.manifest().await.files[&output.file_id].row_sequence_provenance + ); + assert_eq!(3, row_count(&engine, region_id).await); +} + +#[cfg(feature = "enterprise")] +mod multi_region_proof { + use std::collections::BTreeMap; + use std::num::NonZeroU64; + + use datatypes::value::Value; + use partition::expr::col; + use partition::multi_dim::MultiDimPartitionRule; + use store_api::region_request::RegionCreateRequest; + use store_api::storage::{CursorShard, ScanRequest}; + use tokio_util::sync::CancellationToken; + + use super::*; + use crate::cache::CacheManager; + use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, compact_regions, + }; + use crate::engine::scan_slice_test::scan_row_sequences; + use crate::region::options::RegionOptions; + use crate::sst::FormatType; + use crate::sst::file::UncommittedSsts; + + fn tag_range(start: &str, end: &str) -> String { + col("tag_0") + .gt_eq(Value::String(start.into())) + .and(col("tag_0").lt(Value::String(end.into()))) + .as_json_str() + .unwrap() + } + + /// Creates an append-only region whose flushes prove the numbering they write. + async fn create_proving_region( + engine: &MitoEngine, + region_id: RegionId, + ) -> RegionCreateRequest { + let create = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .insert_option("sst_format", "primary_key") + .build(); + engine + .handle_request(region_id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + create + } + + /// Writes `rows` and flushes them, returning the file whose bytes state the + /// flush's own numbering. + async fn flush_proving_rows( + engine: &MitoEngine, + region_id: RegionId, + create: &RegionCreateRequest, + rows: (usize, usize), + ) -> FileMeta { + put_rows( + engine, + region_id, + Rows { + schema: rows_schema(create), + rows: build_rows(rows.0, rows.1), + }, + ) + .await; + flush_region(engine, region_id, None).await; + let file = engine + .get_region(region_id) + .unwrap() + .version() + .ssts + .levels()[0] + .files() + .next() + .unwrap() + .meta_ref() + .clone(); + assert!( + file.has_original_row_sequences(), + "a preserving flush proves the numbering its bytes carry" + ); + file + } + + /// Moves `file` to the shared level without moving its bytes, so the handle + /// keeps the statement the flush wrote. + async fn share_file(engine: &MitoEngine, region_id: RegionId, file: FileMeta) { + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![FileMeta { + level: LEVEL_SHARED, + ..file + }], + ..Default::default() + }, + ) + .await + .unwrap(); + } + + /// Adopts a shared reference to a foreign file, retaining its source's proof. + async fn adopt_foreign_file(engine: &MitoEngine, region_id: RegionId, file: FileMeta) { + let (tx, rx) = tokio::sync::oneshot::channel(); + let request = RegionEditRequest::new( + region_id, + RegionEdit { + files_to_add: vec![FileMeta { + level: LEVEL_SHARED, + ..file + }], + ..Default::default() + }, + false, + tx, + ) + .for_copy_region(); + engine + .inner + .workers + .submit_to_worker(region_id, WorkerRequest::EditRegion(request)) + .await + .unwrap(); + rx.await.unwrap().unwrap(); + } + + fn compaction_context( + engine: &MitoEngine, + region: &MitoRegionRef, + ) -> MultiRegionCompactionContext { + let access = region.access_layer.clone(); + MultiRegionCompactionContext { + index_kind_provider: None, + access_layer: access.clone(), + cache: Arc::new(CacheManager::default()), + config: engine.inner.config.clone(), + protection: Arc::new(UncommittedSsts::new(region.region_id, access, None)), + cancellation: CancellationToken::new(), + } + } + + /// Routes every selected source to `creator` and `foreign`, re-basing each + /// source at the target's own sequence domain. + fn routing_plan( + snapshot: &TableCompactionSnapshot, + creator: RegionId, + foreign: RegionId, + creator_expr: &str, + foreign_expr: &str, + ) -> MultiRegionCompactionPlan { + let mut targets = BTreeMap::new(); + for (id, rebase) in [(creator, false), (foreign, true)] { + let mut metadata = (*snapshot.metadata).clone(); + metadata.region_id = id; + let inputs = snapshot + .inputs + .iter() + .cloned() + .map(|mut input| { + if rebase { + input.sequence = NonZeroU64::new(100 + id.region_sequence() as u64); + } + (input.file_id(), input) + }) + .collect(); + targets.insert( + id, + MultiRegionTarget { + metadata: Arc::new(metadata), + options: RegionOptions { + append_mode: true, + preserve_row_sequence: true, + sst_format: Some(FormatType::PrimaryKey), + ..Default::default() + }, + inputs, + }, + ); + } + let exprs = [creator_expr, foreign_expr] + .into_iter() + .map(|expr| { + crate::region::parse_partition_expr(Some(expr)) + .unwrap() + .unwrap() + }) + .collect(); + let partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["tag_0".into()], + vec![creator.region_sequence(), foreign.region_sequence()], + exprs, + false, + ) + .unwrap(), + ); + MultiRegionCompactionPlan { + partition_rule, + sources: snapshot.inputs.clone(), + targets, + memory_limit: 192 * 1024 * 1024, + max_output_file_size: 1024 * 1024, + window_start: 0, + window_seconds: 3600, + } + } + + /// The writer keeps a positively proved flush's own numbers for the allocating + /// target, and publication hands that statement to the reopened region. + #[tokio::test] + async fn test_creator_output_publishes_original_row_sequences() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let creator = RegionId::new(1, 1); + let foreign = RegionId::new(1, 2); + let creator_expr = tag_range("0", "2"); + let foreign_expr = tag_range("2", "9"); + let create = create_proving_region(&engine, creator).await; + let flushed = flush_proving_rows(&engine, creator, &create, (0, 3)).await; + share_file(&engine, creator, flushed.clone()).await; + + let snapshot = engine.table_compaction_snapshot(creator).unwrap(); + assert_eq!(1, snapshot.inputs.len()); + assert_eq!(flushed.file_id, snapshot.inputs[0].file_id); + assert!(snapshot.inputs[0].has_original_row_sequences()); + + let plan = routing_plan(&snapshot, creator, foreign, &creator_expr, &foreign_expr); + let region = engine.get_region(creator).unwrap(); + let output = compact_regions(plan, compaction_context(&engine, ®ion)) + .await + .unwrap(); + + let creator_files = &output.files[&creator]; + assert_eq!(1, creator_files.len()); + let proved = &creator_files[0]; + assert_eq!( + Some(RowSequenceProvenance::Original), + proved.row_sequence_provenance + ); + assert!(proved.has_original_row_sequences()); + assert!(!output.files[&foreign].is_empty()); + for file in &output.files[&foreign] { + assert_eq!(None, file.row_sequence_provenance); + assert!(!file.has_original_row_sequences()); + assert_eq!( + NonZeroU64::new(100 + foreign.region_sequence() as u64), + file.sequence, + "the foreign target re-bases its rows at its own barrier" + ); + } + + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(creator, snapshot, creator_files.clone()) + .await + .unwrap() + ); + assert_eq!( + Some(RowSequenceProvenance::Original), + region.manifest_ctx.manifest().await.files[&proved.file_id].row_sequence_provenance + ); + + reopen_region( + &engine, + creator, + "test".into(), + true, + create.options.clone(), + ) + .await; + let reopened = engine.get_region(creator).unwrap(); + assert!( + reopened.manifest_ctx.manifest().await.files[&proved.file_id] + .has_original_row_sequences() + ); + let rows = scan_row_sequences( + &engine, + creator, + ScanRequest { + exact_sequence_range: true, + read_row_sequence: true, + memtable_min_sequence: Some(0), + memtable_max_sequence: Some(3), + creator_cursor_shards: Some(Arc::new(BTreeMap::from([( + creator.as_u64(), + vec![CursorShard::whole_domain(0)], + )]))), + ..Default::default() + }, + ) + .await; + assert_eq!( + vec![(0, 1), (1_000, 2)], + rows, + "the published output is bounded by the numbers its allocator assigned" + ); + } + + /// A foreign input's rows reach the creator target at its barrier, so its output + /// states no `Original` and publication rejects a claim that it does. + #[tokio::test] + async fn test_foreign_barrier_output_cannot_claim_original_row_sequences() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let creator = RegionId::new(1, 1); + let foreign = RegionId::new(1, 2); + let creator_expr = tag_range("0", "2"); + let foreign_expr = tag_range("2", "9"); + let creator_create = create_proving_region(&engine, creator).await; + let creator_file = flush_proving_rows(&engine, creator, &creator_create, (0, 3)).await; + share_file(&engine, creator, creator_file).await; + let foreign_create = create_proving_region(&engine, foreign).await; + let foreign_file = flush_proving_rows(&engine, foreign, &foreign_create, (0, 3)).await; + adopt_foreign_file(&engine, creator, foreign_file).await; + + let snapshot = engine.table_compaction_snapshot(creator).unwrap(); + assert_eq!(2, snapshot.inputs.len()); + assert!( + snapshot + .inputs + .iter() + .all(FileMeta::has_original_row_sequences) + ); + assert!( + snapshot + .inputs + .iter() + .any(|input| input.region_id == foreign) + ); + + let plan = routing_plan(&snapshot, creator, foreign, &creator_expr, &foreign_expr); + let region = engine.get_region(creator).unwrap(); + let version = region.manifest_ctx.manifest_version().await; + let output = compact_regions(plan, compaction_context(&engine, ®ion)) + .await + .unwrap(); + + let creator_files = &output.files[&creator]; + assert!(!creator_files.is_empty()); + for file in creator_files { + assert_eq!(None, file.row_sequence_provenance); + assert!(!file.has_original_row_sequences()); + } + + let forged = creator_files + .iter() + .map(|file| FileMeta { + row_sequence_provenance: Some(RowSequenceProvenance::Original), + ..file.clone() + }) + .collect::>(); + let error = engine + .publish_table_compaction(creator, snapshot.clone(), forged) + .await + .unwrap_err(); + let source = match error { + crate::error::Error::EditRegion { source, .. } => source, + other => panic!("unexpected error: {other}"), + }; + assert!( + matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason, .. } + if reason == "Original row sequences are unprovable for this input inventory"), + "unexpected error: {source}" + ); + assert_eq!(version, region.manifest_ctx.manifest_version().await); + assert_eq!( + snapshot.inputs, + engine.table_compaction_snapshot(creator).unwrap().inputs + ); + + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(creator, snapshot, output.files[&creator].clone()) + .await + .unwrap() + ); + let manifest = region.manifest_ctx.manifest().await; + for file in &output.files[&creator] { + assert_eq!( + None, manifest.files[&file.file_id].row_sequence_provenance, + "publication installs the unproved statement as unknown" + ); + } + assert_eq!(4, row_count(&engine, creator).await); + } +} diff --git a/src/mito2/src/memtable.rs b/src/mito2/src/memtable.rs index 3e704650551..336463ef2b1 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,41 @@ pub(crate) fn group_by_sequence( /// Should be unique under the same region. pub type MemtableId = u32; +/// The cursor of one piece of a region's value domain: the expression selecting the piece +/// together with the rows a read still owes on it. +/// +/// A sequence number belongs to the domain of the region that allocated it, so a row is +/// compared against the cursor of the piece its own tag values fall into rather than against +/// one floor for the whole region: after two pieces advanced independently, that floor is the +/// least advanced piece and re-delivers the rows a more advanced piece has already consumed. +#[derive(Debug, Clone)] +pub struct PieceCursor { + /// Expression selecting the piece, or `None` for the region's complete value domain. + /// + /// A whole-domain piece selects every row, which is what a cursor shard that names no + /// expression means: its range still bounds the rows, even though no expression can tell + /// which piece a row belongs to. + pub expr: Option, + /// Last sequence consumed in the piece (exclusive lower bound). + pub seq: SequenceNumber, + /// Last sequence the piece's delta covers (inclusive upper bound), when stated. + pub until: Option, +} + +impl PieceCursor { + /// The rows this piece still owes: `seq < number <= until`, or `seq < number` when the + /// piece states no upper bound. + pub fn rows_owed(&self) -> SequenceRange { + match self.until { + Some(max) => SequenceRange::GtLtEq { min: self.seq, max }, + None => SequenceRange::Gt { min: self.seq }, + } + } +} + +/// The cursor of every piece of one region's value domain. +pub type RegionPieceCursors = Arc>; + /// Options for querying ranges from a memtable. #[derive(Clone)] pub struct RangesOptions { @@ -106,6 +142,16 @@ pub struct RangesOptions { pub predicate: PredicateGroup, /// Sequence range to filter the data. pub sequence: Option, + /// The cursor of each piece a row of this memtable may belong to. + /// + /// When present, a row is delivered only when its own sequence lies in the range of the + /// piece its tag values fall into: the cursor of that piece replaces the lower bound + /// [`Self::sequence`] states, which is the least advanced piece of the region and cannot + /// tell a row of a more advanced piece from a consumed one. The upper bound of + /// [`Self::sequence`] still bounds every row. + /// + /// `None` (or an empty set) 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 +163,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 +177,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 +203,16 @@ impl RangesOptions { self } + /// Sets the cursor of each piece a row may belong to. + /// + /// See [`RangesOptions::creator_slices`]: the cursor of the piece a row belongs to + /// replaces the lower bound of [`RangesOptions::sequence`]. + #[must_use] + pub fn with_creator_slices(mut self, creator_slices: Option) -> Self { + self.creator_slices = creator_slices; + self + } + /// Sets the maximum number of rows readers should produce in one batch. #[must_use] pub fn with_batch_size(mut self, batch_size: usize) -> Self { diff --git a/src/mito2/src/memtable/bulk.rs b/src/mito2/src/memtable/bulk.rs index c67896fe2c2..16c4c9b6e91 100644 --- a/src/mito2/src/memtable/bulk.rs +++ b/src/mito2/src/memtable/bulk.rs @@ -62,7 +62,7 @@ use crate::memtable::{ AllocTracker, BoxedBatchIterator, BoxedRecordBatchIterator, EncodedBulkPart, EncodedRange, IterBuilder, KeyValues, MemScanMetrics, MemoryCharge, Memtable, MemtableBuilder, MemtableId, MemtableRange, MemtableRangeContext, MemtableRanges, MemtableRef, MemtableStats, RangesOptions, - group_by_sequence, + RegionPieceCursors, group_by_sequence, }; use crate::read::flat_dedup::{FlatDedupIterator, FlatLastNonNull, FlatLastRow}; use crate::read::flat_merge::FlatMergeIterator; @@ -561,6 +561,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; @@ -591,6 +592,7 @@ impl Memtable for BulkMemtable { part: unordered_bulk_part, context: context.clone(), sequence, + creator_slices: creator_slices.clone(), // The sorted part may share buffers with the buffered writes. charges: bulk_parts.unordered_charges.clone(), }), @@ -616,12 +618,14 @@ impl Memtable for BulkMemtable { part: part.clone(), context: context.clone(), sequence, + creator_slices: creator_slices.clone(), charges, }), PartToMerge::Multi { part, .. } => Box::new(MultiBulkRangeIterBuilder { part: part.clone(), context: context.clone(), sequence, + creator_slices: creator_slices.clone(), charges, }), PartToMerge::Encoded { part, file_id } => { @@ -630,6 +634,7 @@ impl Memtable for BulkMemtable { part: part.clone(), context: context.clone(), sequence, + creator_slices: creator_slices.clone(), charges, }) } @@ -945,6 +950,9 @@ pub struct BulkRangeIterBuilder { pub part: BulkPart, pub context: Arc, pub sequence: Option, + /// The cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`](crate::memtable::RangesOptions::creator_slices)). + pub creator_slices: Option, /// Keeps the write buffer charged for the part while the range or its iterators are alive. charges: Vec>, } @@ -954,6 +962,7 @@ struct MultiBulkRangeIterBuilder { part: MultiBulkPart, context: Arc, sequence: Option, + creator_slices: Option, /// Keeps the write buffer charged for the part while the range or its iterators are alive. charges: Vec>, } @@ -991,7 +1000,8 @@ impl IterBuilder for BulkRangeIterBuilder { self.sequence, series_count, metrics, - ); + ) + .with_creator_slices(self.creator_slices.clone()); Ok(charged(Box::new(iter), &self.charges)) } @@ -1026,10 +1036,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(charged(iter, &self.charges)), // All batches were pruned by the predicate. Return an empty iterator. None => Ok(Box::new(std::iter::empty())), @@ -1051,6 +1063,7 @@ struct EncodedBulkRangeIterBuilder { part: EncodedBulkPart, context: Arc, sequence: Option, + creator_slices: Option, /// Keeps the write buffer charged for the part while the range or its iterators are alive. charges: Vec>, } @@ -1076,10 +1089,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(charged(iter, &self.charges)) } else { // Return an empty iterator if no data to read @@ -1312,8 +1327,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 3209afc869e..914fac33b70 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::ParquetBulkPartIter; use crate::memtable::time_series::{ValueBuilder, Values}; -use crate::memtable::{BoxedRecordBatchIterator, EncodedData, MemScanMetrics, MemtableStats}; +use crate::memtable::{ + BoxedRecordBatchIterator, EncodedData, MemScanMetrics, MemtableStats, RegionPieceCursors, +}; use crate::region::options::MergeMode; use crate::sst::SeriesEstimator; use crate::sst::file::{FileFormat, NarthexPartMeta, NarthexSamplesMeta}; @@ -1421,6 +1423,7 @@ impl EncodedBulkPart { &self, context: BulkIterContextRef, sequence: Option, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result> { let parquet_part = match &self.payload { @@ -1429,15 +1432,16 @@ impl EncodedBulkPart { let iter = part.read(self.schema.clone()).flat_map( move |batch| -> BoxedRecordBatchIterator { match batch { - Ok(batch) => { - Box::new(super::part_reader::BulkPartBatchIter::from_single( + Ok(batch) => Box::new( + super::part_reader::BulkPartBatchIter::from_single( batch, context.clone(), sequence, 1, mem_scan_metrics.clone(), - )) - } + ) + .with_creator_slices(creator_slices.clone()), + ), Err(error) => Box::new(std::iter::once(Err(error))), } }, @@ -1465,7 +1469,8 @@ impl EncodedBulkPart { row_groups_to_read, sequence, mem_scan_metrics, - )?; + )? + .with_creator_slices(creator_slices); Ok(Some(Box::new(iter) as BoxedRecordBatchIterator)) } } @@ -2105,6 +2110,7 @@ impl MultiBulkPart { &self, context: BulkIterContextRef, sequence: Option, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result> { if self.batches.is_empty() { @@ -2123,7 +2129,8 @@ impl MultiBulkPart { sequence, self.series_count, mem_scan_metrics, - ); + ) + .with_creator_slices(creator_slices); Ok(Some(Box::new(iter) as BoxedRecordBatchIterator)) } @@ -2470,6 +2477,7 @@ mod tests { ), None, None, + None, ) .unwrap() .expect("expect at least one row group"); @@ -2530,7 +2538,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; @@ -2564,7 +2572,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); @@ -3826,7 +3834,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(); @@ -3845,7 +3853,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( @@ -3859,7 +3867,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 32121d0a2f7..3ba352e9145 100644 --- a/src/mito2/src/memtable/bulk/part_reader.rs +++ b/src/mito2/src/memtable/bulk/part_reader.rs @@ -12,10 +12,12 @@ // 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::sync::Arc; use std::time::Instant; -use datatypes::arrow::array::BooleanArray; +use datatypes::arrow::array::{BooleanArray, BooleanBufferBuilder}; +use datatypes::arrow::datatypes::Schema; use datatypes::arrow::record_batch::RecordBatch; use mito_codec::row_converter::PrimaryKeyFilter; use parquet::arrow::ProjectionMask; @@ -23,12 +25,15 @@ use parquet::arrow::arrow_reader::ParquetRecordBatchReader; use snafu::ResultExt; use store_api::storage::SequenceRange; -use crate::error::{self, ComputeArrowSnafu, DecodeArrowRowGroupSnafu}; +use crate::error::{self, ComputeArrowSnafu, DecodeArrowRowGroupSnafu, UnexpectedSnafu}; use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef}; use crate::memtable::bulk::part::ParquetBulkPart; use crate::memtable::bulk::row_group_reader::MemtableRowGroupReaderBuilder; -use crate::memtable::{MemScanMetrics, MemScanMetricsData}; +use crate::memtable::{MemScanMetrics, MemScanMetricsData, PieceCursor, RegionPieceCursors}; use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED}; +use crate::read::piece_cursor::{ + agreed_piece_rows, agreed_piece_rows_or_refuse, evaluate_piece_filter, +}; use crate::sst::parquet::file_range::TagDecodeState; use crate::sst::parquet::flat_format::{primary_key_column_index, sequence_column_index}; use crate::sst::parquet::prefilter::{CachedPrimaryKeyFilter, prefilter_flat_batch_by_primary_key}; @@ -43,6 +48,9 @@ pub struct ParquetBulkPartIter { builder: MemtableRowGroupReaderBuilder, /// Sequence number filter. sequence: Option, + /// The cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`](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. @@ -94,6 +102,7 @@ impl ParquetBulkPartIter { current_reader: init_reader, builder, sequence, + creator_slices: None, current_skip_fields, pk_filter, metrics: MemScanMetricsData { @@ -104,6 +113,15 @@ impl ParquetBulkPartIter { }) } + /// Sets the cursor of each piece a row may belong to. + pub(crate) 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); @@ -125,6 +143,7 @@ impl ParquetBulkPartIter { 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 @@ -153,6 +172,7 @@ impl ParquetBulkPartIter { 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 @@ -224,6 +244,9 @@ pub struct BulkPartBatchIter { context: BulkIterContextRef, /// Sequence number filter. sequence: Option, + /// The cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`](crate::memtable::RangesOptions::creator_slices)). + creator_slices: Option, /// Primary key filter for prefiltering before convert_batch. pk_filter: Option, /// Metrics for this iterator. @@ -247,6 +270,7 @@ impl BulkPartBatchIter { batches: VecDeque::from(batches), context, sequence, + creator_slices: None, pk_filter, metrics: MemScanMetricsData { total_series: series_count, @@ -273,6 +297,15 @@ impl BulkPartBatchIter { ) } + /// Sets the cursor of each piece a row may belong to. + pub(crate) 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); @@ -307,6 +340,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 @@ -375,14 +409,19 @@ impl Drop for BulkPartBatchIter { } } -/// Applies both predicate filtering and sequence filtering in a single pass. +/// Applies the predicate, sequence and piece 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; the two are combined so the per-piece rule +/// only replaces the lower bound the region-level range states. +/// /// # Panics /// Panics if the format is not flat. fn apply_combined_filters( context: &BulkIterContext, sequence: &Option, + creator_slices: Option<&[PieceCursor]>, record_batch: RecordBatch, skip_fields: bool, pk_filter: Option<&mut dyn PrimaryKeyFilter>, @@ -449,6 +488,17 @@ fn apply_combined_filters( }; } + // Filters rows by the cursor of the piece each row belongs to. + if let Some(creator_mask) = creator_slice_mask(context, creator_slices, &record_batch)? { + combined_filter = Some(match combined_filter { + None => creator_mask, + Some(existing_filter) => { + datatypes::arrow::compute::and(&existing_filter, &creator_mask) + .context(ComputeArrowSnafu)? + } + }); + } + // Apply the combined filter if any filters were applied let Some(filter_array) = combined_filter else { // No filters applied, return original batch @@ -468,6 +518,183 @@ fn apply_combined_filters( Ok(Some(filtered_batch)) } +/// Computes the mask of rows of `record_batch` this read still owes, resolved per row by the +/// piece the row belongs to. +/// +/// 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 expressions are evaluated over +/// the whole batch, and a row is kept when at least one selecting piece still owes it under that +/// piece's own range. This is the bulk memtable counterpart of the per-row piece selection of an +/// SST read, and a piece that names no expression ([`PieceCursor::expr`]) selects every row, so +/// its range bounds the whole batch. +/// +/// A row no piece selects has no piece to attribute it to. It takes the range every candidate +/// carries, which exists only when they all carry the same one; otherwise the least advanced +/// cursor would deliver the rows a more advanced piece has already consumed, so the read fails +/// with [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported). +fn creator_slice_mask( + context: &BulkIterContext, + slices: Option<&[PieceCursor]>, + 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())); + let rows_owed = |slice: &PieceCursor| -> error::Result { + slice + .rows_owed() + .filter(sequence_column) + .context(ComputeArrowSnafu) + }; + + // What a row no candidate piece selects is bounded by: the rows every candidate owes, which + // exist only when they all owe the same ones. + let fallback = match agreed_piece_rows(slices) { + Some(range) => Some(range.filter(sequence_column).context(ComputeArrowSnafu)?), + None => None, + }; + // One range for every piece is the region's floor: which piece a row belongs to cannot change + // the outcome, so the batch needs no evaluation of its own. + if let Some(fallback) = &fallback { + return Ok(Some(fallback.clone())); + } + + let region_id = context.region_id(); + let refuse = |detail: &str| -> error::Result> { + agreed_piece_rows_or_refuse( + region_id, + &format!("a bulk memtable batch of region {region_id}"), + slices, + detail, + ) + .map(|_| None) + }; + + let evaluable = slices.iter().any(|slice| slice.expr.is_some()); + let probe = if evaluable { + match piece_probe(context, slices, record_batch) { + Ok(probe) => Some(probe), + Err(e) => return refuse(&format!("{e}")), + } + } else { + None + }; + + let mut owed = Vec::with_capacity(slices.len()); + // `None` selects every row, which is what a whole-domain piece states. + let mut selected: Vec> = Vec::with_capacity(slices.len()); + for slice in slices { + owed.push(rows_owed(slice)?); + let Some(expr) = &slice.expr else { + selected.push(None); + continue; + }; + let Some(probe) = &probe else { + return refuse("the probe batch of the piece columns is missing"); + }; + let filter = match expr.try_as_physical_expr(probe.schema_ref()) { + Ok(filter) => filter, + Err(e) => return refuse(&format!("a piece expression cannot be planned: {e}")), + }; + match evaluate_piece_filter(filter.as_ref(), probe) { + Ok(mask) => selected.push(Some(mask)), + Err(e) => return refuse(&format!("a piece expression cannot be evaluated: {e}")), + } + } + + let num_rows = record_batch.num_rows(); + let selects = |index: usize, row: usize| -> bool { + selected[index].as_ref().is_none_or(|mask| mask.value(row)) + }; + let mut kept = BooleanBufferBuilder::new(num_rows); + for row in 0..num_rows { + // At most one piece usually selects a row, but two pieces of one domain may overlap: the + // row is kept when any selecting piece still owes it, and one piece's interval never + // widens another's. + let keep = (0..slices.len()).any(|index| selects(index, row) && owed[index].value(row)); + if keep { + kept.append(true); + continue; + } + if (0..slices.len()).any(|index| selects(index, row)) { + // A piece selects the row and no longer owes it, so the row is consumed. + kept.append(false); + continue; + } + return refuse(&format!( + "row {} of {} matches no candidate piece", + row + 1, + num_rows + )); + } + + Ok(Some(BooleanArray::from(kept.finish()))) +} + +/// Builds the probe batch of the columns the piece expressions reference, taken from +/// `record_batch`. +/// +/// The scan adds those columns to the read columns (a physical-sequence read resolves a row's +/// piece from them), so they are expected to be present. A column that is not cannot decide a +/// row's piece, and guessing would drop rows, so the read fails instead. +fn piece_probe( + context: &BulkIterContext, + slices: &[PieceCursor], + record_batch: &RecordBatch, +) -> error::Result { + let metadata = context.read_format().metadata(); + let mut referenced = HashSet::new(); + for slice in slices { + if let Some(expr) = &slice.expr { + 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 Some(index) = context + .read_format() + .projected_index_by_id(column_metadata.column_id) + else { + return UnexpectedSnafu { + reason: format!( + "a piece expression references column '{}' (id {}), which this bulk memtable read does not carry", + name, column_metadata.column_id + ), + } + .fail(); + }; + let Some(field) = record_batch.schema_ref().fields().get(index).cloned() else { + return UnexpectedSnafu { + reason: format!( + "the bulk memtable batch has no column at index {} for '{}'", + index, name + ), + } + .fail(); + }; + fields.push(field); + columns.push(record_batch.column(index).clone()); + } + if let Some(missing) = referenced.into_iter().next() { + return UnexpectedSnafu { + reason: format!( + "a piece expression references column '{}', which this region does not have", + missing + ), + } + .fail(); + } + + RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).context(ComputeArrowSnafu) +} + #[cfg(test)] mod tests { use std::sync::Arc; diff --git a/src/mito2/src/memtable/simple_bulk_memtable.rs b/src/mito2/src/memtable/simple_bulk_memtable.rs index db0d358c56f..43587e27523 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,16 @@ 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 rule 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 41b83998855..14f460ee933 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}; @@ -54,8 +54,8 @@ 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, + MemtableRangeContext, MemtableRanges, MemtableRef, MemtableStats, PieceCursor, RangesOptions, + RegionPieceCursors, read_column_ids_from_projection, }; 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)); @@ -548,6 +550,7 @@ impl SeriesSet { } /// Iterates all series in [SeriesSet]. + #[allow(clippy::too_many_arguments)] fn iter_series( &self, projection: HashSet, @@ -555,6 +558,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); @@ -575,6 +579,7 @@ impl SeriesSet { dedup, merge_mode, sequence, + creator_slices, mem_scan_metrics, ) } @@ -625,6 +630,9 @@ struct Iter { dedup: bool, merge_mode: MergeMode, sequence: Option, + /// The cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`](crate::memtable::RangesOptions::creator_slices)). + creator_slices: Option, metrics: Metrics, mem_scan_metrics: Option, } @@ -642,6 +650,7 @@ impl Iter { dedup: bool, merge_mode: MergeMode, sequence: Option, + creator_slices: Option, mem_scan_metrics: Option, ) -> Result { let predicate = predicate @@ -671,6 +680,7 @@ impl Iter { dedup, merge_mode, sequence, + creator_slices, metrics: Metrics::default(), mem_scan_metrics, }) @@ -744,12 +754,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 &dyn PrimaryKeyCodec), self.dedup, self.merge_mode, ) @@ -1223,12 +1236,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`](crate::memtable::RangesOptions::creator_slices)): when + /// present, a row is kept only when its sequence lies in the range of the piece its tag + /// values fall into, which replaces the lower bound `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<&[PieceCursor]>, + codec: Option<&dyn PrimaryKeyCodec>, dedup: bool, merge_mode: MergeMode, ) -> Result { @@ -1255,6 +1277,10 @@ impl Values { // - avoid dropping a timestamp when the newest row is out of range // - avoid filling null fields from rows that should be excluded by the sequence filter. batch.filter_by_sequence(sequence)?; + // The cursor of the piece this series belongs to replaces the lower bound of + // `sequence`: that bound is the least advanced piece of the region, so it cannot tell + // a row of a more advanced piece from a consumed one. + batch.filter_by_creator_slices(creator_slices, metadata, codec)?; match (dedup, merge_mode) { // append-only, keep duplicate rows. @@ -1359,6 +1385,9 @@ struct TimeSeriesIterBuilder { predicate: PredicateGroup, dedup: bool, sequence: Option, + /// The cursor of each piece a row may belong to + /// ([`RangesOptions::creator_slices`](crate::memtable::RangesOptions::creator_slices)). + creator_slices: Option, merge_mode: MergeMode, batch_to_record_batch: Arc, } @@ -1371,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 { @@ -1613,6 +1643,8 @@ mod tests { &schema, &[0, 1, 2, 3, 4].into_iter().collect(), None, + None, + None, true, MergeMode::LastRow, ) @@ -1683,6 +1715,8 @@ mod tests { &schema, &projection, Some(SequenceRange::LtEq { max: 2 }), + None, + None, true, MergeMode::LastNonNull, ) @@ -1730,6 +1764,8 @@ mod tests { &schema, &projection, Some(SequenceRange::Gt { min: 1 }), + None, + None, true, MergeMode::LastNonNull, ) @@ -2213,6 +2249,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 ea991f27a31..ef88eecc1bf 100644 --- a/src/mito2/src/read.rs +++ b/src/mito2/src/read.rs @@ -21,6 +21,7 @@ pub mod flat_dedup; pub mod flat_merge; pub mod flat_projection; pub mod last_row; +pub(crate) mod piece_cursor; pub mod projection; pub(crate) mod prune; pub(crate) mod pruner; @@ -37,7 +38,8 @@ pub mod series_scan; pub mod stream; 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; @@ -46,8 +48,9 @@ use arrow_schema::SchemaRef; use common_time::Timestamp; 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}; @@ -64,13 +67,15 @@ use futures::TryStreamExt; use futures::stream::BoxStream; use mito_codec::row_converter::{CompositeValues, DensePrimaryKeyCodec, PrimaryKeyCodec}; use snafu::{OptionExt, ResultExt, ensure}; -use store_api::storage::{ColumnId, SequenceNumber, SequenceRange}; +use store_api::metadata::RegionMetadataRef; +use store_api::storage::{ColumnId, RegionId, SequenceNumber, SequenceRange}; use crate::error::{ ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, InvalidBatchSnafu, Result, }; -use crate::memtable::BoxedRecordBatchIterator; +use crate::memtable::{BoxedRecordBatchIterator, PieceCursor}; +use crate::read::piece_cursor::{agreed_piece_rows_or_refuse, evaluate_piece_filter}; use crate::region::options::MergeMode; pub(crate) fn timestamp_array_to_i64_slice(arr: &ArrayRef) -> &[i64] { @@ -142,6 +147,87 @@ struct DensePkCache { values: Vec>, } +/// Builds the one-row batch of tag values a time-series batch states, holding the columns the +/// piece expressions 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. +fn piece_probe_batch( + metadata: &RegionMetadataRef, + slices: &[PieceCursor], + pk_values: &CompositeValues, +) -> Option { + let mut referenced = HashSet::new(); + for slice in slices { + if let Some(expr) = &slice.expr { + 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; + 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() { + return None; + } + + RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).ok() +} + +/// Which candidate pieces select the rows of one time-series batch. +enum PieceSelection { + /// One flag per candidate piece, in the order the pieces were given. + Selected(Vec), + /// The selection cannot be proved; the payload says why. + Unresolved(String), +} + +/// The range a time-series memtable batch takes when its piece cannot be resolved: the rows every +/// candidate piece owes, or the refusal when they disagree on them. +/// +/// One range for every piece is the region's floor, so bounding the batch by it delivers exactly +/// the rows the per-piece rule delivers. An empty candidate set bounds nothing, so the batch keeps +/// the rows above 0. +fn unresolved_piece_cursor( + region_id: RegionId, + slices: &[PieceCursor], + detail: &str, +) -> Result { + let agreed = agreed_piece_rows_or_refuse( + region_id, + &format!("a time-series memtable batch of region {region_id}"), + slices, + detail, + )?; + Ok(agreed.unwrap_or(SequenceRange::Gt { min: 0 })) +} + impl Batch { /// Creates a new batch. pub fn new( @@ -415,25 +501,169 @@ 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 the tag values of the whole + /// batch are the values of that series and the selection is resolved once: the expression of + /// each candidate piece is evaluated against them. The rows are then kept one by one, because + /// two pieces may select the same series while owing different rows — a row is kept when at + /// least one selecting piece still owes it under that piece's own range, which is the same + /// rule the SST and bulk memtable reads apply. This replaces the single floor a region-level + /// cursor states: that floor is the least advanced piece, so it re-delivers the rows a more + /// advanced piece has already consumed. + /// + /// A piece that names no expression selects every row ([`PieceCursor::expr`]), so its range + /// bounds the whole batch rather than one series. + /// + /// `None` or an empty set applies no filter. + pub fn filter_by_creator_slices( + &mut self, + creator_slices: Option<&[PieceCursor]>, + metadata: &RegionMetadataRef, + codec: Option<&dyn PrimaryKeyCodec>, + ) -> Result<()> { + let Some(slices) = creator_slices.filter(|slices| !slices.is_empty()) else { + return Ok(()); + }; + let region_id = metadata.region_id; + let selected = match self.piece_selection(slices, metadata, codec) { + PieceSelection::Selected(selected) => selected, + PieceSelection::Unresolved(detail) => { + return self.filter_by_sequence_range(unresolved_piece_cursor( + region_id, slices, &detail, + )?); } }; + // The rows at least one selecting piece still owes. A piece that selects nothing + // contributes no row, so an interval of one piece never widens another's. + let seqs = self.sequences.as_arrow(); + let mut owed: Option = None; + for (slice, selects) in slices.iter().zip(&selected) { + if !*selects { + continue; + } + let rows = slice.rows_owed().filter(seqs).context(ComputeArrowSnafu)?; + owed = Some(match owed { + None => rows, + Some(current) => { + datatypes::arrow::compute::or(¤t, &rows).context(ComputeArrowSnafu)? + } + }); + } + let Some(owed) = owed else { + return self.filter_by_sequence_range(unresolved_piece_cursor( + region_id, + slices, + "no candidate piece selects the series of the batch", + )?); + }; + if owed.true_count() == self.timestamps.len() { + return Ok(()); + } + + self.filter(&BooleanVector::from(owed))?; + + Ok(()) + } + + /// Resolves which candidate pieces select the rows of `self`. + /// + /// A whole-domain piece selects every row without any evaluation; the others are resolved + /// from the batch's tag values, which is how a memtable states its primary key. + fn piece_selection( + &self, + slices: &[PieceCursor], + metadata: &RegionMetadataRef, + codec: Option<&dyn PrimaryKeyCodec>, + ) -> PieceSelection { + let evaluable = slices.iter().any(|slice| slice.expr.is_some()); + let probe = if evaluable { + let Some(codec) = codec else { + return PieceSelection::Unresolved( + "the batch states no primary key codec, so its tag values are unknown" + .to_string(), + ); + }; + 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 PieceSelection::Unresolved(format!( + "the primary key of the batch cannot be decoded: {e}" + )); + } + }, + }; + match piece_probe_batch(metadata, slices, &pk_values) { + Some(probe) => Some(probe), + None => { + return PieceSelection::Unresolved( + "the probe batch of the series' tag values cannot be built: a piece \ + 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" + .to_string(), + ); + } + } + } else { + None + }; + + let mut selected = Vec::with_capacity(slices.len()); + for slice in slices { + let Some(expr) = &slice.expr else { + selected.push(true); + continue; + }; + let Some(probe) = &probe else { + // A piece that names an expression is always evaluable here. + return PieceSelection::Unresolved( + "the probe batch of the series' tag values is missing".to_string(), + ); + }; + match expr.try_as_physical_expr(probe.schema_ref()) { + Ok(filter) => match evaluate_piece_filter(filter.as_ref(), probe) { + Ok(is_selected) => selected.push(is_selected.value(0)), + Err(e) => { + return PieceSelection::Unresolved(format!( + "a piece expression cannot be evaluated: {e}" + )); + } + }, + Err(e) => { + return PieceSelection::Unresolved(format!( + "a piece expression cannot be planned: {e}" + )); + } + } + } + + PieceSelection::Selected(selected) + } + + /// 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/piece_cursor.rs b/src/mito2/src/read/piece_cursor.rs new file mode 100644 index 00000000000..577e9099fce --- /dev/null +++ b/src/mito2/src/read/piece_cursor.rs @@ -0,0 +1,164 @@ +// 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. + +//! The piece cursors of a physical-sequence read. +//! +//! Such a read decides each row against the cursor of the piece its tag values fall into. One +//! rule answers the batches and files it cannot resolve that way: the rows every candidate piece +//! owes, which exist only when they all owe the same ones. + +use std::ops::BitAnd; + +use common_telemetry::debug; +use datafusion::physical_plan::PhysicalExpr; +use datatypes::arrow::array::{Array, BooleanArray}; +use datatypes::arrow::record_batch::RecordBatch; +use snafu::{OptionExt, ResultExt}; +use store_api::storage::{CursorShard, RegionId, SequenceNumber, SequenceRange}; + +use crate::error::{ + EvalPartitionFilterSnafu, Result, SequenceRangeUnsupportedSnafu, UnexpectedSnafu, +}; +use crate::memtable::PieceCursor; +use crate::sst::parquet::file_range::CreatorSliceFilter; + +/// A candidate piece of a physical-sequence read, whose still-unresolved cursor decides which +/// rows of one batch or file it owes. +pub(crate) trait PieceCursorBound { + /// The rows the piece still owes: `cursor < number <= until`, or `cursor < number` when the + /// piece states no upper bound. + fn rows_owed(&self) -> SequenceRange; +} + +impl PieceCursorBound for CursorShard { + fn rows_owed(&self) -> SequenceRange { + match self.until { + Some(max) => SequenceRange::GtLtEq { min: self.seq, max }, + None => SequenceRange::Gt { min: self.seq }, + } + } +} + +impl PieceCursorBound for PieceCursor { + fn rows_owed(&self) -> SequenceRange { + PieceCursor::rows_owed(self) + } +} + +impl PieceCursorBound for CreatorSliceFilter { + fn rows_owed(&self) -> SequenceRange { + self.range + } +} + +/// The rows every candidate piece owes, when they all owe the same ones. +/// +/// `None` when the set is empty or when the pieces disagree. +pub(crate) fn agreed_piece_rows(pieces: &[impl PieceCursorBound]) -> Option { + let first = pieces.first()?.rows_owed(); + pieces + .iter() + .all(|piece| piece.rows_owed() == first) + .then_some(first) +} + +/// [`agreed_piece_rows`], refusing the read instead of answering `None` when the candidates +/// disagree on the rows they owe: bounding by the least advanced cursor would deliver the rows a +/// more advanced piece has already consumed. +/// +/// `target` names what the read could not resolve, and `detail` says why it cannot be resolved per +/// piece. `Ok(None)` means `pieces` is empty: there is nothing to decide and nothing to refuse. +pub(crate) fn agreed_piece_rows_or_refuse( + region_id: RegionId, + target: &str, + pieces: &[impl PieceCursorBound], + detail: &str, +) -> Result> { + if let Some(agreed) = agreed_piece_rows(pieces) { + return Ok(Some(agreed)); + } + if pieces.is_empty() { + return Ok(None); + } + + let (min, max) = piece_cursor_span(pieces); + debug!( + "Cannot resolve the piece cursors of {} of region {} (candidates {}..={}), detail: {}", + target, region_id, min, max, detail + ); + let mut reason = format!( + "the physical-sequence read of {target} cannot resolve a per-piece cursor while the \ + candidate pieces of the region that allocated its rows disagree on the rows they owe \ + (cursors {min}..={max}): bounding it by the least advanced cursor {min} would deliver the \ + rows a more advanced piece has already consumed." + ); + if !detail.is_empty() { + reason.push(' '); + reason.push_str(detail); + } + SequenceRangeUnsupportedSnafu { + region_id, + min_seq: min, + max_seq: max, + reason, + } + .fail() +} + +/// The least and the greatest cursor value of a piece set. +fn piece_cursor_span(pieces: &[impl PieceCursorBound]) -> (SequenceNumber, SequenceNumber) { + let mut span: Option<(SequenceNumber, SequenceNumber)> = None; + for piece in pieces { + let cursor = lower_bound(piece.rows_owed()); + span = Some(match span { + None => (cursor, cursor), + Some((min, max)) => (min.min(cursor), max.max(cursor)), + }); + } + span.unwrap_or_default() +} + +fn lower_bound(rows_owed: SequenceRange) -> SequenceNumber { + match rows_owed { + SequenceRange::Gt { min } | SequenceRange::GtLtEq { min, .. } => min, + SequenceRange::LtEq { .. } => 0, + } +} + +/// Evaluates one piece expression against a probe batch, treating a null result as "not selected" +/// (the same rule the region partition filter applies). +pub(crate) fn evaluate_piece_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(UnexpectedSnafu { + reason: format!( + "a partition expression must evaluate to a boolean array, got {:?}", + array.data_type() + ), + })?; + let mut selected = boolean.values().clone(); + if let Some(nulls) = boolean.nulls() { + selected = selected.bitand(nulls.inner()); + } + + Ok(BooleanArray::from(selected)) +} diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 6cbcdfc48e7..b73fee8a9df 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -52,8 +52,8 @@ use snafu::{OptionExt, ResultExt, ensure}; use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef}; use store_api::region_engine::{PartitionRange, RegionScannerRef, ScannerProperties}; use store_api::storage::{ - ColumnId, RegionId, ScanRequest, SequenceNumber, SequenceRange, TimeSeriesDistribution, - TimeSeriesRowSelector, + ColumnId, CreatorCursorShards, 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}; @@ -68,10 +68,11 @@ use crate::error::{ }; #[cfg(feature = "enterprise")] use crate::extension::{BoxedExtensionRange, BoxedExtensionRangeProvider}; -use crate::memtable::{MemtableRange, RangesOptions}; +use crate::memtable::{MemtableRange, PieceCursor, RangesOptions, RegionPieceCursors}; use crate::metrics::READ_SST_COUNT; use crate::read::compat::{self, FlatCompatBatch}; use crate::read::flat_projection::FlatProjectionMapper; +use crate::read::piece_cursor::agreed_piece_rows_or_refuse; use crate::read::range::{FileRangeBuilder, MemRangeBuilder, RangeMeta, RowGroupIndex}; use crate::read::range_cache::{ScanRequestFingerprint, implied_time_range_from_exprs}; use crate::read::read_columns::ReadColumns; @@ -449,9 +450,214 @@ impl ScanRegion { || self.version.options.sst_format == Some(crate::sst::FormatType::Narthex) } + /// The cursor shards this exact read filters with: validated against the request's own exact + /// range, and capped by this region's snapshot `H`. + /// + /// Four checks happen here, before any file is pruned or any row is read: + /// + /// 1. a shard whose upper bound sits below its own cursor is an invalid request, not an empty + /// range: it would silently deliver nothing for a piece that claims to owe rows; + /// 2. a physical-sequence read needs the exact `(C, H]` it is a row-level form of, so a scan + /// that could not prove one fails closed instead of reading through the non-exact path; + /// 3. the request floor `C` is the region-level lower bound used to prune files, and it is a + /// *conservative* one only while it does not exceed a shard's own floor: a shard consumed + /// less than `C` still owes the rows in between, and pruning them away would truncate the + /// delta. Such a request is refused rather than narrowed; + /// 4. a shard states its value domain by an identity this build must be able to read back, so + /// a malformed one fails the request itself instead of the pruning of a file later on. + /// + /// The own region's shards are then capped at `H`: a row this region numbered above the + /// read's own snapshot does not exist yet in this read, so no piece owes it. A creator's + /// shards are left alone, because the holder's `H` states nothing about another region's + /// numbers. + fn exact_creator_cursor_shards( + &self, + sequence_range: Option, + ) -> Result> { + let Some(shards) = self.request.creator_cursor_shards.clone() else { + if self.request.read_row_sequence { + return SequenceRangeUnsupportedSnafu { + region_id: self.region_id(), + min_seq: self.request.memtable_min_sequence.unwrap_or_default(), + max_seq: self.request.memtable_max_sequence.unwrap_or_default(), + reason: "a physical-sequence read states no cursor shard, so it cannot tell \ + which rows it already consumed" + .to_string(), + } + .fail(); + } + return Ok(None); + }; + if !self.request.read_row_sequence { + return Ok(Some(shards)); + } + let Some(SequenceRange::GtLtEq { + min: floor, + max: own_upper, + }) = sequence_range + else { + return SequenceRangeUnsupportedSnafu { + region_id: self.region_id(), + min_seq: self.request.memtable_min_sequence.unwrap_or_default(), + max_seq: self.request.memtable_max_sequence.unwrap_or_default(), + reason: "a physical-sequence read requires the exact `(min, max]` range it is a \ + row-level form of, and this scan could not prove one" + .to_string(), + } + .fail(); + }; + + let own_region = self.region_id().as_u64(); + let mut normalized = BTreeMap::new(); + for (region, region_shards) in shards.iter() { + let mut capped = Vec::with_capacity(region_shards.len()); + for shard in region_shards { + if shard.until.is_some_and(|until| until < shard.seq) { + return InvalidRequestSnafu { + region_id: self.region_id(), + reason: format!( + "cursor shard of region {region} states an upper bound {} below its \ + own cursor {}, which owes no row at all", + shard.until.unwrap_or_default(), + shard.seq + ), + } + .fail(); + } + let mut shard = shard.clone(); + if *region == own_region { + if shard.seq < floor { + return SequenceRangeUnsupportedSnafu { + region_id: self.region_id(), + min_seq: floor, + max_seq: own_upper, + reason: format!( + "the request floor {floor} exceeds the floor {} of a cursor shard \ + of this region, so the shard still owes rows the file-level \ + bound would prune", + shard.seq + ), + } + .fail(); + } + shard.until = Some(shard.until.map_or(own_upper, |until| until.min(own_upper))); + } + // A bound that names no expression selects the whole domain, so only an identity + // this build cannot decode is refused. It is request state, not a file: the prune + // worker that would otherwise meet it reports it as a file that failed to prune. + if let Some(identity) = shard.partition_expr.as_deref() { + let _ = PartitionExpr::from_json_str(identity).with_context(|_| { + InvalidPartitionExprSnafu { + expr: identity.to_string(), + } + })?; + } + capped.push(shard); + } + normalized.insert(*region, capped); + } + + Ok(Some(Arc::new(normalized))) + } + + /// 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 + /// pieces: every one of them may hold a row, and no file metadata narrows the set the way it + /// does for the pieces 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. + /// + /// A shard that names no expression selects every row, so it is carried as a whole-domain + /// piece ([`PieceCursor::expr`]) of its own: readers keep a row when any selecting piece + /// still owes it, which credits the whole-domain piece's range without letting it widen the + /// range of a piece whose expression also selects the row. Every shard therefore stays a + /// candidate; only a shard whose identity this build cannot read back collapses the set. + /// + /// `Ok(None)` only when the scan is not a physical-sequence read or the region states no + /// cursor at all. + fn memtable_creator_slices( + &self, + shards: Option<&BTreeMap>>, + ) -> Result> { + if !self.request.read_row_sequence { + return Ok(None); + } + let Some(shards) = shards.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 { + slices.push(PieceCursor { + expr: None, + seq: shard.seq, + until: shard.until, + }); + continue; + }; + let Ok(Some(expr)) = PartitionExpr::from_json_str(identity) else { + debug!( + "Cannot read back piece cursor expression {}; bounding every memtable row by \ + the rows the candidates agree on", + identity + ); + return self.whole_domain_memtable_piece(shards); + }; + slices.push(PieceCursor { + expr: Some(expr), + seq: shard.seq, + until: shard.until, + }); + } + if slices.is_empty() { + return Ok(None); + } + + Ok(Some(Arc::new(slices))) + } + + /// The single whole-domain piece a memtable is bounded by when it states a candidate piece + /// whose identity this build cannot read back, so no row can be attributed to a piece. + /// + /// The piece carries the rows every candidate agrees on, which is what makes it exact for a + /// row no expression selects. Candidates that disagree cannot be resolved, so the read fails. + fn whole_domain_memtable_piece( + &self, + shards: &[CursorShard], + ) -> Result> { + let Some(first) = shards.first() else { + return Ok(None); + }; + agreed_piece_rows_or_refuse( + self.region_id(), + &format!("the memtable of region {}", self.region_id()), + shards, + "no row of the memtable can be attributed to a piece", + )?; + + Ok(Some(Arc::new(vec![PieceCursor { + expr: None, + seq: first.seq, + until: first.until, + }]))) + } + /// Creates a scan input. #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))] async fn scan_input(mut self) -> Result { + if self.request.read_row_sequence && self.use_series_scan() { + // The series reader builds its own streams from the series it collects and never + // applies a per-piece cursor, so it cannot serve a physical-sequence read. + return SequenceRangeUnsupportedSnafu { + region_id: self.region_id(), + min_seq: self.request.memtable_min_sequence.unwrap_or_default(), + max_seq: self.request.memtable_max_sequence.unwrap_or_default(), + reason: "a physical-sequence read is unsupported on a per-series or narthex scan" + .to_string(), + } + .fail(); + } 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(); @@ -491,6 +697,9 @@ impl ScanRegion { } .fail(); } + let creator_cursor_shards = self.exact_creator_cursor_shards(sequence_range)?; + let memtable_creator_slices = + self.memtable_creator_slices(creator_cursor_shards.as_deref())?; let memtables = self.version.memtables.list_memtables(); // Skip empty memtables and memtables out of time range. let mut mem_range_builders = Vec::new(); @@ -530,6 +739,7 @@ impl ScanRegion { self.request.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| { @@ -602,12 +812,14 @@ impl ScanRegion { .flatten(), ) .with_sequence_range(sequence_range) + .with_read_row_sequence(self.request.read_row_sequence) + .with_creator_slice_cursors(creator_cursor_shards) .with_query_stat_counters(self.query_stat_counters); #[cfg(feature = "enterprise")] let input = if !self.request.skip_sst_files && let Some(provider) = self.extension_range_provider { - if sequence_range.is_some() { + if sequence_range.is_some() || self.request.read_row_sequence { // Defense in depth: the engine already rejects exact // sequence-range reads on follower regions with an extension // provider, but if one ever reaches the reader, fail closed @@ -704,6 +916,25 @@ impl ScanRegion { expr.collect_column_names(&mut extra_col_names); } + // A physical-sequence read resolves a row's piece from the columns its expression + // references, so those columns must be read too. They are internal: the output projection + // happens after the flat batch, so adding them does not change the result schema. + if self.request.read_row_sequence + && let Some(cursors) = &self.request.creator_cursor_shards + { + for shard in cursors.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 + // reaches the same conclusion when it compiles the pieces. + 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) @@ -919,6 +1150,7 @@ pub(crate) fn request_preserves_rows(request: &ScanRequest) -> bool { && request.sst_min_sequence.is_none() && !request.snapshot_on_scan && !request.exact_sequence_range + && !request.read_row_sequence && !request.skip_sst_files } @@ -999,6 +1231,12 @@ pub struct ScanInput { /// 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 the scan keeps the physical `__sequence` column of a file another region + /// created and filters its rows by [`ScanInput::creator_slice_cursors`]. + pub(crate) read_row_sequence: bool, + /// Per-region piece cursors of a physical-sequence read, keyed by the region that allocated + /// the numbers ([`ScanRequest::creator_cursor_shards`]). + pub(crate) creator_slice_cursors: Option>>>, /// Whether this scan is for compaction. pub(crate) compaction: bool, /// Max number of compaction inputs decoded concurrently ahead of the merge. @@ -1073,6 +1311,8 @@ impl ScanInput { explain_flat_format: false, snapshot_sequence: None, sequence_range: None, + read_row_sequence: false, + creator_slice_cursors: None, compaction: false, compaction_read_parallelism: 1, json2_rewrite_targets: Arc::default(), @@ -1141,8 +1381,14 @@ impl ScanInputBuilder { self.input.scan_memory_tracker = None; } let input = &self.input; + // A physical-sequence read filters rows by the cursor of the piece each row belongs to, + // and a cached range result carries no record of which piece produced a row: replaying + // one for a different (or no) cursor set would hand the caller rows this read already + // consumed. Such a read therefore keeps no range-cache entry of its own and never reuses + // one. let eligible = !input.compaction && !input.files.is_empty() + && !input.read_row_sequence && matches!(input.cache_strategy, CacheStrategy::EnableAll(_)); let metadata = input.region_metadata(); @@ -1429,6 +1675,23 @@ impl ScanInputBuilder { self } + /// Sets whether the scan reads the physical row sequences of adopted files. + #[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 + } + + /// Sets the per-region piece cursors a physical-sequence read filters with. + #[must_use] + pub(crate) fn with_creator_slice_cursors( + mut self, + creator_slice_cursors: Option>>>, + ) -> Self { + self.input.creator_slice_cursors = creator_slice_cursors; + self + } + /// Sets whether this scan is for compaction. #[must_use] pub(crate) fn with_compaction(mut self, compaction: bool) -> Self { @@ -1674,6 +1937,8 @@ impl ScanInput { .pre_filter_mode(pre_filter_mode) .postpone_time_index_filter(postpone_time_index_filter) .decode_primary_key_values(decode_pk_values) + .read_row_sequence(self.read_row_sequence) + .creator_slice_cursors(self.creator_mode_cursors(file)) .build_reader_input(reader_metrics) .await; let read_input = match res { @@ -1908,6 +2173,139 @@ impl ScanInput { self.mapper.metadata() } + /// 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 file-level row filter of a physical-sequence read of `file`: the piece cursors of the + /// region that allocated its numbers, which is what bounds the file before any row is read. + /// + /// The cursors are the pieces of the file's own region, and the filter is the *conservative* + /// one they allow: the least advanced cursor bounds the file from below, and from above only + /// when every piece states a bound — the greatest of them, since a row above its own piece's + /// bound is refused per row, but a row below another piece's bound must not be dropped here. + /// The per-row rule ([`ScanInput::creator_slice_cursors`]) is the exact one. + /// + /// A region's **own** files are bounded the same way, and additionally by the scan's own + /// `H`: their rows carry this region's numbers, so `H` bounds them whenever no piece states a + /// bound. A creator's numbers are not bounded by any statement of this region, so an adopted + /// file stays unbounded above instead. + /// + /// `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); + } + let meta = file.meta_ref(); + let Some(cursors) = self + .creator_slice_cursors + .as_ref() + .and_then(|cursors| cursors.get(&meta.region_id.as_u64())) + else { + return Ok(None); + }; + let mut cursor: Option = None; + let mut bound: Option = None; + let mut every_bound = true; + for shard in cursors { + cursor = Some(cursor.map_or(shard.seq, |current| current.min(shard.seq))); + match shard.until { + Some(until) => bound = Some(bound.map_or(until, |current| current.max(until))), + None => every_bound = false, + } + } + // The own region's rows do not exist above the read's own snapshot, so `H` caps whatever + // its shards state. A creator's numbers are not bounded by any statement of this region, + // so an adopted file is left with the envelope its own shards allow. + let own_bound = if meta.region_id == self.region_metadata().region_id { + match self.sequence_range { + Some(SequenceRange::GtLtEq { max, .. } | SequenceRange::LtEq { max }) => Some(max), + _ => None, + } + } else { + None + }; + let bound = if every_bound { bound } else { None }; + let bound = match (own_bound, bound) { + (Some(own), Some(bound)) => Some(bound.min(own)), + (Some(own), None) => Some(own), + (None, bound) => bound, + }; + + Ok(cursor.map(|min| match bound { + Some(max) => SequenceRange::GtLtEq { min, max }, + None => SequenceRange::Gt { min }, + })) + } + + /// The piece cursors a physical-sequence read of `file` decides each row against: those of + /// the region that allocated its numbers. + /// + /// A file carrying this region's own numbers is read the same way — the cursors 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. + /// + /// `None` means the per-row rule cannot narrow the file's floor any further: no cursor of the + /// file's region is known (`row_sequence_filter` still fails an adopted file closed). + pub(crate) fn creator_mode_cursors(&self, file: &FileHandle) -> Option>> { + if !self.read_row_sequence { + return None; + } + let meta = file.meta_ref(); + self.creator_slice_cursors + .as_ref()? + .get(&meta.region_id.as_u64()) + .map(|shards| Arc::new(shards.clone())) + } + + /// The row filter a physical-sequence read applies to `file` at file granularity: the cursors + /// of the region that allocated its numbers, never this region's own `(C, H]` for a number it + /// did not allocate. + /// + /// A file of **this** region whose region states no cursor keeps the scan's own `(C, H]`: its + /// rows carry this region's numbers, and the selection proved the column holds them + /// (`FileMeta::has_original_row_sequences`), so the bound applies without asking the + /// target-effective marker, which states nothing about the encoded bytes. For a file of + /// another region that bound is no answer — the holder's `(C, H]` states nothing about a + /// number another region allocated — so a file whose creator states no cursor fails closed. + /// + /// `Ok(None)` only when the scan is not a physical-sequence read. + 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) { + return Ok(self.sequence_range); + } + 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 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 { // A single LastNonNull source can retain delete markers and multiple versions // of a row. Field filters must leave all of them available for deduplication. @@ -2053,6 +2451,16 @@ fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode { /// A foreign file without that barrier is retained as a failed-closed error so /// it cannot be mistaken for a local sequence domain. This check is performed /// even when another exact-range capability condition would return `None`. +/// +/// A physical-sequence read ([`ScanRequest::read_row_sequence`]) does not virtualize +/// anything: it compares every row against the cursor of the region that allocated its +/// number. The barrier and the target-effective marker then say nothing about the encoded +/// numbers, so the file-level capability such a read needs is proof of them +/// (`FileMeta::has_original_row_sequences`). Every file the time range selects must +/// carry that proof before the file is pruned or a row of it is compared, which is the +/// single gate: a file whose bytes are a uniform barrier, a folded version, or an +/// unproved legacy encoding has no physical maximum a cursor bounds, so pruning it by +/// its barrier or filtering its rows by it would report an empty or a partial success. pub(crate) fn exact_sequence_range( request: &ScanRequest, version: &crate::region::version::Version, @@ -2073,6 +2481,7 @@ pub(crate) fn exact_sequence_range( let min = request.memtable_min_sequence; let mut check_capability = request.exact_sequence_range && min.is_some(); let sst_min_sequence = request.sst_min_sequence.and_then(NonZeroU64::new); + let physical_read = request.read_row_sequence; let mut files = Vec::new(); let mut files_allow_exact_range = true; @@ -2084,7 +2493,29 @@ pub(crate) fn exact_sequence_range( .filter(|file| file_in_range(file, &time_range)) { let meta = file.meta_ref(); + // The single proof gate of a physical-sequence read: it runs for every file the time + // range selects, before a barrier prunes it or a creator cursor bounds a row of it. + if physical_read && !meta.has_original_row_sequences() { + return SequenceRangeUnsupportedSnafu { + region_id: version.metadata.region_id, + min_seq: min.unwrap_or_default(), + max_seq: request.memtable_max_sequence.unwrap_or_default(), + reason: format!( + "the physical-sequence read of file {} of region {} cannot prove that its \ + bytes carry the numbers the allocating region assigned to its rows, so \ + neither its barrier nor a creator cursor can tell which of them a read \ + already consumed", + meta.file_id, meta.region_id + ), + } + .fail(); + } + // A physical-sequence read keeps the creator's numbers, which the barrier does not bound: + // the file is kept and filtered by the creator's cursors. + let keeps_foreign_sequence_domain = + physical_read && meta.region_id != version.metadata.region_id; let selected = (!request.exact_sequence_range + || keeps_foreign_sequence_domain || min.is_none_or(|min| meta.sequence.is_none_or(|sequence| sequence.get() > min))) && match (sst_min_sequence, meta.sequence) { (Some(min_sequence), Some(file_sequence)) => file_sequence > min_sequence, @@ -2096,7 +2527,10 @@ pub(crate) fn exact_sequence_range( continue; } - if let Some(min) = min + // The target-effective capability checks describe a read that virtualizes rows at the + // barrier, which a proven physical read does not do: its proof replaces them. + if !physical_read + && let Some(min) = min && check_capability { if meta.region_id != version.metadata.region_id && meta.sequence.is_none() { @@ -3869,6 +4303,67 @@ mod tests { assert!(exact_sequence_range(&request, &version).is_err()); } + /// A physical-sequence read refuses a file whose bytes carry no proven allocator numbers, + /// even when the file's barrier would prune it at the request floor: pruning it would report + /// the delta as complete while the caller may still owe its rows. + #[test] + fn test_exact_sequence_selection_refuses_an_unproved_physical_file() { + 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 version = crate::region::version::VersionBuilder::new(metadata.clone(), mutable) + .options(crate::region::options::RegionOptions { + preserve_row_sequence: true, + ..Default::default() + }) + .add_files( + new_noop_file_purger(), + [FileMeta { + region_id: metadata.region_id, + sequence: NonZeroU64::new(3), + preserve_row_sequence: true, + ..Default::default() + }] + .into_iter(), + ) + .build(); + let request = ScanRequest { + exact_sequence_range: true, + read_row_sequence: true, + memtable_min_sequence: Some(3), + memtable_max_sequence: Some(20), + creator_cursor_shards: Some(Arc::new(BTreeMap::from([( + metadata.region_id.as_u64(), + vec![CursorShard::whole_domain(3)], + )]))), + ..Default::default() + }; + let err = exact_sequence_range(&request, &version).unwrap_err(); + assert!( + matches!(err, crate::error::Error::SequenceRangeUnsupported { .. }), + "a physical read must refuse a file whose bytes carry no proven numbers: {err}" + ); + + // The unopted read keeps the target-effective rule: the barrier at the floor proves the + // file disjoint, so it is pruned and the exact range stays available. + let unopted = ScanRequest { + read_row_sequence: false, + creator_cursor_shards: None, + ..request.clone() + }; + let (files, range) = exact_sequence_range(&unopted, &version).unwrap(); + assert!(files.is_empty()); + assert_eq!(Some(SequenceRange::GtLtEq { min: 3, max: 20 }), 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 905f7c17095..21943bbf721 100644 --- a/src/mito2/src/read/scan_util.rs +++ b/src/mito2/src/read/scan_util.rs @@ -1536,6 +1536,10 @@ pub(crate) async fn scan_flat_file_ranges( /// batches have already been virtualized to the target-local file barrier, so /// they are filtered using the effective batch sequence. Local untrusted files /// pass through because exact capability excludes them before row filtering. +/// A physical-sequence read states the decision itself: the selection proved the +/// column carries the allocating region's numbers +/// (`FileMeta::has_original_row_sequences`), so the target-effective marker of a +/// participating file never suppresses the filter. pub(crate) fn filter_flat_batch_by_sequence( record_batch: RecordBatch, sequence_range: Option, @@ -1633,12 +1637,23 @@ pub fn build_flat_file_range_scan_stream( let build_cost = build_reader_start.elapsed(); part_metrics.inc_build_reader_cost(build_cost); - let file_sequence_trusted = range - .file_handle() - .is_effective_target_sequence_trusted(stream_ctx.input.region_metadata().region_id); + // Which rows of this file the read has already consumed: whichever region allocated + // a row's number decides, through the cursor of the piece the row belongs to. 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, + range.file_handle().is_effective_target_sequence_trusted( + stream_ctx.input.region_metadata().region_id, + ), + ), + }; while let Some(batch) = next_aligned_file_batch( - &range, &mut reader, stream_ctx.input.sequence_range, file_sequence_trusted, + &range, &mut reader, file_sequence_range, file_sequence_trusted, ).await? { yield batch; } diff --git a/src/mito2/src/sst/parquet/file_range.rs b/src/mito2/src/sst/parquet/file_range.rs index fec4cec6d96..25a4478b1e9 100644 --- a/src/mito2/src/sst/parquet/file_range.rs +++ b/src/mito2/src/sst/parquet/file_range.rs @@ -23,9 +23,9 @@ use api::v1::{OpType, SemanticType}; use common_telemetry::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::arrow::record_batch::{RecordBatch, RecordBatchOptions}; use datatypes::schema::Schema; use mito_codec::row_converter::PrimaryKeyCodec; use parquet::arrow::arrow_reader::RowSelection; @@ -33,7 +33,7 @@ use parquet::file::metadata::ParquetMetaData; use snafu::{OptionExt, ResultExt}; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::RegionMetadataRef; -use store_api::storage::{ColumnId, TimeSeriesRowSelector}; +use store_api::storage::{ColumnId, SequenceRange, TimeSeriesRowSelector}; use table::predicate::Predicate; use crate::cache::CacheStrategy; @@ -43,10 +43,12 @@ use crate::error::{ }; use crate::read::compat::FlatCompatBatch; use crate::read::last_row::FlatRowGroupLastRowCachedReader; +use crate::read::piece_cursor::agreed_piece_rows_or_refuse; use crate::read::prune::FlatPruneReader; use crate::sst::file::FileHandle; use crate::sst::parquet::flat_format::{ - DecodedPrimaryKeys, FlatReadFormat, decode_primary_keys, time_index_column_index, + DecodedPrimaryKeys, FlatReadFormat, decode_primary_keys, sequence_column_index, + time_index_column_index, }; use crate::sst::parquet::reader::{ FlatRowGroupReader, MaybeFilter, RowGroupBuildContext, RowGroupReaderBuilder, @@ -355,10 +357,35 @@ 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 piece cursors a physical-sequence read filters the file's rows with, compiled for + /// per-row evaluation. + /// + /// The pieces are slices of one region's value domain, so at most one of them selects a + /// given row, except a whole-domain piece ([`CreatorSliceFilter::filter`]), which selects + /// every row. Empty for every other read. + pub(crate) creator_slices: Vec, + /// The sequence range a row of this file takes when no piece expression selects it: the + /// range every candidate piece carries, or `None` when the candidates disagree. + /// + /// `None` makes the read fail on such a row instead of bounding it by the least advanced + /// cursor, which would deliver the rows a more advanced piece has already consumed. + pub(crate) fallback_range: Option, +} + +/// One piece cursor of a file, compiled for per-row evaluation. +pub(crate) struct CreatorSliceFilter { + /// Physical expression selecting the piece, or `None` for the region's whole value domain, + /// which selects every row of the file. + pub(crate) filter: Option>, + /// The rows the piece still owes: `cursor < number <= until`, or `cursor < number` when + /// the piece states no upper bound. + pub(crate) range: SequenceRange, } /// Common fields for a range to read and filter batches. @@ -429,8 +456,22 @@ impl RangeBase { &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.as_ref(), + )?; + mask = mask.bitand(&partition_mask); + } + // Which rows of the file this read has already consumed: decided per row by the + // piece 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(); @@ -658,10 +699,9 @@ impl RangeBase { fn evaluate_partition_filter( &self, record_batch: &RecordBatch, - partition_filter: &PartitionFilterContext, + physical_expr: &dyn PhysicalExpr, ) -> Result { - let columnar_value = partition_filter - .region_partition_physical_expr + let columnar_value = physical_expr .evaluate(record_batch) .context(EvalPartitionFilterSnafu)?; let array = columnar_value @@ -684,6 +724,95 @@ impl RangeBase { Ok(mask) } + /// Computes the mask of rows this read still owes, resolved per row by the piece the row + /// belongs to. + /// + /// The pieces are slices of the file's region, so at most one of them selects a row: the + /// row is kept when its own sequence lies in that piece's range, which is why a file that + /// straddles several pieces delivers each row once, from the piece that row belongs to. + /// Bounding the whole file by one cursor cannot do that — the least advanced one + /// re-delivers the rows a more advanced piece has already consumed, the most advanced one + /// drops the rows a lagging piece still owes. + /// + /// A piece that names no expression ([`CreatorSliceFilter::filter`]) selects every row, so a + /// row two pieces select is kept while either still owes it under its own range. + /// + /// A row no piece expression selects has no piece to attribute it to, so it takes + /// [`PartitionFilterContext::fallback_range`], which exists only when every candidate + /// carries the same range. Otherwise the read fails rather than guessing. + fn evaluate_creator_slices( + &self, + input: &RecordBatch, + record_batch: &RecordBatch, + partition_filter: &PartitionFilterContext, + ) -> Result { + let num_rows = input.num_rows(); + let slices = &partition_filter.creator_slices; + let sequence_column = input.column(sequence_column_index(input.num_columns())); + + // Per piece, the rows whose own sequence lies in the range it owes. + let mut owed = Vec::with_capacity(slices.len()); + for slice in slices { + owed.push( + slice + .range + .filter(sequence_column) + .context(ComputeArrowSnafu)?, + ); + } + // Per row, the piece whose expression selects it; `None` is a whole-domain piece, which + // selects every row. + let mut selected = Vec::with_capacity(slices.len()); + for slice in slices { + selected.push( + slice + .filter + .as_ref() + .map(|filter| self.evaluate_partition_filter(record_batch, filter.as_ref())) + .transpose()?, + ); + } + let fallback = match &partition_filter.fallback_range { + Some(range) => Some(range.filter(sequence_column).context(ComputeArrowSnafu)?), + None => None, + }; + + let mut kept = BooleanBufferBuilder::new(num_rows); + for row in 0..num_rows { + // The pieces are disjoint, so at most one expression selects a row, and a whole-domain + // piece selects every row. If more than one selects it, a piece that still owes the + // row is enough: one piece's range never widens another's. + let mut attributed = false; + let mut keep = false; + for (index, mask) in selected.iter().enumerate() { + if mask.as_ref().is_none_or(|mask| mask.value(row)) { + attributed = true; + keep |= owed[index].value(row); + } + } + if !attributed { + keep = match &fallback { + Some(fallback) => fallback.value(row), + None => { + // The reader states no fallback exactly while the candidates disagree, + // which the refusal proves. + let region_id = self.read_format.metadata().region_id; + agreed_piece_rows_or_refuse( + region_id, + &format!("a file of region {region_id}"), + slices, + &format!("row {} of {} matches no candidate piece", row + 1, num_rows), + )?; + false + } + }; + } + kept.append(keep); + } + + Ok(kept.finish()) + } + /// Projects the input `RecordBatch` to match the given schema. /// /// This is used for partition expression evaluation. The schema should only contain @@ -742,6 +871,17 @@ impl RangeBase { .fail(); } + if columns.is_empty() { + // A context carrying only whole-domain piece cursors references no column, so there is + // nothing to project: the row count has to be stated instead. + return RecordBatch::try_new_with_options( + arrow_schema.clone(), + columns, + &RecordBatchOptions::new().with_row_count(Some(input.num_rows())), + ) + .context(NewRecordBatchSnafu); + } + RecordBatch::try_new(arrow_schema.clone(), columns).context(NewRecordBatchSnafu) } } @@ -939,7 +1079,9 @@ 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_range: None, }), }; for (skip_fields, skip_tags, expected) in [ @@ -1029,11 +1171,15 @@ 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_range: None, }); let temporary = base .project_record_batch_for_pruning_flat(&batch, &schema, &mut TagDecodeState::new()) @@ -1095,10 +1241,14 @@ 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_range: None, }); let filtered = base diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index df1be80788c..40671bb7fe4 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, CursorShard, FileId}; use table::predicate::Predicate; use crate::cache::index::result_cache::PredicateKey; @@ -58,10 +58,11 @@ use crate::cache::{ prepare_sst_meta, }; use crate::error::{ - ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, SerializePartitionExprSnafu, - UnexpectedSnafu, + InvalidPartitionExprSnafu, ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, + SerializePartitionExprSnafu, UnexpectedSnafu, }; use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED}; +use crate::read::piece_cursor::{PieceCursorBound, agreed_piece_rows, agreed_piece_rows_or_refuse}; use crate::read::prune::FlatPruneReader; use crate::read::read_columns::ReadColumns; use crate::sst::file::FileHandle; @@ -75,7 +76,8 @@ use crate::sst::index::inverted_index::applier::{ InvertedIndexApplierRef, InvertedIndexApplyMetrics, }; use crate::sst::parquet::file_range::{ - FileRangeContext, FileRangeContextRef, PartitionFilterContext, PreFilterMode, RangeBase, + 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}; @@ -212,6 +214,23 @@ pub struct ParquetReaderBuilder { expected_metadata: Option, /// Whether this reader is for compaction. compaction: bool, + /// Keeps the physical `__sequence` column of a file instead of virtualizing it at the + /// handle's admission barrier. + /// + /// Only a physical-sequence read sets this, and only once the file proved that its bytes + /// carry the numbers its allocating region assigned + /// (`FileMeta::has_original_row_sequences`); its caller then filters the rows by the cursor + /// of that region. Every other reader leaves it `false`: compaction and ordinary queries + /// depend on the substitution. + read_row_sequence: bool, + /// Candidate piece cursors of a physical-sequence read, keyed by the region that allocated + /// the numbers ([`ScanRequest::creator_cursor_shards`]) and already narrowed to the pieces + /// that may hold a row of this file. + /// + /// The reader compiles each identity into a row filter and keeps a row only when its own + /// sequence lies in the range of the piece its values fall into + /// (`PartitionFilterContext::creator_slices`). + creator_slice_cursors: Option>>, /// Mode to pre-filter columns. pre_filter_mode: PreFilterMode, /// Whether to run the reduced-column predicate prefilter pass. @@ -257,6 +276,8 @@ impl ParquetReaderBuilder { fulltext_index_appliers: [None, None], expected_metadata: None, compaction: false, + read_row_sequence: false, + creator_slice_cursors: None, pre_filter_mode: PreFilterMode::All, enable_predicate_prefilter: true, postpone_time_index_filter: false, @@ -348,6 +369,29 @@ impl ParquetReaderBuilder { self } + /// Reads the physical `__sequence` of a file instead of substituting the handle's barrier for + /// every row. + /// + /// See [`ScanRequest::read_row_sequence`]; the selection refuses a file that cannot prove its + /// bytes carry the allocating region's numbers, and the caller filters the rows by that + /// region's cursor. + #[must_use] + pub(crate) fn read_row_sequence(mut self, read_row_sequence: bool) -> Self { + self.read_row_sequence = read_row_sequence; + self + } + + /// Sets the candidate piece cursors of a physical-sequence read. + /// + /// The reader keeps a row only when its own sequence lies in the range of the piece its + /// values fall into (`PartitionFilterContext::creator_slices`), so the file's rows are split + /// by the piece 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 + } + /// Sets the pre-filter mode. #[must_use] pub(crate) fn pre_filter_mode(mut self, pre_filter_mode: PreFilterMode) -> Self { @@ -505,7 +549,14 @@ impl ParquetReaderBuilder { ); } let file_meta = self.file_handle.meta_ref(); - let override_sequence = if is_foreign { + let override_sequence = if self.read_row_sequence { + // The selection proved the file's bytes carry the numbers its allocating region + // assigned (`FileMeta::has_original_row_sequences`), and the caller compares each row + // against that region's cursor. A local barrier says only when the file was admitted + // and a footer-derived value only what a writer substituted, so either would make + // every row look uniformly old or freshly published. + None + } else if is_foreign { file_meta.sequence.map(|sequence| sequence.get()) } else if file_meta.preserve_row_sequence { None @@ -693,6 +744,10 @@ impl ParquetReaderBuilder { /// 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 piece cursors 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, @@ -707,17 +762,66 @@ 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 piece cursors below are independent of that. + let region_partition_expr = if is_same_region_partition { + None + } else { + region_partition_expr + }; + + let cursors = self + .creator_slice_cursors + .as_deref() + .map(Vec::as_slice) + .unwrap_or_default(); + if region_partition_expr.is_none() && 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 scan_region_id = self + .expected_metadata + .as_ref() + .map(|metadata| metadata.region_id) + .unwrap_or_else(|| read_format.metadata().region_id); + let meta = self.file_handle.meta_ref(); + let refuse = |detail: &str| -> Result<()> { + agreed_piece_rows_or_refuse( + scan_region_id, + &format!("file {} of region {}", meta.file_id, meta.region_id), + cursors, + detail, + ) + .map(|_| ()) + }; + let mut piece_exprs = Vec::with_capacity(cursors.len()); + for cursor in cursors { + // A whole-domain cursor selects every row: it takes part in the per-row rule as a + // filter of its own, so its range is credited to a row without widening the range of + // the piece whose expression also selects it. + let Some(identity) = cursor.partition_expr.as_deref() else { + piece_exprs.push((None, cursor.rows_owed())); + continue; + }; + let Some(expr) = PartitionExpr::from_json_str(identity).with_context(|_| { + InvalidPartitionExprSnafu { + expr: identity.to_string(), + } + })? + else { + refuse( + "it cannot read back the partition expression of one of its candidate pieces", + )?; + return Ok(None); + }; + expr.collect_column_names(&mut referenced_columns); + piece_exprs.push((Some(expr), cursor.rows_owed())); + } // Build a partition_schema containing only referenced columns. let partition_schema = Arc::new(datatypes::schema::Schema::new( @@ -748,12 +852,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 = piece_exprs + .into_iter() + .map(|(expr, range)| { + Ok(CreatorSliceFilter { + filter: expr + .map(|expr| expr.try_as_physical_expr(partition_schema.arrow_schema())) + .transpose() + .context(SerializePartitionExprSnafu)?, + range, + }) + }) + .collect::>>()?; + let fallback_range = agreed_piece_rows(cursors); Ok(Some(PartitionFilterContext { region_partition_physical_expr, partition_schema, + creator_slices, + fallback_range, })) } diff --git a/src/store-api/src/storage.rs b/src/store-api/src/storage.rs index e0761f8a006..0cabfc2d894 100644 --- a/src/store-api/src/storage.rs +++ b/src/store-api/src/storage.rs @@ -29,5 +29,7 @@ pub use datatypes::schema::{ pub use self::descriptors::*; pub use self::file::{FileId, FileRef, FileRefsManifest, GcReport, IndexVersion, ParseIdError}; pub use self::projection::NestedPath; -pub use self::requests::{ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector}; +pub use self::requests::{ + CreatorCursorShards, CursorShard, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector, +}; pub use self::types::{SequenceNumber, SequenceRange}; diff --git a/src/store-api/src/storage/requests.rs b/src/store-api/src/storage/requests.rs index 6ba43fb6af1..6bce30af76a 100644 --- a/src/store-api/src/storage/requests.rs +++ b/src/store-api/src/storage/requests.rs @@ -12,8 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::fmt::{Display, Formatter}; +use std::sync::Arc; use common_recordbatch::OrderOption; use datafusion_expr::expr::Expr; @@ -45,6 +46,59 @@ pub enum TimeSeriesDistribution { PerSeries, } +/// One slice of a sequence-domain cursor: the partition expression selecting a region's value +/// domain, the last sequence consumed inside it, and — when the producer can state it — the +/// last sequence the slice's delta covers. +/// +/// The pair bounds the rows one read owes on the slice: `seq < number <= until`. The upper end +/// matters because a row's number belongs to the domain of the region that allocated it, and a +/// read of a file **another** region created compares the row against the creator's numbers: +/// without the bound, every row the creator numbered above the delta is delivered as if it were +/// part of it. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct CursorShard { + /// Identity (`PartitionExpr::as_json_str()`) of the expression selecting this slice's value + /// domain, or `None` for the creator region's complete value domain. + pub partition_expr: Option, + /// Last sequence consumed in the domain `partition_expr` selects (exclusive lower bound). + pub seq: SequenceNumber, + /// Last sequence the delta of this slice covers (inclusive upper bound), when the producer + /// states one. + /// + /// `None` leaves the slice unbounded above: a row above `seq` is live until proven + /// otherwise. `Some(until)` says a row numbered above `until` belongs to a later delta and + /// must not be delivered by a read of this one. + pub until: Option, +} + +/// The cursor of every piece a request reads, keyed by the region that allocated the sequence +/// numbers. Shared between the request and the reader that resolves it, so the type is named once. +pub type CreatorCursorShards = Arc>>; + +impl CursorShard { + /// Creates a slice whose delta is unbounded above. + pub fn new(partition_expr: Option, seq: SequenceNumber) -> Self { + Self { + partition_expr, + seq, + until: None, + } + } + + /// Creates the slice covering a region's complete value domain, which is what a + /// region-keyed cursor states. + pub fn whole_domain(seq: SequenceNumber) -> Self { + Self::new(None, seq) + } + + /// Returns this slice with `until` as the inclusive upper bound of its delta + /// ([`CursorShard::until`]). + pub fn with_until(mut self, until: SequenceNumber) -> Self { + self.until = Some(until); + self + } +} + #[derive(Default, Clone, Debug, PartialEq)] pub struct ScanRequest { /// Requests bounded asynchronous exact-count preparation for a scalar COUNT. @@ -90,6 +144,57 @@ pub struct ScanRequest { /// /// Historical `memtable_only` reads must never set this flag. pub exact_sequence_range: bool, + /// Whether this scan reads the **physical** `__sequence` column of a file instead of + /// virtualizing every row to the handle's admission barrier. + /// + /// Only a file that proves its bytes carry the numbers its allocating region assigned is + /// compared. Every file the time range selects must state that proof, and a file whose column + /// is a uniform barrier, a folded version, or an unproved legacy encoding **fails closed** + /// with `SequenceRangeUnsupported` before it is pruned or a row of it is compared: the + /// barrier, the target-effective marker and the dedup markers state nothing about the encoded + /// numbers. + /// + /// A proved file of another region is filtered by [`Self::creator_cursor_shards`]: its + /// numbers belong to the domain of the region that allocated them, so neither this region's + /// own delta `(C, H]` — `C` its [`Self::memtable_min_sequence`], `H` its + /// [`Self::memtable_max_sequence`] — nor the file's barrier bounds them. A proved file of this + /// region is filtered by its own slices and, when it states none, by that delta. The read + /// neither cuts a file's numbers at its barrier nor reports what such a cut would leave: the + /// slices' `seq` and `until` — and, for this region's own rows, `(C, H]` — are the only bounds + /// it applies, and its output is just the rows. Every other reader, compaction included, + /// leaves this `false`. + /// + /// Such a read is a row-level form of an exact request, so it must also prove one and state + /// at least one cursor shard; an engine that cannot prove either **fails closed** with + /// `SequenceRangeUnsupported` instead of reading through the non-exact path. + pub read_row_sequence: bool, + /// Per-creator-region cursor slices a physical-sequence read filters with + /// ([`Self::read_row_sequence`]), keyed by the region that allocated the numbers. + /// + /// A scan of one region may hold files it adopted from others, and a row's number then + /// belongs to the creator's domain. The reader looks a file's + /// `FileMeta::region_id` up here and keeps the slices whose partition expression may hold + /// a row of the file, then compares every row against the cursor of the slice its own + /// partition expression selects. Only a file that proved its numbers belong to the region + /// this map keys it under is looked up at all: one without the proof of + /// [`Self::read_row_sequence`] fails closed before any slice of it applies. + /// + /// The slices bound rows only. The reader neither cuts a file's numbers at its barrier nor + /// reports which rows it delivered, so a caller must not read a new cursor out of the result: + /// what an adopted file's rows are compared against is exactly what this map states. + /// + /// Empty or absent means no cursor of the file's creator domain is known, and an adopted + /// file then **fails closed** with `SequenceRangeUnsupported`: comparing its numbers with a + /// bound of another domain drops live rows, and reading it unfiltered delivers every + /// already consumed row again. Every reader but a physical-sequence incremental delta + /// leaves it `None`. + /// + /// The shards of the scanned region itself describe this region's own numbering, so they are + /// bounded by the request's own snapshot upper bound and must not state a floor below the + /// request's `memtable_min_sequence`: that floor prunes files before any row is read, and a + /// shard consumed less than it still owes the rows in between. A shard of any region whose + /// upper bound sits below its own cursor owes no row at all and is an invalid request. + pub creator_cursor_shards: Option, /// Optional hint for the distribution of time-series data. pub distribution: Option, /// Optional hint from query-driven JSON type concretization. @@ -184,6 +289,9 @@ impl Display for ScanRequest { if self.exact_sequence_range { write!(f, "{}exact_sequence_range: true", delimiter.as_str())?; } + if self.read_row_sequence { + write!(f, "{}read_row_sequence: true", delimiter.as_str())?; + } if self.preserve_pk_dictionary_encoding { write!( f, @@ -222,6 +330,15 @@ mod tests { }; assert_eq!(request.to_string(), "ScanRequest { }"); + let request = ScanRequest { + read_row_sequence: true, + ..Default::default() + }; + assert_eq!( + request.to_string(), + "ScanRequest { read_row_sequence: true }" + ); + let projection = Some(vec![1, 2]); let request = ScanRequest { projection,