From 94ec9f44ffbeb5d07c7c302a7d28c99de8d2ef25 Mon Sep 17 00:00:00 2001 From: discord9 Date: Thu, 19 Nov 2026 19:43:28 +0800 Subject: [PATCH] feat(query,flow): sample every region and parse expression-keyed cursors The watermark sample no longer truncates the plan, the cursor extension carries the expression-keyed shards, and the flight test asserts that shape. Signed-off-by: discord9 --- .../src/bin/query_perf_fixture/direct_sst.rs | 2 + src/cmd/src/datanode/parquetbench.rs | 2 + src/datanode/src/region_server.rs | 65 ++- src/flow/src/batching_mode/frontend_client.rs | 1 + src/flow/src/batching_mode/state.rs | 119 ++++ src/flow/src/batching_mode/task.rs | 298 +++++++++- src/flow/src/batching_mode/task/inc.rs | 56 +- src/flow/src/batching_mode/task/test.rs | 487 +++++++++++++++- src/flow/src/lib.rs | 2 +- src/query/src/dummy_catalog.rs | 208 ++++++- src/query/src/metrics.rs | 262 ++++++++- src/query/src/options.rs | 541 +++++++++++++++++- src/servers/src/grpc/flight.rs | 133 ++++- tests-integration/src/grpc/flight.rs | 1 + 14 files changed, 2105 insertions(+), 72 deletions(-) diff --git a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs index 38211863700..e8c3e8ae509 100644 --- a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs +++ b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs @@ -315,6 +315,8 @@ fn file_meta_from_sst_info( primary_key_min: None, primary_key_max: None, preserve_row_sequence: false, + // The fixture's rows carry the numbers its own writer allocated. + substituted_up_to: None, format: Default::default(), } } diff --git a/src/cmd/src/datanode/parquetbench.rs b/src/cmd/src/datanode/parquetbench.rs index 0bdb53c39f5..4e891dab020 100644 --- a/src/cmd/src/datanode/parquetbench.rs +++ b/src/cmd/src/datanode/parquetbench.rs @@ -358,6 +358,8 @@ impl ParquetbenchCommand { primary_key_min: None, primary_key_max: None, preserve_row_sequence: false, + // The benchmark reads the file's physical column as it is written. + substituted_up_to: None, format: Default::default(), }, Arc::new(NoopFilePurger), diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 1c2c4e19550..286b960dfb3 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -1038,11 +1038,18 @@ impl RegionWatermarkStream { } fn merged_metrics(&self, mut metrics: RecordBatchMetrics) -> RecordBatchMetrics { - if metrics + // Opening the region at `snapshot_seq` bounds the region's **complete** value + // domain, so this statement is region-wide (`partition_expr: None`) and is a + // duplicate only of another region-wide statement of the same region. An entry + // about one partition expression says something narrower: dropping this one for + // it would forget that the whole region was opened, and dropping that one for + // this one would claim a slice nobody read. Both are kept, and the merge that + // follows keys them apart. + let duplicate = metrics .region_watermarks .iter() - .any(|entry| entry.region_id == self.region_id) - { + .any(|entry| entry.region_id == self.region_id && entry.partition_expr.is_none()); + if duplicate { return metrics; } @@ -1050,6 +1057,7 @@ impl RegionWatermarkStream { .region_watermarks .push(common_recordbatch::adapter::RegionWatermarkEntry { region_id: self.region_id, + partition_expr: None, watermark: Some(self.snapshot_seq), }); metrics @@ -2568,6 +2576,7 @@ mod tests { metrics.region_watermarks, vec![RegionWatermarkEntry { region_id: region_id.as_u64(), + partition_expr: None, watermark: Some(99), }] ); @@ -2591,6 +2600,7 @@ mod tests { let metrics = RecordBatchMetrics { region_watermarks: vec![RegionWatermarkEntry { region_id: region_id.as_u64(), + partition_expr: None, watermark: None, }], ..Default::default() @@ -2601,11 +2611,59 @@ mod tests { merged.region_watermarks, vec![RegionWatermarkEntry { region_id: region_id.as_u64(), + partition_expr: None, watermark: None, }] ); } + #[test] + fn test_region_watermark_stream_keeps_expression_entries_of_the_same_region() { + let schema = Arc::new(Schema::new(vec![ColumnSchema::new( + "v", + ConcreteDataType::int32_datatype(), + false, + )])); + let values: VectorRef = Arc::new(Int32Vector::from_slice([1])); + let batch = RecordBatch::new(schema.clone(), vec![values]).unwrap(); + let stream = RecordBatches::try_new(schema, vec![batch]) + .unwrap() + .as_stream(); + + let region_id = RegionId::new(42, 7); + let wrapped = RegionWatermarkStream::new(stream, region_id, 99); + let slice_metrics = RecordBatchMetrics { + region_watermarks: vec![RegionWatermarkEntry { + region_id: region_id.as_u64(), + partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()), + watermark: Some(5), + }], + ..Default::default() + }; + + let merged = wrapped.merged_metrics(slice_metrics); + assert_eq!( + merged.region_watermarks, + vec![ + RegionWatermarkEntry { + region_id: region_id.as_u64(), + partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()), + watermark: Some(5), + }, + RegionWatermarkEntry { + region_id: region_id.as_u64(), + partition_expr: None, + watermark: Some(99), + }, + ], + "the region-wide statement must not be dropped for a narrower one" + ); + + // A second region-wide statement of the same region is the duplicate to skip. + let merged_again = wrapped.merged_metrics(merged); + assert_eq!(2, merged_again.region_watermarks.len()); + } + #[tokio::test] async fn test_wrap_flow_region_watermark_stream_adds_terminal_metrics() { let region_id = RegionId::new(42, 7); @@ -2629,6 +2687,7 @@ mod tests { metrics.region_watermarks, vec![RegionWatermarkEntry { region_id: region_id.as_u64(), + partition_expr: None, watermark: Some(99), }] ); diff --git a/src/flow/src/batching_mode/frontend_client.rs b/src/flow/src/batching_mode/frontend_client.rs index 6e1184490aa..2949060a3a1 100644 --- a/src/flow/src/batching_mode/frontend_client.rs +++ b/src/flow/src/batching_mode/frontend_client.rs @@ -969,6 +969,7 @@ mod tests { metrics: RecordBatchMetrics { region_watermarks: vec![common_recordbatch::adapter::RegionWatermarkEntry { region_id: 42, + partition_expr: None, watermark: Some(99), }], ..Default::default() diff --git a/src/flow/src/batching_mode/state.rs b/src/flow/src/batching_mode/state.rs index 55307dbcdec..1ecffcd0953 100644 --- a/src/flow/src/batching_mode/state.rs +++ b/src/flow/src/batching_mode/state.rs @@ -23,6 +23,7 @@ use common_time::Timestamp; use datatypes::value::Value; use session::context::QueryContextRef; use snafu::{OptionExt, ResultExt, ensure}; +use store_api::storage::CursorShard; use tokio::sync::oneshot; use tokio::time::Instant; @@ -56,6 +57,16 @@ pub struct TaskState { /// Region id -> last consumed watermark sequence. Incremental scans use /// this as the next lower sequence bound for each source region. checkpoints: BTreeMap, + /// Region id -> the cursor of each of its partition-expression slices, when the + /// owner of this cursor knows them (Enterprise keeps a `(region, slice) -> seq` + /// cursor and writes it here). + /// + /// `checkpoints` stays the region projection every decision of this task reads: the + /// least advanced slice, because a region-level bound may not claim a sequence that + /// some slice has not consumed. The slices are only the *wire* form, so that a reader + /// holding a file adopted from the region can filter its rows by the cursor of the + /// slice the file belongs to. Empty means "only the region projection is known". + checkpoint_shards: BTreeMap>, /// Once set, the task will never attempt incremental mode again. /// Set when the flow's query shape is deterministically incompatible /// with incremental execution (e.g. unsupported aggregate expressions). @@ -86,6 +97,7 @@ impl TaskState { checkpoint_mode: CheckpointMode::FullSnapshot, pending_fenced_repair: None, checkpoints: Default::default(), + checkpoint_shards: Default::default(), incremental_disabled: false, exec_state: ExecState::Idle, shutdown_rx, @@ -131,6 +143,38 @@ impl TaskState { &self.checkpoints } + /// The expression slices of every region's cursor, when the owner knows them. + /// + /// Empty means the cursor is only known as the region projection + /// [`Self::checkpoints`] holds. + pub fn checkpoint_shards(&self) -> &BTreeMap> { + &self.checkpoint_shards + } + + /// Advance the cursor of every `(region, expression slice)` the owner proved, and + /// keep [`Self::checkpoints`] the region projection of it. + /// + /// A region-level entry is the *least* advanced slice of that region: a reader of the + /// region's own rows cannot tell which slice a row belongs to, so it may not be told + /// to start after a sequence some other slice has not consumed. + pub fn advance_checkpoint_shards(&mut self, shards: BTreeMap>) { + self.checkpoints = shards + .iter() + .filter_map(|(region_id, shards)| { + shards + .iter() + .map(|shard| shard.seq) + .min() + .map(|seq| (*region_id, seq)) + }) + .collect(); + self.checkpoint_shards = shards; + self.pending_fenced_repair = None; + if !self.incremental_disabled { + self.checkpoint_mode = CheckpointMode::Incremental; + } + } + /// Read the live dirty-window queue without exposing TaskState internals to execution owners. pub fn dirty_time_windows(&self) -> &DirtyTimeWindows { &self.dirty_time_windows @@ -160,10 +204,31 @@ impl TaskState { self.abandon_fenced_repair(); } + /// Drop every stored cursor and re-enter FullSnapshot mode from scratch. + /// + /// Unlike [`Self::mark_full_snapshot`], which keeps the checkpoint map and + /// only abandons a fenced repair, and [`Self::advance_checkpoints`], which + /// replaces the map but promotes the task back to `Incremental`, this drops + /// the cursors themselves: they belong to a data layout that no longer + /// exists (for example after a region edit reassigned which rows a region + /// owns). A fresh full-snapshot watermark proof is required before + /// incremental mode may resume. + /// + /// `incremental_disabled` is left untouched: a permanently disabled task + /// stays disabled. + pub fn reset_to_full_snapshot(&mut self) { + self.checkpoints.clear(); + self.checkpoint_shards.clear(); + self.abandon_fenced_repair(); + self.checkpoint_mode = CheckpointMode::FullSnapshot; + } + /// Replace full-snapshot checkpoints with a complete watermark proof. /// Clears fenced repair state and enters Incremental unless disabled. pub fn advance_checkpoints(&mut self, watermark_map: HashMap) { self.checkpoints = watermark_map.into_iter().collect(); + // A region-keyed proof says nothing about the slices of a region. + self.checkpoint_shards.clear(); self.pending_fenced_repair = None; if !self.incremental_disabled { self.checkpoint_mode = CheckpointMode::Incremental; @@ -182,6 +247,8 @@ impl TaskState { self.checkpoints.insert(*region_id, *seq); } } + // A region-keyed proof says nothing about the slices of a region. + self.checkpoint_shards.clear(); if !self.incremental_disabled { self.checkpoint_mode = CheckpointMode::Incremental; } @@ -232,6 +299,8 @@ impl TaskState { pub fn finish_fenced_repair(&mut self) -> Option> { let repair = self.pending_fenced_repair.take()?; self.checkpoints = repair.high; + // A repair proves region watermarks, not the slices of a region. + self.checkpoint_shards.clear(); if !self.incremental_disabled { self.checkpoint_mode = CheckpointMode::Incremental; } @@ -1408,6 +1477,56 @@ mod test { assert_eq!(state.dirty_time_windows.len(), 2); } + #[test] + fn test_reset_to_full_snapshot_drops_cursors_and_fenced_state() { + let query_ctx = QueryContext::arc(); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let mut state = TaskState::new(query_ctx, rx); + state.advance_checkpoints(HashMap::from([(1_u64, 10_u64), (2_u64, 20_u64)])); + assert_eq!(state.checkpoint_mode(), CheckpointMode::Incremental); + assert!(!state.is_incremental_disabled()); + + for second in [30, 40] { + state.dirty_time_windows.add_window( + Timestamp::new_second(second), + Some(Timestamp::new_second(second + 5)), + ); + } + state + .start_fenced_repair(BTreeMap::from([(1_u64, 10_u64)])) + .unwrap(); + assert!(state.pending_fenced_repair().is_some()); + + state.reset_to_full_snapshot(); + + // The cursors themselves are gone: they belonged to a data layout that + // no longer exists. + assert!(state.checkpoints().is_empty()); + // The fenced repair is abandoned and its pending windows return to the + // live dirty queue, so a later full snapshot still covers the backlog. + assert!(state.pending_fenced_repair().is_none()); + assert_eq!(state.dirty_time_windows.len(), 2); + assert_eq!(state.checkpoint_mode(), CheckpointMode::FullSnapshot); + // Resetting the cursors never re-enables a disabled task. + assert!(!state.is_incremental_disabled()); + } + + #[test] + fn test_reset_to_full_snapshot_keeps_incremental_disabled() { + let query_ctx = QueryContext::arc(); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let mut state = TaskState::new(query_ctx, rx); + state.advance_checkpoints(HashMap::from([(1_u64, 10_u64)])); + state.disable_incremental(); + assert!(state.is_incremental_disabled()); + + state.reset_to_full_snapshot(); + + assert!(state.checkpoints().is_empty()); + assert!(state.is_incremental_disabled()); + assert_eq!(state.checkpoint_mode(), CheckpointMode::FullSnapshot); + } + #[test] fn test_explicit_fenced_repair_windows_keep_live_windows_separate() { let mut state = state_with_past_update(Duration::from_secs(1)); diff --git a/src/flow/src/batching_mode/task.rs b/src/flow/src/batching_mode/task.rs index 48b918400c7..5a8c8606029 100644 --- a/src/flow/src/batching_mode/task.rs +++ b/src/flow/src/batching_mode/task.rs @@ -27,19 +27,21 @@ use common_query::logical_plan::breakup_insert_plan; use common_telemetry::tracing::warn; use common_telemetry::{debug, info}; use common_time::{TimeToLive, Timestamp}; +use datafusion::arrow::datatypes::{DataType, TimeUnit}; use datafusion::datasource::DefaultTableSource; use datafusion::sql::unparser::expr_to_sql; -use datafusion_common::tree_node::{Transformed, TreeNode}; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRewriter}; use datafusion_common::utils::quote_identifier; +use datafusion_common::{DFSchema, DataFusionError, Result as DfResult}; use datafusion_common::{DFSchemaRef, ScalarValue, TableReference}; -use datafusion_expr::{DmlStatement, LogicalPlan, Projection, WriteOp, col, lit}; +use datafusion_expr::{DmlStatement, Filter, LogicalPlan, Projection, WriteOp, col, lit}; use datatypes::schema::Schema; use datatypes::vectors::Helper; use futures::TryStreamExt; use query::QueryEngineRef; use query::options::{ FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE, - FLOW_RETURN_REGION_SEQ, + FLOW_REPAIR_MODE, FLOW_REPAIR_MODE_DISCOVERY, FLOW_RETURN_REGION_SEQ, }; use query::query_engine::DefaultSerializer; use session::context::QueryContextRef; @@ -200,6 +202,192 @@ fn encode_insert_plan_request( }) } +/// One round of the read-only source watermark sample. +/// +/// A region can be absent from the proved watermark map in two ways, and they mean +/// different things: +/// - it is **not** in [`Self::read_regions`]: this round never read it, so the sample +/// says nothing at all about its watermark; +/// - it **is** in [`Self::read_regions`] but has no entry in [`Self::watermarks`]: this +/// round read it and could not prove a watermark. +/// +/// Neither case is ever reported as `0`: a missing report is not a sequence, and +/// turning it into one would let a checkpoint advance past rows nobody read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RegionWatermarkSample { + /// Regions this round covered, i.e. regions the sample plan named and whose + /// terminal metrics reported them. The plan no longer truncates, so a named + /// region is opened and read to EOF and answers either "watermark unknown" or a + /// proved watermark; a region missing from this set is one the plan never named + /// (for example, a region the source route pruned), which this round did not read + /// at all. + read_regions: BTreeSet, + /// Watermarks proved for a subset of `read_regions`. + watermarks: BTreeMap, +} + +impl RegionWatermarkSample { + fn new(read_regions: BTreeSet, watermarks: BTreeMap) -> Self { + Self { + read_regions, + watermarks, + } + } + + /// Regions this round covered. A region missing here was not read this round. + pub fn read_regions(&self) -> &BTreeSet { + &self.read_regions + } + + /// Proved watermarks, always a subset of [`Self::read_regions`]. + pub fn watermarks(&self) -> &BTreeMap { + &self.watermarks + } + + /// Regions this round read without proving a watermark for them. + pub fn unproved_regions(&self) -> BTreeSet { + self.read_regions + .iter() + .copied() + .filter(|region_id| !self.watermarks.contains_key(region_id)) + .collect() + } + + /// Whether this round read no region at all. + pub fn is_empty(&self) -> bool { + self.read_regions.is_empty() + } + + /// Keeps only the proved watermarks, dropping the read/unproved distinction. + pub fn into_watermarks(self) -> BTreeMap { + self.watermarks + } +} + +/// Returns the earliest timestamp the time index unit can represent. +/// +/// Used to pin the sample below any value the source can hold: no row satisfies +/// `time_index < earliest_representable_timestamp`. +fn earliest_representable_timestamp(schema: &DFSchema, column: &str) -> Option { + schema.fields().iter().find_map(|field| { + if field.name() != column { + return None; + } + let DataType::Timestamp(unit, _) = field.data_type() else { + return None; + }; + Some(match unit { + TimeUnit::Second => Timestamp::MIN_SECOND, + TimeUnit::Millisecond => Timestamp::MIN_MILLISECOND, + TimeUnit::Microsecond => Timestamp::MIN_MICROSECOND, + TimeUnit::Nanosecond => Timestamp::MIN_NANOSECOND, + }) + }) +} + +/// Pins the time index of every source scan below every representable value, so the +/// drained sample opens each region without producing a business row. +struct ZeroRowTimeIndexRewriter { + column: String, +} + +impl TreeNodeRewriter for ZeroRowTimeIndexRewriter { + type Node = LogicalPlan; + + fn f_up(&mut self, node: Self::Node) -> DfResult> { + let LogicalPlan::TableScan(scan) = &node else { + return Ok(Transformed::no(node)); + }; + let Some(bound) = + earliest_representable_timestamp(scan.projected_schema.as_ref(), &self.column) + else { + // This source does not carry the flow's time index, so it cannot be + // pinned and the sample leaves it alone. + return Ok(Transformed::no(node)); + }; + let bound = to_df_literal(bound).map_err(|err| DataFusionError::External(Box::new(err)))?; + let filter = Filter::try_new(col(&self.column).lt(lit(bound)), Arc::new(node))?; + Ok(Transformed::yes(LogicalPlan::Filter(filter))) + } +} + +/// Builds the source-side plan of the read-only region watermark sample. +/// +/// The sample must reach **every** participating region, because a region states its +/// watermark through its own terminal metrics and only once its read finishes. A +/// single `LIMIT` over the whole plan therefore cannot be used: the frontend runs the +/// plan with `parallelism = 1`, so `LimitStream` ends after the first batch of the +/// first region and the coalesced input's remaining region clients are never opened, +/// which is exactly how watermarks went missing. `LIMIT 0` cannot be used either: the +/// frontend re-decodes the plan with optimization on and `EliminateLimit` rewrites it +/// into an `EmptyRelation`, so no region opens at all. What is left is a plan with no +/// truncating operator anywhere, which the caller drains to EOF. +/// +/// Draining must not read business rows, so the sample pins the time index below +/// every representable value: no row can satisfy that predicate, the storage layer +/// prunes the region's files and memtables against it, and each region's read still +/// opens - binding the scan-open snapshot the watermark proves - and finishes at once. +/// An empty region finishes just as immediately, so "no rows" and "not read" stay +/// distinguishable through the terminal metrics rather than through rows. +fn region_watermark_sample_plan( + input: LogicalPlan, + time_index_column: &str, + catalog: &str, + schema: &str, +) -> Result { + let mut zero_rows = ZeroRowTimeIndexRewriter { + column: time_index_column.to_string(), + }; + let input = input + .rewrite(&mut zero_rows) + .with_context(|_| DatafusionSnafu { + context: "Failed to pin the region watermark sample time index".to_string(), + })? + .data; + let projection = LogicalPlan::Projection( + Projection::try_new(vec![col(time_index_column)], Arc::new(input)).context( + DatafusionSnafu { + context: "Failed to project the region watermark source".to_string(), + }, + )?, + ); + // The decoded plan carries the source tables under their `datafusion.public` + // names; resolve them back to the flow's catalog/schema like the recovery + // window capture does, otherwise the frontend cannot find the table. + projection + .transform_down_with_subqueries(|p| { + if let LogicalPlan::TableScan(mut table_scan) = p { + let resolved = table_scan.table_name.resolve(catalog, schema); + table_scan.table_name = resolved.into(); + Ok(Transformed::yes(LogicalPlan::TableScan(table_scan))) + } else { + Ok(Transformed::no(p)) + } + }) + .with_context(|_| DatafusionSnafu { + context: "Failed to fix table ref in the region watermark plan".to_string(), + }) + .map(|transformed| transformed.data) +} + +/// Consumes an output so its terminal metrics become ready. +async fn drain_output_data(output: &mut OutputData) -> Result<(), Error> { + match output { + OutputData::AffectedRows(_) => Ok(()), + OutputData::RecordBatches(_) => Ok(()), + OutputData::Stream(stream) => { + while stream + .try_next() + .await + .map_err(BoxedError::new) + .context(ExternalSnafu)? + .is_some() + {} + Ok(()) + } + } +} + fn recovery_aggregate_input(plan: &LogicalPlan) -> Result { let plan = match plan { LogicalPlan::Projection(projection) => projection.input.as_ref(), @@ -735,6 +923,106 @@ impl BatchingTask { .await } + /// Reads the region watermarks of this flow's sources **without reading business + /// rows**, covering **every** participating region. + /// + /// This is the baseline/degraded-advance read. It asks for `flow.return_region_seq`, + /// projects only the time-index column and sends no incremental `after_seqs`, so + /// - it never runs an insert plan and never writes the sink; + /// - it does not depend on `sequence_range_capable()`. + /// + /// The sample plan carries no truncating operator (see + /// [`region_watermark_sample_plan`]), so draining it opens every source region + /// instead of the first non-empty one, and an empty region is sampled too. A + /// region states its watermark through its own terminal metrics, which are only + /// final once it has been read to EOF, so the drain - not the rows - is what makes + /// the sample complete. The result keeps "not read this round" and "read but no + /// watermark proved" apart, and never substitutes `0` for a missing report. + /// + /// Cost: the pinned time index makes every region read zero rows, so the read + /// reports metadata only. + pub async fn sample_region_watermarks( + &self, + engine: &QueryEngineRef, + frontend_client: &FrontendClient, + ) -> Result { + let query_ctx = self.query_context_snapshot(); + let plan = sql_to_df_plan(query_ctx, engine.clone(), &self.config.query, false).await?; + let input = recovery_aggregate_input(&plan)?; + let column_name = self + .config + .time_window_expr + .as_ref() + .map(|expr| expr.column_name.clone()) + .context(UnexpectedSnafu { + reason: format!( + "Flow {} region watermark query requires a time-window expression", + self.config.flow_id + ), + })?; + let catalog = &self.config.sink_table_name[0]; + let schema = &self.config.sink_table_name[1]; + let plan = region_watermark_sample_plan(input, &column_name, catalog, schema)?; + let message = DFLogicalSubstraitConvertor {} + .encode(&plan, DefaultSerializer) + .context(SubstraitEncodeLogicalPlanSnafu)?; + let request = api::v1::QueryRequest { + query: Some(api::v1::query_request::Query::LogicalPlan(message.to_vec())), + }; + let mut peer_desc = None; + // No `after_seqs`: this read must not depend on exact incremental capability. + let extensions = [(FLOW_RETURN_REGION_SEQ, "true")]; + let mut result = frontend_client + .query_with_terminal_metrics( + catalog, + schema, + request, + &extensions, + &HashMap::new(), + &mut peer_desc, + ) + .await?; + // Terminal metrics are only ready once the output is fully consumed: the drain + // is what drives every region scan to EOF, and never a row bound. + drain_output_data(&mut result.output.data).await?; + // A region is "read" only when its terminal metrics arrived for this round; a + // region without proved terminal metrics was read and still unknown. Neither + // is defaulted to a sequence. + let read_regions = result.participating_regions().context(UnexpectedSnafu { + reason: format!( + "Flow {} region watermark query returned no terminal metrics", + self.config.flow_id + ), + })?; + let watermarks = result + .region_watermark_map() + .context(UnexpectedSnafu { + reason: format!( + "Flow {} region watermark query returned no per-region watermarks", + self.config.flow_id + ), + })? + .into_iter() + .collect::>(); + Ok(RegionWatermarkSample::new(read_regions, watermarks)) + } + + /// Reads the proved region watermarks of this flow's sources. + /// + /// Convenience wrapper of [`Self::sample_region_watermarks`] for callers that only + /// need the proved bounds: a region the sample did not read, and a region it read + /// without proving a watermark, are both absent from the map - never reported as + /// `0`. Callers that must tell those two apart use the sample itself. + pub async fn query_region_watermarks( + &self, + engine: &QueryEngineRef, + frontend_client: &FrontendClient, + ) -> Result, Error> { + self.sample_region_watermarks(engine, frontend_client) + .await + .map(RegionWatermarkSample::into_watermarks) + } + /// Discovers windows under `lower` using a caller-frozen retention bound. /// /// The caller owns the execution guard and freezes this bound with its recovery scope. @@ -852,6 +1140,10 @@ impl BatchingTask { (FLOW_RETURN_REGION_SEQ, "true"), (FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE), (FLOW_INCREMENTAL_AFTER_SEQS, lower_json.as_str()), + // This query only discovers the windows a stale cursor can no longer + // explain; it reads rows an old cursor no longer explains and does not need + // row-level sequence exactness. + (FLOW_REPAIR_MODE, FLOW_REPAIR_MODE_DISCOVERY), ]; let mut peer_desc = None; let result = frontend_client diff --git a/src/flow/src/batching_mode/task/inc.rs b/src/flow/src/batching_mode/task/inc.rs index a980e1b9814..3d99ffc320e 100644 --- a/src/flow/src/batching_mode/task/inc.rs +++ b/src/flow/src/batching_mode/task/inc.rs @@ -21,7 +21,8 @@ use datafusion_expr::{DmlStatement, LogicalPlan}; use query::QueryEngineRef; use query::options::{ FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY, - FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE, FLOW_SINK_TABLE_ID, + FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE, FLOW_READ_ROW_SEQUENCE, FLOW_REPAIR_MODE, + FLOW_REPAIR_MODE_FENCED, FLOW_SINK_TABLE_ID, }; use snafu::ResultExt; use store_api::mito_engine_options::PRESERVE_ROW_SEQUENCE; @@ -265,6 +266,11 @@ impl BatchingTask { ) -> Result, Error> { let mut extensions = vec![("flow.return_region_seq", "true".to_string())]; + let repair_fenced = { + let state = self.state.read().unwrap(); + state.pending_fenced_repair().is_some() + }; + let incremental_checkpoints_json = { let state = self.state.read().unwrap(); if incremental_safe @@ -273,12 +279,31 @@ impl BatchingTask { && state.checkpoint_mode() == CheckpointMode::Incremental && !state.checkpoints().is_empty() { - Some(serde_json::to_string(state.checkpoints()).map_err(|err| { - UnexpectedSnafu { - reason: format!("Failed to serialize checkpoint map: {err}"), - } - .build() - })?) + let shards = state.checkpoint_shards(); + if shards.is_empty() { + // Only the region projection is known: the region-keyed form, which + // every reader understands as one slice over the whole value domain. + Some(serde_json::to_string(state.checkpoints()).map_err(|err| { + UnexpectedSnafu { + reason: format!("Failed to serialize checkpoint map: {err}"), + } + .build() + })?) + } else { + // The owner of the cursor proved its expression slices. Send them + // instead of the region projection: a reader holding a file adopted + // from another region can only filter its rows by the cursor of the + // slice the file belongs to, and the projection would hand it the + // least advanced slice of the whole region. + Some( + query::options::encode_incremental_after_seqs(shards).map_err(|err| { + UnexpectedSnafu { + reason: format!("Failed to serialize checkpoint slices: {err}"), + } + .build() + })?, + ) + } } else { None } @@ -322,6 +347,23 @@ impl BatchingTask { extensions.push((FLOW_SINK_TABLE_ID, sink_table_id.to_string())); extensions.push((FLOW_INCREMENTAL_MODE, incremental_mode.to_string())); extensions.push((FLOW_INCREMENTAL_AFTER_SEQS, checkpoints_json)); + if capable { + // A `sequence_range` delta is the only read that must split an adopted + // file into already-consumed and not-yet-consumed rows. It reads the + // physical `__sequence` column and lets the file's own substituted cut + // hide the rows whose number a compaction substituted; the hidden rows' + // windows come back in the terminal metrics so the caller can recompute + // exactly those windows. Every other reader keeps today's substitution. + extensions.push((FLOW_READ_ROW_SEQUENCE, "true".to_string())); + } + } + + // Repair reads are marked independently of the incremental branch: a fenced + // repair DML is not an incremental delta (it advances no checkpoint) yet it + // must still read rows an old cursor no longer explains, otherwise the repair it performs + // is rejected by `C < B` and recovery can never make progress. + if repair_fenced { + extensions.push((FLOW_REPAIR_MODE, FLOW_REPAIR_MODE_FENCED.to_string())); } Ok(extensions) diff --git a/src/flow/src/batching_mode/task/test.rs b/src/flow/src/batching_mode/task/test.rs index a521567dc2b..c96fe6f3cb7 100644 --- a/src/flow/src/batching_mode/task/test.rs +++ b/src/flow/src/batching_mode/task/test.rs @@ -39,7 +39,8 @@ use pretty_assertions::assert_eq; use prost::Message; use query::options::{ FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY, - FLOW_SCHEDULED_TIME_MILLIS, FLOW_SINK_TABLE_ID, QueryOptions, + FLOW_READ_ROW_SEQUENCE, FLOW_REPAIR_MODE, FLOW_REPAIR_MODE_FENCED, FLOW_SCHEDULED_TIME_MILLIS, + FLOW_SINK_TABLE_ID, QueryOptions, }; use session::context::QueryContext; use snafu::ResultExt; @@ -1449,6 +1450,7 @@ fn recovery_stream_output( .into_iter() .map(|(region_id, watermark)| RegionWatermarkEntry { region_id, + partition_expr: None, watermark, }) .collect(), @@ -1835,6 +1837,7 @@ fn output_with_region_watermarks( .into_iter() .map(|(region_id, watermark)| RegionWatermarkEntry { region_id, + partition_expr: None, watermark, }) .collect(), @@ -2982,6 +2985,11 @@ async fn test_sequence_range_producer_emits_capable_source_extensions() { FLOW_INCREMENTAL_AFTER_SEQS, serde_json::json!({"1024": 10, "2048": 20}).to_string(), ), + // A capable `sequence_range` delta is also the read that splits an adopted + // file into consumed and unconsumed rows, so the producer asks the scan for + // the physical `__sequence` column and for the substituted cut to hide the + // rows whose number a compaction substituted. + (FLOW_READ_ROW_SEQUENCE, "true".to_string()), ] ); } @@ -4707,3 +4715,480 @@ async fn test_fenced_incremental_delta_default_wrapper_rejects_before_dispatch() assert_eq!(state.checkpoints(), &BTreeMap::from([(1_u64, 10_u64)])); assert_eq!(state.checkpoint_mode(), CheckpointMode::Incremental); } + +/// Counts how many source partitions a plan actually opened and drained. +/// +/// A source region states its watermark through its own read's terminal metrics, which +/// are final only once that read reaches EOF, so "opened" and "finished" are exactly +/// what a watermark sample has to cause for every participating region. +#[derive(Debug, Default)] +struct PartitionCoverage { + opened: std::sync::atomic::AtomicUsize, + finished: std::sync::atomic::AtomicUsize, +} + +impl PartitionCoverage { + fn opened(&self) -> usize { + self.opened.load(Ordering::SeqCst) + } + + fn finished(&self) -> usize { + self.finished.load(Ordering::SeqCst) + } +} + +/// A source scan whose per-partition streams report when they open and when they end. +struct CoverageExec { + inner: Arc, + coverage: Arc, +} + +impl std::fmt::Debug for CoverageExec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CoverageExec") + .field("inner", &self.inner.name()) + .finish() + } +} + +impl datafusion::physical_plan::DisplayAs for CoverageExec { + fn fmt_as( + &self, + _t: datafusion::physical_plan::DisplayFormatType, + f: &mut std::fmt::Formatter<'_>, + ) -> std::fmt::Result { + write!(f, "CoverageExec") + } +} + +impl datafusion::physical_plan::ExecutionPlan for CoverageExec { + fn name(&self) -> &str { + self.inner.name() + } + + fn properties(&self) -> &Arc { + self.inner.properties() + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + _children: Vec>, + ) -> datafusion_common::Result> { + Ok(self) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> datafusion_common::Result { + let stream = self.inner.execute(partition, context)?; + Ok(Box::pin(CoverageStream { + inner: stream, + coverage: self.coverage.clone(), + started: false, + finished: false, + })) + } +} + +struct CoverageStream { + inner: datafusion::physical_plan::SendableRecordBatchStream, + coverage: Arc, + started: bool, + finished: bool, +} + +impl futures::Stream for CoverageStream { + type Item = datafusion_common::Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if !self.started { + // A region read opens when it is first polled, not when its stream object + // is created, which is what `MergeScanExec` does with a region client. + self.started = true; + self.coverage.opened.fetch_add(1, Ordering::SeqCst); + } + let poll = Pin::new(&mut self.inner).poll_next(cx); + if matches!(poll, Poll::Ready(None)) && !self.finished { + self.finished = true; + self.coverage.finished.fetch_add(1, Ordering::SeqCst); + } + poll + } +} + +impl datafusion::physical_plan::RecordBatchStream for CoverageStream { + fn schema(&self) -> datafusion::arrow::datatypes::SchemaRef { + self.inner.schema() + } +} + +/// A three-partition source table that records partition coverage. +#[derive(Debug)] +struct CoverageProvider { + inner: datafusion::datasource::MemTable, + coverage: Arc, +} + +#[async_trait::async_trait] +impl datafusion::catalog::TableProvider for CoverageProvider { + fn schema(&self) -> datafusion::arrow::datatypes::SchemaRef { + self.inner.schema() + } + + fn table_type(&self) -> datafusion::logical_expr::TableType { + self.inner.table_type() + } + + async fn scan( + &self, + state: &dyn datafusion::catalog::Session, + projection: Option<&Vec>, + filters: &[datafusion_expr::Expr], + limit: Option, + ) -> datafusion_common::Result> { + let plan = self.inner.scan(state, projection, filters, limit).await?; + Ok(Arc::new(CoverageExec { + inner: plan, + coverage: self.coverage.clone(), + })) + } +} + +fn timestamp_source_schema() -> datafusion::arrow::datatypes::SchemaRef { + Arc::new(datafusion::arrow::datatypes::Schema::new(vec![ + datafusion::arrow::datatypes::Field::new( + "ts", + datafusion::arrow::datatypes::DataType::Timestamp( + datafusion::arrow::datatypes::TimeUnit::Millisecond, + None, + ), + false, + ), + ])) +} + +/// Builds a three-partition source whose first partition is non-empty, i.e. the shape +/// that used to starve the sample: the first region answers and the rest are skipped. +/// +/// Every partition holds several batches so that reaching EOF takes more than one poll: +/// a read that is cancelled after the first batch must be distinguishable from one that +/// ran to completion, which is what the terminal watermark needs. +fn three_partition_timestamp_source(coverage: Arc) -> Arc { + let schema = timestamp_source_schema(); + let partition = |start: i64| { + (0..8) + .map(|step| { + let batch_start = start + step * 3; + let values = (batch_start..batch_start + 3).collect::>(); + datafusion::arrow::record_batch::RecordBatch::try_new( + schema.clone(), + vec![Arc::new( + datafusion::arrow::array::TimestampMillisecondArray::from(values), + )], + ) + .unwrap() + }) + .collect::>() + }; + let partitions = vec![partition(0), partition(100), partition(200)]; + Arc::new(CoverageProvider { + inner: datafusion::datasource::MemTable::try_new(schema, partitions).unwrap(), + coverage, + }) +} + +/// Runs the watermark sample plan over a three-partition source with +/// `parallelism = 1` and returns the partition coverage the sample caused. +async fn run_sample_over_three_partitions(shape: SampleShape) -> Arc { + let coverage = Arc::new(PartitionCoverage::default()); + let provider = three_partition_timestamp_source(coverage.clone()); + let input = datafusion_expr::LogicalPlanBuilder::scan( + datafusion_common::TableReference::bare("numbers_with_ts"), + datafusion::datasource::provider_as_source(provider), + None, + ) + .unwrap() + .build() + .unwrap(); + let (plan, expect_rows) = match shape { + SampleShape::SampleWithoutTruncation => ( + super::region_watermark_sample_plan(input, "ts", "greptime", "public").unwrap(), + // The pin makes the sample report metadata only, never a business row. + false, + ), + SampleShape::RemovedLimitOne => ( + // The removed shape: the time-index projection with one `LIMIT` over the + // whole plan, which is what truncated the sample after the first + // non-empty region. + datafusion_expr::LogicalPlanBuilder::from(input) + .project(vec![datafusion_expr::col("ts")]) + .unwrap() + .limit(0, Some(1)) + .unwrap() + .build() + .unwrap(), + true, + ), + }; + + let ctx = datafusion::prelude::SessionContext::new_with_config( + datafusion::prelude::SessionConfig::new().with_target_partitions(1), + ); + // `collect` drains the plan to EOF, exactly like `drain_output_data` does. + let batches = ctx + .execute_logical_plan(plan) + .await + .unwrap() + .collect() + .await + .unwrap(); + if expect_rows { + assert_eq!(1, batches.len(), "the removed shape returned one row"); + } else { + assert!( + batches.is_empty(), + "the sample must not produce a business row, got: {batches:?}" + ); + } + coverage +} + +/// The two plan shapes compared by +/// [`test_region_watermark_sample_reaches_every_partition_with_parallelism_one`]. +#[derive(Clone, Copy, Debug)] +enum SampleShape { + /// The sample shape this module builds: no truncating operator anywhere. + SampleWithoutTruncation, + /// The removed shape: one `LIMIT 1` over the whole plan. + RemovedLimitOne, +} + +/// The sample must reach every participating region: with `parallelism = 1` any +/// truncating operator ends the read after the first non-empty region's first batch, so +/// the remaining region reads are cancelled before EOF and never state a watermark. +#[tokio::test] +async fn test_region_watermark_sample_reaches_every_partition_with_parallelism_one() { + let sampled = run_sample_over_three_partitions(SampleShape::SampleWithoutTruncation).await; + assert_eq!( + 3, + sampled.opened(), + "every source partition must be opened, not just the first non-empty one" + ); + assert_eq!( + 3, + sampled.finished(), + "every source partition must be read to EOF so its terminal watermark is final" + ); + + // Regression for the removed shape: one `LIMIT` over the whole plan cancels the + // remaining partition reads before EOF, which is how watermarks went missing. + let truncated = run_sample_over_three_partitions(SampleShape::RemovedLimitOne).await; + assert!( + truncated.finished() < 3, + "a global LIMIT must cancel later partitions before EOF, finished: {}", + truncated.finished() + ); +} + +/// The sample plan must keep every source scan and carry no truncating operator; the +/// source rows it can return are pinned away by the time-index predicate so the drain +/// reports metadata instead of reading business rows. +#[test] +fn test_region_watermark_sample_plan_has_no_truncation_and_keeps_sources() { + let coverage = Arc::new(PartitionCoverage::default()); + let provider = three_partition_timestamp_source(coverage); + let input = datafusion_expr::LogicalPlanBuilder::scan( + datafusion_common::TableReference::bare("numbers_with_ts"), + datafusion::datasource::provider_as_source(provider), + None, + ) + .unwrap() + .build() + .unwrap(); + + let plan = super::region_watermark_sample_plan(input, "ts", "greptime", "public").unwrap(); + + let mut limits = 0; + let mut scans = 0; + let mut predicates = Vec::new(); + plan.apply(|node| { + match node { + LogicalPlan::Limit(_) => limits += 1, + LogicalPlan::TableScan(scan) => { + scans += 1; + assert_eq!( + "greptime.public.numbers_with_ts", + scan.table_name.to_string(), + "the sample must resolve source tables back to the flow's catalog/schema" + ); + } + LogicalPlan::Filter(filter) => predicates.push(filter.predicate.clone()), + _ => {} + } + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + }) + .unwrap(); + + assert_eq!( + 0, limits, + "the sample must not truncate the plan, got: {plan:?}" + ); + assert_eq!( + 1, scans, + "the sample must keep the source scan, got: {plan:?}" + ); + assert_eq!( + 1, + predicates.len(), + "the sample must pin the time index, got: {plan:?}" + ); + let expected = datafusion_expr::col("ts").lt(datafusion_expr::lit( + datafusion_common::ScalarValue::TimestampMillisecond( + Some(Timestamp::MIN_MILLISECOND.value()), + None, + ), + )); + assert_eq!( + expected, predicates[0], + "the sample must pin the time index below every representable value" + ); + let LogicalPlan::Projection(projection) = &plan else { + panic!("the sample plan must project the time index, got: {plan:?}"); + }; + assert_eq!(1, projection.expr.len()); +} + +/// A region the sample did not read and a region it read without proving a watermark +/// must stay apart, and neither may become a `0` sequence. +#[tokio::test] +async fn test_region_watermark_sample_keeps_unread_and_unproved_regions_apart() { + let TestTaskParts { + task, + query_engine, + .. + } = new_time_window_test_task_with_query( + "SELECT max(src.number) AS output_value, date_bin(INTERVAL '5 second', src.ts) AS output_window FROM numbers_with_ts AS src GROUP BY output_window", + ) + .await; + + struct WatermarkHandler { + invoked: Arc, + } + + #[async_trait::async_trait] + impl crate::batching_mode::frontend_client::GrpcQueryHandlerWithBoxedError for WatermarkHandler { + async fn do_query( + &self, + _query: api::v1::greptime_request::Request, + ctx: QueryContextRef, + ) -> std::result::Result { + self.invoked.store(true, Ordering::SeqCst); + assert_eq!(ctx.extension(FLOW_RETURN_REGION_SEQ), Some("true")); + // Region 1 proved a watermark, region 2 was read but proved none, and + // region 3 was never read this round. The sample produces no row, so the + // scripted stream is empty on purpose. + Ok(recovery_stream_output( + Vec::new(), + Some(vec![(1_u64, Some(10_u64)), (2_u64, None)]), + false, + )) + } + } + + let invoked = Arc::new(AtomicBool::new(false)); + let handler: Arc = + Arc::new(WatermarkHandler { + invoked: invoked.clone(), + }); + let frontend = + FrontendClient::from_grpc_handler(Arc::downgrade(&handler), QueryOptions::default()); + + let sample = task + .sample_region_watermarks(&query_engine, &frontend) + .await + .unwrap(); + assert!(invoked.load(Ordering::SeqCst)); + + assert_eq!( + &BTreeSet::from([1_u64, 2_u64]), + sample.read_regions(), + "the sample must report exactly the regions it read" + ); + assert_eq!( + &BTreeMap::from([(1_u64, 10_u64)]), + sample.watermarks(), + "only a proved watermark may be reported, never a fabricated zero" + ); + assert_eq!( + BTreeSet::from([2_u64]), + sample.unproved_regions(), + "a region that was read without a proved watermark must stay visible" + ); + assert!( + !sample.read_regions().contains(&3), + "a region this round did not read must not be claimed" + ); + // The proved-only wrapper drops region 2 instead of inventing a bound for it. + let proved = task + .query_region_watermarks(&query_engine, &frontend) + .await + .unwrap(); + assert_eq!(BTreeMap::from([(1_u64, 10_u64)]), proved); +} + +/// Regression: the fenced repair DML is not an incremental delta, but it must still +/// carry `flow.repair_mode=fenced`, otherwise mito2 rejects it with `C < B` and the +/// repair loop never terminates. +#[tokio::test] +async fn test_build_flow_query_extensions_marks_fenced_repair_dml() { + let (task, _) = new_test_task_engine_and_plan_with_query( + "SELECT number, ts FROM numbers_with_ts", + "numbers_with_ts", + ) + .await + .into_task_and_plan(); + + task.state + .write() + .unwrap() + .advance_checkpoints(HashMap::from([(1_u64, 10_u64)])); + task.state.write().unwrap().start_fenced_repair_windows( + BTreeMap::from([(1_u64, 10_u64)]), + vec![(Timestamp::new_second(0), Timestamp::new_second(10))], + ); + + // `can_advance_checkpoints == false`: exactly what a fenced repair DML gets. + let extensions = task + .build_flow_query_extensions(false, false) + .await + .unwrap(); + assert!( + extensions.contains(&(FLOW_REPAIR_MODE, FLOW_REPAIR_MODE_FENCED.to_string())), + "fenced repair DML must mark the repair mode, got: {extensions:?}" + ); + + // An ordinary delta (no pending repair) must not mark it. + task.state.write().unwrap().abandon_fenced_repair(); + let extensions = task.build_flow_query_extensions(true, true).await.unwrap(); + assert!( + !extensions.iter().any(|(key, _)| *key == FLOW_REPAIR_MODE), + "ordinary deltas must not mark the repair mode, got: {extensions:?}" + ); +} diff --git a/src/flow/src/lib.rs b/src/flow/src/lib.rs index 36dc7c21818..4f9d4b04b2b 100644 --- a/src/flow/src/lib.rs +++ b/src/flow/src/lib.rs @@ -45,7 +45,7 @@ pub use batching_mode::frontend_client::{ }; pub use batching_mode::task::{ BatchingExecutionGuard, BatchingTask, DirtyRestore, ExecuteOnceOutcome, PlanInfo, - QueryCoverage, TaskArgs, + QueryCoverage, RegionWatermarkSample, TaskArgs, }; pub use batching_mode::time_window::{TimeWindowExpr, find_time_window_expr}; pub use batching_mode::utils::{ diff --git a/src/query/src/dummy_catalog.rs b/src/query/src/dummy_catalog.rs index 8f0a2c7ac60..8229cfccc1b 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)] @@ -365,6 +367,21 @@ 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 read requires its snapshot to cover the region's flushed frontier: + /// it must read the selected windows completely, so it gets no file pruning and no + /// forced override. Both reads return rows a stale cursor can no longer explain. + require_flushed_frontier: 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 { @@ -376,6 +393,10 @@ impl FlowScanDecision { memtable_max_sequence: None, skip_sst_files: false, exact_sequence_range: false, + read_across_invalid_boundary: false, + require_flushed_frontier: false, + read_row_sequence: false, + creator_cursor_shards: None, } } } @@ -391,6 +412,10 @@ fn decide_flow_scan(query_ctx: &QueryContext, region_id: RegionId) -> Result 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(); @@ -831,6 +896,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 3c0043dcc09..74429112d98 100644 --- a/src/query/src/metrics.rs +++ b/src/query/src/metrics.rs @@ -17,7 +17,10 @@ use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; -use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry}; +use common_recordbatch::adapter::{ + ObservedPartitionExpr, RecordBatchMetrics, RegionWatermarkEntry, SubstitutedRange, + SubstitutedRowRanges, +}; use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream}; use common_telemetry::warn; use datafusion::physical_plan::ExecutionPlan; @@ -32,18 +35,27 @@ 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, }, } @@ -212,6 +224,16 @@ impl RecordBatchStream for RegionWatermarkMetricsStream { if !region_watermarks.is_empty() { metrics.region_watermarks = region_watermarks; } + // 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); Some(metrics) } } @@ -252,12 +274,20 @@ pub fn maybe_attach_region_watermark_metrics( pub fn terminal_recordbatch_metrics_from_plan( plan: Arc, ) -> Option { - let region_watermarks = collect_region_watermarks(plan); - if region_watermarks.is_empty() { + let region_watermarks = collect_region_watermarks(plan.clone()); + let own = RecordBatchMetrics::default(); + let substituted_row_ranges = collect_substituted_row_ranges(plan.clone(), &own); + let observed_slices = collect_observed_slices(plan, &own); + if region_watermarks.is_empty() + && substituted_row_ranges.is_empty() + && observed_slices.is_empty() + { None } else { Some(RecordBatchMetrics { region_watermarks, + substituted_row_ranges, + observed_slices, ..Default::default() }) } @@ -275,8 +305,10 @@ 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 merged = BTreeMap::::new(); let mut stack = vec![plan]; while let Some(plan) = stack.pop() { @@ -298,7 +330,91 @@ fn collect_region_watermarks(plan: Arc) -> Vec, + own: &RecordBatchMetrics, +) -> Vec { + let mut merged = BTreeMap::>::new(); + let mut merge = |entries: Vec| { + for entry in entries { + let ranges = merged.entry(entry.region_id).or_default(); + ranges.extend( + entry + .ranges + .into_iter() + .map(|range| (range.start_millis, range.end_millis)), + ); + } + }; + merge(own.substituted_row_ranges.clone()); + + 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() + { + for metrics in merge_scan.sub_stage_metrics() { + merge(metrics.substituted_row_ranges); + } + } + stack.extend(plan.children().into_iter().cloned()); + } + + 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() +} + +/// 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 +/// in standalone mode), 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() { + if let Some(merge_scan) = plan.downcast_ref::() + && !merge_scan.is_flow_sink_scan() + { + for metrics in merge_scan.sub_stage_metrics() { + merged.extend(metrics.observed_slices); + } + } + stack.extend(plan.children().into_iter().cloned()); + } + + merged.into_iter().collect() +} + +/// 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 /// @@ -316,13 +432,18 @@ fn collect_region_watermarks(plan: Arc) -> Vec, + merged: &mut BTreeMap, entries: impl IntoIterator, ) { for entry in entries { + let RegionWatermarkEntry { + region_id, + partition_expr, + watermark, + } = entry; merged - .entry(entry.region_id) - .and_modify(|existing| match entry.watermark { + .entry((region_id, partition_expr)) + .and_modify(|existing| match watermark { None => match existing { MergeState::Proved(_) => { *existing = MergeState::Unproved; @@ -345,7 +466,7 @@ fn merge_region_watermark_entries( } }, }) - .or_insert(match entry.watermark { + .or_insert(match watermark { Some(seq) => MergeState::Proved(seq), None => MergeState::Unproved, }); @@ -353,7 +474,7 @@ fn merge_region_watermark_entries( } fn merge_merge_scan_region_watermarks( - merged: &mut BTreeMap, + merged: &mut BTreeMap, regions: impl IntoIterator, sub_stage_metrics: impl IntoIterator, ) { @@ -372,7 +493,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 @@ -380,27 +503,31 @@ 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, }), ); } -fn finalize_region_watermarks(merged: BTreeMap) -> Vec { +fn finalize_region_watermarks( + merged: BTreeMap, +) -> Vec { merged .into_iter() - .map(|(region_id, state)| RegionWatermarkEntry { + .map(|((region_id, partition_expr), 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 + "Conflicting proved watermarks for region {} expression {:?}: {:?}; degrading to unproved", + region_id, partition_expr, watermarks ); None } }, + partition_expr, }) .collect() } @@ -471,6 +598,7 @@ mod tests { .iter() .map(|(region_id, watermark)| RegionWatermarkEntry { region_id: *region_id, + partition_expr: None, watermark: *watermark, }) .collect(), @@ -478,6 +606,24 @@ mod tests { } } + 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, + }, + ) + .collect(), + ..Default::default() + } + } + fn test_merge_scan_exec(table_id: u32, query_ctx: QueryContextRef) -> Arc { let session_state = SessionStateBuilder::new().with_default_features().build(); let plan = LogicalPlanBuilder::empty(false).build().unwrap(); @@ -534,6 +680,7 @@ mod tests { .region_watermarks, vec![RegionWatermarkEntry { region_id: RegionId::new(43, 0).as_u64(), + partition_expr: None, watermark: None, }] ); @@ -550,10 +697,12 @@ mod tests { vec![ RegionWatermarkEntry { region_id: 1, + partition_expr: None, watermark: None, }, RegionWatermarkEntry { region_id: 2, + partition_expr: None, watermark: None, }, ] @@ -577,11 +726,77 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 42, + partition_expr: None, watermark: Some(7), }] ); } + /// 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), + }, + RegionWatermarkEntry { + region_id: 42, + partition_expr: Some("k0 < 10".to_string()), + watermark: Some(5), + }, + RegionWatermarkEntry { + region_id: 42, + partition_expr: Some("k0 >= 10".to_string()), + watermark: Some(7), + }, + ] + ); + } + + /// 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, + }] + ); + } + #[test] fn merge_merge_scan_region_watermarks_degrades_conflicting_proved_values() { let mut merged = BTreeMap::new(); @@ -599,6 +814,7 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 7, + partition_expr: None, watermark: None, }] ); @@ -621,6 +837,7 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, }] ); @@ -643,6 +860,7 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, }] ); @@ -663,6 +881,7 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, }] ); @@ -683,6 +902,7 @@ mod tests { finalize_region_watermarks(merged), vec![RegionWatermarkEntry { region_id: 9, + partition_expr: None, watermark: None, }] ); diff --git a/src/query/src/options.rs b/src/query/src/options.rs index a420ebe5d12..b0bfd4ce1ab 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,35 @@ 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. +/// +/// Only Flow's `sequence_range` incremental delta sets it. The barrier makes an adopted +/// row indistinguishable from one the import published, so the delta cannot tell which +/// adopted rows its checkpoint already consumed. With this option the scan keeps the +/// physical column, hides the rows whose number is at or below the file's own substituted +/// cut (`FileMeta::substituted_up_to`), and reports the time ranges of those substituted +/// rows in the terminal metrics (`substituted_row_ranges`) so Flow recomputes exactly +/// those windows. +/// Every other read leaves it off and keeps the substitution. +pub const FLOW_READ_ROW_SEQUENCE: &str = "flow.read_row_sequence"; pub const FLOW_SINK_TABLE_ID: &str = "flow.sink_table_id"; /// Flow scheduler binding for the logical time of one scheduled attempt. /// Query planning, SQL/TQL parsing, range-select rewrite and DataFusion @@ -38,6 +68,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"; @@ -182,14 +235,26 @@ 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 + /// substitution produced (see [FLOW_READ_ROW_SEQUENCE]). + pub read_row_sequence: bool, } impl FlowQueryExtensions { @@ -202,6 +267,8 @@ impl FlowQueryExtensions { let has_flow_context = extensions.contains_key(FLOW_INCREMENTAL_AFTER_SEQS) || extensions.contains_key(FLOW_INCREMENTAL_MODE) || 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 { @@ -235,6 +302,17 @@ 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())) + .transpose()? + .unwrap_or(false); + let sink_table_id = extensions .get(FLOW_SINK_TABLE_ID) .map(|value| { @@ -274,7 +352,9 @@ impl FlowQueryExtensions { incremental_after_seqs, incremental_mode, return_region_seq, + repair_mode, sink_table_id, + read_row_sequence, })) } @@ -316,6 +396,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. @@ -356,7 +465,34 @@ 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. +/// +/// The key is explicit because an expression identity is *not* interchangeable with a +/// projection of it: no reader can turn a projected interval back into the expression it +/// came from. A producer that writes an expression identity therefore states the version it +/// speaks, and a reader refuses a version it does not know instead of guessing. +const CURSOR_SHARD_VERSION_KEY: &str = "version"; +/// The version this build writes and reads: one partition expression per slice. +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"; + +/// Parses [`FLOW_INCREMENTAL_AFTER_SEQS`] in every shape it has taken. +/// +/// * expression-keyed (current, version 2): +/// `{"": {"version": 2, "shards": [{"expr": "", "seq": +/// seq}, {"expr": null, "seq": seq}, ...]}}` — one cursor per partition expression of +/// that region, `null` selecting the region's complete value domain. `expr` is the JSON +/// form `PartitionExpr::as_json_str()` writes and is validated here, so an expression +/// identity that does not decode never reaches a scan; +/// * region-keyed: `{"": seq}` — one cursor for the region's complete value +/// domain, i.e. the single whole-domain slice. A reader that only knows the holder's +/// cursor keeps working, and it states exactly what it always stated. +/// +/// 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 {}: {} ({})", @@ -365,7 +501,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 {}: {}", @@ -373,32 +509,194 @@ 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}` slice. +fn parse_cursor_shard(region_id: u64, shard: &serde_json::Value) -> Result { + let serde_json::Value::Object(fields) = shard else { + return Err(invalid_query_context_extension(format!( + "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)?; + + Ok(CursorShard::new(partition_expr, seq)) +} + +/// Checks that `expr` is a partition expression this build can read back, and returns the +/// identity to store. +/// +/// The identity travels through `store-api`, which cannot depend on `partition`, so this +/// is the last place a malformed expression could be rejected before a scan has to fall +/// back to the whole domain for it. +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 (version [`CURSOR_SHARD_VERSION`]) form +/// of [`FLOW_INCREMENTAL_AFTER_SEQS`], which [`parse_incremental_after_seqs`] reads back. +/// +/// This is the wire form the producer keeps: projecting the slices of a region onto the +/// least advanced one would tell the reader to re-read the rows of every other slice, and +/// writing the interval a slice was projected from would lose the expression identity the +/// reader needs to decide which slice a file belongs to. A whole-domain slice is written +/// as an explicit `"expr": null`. +pub fn encode_incremental_after_seqs(cursors: &BTreeMap>) -> Result { + let encoded = cursors + .iter() + .map(|(region_id, shards)| { + let shards = shards + .iter() + .map(|shard| { + serde_json::json!({ + CURSOR_SHARD_EXPR_KEY: shard.partition_expr, + CURSOR_SHARD_SEQ_KEY: shard.seq, + }) + }) + .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), @@ -549,8 +847,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(); @@ -614,7 +925,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)); @@ -642,7 +956,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)])])) ); } @@ -719,7 +1033,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)]), + ]) ); } @@ -804,7 +1121,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()); @@ -863,7 +1180,179 @@ 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)); + } + + /// 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}" + ); + } + } + + /// Old bytes must not be reinterpreted as new semantics, in either direction: an + /// unknown version is refused and the version marker is mandatory for an object value. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_unknown_version() { + for value in [ + // A version this build does not know. + r#"{"7":{"version":3,"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}" + ); + } + } + + #[test] + fn test_encode_incremental_after_seqs_round_trips() { + let low = slice_expr(0, 50); + let high = slice_expr(50, 100); + let cursors = BTreeMap::from([ + (1, vec![CursorShard::whole_domain(10)]), + ( + 2, + vec![ + CursorShard::new(Some(low.clone()), 10), + 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 and the sequence are what the wire states. + assert_eq!( + serde_json::json!({ + "1": {"version": 2, "shards": [{"expr": null, "seq": 10}]}, + "2": { + "version": 2, + "shards": [ + {"expr": low, "seq": 10}, + {"expr": high, "seq": 3}, + ] + }, + }), + serde_json::from_str::(&json).unwrap() + ); + + 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/servers/src/grpc/flight.rs b/src/servers/src/grpc/flight.rs index d5759cc833e..6d8d1b0c4ac 100644 --- a/src/servers/src/grpc/flight.rs +++ b/src/servers/src/grpc/flight.rs @@ -646,10 +646,14 @@ fn output_to_flight_record_batch_source( #[cfg(test)] mod tests { + use datatypes::value::Value; + use partition::expr::{Operand, col}; + use query::error::Error as QueryError; use query::options::{ FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_RETURN_REGION_SEQ, FLOW_SCHEDULED_TIME_MILLIS, FLOW_SINK_TABLE_ID, FlowIncrementalMode, }; + use store_api::storage::CursorShard; use tonic::metadata::{AsciiMetadataValue, MetadataMap}; use super::*; @@ -722,7 +726,22 @@ mod tests { ); assert_eq!( parsed.incremental_after_seqs, - Some(HashMap::from([(1, 10), (2, 20)])) + Some(HashMap::from([ + ( + 1, + vec![CursorShard { + partition_expr: None, + seq: 10, + }], + ), + ( + 2, + vec![CursorShard { + partition_expr: None, + seq: 20, + }], + ), + ])) ); assert!(parsed.return_region_seq); assert_eq!(parsed.sink_table_id, Some(42)); @@ -738,6 +757,118 @@ mod tests { assert_eq!(query_ctx.extension(FLOW_SINK_TABLE_ID), Some("42")); } + #[test] + fn test_flow_extensions_forward_expression_cursor_to_query_context() { + let expr = col("k0") + .gt_eq(Operand::Value(Value::UInt64(50))) + .as_json_str() + .unwrap(); + let cursor = serde_json::json!({ + "1": { + "version": 2, + "shards": [ + {"expr": expr, "seq": 10}, + {"expr": null, "seq": 15} + ] + }, + "2": {"version": 2, "shards": [{"expr": null, "seq": 20}]} + }) + .to_string(); + let extensions = vec![ + (FLOW_INCREMENTAL_MODE, "sequence_range"), + (FLOW_INCREMENTAL_AFTER_SEQS, cursor.as_str()), + ]; + let metadata_value = serde_json::to_string(&extensions).unwrap(); + let mut metadata = MetadataMap::new(); + metadata.insert( + FLOW_EXTENSIONS_METADATA_KEY, + AsciiMetadataValue::try_from(metadata_value.as_str()).unwrap(), + ); + + let flow_extensions = extract_flow_extensions(&metadata).unwrap(); + let query_ctx = + create_query_context(Channel::Grpc, None, flow_extensions, HashMap::new()).unwrap(); + assert_eq!( + query_ctx.extension(FLOW_INCREMENTAL_AFTER_SEQS), + Some(cursor.as_str()) + ); + let parsed = + query::options::FlowQueryExtensions::parse_flow_extensions(&query_ctx.extensions()) + .unwrap() + .unwrap(); + assert_eq!( + parsed.incremental_mode, + Some(FlowIncrementalMode::SequenceRange) + ); + assert_eq!( + parsed.incremental_after_seqs, + Some(HashMap::from([ + ( + 1, + vec![ + CursorShard { + partition_expr: Some(expr), + seq: 10, + }, + CursorShard { + partition_expr: None, + seq: 15, + }, + ], + ), + ( + 2, + vec![CursorShard { + partition_expr: None, + seq: 20, + }], + ), + ])) + ); + } + + #[test] + fn test_flow_extensions_reject_unknown_cursor_shapes() { + for (cursor, expected_reason) in [ + ( + r#"{"1":[[0,50,10],[50,100,3]]}"#, + "Invalid cursor value type in flow.incremental_after_seqs for region 1", + ), + ( + r#"{"1":{"shards":[{"expr":null,"seq":10}]}}"#, + "Missing cursor version in flow.incremental_after_seqs for region 1: an object value must state version 2", + ), + ( + r#"{"1":{"version":1,"shards":[{"expr":null,"seq":10}]}}"#, + "Unsupported cursor version Number(1) in flow.incremental_after_seqs for region 1: this build reads version 2", + ), + ( + r#"{"not-a-region":{"version":2,"shards":[{"expr":null,"seq":10}]}}"#, + "Invalid region id in flow.incremental_after_seqs: not-a-region", + ), + ] { + let extensions = vec![(FLOW_INCREMENTAL_AFTER_SEQS, cursor)]; + let metadata_value = serde_json::to_string(&extensions).unwrap(); + let mut metadata = MetadataMap::new(); + metadata.insert( + FLOW_EXTENSIONS_METADATA_KEY, + AsciiMetadataValue::try_from(metadata_value.as_str()).unwrap(), + ); + let flow_extensions = extract_flow_extensions(&metadata).unwrap(); + let query_ctx = + create_query_context(Channel::Grpc, None, flow_extensions, HashMap::new()).unwrap(); + let err = + query::options::FlowQueryExtensions::parse_flow_extensions(&query_ctx.extensions()) + .unwrap_err(); + match err { + QueryError::InvalidQueryContextExtension { reason, .. } => { + assert_eq!(reason, expected_reason, "cursor: {cursor}"); + } + other => panic!("unexpected error for {cursor}: {other:?}"), + } + } + } + #[test] fn test_extract_flow_extensions_rejects_invalid_json() { let mut metadata = MetadataMap::new(); diff --git a/tests-integration/src/grpc/flight.rs b/tests-integration/src/grpc/flight.rs index 80030174424..d7488bd3e08 100644 --- a/tests-integration/src/grpc/flight.rs +++ b/tests-integration/src/grpc/flight.rs @@ -1053,6 +1053,7 @@ mod test { region_watermarks, vec![RegionWatermarkEntry { region_id: expected_watermark.0, + partition_expr: None, watermark: Some(expected_watermark.1), }] );