feat(store-api): carry a partition expression identity on cursor shards

A shard names the value domain by the expression itself, and the observation
of a read names the (region, expression) it consumed, so the query layer can
report what it read without projecting an expression onto a numeric range.

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-23 23:21:52 +08:00
parent 90e08d4bf0
commit 3d86dfe7bc
4 changed files with 391 additions and 12 deletions
+72 -7
View File
@@ -181,16 +181,26 @@ impl OutputMetrics {
/// Returns proved per-region watermarks.
///
/// Entries whose watermark is `None` are intentionally omitted because they
/// represent participating regions whose terminal sequence bound was not
/// provable.
/// The terminal metrics state one entry per `(region, partition expression)`. A
/// region-keyed consumer cannot claim a sequence that one of the region's expressions
/// has not reached, so a region is omitted when **any** of its entries is unproved
/// (that entry represents a participating domain whose terminal sequence bound was not
/// provable) and otherwise reports the *minimum* over its entries. With the region-wide
/// entries a pre-expression producer writes, that minimum is exactly its one value.
pub fn region_watermark_map(&self) -> Option<std::collections::HashMap<u64, u64>> {
let mut regions: std::collections::HashMap<u64, Option<u64>> = Default::default();
for entry in self.get()?.region_watermarks {
let slot = regions.entry(entry.region_id).or_insert(entry.watermark);
*slot = match (*slot, entry.watermark) {
(Some(current), Some(seq)) => Some(current.min(seq)),
_ => None,
};
}
Some(
self.get()?
.region_watermarks
regions
.into_iter()
.filter_map(|entry| entry.watermark.map(|seq| (entry.region_id, seq)))
.collect::<std::collections::HashMap<_, _>>(),
.filter_map(|(region_id, watermark)| watermark.map(|seq| (region_id, seq)))
.collect(),
)
}
@@ -1089,6 +1099,8 @@ mod tests {
use tonic::metadata::MetadataMap;
use tonic::{Code, Status};
use common_recordbatch::adapter::RegionWatermarkEntry;
use super::*;
use crate::error::TonicSnafu;
@@ -1136,6 +1148,7 @@ mod tests {
serde_json::to_string(&RecordBatchMetrics {
region_watermarks: vec![common_recordbatch::adapter::RegionWatermarkEntry {
region_id: 7,
partition_expr: None,
watermark: Some(seq),
}],
..Default::default()
@@ -1367,6 +1380,7 @@ mod tests {
metrics: RecordBatchMetrics {
region_watermarks: vec![common_recordbatch::adapter::RegionWatermarkEntry {
region_id: 7,
partition_expr: None,
watermark: Some(42),
}],
..Default::default()
@@ -1698,6 +1712,57 @@ mod tests {
);
}
#[test]
fn test_region_watermark_map_projects_expression_entries_conservatively() {
let metrics = OutputMetrics::default();
metrics.update(Some(RecordBatchMetrics {
region_watermarks: vec![
// One region, two expressions: the region may only advance to the least
// advanced of them.
RegionWatermarkEntry {
region_id: 1,
partition_expr: Some("k0 < 10".to_string()),
watermark: Some(9),
},
RegionWatermarkEntry {
region_id: 1,
partition_expr: Some("k0 >= 10".to_string()),
watermark: Some(4),
},
// One unproved expression omits the whole region.
RegionWatermarkEntry {
region_id: 2,
partition_expr: Some("k0 < 10".to_string()),
watermark: Some(7),
},
RegionWatermarkEntry {
region_id: 2,
partition_expr: Some("k0 >= 10".to_string()),
watermark: None,
},
// A region-wide entry keeps its single value.
RegionWatermarkEntry {
region_id: 3,
partition_expr: None,
watermark: Some(5),
},
],
..Default::default()
}));
assert_eq!(
metrics.region_watermark_map(),
Some(std::collections::HashMap::from([
(1_u64, 4_u64),
(3_u64, 5_u64)
]))
);
assert_eq!(
metrics.participating_regions(),
Some(std::collections::BTreeSet::from([1_u64, 2, 3]))
);
}
#[test]
fn test_output_metrics_distinguishes_empty_region_watermarks_from_absence() {
let metrics = OutputMetrics::default();
+169
View File
@@ -698,11 +698,107 @@ pub struct RecordBatchMetrics {
/// Omitted when empty for backward compatibility.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub region_watermarks: Vec<RegionWatermarkEntry>,
/// Per-region time ranges of the rows a scan deliberately substituted.
///
/// A region that re-homes files from another region cannot tell, per row, which
/// of the adopted rows its incremental consumers already saw. A read that asks
/// for the physical sequence column (Flow's incremental delta) therefore drops
/// the rows whose number a substitution produced instead of reporting them as
/// new, and reports where those rows sit so the caller recomputes those ranges.
/// The scan fails instead of guessing when it cannot decide that, so an empty
/// list means "this scan substituted nothing" and never "unknown".
///
/// Entries are ordered by region id and each region's ranges are sorted and
/// non-overlapping. Omitted when empty for backward compatibility.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub substituted_row_ranges: Vec<SubstitutedRowRanges>,
/// The `(region, partition expression)` pairs this round's scans actually read.
///
/// A scan of one region may hold files another region created, and a row's number
/// then belongs to the *creator's* domain, which the holder's cursor does not bound.
/// A durable cursor keyed by the region alone therefore cannot say which part of a
/// creator's value domain this round consumed. A scan that reads physical row
/// sequences (`ScanRequest::read_row_sequence`) reports the creator and the partition
/// expression of every file it read, so the owner of the cursor can split a
/// whole-domain entry into the slices it observed and advance only those it read.
///
/// Entries are deduplicated and sorted. Omitted when empty. The wire key states the
/// format explicitly (`observed_partition_exprs`): the previous format of this field
/// carried a numeric `[lo, hi)` projection of the same expressions, which cannot be
/// turned back into them, so old bytes must not be read as expression identities — a
/// reader of the old key ignores it instead, which leaves every cursor unadvanced.
#[serde(
default,
rename = "observed_partition_exprs",
skip_serializing_if = "Vec::is_empty"
)]
pub observed_slices: Vec<ObservedPartitionExpr>,
}
/// The partition expression of one region that a scan read rows of, i.e. one
/// `(region, partition expression)` pair.
///
/// `region_id` is the region that allocated the rows' sequences, i.e. the creator of the
/// file they were read from — this region itself for a file it wrote. `partition_expr` is
/// the identity of the expression that file states for its own rows, in the JSON form
/// `PartitionExpr::as_json_str()` writes; `None` means the file states no expression and
/// therefore covers its region's complete value domain.
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ObservedPartitionExpr {
pub region_id: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partition_expr: Option<String>,
}
impl ObservedPartitionExpr {
/// Creates the observed pair `(region_id, partition_expr)`.
pub fn new(region_id: u64, partition_expr: Option<String>) -> Self {
Self {
region_id,
partition_expr,
}
}
/// The pair covering `region_id`'s complete value domain, which is what a read of a
/// file that states no expression observed.
pub fn whole_domain(region_id: u64) -> Self {
Self::new(region_id, None)
}
}
/// The time ranges a scan substituted for one region.
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct SubstitutedRowRanges {
pub region_id: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ranges: Vec<SubstitutedRange>,
}
/// One `[start, end]` range of row timestamps, in milliseconds since the Unix epoch.
///
/// Both ends are inclusive: a caller that owns time windows must recompute every
/// window that intersects the range.
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
)]
pub struct SubstitutedRange {
pub start_millis: i64,
pub end_millis: i64,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct RegionWatermarkEntry {
pub region_id: u64,
/// Identity (`PartitionExpr::as_json_str()`) of the partition expression this entry
/// speaks about, or `None` when it speaks about the region's complete value domain.
///
/// A statement keyed by the region alone is a whole-domain statement, which is what
/// every producer of the pre-expression format states, so leaving the field out keeps
/// its meaning. A statement about one expression slice of the region says something
/// narrower and must be merged under its own key: merging the two would let a slice
/// the round did not read advance as far as one it did.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partition_expr: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub watermark: Option<u64>,
}
@@ -1850,10 +1946,12 @@ mod test {
region_watermarks: vec![
RegionWatermarkEntry {
region_id: 1,
partition_expr: None,
watermark: Some(100),
},
RegionWatermarkEntry {
region_id: 2,
partition_expr: None,
watermark: None,
},
],
@@ -1980,4 +2078,75 @@ mod test {
let value = serde_json::to_value(RecordBatchMetrics::default()).unwrap();
assert!(value.get("region_watermarks").is_none());
}
#[test]
fn test_region_watermark_entry_states_its_partition_expression() {
let metrics = RecordBatchMetrics {
region_watermarks: vec![RegionWatermarkEntry {
region_id: 1,
partition_expr: Some(r#"{"lhs":...}"#.to_string()),
watermark: Some(100),
}],
..Default::default()
};
let value = serde_json::to_value(&metrics).unwrap();
assert_eq!(
value.get("region_watermarks").unwrap(),
&json!([
{
"region_id": 1,
"partition_expr": r#"{"lhs":...}"#,
"watermark": 100
}
])
);
// A statement written before the expression field existed is a region-keyed
// statement, i.e. one about the region's complete value domain.
let mut legacy = serde_json::to_value(RecordBatchMetrics::default()).unwrap();
legacy["region_watermarks"] = json!([{ "region_id": 3 }]);
let decoded: RecordBatchMetrics = serde_json::from_value(legacy).unwrap();
assert_eq!(
decoded.region_watermarks,
vec![RegionWatermarkEntry {
region_id: 3,
partition_expr: None,
watermark: None,
}]
);
}
#[test]
fn test_observed_slices_keep_their_wire_key_and_carry_expressions() {
let metrics = RecordBatchMetrics {
observed_slices: vec![
ObservedPartitionExpr::new(7, Some(r#"{"op":"Eq"}"#.to_string())),
ObservedPartitionExpr::whole_domain(8),
],
..Default::default()
};
let value = serde_json::to_value(&metrics).unwrap();
// The old key carried a numeric `[lo, hi)` projection that cannot be turned back
// into an expression, so the identity now travels under a key of its own.
assert!(value.get("observed_slices").is_none());
assert_eq!(
value.get("observed_partition_exprs").unwrap(),
&json!([
{ "region_id": 7, "partition_expr": r#"{"op":"Eq"}"# },
{ "region_id": 8 }
])
);
let decoded: RecordBatchMetrics = serde_json::from_value(value).unwrap();
assert_eq!(decoded.observed_slices, metrics.observed_slices);
// Old bytes must not be reinterpreted: the numeric projection is not an expression
// identity, so a reader of the new key sees no observation at all.
let mut legacy = serde_json::to_value(RecordBatchMetrics::default()).unwrap();
legacy["observed_slices"] = json!([{ "region_id": 7, "lo": 50, "hi": 100 }]);
let old: RecordBatchMetrics = serde_json::from_value(legacy).unwrap();
assert!(old.observed_slices.is_empty());
}
}
+1 -1
View File
@@ -29,5 +29,5 @@ pub use datatypes::schema::{
pub use self::descriptors::*;
pub use self::file::{FileId, FileRef, FileRefsManifest, GcReport, IndexVersion, ParseIdError};
pub use self::projection::NestedPath;
pub use self::requests::{ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector};
pub use self::requests::{CursorShard, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector};
pub use self::types::{SequenceNumber, SequenceRange};
+149 -4
View File
@@ -12,8 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::fmt::{Display, Formatter};
use std::sync::Arc;
use common_recordbatch::OrderOption;
use datafusion_expr::expr::Expr;
@@ -45,6 +46,48 @@ pub enum TimeSeriesDistribution {
PerSeries,
}
/// One slice of an incremental cursor: the partition expression selecting a region's value
/// domain together with the last sequence consumed inside it.
///
/// A sequence number belongs to the domain of the region that allocated it, not to the
/// region that currently stores the rows. A cursor is therefore keyed by the **creator**
/// region plus the expression slice, so that a reader holding adopted files can compare
/// a row's number against the cursor of the domain the number came from.
///
/// The slice is carried as the *identity of its partition expression* — the JSON form
/// `PartitionExpr::as_json_str()` writes — and never as a numeric projection of that
/// expression: a projection has to invent a comparison semantics for every operator it
/// cannot express, and silently widens a slice to the whole domain when it meets one.
/// `store-api` cannot depend on the `partition` crate, so the identity stays an opaque
/// string here; the layers that can (`mito2`, `query`) decode it with
/// `PartitionExpr::from_json_str` before they reason about it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CursorShard {
/// Identity (`PartitionExpr::as_json_str()`) of the partition expression that
/// selects this slice's value domain, or `None` when the slice covers the creator
/// region's complete value domain — which is exactly what a region-keyed cursor
/// states.
pub partition_expr: Option<String>,
/// Last sequence consumed in the domain `partition_expr` selects.
pub seq: SequenceNumber,
}
impl CursorShard {
/// Creates a slice cursor over the value domain of `partition_expr`.
pub fn new(partition_expr: Option<String>, seq: SequenceNumber) -> Self {
Self {
partition_expr,
seq,
}
}
/// Creates the slice covering a region's complete value domain, which is what a
/// region-keyed cursor states.
pub fn whole_domain(seq: SequenceNumber) -> Self {
Self::new(None, seq)
}
}
#[derive(Default, Clone, Debug, PartialEq)]
pub struct ScanRequest {
/// Optional projection information for the scan. `None` reads all root
@@ -81,12 +124,111 @@ pub struct ScanRequest {
/// Explicit intent to read an exact row-level sequence delta `(min, max]`
/// across memtables and all SST files (Flow's `sequence_range` incremental
/// mode). The engine performs exact row-level filtering only when the region
/// preserves per-row sequences and every participating SST file is trusted;
/// otherwise it returns a structured stale/unsupported error so the caller
/// falls back instead of silently approximating.
/// preserves per-row sequences and every participating SST file is trusted.
///
/// When it cannot, it **fails closed**: the read returns the structured
/// `SequenceRangeUnsupported` error (`Error::SequenceRangeUnsupported`, status
/// `InvalidArguments`, retry hint `FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE`)
/// instead of approximating the delta. The caller decides what to do with it —
/// the read never silently widens, narrows or partially honours the range, so a
/// caller that ignores the error cannot mistake an approximation for the exact
/// delta it asked for.
///
/// Historical `memtable_only` reads must never set this flag.
pub exact_sequence_range: bool,
/// Whether this scan reads the **physical** `__sequence` column of a foreign file
/// and hides the rows whose number a substitution produced.
///
/// A file this region adopted from another region is read with every row's
/// sequence replaced by the handle's admission barrier by default, because the
/// bytes carry the creator's numbering and no caller may observe another
/// region's domain. Flow's incremental read is the one caller that needs the
/// opposite: the barrier makes every adopted row look freshly published, so an
/// adopted file cannot be split into rows already consumed and rows not yet
/// consumed. With this flag the reader
///
/// 1. keeps the physical column of **any** foreign file instead of
/// virtualizing it. `FileMeta::preserve_row_sequence` describes whether the
/// writer kept per-row numbers; a repartition only rewrites handle metadata
/// and never the bytes, so it clears that flag while the column still holds
/// the creator's numbers. Gating the physical read on the flag would
/// therefore exclude exactly the files this read exists for,
/// 2. filters a foreign file's rows by the cursor of the domain that allocated
/// their numbers ([`Self::creator_cursor_shards`]), never by this region's own
/// `(C, H]`. When this scan knows no cursor slice of the file's creator the
/// read **fails closed** with `SequenceRangeUnsupported` instead of
/// approximating: comparing the file's numbers with a bound of another domain
/// silently drops live rows, and reading the file unfiltered delivers every
/// already consumed row again on every round,
/// 3. hides the rows whose number a substitution produced, by the file's own
/// `FileMeta::substituted_up_to` cut (a statement about the bytes, so it
/// applies to local and foreign files alike), and reports the timestamp range
/// of those rows to the caller as `substituted_row_ranges`, so Flow recomputes
/// exactly those windows.
///
/// A foreign file whose creator this scan has no cursor for cannot be attributed
/// at all and fails closed as described above. A file whose bytes were never given
/// per-row numbers (an option-off plateau) is out of this read's scope and is
/// refused by the region option instead. Every other reader, including compaction,
/// leaves this `false` and reads foreign files with the admission-barrier
/// substitution.
pub read_row_sequence: bool,
/// Per-creator-region cursor slices a physical-sequence read filters with
/// ([`Self::read_row_sequence`]), keyed by the region that allocated the numbers.
///
/// A scan of one region may hold files it adopted from others, and a row's number
/// then belongs to the creator's domain: the holder's `(C, H]` cannot bound it.
/// The reader therefore looks the file's `FileMeta::region_id` up here and keeps the
/// slices whose partition expression can hold a row of the file's own
/// `FileMeta::partition_expr` (an expression-overlap check, not a numeric one). The
/// least advanced of those sequences bounds candidate **file pruning**, and every row
/// is then compared against the cursor of the slice its own partition expression
/// selects: a file that straddles several slices delivers each row once, from the
/// slice that row belongs to.
///
/// Empty or absent means no cursor of the creator's domain is known. An adopted
/// file then has no provable row-level bound at all, and the read **fails
/// closed** with `SequenceRangeUnsupported` instead of falling back to this
/// region's own `(C, H]`: comparing the file's numbers with a bound of another
/// domain silently drops live rows, while reading the file unfiltered delivers
/// every already consumed row again on every round. Every reader but a
/// `read_row_sequence` incremental delta leaves it `None`.
pub creator_cursor_shards: Option<Arc<BTreeMap<u64, Vec<CursorShard>>>>,
/// Whether this read may cross an invalid boundary: rows whose sequence the
/// region can no longer vouch for are still returned instead of the read being
/// refused for asking about them. Such a read only needs the timestamps of the
/// rows a stale cursor may have missed, and never accumulates an incremental
/// delta.
///
/// Concretely it (1) allows the boundary to be crossed at all — refusing a cursor
/// for being older than the region's files would deadlock recovery, and this read
/// is what rediscovers the windows a cursor can no longer explain — and applies no
/// lower sequence bound to memtables either (`memtable_min_sequence` is the caller's
/// cursor, and rows at or below it are exactly the ones whose windows are being
/// rediscovered) —, (2) prunes at
/// file granularity only: a file whose admission barrier is at or below the cursor
/// was fully consumed and is dropped, while a file that states no barrier cannot be
/// proven consumed, so the read **fails closed** with `SequenceRangeUnsupported`
/// instead of reading it — keeping it would silently turn discovery into a
/// whole-region scan —, and (3) does not require row-level sequence exactness, so
/// files admitted by an edit are readable even though their row sequences cannot be
/// trusted. The result is a conservative superset of windows, which is safe: those
/// windows are simply recomputed.
///
/// Ordinary incremental deltas must leave it `false`.
pub read_across_invalid_boundary: bool,
/// Whether this read requires its snapshot to cover the region's flushed frontier:
/// it reads whole windows completely under a frozen high watermark, and its result
/// may only be committed when that watermark still covers everything flushed.
///
/// It differs from [`Self::read_across_invalid_boundary`] in two ways: it must
/// **not** prune at file granularity and must **not** force row-sequence override,
/// otherwise the rows of a partially consumed file would be dropped and the
/// recomputed window would be wrong. What it shares with that read is crossing the
/// invalid boundary (an old cursor is allowed, because this read is what repairs
/// that state) and the requirement to prove the frozen `H` still covers the
/// region's flushed frontier before its result may be committed.
pub require_flushed_frontier: bool,
/// Optional hint for the distribution of time-series data.
pub distribution: Option<TimeSeriesDistribution>,
/// Optional hint from query-driven JSON type concretization.
@@ -181,6 +323,9 @@ impl Display for ScanRequest {
if self.exact_sequence_range {
write!(f, "{}exact_sequence_range: true", delimiter.as_str())?;
}
if self.read_row_sequence {
write!(f, "{}read_row_sequence: true", delimiter.as_str())?;
}
if self.preserve_pk_dictionary_encoding {
write!(
f,