diff --git a/src/common/recordbatch/src/adapter.rs b/src/common/recordbatch/src/adapter.rs index c18d1e4b8f3..3fca666d06d 100644 --- a/src/common/recordbatch/src/adapter.rs +++ b/src/common/recordbatch/src/adapter.rs @@ -705,83 +705,220 @@ pub struct RecordBatchMetrics { /// omitted when empty. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub substituted_row_ranges: Vec, -} - -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] -pub struct RegionWatermarkEntry { - pub region_id: u64, + /// The `(region, partition expression)` pairs this round's scans actually read, so the + /// owner of a `(region, slice)` cursor advances only the slices that were read. + /// Deduplicated and sorted, omitted when empty. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub observed_slices: Vec, + /// The creator regions of the files this round's scans **delivered rows** from, where the + /// file was created by a region other than the one that read it (an adopted file). + /// + /// A region that reads such a file compares the file's own row numbers against the + /// creator's cursor, so a row above the creator's proved watermark can reach the result + /// while the caller cannot tell it apart from a row of the holder. This field is that + /// evidence. + /// + /// `Some(creators)` — possibly empty — is an affirmative answer, sorted and + /// deduplicated: the scans this answer covers delivered rows of files created by exactly + /// these regions. `Some(vec![])` therefore says "delivered none". `None` (also: the + /// field's absence in a payload an earlier build wrote) states **nothing**, and is not + /// the same as `Some(vec![])`: a consumer that must not count a row above its creator's + /// proved watermark has to read an unknown answer as "could have delivered adopted rows". + /// + /// Delivered means the rows survived the reading region's own row filters and entered + /// its output. A later stage of the same query (merge, dedup, projection, an outer + /// predicate) may still drop them, so the claim is a deliberate over-approximation: it + /// never answers "none" for rows that were handed on, and it may name a creator whose + /// rows the query finally discarded. #[serde(default, skip_serializing_if = "Option::is_none")] - pub watermark: Option, + pub foreign_file_row_creators: Option>, } -/// The terminal substituted-range answers of one region scan's partition streams. +/// What one region scan's partition streams stated when they ended, i.e. what a plan node that +/// reads a region on several partitions of DataFusion parallelism can answer about its own read. /// -/// Each partition's stream states, when it ends, which time ranges it substituted. A plan node -/// that reads a region on several partitions of DataFusion parallelism reports through this -/// structure, so the ranges of every partition it ran reach the caller instead of only those of -/// the stream the node happens to hand out last. +/// Each partition's stream states three facts when it ends, and this node keeps them because +/// DataFusion's own metrics keep figures only: the other regions' files it delivered rows from +/// ([`RecordBatchMetrics::foreign_file_row_creators`]), the time ranges of the rows it +/// substituted ([`RecordBatchMetrics::substituted_row_ranges`]) and the +/// `(region, partition expression)` slices it read ([`RecordBatchMetrics::observed_slices`]). +/// A [`crate::RecordBatchStreamAdapter`] rebuilt from a plan's figures states none of them, so a +/// plan-level collector reads them here instead. +/// +/// The three facts merge like the read they describe. The node states a creator answer only +/// when every partition it planned to run ended and stated one: a partition that is still +/// running, that never ran, or that ended without an answer leaves that answer unknown, +/// because the partitions that did answer cover only part of the read. The substituted ranges +/// and the observed slices of every partition union instead: a range or slice two partitions +/// both name is one range or slice, because it states what was substituted or read, not how +/// often, and a partition that substituted or read nothing adds nothing. #[derive(Debug, Default)] -pub struct SubstitutedRowRangesReports { - state: Mutex, +pub struct TerminalScanReports { + state: Mutex, } #[derive(Debug, Default)] -struct SubstitutedRowRangesReportsState { - /// The ranges each partition reported, keyed by partition. - reported: BTreeMap>, +struct TerminalScanReportsState { + /// The partitions whose stream ended and stated an answer. + reported: BTreeSet, + /// The creator regions those partitions named. + creators: BTreeSet, + /// The row timestamp ranges those partitions substituted, per region. + substituted: BTreeMap>, + /// The `(region, partition expression)` pairs those partitions read. + observed: BTreeSet, + /// A partition ended without stating an answer, so no set of partitions can answer for + /// the node. + unknown: bool, + /// How many partitions the reporting node has, as last reported. + partitions: usize, } -impl SubstitutedRowRangesReports { +impl TerminalScanReports { pub fn new() -> Self { Self::default() } - /// Records the ranges `partition` reported when its stream ended. - pub fn record(&self, partition: usize, ranges: Vec) { - if ranges.is_empty() { + /// Records what the stream of `partition` stated when it ended, `partitions` being how many + /// partitions the node runs, and `answer` the stream's terminal metrics. + /// + /// The count travels with the answer rather than with the node: a node whose partition + /// ranges are re-assigned before it runs reports the count it actually ran with, and a + /// report left by an earlier assignment only ever widens the answer, never narrows it. + /// + /// A stream that states no metrics at all states no answer: the node's creator answer stays + /// unknown and it adds no range or slice, because a read that stated nothing must not be + /// read as a read that substituted and observed nothing. + pub fn record(&self, partition: usize, partitions: usize, answer: Option<&RecordBatchMetrics>) { + let mut state = self.lock(); + state.partitions = partitions; + let Some(answer) = answer else { + state.unknown = true; return; + }; + state.reported.insert(partition); + // Of the three facts only the creator answer can be unknown on its own: the other two + // state "nothing" by being empty. + match &answer.foreign_file_row_creators { + Some(creators) => state.creators.extend(creators.iter().copied()), + None => state.unknown = true, } - self.lock().reported.insert(partition, ranges); + for entry in &answer.substituted_row_ranges { + state + .substituted + .entry(entry.region_id) + .or_default() + .extend( + entry + .ranges + .iter() + .map(|range| (range.start_millis, range.end_millis)), + ); + } + state + .observed + .extend(answer.observed_slices.iter().cloned()); } - /// Returns the ranges every reporting partition substituted, merged per region and sorted. - /// - /// Ranges are claims about rows that were read, so the answer is the union: a partition that - /// reported nothing substitutes nothing, and it cannot make another partition's claim vanish. - pub fn ranges(&self) -> Vec { + /// The creators every partition reported together, or `None` when the partitions do not + /// state such an answer (yet). + pub fn foreign_file_row_creators(&self) -> Option> { let state = self.lock(); - let mut merged = BTreeMap::>::new(); - for entry in state.reported.values().flatten() { - let ranges = merged.entry(entry.region_id).or_default(); - ranges.extend( - entry - .ranges - .iter() - .map(|range| (range.start_millis, range.end_millis)), - ); + // A node with no partition to report from answers nothing: nothing was read, so + // "delivered none" would be a claim about a read that never happened. + if state.unknown || state.partitions == 0 || state.reported.len() != state.partitions { + return None; } - merged - .into_iter() - .map(|(region_id, ranges)| SubstitutedRowRanges { - region_id, - ranges: ranges - .into_iter() - .map(|(start_millis, end_millis)| SubstitutedRange { - start_millis, - end_millis, - }) - .collect(), - }) - .collect() + Some(state.creators.iter().copied().collect()) + } + + /// The time ranges of the rows the partitions substituted, per region, or `None` when no + /// partition stated an answer (yet). + /// + /// Ranges are unioned per region, so a row substituted by two partitions is reported once. + /// An answer of `Some(vec![])` says the read substituted nothing, which is what a caller + /// that recomputes the windows of substituted rows needs to tell apart from a read that has + /// not finished. A range a partition stated is reported even when another partition ended + /// without stating anything: the known windows still have to be recomputed, and dropping + /// them would read as "substituted nothing" for rows that were substituted. + pub fn substituted_row_ranges(&self) -> Option> { + let state = self.lock(); + if state.reported.is_empty() { + return None; + } + Some( + state + .substituted + .iter() + .map(|(region_id, ranges)| SubstitutedRowRanges { + region_id: *region_id, + ranges: ranges + .iter() + .map(|(start_millis, end_millis)| SubstitutedRange { + start_millis: *start_millis, + end_millis: *end_millis, + }) + .collect(), + }) + .collect(), + ) + } + + /// The `(region, partition expression)` pairs the partitions read, or `None` when no + /// partition stated an answer (yet). + /// + /// Deduplicated and sorted: a slice two partitions both read is one slice, and a slice a + /// partition stated is reported even when another partition ended without stating one. + pub fn observed_slices(&self) -> Option> { + let state = self.lock(); + if state.reported.is_empty() { + return None; + } + Some(state.observed.iter().cloned().collect()) + } + + /// Clears every fact an earlier run stated, so a reused plan cannot report what the run + /// before it read. + pub fn reset(&self) { + *self.lock() = TerminalScanReportsState::default(); } /// A panic while the state is held cannot leave it inconsistent (an insert is the only /// mutation), so a poisoned lock is recovered instead of failing the caller. - fn lock(&self) -> std::sync::MutexGuard<'_, SubstitutedRowRangesReportsState> { + fn lock(&self) -> std::sync::MutexGuard<'_, TerminalScanReportsState> { self.state.lock().unwrap_or_else(|e| e.into_inner()) } } +/// The partition expression of one region that a scan read rows of, i.e. one +/// `(region, partition expression)` pair. +/// +/// `region_id` is the region that allocated the rows' sequences — the creator of the file they +/// were read from, this region itself for a file it wrote. `partition_expr` is the identity of +/// the expression that file states for its own rows (`PartitionExpr::as_json_str()`); `None` +/// means the file states none and covers its region's complete value domain. +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct ObservedPartitionExpr { + pub region_id: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub partition_expr: Option, +} + +impl ObservedPartitionExpr { + pub fn new(region_id: u64, partition_expr: Option) -> Self { + Self { + region_id, + partition_expr, + } + } + + /// The pair covering `region_id`'s complete value domain, which is what a read of a + /// file that states no expression observed. + pub fn whole_domain(region_id: u64) -> Self { + Self::new(region_id, None) + } +} + /// The time ranges a scan substituted for one region. #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct SubstitutedRowRanges { @@ -800,6 +937,34 @@ pub struct SubstitutedRange { pub end_millis: i64, } +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct RegionWatermarkEntry { + pub region_id: u64, + /// Identity (`PartitionExpr::as_json_str()`) of the partition expression this entry speaks + /// about, or `None` when it speaks about the region's complete value domain. A slice is + /// merged under its own key, never with the region's whole-domain entry. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub partition_expr: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub watermark: Option, + /// One sentence: **the creators of the files the region had visible when this read opened + /// it**, i.e. the regions whose rows its own file list may hold, read from the same version + /// snapshot as `partition_expr` and `watermark` and independent of what the read pruned. + /// + /// The region itself is never listed: a file it wrote is its own rows, and a consumer that + /// enumerates candidates adds the region on its own. Sorted, deduplicated. + /// + /// - `Some(creators)` — possibly empty — states the set: `Some(vec![])` says every visible + /// file was created by the region itself, which is a positive "nothing foreign" answer. + /// - `None` (also: the field's absence in a payload an earlier build wrote) states **nothing** + /// about the file list, and must be read as "unknown", not as "empty". + /// + /// This is not [`RecordBatchMetrics::foreign_file_row_creators`]: that answers which creators + /// the read *delivered rows* of, this answers which creators were *visible* before it started. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub visible_foreign_file_creators: Option>, +} + /// Determines if a metric name represents a time measurement that should be formatted. pub fn is_time_metric(metric_name: &str) -> bool { metric_name.contains("elapsed") || metric_name.contains("time") || metric_name.contains("cost") @@ -1921,6 +2086,202 @@ mod test { assert_eq!(metrics.memory_usage, 34); } + /// The field an earlier build's payload does not carry decodes to `None` — the absence of + /// an answer — and never to "delivered none". The two must not be confusable: one is a + /// claim about what the read delivered, the other says nothing. + #[test] + fn test_recordbatch_metrics_deserializes_without_foreign_file_row_creators() { + let metrics: RecordBatchMetrics = serde_json::from_value(json!({ + "elapsed_compute": 12, + "memory_usage": 34, + "plan_metrics": [], + "region_watermarks": [{"region_id": 1, "watermark": 7}] + })) + .unwrap(); + + assert_eq!(None, metrics.foreign_file_row_creators); + } + + /// The partitions of a region scan answer together: their reports union, and a partition + /// that did not state an answer keeps the node's answer unknown. + #[test] + fn test_terminal_scan_reports_answer_for_all_partitions() { + // The terminal metrics one partition states when its stream ends. + fn stated(creators: Option>) -> RecordBatchMetrics { + RecordBatchMetrics { + foreign_file_row_creators: creators, + ..Default::default() + } + } + + let reports = TerminalScanReports::new(); + assert_eq!( + None, + reports.foreign_file_row_creators(), + "no partition reported yet" + ); + + reports.record(0, 2, Some(&stated(Some(vec![7, 9])))); + assert_eq!( + None, + reports.foreign_file_row_creators(), + "one partition answered and another has not" + ); + + reports.record(1, 2, Some(&stated(Some(vec![9])))); + assert_eq!( + Some(vec![7, 9]), + reports.foreign_file_row_creators(), + "the delivered creators are the union of what the partitions reported" + ); + + // A partition that ended without an answer covers part of the read, so no set of + // reported partitions can answer for the node. + let reports = TerminalScanReports::new(); + reports.record(0, 2, Some(&stated(Some(vec![7])))); + reports.record(1, 2, None); + assert_eq!(None, reports.foreign_file_row_creators()); + + // An answer of "delivered none" from every partition is still an answer. + let reports = TerminalScanReports::new(); + reports.record(0, 1, Some(&stated(Some(vec![])))); + assert_eq!(Some(vec![]), reports.foreign_file_row_creators()); + } + + /// The substituted ranges and the observed slices union across partitions, and a reset + /// leaves nothing a later run could mistake for its own read. + #[test] + fn test_terminal_scan_reports_merge_ranges_and_slices_and_reset() { + let reports = TerminalScanReports::new(); + assert_eq!(None, reports.substituted_row_ranges()); + assert_eq!(None, reports.observed_slices()); + + let first = RecordBatchMetrics { + foreign_file_row_creators: Some(vec![]), + substituted_row_ranges: vec![SubstitutedRowRanges { + region_id: 7, + ranges: vec![SubstitutedRange { + start_millis: 10, + end_millis: 20, + }], + }], + observed_slices: vec![ObservedPartitionExpr::whole_domain(7)], + ..Default::default() + }; + let second = RecordBatchMetrics { + foreign_file_row_creators: Some(vec![]), + substituted_row_ranges: vec![ + // The same range one more partition substituted is one range. + SubstitutedRowRanges { + region_id: 7, + ranges: vec![SubstitutedRange { + start_millis: 10, + end_millis: 20, + }], + }, + SubstitutedRowRanges { + region_id: 8, + ranges: vec![SubstitutedRange { + start_millis: 30, + end_millis: 40, + }], + }, + ], + observed_slices: vec![ + ObservedPartitionExpr::whole_domain(7), + ObservedPartitionExpr::new(8, Some("k0 < 10".to_string())), + ], + ..Default::default() + }; + + reports.record(0, 2, Some(&first)); + reports.record(1, 2, Some(&second)); + + assert_eq!( + Some(vec![ + SubstitutedRowRanges { + region_id: 7, + ranges: vec![SubstitutedRange { + start_millis: 10, + end_millis: 20, + }], + }, + SubstitutedRowRanges { + region_id: 8, + ranges: vec![SubstitutedRange { + start_millis: 30, + end_millis: 40, + }], + }, + ]), + reports.substituted_row_ranges() + ); + assert_eq!( + Some(vec![ + ObservedPartitionExpr::whole_domain(7), + ObservedPartitionExpr::new(8, Some("k0 < 10".to_string())), + ]), + reports.observed_slices() + ); + + reports.reset(); + assert_eq!(None, reports.foreign_file_row_creators()); + assert_eq!(None, reports.substituted_row_ranges()); + assert_eq!(None, reports.observed_slices()); + + // A partition that states ranges without a creator answer still states its ranges: only + // the creator answer becomes unknown, because only it has an "unknown" of its own. + let ranges_only = RecordBatchMetrics { + substituted_row_ranges: first.substituted_row_ranges.clone(), + ..Default::default() + }; + let reports = TerminalScanReports::new(); + reports.record(0, 1, Some(&ranges_only)); + assert_eq!( + Some(vec![SubstitutedRowRanges { + region_id: 7, + ranges: vec![SubstitutedRange { + start_millis: 10, + end_millis: 20, + }], + }]), + reports.substituted_row_ranges() + ); + assert_eq!( + None, + reports.foreign_file_row_creators(), + "no creator answer was stated, so that one is unknown" + ); + } + + /// An affirmative answer of "delivered none" is written as an empty array and read back as + /// exactly that, distinct from an omitted field. + #[test] + fn test_recordbatch_metrics_foreign_file_row_creators_serde_roundtrip() { + let none_delivered = RecordBatchMetrics { + foreign_file_row_creators: Some(Vec::new()), + ..Default::default() + }; + let value = serde_json::to_value(&none_delivered).unwrap(); + assert_eq!(Some(&json!([])), value.get("foreign_file_row_creators")); + let decoded: RecordBatchMetrics = serde_json::from_value(value).unwrap(); + assert_eq!(Some(Vec::new()), decoded.foreign_file_row_creators); + + let delivered = RecordBatchMetrics { + foreign_file_row_creators: Some(vec![7, 9]), + ..Default::default() + }; + let value = serde_json::to_value(&delivered).unwrap(); + assert_eq!(Some(&json!([7, 9])), value.get("foreign_file_row_creators")); + let decoded: RecordBatchMetrics = serde_json::from_value(value).unwrap(); + assert_eq!(Some(vec![7, 9]), decoded.foreign_file_row_creators); + + // Unknown is not serialized at all: an answer is either stated or absent. + let unknown = RecordBatchMetrics::default(); + let value = serde_json::to_value(&unknown).unwrap(); + assert!(value.get("foreign_file_row_creators").is_none()); + } + #[test] fn test_plan_metrics_deserializes_without_plan_name() { let metrics: RecordBatchMetrics = serde_json::from_value(json!({ @@ -1943,11 +2304,15 @@ mod test { region_watermarks: vec![ RegionWatermarkEntry { region_id: 1, + partition_expr: None, watermark: Some(100), + visible_foreign_file_creators: None, }, RegionWatermarkEntry { region_id: 2, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }, ], ..Default::default() @@ -2073,4 +2438,93 @@ mod test { let value = serde_json::to_value(RecordBatchMetrics::default()).unwrap(); assert!(value.get("region_watermarks").is_none()); } + + #[test] + fn test_region_watermark_entry_states_its_partition_expression() { + let metrics = RecordBatchMetrics { + region_watermarks: vec![RegionWatermarkEntry { + region_id: 1, + partition_expr: Some(r#"{"lhs":...}"#.to_string()), + watermark: Some(100), + visible_foreign_file_creators: None, + }], + ..Default::default() + }; + + let value = serde_json::to_value(&metrics).unwrap(); + assert_eq!( + value.get("region_watermarks").unwrap(), + &json!([ + { + "region_id": 1, + "partition_expr": r#"{"lhs":...}"#, + "watermark": 100 + } + ]) + ); + + // A statement written before the expression field existed is a region-keyed + // statement, i.e. one about the region's complete value domain. + let mut legacy = serde_json::to_value(RecordBatchMetrics::default()).unwrap(); + legacy["region_watermarks"] = json!([{ "region_id": 3 }]); + let decoded: RecordBatchMetrics = serde_json::from_value(legacy).unwrap(); + assert_eq!( + decoded.region_watermarks, + vec![RegionWatermarkEntry { + region_id: 3, + partition_expr: None, + watermark: None, + visible_foreign_file_creators: None, + }] + ); + } + + #[test] + fn test_region_watermark_entry_states_visible_file_creators_on_the_wire() { + let metrics = RecordBatchMetrics { + region_watermarks: vec![ + RegionWatermarkEntry { + region_id: 1, + partition_expr: None, + watermark: Some(10), + visible_foreign_file_creators: Some(vec![7, 9]), + }, + // "Nothing foreign visible" is a positive answer and travels as an empty list. + RegionWatermarkEntry { + region_id: 2, + partition_expr: None, + watermark: Some(20), + visible_foreign_file_creators: Some(Vec::new()), + }, + ], + ..Default::default() + }; + + let value = serde_json::to_value(&metrics).unwrap(); + assert_eq!( + value.get("region_watermarks").unwrap(), + &json!([ + { "region_id": 1, "watermark": 10, "visible_foreign_file_creators": [7, 9] }, + { "region_id": 2, "watermark": 20, "visible_foreign_file_creators": [] } + ]) + ); + + let decoded: RecordBatchMetrics = serde_json::from_value(value).unwrap(); + assert_eq!(decoded.region_watermarks, metrics.region_watermarks); + + // A statement written before the field existed states nothing about the region's files, + // which reads back as unknown - never as "holds no foreign file". + let mut legacy = serde_json::to_value(RecordBatchMetrics::default()).unwrap(); + legacy["region_watermarks"] = json!([{ "region_id": 3, "watermark": 5 }]); + let decoded: RecordBatchMetrics = serde_json::from_value(legacy).unwrap(); + assert_eq!( + decoded.region_watermarks, + vec![RegionWatermarkEntry { + region_id: 3, + partition_expr: None, + watermark: Some(5), + visible_foreign_file_creators: None, + }] + ); + } } diff --git a/src/query/src/dummy_catalog.rs b/src/query/src/dummy_catalog.rs index 59a86c44972..3b1deee4f3e 100644 --- a/src/query/src/dummy_catalog.rs +++ b/src/query/src/dummy_catalog.rs @@ -15,7 +15,7 @@ //! Dummy catalog for region server. use std::any::Any; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::fmt; use std::sync::{Arc, Mutex}; @@ -38,14 +38,16 @@ use session::context::{QueryContext, QueryContextRef}; use snafu::ResultExt; use store_api::metadata::RegionMetadataRef; use store_api::region_engine::RegionEngineRef; -use store_api::storage::{RegionId, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector}; +use store_api::storage::{ + CursorShard, RegionId, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector, +}; use table::TableRef; use table::metadata::{TableId, TableInfoRef}; use table::table::adapter::{dictionary_encode_string_columns, supports_pk_dictionary_encoding}; use table::table::scan::RegionScanExec; use crate::error::{GetRegionMetadataSnafu, Result}; -use crate::options::{FlowIncrementalMode, FlowQueryExtensions}; +use crate::options::{FlowIncrementalMode, FlowQueryExtensions, FlowRepairMode}; /// Resolve to the given region (specified by [RegionId]) unconditionally. #[derive(Clone, Debug)] @@ -194,6 +196,20 @@ impl TableProvider for DummyTableProvider { .map_err(|e| DataFusionError::External(Box::new(e)))?; } + // Bind what the region's scan stated about the snapshot it reads under: the partition + // expression it covers and the creators of the files it had visible. The engine states all + // of it from one version snapshot, so the expression a region read reports, the watermark + // it reports and the file list it started from describe the same instant: a scan that + // inherited a caller-fenced bound still states what it actually read under. + if let Some(query_ctx) = &self.query_ctx + && let Some(identity) = scanner.snapshot_identity() + { + query_ctx.bind_scan_partition_expr(self.region_id.as_u64(), identity.partition_expr); + if let Some(creators) = identity.visible_foreign_file_creators { + query_ctx.bind_scan_visible_file_creators(self.region_id.as_u64(), creators); + } + } + let query_memory_tracker = self.engine.query_memory_tracker(); let mut scan_exec = RegionScanExec::new(scanner, request, query_memory_tracker)?; if let Some(query_ctx) = &self.query_ctx { @@ -365,11 +381,17 @@ struct FlowScanDecision { skip_sst_files: bool, /// Whether this source scan must enforce the exact sequence range. exact_sequence_range: bool, + /// Whether the read may cross an invalid boundary: it prunes at file granularity + /// and forces the file barrier as each row's sequence. + read_across_invalid_boundary: bool, /// Whether the scan reads physical row sequences and hides the rows a substitution /// produced, reporting the windows they occupy. Only the incremental delta asks for /// it: it is the read that must split an adopted file into consumed and unconsumed /// rows instead of trusting the handle's barrier. read_row_sequence: bool, + /// The cursor slices of every creator region, used to filter the rows of a file this + /// region adopted from another one. Only a physical-sequence read carries them. + creator_cursor_shards: Option>>>, } impl FlowScanDecision { @@ -381,7 +403,9 @@ impl FlowScanDecision { memtable_max_sequence: None, skip_sst_files: false, exact_sequence_range: false, + read_across_invalid_boundary: false, read_row_sequence: false, + creator_cursor_shards: None, } } } @@ -397,7 +421,9 @@ fn decide_flow_scan(query_ctx: &QueryContext, region_id: RegionId) -> Result Result Result= lo AND k0 < hi`, in the form + /// the cursor wire form carries it. + fn test_slice_expr(lo: u64, hi: u64) -> String { + use datatypes::value::Value; + use partition::expr::{Operand, col as partition_col}; + + partition_col("k0") + .gt_eq(Operand::Value(Value::UInt64(lo))) + .and(partition_col("k0").lt(Operand::Value(Value::UInt64(hi)))) + .as_json_str() + .unwrap() + } + #[test] fn test_scan_request_from_query_context_uses_snapshot_bound_intent() { let region_id = test_region_id(); @@ -847,6 +899,131 @@ mod tests { assert!(!request.skip_sst_files); } + /// The expression-keyed cursor an incremental delta carries: the holder's own rows + /// start after the least advanced of its expressions, and every creator's expressions + /// travel with the scan, because a physical read of an adopted file is filtered by the + /// expression the file belongs to. + #[test] + fn test_scan_request_from_slice_cursors_keeps_creator_slices() { + let region_id = test_region_id(); + let creator = RegionId::new(1024, 7); + let narrow = test_slice_expr(0, 50); + let wide = test_slice_expr(50, 100); + let query_ctx = QueryContextBuilder::default() + .extensions(HashMap::from([ + ( + FLOW_INCREMENTAL_MODE.to_string(), + FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(), + ), + (FLOW_READ_ROW_SEQUENCE.to_string(), "true".to_string()), + ( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + encode_incremental_after_seqs(&BTreeMap::from([ + ( + region_id.as_u64(), + vec![ + CursorShard::new(Some(narrow.clone()), 10), + CursorShard::new(Some(wide.clone()), 3), + ], + ), + ( + creator.as_u64(), + vec![CursorShard::new(Some(wide.clone()), 3)], + ), + ])) + .unwrap(), + ), + ])) + .build(); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(request.exact_sequence_range); + assert!(request.read_row_sequence); + assert_eq!( + request.memtable_min_sequence, + Some(3), + "a region-level bound starts after the least advanced slice of the region" + ); + assert_eq!( + Some(Arc::new(BTreeMap::from([ + ( + region_id.as_u64(), + vec![ + CursorShard::new(Some(narrow), 10), + CursorShard::new(Some(wide.clone()), 3) + ] + ), + (creator.as_u64(), vec![CursorShard::new(Some(wide), 3)]), + ]))), + request.creator_cursor_shards + ); + } + + /// The region-keyed form is the same statement as one whole-domain slice per region, + /// which is what keeps a producer of the older shape working. + #[test] + fn test_scan_request_from_region_cursors_is_the_full_slice() { + let region_id = test_region_id(); + let creator = RegionId::new(1024, 7); + let query_ctx = QueryContextBuilder::default() + .extensions(HashMap::from([ + ( + FLOW_INCREMENTAL_MODE.to_string(), + FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(), + ), + (FLOW_READ_ROW_SEQUENCE.to_string(), "true".to_string()), + ( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + format!( + r#"{{"{}":10,"{}":3}}"#, + region_id.as_u64(), + creator.as_u64() + ), + ), + ])) + .build(); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert_eq!(request.memtable_min_sequence, Some(10)); + assert_eq!( + Some(Arc::new(BTreeMap::from([ + (region_id.as_u64(), vec![CursorShard::whole_domain(10)]), + (creator.as_u64(), vec![CursorShard::whole_domain(3)]), + ]))), + request.creator_cursor_shards + ); + } + + /// A read that does not split adopted files by their physical sequences carries no + /// creator cursors: no other read compares a number against a foreign domain. + #[test] + fn test_scan_request_without_physical_sequence_read_carries_no_creator_cursors() { + let region_id = test_region_id(); + let query_ctx = QueryContextBuilder::default() + .extensions(HashMap::from([ + ( + FLOW_INCREMENTAL_MODE.to_string(), + FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(), + ), + ( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + encode_incremental_after_seqs(&BTreeMap::from([( + region_id.as_u64(), + vec![CursorShard::new(Some(test_slice_expr(0, 50)), 10)], + )])) + .unwrap(), + ), + ])) + .build(); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(!request.read_row_sequence); + assert_eq!(None, request.creator_cursor_shards); + } + #[test] fn test_scan_request_from_query_context_keeps_snapshot_fields() { let region_id = test_region_id(); diff --git a/src/query/src/metrics.rs b/src/query/src/metrics.rs index 24e64cad2da..9f28a26ee83 100644 --- a/src/query/src/metrics.rs +++ b/src/query/src/metrics.rs @@ -18,7 +18,8 @@ use std::sync::Arc; use std::task::{Context, Poll}; use common_recordbatch::adapter::{ - RecordBatchMetrics, RegionWatermarkEntry, SubstitutedRange, SubstitutedRowRanges, + ObservedPartitionExpr, RecordBatchMetrics, RegionWatermarkEntry, SubstitutedRange, + SubstitutedRowRanges, }; use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream}; use common_telemetry::warn; @@ -30,24 +31,33 @@ use lazy_static::lazy_static; use prometheus::*; use session::context::QueryContextRef; -use table::table::scan::RegionScanExec; +use table::table::scan::{RegionScanExec, SeriesScanExec}; use crate::dist_plan::MergeScanExec; use crate::error::Result; use crate::options::FlowQueryExtensions; -/// Intermediate merge state for one participating region while collecting -/// terminal correctness watermarks across merge-scan sub-stages. +/// The key one terminal watermark statement is merged under: the region that +/// allocated the sequences plus the identity of the partition expression the +/// statement is about (`None` for the region's complete value domain). +/// +/// Two statements about the same region but different expressions are statements +/// about different value domains: a round that read one slice of a region says +/// nothing about the other slices, so they must not be merged into one entry. +type WatermarkKey = (u64, Option); + +/// Intermediate merge state for one participating `(region, expression)` while +/// collecting terminal correctness watermarks across merge-scan sub-stages. enum MergeState { - /// At least one branch reported that this region cannot prove a safe + /// At least one branch reported that this key cannot prove a safe /// checkpoint watermark for the current query round. Unproved, - /// All seen branches agree the region can advance safely to this sequence. + /// All seen branches agree the domain can advance safely to this sequence. Proved(u64), - /// Different proved sequences were reported for the same region. The final + /// Different proved sequences were reported for the same key. The final /// result is degraded to `None`, and the collected values are logged. Conflict { - /// Distinct proved watermark candidates reported for the region. + /// Distinct proved watermark candidates reported for the key. watermarks: Vec, }, } @@ -216,11 +226,21 @@ impl RecordBatchStream for RegionWatermarkMetricsStream { if !region_watermarks.is_empty() { metrics.region_watermarks = region_watermarks; } - // A region scan reports the rows it substituted (files whose sequences a substitution - // produced) through its own stream metrics, which a merge-scan sub-stage keeps per - // region. Both sources are joined here so the caller sees one range set per region. - metrics.substituted_row_ranges = - collect_substituted_row_ranges(self.plan.clone(), &metrics); + // A region scan reports the rows it substituted (adopted files whose sequences a + // substitution produced) through its own stream metrics, which a merge-scan + // sub-stage keeps per region. Both sources are joined here so the caller sees one + // range set per region. + let substituted_row_ranges = collect_substituted_row_ranges(self.plan.clone(), &metrics); + metrics.substituted_row_ranges = substituted_row_ranges; + // Which `(region, partition expression)` pairs the regions actually read travel with + // the same result: the owner of a `(region, slice)` cursor splits and advances its + // entries by exactly what this round observed. + metrics.observed_slices = collect_observed_slices(self.plan.clone(), &metrics); + // Which other regions' files the regions delivered rows from. A caller that must not + // count a row above its creator's proved watermark cannot recover this from the + // watermarks: they say what was proved, not what was read. + metrics.foreign_file_row_creators = + collect_foreign_file_row_creators(self.plan.clone(), &metrics); Some(metrics) } } @@ -263,13 +283,21 @@ pub fn terminal_recordbatch_metrics_from_plan( ) -> Option { let region_watermarks = collect_region_watermarks(plan.clone()); let own = RecordBatchMetrics::default(); - let substituted_row_ranges = collect_substituted_row_ranges(plan, &own); - if region_watermarks.is_empty() && substituted_row_ranges.is_empty() { + let substituted_row_ranges = collect_substituted_row_ranges(plan.clone(), &own); + let observed_slices = collect_observed_slices(plan.clone(), &own); + let foreign_file_row_creators = collect_foreign_file_row_creators(plan.clone(), &own); + if region_watermarks.is_empty() + && substituted_row_ranges.is_empty() + && observed_slices.is_empty() + && foreign_file_row_creators.is_none() + { None } else { Some(RecordBatchMetrics { region_watermarks, substituted_row_ranges, + observed_slices, + foreign_file_row_creators, ..Default::default() }) } @@ -287,12 +315,50 @@ pub fn terminal_recordbatch_metrics_from_plan_if_requested( } } +/// Collects the proved terminal watermarks of `plan`, one entry per +/// `(region, partition expression)` the plan's scans stated. +fn collect_region_watermarks(plan: Arc) -> Vec { + let mut merged = BTreeMap::::new(); + let mut stack = vec![plan]; + + while let Some(plan) = stack.pop() { + if let Some(merge_scan) = plan.downcast_ref::() + && !merge_scan.is_flow_sink_scan() + { + merge_merge_scan_region_watermarks( + &mut merged, + merge_scan + .regions() + .iter() + .map(|region_id| region_id.as_u64()), + merge_scan.sub_stage_metrics(), + ); + } + stack.extend(plan.children().into_iter().cloned()); + } + + finalize_region_watermarks(merged) +} + +/// The region scan a plan node reads a region through: the node itself, or the native +/// raw-series leaf that packs one and reads through it. +/// +/// Such a scan states what it read through its own report rather than through its stream, so +/// every collector of those facts has to find it the same way. +fn region_scan_of(plan: &Arc) -> Option<&RegionScanExec> { + if let Some(region_scan) = plan.downcast_ref::() { + return Some(region_scan); + } + plan.downcast_ref::() + .map(SeriesScanExec::region_scan) +} + /// Collects the time ranges of the rows the plan's region scans substituted. /// -/// `own` carries the ranges of the stream that already reported them, every merge-scan -/// sub-stage contributes the ranges of its own regions, and a region scan that ran in this -/// process contributes what its partition streams stated when they ended. Ranges are unioned -/// per region, so a row substituted by two branches is reported once. +/// `own` carries the ranges of the stream that already reported them, a local region scan +/// contributes what its partition streams stated when they ended, and every merge-scan +/// sub-stage contributes the ranges of its own regions. Ranges are unioned per region, so a row +/// substituted by two branches is reported once. fn collect_substituted_row_ranges( plan: Arc, own: &RecordBatchMetrics, @@ -313,11 +379,14 @@ fn collect_substituted_row_ranges( let mut stack = vec![plan]; while let Some(plan) = stack.pop() { - // A region scan keeps the ranges its partition streams stated when they ended, which - // is the only source of them once the stream of a plan that ran in this process is - // rebuilt from the plan's figures. - if let Some(region_scan) = plan.downcast_ref::() { - merge(region_scan.substituted_row_ranges()); + // A scan that ran in this process keeps the ranges its partition streams stated when + // they ended. Its stream cannot carry them here: a `RecordBatchMetrics` rebuilt from a + // plan's figures holds numbers, so a range list that crossed that boundary would read + // as "substituted nothing". + if let Some(region_scan) = region_scan_of(&plan) + && let Some(ranges) = region_scan.substituted_row_ranges() + { + merge(ranges); } if let Some(merge_scan) = plan.downcast_ref::() && !merge_scan.is_flow_sink_scan() @@ -344,30 +413,173 @@ fn collect_substituted_row_ranges( .collect() } -fn collect_region_watermarks(plan: Arc) -> Vec { - let mut merged = BTreeMap::::new(); - let mut stack = vec![plan]; +/// Collects the `(region, partition expression)` pairs the plan's region scans read. +/// +/// `own` carries the slices of the stream that already reported them, a local region scan +/// contributes what its partition streams stated when they ended, and every merge-scan +/// sub-stage contributes the slices of its own regions. A slice reported by two branches is one +/// slice, because it states what was read, not how often. +fn collect_observed_slices( + plan: Arc, + own: &RecordBatchMetrics, +) -> Vec { + let mut merged = BTreeSet::new(); + merged.extend(own.observed_slices.iter().cloned()); + let mut stack = vec![plan]; while let Some(plan) = stack.pop() { + // Same as the substituted ranges: the slices a scan observed are a statement about its + // read, not a figure, so they are read from the scan rather than from its stream. + if let Some(region_scan) = region_scan_of(&plan) + && let Some(slices) = region_scan.observed_slices() + { + merged.extend(slices); + } if let Some(merge_scan) = plan.downcast_ref::() && !merge_scan.is_flow_sink_scan() { - merge_merge_scan_region_watermarks( - &mut merged, - merge_scan - .regions() - .iter() - .map(|region_id| region_id.as_u64()), - merge_scan.sub_stage_metrics(), - ); + for metrics in merge_scan.sub_stage_metrics() { + merged.extend(metrics.observed_slices); + } } stack.extend(plan.children().into_iter().cloned()); } - finalize_region_watermarks(merged) + merged.into_iter().collect() } -/// Merge a batch of per-region watermark entries into the global merged state. +/// Collects the creator regions of the adopted files the plan's region scans delivered rows +/// from (`RecordBatchMetrics::foreign_file_row_creators`). +/// +/// The answer is `Some` only when **every** region scan that could have read a file stated +/// what it delivered, and the region set is then the union of their answers. A scan that +/// reported nothing — a build that predates the field, a region whose metrics never arrived, +/// or a plan node that never ended its stream — latches the whole answer to `None`, because an +/// answer covering part of the read must not claim that nothing came from another region. +/// `Some(vec![])` is an affirmative "delivered none" and survives the merge as the empty set. +fn collect_foreign_file_row_creators( + plan: Arc, + own: &RecordBatchMetrics, +) -> Option> { + // `own` contributes when it states an answer, and is otherwise the absence of one this + // function cannot interpret: the stream of a distributed plan reports plan-level metrics + // and never a region's read, so its silence is not a scan that failed to report. A stream + // that *is* a region scan has a merge scan in the plan only when the plan reads a table, + // and then that region answers through the merge scan's sub-stage metrics. + let mut merged = BTreeSet::new(); + let mut conclusive = false; + let mut unknown = false; + if let Some(creators) = own.foreign_file_row_creators.as_deref() { + conclusive = true; + merged.extend(creators.iter().copied()); + } + + let mut stack = vec![plan]; + while let Some(plan) = stack.pop() { + // A region scan keeps the answer its partition streams stated when they ended, which + // is the only source of it once the stream of a plan that ran in this process is + // rebuilt from the plan's figures. Its silence is a scan that did not report, so it + // latches the answer unknown. + if let Some(region_scan) = region_scan_of(&plan) { + let creators = region_scan.foreign_file_row_creators(); + merge_foreign_file_row_creators( + creators.as_deref(), + &mut merged, + &mut conclusive, + &mut unknown, + ); + } + if let Some(merge_scan) = plan.downcast_ref::() + && !merge_scan.is_flow_sink_scan() + { + let sub_stage_metrics = merge_scan.sub_stage_metrics(); + // A merge scan with no region to read states "delivered none": unlike a node whose + // partitions have not run, it covers a read that happened and that read delivered + // nothing, so its silence here is an answer and not an absence. + if merge_scan.regions().is_empty() { + conclusive = true; + } + // A region without sub-stage metrics never reported, so the read over it is + // unknown even when every other region stated its answer. + if sub_stage_metrics.len() != merge_scan.regions().len() { + unknown = true; + } + for metrics in sub_stage_metrics { + merge_foreign_file_row_creators( + metrics.foreign_file_row_creators.as_deref(), + &mut merged, + &mut conclusive, + &mut unknown, + ); + } + } + stack.extend(plan.children().into_iter().cloned()); + } + + if unknown || !conclusive { + None + } else { + Some(merged.into_iter().collect()) + } +} + +/// Merges one scan's answer into the plan-wide one. +/// +/// `Some` is an answer (it accumulates and makes the merged result conclusive); `None` is the +/// absence of one and latches the merged result to unknown. +fn merge_foreign_file_row_creators( + creators: Option<&[u64]>, + merged: &mut BTreeSet, + conclusive: &mut bool, + unknown: &mut bool, +) { + match creators { + Some(creators) => { + *conclusive = true; + merged.extend(creators.iter().copied()); + } + None => *unknown = true, + } +} + +/// One `(region, partition expression)` slice's merged state. +/// +/// Two independent statements live here, because a scan states both from one version snapshot: +/// the proof of the slice's sequence bound, and the creators of the files the region had visible +/// when it was opened ([`RegionWatermarkEntry::visible_foreign_file_creators`]). +#[derive(Default)] +struct MergedWatermarkSlice { + /// Proof state of the slice's bound; `None` until a report states one. + proof: Option, + /// The creators of the files visible at open, or `None` when no report stated them or two + /// reports stated different sets (then the merged answer is unknown, never one of them). + visible_foreign_file_creators: Option>, +} + +impl MergedWatermarkSlice { + /// Merges one statement about the creators visible at open. + /// + /// A report that states nothing adds no information, so it leaves a stated set in place. Two + /// reports that state different sets describe file lists that were not the same, so the + /// merged answer is unknown rather than either set. + fn merge_visible_foreign_file_creators(&mut self, incoming: Option>) { + let Some(incoming) = incoming else { + return; + }; + match &self.visible_foreign_file_creators { + None => self.visible_foreign_file_creators = Some(incoming), + Some(current) if *current == incoming => {} + Some(_) => self.visible_foreign_file_creators = None, + } + } +} + +/// Merge a batch of watermark entries into the global merged state. +/// +/// Entries are merged per `(region, partition expression)` ([`WatermarkKey`]): an +/// entry about one expression slice of a region is a statement about that slice only, +/// and letting it share a key with the region's whole-domain entry would either +/// advance a slice the round never read or forget that the region was opened. /// /// # Merge strategy: correctness over maximum /// @@ -385,13 +597,26 @@ fn collect_region_watermarks(plan: Arc) -> Vec, + merged: &mut BTreeMap, entries: impl IntoIterator, ) { for entry in entries { - merged - .entry(entry.region_id) - .and_modify(|existing| match entry.watermark { + let RegionWatermarkEntry { + region_id, + partition_expr, + watermark, + visible_foreign_file_creators, + } = entry; + let slice = merged.entry((region_id, partition_expr)).or_default(); + slice.merge_visible_foreign_file_creators(visible_foreign_file_creators); + match &mut slice.proof { + None => { + slice.proof = Some(match watermark { + Some(seq) => MergeState::Proved(seq), + None => MergeState::Unproved, + }); + } + Some(existing) => match watermark { None => match existing { MergeState::Proved(_) => { *existing = MergeState::Unproved; @@ -413,16 +638,13 @@ fn merge_region_watermark_entries( } } }, - }) - .or_insert(match entry.watermark { - Some(seq) => MergeState::Proved(seq), - None => MergeState::Unproved, - }); + }, + } } } fn merge_merge_scan_region_watermarks( - merged: &mut BTreeMap, + merged: &mut BTreeMap, regions: impl IntoIterator, sub_stage_metrics: impl IntoIterator, ) { @@ -441,7 +663,9 @@ fn merge_merge_scan_region_watermarks( // Regions listed by a MergeScanExec participated even when no sub-stage can // prove a watermark. Merge missing per-scan region entries as explicit // `None` entries so an unproved participating branch vetoes any proof from - // another branch for the same region. + // another branch for the same region. Participation is stated for the region + // as a whole — no sub-stage said anything about one expression of it — so the + // missing entry is the region-wide one. merge_region_watermark_entries( merged, regions @@ -449,28 +673,37 @@ fn merge_merge_scan_region_watermarks( .filter(|region_id| !proved_or_unproved_regions.contains(region_id)) .map(|region_id| RegionWatermarkEntry { region_id, + partition_expr: None, watermark: None, + // No branch said anything about the region's file list. + visible_foreign_file_creators: None, }), ); } -fn finalize_region_watermarks(merged: BTreeMap) -> Vec { +fn finalize_region_watermarks( + merged: BTreeMap, +) -> Vec { merged .into_iter() - .map(|(region_id, state)| RegionWatermarkEntry { - region_id, - watermark: match state { - MergeState::Unproved => None, - MergeState::Proved(seq) => Some(seq), - MergeState::Conflict { watermarks } => { - warn!( - "Conflicting proved watermarks for region {}: {:?}; degrading to unproved", - region_id, watermarks - ); - None - } + .map( + |((region_id, partition_expr), slice)| RegionWatermarkEntry { + region_id, + watermark: match slice.proof.unwrap_or(MergeState::Unproved) { + MergeState::Unproved => None, + MergeState::Proved(seq) => Some(seq), + MergeState::Conflict { watermarks } => { + warn!( + "Conflicting proved watermarks for region {} expression {:?}: {:?}; degrading to unproved", + region_id, partition_expr, watermarks + ); + None + } + }, + partition_expr, + visible_foreign_file_creators: slice.visible_foreign_file_creators, }, - }) + ) .collect() } @@ -481,6 +714,7 @@ mod tests { use api::v1::region::{RemoteDynFilterUnregister, RemoteDynFilterUpdate}; use async_trait::async_trait; + use common_recordbatch::{RecordBatchStream, RecordBatches}; use datafusion::arrow::datatypes::Schema as ArrowSchema; use datafusion::execution::SessionStateBuilder; use datafusion::physical_plan::empty::EmptyExec; @@ -495,6 +729,9 @@ mod tests { use crate::options::{FLOW_RETURN_REGION_SEQ, FLOW_SINK_TABLE_ID}; use crate::region_query::RegionQueryHandler; + /// The partition expression the tests of the observed slices state. + const PARTITION_EXPR: &str = "k0 < 10"; + struct NoopRegionQueryHandler; #[async_trait] @@ -540,14 +777,47 @@ mod tests { .iter() .map(|(region_id, watermark)| RegionWatermarkEntry { region_id: *region_id, + partition_expr: None, watermark: *watermark, + visible_foreign_file_creators: None, }) .collect(), ..Default::default() } } + fn metrics_with_expression_watermarks( + entries: &[(u64, Option<&str>, Option)], + ) -> RecordBatchMetrics { + RecordBatchMetrics { + region_watermarks: entries + .iter() + .map( + |(region_id, partition_expr, watermark)| RegionWatermarkEntry { + region_id: *region_id, + partition_expr: partition_expr.map(|expr| expr.to_string()), + watermark: *watermark, + visible_foreign_file_creators: None, + }, + ) + .collect(), + ..Default::default() + } + } + fn test_merge_scan_exec(table_id: u32, query_ctx: QueryContextRef) -> Arc { + merge_scan_exec(vec![RegionId::new(table_id, 0)], query_ctx) + } + + /// A merge scan over `regions`, with a query context that asks for nothing. + fn merge_scan_exec_with_regions(regions: Vec) -> Arc { + merge_scan_exec(regions, Arc::new(QueryContextBuilder::default().build())) + } + + fn merge_scan_exec( + regions: Vec, + query_ctx: QueryContextRef, + ) -> Arc { let session_state = SessionStateBuilder::new().with_default_features().build(); let plan = LogicalPlanBuilder::empty(false).build().unwrap(); let schema = ArrowSchema::empty(); @@ -556,7 +826,7 @@ mod tests { MergeScanExec::new( &session_state, TableName::new("greptime", "public", "test"), - vec![RegionId::new(table_id, 0)], + regions, plan, &schema, Arc::new(NoopRegionQueryHandler), @@ -603,11 +873,304 @@ mod tests { .region_watermarks, vec![RegionWatermarkEntry { region_id: RegionId::new(43, 0).as_u64(), + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }] ); } + /// The union of what the branches stated: a creator named by two branches is one entry, + /// and an answer of "delivered none" survives as the empty set instead of disappearing. + #[test] + fn merge_foreign_file_row_creators_unions_the_branches() { + let mut merged = BTreeSet::new(); + let mut conclusive = false; + let mut unknown = false; + + merge_foreign_file_row_creators(Some(&[7, 9]), &mut merged, &mut conclusive, &mut unknown); + merge_foreign_file_row_creators(Some(&[9]), &mut merged, &mut conclusive, &mut unknown); + merge_foreign_file_row_creators(Some(&[]), &mut merged, &mut conclusive, &mut unknown); + + assert!(conclusive); + assert!(!unknown); + assert_eq!( + BTreeSet::from([7, 9]), + merged, + "the delivered creators are the union of what the branches reported" + ); + } + + /// A branch that states nothing latches the answer to unknown: the other branches' answers + /// cover only part of the read, and "these are the creators" would claim the rest + /// delivered nothing. + #[test] + fn merge_foreign_file_row_creators_keeps_a_silent_branch_unknown() { + let mut merged = BTreeSet::new(); + let mut conclusive = false; + let mut unknown = false; + + merge_foreign_file_row_creators(Some(&[]), &mut merged, &mut conclusive, &mut unknown); + merge_foreign_file_row_creators(None, &mut merged, &mut conclusive, &mut unknown); + + assert!(conclusive); + assert!( + unknown, + "one silent branch is enough to make the answer unknown" + ); + } + + /// A plan whose stream states the answer reports it; one whose stream states nothing + /// reports unknown rather than "none". + #[test] + fn collect_foreign_file_row_creators_reads_the_stream_that_reports_it() { + let plan: Arc = Arc::new(EmptyExec::new(Arc::new(ArrowSchema::empty()))); + + let own = RecordBatchMetrics { + foreign_file_row_creators: Some(vec![7]), + ..Default::default() + }; + assert_eq!( + Some(vec![7]), + collect_foreign_file_row_creators(plan.clone(), &own) + ); + + assert_eq!( + None, + collect_foreign_file_row_creators(plan, &RecordBatchMetrics::default()) + ); + } + + /// A merge scan lists its regions, so a region that never reported its metrics makes the + /// whole answer unknown: the read over that region is uncovered, not empty. + #[test] + fn collect_foreign_file_row_creators_stays_unknown_when_a_region_never_reported() { + let query_ctx = flow_query_ctx_with_sink_table_id(42); + let plan = test_merge_scan_exec(43, query_ctx); + let own = RecordBatchMetrics { + foreign_file_row_creators: Some(vec![]), + ..Default::default() + }; + + assert_eq!( + None, + collect_foreign_file_row_creators(plan, &own), + "the merge scan's one region reported no metrics, so nothing about it is proved" + ); + } + + /// A partition stream that states what a Mito region's stream states when it ends. + struct StatedStream { + inner: common_recordbatch::SendableRecordBatchStream, + terminal: RecordBatchMetrics, + } + + impl futures::Stream for StatedStream { + type Item = common_recordbatch::error::Result; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_next(cx) + } + } + + impl RecordBatchStream for StatedStream { + fn schema(&self) -> datatypes::schema::SchemaRef { + self.inner.schema() + } + + fn output_ordering(&self) -> Option<&[common_recordbatch::OrderOption]> { + self.inner.output_ordering() + } + + fn metrics(&self) -> Option { + Some(self.terminal.clone()) + } + } + + /// A `RegionScanExec` whose one partition states `terminal` when its stream ends. + fn stated_region_scan(terminal: RecordBatchMetrics) -> Arc { + use store_api::region_engine::SinglePartitionScanner; + + let mut builder = store_api::metadata::RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder + .push_column_metadata(store_api::metadata::ColumnMetadata { + column_schema: datatypes::schema::ColumnSchema::new( + "field", + datatypes::data_type::ConcreteDataType::float64_datatype(), + true, + ), + semantic_type: api::v1::SemanticType::Field, + column_id: 1, + }) + .push_column_metadata(store_api::metadata::ColumnMetadata { + column_schema: datatypes::schema::ColumnSchema::new( + "ts", + datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: api::v1::SemanticType::Timestamp, + column_id: 2, + }) + .primary_key(vec![]); + let metadata = Arc::new(builder.build().unwrap()); + let batches = RecordBatches::try_new(metadata.schema.clone(), vec![]).unwrap(); + let stream = StatedStream { + inner: batches.as_stream(), + terminal, + }; + let scanner = Box::new(SinglePartitionScanner::new( + Box::pin(stream), + false, + metadata, + None, + )); + Arc::new( + RegionScanExec::new(scanner, store_api::storage::ScanRequest::default(), None).unwrap(), + ) + } + + /// Runs `plan` as a plan, through the DataFusion boundary, until its streams ended. + async fn drain_plan(plan: Arc) { + use datafusion::prelude::SessionContext; + use futures::TryStreamExt; + + let ctx = SessionContext::new(); + let mut stream = plan.execute(0, ctx.task_ctx()).unwrap(); + while stream.try_next().await.unwrap().is_some() {} + } + + /// The terminal metrics of a scan that stated only the creators it delivered rows from. + fn creator_answer(creators: Option>) -> RecordBatchMetrics { + RecordBatchMetrics { + foreign_file_row_creators: creators, + ..Default::default() + } + } + + /// A plan that runs in this process states its answer through the region scan that read the + /// region, not through a stream that a rebuilt `RecordBatchMetrics` could still describe. + #[tokio::test] + async fn collect_foreign_file_row_creators_reads_the_local_region_scan() { + // The scan answered what its stream stated. + let plan = stated_region_scan(creator_answer(Some(vec![7]))); + assert_eq!( + None, + collect_foreign_file_row_creators(plan.clone(), &RecordBatchMetrics::default()), + "a scan whose stream has not ended states nothing" + ); + drain_plan(plan.clone()).await; + assert_eq!( + Some(vec![7]), + collect_foreign_file_row_creators(plan.clone(), &RecordBatchMetrics::default()), + "the plan states what its region scan delivered" + ); + assert_eq!( + Some(vec![7]), + terminal_recordbatch_metrics_from_plan(plan) + .expect("a conclusive creator answer is terminal metrics") + .foreign_file_row_creators + ); + + // A scan whose stream stated nothing stays unknown: a read that did not report must + // not be read as "delivered none". + let plan = stated_region_scan(creator_answer(None)); + drain_plan(plan.clone()).await; + assert_eq!( + None, + collect_foreign_file_row_creators(plan, &RecordBatchMetrics::default()), + "a scan that states no answer leaves the plan's answer unknown" + ); + } + + /// The ranges a scan substituted and the slices it observed are statements about its read, + /// not figures, so they must survive the DataFusion boundary: the plan is polled to EOF as a + /// plan, and its stream reports only numbers. A read that substituted rows must not reach + /// the caller as "substituted nothing". + #[tokio::test] + async fn substituted_ranges_and_observed_slices_cross_the_datafusion_boundary() { + let plan = stated_region_scan(RecordBatchMetrics { + foreign_file_row_creators: Some(vec![]), + substituted_row_ranges: vec![SubstitutedRowRanges { + region_id: 7, + ranges: vec![SubstitutedRange { + start_millis: 1_000, + end_millis: 2_000, + }], + }], + observed_slices: vec![ObservedPartitionExpr::new( + 7, + Some(PARTITION_EXPR.to_string()), + )], + ..Default::default() + }); + + // Nothing is stated before the read ends, so nothing is claimed. + assert!( + terminal_recordbatch_metrics_from_plan(plan.clone()).is_none(), + "a scan whose stream has not ended states nothing" + ); + + drain_plan(plan.clone()).await; + + let metrics = terminal_recordbatch_metrics_from_plan(plan) + .expect("a read that substituted rows and observed slices is terminal metrics"); + assert_eq!( + vec![SubstitutedRowRanges { + region_id: 7, + ranges: vec![SubstitutedRange { + start_millis: 1_000, + end_millis: 2_000, + }], + }], + metrics.substituted_row_ranges, + "the substituted ranges must cross the boundary, not read as \"substituted nothing\"" + ); + assert_eq!( + vec![ObservedPartitionExpr::new( + 7, + Some(PARTITION_EXPR.to_string()) + )], + metrics.observed_slices, + "the observed slices must cross the boundary" + ); + assert_eq!( + Some(vec![]), + metrics.foreign_file_row_creators, + "the same terminal call states the creator answer as well" + ); + } + + /// A merge scan that lists no region read nothing, so it states "delivered none" instead of + /// leaving the answer unknown: the read over zero regions covers every row it could have + /// delivered, and that read delivered none. + #[test] + fn zero_region_merge_scan_states_delivered_none() { + let plan = merge_scan_exec_with_regions(vec![]); + assert_eq!( + Some(vec![]), + collect_foreign_file_row_creators(plan.clone(), &RecordBatchMetrics::default()), + "a merge scan with no region delivered no adopted row, and states so" + ); + assert_eq!( + Some(vec![]), + terminal_recordbatch_metrics_from_plan(plan) + .expect("an affirmative creator answer is terminal metrics") + .foreign_file_row_creators + ); + + // A merge scan that names a region that never reported stays unknown, so the empty + // answer above is the zero-region read and not a blanket "silence is none". + let plan = merge_scan_exec_with_regions(vec![RegionId::new(43, 0)]); + assert_eq!( + None, + collect_foreign_file_row_creators(plan, &RecordBatchMetrics::default()), + "a region without sub-stage metrics leaves the answer unknown" + ); + } + #[test] fn merge_merge_scan_region_watermarks_marks_missing_watermarks_unproved() { let mut merged = BTreeMap::new(); @@ -619,11 +1182,15 @@ mod tests { vec![ RegionWatermarkEntry { region_id: 1, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }, RegionWatermarkEntry { region_id: 2, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }, ] ); @@ -646,7 +1213,78 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 42, + partition_expr: None, watermark: Some(7), + visible_foreign_file_creators: None, + }] + ); + } + + /// A statement about one partition expression of a region and a statement about the + /// region's complete value domain are statements about different domains: merging + /// them into one key would either advance a slice the round never read or forget + /// that the whole region was opened. + #[test] + fn merge_merge_scan_region_watermarks_keys_by_region_and_expression() { + let mut merged = BTreeMap::new(); + + merge_merge_scan_region_watermarks( + &mut merged, + [42], + [ + metrics_with_expression_watermarks(&[(42, None, Some(9))]), + metrics_with_expression_watermarks(&[(42, Some("k0 < 10"), Some(5))]), + metrics_with_expression_watermarks(&[(42, Some("k0 >= 10"), Some(7))]), + ], + ); + + assert_eq!( + finalize_region_watermarks(merged), + vec![ + RegionWatermarkEntry { + region_id: 42, + partition_expr: None, + watermark: Some(9), + visible_foreign_file_creators: None, + }, + RegionWatermarkEntry { + region_id: 42, + partition_expr: Some("k0 < 10".to_string()), + watermark: Some(5), + visible_foreign_file_creators: None, + }, + RegionWatermarkEntry { + region_id: 42, + partition_expr: Some("k0 >= 10".to_string()), + watermark: Some(7), + visible_foreign_file_creators: None, + }, + ] + ); + } + + /// The conflict rule still applies to one and the same expression. + #[test] + fn merge_merge_scan_region_watermarks_degrades_conflicting_expression_entries() { + let mut merged = BTreeMap::new(); + + merge_merge_scan_region_watermarks( + &mut merged, + [42], + [ + metrics_with_expression_watermarks(&[(42, Some("k0 < 10"), Some(5))]), + metrics_with_expression_watermarks(&[(42, Some("k0 < 10"), Some(6))]), + metrics_with_expression_watermarks(&[(42, Some("k0 < 10"), None)]), + ], + ); + + assert_eq!( + finalize_region_watermarks(merged), + vec![RegionWatermarkEntry { + region_id: 42, + partition_expr: Some("k0 < 10".to_string()), + watermark: None, + visible_foreign_file_creators: None, }] ); } @@ -668,7 +1306,9 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 7, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }] ); } @@ -690,7 +1330,9 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }] ); } @@ -712,7 +1354,9 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }] ); } @@ -732,7 +1376,9 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }] ); } @@ -752,7 +1398,9 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, + visible_foreign_file_creators: None, }] ); } diff --git a/src/query/src/options.rs b/src/query/src/options.rs index ae0bceb19aa..02f02b7806e 100644 --- a/src/query/src/options.rs +++ b/src/query/src/options.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::path::PathBuf; +use std::sync::Arc; use chrono::{DateTime, Utc}; use common_base::memory_limit::MemoryLimit; @@ -21,7 +22,7 @@ use common_base::readable_size::ReadableSize; use datafusion::config::{ConfigEntry, ConfigExtension, ExtensionOptions}; use serde::{Deserialize, Serialize}; use session::context::QueryContextRef; -use store_api::storage::RegionId; +use store_api::storage::{CursorShard, RegionId, SequenceNumber}; use table::metadata::TableId; use crate::error::{Error, InvalidQueryContextExtensionSnafu, Result}; @@ -29,6 +30,23 @@ use crate::error::{Error, InvalidQueryContextExtensionSnafu, Result}; pub const FLOW_INCREMENTAL_AFTER_SEQS: &str = "flow.incremental_after_seqs"; pub const FLOW_INCREMENTAL_MODE: &str = "flow.incremental_mode"; pub const FLOW_RETURN_REGION_SEQ: &str = "flow.return_region_seq"; +/// Marks a Flow repair read. Such a query only discovers or overwrites time windows, +/// so it must never be refused for holding an old cursor: it is the query +/// that repairs the state a stale cursor can no longer explain. Ordinary incremental +/// deltas must not set it. +/// +/// The value selects the mode, because the two repair reads need different scans: +/// - [`FLOW_REPAIR_MODE_DISCOVERY`]: dirty-window discovery. It may prune at file +/// granularity and force every row's sequence to the file barrier, because it only +/// needs the timestamps of the rows a stale cursor may have missed. +/// - [`FLOW_REPAIR_MODE_FENCED`]: the fenced repair DML. It must read the selected +/// windows completely, so it gets no file pruning and no forced override; it only +/// skips the `C < B` rejection and must still prove `B <= H`. +pub const FLOW_REPAIR_MODE: &str = "flow.repair_mode"; +/// `flow.repair_mode` value: recovery dirty-window discovery. +pub const FLOW_REPAIR_MODE_DISCOVERY: &str = "discovery"; +/// `flow.repair_mode` value: fenced repair DML. +pub const FLOW_REPAIR_MODE_FENCED: &str = "fenced"; /// Reads the physical `__sequence` column of a file this region adopted from another region, /// instead of virtualizing every row at the handle's admission barrier. The scan then hides the /// rows whose number is at or below the file's own substituted cut @@ -45,6 +63,29 @@ pub const FLOW_SCHEDULED_TIME_MILLIS: &str = "flow.scheduled_time_millis"; pub const QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN: &str = "query.enable_remote_dynamic_filter_pushdown"; +/// The kind of Flow repair read requested through [FLOW_REPAIR_MODE]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlowRepairMode { + /// Dirty-window discovery: prunes at file granularity and forces the file + /// barrier as every row's sequence. + Discovery, + /// Fenced repair DML: reads the selected windows completely. + Fenced, +} + +impl FlowRepairMode { + fn parse(value: &str) -> Result { + match value { + v if v.eq_ignore_ascii_case(FLOW_REPAIR_MODE_DISCOVERY) => Ok(Self::Discovery), + v if v.eq_ignore_ascii_case(FLOW_REPAIR_MODE_FENCED) => Ok(Self::Fenced), + _ => Err(invalid_query_context_extension(format!( + "Invalid value for {}: {}, expected {} or {}", + FLOW_REPAIR_MODE, value, FLOW_REPAIR_MODE_DISCOVERY, FLOW_REPAIR_MODE_FENCED + ))), + } + } +} + pub const FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY: &str = "memtable_only"; pub const FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE: &str = "sequence_range"; @@ -189,12 +230,21 @@ pub enum FlowIncrementalMode { #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct FlowQueryExtensions { - /// Maps region id -> lower exclusive sequence bound for incremental reads. - pub incremental_after_seqs: Option>, + /// Maps a region id to the incremental cursor of each of its partition expressions. + /// + /// The region is the **creator** of the sequences, and the cursor of a slice is the + /// last sequence consumed in the value domain its partition expression selects (see + /// [`CursorShard`]). A holder region reads its own memtables and files after the + /// least advanced of its own slices, while a file it adopted from another region is + /// filtered by the cursor of the creator's slice its own partition expression + /// belongs to. + pub incremental_after_seqs: Option>>, /// Incremental read mode requested by the caller. pub incremental_mode: Option, /// Whether the caller expects per-region watermark metadata in terminal metrics. pub return_region_seq: bool, + /// Which kind of Flow repair read this is, if any (see [FLOW_REPAIR_MODE]). + pub repair_mode: Option, /// Optional sink table id used to distinguish source scans from sink reads. pub sink_table_id: Option, /// Whether an incremental scan reads physical row sequences and hides the rows a @@ -211,8 +261,9 @@ impl FlowQueryExtensions { pub fn parse_flow_extensions(extensions: &HashMap) -> Result> { let has_flow_context = extensions.contains_key(FLOW_INCREMENTAL_AFTER_SEQS) || extensions.contains_key(FLOW_INCREMENTAL_MODE) - || extensions.contains_key(FLOW_READ_ROW_SEQUENCE) || extensions.contains_key(FLOW_RETURN_REGION_SEQ) + || extensions.contains_key(FLOW_REPAIR_MODE) + || extensions.contains_key(FLOW_READ_ROW_SEQUENCE) || extensions.contains_key(FLOW_SINK_TABLE_ID); if !has_flow_context { @@ -246,6 +297,11 @@ impl FlowQueryExtensions { .transpose()? .unwrap_or(false); + let repair_mode = extensions + .get(FLOW_REPAIR_MODE) + .map(|value| FlowRepairMode::parse(value.as_str())) + .transpose()?; + let read_row_sequence = extensions .get(FLOW_READ_ROW_SEQUENCE) .map(|value| parse_bool(FLOW_READ_ROW_SEQUENCE, value.as_str())) @@ -291,6 +347,7 @@ impl FlowQueryExtensions { incremental_after_seqs, incremental_mode, return_region_seq, + repair_mode, sink_table_id, read_row_sequence, })) @@ -334,6 +391,35 @@ impl FlowQueryExtensions { self.incremental_after_seqs.is_some(), ) } + + /// The cursor of the least advanced expression slice of `region_id`. + /// + /// A read of the region's **own** memtables and files cannot tell which slice a row + /// belongs to, so it has to start after the least advanced one: the highest slice + /// bound would drop the rows of a slice that has not been consumed yet. The value is a + /// lower bound for the whole read, not a per-row decision. + pub fn region_cursor(&self, region_id: u64) -> Option { + self.incremental_after_seqs + .as_ref()? + .get(®ion_id)? + .iter() + .map(|shard| shard.seq) + .min() + } + + /// The slice cursors of every creator region, as a scan request carries them. + /// + /// Only a physical-sequence read of an adopted file needs them: it is the only read + /// that compares a row's number against the domain the number was allocated in. + pub fn creator_cursor_shards(&self) -> Option>>> { + let cursors = self.incremental_after_seqs.as_ref()?; + Some(Arc::new( + cursors + .iter() + .map(|(region_id, shards)| (*region_id, shards.clone())) + .collect(), + )) + } } /// Returns whether query-level remote dynamic filter propagation is enabled. @@ -374,7 +460,38 @@ fn should_collect_region_watermark( return_region_seq || has_incremental_after_seqs } -fn parse_incremental_after_seqs(value: &str) -> Result> { +/// Version marker of the expression-keyed cursor form. A reader refuses a version it does not +/// know. +const CURSOR_SHARD_VERSION_KEY: &str = "version"; +/// The only version of the expression-keyed cursor form. A slice states whether it carries an +/// upper bound through [`CURSOR_SHARD_UNTIL_KEY`], so the version distinguishes nothing and +/// carries no information. +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; absent means the slice is unbounded above. +const CURSOR_SHARD_UNTIL_KEY: &str = "until"; + +/// Parses [`FLOW_INCREMENTAL_AFTER_SEQS`]. +/// +/// * expression-keyed (version [`CURSOR_SHARD_VERSION`]): +/// `{"": {"version": 2, "shards": [{"expr": "", "seq": +/// 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. [`encode_incremental_after_seqs`] writes exactly this shape; +/// * region-keyed: `{"": seq}` — one cursor for the region's complete value +/// domain, i.e. the single whole-domain slice. Flow still writes it whenever it knows only +/// the region projection and no per-slice cursor +/// (`batching_mode::task::inc::BatchingTask::build_flow_query_extensions`), so it is a live +/// shape, not history. +/// +/// Any other shape is refused as an unknown format: it is never read as a cursor this +/// build can act on. +fn parse_incremental_after_seqs(value: &str) -> Result>> { let raw = serde_json::from_str::>(value).map_err(|e| { invalid_query_context_extension(format!( "Invalid JSON for {}: {} ({})", @@ -383,7 +500,7 @@ fn parse_incremental_after_seqs(value: &str) -> Result> { })?; raw.into_iter() - .map(|(region_id, raw_seq)| { + .map(|(region_id, raw_cursor)| { let region_id = region_id.parse::().map_err(|_| { invalid_query_context_extension(format!( "Invalid region id in {}: {}", @@ -391,32 +508,227 @@ fn parse_incremental_after_seqs(value: &str) -> Result> { )) })?; - let seq = match raw_seq { - serde_json::Value::Number(num) => num.as_u64().ok_or_else(|| { - invalid_query_context_extension(format!( - "Invalid sequence value in {} for region {}: {}", - FLOW_INCREMENTAL_AFTER_SEQS, region_id, num - )) - })?, - serde_json::Value::String(s) => s.parse::().map_err(|_| { - invalid_query_context_extension(format!( - "Invalid sequence string in {} for region {}: {}", - FLOW_INCREMENTAL_AFTER_SEQS, region_id, s - )) - })?, + let shards = match raw_cursor { + // Region-keyed shape: the region's complete value domain. + serde_json::Value::Number(_) | serde_json::Value::String(_) => { + vec![CursorShard::whole_domain(parse_cursor_seq( + region_id, + &raw_cursor, + )?)] + } + // Expression-keyed shape. + serde_json::Value::Object(fields) => { + parse_expression_keyed_shards(region_id, &fields)? + } + // Any other shape is an unknown format, never a cursor to guess at. _ => { return Err(invalid_query_context_extension(format!( - "Invalid sequence value type in {} for region {}", + "Invalid cursor value type in {} for region {}", FLOW_INCREMENTAL_AFTER_SEQS, region_id ))); } }; - Ok((region_id, seq)) + Ok((region_id, shards)) }) .collect() } +/// Parses the expression-keyed value of one region. +fn parse_expression_keyed_shards( + region_id: u64, + fields: &serde_json::Map, +) -> Result> { + match fields.get(CURSOR_SHARD_VERSION_KEY) { + Some(version) if version.as_u64() == Some(CURSOR_SHARD_VERSION) => {} + Some(version) => { + return Err(invalid_query_context_extension(format!( + "Unsupported cursor version {:?} in {} for region {}: this build reads version {}", + version, FLOW_INCREMENTAL_AFTER_SEQS, region_id, CURSOR_SHARD_VERSION + ))); + } + None => { + return Err(invalid_query_context_extension(format!( + "Missing cursor version in {} for region {}: an object value must state version {}", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, CURSOR_SHARD_VERSION + ))); + } + } + + let Some(serde_json::Value::Array(shards)) = fields.get(CURSOR_SHARD_SHARDS_KEY) else { + return Err(invalid_query_context_extension(format!( + "Missing cursor shards in {} for region {}: expected an array under \"{}\"", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, CURSOR_SHARD_SHARDS_KEY + ))); + }; + if shards.is_empty() { + return Err(invalid_query_context_extension(format!( + "Region {} states no cursor slice in {}", + region_id, FLOW_INCREMENTAL_AFTER_SEQS + ))); + } + + shards + .iter() + .map(|shard| parse_cursor_shard(region_id, shard)) + .collect() +} + +/// Parses one `{"expr": | null, "seq": N, "until": N?}` slice. +/// +/// `until` is optional and read whenever it is stated: a bound is a bound. A bound below +/// the slice's own `seq` states an empty delta (a slice covers `seq < number <= until`) and +/// is refused instead of being clamped or swapped. +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!( + "Invalid cursor slice in {} for region {}: expected {{\"expr\": ..., \"seq\": ...}}, found {}", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, shard + ))); + }; + + let partition_expr = match fields.get(CURSOR_SHARD_EXPR_KEY) { + // A missing key would have to be guessed: an absent expression is not the same + // statement as an explicit whole-domain `null`. + None => { + return Err(invalid_query_context_extension(format!( + "Invalid cursor slice in {} for region {}: expected the partition expression under \"{}\" (null for the whole domain)", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, CURSOR_SHARD_EXPR_KEY + ))); + } + Some(serde_json::Value::Null) => None, + Some(serde_json::Value::String(expr)) => Some(validate_partition_expr(region_id, expr)?), + Some(other) => { + return Err(invalid_query_context_extension(format!( + "Invalid partition expression in {} for region {}: expected a JSON string or null, found {}", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, other + ))); + } + }; + + let Some(seq) = fields.get(CURSOR_SHARD_SEQ_KEY) else { + return Err(invalid_query_context_extension(format!( + "Invalid cursor slice in {} for region {}: expected the consumed sequence under \"{}\"", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, CURSOR_SHARD_SEQ_KEY + ))); + }; + let seq = parse_cursor_seq(region_id, seq)?; + + // A slice that states no bound is unbounded above; an explicit `null` states the same. + let until = match fields.get(CURSOR_SHARD_UNTIL_KEY) { + None | Some(serde_json::Value::Null) => None, + Some(raw) => Some(parse_cursor_seq(region_id, raw)?), + }; + + // A slice covers `seq < number <= until`, so an `until` below its own `seq` states an + // empty window. Refusing it is the only reading that keeps the producer's statement + // intact: clamping or swapping would silently deliver a delta it never asked for. A + // lower bound is also worse than a no-op downstream — a read bounds a file with + // `GtLtEq { min, max }` and `max < min` selects no row at all, while a file several + // slices match can still admit rows through another slice's smaller minimum, so the + // read would answer with a plain wrong result instead of failing. + if let Some(until) = until + && until < seq + { + return Err(invalid_query_context_extension(format!( + "Invalid cursor slice in {} for region {}: the upper bound {} is below the slice's \ + own consumed sequence {} (a slice covers seq < number <= until, so its until must \ + be at least its seq)", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, until, seq + ))); + } + + 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 +/// identity to store. `store-api` cannot depend on `partition`, so this is the last place a +/// malformed expression is rejected. +fn validate_partition_expr(region_id: u64, expr: &str) -> Result { + match partition::expr::PartitionExpr::from_json_str(expr) { + Ok(Some(parsed)) => Ok(parsed.as_json_str().map_err(|e| { + invalid_query_context_extension(format!( + "Cannot re-serialize the partition expression of region {} in {}: {}", + region_id, FLOW_INCREMENTAL_AFTER_SEQS, e + )) + })?), + Ok(None) => Err(invalid_query_context_extension(format!( + "Invalid partition expression of region {} in {}: {} is not a partition expression", + region_id, FLOW_INCREMENTAL_AFTER_SEQS, expr + ))), + Err(e) => Err(invalid_query_context_extension(format!( + "Invalid partition expression of region {} in {}: {} ({})", + region_id, FLOW_INCREMENTAL_AFTER_SEQS, expr, e + ))), + } +} + +/// Parses one sequence number of a cursor, accepting the numeric and the string form. +fn parse_cursor_seq(region_id: u64, raw: &serde_json::Value) -> Result { + match raw { + serde_json::Value::Number(num) => num.as_u64().ok_or_else(|| { + invalid_query_context_extension(format!( + "Invalid sequence value in {} for region {}: {}", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, num + )) + }), + serde_json::Value::String(s) => s.parse::().map_err(|_| { + invalid_query_context_extension(format!( + "Invalid sequence string in {} for region {}: {}", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, s + )) + }), + other => Err(invalid_query_context_extension(format!( + "Invalid sequence value type in {} for region {}: {}", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, other + ))), + } +} + +/// Encodes slice cursors as the expression-keyed form of [`FLOW_INCREMENTAL_AFTER_SEQS`], +/// which [`parse_incremental_after_seqs`] reads back. +/// +/// A whole-domain slice is written as an explicit `"expr": null`, and an upper bound +/// ([`CursorShard::until`]) only when the slice states one. Every region is written under +/// [`CURSOR_SHARD_VERSION`]: the bound travels per slice, so nothing about a region has to be +/// stated at its version marker. +pub fn encode_incremental_after_seqs(cursors: &BTreeMap>) -> Result { + let encoded = cursors + .iter() + .map(|(region_id, shards)| { + let shards = shards + .iter() + .map(|shard| { + 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, so its absence is the unbounded slice. + if let Some(until) = shard.until { + encoded[CURSOR_SHARD_UNTIL_KEY] = serde_json::json!(until); + } + encoded + }) + .collect::>(); + let value = serde_json::json!({ + CURSOR_SHARD_VERSION_KEY: CURSOR_SHARD_VERSION, + CURSOR_SHARD_SHARDS_KEY: shards, + }); + (region_id.to_string(), value) + }) + .collect::>(); + serde_json::to_string(&encoded).map_err(|e| { + invalid_query_context_extension(format!( + "Failed to serialize {}: {}", + FLOW_INCREMENTAL_AFTER_SEQS, e + )) + }) +} + fn parse_bool(option_name: &str, value: &str) -> Result { match value { v if v.eq_ignore_ascii_case("true") => Ok(true), @@ -567,8 +879,21 @@ fn invalid_query_context_extension(reason: String) -> Error { #[cfg(test)] mod flow_extension_tests { + use datatypes::value::Value; + use partition::expr::{Operand, col as partition_col}; + use super::*; + /// The identity of one half-open expression slice `k0 >= lo AND k0 < hi`, in the form + /// the wire carries it. + fn slice_expr(lo: u64, hi: u64) -> String { + partition_col("k0") + .gt_eq(Operand::Value(Value::UInt64(lo))) + .and(partition_col("k0").lt(Operand::Value(Value::UInt64(hi)))) + .as_json_str() + .unwrap() + } + #[test] fn test_parse_flow_extensions_returns_none_for_non_flow_query() { let exts = HashMap::new(); @@ -632,7 +957,10 @@ mod flow_extension_tests { ); assert_eq!( parsed.incremental_after_seqs.unwrap(), - HashMap::from([(1, 10), (2, 20)]) + HashMap::from([ + (1, vec![CursorShard::whole_domain(10)]), + (2, vec![CursorShard::whole_domain(20)]), + ]) ); assert!(parsed.return_region_seq); assert_eq!(parsed.sink_table_id, Some(1024)); @@ -660,7 +988,7 @@ mod flow_extension_tests { ); assert_eq!( parsed.incremental_after_seqs, - Some(HashMap::from([(1, 10)])) + Some(HashMap::from([(1, vec![CursorShard::whole_domain(10)])])) ); } @@ -737,7 +1065,10 @@ mod flow_extension_tests { .unwrap(); assert_eq!( parsed.incremental_after_seqs.unwrap(), - HashMap::from([(1, 10), (2, 20)]) + HashMap::from([ + (1, vec![CursorShard::whole_domain(10)]), + (2, vec![CursorShard::whole_domain(20)]), + ]) ); } @@ -822,7 +1153,7 @@ mod flow_extension_tests { #[test] fn test_should_collect_region_watermark_true_for_incremental_query() { let parsed = FlowQueryExtensions { - incremental_after_seqs: Some(HashMap::from([(1, 10)])), + incremental_after_seqs: Some(HashMap::from([(1, vec![CursorShard::whole_domain(10)])])), ..Default::default() }; assert!(parsed.should_collect_region_watermark()); @@ -881,7 +1212,327 @@ mod flow_extension_tests { assert_eq!( parsed.incremental_after_seqs, - Some(HashMap::from([(1, 10)])) + Some(HashMap::from([(1, vec![CursorShard::whole_domain(10)])])) + ); + } + + #[test] + fn test_parse_flow_extensions_after_seqs_slice_form() { + // The expression-keyed shape: the partition expressions of one region, each with + // its own cursor. + let low = slice_expr(0, 50); + let high = slice_expr(50, 100); + let value = format!( + r#"{{"7":{{"version":2,"shards":[{{"expr":{},"seq":10}},{{"expr":{},"seq":3}},{{"expr":null,"seq":4}}]}}}}"#, + serde_json::to_string(&low).unwrap(), + serde_json::to_string(&high).unwrap() + ); + let exts = HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value)]); + + let parsed = FlowQueryExtensions::parse_flow_extensions(&exts) + .unwrap() + .unwrap(); + + assert_eq!( + parsed.incremental_after_seqs, + Some(HashMap::from([( + 7, + vec![ + CursorShard::new(Some(low), 10), + CursorShard::new(Some(high), 3), + CursorShard::whole_domain(4), + ] + )])) + ); + // A region-level read has to start after the least advanced slice. + assert_eq!(Some(3), parsed.region_cursor(7)); + assert_eq!(None, parsed.region_cursor(8)); + } + + /// A slice that states no upper bound decodes as the unbounded slice it is, under the one + /// version the format has. + #[test] + fn test_parse_flow_extensions_after_seqs_unbounded_slice_reads() { + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10},{"expr":null,"seq":4}]}}"# + .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), CursorShard::whole_domain(4)] + )])), + "a slice that states no upper bound is the unbounded slice" + ); + assert_eq!( + None, + parsed.incremental_after_seqs.as_ref().unwrap()[&7][0].until + ); + } + + /// A slice that states an upper bound carries it in the same version: `seq < number <= + /// until` decodes as the bounded slice it states, and an invalid bound is refused at the + /// boundary like `seq`. + #[test] + fn test_parse_flow_extensions_after_seqs_bounded_slice_reads() { + 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`. + for value in [ + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":"nope"}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":-1}]}}"#, + ] { + let exts = + HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value.to_string())]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + assert!( + format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS), + "{value}: {err}" + ); + } + } + + /// A slice covers `seq < number <= until`, so an `until` below its own `seq` states an + /// empty delta and is refused at the boundary instead of being clamped or swapped: a read + /// bounds a file with `GtLtEq { min, max }` and `max < min` selects no row at all, while a + /// file several slices match can still admit rows through another slice's smaller minimum, + /// so the wrong slice would look like a plausible but wrong answer instead of a failure. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_upper_bound_below_cursor() { + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":9}]}}"#.to_string(), + )]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + let message = format!("{err}"); + assert!( + message.contains("region 7"), + "the failure names the region: {message}" + ); + assert!( + message.contains("upper bound 9"), + "the failure names the stated bound: {message}" + ); + assert!( + message.contains("consumed sequence 10"), + "the failure names the slice's own cursor: {message}" + ); + assert!( + message.contains("at least its seq"), + "the failure names the ordering rule: {message}" + ); + + // The bound is refused whatever the distance is. + for (value, region) in [ + ( + r#"{"8":{"version":2,"shards":[{"expr":null,"seq":10,"until":9}]}}"#, + "region 8", + ), + ( + r#"{"9":{"version":2,"shards":[{"expr":null,"seq":5,"until":0}]}}"#, + "region 9", + ), + ] { + let exts = + HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value.to_string())]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + let message = format!("{err}"); + assert!( + message.contains(region) && message.contains("at least its seq"), + "{value}: {message}" + ); + } + + // `until == seq` is the boundary the rule allows: the slice states the bound it + // covers, and no row of it is above the cursor. + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":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).with_until(10)] + )])), + "a bound equal to the cursor states an empty window and is not a contradiction" + ); + } + + /// 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] + fn test_parse_flow_extensions_after_seqs_rejects_invalid_expression() { + for value in [ + // Not a partition expression at all. + r#"{"7":{"version":2,"shards":[{"expr":"not-json","seq":1}]}}"#.to_string(), + // A bound shape this build does not treat as an expression. + r#"{"7":{"version":2,"shards":[{"expr":"","seq":1}]}}"#.to_string(), + // An expression identity must be stated, an absent key is not a whole domain. + r#"{"7":{"version":2,"shards":[{"seq":1}]}}"#.to_string(), + // The sequence must be stated. + r#"{"7":{"version":2,"shards":[{"expr":null}]}}"#.to_string(), + // A non-string, non-null expression identity. + r#"{"7":{"version":2,"shards":[{"expr":7,"seq":1}]}}"#.to_string(), + ] { + let exts = HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value.clone())]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + assert!( + format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS), + "{value}: {err}" + ); + } + } + + /// A version this build does not know is refused, and the version marker is mandatory for + /// an object value: a cursor is never guessed at from a shape that states its own format. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_unknown_version() { + for value in [ + // A version this build does not know. + r#"{"7":{"version":4,"shards":[{"expr":null,"seq":1}]}}"#.to_string(), + // No version marker at all. + r#"{"7":{"shards":[{"expr":null,"seq":1}]}}"#.to_string(), + // The version marker is not a number. + r#"{"7":{"version":"2","shards":[{"expr":null,"seq":1}]}}"#.to_string(), + // Shards are missing. + r#"{"7":{"version":2}}"#.to_string(), + ] { + let exts = HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value.clone())]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + assert!( + format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS), + "{value}: {err}" + ); + } + } + + #[test] + fn test_parse_flow_extensions_after_seqs_region_form_is_the_full_slice() { + // The region-keyed shape is exactly the region's complete value domain, so a + // reader that only knows it keeps working. + let exts = HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":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)])])) + ); + assert_eq!(Some(10), parsed.region_cursor(7)); + } + + /// A shape this build does not know is refused, never guessed at: the numeric + /// `[[lo, hi, seq], ...]` projection cannot name an expression, so it is not a cursor + /// this build can act on. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_unknown_shapes() { + for value in [ + // The numeric slice projection: no expression identity to act on. + r#"{"7":[[0,50,10],[50,100,3]]}"#, + r#"{"7":[10]}"#, + r#"{"7":[]}"#, + // Neither a region-keyed cursor, an expression-keyed one, nor a stateable + // cursor at all. + r#"{"7":true}"#, + r#"{"7":null}"#, + ] { + let exts = + HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value.to_string())]); + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + assert!( + format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS), + "{value}: {err}" + ); + } + } + + /// The writer and the reader agree on the one surviving format: a region with two slices, + /// one bounded and one not, encodes to the expression-keyed shape and decodes back to the + /// very cursors it was written from. + #[test] + fn test_encode_incremental_after_seqs_round_trips() { + let low = slice_expr(0, 50); + let high = slice_expr(50, 100); + let low_json = serde_json::to_string(&low).unwrap(); + let high_json = serde_json::to_string(&high).unwrap(); + let cursors = BTreeMap::from([ + (1, vec![CursorShard::whole_domain(10)]), + ( + 2, + vec![ + CursorShard::new(Some(low.clone()), 10).with_until(15), + CursorShard::new(Some(high.clone()), 3), + ], + ), + ]); + + let json = encode_incremental_after_seqs(&cursors).unwrap(); + // Compared as JSON: the order of the object keys is serde_json's business, the + // identity, the sequence and the optional bound are what the wire states. Every region + // states the same version, and only a slice that carries a bound states `until`. + assert_eq!( + serde_json::json!({ + "1": {"version": 2, "shards": [{"expr": null, "seq": 10}]}, + "2": { + "version": 2, + "shards": [ + {"expr": low, "seq": 10, "until": 15}, + {"expr": high, "seq": 3}, + ] + }, + }), + serde_json::from_str::(&json).unwrap() + ); + + // The bytes themselves: `serde_json` keeps object keys sorted, so "shards" precedes + // "version" and "expr" precedes "seq". + assert_eq!( + format!( + r#"{{"1":{{"shards":[{{"expr":null,"seq":10}}],"version":2}},"2":{{"shards":[{{"expr":{},"seq":10,"until":15}},{{"expr":{},"seq":3}}],"version":2}}}}"#, + low_json, high_json, + ), + json + ); + + // The reader of this build reads it back as the cursors it was written from. + let exts = HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), json)]); + let parsed = FlowQueryExtensions::parse_flow_extensions(&exts) + .unwrap() + .unwrap(); + assert_eq!( + parsed.incremental_after_seqs, + Some( + cursors + .into_iter() + .collect::>>() + ) ); } diff --git a/src/session/src/context.rs b/src/session/src/context.rs index 65a62a249d3..eb59a6ac499 100644 --- a/src/session/src/context.rs +++ b/src/session/src/context.rs @@ -89,6 +89,42 @@ pub fn generate_remote_query_id_value() -> QueryId { QueryId::new() } +/// The partition-expression identity the scans of one query stated for one region, i.e. which +/// part of the region's value domain the snapshot they read under covers. +/// +/// A region states its identity through its scan (`RegionScanner::snapshot_identity` in the +/// engine's terms); the engine states the identity and the pinned snapshot sequence together, so +/// a watermark reported for the region can be paired with the expression it was measured under. +/// `store-api` owns that statement; this crate only records what the scans of one query said. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ScanPartitionExpr { + /// The region's complete value domain: it has no partition expression, so the whole domain + /// is the only slice it has. Never means "not known". + WholeDomain, + /// One partition expression of the region, in the canonical `PartitionExpr::as_json_str()` + /// form a cursor entry and an observed slice also carry. + Slice(String), + /// The query's scans stated two different identities for the region, so the query states + /// none: either expression would describe a read the region did not all happen under. + Conflicting, +} + +/// The creators of the files one query's scans saw visible when they opened one region. +/// +/// It travels beside [`ScanPartitionExpr`] because both are statements about the same version +/// snapshot: the expression says which part of the region's value domain the read covered, this +/// says which other regions' rows were sitting in the region's files before the read pruned +/// anything away. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ScanVisibleFileCreators { + /// The stated set, sorted and deduplicated, never containing the region itself. It may be + /// empty, which states "no file of another region was visible" - a positive answer. + Stated(Vec), + /// The query's scans saw two different sets, so the query states none: either set would + /// leave out files another scan held. + Conflicting, +} + #[derive(Debug, Builder, Clone)] #[builder(pattern = "owned")] #[builder(build_fn(skip))] @@ -97,6 +133,17 @@ pub struct QueryContext { /// mapping of RegionId to SequenceNumber, for snapshot read, meaning that the read should only /// container data that was committed before(and include) the given sequence number snapshot_seqs: Arc>>, + /// Mappings of the RegionId to the partition-expression identity its scans read the + /// snapshot above under. Process-local: it describes what this process's scans stated, so + /// it is never transported and never accepted from a wire context. A region is absent until + /// a scan states its identity. + #[builder(default)] + scan_partition_exprs: Arc>>, + /// Mappings of the RegionId to the creators of the files its scans saw visible when they + /// opened it. Process-local, like [`Self::scan_partition_exprs`]. A region is absent until a + /// scan states a set. + #[builder(default)] + scan_visible_file_creators: Arc>>, /// Mappings of the RegionId to the minimal sequence of SST file to scan. sst_min_sequences: Arc>>, // we use Arc> for modifiable fields @@ -802,6 +849,71 @@ impl QueryContext { .insert(region_id, sequence); } + /// Records the partition-expression identity a scan of `region_id` read the query's pinned + /// snapshot under: `None` states the region's complete value domain. + /// + /// A region's first statement stands. A later scan that states another identity for the same + /// region marks it [`ScanPartitionExpr::Conflicting`]: the query then states no identity for + /// it, because each expression would describe a read the region did not all happen under. + pub fn bind_scan_partition_expr(&self, region_id: u64, partition_expr: Option) { + let stated = match partition_expr { + Some(expr) => ScanPartitionExpr::Slice(expr), + None => ScanPartitionExpr::WholeDomain, + }; + let mut exprs = self.scan_partition_exprs.write().unwrap(); + match exprs.get(®ion_id) { + Some(existing) if *existing == stated => {} + Some(_) => { + exprs.insert(region_id, ScanPartitionExpr::Conflicting); + } + None => { + exprs.insert(region_id, stated); + } + } + } + + /// Records the creators of the files a scan of `region_id` saw visible when it opened the + /// region. `creators` is sorted and deduplicated and must not contain the region itself. + /// + /// A region's first statement stands. A later scan that saw another set marks it + /// [`ScanVisibleFileCreators::Conflicting`]: the query then states none, because a set that + /// omits files another scan held would hide the regions those files' rows come from. + pub fn bind_scan_visible_file_creators(&self, region_id: u64, creators: Vec) { + let stated = ScanVisibleFileCreators::Stated(creators); + let mut sets = self.scan_visible_file_creators.write().unwrap(); + match sets.get(®ion_id) { + Some(existing) if *existing == stated => {} + Some(_) => { + sets.insert(region_id, ScanVisibleFileCreators::Conflicting); + } + None => { + sets.insert(region_id, stated); + } + } + } + + /// The creators of the files the query's scans of `region_id` saw visible when they opened + /// it, or `None` when no scan stated a set. A caller must report "unknown" for such a region + /// rather than assume it holds no file of another region. + pub fn scan_visible_file_creators(&self, region_id: u64) -> Option { + self.scan_visible_file_creators + .read() + .unwrap() + .get(®ion_id) + .cloned() + } + + /// The partition-expression identity the query's scans of `region_id` stated, or `None` when + /// no scan stated one. A caller must not report an identity for such a region rather than + /// assume the region's whole domain. + pub fn scan_partition_expr(&self, region_id: u64) -> Option { + self.scan_partition_exprs + .read() + .unwrap() + .get(®ion_id) + .cloned() + } + /// Returns `true` if the session can cast strings to numbers in MySQL style. pub fn auto_string_to_numeric(&self) -> bool { matches!(self.channel, Channel::Mysql) @@ -846,6 +958,8 @@ impl QueryContextBuilder { .current_catalog .unwrap_or_else(|| DEFAULT_CATALOG_NAME.to_string()), snapshot_seqs: self.snapshot_seqs.unwrap_or_default(), + scan_partition_exprs: self.scan_partition_exprs.unwrap_or_default(), + scan_visible_file_creators: self.scan_visible_file_creators.unwrap_or_default(), sst_min_sequences: self.sst_min_sequences.unwrap_or_default(), mutable_session_data: self.mutable_session_data.unwrap_or_default(), mutable_query_context_data: self.mutable_query_context_data.unwrap_or_default(), diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index cc50e0bc202..387fa663460 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -774,9 +774,52 @@ pub trait RegionScanner: Debug + DisplayAs + Send { /// Sets the region id that should receive query-load metrics. fn set_query_load_region_id(&mut self, region_id: RegionId); - fn snapshot_sequence(&self) -> Option { + /// The snapshot this scan reads under, or `None` when the engine states none. + /// + /// An engine that states one reads both fields from **one** version of the region, so a + /// caller that reports the scan's watermark together with the region's partition + /// expression cannot pair an expression with a watermark measured under another one. + /// `None` states nothing: a caller that must report a `(region, expression, watermark)` + /// triple reports none for such a scanner instead of assuming a value. + fn snapshot_identity(&self) -> Option { None } + + /// The sequence upper bound [`Self::snapshot_identity`] states, when it bound one at scan + /// open. A scan that inherited its bound from the caller (a fenced read) states none. + fn snapshot_sequence(&self) -> Option { + self.snapshot_identity() + .and_then(|identity| identity.bound_sequence) + } +} + +/// The identity of the snapshot one region scan reads under. +/// +/// Both fields describe the same version of the region: the sequence upper bound the scan +/// bound when it opened keeps its data inside that version, and `partition_expr` is the +/// region's partition expression that same version states. Taking them from one snapshot is +/// what makes a reported `(expression, watermark)` pair trustworthy: a concurrent repartition +/// that gives the region another expression cannot pair the old expression with the new +/// watermark, because neither is read again after the scan pinned the version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScanSnapshotIdentity { + /// The sequence upper bound the scan **bound** when it opened, or `None` when it did not + /// bind one (a caller-fenced read, whose bound the caller supplies). + pub bound_sequence: Option, + /// The region's partition expression at that snapshot, in the canonical + /// `PartitionExpr::as_json_str()` form a cursor and an observed slice also use. + /// + /// `None` states the region's **complete value domain** - the region has no partition + /// expression, so the whole domain is the only slice it has. It never means "not known". + pub partition_expr: Option, + /// The creators of the files the region had visible at that snapshot, i.e. the regions whose + /// rows its file list may hold. Read from the version's file list in memory, so what the scan + /// prunes afterwards cannot hide a file from it. + /// + /// The region itself is never listed. `Some(vec![])` states the region held no file of + /// another region, which is a positive "nothing foreign" answer; `None` states that this + /// engine does not know. + pub visible_foreign_file_creators: Option>, } pub type RegionScannerRef = Box; @@ -1681,8 +1724,19 @@ impl RegionScanner for SinglePartitionScanner { self.properties.set_query_load_region_id(region_id); } - fn snapshot_sequence(&self) -> Option { - self.snapshot_sequence + fn snapshot_identity(&self) -> Option { + Some(ScanSnapshotIdentity { + bound_sequence: self.snapshot_sequence, + // `store-api` cannot depend on `partition`, so this states the expression the + // metadata carries instead of canonicalizing it. An engine that partitions a region + // and reads it under a pinned snapshot overrides this with the identity its own scans + // state (see the mito engine), so this value only has to be right for an engine whose + // regions keep the expression they were created with. + partition_expr: self.metadata.partition_expr.clone(), + // This scanner does not hold a region file list, so it states nothing about the + // files instead of claiming the region holds none. + visible_foreign_file_creators: None, + }) } } diff --git a/src/store-api/src/storage.rs b/src/store-api/src/storage.rs index e0761f8a006..18d0d5eec4d 100644 --- a/src/store-api/src/storage.rs +++ b/src/store-api/src/storage.rs @@ -29,5 +29,5 @@ 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::{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 d71742f1c46..7d3aed9e6e7 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,55 @@ pub enum TimeSeriesDistribution { PerSeries, } +/// One slice of an incremental cursor: the partition expression selecting a region's value +/// 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 (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, + } + } + + /// 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 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)] pub struct ScanRequest { /// Optional projection information for the scan. `None` reads all root @@ -78,22 +128,41 @@ pub struct ScanRequest { pub skip_sst_files: bool, /// Whether to bind the effective snapshot upper bound when opening the scan. pub snapshot_on_scan: bool, - /// Explicit intent to read an exact row-level sequence delta `(min, max]` - /// across memtables and all SST files (Flow's `sequence_range` incremental - /// mode). The engine performs exact row-level filtering only when the region - /// preserves per-row sequences and every participating SST file is trusted; - /// otherwise it returns a structured stale/unsupported error so the caller - /// falls back instead of silently approximating. + /// Explicit intent to read an exact row-level sequence delta `(min, max]` across memtables + /// and all SST files (Flow's `sequence_range` incremental mode). Exact row-level filtering + /// happens only when the region preserves per-row sequences and every participating SST + /// file is trusted; otherwise the read **fails closed** with `SequenceRangeUnsupported` + /// (status `InvalidArguments`, retry hint `FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE`). /// /// Historical `memtable_only` reads must never set this flag. pub exact_sequence_range: bool, /// Whether this scan reads the **physical** `__sequence` column of a foreign file and hides /// the rows whose number a substitution produced. /// - /// The reader then keeps the column of any foreign file, hides the rows at or below the - /// file's own `FileMeta::substituted_up_to` cut, and reports their timestamp ranges as + /// The reader then keeps the column of any foreign file, filters its rows by + /// [`Self::creator_cursor_shards`] (**fails closed** with `SequenceRangeUnsupported` when + /// the creator's cursor is unknown), and hides the rows at or below the file's own + /// `FileMeta::substituted_up_to` cut, reporting their timestamp ranges as /// `substituted_row_ranges`. Every other reader, compaction included, leaves this `false`. 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 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`. + pub creator_cursor_shards: Option>>>, + /// Whether this read may cross a boundary a stale cursor can no longer explain (the flag's + /// name says "invalid boundary"): rows whose sequence the region can no longer vouch for + /// are returned instead of the read being refused. + /// + /// It applies no lower sequence bound to memtables, prunes at file granularity only + /// (**fails closed** with `SequenceRangeUnsupported` for a file stating no admission + /// barrier), requires no row-level exactness, and returns a superset of the windows a stale + /// cursor can no longer explain. Ordinary incremental deltas must leave it `false`. + pub read_across_invalid_boundary: bool, /// Optional hint for the distribution of time-series data. pub distribution: Option, /// Optional hint from query-driven JSON type concretization. diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index 4f6e7412ce7..5636e827941 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -24,8 +24,8 @@ use common_query::series_frame::{ PendingBatching, pack_raw_series_with, raw_series_frame_schema_with_ordering, }; use common_recordbatch::adapter::{ - RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME, SubstitutedRowRanges, - SubstitutedRowRangesReports, + ObservedPartitionExpr, RecordBatchStreamAdapter, RegionQueryStatCounters, + SERIES_SCAN_EXEC_NAME, SubstitutedRowRanges, TerminalScanReports, }; use common_recordbatch::{ DfRecordBatch, DfSendableRecordBatchStream, MemoryTrackedStream, QueryMemoryTracker, @@ -91,13 +91,15 @@ pub struct RegionScanExec { /// Dynamic filters accepted by the scanner and applied to decoded output batches. /// The wrappers themselves remain live and are updated by their producers. pushed_dyn_filters: Arc>>>, - /// The time ranges the partition streams substituted, each stream reporting them when it - /// ends. + /// What this node's partition streams stated when they ended: the other regions' files they + /// delivered rows from, the time ranges of the rows they substituted, and the + /// `(region, partition expression)` slices they read. /// - /// The scanner's stream states them in its terminal metrics, and this node is what a - /// plan-level collector can ask after the read: a rebuilt [`RecordBatchMetrics`] carries - /// figures, not the ranges a region's read stated. - substituted_row_ranges: Arc, + /// The scanner's stream states them, and this node is what a plan-level collector can ask + /// after the read: DataFusion's metrics carry figures, not an answer about what was read, and + /// a rebuilt [`RecordBatchMetrics`] cannot recover one. Shared with the clones that re-assign + /// partition ranges, so an answer stated before a re-assignment is not lost. + terminal_reports: Arc, } impl std::fmt::Debug for RegionScanExec { @@ -336,7 +338,7 @@ impl RegionScanExec { explain_verbose: false, query_memory_tracker, pushed_dyn_filters: Arc::new(Mutex::new(Vec::new())), - substituted_row_ranges: Arc::new(SubstitutedRowRangesReports::new()), + terminal_reports: Arc::new(TerminalScanReports::new()), }) } @@ -411,7 +413,7 @@ impl RegionScanExec { explain_verbose: self.explain_verbose, query_memory_tracker: self.query_memory_tracker.clone(), pushed_dyn_filters: self.pushed_dyn_filters.clone(), - substituted_row_ranges: self.substituted_row_ranges.clone(), + terminal_reports: self.terminal_reports.clone(), }) } @@ -419,12 +421,30 @@ impl RegionScanExec { self.distribution } - /// The time ranges this node's partition streams substituted, merged per region. + /// The creator regions this node's partition streams reported delivering rows from, or + /// `None` when they do not state an answer. /// - /// A partition states its ranges when its stream ends, so a caller asks after the read - /// finished; a partition that never ran contributed nothing and simply adds no range. - pub fn substituted_row_ranges(&self) -> Vec { - self.substituted_row_ranges.ranges() + /// A partition states its answer when its stream ends, so a caller asks after the read + /// finished; a partition that is still running, that never ran or that ended without an + /// answer leaves this unknown instead of answering "delivered none". + pub fn foreign_file_row_creators(&self) -> Option> { + self.terminal_reports.foreign_file_row_creators() + } + + /// The time ranges of the rows this node's partition streams substituted, per region, or + /// `None` when they do not state an answer (yet). + /// + /// Empty is the protocol's "substituted nothing": it tells a caller that recomputes the + /// windows of substituted rows that it has nothing to recompute, which is only true once the + /// partitions stated that they substituted nothing. + pub fn substituted_row_ranges(&self) -> Option> { + self.terminal_reports.substituted_row_ranges() + } + + /// The `(region, partition expression)` pairs this node's partition streams read, or `None` + /// when they do not state an answer (yet). + pub fn observed_slices(&self) -> Option> { + self.terminal_reports.observed_slices() } pub fn with_distinguish_partition_range(&self, distinguish_partition_range: bool) { @@ -699,6 +719,12 @@ impl std::fmt::Debug for SeriesScanExec { } impl SeriesScanExec { + /// Returns the region scan this leaf packs, which is also what states what the read + /// delivered, substituted and observed once its partition streams ended. + pub fn region_scan(&self) -> &RegionScanExec { + &self.scan + } + /// Returns the immutable label binding supplied to the storage scan. pub fn scan_binding(&self) -> &RawLabelSource { &self.scan_binding @@ -802,6 +828,9 @@ impl ExecutionPlan for SeriesScanExec { fn reset_state(self: Arc) -> DfResult> { self.scan.scanner.lock().unwrap().reset_state(); self.scan.pushed_dyn_filters.lock().unwrap().clear(); + // What the read stated belongs to the run that read it, so a reused plan starts with + // nothing stated instead of reporting the run before it. + self.scan.terminal_reports.reset(); Ok(self) } fn execute( @@ -908,7 +937,11 @@ impl ExecutionPlan for SeriesScanExec { span, await_timer: None, dyn_filter: None, - substituted_range_report: None, + terminal_report: Some(TerminalReport { + reports: self.scan.terminal_reports.clone(), + partition, + partitions, + }), })) } } @@ -1002,9 +1035,10 @@ impl ExecutionPlan for RegionScanExec { span, await_timer: None, dyn_filter, - substituted_range_report: Some(SubstitutedRangeReport { - reports: self.substituted_row_ranges.clone(), + terminal_report: Some(TerminalReport { + reports: self.terminal_reports.clone(), partition, + partitions: self.properties.output_partitioning().partition_count(), }), })) } @@ -1016,6 +1050,9 @@ impl ExecutionPlan for RegionScanExec { fn reset_state(self: Arc) -> DfResult> { self.scanner.lock().unwrap().reset_state(); self.pushed_dyn_filters.lock().unwrap().clear(); + // What the read stated belongs to the run that read it, so a reused plan starts with + // nothing stated instead of reporting the run before it. + self.terminal_reports.reset(); Ok(self) } @@ -1136,11 +1173,11 @@ impl DisplayAs for RegionScanExec { } } -/// Where a partition stream of [`RegionScanExec`] reports the ranges it substituted when it -/// ends. -struct SubstitutedRangeReport { - reports: Arc, +/// Where a partition stream of [`RegionScanExec`] states what it read when it ends. +struct TerminalReport { + reports: Arc, partition: usize, + partitions: usize, } pub struct StreamWithMetricWrapper { @@ -1149,8 +1186,8 @@ pub struct StreamWithMetricWrapper { span: Span, await_timer: Option, dyn_filter: Option>, - /// Where this stream states the ranges it substituted, taken once the stream ended. - substituted_range_report: Option, + /// Where this stream states what it read, taken once the stream ended. + terminal_report: Option, } impl Stream for StreamWithMetricWrapper { @@ -1195,16 +1232,16 @@ impl Stream for StreamWithMetricWrapper { } } Poll::Ready(None) => { - // The stream is over, so the ranges its metrics state now are terminal: they - // describe the rows this partition substituted, which the node has to keep for - // a plan-level collector. - if let Some(report) = this.substituted_range_report.take() { - let ranges = this - .stream - .metrics() - .map(|metrics| metrics.substituted_row_ranges) - .unwrap_or_default(); - report.reports.record(report.partition, ranges); + // The stream is over, so what its metrics state now is the terminal answer. It + // is an answer about the rows it read, which is what the plan's collector must + // see: DataFusion's own metrics carry figures only, so the creators it delivered + // rows from, the ranges it substituted and the slices it observed can only + // cross that boundary through this report. + if let Some(report) = this.terminal_report.take() { + let answer = this.stream.metrics(); + report + .reports + .record(report.partition, report.partitions, answer.as_ref()); } Poll::Ready(None) } @@ -1424,6 +1461,106 @@ mod test { ) } + /// A stream that states, when it ends, which other regions' files it delivered rows from, + /// the way a Mito region's stream does. + struct ReportedStream { + inner: SendableRecordBatchStream, + creators: Option>, + } + + impl Stream for ReportedStream { + type Item = common_recordbatch::error::Result; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_next(cx) + } + } + + impl common_recordbatch::RecordBatchStream for ReportedStream { + fn schema(&self) -> SchemaRef { + self.inner.schema() + } + + fn output_ordering(&self) -> Option<&[common_recordbatch::OrderOption]> { + self.inner.output_ordering() + } + + fn metrics(&self) -> Option { + Some(common_recordbatch::adapter::RecordBatchMetrics { + foreign_file_row_creators: self.creators.clone(), + ..Default::default() + }) + } + } + + fn reporting_region_scan(creators: Option>) -> RegionScanExec { + let (schema, _, metadata) = dynamic_filter_test_data(5688, false); + let batches = RecordBatches::try_new(schema, vec![]).unwrap(); + let stream = ReportedStream { + inner: batches.as_stream(), + creators, + }; + let scanner = Box::new(SinglePartitionScanner::new( + Box::pin(stream), + false, + metadata, + None, + )); + RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap() + } + + async fn drain_plan(plan: Arc, context: Arc) { + let partitions = plan.properties().output_partitioning().partition_count(); + for partition in 0..partitions { + let mut stream = plan.execute(partition, context.clone()).unwrap(); + while stream.try_next().await.unwrap().is_some() {} + } + } + + /// What a region scan delivered is stated by its stream when the stream ends, so the node + /// keeps that answer: DataFusion's own metrics carry figures, and a rebuilt + /// `RecordBatchMetrics` cannot recover the answer from them. + #[tokio::test] + async fn test_region_scan_keeps_the_terminal_creator_answer_of_its_stream() { + let ctx = SessionContext::new(); + + let plan = Arc::new(reporting_region_scan(Some(vec![7]))); + assert_eq!( + None, + plan.foreign_file_row_creators(), + "a scan that has not read anything states nothing, not \"delivered none\"" + ); + drain_plan(plan.clone(), ctx.task_ctx()).await; + assert_eq!( + Some(vec![7]), + plan.foreign_file_row_creators(), + "the answer the stream stated when it ended is the node's answer" + ); + + // A stream that states nothing leaves the node's answer unknown: silence is not + // "delivered none". + let plan = Arc::new(reporting_region_scan(None)); + drain_plan(plan.clone(), ctx.task_ctx()).await; + assert_eq!(None, plan.foreign_file_row_creators()); + + // One partition answers and another has nothing to say, so the answer covers only + // part of the read. + let plan = Arc::new( + reporting_region_scan(Some(vec![7])) + .with_new_partitions(vec![vec![], vec![]], 2) + .unwrap(), + ); + drain_plan(plan.clone(), ctx.task_ctx()).await; + assert_eq!( + None, + plan.foreign_file_row_creators(), + "a silent partition makes the read uncovered, not empty" + ); + } + #[test] fn assign_partition_ranges_balances_rows_deterministically() { let ranges: Vec<_> = [100, 200, 150, 250]