diff --git a/src/flow/src/batching_mode/task.rs b/src/flow/src/batching_mode/task.rs index 421f4869965..91af49562e8 100644 --- a/src/flow/src/batching_mode/task.rs +++ b/src/flow/src/batching_mode/task.rs @@ -232,6 +232,18 @@ impl RegionWatermarkSample { &self.watermarks } + /// The regions this round read, i.e. the sample plan's own participating set. + /// + /// A caller that must tell "read without a proved terminal watermark" from "never read" + /// (the plan pruned it) needs this beside [`Self::watermarks`]: the proved map alone + /// cannot distinguish them, and a baseline frozen from it alone would silently omit a + /// region the plan read and could not prove. Such a region's history would then be + /// aggregated from `0` by the first later read naming it, so freezing has to compare the + /// two sets instead of projecting the sample onto its proved watermarks. + pub fn read_regions(&self) -> &BTreeSet { + &self.read_regions + } + /// Keeps only the proved watermarks, dropping the read/unproved distinction. pub fn into_watermarks(self) -> BTreeMap { self.watermarks diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 1ae61e4e8b1..c6576ed979e 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -7106,6 +7106,126 @@ async fn test_read_row_sequence_filters_adopted_file_without_cut_by_creator_curs ); } +/// A creator slice that states the last sequence its delta covers bounds an adopted file from +/// above as well: a row above that bound was numbered after the delta this read stands for, +/// so delivering it here reports identity the caller has not consumed yet while its marker +/// stays below the row's number. +#[tokio::test] +async fn test_read_row_sequence_drops_adopted_rows_above_creator_upper_bound() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_creator_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // The creator's file states the numbers 1..5 and no cut, so the cursor decides alone. + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + // The delta is `(1, 3]`: rows 4 and 5 carry numbers the creator's cursor did not consume + // and its bound does not cover, so this round must not read them. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![CursorShard::whole_domain(1).with_until(3)], + 0, + 10, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "the rows above the creator's upper bound belong to a later delta, not to this read" + ); + + // The bound is a filter on the creator's domain, not a change of the cursor: stating a + // bound that covers every row delivers every row above the cursor, as before. + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![CursorShard::whole_domain(1).with_until(5)], + 0, + 10, + ), + ) + .await; + assert_eq!(vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], rows); +} + +/// A slice that states no upper bound keeps the unbounded `(cursor, +inf)` filter it always +/// had: the bound is optional evidence, and a read that lacks it must not lose a row that no +/// bound excludes. +#[tokio::test] +async fn test_read_row_sequence_reads_above_cursor_without_creator_upper_bound() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_without_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 0, 10), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], + rows, + "without a bound every row above the creator's cursor is still owed" + ); +} + +/// Several candidate slices: the file-level upper bound is the **least** bound any of them +/// states, because the file-level filter cannot tell which slice a row belongs to. The +/// counterexample this pins: the slice holding the file's rows proves the delta ends at 3 +/// while another candidate's bound reaches 9, and reading up to 9 delivers rows 4 and 5, +/// which no slice yields this round. +#[tokio::test] +async fn test_read_row_sequence_takes_the_least_creator_upper_bound() { + let mut env = TestEnv::with_prefix("test_read_row_sequence_least_upper_bound").await; + let engine = env.create_engine(MitoConfig::default()).await; + let source = RegionId::new(1, 2); + let target = RegionId::new(1, 1); + + // One file stating no expression, so every slice of the creator is a candidate for it. + // Its five rows carry the tag `0`, i.e. they all fall in the `[0, 5)` slice. + let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await; + assert_eq!(None, source_file.partition_expr); + create_foreign_target(&engine, target).await; + adopt_foreign_file(&engine, target, source_file, 6, true, None); + + let rows = scan_flat_row_sequences( + &engine, + target, + creator_cursor_scan( + source, + vec![ + // The slice the file's rows belong to: consumed up to 1, delta ends at 3. + partition_str_slice_cursor("0", "5", 1).with_until(3), + // A candidate that overlaps no row of this file, with a looser bound. + partition_str_slice_cursor("5", "9", 3).with_until(9), + ], + 0, + 10, + ), + ) + .await; + assert_eq!( + vec![(1000, 2), (2000, 3)], + rows, + "the file-level bound is the least bound of the candidates, so row 4 is left out" + ); +} + /// A creator this scan has no cursor slice for fails closed. Reading the file against this /// region's own `(C, H]` compares two sequence domains, and reading it unfiltered delivers /// every already consumed row again on every round; the scan reports the shared diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 7e45a29e761..739fa30c789 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -2037,13 +2037,19 @@ impl ScanInput { file.meta_ref().substituted_up_to } - /// The row filter of a physical-sequence read of `file`: `(candidate creator cursor, - /// +inf)`. + /// The row filter of a physical-sequence read of `file`: + /// `(candidate creator cursor, candidate creator bound]`, or `(.., +inf)` when no + /// candidate slice states an upper bound. /// /// This is the candidate selection of [`cursor_slice_may_hold_file_rows`] followed by one /// sequence range for the whole file, so a file whose expressions advanced differently is - /// read from the least advanced of them. The upper end is unbounded because no upper bound - /// of the creator's domain survives adoption. + /// read from the least advanced of them: the lower end is the *minimum* of the candidates' + /// cursors, and the upper end the *minimum* of the upper bounds they state + /// ([`CursorShard::until`]). The file-level filter cannot tell which slice a row belongs + /// to, so it may only prove what the least bound proves: a row above it may belong to the + /// slice whose delta ends exactly there, and delivering it would report progress this read + /// does not stand for. No candidate stating a bound leaves the file unbounded above, which + /// is what a creator whose domain states no bound allows. /// /// `None` means this scan has no cursor for the file's creator, or the file is not foreign /// at all. @@ -2074,15 +2080,21 @@ impl ScanInput { else { return Ok(None); }; - let mut cursor = None; + let mut cursor: Option = None; + let mut until: Option = None; for shard in shards { if cursor_slice_may_hold_file_rows(shard, meta)? { - cursor = Some( - cursor.map_or(shard.seq, |current: SequenceNumber| current.min(shard.seq)), - ); + cursor = Some(cursor.map_or(shard.seq, |current| current.min(shard.seq))); + if let Some(shard_until) = shard.until { + until = Some(until.map_or(shard_until, |current| current.min(shard_until))); + } } } - Ok(cursor.map(|min| SequenceRange::Gt { min })) + Ok(cursor.map(|min| match until { + // `min < number <= max`: the rows of the delta, neither re-read nor read ahead. + Some(max) => SequenceRange::GtLtEq { min, max }, + None => SequenceRange::Gt { min }, + })) } /// The candidate creator cursor slices of `file`, as the reader compiles them: @@ -2132,7 +2144,8 @@ impl ScanInput { /// `Ok(None)` means the file carries this region's own numbers (or this scan is not a /// physical-sequence read at all), so the scan's own `(C, H]` bounds it. /// - /// A foreign file is filtered by `(creator cursor, +inf)` + /// A foreign file is filtered by the cursor of its creator's slices — `(cursor, until]`, + /// or `(cursor, +inf)` when the creator states no bound /// ([`Self::creator_domain_sequence_range`]), with or without a substituted cut. A file /// whose creator this scan has no cursor slice for fails closed instead of falling back to /// the holder's `(C, H]`. [`exact_sequence_range`] never prunes such a file by this diff --git a/src/query/src/options.rs b/src/query/src/options.rs index 8fdaf4be0ff..39664ebadd3 100644 --- a/src/query/src/options.rs +++ b/src/query/src/options.rs @@ -468,15 +468,20 @@ const CURSOR_SHARD_VERSION: u64 = 2; const CURSOR_SHARD_SHARDS_KEY: &str = "shards"; const CURSOR_SHARD_EXPR_KEY: &str = "expr"; const CURSOR_SHARD_SEQ_KEY: &str = "seq"; +/// Inclusive upper bound of a slice's delta. Optional, and absent from a version 2 payload +/// written before the bound existed, which states the unbounded slice it always stated. +const CURSOR_SHARD_UNTIL_KEY: &str = "until"; /// Parses [`FLOW_INCREMENTAL_AFTER_SEQS`] in every shape it has taken. /// /// * expression-keyed (current, version 2): /// `{"": {"version": 2, "shards": [{"expr": "", "seq": -/// seq}, {"expr": null, "seq": seq}, ...]}}` — one cursor per partition expression of -/// that region, `null` selecting the region's complete value domain. `expr` is the JSON -/// form `PartitionExpr::as_json_str()` writes and is validated here, so an expression -/// identity that does not decode never reaches a scan; +/// seq, "until": seq?}, {"expr": null, "seq": seq}, ...]}}` — one cursor per partition +/// expression of that region, `null` selecting the region's complete value domain. `expr` +/// is the JSON form `PartitionExpr::as_json_str()` writes and is validated here, so an +/// expression identity that does not decode never reaches a scan. `until` is optional: a +/// slice that states it covers `seq < number <= until`, one that omits it is unbounded +/// above, exactly like a payload written before the bound existed; /// * region-keyed: `{"": seq}` — one cursor for the region's complete value /// domain, i.e. the single whole-domain slice. A reader that only knows the holder's /// cursor keeps working, and it states exactly what it always stated. @@ -566,7 +571,7 @@ fn parse_expression_keyed_shards( .collect() } -/// Parses one `{"expr": | null, "seq": N}` slice. +/// Parses one `{"expr": | null, "seq": N, "until": N?}` slice. fn parse_cursor_shard(region_id: u64, shard: &serde_json::Value) -> Result { let serde_json::Value::Object(fields) = shard else { return Err(invalid_query_context_extension(format!( @@ -602,7 +607,17 @@ fn parse_cursor_shard(region_id: u64, shard: &serde_json::Value) -> Result None, + Some(raw) => Some(parse_cursor_seq(region_id, raw)?), + }; + + Ok(match until { + Some(until) => CursorShard::new(partition_expr, seq).with_until(until), + None => CursorShard::new(partition_expr, seq), + }) } /// Checks that `expr` is a partition expression this build can read back, and returns the @@ -651,7 +666,9 @@ fn parse_cursor_seq(region_id: u64, raw: &serde_json::Value) -> Result { /// Encodes slice cursors as the expression-keyed (version [`CURSOR_SHARD_VERSION`]) form /// of [`FLOW_INCREMENTAL_AFTER_SEQS`], which [`parse_incremental_after_seqs`] reads back. -/// A whole-domain slice is written as an explicit `"expr": null`. +/// A whole-domain slice is written as an explicit `"expr": null`; an upper bound +/// ([`CursorShard::until`]) is written only when the slice states one, so a cursor of +/// unbounded slices encodes to exactly the payload the earlier builds wrote. pub fn encode_incremental_after_seqs(cursors: &BTreeMap>) -> Result { let encoded = cursors .iter() @@ -659,10 +676,17 @@ pub fn encode_incremental_after_seqs(cursors: &BTreeMap>) let shards = shards .iter() .map(|shard| { - serde_json::json!({ + let mut encoded = serde_json::json!({ CURSOR_SHARD_EXPR_KEY: shard.partition_expr, CURSOR_SHARD_SEQ_KEY: shard.seq, - }) + }); + // A slice with no upper bound writes no `until`: the field states a + // bound, and its absence is exactly the unbounded slice an older reader + // already understands. + if let Some(until) = shard.until { + encoded[CURSOR_SHARD_UNTIL_KEY] = serde_json::json!(until); + } + encoded }) .collect::>(); let value = serde_json::json!({ @@ -1200,6 +1224,58 @@ mod flow_extension_tests { assert_eq!(None, parsed.region_cursor(8)); } + /// A slice may state the last sequence its delta covers. A payload written before the + /// bound existed must keep decoding — as the unbounded slice it stated — and the bound + /// must survive a round trip, because a reader of an adopted file relies on it to leave + /// the creator's later rows alone. + #[test] + fn test_parse_flow_extensions_after_seqs_slice_upper_bound() { + // Version 2 payload without `until`, i.e. exactly what earlier builds wrote. + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10}]}}"#.to_string(), + )]); + let parsed = FlowQueryExtensions::parse_flow_extensions(&exts) + .unwrap() + .unwrap(); + assert_eq!( + parsed.incremental_after_seqs, + Some(HashMap::from([(7, vec![CursorShard::whole_domain(10)])])), + "a slice that states no upper bound is the unbounded slice it always was" + ); + assert_eq!( + None, + parsed.incremental_after_seqs.as_ref().unwrap()[&7][0].until + ); + + // The same payload with the bound stated. + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":20}]}}"#.to_string(), + )]); + let parsed = FlowQueryExtensions::parse_flow_extensions(&exts) + .unwrap() + .unwrap(); + assert_eq!( + parsed.incremental_after_seqs, + Some(HashMap::from([( + 7, + vec![CursorShard::whole_domain(10).with_until(20)] + )])) + ); + + // An upper bound that is not a sequence is refused at the boundary, like `seq`. + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":"nope"}]}}"#.to_string(), + )]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + assert!( + format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS), + "{err}" + ); + } + /// An expression this build cannot read back is rejected at the boundary rather than /// silently widened to the whole domain by the scan that receives it. #[test] @@ -1302,7 +1378,7 @@ mod flow_extension_tests { ( 2, vec![ - CursorShard::new(Some(low.clone()), 10), + CursorShard::new(Some(low.clone()), 10).with_until(15), CursorShard::new(Some(high.clone()), 3), ], ), @@ -1310,14 +1386,14 @@ mod flow_extension_tests { let json = encode_incremental_after_seqs(&cursors).unwrap(); // Compared as JSON: the order of the object keys is serde_json's business, the - // identity and the sequence are what the wire states. + // identity, the sequence and the optional bound are what the wire states. assert_eq!( serde_json::json!({ "1": {"version": 2, "shards": [{"expr": null, "seq": 10}]}, "2": { "version": 2, "shards": [ - {"expr": low, "seq": 10}, + {"expr": low, "seq": 10, "until": 15}, {"expr": high, "seq": 3}, ] }, diff --git a/src/servers/src/grpc/flight.rs b/src/servers/src/grpc/flight.rs index 6d8d1b0c4ac..e0a330a7835 100644 --- a/src/servers/src/grpc/flight.rs +++ b/src/servers/src/grpc/flight.rs @@ -732,6 +732,7 @@ mod tests { vec![CursorShard { partition_expr: None, seq: 10, + until: None, }], ), ( @@ -739,6 +740,7 @@ mod tests { vec![CursorShard { partition_expr: None, seq: 20, + until: None, }], ), ])) @@ -809,10 +811,12 @@ mod tests { CursorShard { partition_expr: Some(expr), seq: 10, + until: None, }, CursorShard { partition_expr: None, seq: 15, + until: None, }, ], ), @@ -821,6 +825,7 @@ mod tests { vec![CursorShard { partition_expr: None, seq: 20, + until: None, }], ), ])) diff --git a/src/store-api/src/storage/requests.rs b/src/store-api/src/storage/requests.rs index 0f48a797ee3..b483a558185 100644 --- a/src/store-api/src/storage/requests.rs +++ b/src/store-api/src/storage/requests.rs @@ -47,21 +47,37 @@ pub enum TimeSeriesDistribution { } /// One slice of an incremental cursor: the partition expression selecting a region's value -/// domain together with the last sequence consumed inside it. +/// domain together with the last sequence consumed inside it, and — when the producer can +/// state it — the last sequence that delta covers. +/// +/// The pair bounds the rows one round owes on the slice: `seq < number <= until`. The upper +/// end matters to a read of a file **another** region created, because such a read compares a +/// row's number against the creator's domain: 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. + /// 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` — also what a payload that states no bound means — 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, } 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, } } @@ -70,6 +86,13 @@ impl CursorShard { pub fn whole_domain(seq: SequenceNumber) -> Self { Self::new(None, seq) } + + /// Returns this slice with `until` as its inclusive upper bound + /// ([`Self::until`]). + pub fn with_until(mut self, until: SequenceNumber) -> Self { + self.until = Some(until); + self + } } #[derive(Default, Clone, Debug, PartialEq)] @@ -124,8 +147,9 @@ pub struct ScanRequest { 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. The least - /// advanced slice is the file-level bound; each row is compared against the slice that - /// selects it. + /// advanced slice is the file-level lower bound, the least upper bound any slice states is + /// its file-level upper bound ([`CursorShard::until`]); each row is compared against the + /// slice that selects it. /// /// Empty or absent means no cursor of the creator's domain is known, and an adopted file /// then **fails closed** with `SequenceRangeUnsupported`.