diff --git a/src/query/src/dummy_catalog.rs b/src/query/src/dummy_catalog.rs index 689a4e472e1..6b344ecaa98 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}; @@ -39,14 +39,19 @@ 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::error::{GetRegionMetadataSnafu, InvalidQueryContextExtensionSnafu, Result}; +use crate::options::{ + FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE, + FLOW_READ_ROW_SEQUENCE, FlowIncrementalMode, FlowQueryExtensions, +}; /// Resolve to the given region (specified by [RegionId]) unconditionally. #[derive(Clone, Debug)] @@ -389,6 +394,13 @@ struct FlowScanDecision { skip_sst_files: bool, /// Whether this source scan must enforce the exact sequence range. exact_sequence_range: bool, + /// Whether the read bounds rows with cursor pieces instead of the handle's admission + /// barrier, so a file adopted from another region is split into consumed and unconsumed + /// rows. + read_row_sequence: bool, + /// The cursor pieces of every creator region, keyed by the region that allocated the + /// numbers. Only a physical row-sequence read carries them. + creator_cursor_shards: Option>>>, } impl FlowScanDecision { @@ -400,6 +412,8 @@ impl FlowScanDecision { memtable_max_sequence: None, skip_sst_files: false, exact_sequence_range: false, + read_row_sequence: false, + creator_cursor_shards: None, } } } @@ -415,6 +429,8 @@ fn decide_flow_scan(query_ctx: &QueryContext, region_id: RegionId) -> Result Result Result Result= lo AND k0 < hi`, in the form the + /// extension 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() + } + + /// A `sequence_range` query context that opts into a physical row-sequence read. + fn opted_in_sequence_range_context( + after_seqs: String, + snapshot_seqs: &[(RegionId, u64)], + ) -> QueryContext { + QueryContextBuilder::default() + .extensions(HashMap::from([ + ( + FLOW_INCREMENTAL_MODE.to_string(), + FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(), + ), + (FLOW_INCREMENTAL_AFTER_SEQS.to_string(), after_seqs), + (FLOW_READ_ROW_SEQUENCE.to_string(), "true".to_string()), + ])) + .snapshot_seqs(Arc::new(RwLock::new( + snapshot_seqs + .iter() + .map(|(id, seq)| (id.as_u64(), *seq)) + .collect::>(), + ))) + .build() + } + + fn shards_of(request: &ScanRequest) -> BTreeMap> { + request + .creator_cursor_shards + .as_deref() + .cloned() + .unwrap_or_default() + } + + /// Two pieces of one creator reach the scan request with their own bounds: a single + /// region-level lower/upper bound would deliver the rows of the piece it dropped, or drop + /// those of the piece still owed. + #[test] + fn test_scan_request_from_sequence_range_context_carries_every_piece() { + let region_id = test_region_id(); + let low = slice_expr(0, 50); + let high = slice_expr(50, 100); + let query_ctx = opted_in_sequence_range_context( + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":{},"seq":10,"until":20}},{{"expr":{},"seq":30,"until":45}}]}}}}"#, + region_id.as_u64(), + serde_json::to_string(&low).unwrap(), + serde_json::to_string(&high).unwrap() + ), + &[(region_id, 60)], + ); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(request.read_row_sequence); + assert!(request.exact_sequence_range); + assert_eq!( + shards_of(&request), + BTreeMap::from([( + region_id.as_u64(), + vec![ + CursorShard::new(Some(low), 10).with_until(20), + CursorShard::new(Some(high), 30).with_until(45), + ] + )]) + ); + // The request envelope is the least advanced piece, not the cursor of any row. + assert_eq!(request.memtable_min_sequence, Some(10)); + assert_eq!(request.memtable_max_sequence, Some(60)); + } + + /// A creator's bounds state the numbers that creator allocated, so neither the holding + /// region's snapshot nor its own floor may cap them. + #[test] + fn test_scan_request_from_sequence_range_context_keeps_a_foreign_creator_bounds() { + let region_id = test_region_id(); + let foreign_region_id = RegionId::new(region_id.table_id(), 2); + let low = slice_expr(0, 50); + let query_ctx = opted_in_sequence_range_context( + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":5,"until":50}}]}},"{}":{{"version":2,"shards":[{{"expr":{},"seq":2,"until":900}}]}}}}"#, + region_id.as_u64(), + foreign_region_id.as_u64(), + serde_json::to_string(&low).unwrap() + ), + &[(region_id, 100)], + ); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert_eq!( + shards_of(&request), + BTreeMap::from([ + ( + region_id.as_u64(), + vec![CursorShard::whole_domain(5).with_until(50)] + ), + ( + foreign_region_id.as_u64(), + vec![CursorShard::new(Some(low), 2).with_until(900)] + ), + ]), + "the holder's snapshot and floor bound only the rows the holder allocated" + ); + assert_eq!(request.memtable_min_sequence, Some(5)); + assert_eq!(request.memtable_max_sequence, Some(100)); + } + + /// A region stated as one number is its complete value domain, which is what the engine + /// reads as a whole-domain piece. + #[test] + fn test_scan_request_from_sequence_range_context_reads_a_scalar_as_whole_domain() { + let region_id = test_region_id(); + let query_ctx = opted_in_sequence_range_context( + format!(r#"{{"{}":10}}"#, region_id.as_u64()), + &[(region_id, 42)], + ); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(request.read_row_sequence); + assert_eq!( + shards_of(&request), + BTreeMap::from([(region_id.as_u64(), vec![CursorShard::whole_domain(10)])]) + ); + assert_eq!(request.memtable_min_sequence, Some(10)); + assert_eq!(request.memtable_max_sequence, Some(42)); + assert_eq!(request.sst_min_sequence, None); + } + + /// Two spellings of one creator id state that creator twice: the cursor bounded by 9 would + /// be replaced by the whole-domain scalar 2, so no request is built from the payload. + #[test] + fn test_scan_request_from_sequence_range_context_refuses_an_aliased_creator() { + let region_id = test_region_id(); + let foreign_region_id = RegionId::new(region_id.table_id(), 2); + let bounded = r#"{"version":2,"shards":[{"expr":null,"seq":2,"until":9}]}"#; + + for after_seqs in [ + format!( + r#"{{"{}":5,"{}":{},"0{}":2}}"#, + region_id.as_u64(), + foreign_region_id.as_u64(), + bounded, + foreign_region_id.as_u64() + ), + format!( + r#"{{"{}":5,"0{}":2,"{}":{}}}"#, + region_id.as_u64(), + foreign_region_id.as_u64(), + foreign_region_id.as_u64(), + bounded + ), + ] { + let query_ctx = + opted_in_sequence_range_context(after_seqs.clone(), &[(region_id, 100)]); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert_eq!(err.status_code(), StatusCode::InvalidArguments); + let message = format!("{err}"); + assert!( + message.contains("Duplicate region id"), + "{after_seqs}: {message}" + ); + } + } + + /// The opt-in does not replace the holder's snapshot binding: without a cached bound the + /// scan still binds one on open, so a stale upper bound is still rejected by the engine. + #[test] + fn test_scan_request_from_sequence_range_context_still_binds_the_holder_snapshot() { + let region_id = test_region_id(); + let query_ctx = + opted_in_sequence_range_context(format!(r#"{{"{}":10}}"#, region_id.as_u64()), &[]); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(request.read_row_sequence); + assert!(request.snapshot_on_scan); + assert_eq!(request.memtable_max_sequence, None); + assert_eq!(request.memtable_min_sequence, Some(10)); + assert!(!request.skip_sst_files); + } + + /// A region-level payload that does not opt in keeps the legacy sequence-range read: no + /// physical row sequences, no cursor pieces, and the same envelope it always carried. A + /// piece payload in the same mode is refused instead (see the refusal test below). + #[test] + fn test_scan_request_from_sequence_range_context_without_the_opt_in_stays_legacy() { + 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(), + format!(r#"{{"{}":10}}"#, region_id.as_u64()), + ), + ])) + .build(); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(!request.read_row_sequence); + assert_eq!(request.creator_cursor_shards, None); + assert!(request.exact_sequence_range); + assert_eq!(request.memtable_min_sequence, Some(10)); + assert!(request.snapshot_on_scan); + } + + /// Historical memtable-only reads never read physical row sequences, even when the query + /// states the opt-in. + #[test] + fn test_scan_request_from_memtable_only_context_never_reads_row_sequence() { + let region_id = test_region_id(); + let query_ctx = QueryContextBuilder::default() + .extensions(HashMap::from([ + ( + FLOW_INCREMENTAL_MODE.to_string(), + "memtable_only".to_string(), + ), + ( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + format!(r#"{{"{}":55}}"#, region_id.as_u64()), + ), + (FLOW_READ_ROW_SEQUENCE.to_string(), "true".to_string()), + ])) + .build(); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(!request.read_row_sequence); + assert_eq!(request.creator_cursor_shards, None); + assert!(request.skip_sst_files); + assert!(!request.exact_sequence_range); + assert_eq!(request.memtable_min_sequence, Some(55)); + } + + /// A sink scan keeps behaving like a plain read, piece cursors included, and a piece payload + /// neither reaches it nor refuses it. + #[test] + fn test_scan_request_from_sequence_range_context_keeps_sink_scans_plain() { + let region_id = test_region_id(); + let pieces = format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10,"until":20}}]}}}}"#, + region_id.as_u64() + ); + + let opted_in = opted_in_sequence_range_context(pieces.clone(), &[(region_id, 60)]); + let unopted = QueryContextBuilder::default() + .extensions(HashMap::from([ + (FLOW_INCREMENTAL_AFTER_SEQS.to_string(), pieces), + ( + FLOW_SINK_TABLE_ID.to_string(), + region_id.table_id().to_string(), + ), + ])) + .build(); + + for mut query_ctx in [opted_in, unopted] { + query_ctx.set_extension( + FLOW_SINK_TABLE_ID.to_string(), + region_id.table_id().to_string(), + ); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(!request.read_row_sequence); + assert_eq!(request.creator_cursor_shards, None); + assert_eq!(request.memtable_min_sequence, None); + assert_eq!(request.memtable_max_sequence, None); + assert!(!request.exact_sequence_range); + } + } + + /// A payload that states an inverted bound is refused where the read is lowered, so no + /// ScanRequest is built from it: reading it as unbounded would widen the delta. + #[test] + fn test_scan_request_from_sequence_range_context_refuses_an_inverted_bound() { + let region_id = test_region_id(); + let query_ctx = opted_in_sequence_range_context( + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10,"until":9}}]}}}}"#, + region_id.as_u64() + ), + &[(region_id, 60)], + ); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert_eq!(err.status_code(), StatusCode::InvalidArguments); + assert!(format!("{err}").contains("below its own cursor")); + } + + /// A field the lowering does not read may state a bound, so it is refused instead of + /// dropped. + #[test] + fn test_scan_request_from_sequence_range_context_refuses_an_unread_field() { + let region_id = test_region_id(); + let query_ctx = opted_in_sequence_range_context( + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10,"upper":20}}]}}}}"#, + region_id.as_u64() + ), + &[(region_id, 60)], + ); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert!(format!("{err}").contains("unknown field")); + } + + /// Two pieces of one creator for the same value domain state two different cursors, and + /// nothing says which one bounds a row. + #[test] + fn test_scan_request_from_sequence_range_context_refuses_an_ambiguous_piece() { + let region_id = test_region_id(); + let expr = slice_expr(0, 50); + let query_ctx = opted_in_sequence_range_context( + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":{},"seq":10}},{{"expr":{},"seq":4}}]}}}}"#, + region_id.as_u64(), + serde_json::to_string(&expr).unwrap(), + serde_json::to_string(&expr).unwrap() + ), + &[(region_id, 60)], + ); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert!(format!("{err}").contains("more than one cursor")); + } + + /// A piece payload states expressions and upper bounds that a request built from + /// region-level numbers cannot carry. Without the opt-in the lowering refuses it instead of + /// reading it as the region-level minimum. + #[test] + fn test_scan_request_from_sequence_range_context_refuses_pieces_without_the_opt_in() { + 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(), + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10,"until":20}}]}}}}"#, + region_id.as_u64() + ), + ), + ])) + .build(); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert_eq!(err.status_code(), StatusCode::InvalidArguments); + let message = format!("{err}"); + assert!(message.contains(FLOW_READ_ROW_SEQUENCE), "{message}"); + assert!(message.contains(FLOW_INCREMENTAL_AFTER_SEQS), "{message}"); + } + + /// A mode that never reads row sequences cannot enforce a piece payload either, even when + /// the query states the opt-in. + #[test] + fn test_scan_request_from_memtable_only_context_refuses_pieces() { + let region_id = test_region_id(); + let query_ctx = QueryContextBuilder::default() + .extensions(HashMap::from([ + ( + FLOW_INCREMENTAL_MODE.to_string(), + "memtable_only".to_string(), + ), + ( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10,"until":20}}]}}}}"#, + region_id.as_u64() + ), + ), + (FLOW_READ_ROW_SEQUENCE.to_string(), "true".to_string()), + ])) + .build(); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert_eq!(err.status_code(), StatusCode::InvalidArguments); + } + + /// A piece payload with no mode at all is refused too: it would otherwise become the + /// region-level read the piece form exists to replace. + #[test] + fn test_scan_request_from_incremental_context_refuses_pieces_without_a_mode() { + let region_id = test_region_id(); + let query_ctx = QueryContextBuilder::default() + .extensions(HashMap::from([( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10}}]}}}}"#, + region_id.as_u64() + ), + )])) + .build(); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert_eq!(err.status_code(), StatusCode::InvalidArguments); + } + + /// A repeated field inside a piece is refused at the lowering: raw JSON is required to state + /// it, and a covering map would keep the last `until` and widen the read. + #[test] + fn test_scan_request_from_sequence_range_context_refuses_a_repeated_piece_field() { + let region_id = test_region_id(); + let query_ctx = opted_in_sequence_range_context( + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10,"until":20,"until":60}}]}}}}"#, + region_id.as_u64() + ), + &[(region_id, 60)], + ); + + let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err(); + assert!(matches!(err, Error::InvalidQueryContextExtension { .. })); + assert_eq!(err.status_code(), StatusCode::InvalidArguments); + assert!(format!("{err}").contains("duplicate field")); + } + + /// The lowering carries the pieces without the terminal-watermark (report) intent: no + /// `flow.return_region_seq` is stated, and nothing about the pieces depends on it. + #[test] + fn test_scan_request_from_sequence_range_context_carries_pieces_without_the_watermark_intent() { + let region_id = test_region_id(); + let low = slice_expr(0, 50); + let query_ctx = opted_in_sequence_range_context( + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":{},"seq":10,"until":20}}]}}}}"#, + region_id.as_u64(), + serde_json::to_string(&low).unwrap() + ), + &[(region_id, 60)], + ); + + let request = scan_request_from_query_context(region_id, &query_ctx).unwrap(); + + assert!(!query_ctx.extensions().contains_key(FLOW_RETURN_REGION_SEQ)); + assert!(request.read_row_sequence); + assert_eq!( + shards_of(&request), + BTreeMap::from([( + region_id.as_u64(), + vec![CursorShard::new(Some(low), 10).with_until(20)] + )]) + ); + } } diff --git a/src/query/src/options.rs b/src/query/src/options.rs index fe5ec05a195..f900a5598f8 100644 --- a/src/query/src/options.rs +++ b/src/query/src/options.rs @@ -12,22 +12,29 @@ // 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; use common_base::readable_size::ReadableSize; use datafusion::config::{ConfigEntry, ConfigExtension, ExtensionOptions}; +use partition::expr::PartitionExpr; 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}; pub const FLOW_INCREMENTAL_AFTER_SEQS: &str = "flow.incremental_after_seqs"; pub const FLOW_INCREMENTAL_MODE: &str = "flow.incremental_mode"; +/// Opts an incremental read into comparing a row's physical sequence against the +/// [`FlowQueryExtensions::incremental_after_shards`] cursors, which is what lets a scan split a +/// file it adopted from another region into consumed and unconsumed rows. Only Flow's +/// `sequence_range` delta sets it. +pub const FLOW_READ_ROW_SEQUENCE: &str = "flow.read_row_sequence"; pub const FLOW_RETURN_REGION_SEQ: &str = "flow.return_region_seq"; pub const FLOW_SINK_TABLE_ID: &str = "flow.sink_table_id"; /// Flow scheduler binding for the logical time of one scheduled attempt. @@ -190,10 +197,26 @@ pub enum FlowIncrementalMode { #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct FlowQueryExtensions { - /// Maps region id -> lower exclusive sequence bound for incremental reads. + /// Maps region id -> the number the region-keyed form of [`FLOW_INCREMENTAL_AFTER_SEQS`] + /// states for it, the region's complete value domain. + /// + /// Set only for a payload that states every region as one number. A payload that states any + /// region piece by piece is carried in [`Self::incremental_after_shards`] instead, so a + /// region-level number is never derived from piece cursors and no stated bound is dropped. pub incremental_after_seqs: Option>, + /// Maps a creator region id -> every cursor piece the producer stated for it, keyed by + /// [`CursorShard::partition_expr`] (`None` for the creator's whole value domain). + /// + /// A piece bounds the rows of the value domain its expression selects with + /// `seq < row sequence <= until`. Set for a payload that states any region piece by piece; + /// a region that payload states as one number contributes its single whole-domain piece + /// ([`CursorShard::whole_domain`]). Only a physical piece read can enforce these bounds. + pub incremental_after_shards: Option>>, /// Incremental read mode requested by the caller. pub incremental_mode: Option, + /// Whether the read bounds rows with [`Self::incremental_after_shards`] instead of the + /// handle's admission barrier ([`FLOW_READ_ROW_SEQUENCE`]). + pub read_row_sequence: bool, /// Whether the caller expects per-region watermark metadata in terminal metrics. pub return_region_seq: bool, /// Optional sink table id used to distinguish source scans from sink reads. @@ -209,6 +232,7 @@ impl FlowQueryExtensions { pub fn parse_flow_extensions(extensions: &HashMap) -> Result> { let has_flow_context = extensions.contains_key(FLOW_INCREMENTAL_AFTER_SEQS) || extensions.contains_key(FLOW_INCREMENTAL_MODE) + || extensions.contains_key(FLOW_READ_ROW_SEQUENCE) || extensions.contains_key(FLOW_RETURN_REGION_SEQ) || extensions.contains_key(FLOW_SINK_TABLE_ID); @@ -232,10 +256,21 @@ impl FlowQueryExtensions { }) .transpose()?; - let incremental_after_seqs = extensions + let (incremental_after_seqs, incremental_after_shards) = match extensions .get(FLOW_INCREMENTAL_AFTER_SEQS) .map(|value| parse_incremental_after_seqs(value.as_str())) - .transpose()?; + .transpose()? + { + Some(ParsedCursors::Scalars(scalars)) => (Some(scalars), None), + Some(ParsedCursors::Pieces(pieces)) => (None, Some(pieces)), + None => (None, None), + }; + + 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 return_region_seq = extensions .get(FLOW_RETURN_REGION_SEQ) @@ -264,13 +299,19 @@ impl FlowQueryExtensions { } else { FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE }; - let after_seqs = incremental_after_seqs.as_ref().ok_or_else(|| { - invalid_query_context_extension(format!( + if incremental_after_seqs.is_none() && incremental_after_shards.is_none() { + return Err(invalid_query_context_extension(format!( "{} is required when {}={}.", FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode - )) - })?; - if after_seqs.is_empty() { + ))); + } + let states_a_cursor = incremental_after_seqs + .as_ref() + .is_some_and(|cursors| !cursors.is_empty()) + || incremental_after_shards + .as_ref() + .is_some_and(|pieces| !pieces.is_empty()); + if !states_a_cursor { return Err(invalid_query_context_extension(format!( "{} must not be empty when {}={}.", FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode @@ -280,7 +321,9 @@ impl FlowQueryExtensions { Ok(Some(Self { incremental_after_seqs, + incremental_after_shards, incremental_mode, + read_row_sequence, return_region_seq, sink_table_id, })) @@ -300,14 +343,14 @@ impl FlowQueryExtensions { } else { FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE }; - let after_seqs = self.incremental_after_seqs.as_ref().ok_or_else(|| { - invalid_query_context_extension(format!( + if !self.states_cursors() { + return Err(invalid_query_context_extension(format!( "{} is required when {}={}.", FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode - )) - })?; + ))); + } - if !after_seqs.contains_key(&source_region_id.as_u64()) { + if !self.states_cursor_for(source_region_id.as_u64()) { return Err(invalid_query_context_extension(format!( "Missing region {} in {} when {}={}.", source_region_id, FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode @@ -315,14 +358,78 @@ impl FlowQueryExtensions { } } - Ok(self.incremental_after_seqs.is_some()) + Ok(self.states_cursors()) + } + + /// Whether the payload states a region's cursor piece by piece instead of as one + /// region-level number. + /// + /// Such a payload states the expressions and upper bounds a piece read filters rows with, + /// and none of them survive in a request built from region-level numbers alone. + pub fn states_piece_cursors(&self) -> bool { + self.incremental_after_shards.is_some() + } + + /// Whether the payload states a cursor for any region, in either form. + fn states_cursors(&self) -> bool { + self.incremental_after_seqs.is_some() || self.incremental_after_shards.is_some() + } + + /// Whether the payload states a cursor for `region_id`, in either form. + fn states_cursor_for(&self, region_id: u64) -> bool { + self.incremental_after_seqs + .as_ref() + .is_some_and(|cursors| cursors.contains_key(®ion_id)) + || self + .incremental_after_shards + .as_ref() + .is_some_and(|pieces| pieces.contains_key(®ion_id)) } pub fn should_collect_region_watermark(&self) -> bool { - should_collect_region_watermark( - self.return_region_seq, - self.incremental_after_seqs.is_some(), - ) + should_collect_region_watermark(self.return_region_seq, self.states_cursors()) + } + + /// The cursor of the least advanced piece of `region_id`. + /// + /// A read of the region's own memtables and files cannot tell which piece a row belongs to, + /// so it has to start after the least advanced one: the highest bound would drop the rows of + /// a piece that has not been consumed yet. The result is a lower pruning bound for the whole + /// read, not the cursor of any row, and it is never written back as a cursor. + pub fn region_cursor(&self, region_id: u64) -> Option { + match &self.incremental_after_shards { + Some(pieces) => pieces.get(®ion_id)?.iter().map(|piece| piece.seq).min(), + None => self + .incremental_after_seqs + .as_ref()? + .get(®ion_id) + .copied(), + } + } + + /// The cursor pieces of every creator region, as a scan request carries them. + /// + /// Only a physical piece 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. The pieces are + /// carried as stated: the snapshot upper bound of the scanned region says nothing about the + /// numbers another region allocated, so it must not cap their bounds. A region-keyed payload + /// contributes one whole-domain piece per region ([`CursorShard::whole_domain`]). + pub fn creator_cursor_shards(&self) -> Option>>> { + if let Some(pieces) = &self.incremental_after_shards { + return Some(Arc::new( + pieces + .iter() + .map(|(region_id, pieces)| (*region_id, pieces.clone())) + .collect(), + )); + } + let cursors = self.incremental_after_seqs.as_ref()?; + Some(Arc::new( + cursors + .iter() + .map(|(region_id, seq)| (*region_id, vec![CursorShard::whole_domain(*seq)])) + .collect(), + )) } } @@ -364,47 +471,341 @@ fn should_collect_region_watermark( return_region_seq || has_incremental_after_seqs } -fn parse_incremental_after_seqs(value: &str) -> Result> { - let raw = serde_json::from_str::>(value).map_err(|e| { +/// Version marker of the expression-keyed cursor form. A reader refuses a version it does not +/// know. +const CURSOR_SHARD_VERSION: u64 = 2; + +/// The two shapes [`FLOW_INCREMENTAL_AFTER_SEQS`] has taken, kept apart so that a region-level +/// number is never mistaken for a piece cursor (or the reverse). +enum ParsedCursors { + /// Region-keyed: one number per region, the region's complete value domain. + Scalars(HashMap), + /// Expression-keyed: at least one region stated its cursors piece by piece. + Pieces(HashMap>), +} + +/// Parses [`FLOW_INCREMENTAL_AFTER_SEQS`] in every shape it has taken. +/// +/// * region-keyed: `{"": seq}` — one cursor for the region's complete value domain +/// ([`CursorShard::whole_domain`]). This is what a producer that only knows a region-level +/// cursor states, and it means exactly what it always meant; +/// * expression-keyed: `{"": {"version": 2, "shards": [{"expr": "" | null, "seq": seq, "until": seq?}, ...]}}` — one cursor piece per partition +/// expression of that region, `null` selecting the region's complete value domain. `until` is +/// optional, and an absent key and an explicit `null` both state no upper bound. +/// +/// A payload that states any region piece by piece is read as piece cursors for all of them, so +/// no stated expression or bound can be dropped on the way to a scan. +/// +/// A missing or unknown `version`, an unknown or repeated field, a repeated region or piece, a +/// non-expression `expr`, and a bound below its own cursor are refused: each would otherwise +/// silently change which rows the read delivers. A key that spells an id already stated is a +/// repeated region, not a new one. +fn parse_incremental_after_seqs(value: &str) -> Result { + let wire = serde_json::from_str::(value).map_err(|e| { invalid_query_context_extension(format!( "Invalid JSON for {}: {} ({})", FLOW_INCREMENTAL_AFTER_SEQS, value, e )) })?; - raw.into_iter() - .map(|(region_id, raw_seq)| { - let region_id = region_id.parse::().map_err(|_| { - invalid_query_context_extension(format!( - "Invalid region id in {}: {}", - FLOW_INCREMENTAL_AFTER_SEQS, region_id - )) - })?; + let mut scalars = HashMap::with_capacity(wire.0.len()); + let mut pieces = HashMap::with_capacity(wire.0.len()); + let mut states_pieces = false; - 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 - )) - })?, - _ => { + for (raw_region_id, cursor) in wire.0 { + let region_id = raw_region_id.parse::().map_err(|_| { + invalid_query_context_extension(format!( + "Invalid region id in {}: {}", + FLOW_INCREMENTAL_AFTER_SEQS, raw_region_id + )) + })?; + + // Both cursor forms land in `pieces`, so it remembers the ids already stated. + if pieces.contains_key(®ion_id) { + return Err(invalid_query_context_extension(format!( + "Duplicate region id {} in {}", + raw_region_id, FLOW_INCREMENTAL_AFTER_SEQS + ))); + } + + match cursor { + WireCursor::Seq(seq) => { + scalars.insert(region_id, seq); + pieces.insert(region_id, vec![CursorShard::whole_domain(seq)]); + } + WireCursor::Pieces(wire) => { + states_pieces = true; + pieces.insert(region_id, piece_cursors(region_id, wire)?); + } + } + } + + Ok(if states_pieces { + ParsedCursors::Pieces(pieces) + } else { + ParsedCursors::Scalars(scalars) + }) +} + +/// `flow.incremental_after_seqs` as the entries it states. +/// +/// A repeated region id has to be refused: a map keeps one of the two cursors without a word, +/// and the rows the dropped one no longer bounds are delivered again. +struct UniqueRegions(Vec<(String, WireCursor)>); + +impl<'de> serde::Deserialize<'de> for UniqueRegions { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct RegionsVisitor; + + impl<'de> serde::de::Visitor<'de> for RegionsVisitor { + type Value = UniqueRegions; + + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a JSON object of region id to its incremental cursor") + } + + fn visit_map(self, mut map: A) -> std::result::Result + where + A: serde::de::MapAccess<'de>, + { + use serde::de::Error as _; + + let mut regions: Vec<(String, WireCursor)> = Vec::new(); + while let Some((region_id, cursor)) = map.next_entry::()? { + if regions.iter().any(|(seen, _)| *seen == region_id) { + return Err(A::Error::custom(format!( + "Duplicate region id {} in {}", + region_id, FLOW_INCREMENTAL_AFTER_SEQS + ))); + } + regions.push((region_id, cursor)); + } + Ok(UniqueRegions(regions)) + } + } + + deserializer.deserialize_map(RegionsVisitor) + } +} + +/// One region's cursor as the extension states it: a single number for the region's complete +/// value domain, or the versioned object that names each piece. +enum WireCursor { + Seq(SequenceNumber), + Pieces(WirePieceCursors), +} + +impl<'de> serde::Deserialize<'de> for WireCursor { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct CursorVisitor; + + impl<'de> serde::de::Visitor<'de> for CursorVisitor { + type Value = WireCursor; + + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a region cursor: a sequence number or a versioned cursor object") + } + + fn visit_u64(self, seq: u64) -> std::result::Result { + Ok(WireCursor::Seq(seq)) + } + + fn visit_str(self, seq: &str) -> std::result::Result + where + E: serde::de::Error, + { + seq.parse::() + .map(WireCursor::Seq) + .map_err(|_| E::custom(format!("Invalid sequence string: {seq}"))) + } + + fn visit_map(self, map: A) -> std::result::Result + where + A: serde::de::MapAccess<'de>, + { + WirePieceCursors::deserialize(serde::de::value::MapAccessDeserializer::new(map)) + .map(WireCursor::Pieces) + } + } + + deserializer.deserialize_any(CursorVisitor) + } +} + +/// The versioned object form of one region's cursor pieces. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct WirePieceCursors { + version: u64, + shards: Vec, +} + +/// One cursor piece as the extension states it. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct WireCursorPiece { + /// Identity of the value domain this piece selects. + expr: WireExpr, + seq: WireSeq, + /// Inclusive upper bound of the piece's delta. An absent key and an explicit `null` both + /// state no bound. + #[serde(default, skip_serializing_if = "Option::is_none")] + until: Option, +} + +/// The identity of the value domain a piece selects, `null` for the region's complete value +/// domain. +/// +/// The key is required and its absence is refused: it is a different statement from an explicit +/// whole-domain `null`, so it cannot be guessed. +struct WireExpr(Option); + +impl<'de> serde::Deserialize<'de> for WireExpr { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct ExprVisitor; + + impl<'de> serde::de::Visitor<'de> for ExprVisitor { + type Value = WireExpr; + + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a partition expression identity, or null for the whole value domain") + } + + fn visit_unit(self) -> std::result::Result { + Ok(WireExpr(None)) + } + + fn visit_str(self, expr: &str) -> std::result::Result { + Ok(WireExpr(Some(expr.to_string()))) + } + + fn visit_string(self, expr: String) -> std::result::Result { + Ok(WireExpr(Some(expr))) + } + } + + deserializer.deserialize_any(ExprVisitor) + } +} + +/// A sequence number as the extension states it: a number or its decimal string. +#[derive(serde::Deserialize)] +#[serde(untagged)] +enum WireSeq { + Number(u64), + Text(String), +} + +impl WireSeq { + fn value(&self, region_id: u64) -> Result { + match self { + WireSeq::Number(seq) => Ok(*seq), + WireSeq::Text(text) => text.parse::().map_err(|_| { + invalid_query_context_extension(format!( + "Invalid sequence string in {} for region {}: {}", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, text + )) + }), + } + } +} + +/// Checks the version of one region's value and turns its pieces into cursor pieces. +fn piece_cursors(region_id: u64, wire: WirePieceCursors) -> Result> { + if wire.version != CURSOR_SHARD_VERSION { + return Err(invalid_query_context_extension(format!( + "Unsupported cursor version {} in {} for region {}: this build reads version {}", + wire.version, FLOW_INCREMENTAL_AFTER_SEQS, region_id, CURSOR_SHARD_VERSION + ))); + } + if wire.shards.is_empty() { + return Err(invalid_query_context_extension(format!( + "Region {} states no cursor piece in {}", + region_id, FLOW_INCREMENTAL_AFTER_SEQS + ))); + } + + let mut pieces = Vec::with_capacity(wire.shards.len()); + for piece in wire.shards { + let seq = piece.seq.value(region_id)?; + let until = match piece.until { + Some(until) => { + let until = until.value(region_id)?; + if until < seq { return Err(invalid_query_context_extension(format!( - "Invalid sequence value type in {} for region {}", - FLOW_INCREMENTAL_AFTER_SEQS, region_id + "Invalid cursor piece in {} for region {}: upper bound {} sits below its \ + own cursor {}, which owes no row at all", + FLOW_INCREMENTAL_AFTER_SEQS, region_id, until, seq ))); } - }; + Some(until) + } + None => None, + }; + let partition_expr = match piece.expr.0 { + Some(expr) => Some(validate_partition_expr(region_id, &expr)?), + None => None, + }; + pieces.push(match until { + Some(until) => CursorShard::new(partition_expr, seq).with_until(until), + None => CursorShard::new(partition_expr, seq), + }); + } - Ok((region_id, seq)) - }) - .collect() + reject_repeated_pieces(region_id, &pieces)?; + Ok(pieces) +} + +/// Two pieces of one region with the same expression state two different cursors for the same +/// value domain, and nothing in the payload says which of them bounds a row. +fn reject_repeated_pieces(region_id: u64, pieces: &[CursorShard]) -> Result<()> { + let mut identities = pieces + .iter() + .map(|piece| piece.partition_expr.as_deref()) + .collect::>(); + identities.sort_unstable(); + if let Some(repeated) = identities.windows(2).find(|pair| pair[0] == pair[1]) { + return Err(invalid_query_context_extension(format!( + "Region {} states more than one cursor for the partition expression {} in {}: which \ + of them bounds a row is ambiguous", + region_id, + repeated[0].unwrap_or("null"), + FLOW_INCREMENTAL_AFTER_SEQS + ))); + } + Ok(()) +} + +/// Checks that `expr` is a partition expression this build can read back, and returns the +/// identity to store. `store-api` cannot depend on `partition`, so this is the last place a +/// malformed expression is rejected. +fn validate_partition_expr(region_id: u64, expr: &str) -> Result { + match 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 + ))), + } } fn parse_bool(option_name: &str, value: &str) -> Result { @@ -557,8 +958,37 @@ 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 + /// extension 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() + } + + fn parse_after_seqs(value: &str) -> Result { + let exts = HashMap::from([(FLOW_INCREMENTAL_AFTER_SEQS.to_string(), value.to_string())]); + Ok(FlowQueryExtensions::parse_flow_extensions(&exts)? + .expect("the extension alone states flow context")) + } + + fn assert_refused(value: &str) -> String { + let err = parse_after_seqs(value).unwrap_err(); + let message = format!("{err}"); + assert!( + message.contains(FLOW_INCREMENTAL_AFTER_SEQS), + "{value}: {message}" + ); + message + } + #[test] fn test_parse_flow_extensions_returns_none_for_non_flow_query() { let exts = HashMap::new(); @@ -742,6 +1172,296 @@ mod flow_extension_tests { assert!(format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS)); } + /// The region-keyed form states a region's complete value domain, so it decodes as the + /// single whole-domain piece it always meant. + #[test] + fn test_parse_flow_extensions_after_seqs_region_form_is_the_whole_domain_piece() { + let parsed = parse_after_seqs(r#"{"7":10,"8":"20"}"#).unwrap(); + + assert_eq!( + parsed.incremental_after_seqs, + Some(HashMap::from([(7, 10), (8, 20)])) + ); + assert_eq!( + parsed.incremental_after_shards, None, + "a region-level number is not a piece cursor" + ); + assert!(!parsed.states_piece_cursors()); + assert_eq!( + parsed.creator_cursor_shards(), + Some(Arc::new(BTreeMap::from([ + (7, vec![CursorShard::whole_domain(10)]), + (8, vec![CursorShard::whole_domain(20)]), + ]))) + ); + assert_eq!(Some(10), parsed.region_cursor(7)); + assert_eq!(None, parsed.region_cursor(9)); + assert!(!parsed.read_row_sequence); + } + + /// Every piece of a region keeps its own expression, cursor and bound: a scan that received + /// one bound for the region instead would deliver the rows of the pieces it dropped. + #[test] + fn test_parse_flow_extensions_after_seqs_keeps_every_piece() { + let low = slice_expr(0, 50); + let high = slice_expr(50, 100); + let value = format!( + r#"{{"7":{{"version":2,"shards":[{{"expr":{},"seq":10,"until":20}},{{"expr":{},"seq":30,"until":45}},{{"expr":null,"seq":4}}]}}}}"#, + serde_json::to_string(&low).unwrap(), + serde_json::to_string(&high).unwrap() + ); + + let parsed = parse_after_seqs(&value).unwrap(); + + assert_eq!( + parsed.incremental_after_shards, + Some(HashMap::from([( + 7, + vec![ + CursorShard::new(Some(low), 10).with_until(20), + CursorShard::new(Some(high), 30).with_until(45), + CursorShard::whole_domain(4), + ] + )])) + ); + assert!(parsed.states_piece_cursors()); + // The region-level bound is the least advanced piece, a pruning bound only: it is not a + // cursor and is never stored as the region-keyed cursor. + assert_eq!(Some(4), parsed.region_cursor(7)); + assert_eq!(parsed.incremental_after_seqs, None); + assert_eq!( + parsed.creator_cursor_shards(), + Some(Arc::new(BTreeMap::from([( + 7, + vec![ + CursorShard::new(Some(slice_expr(0, 50)), 10).with_until(20), + CursorShard::new(Some(slice_expr(50, 100)), 30).with_until(45), + CursorShard::whole_domain(4), + ] + )]))) + ); + } + + /// A payload written before the bound existed states no `until` and keeps decoding as the + /// unbounded pieces it always stated; an explicit `null` states the same. + #[test] + fn test_parse_flow_extensions_after_seqs_v2_without_a_bound_still_reads() { + let low = slice_expr(0, 50); + let expected = Some(HashMap::from([( + 7, + vec![ + CursorShard::new(Some(low.clone()), 10), + CursorShard::whole_domain(4), + ], + )])); + + for (case, until) in [("absent", ""), ("null", r#","until":null"#)] { + let value = format!( + r#"{{"7":{{"version":2,"shards":[{{"expr":{},"seq":10{until}}},{{"expr":null,"seq":4}}]}}}}"#, + serde_json::to_string(&low).unwrap() + ); + + assert_eq!( + parse_after_seqs(&value).unwrap().incremental_after_shards, + expected, + "{case}: {value}" + ); + } + } + + /// A bound below its own cursor owes no row at all, so the payload is a mistake rather than + /// the empty delta it would otherwise be read as. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_a_bound_below_its_cursor() { + let message = + assert_refused(r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":9}]}}"#); + assert!(message.contains("below its own cursor"), "{message}"); + + // An empty delta is not inverted. + assert!( + parse_after_seqs(r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":10}]}}"#) + .is_ok() + ); + } + + /// Two pieces of one region with the same expression state two different cursors for the + /// same value domain; nothing in the payload says which one bounds a row. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_two_cursors_for_one_expression() { + let expr = slice_expr(0, 50); + let value = format!( + r#"{{"7":{{"version":2,"shards":[{{"expr":{},"seq":10}},{{"expr":{},"seq":4}}]}}}}"#, + serde_json::to_string(&expr).unwrap(), + serde_json::to_string(&expr).unwrap() + ); + let message = assert_refused(&value); + assert!(message.contains("more than one cursor"), "{message}"); + + // A whole-domain piece and an expression piece are different keys. + assert!( + parse_after_seqs(&format!( + r#"{{"7":{{"version":2,"shards":[{{"expr":null,"seq":10}},{{"expr":{},"seq":4}}]}}}}"#, + serde_json::to_string(&slice_expr(0, 50)).unwrap() + )) + .is_ok() + ); + } + + /// A field this build does not read may state a bound, so dropping it is refused instead of + /// widening the read. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_a_field_this_build_does_not_read() { + for value in [ + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"upper":20}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10}],"until":20}}"#, + ] { + let message = assert_refused(value); + assert!(message.contains("unknown field"), "{value}: {message}"); + } + } + + /// A repeated region id would silently drop one of the two cursors. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_a_repeated_region() { + let message = assert_refused(r#"{"7":10,"7":20}"#); + assert!(message.contains("Duplicate region id"), "{message}"); + } + + /// Two spellings of one region id are two entries for one region, so the map keeps one of + /// the two cursors: a whole-domain scalar would replace a bounded piece and deliver the rows + /// the bound excludes. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_an_aliased_region() { + for value in [ + r#"{"7":5,"8":{"version":2,"shards":[{"expr":null,"seq":2,"until":9}]},"08":2}"#, + r#"{"7":5,"08":2,"8":{"version":2,"shards":[{"expr":null,"seq":2,"until":9}]}}"#, + r#"{"7":5,"007":2}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":2,"until":9}]},"07":5}"#, + ] { + let message = assert_refused(value); + assert!( + message.contains("Duplicate region id"), + "{value}: {message}" + ); + } + + // A padded spelling of an id no other key states stays a region of its own, and a + // well-formed piece cursor is still read as the bound it states. + assert_eq!( + parse_after_seqs(r#"{"7":5,"8":2,"09":3}"#) + .unwrap() + .incremental_after_seqs, + Some(HashMap::from([(7, 5), (8, 2), (9, 3)])) + ); + assert_eq!( + parse_after_seqs(r#"{"8":{"version":2,"shards":[{"expr":null,"seq":2,"until":9}]}}"#) + .unwrap() + .creator_cursor_shards(), + Some(Arc::new(BTreeMap::from([( + 8, + vec![CursorShard::whole_domain(2).with_until(9)], + )]))) + ); + } + + /// A repeated field is the same hazard one level down, and a map that keeps the last value + /// would read the widest bound in the payload. Raw JSON is required to state it: an object + /// builder would normalize the duplicate away. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_a_repeated_field() { + for value in [ + // The last `until` wins in a map: 60 would widen the read past 20. + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"until":20,"until":60}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10,"seq":40}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"expr":null,"seq":10}]}}"#, + r#"{"7":{"version":2,"version":3,"shards":[{"expr":null,"seq":10}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":10}],"shards":[]}}"#, + ] { + let message = assert_refused(value); + assert!(message.contains("duplicate field"), "{value}: {message}"); + } + } + + /// A payload that states any region piece by piece is read as piece cursors for all of + /// them, so no stated bound is dropped and the whole request needs a piece read. + #[test] + fn test_parse_flow_extensions_after_seqs_mixes_forms_as_pieces() { + let parsed = parse_after_seqs( + r#"{"7":10,"8":{"version":2,"shards":[{"expr":null,"seq":5,"until":6}]}}"#, + ) + .unwrap(); + + assert!(parsed.states_piece_cursors()); + assert_eq!(parsed.incremental_after_seqs, None); + assert_eq!( + parsed.creator_cursor_shards(), + Some(Arc::new(BTreeMap::from([ + (7, vec![CursorShard::whole_domain(10)]), + (8, vec![CursorShard::whole_domain(5).with_until(6)]), + ]))) + ); + assert_eq!(Some(10), parsed.region_cursor(7)); + assert_eq!(Some(5), parsed.region_cursor(8)); + } + + /// Old bytes must not be reinterpreted as new semantics: an unknown or missing version is + /// refused rather than read without whatever the payload states. + #[test] + fn test_parse_flow_extensions_after_seqs_rejects_unknown_versions_and_shapes() { + for value in [ + r#"{"7":{"version":3,"shards":[{"expr":null,"seq":1}]}}"#, + r#"{"7":{"version":4,"shards":[{"expr":null,"seq":1}]}}"#, + r#"{"7":{"version":"2","shards":[{"expr":null,"seq":1}]}}"#, + r#"{"7":{"shards":[{"expr":null,"seq":1}]}}"#, + r#"{"7":{"version":2}}"#, + r#"{"7":{"version":2,"shards":[]}}"#, + r#"{"7":[10]}"#, + r#"{"7":{"version":2,"shards":[{"seq":1}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":7,"seq":1}]}}"#, + r#"{"7":{"version":2,"shards":["not-a-piece"]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":"not-json","seq":1}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":"","seq":1}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":1,"until":"nope"}]}}"#, + r#"{"7":{"version":2,"shards":[{"expr":null,"seq":1,"until":-1}]}}"#, + ] { + assert_refused(value); + } + } + + #[test] + fn test_parse_flow_extensions_read_row_sequence_is_off_unless_stated() { + assert!(!parse_after_seqs(r#"{"7":10}"#).unwrap().read_row_sequence); + + let exts = HashMap::from([ + ( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + r#"{"7":10}"#.to_string(), + ), + (FLOW_READ_ROW_SEQUENCE.to_string(), "TRUE".to_string()), + ]); + let parsed = FlowQueryExtensions::parse_flow_extensions(&exts) + .unwrap() + .unwrap(); + assert!(parsed.read_row_sequence); + assert!(!parsed.states_piece_cursors()); + assert_eq!( + parsed.creator_cursor_shards(), + Some(Arc::new(BTreeMap::from([( + 7, + vec![CursorShard::whole_domain(10)] + )]))) + ); + } + + #[test] + fn test_parse_flow_extensions_rejects_an_unreadable_read_row_sequence() { + let exts = HashMap::from([(FLOW_READ_ROW_SEQUENCE.to_string(), "maybe".to_string())]); + + let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err(); + assert!(format!("{err}").contains(FLOW_READ_ROW_SEQUENCE)); + } + #[test] fn test_parse_flow_extensions_invalid_sink_table_id() { let exts = HashMap::from([(FLOW_SINK_TABLE_ID.to_string(), "x".to_string())]); @@ -818,6 +1538,48 @@ mod flow_extension_tests { assert!(parsed.should_collect_region_watermark()); } + #[test] + fn test_should_collect_region_watermark_true_for_piece_cursors() { + let parsed = FlowQueryExtensions { + incremental_after_shards: Some(HashMap::from([( + 1, + vec![CursorShard::whole_domain(10)], + )])), + ..Default::default() + }; + assert!(parsed.should_collect_region_watermark()); + } + + /// The piece form states which regions it covers, and a scan of a region it does not name + /// is refused rather than read from nothing. + #[test] + fn test_validate_for_scan_reads_the_piece_form() { + let source_region_id = RegionId::new(100, 1); + let exts = HashMap::from([ + ( + FLOW_INCREMENTAL_MODE.to_string(), + FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(), + ), + ( + FLOW_INCREMENTAL_AFTER_SEQS.to_string(), + format!( + r#"{{"{}":{{"version":2,"shards":[{{"expr":null,"seq":10,"until":20}}]}}}}"#, + source_region_id.as_u64() + ), + ), + ]); + let parsed = FlowQueryExtensions::parse_flow_extensions(&exts) + .unwrap() + .unwrap(); + + assert!(parsed.states_piece_cursors()); + assert_eq!(parsed.incremental_after_seqs, None); + assert!(parsed.validate_for_scan(source_region_id).unwrap()); + + let err = parsed.validate_for_scan(RegionId::new(100, 2)).unwrap_err(); + assert!(format!("{err}").contains("Missing region")); + } + #[test] fn test_should_collect_region_watermark_from_extensions() { let exts = HashMap::from([(FLOW_RETURN_REGION_SEQ.to_string(), "true".to_string())]);