refactor(mito2,flow): trim comments to the facts a reader cannot infer and drop dead helpers

Assume the reader knows what a cursor and a partition expression are: the
paragraphs arguing against alternatives nobody would pick are gone, while the
cross-layer constraints, ordering requirements and invariants stay. Also drop
three helpers and their tests that had no caller.

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-23 23:21:52 +08:00
parent 587b1f204b
commit 543f44a6c0
19 changed files with 238 additions and 869 deletions
+20 -49
View File
@@ -698,35 +698,17 @@ 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.
/// Per-region time ranges of the rows a scan deliberately substituted, so the caller
/// recomputes those windows. An empty list means "substituted nothing", never "unknown".
/// Entries are ordered by region id, each region's ranges sorted and non-overlapping,
/// omitted when empty.
#[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.
/// The `(region, partition expression)` pairs this round's scans actually read, so the
/// owner of a `(region, slice)` cursor advances only the slices that were read.
/// Deduplicated and sorted, omitted when empty. Old bytes carried a numeric projection
/// under the previous key, so the new key (`observed_partition_exprs`) is not read back as
/// expressions.
#[serde(
default,
rename = "observed_partition_exprs",
@@ -738,11 +720,10 @@ pub struct RecordBatchMetrics {
/// 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.
/// `region_id` is the region that allocated the rows' sequences — the creator of the file they
/// were read from, this region itself for a file it wrote. `partition_expr` is the identity of
/// the expression that file states for its own rows (`PartitionExpr::as_json_str()`); `None`
/// means the file states none and covers its region's complete value domain.
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ObservedPartitionExpr {
pub region_id: u64,
@@ -751,7 +732,6 @@ pub struct ObservedPartitionExpr {
}
impl ObservedPartitionExpr {
/// Creates the observed pair `(region_id, partition_expr)`.
pub fn new(region_id: u64, partition_expr: Option<String>) -> Self {
Self {
region_id,
@@ -774,10 +754,8 @@ pub struct SubstitutedRowRanges {
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.
/// One `[start, end]` range of row timestamps, in milliseconds since the Unix epoch, both ends
/// inclusive: a caller that owns time windows must recompute every window that intersects it.
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
)]
@@ -789,14 +767,9 @@ pub struct SubstitutedRange {
#[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.
/// Identity (`PartitionExpr::as_json_str()`) of the partition expression this entry speaks
/// about, or `None` when it speaks about the region's complete value domain. A slice is
/// merged under its own key, never with the region's whole-domain entry.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partition_expr: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -2128,8 +2101,7 @@ mod test {
};
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.
// The old key carried a numeric projection, so the identity travels under its own key.
assert!(value.get("observed_slices").is_none());
assert_eq!(
value.get("observed_partition_exprs").unwrap(),
@@ -2142,8 +2114,7 @@ mod test {
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.
// Old bytes are not reinterpreted: a reader of the new key sees no observation.
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();
-69
View File
@@ -204,25 +204,6 @@ 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<u64, u64>) {
@@ -1477,56 +1458,6 @@ 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));
+12 -44
View File
@@ -204,15 +204,8 @@ 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.
/// A region absent from the proved map is never reported as `0`: a missing report is not a
/// sequence.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RegionWatermarkSample {
/// Regions this round covered, i.e. regions the sample plan named and whose
@@ -234,30 +227,11 @@ impl RegionWatermarkSample {
}
}
/// Regions this round covered. A region missing here was not read this round.
pub fn read_regions(&self) -> &BTreeSet<u64> {
&self.read_regions
}
/// Proved watermarks, always a subset of [`Self::read_regions`].
/// Proved watermarks, always a subset of `read_regions`.
pub fn watermarks(&self) -> &BTreeMap<u64, u64> {
&self.watermarks
}
/// Regions this round read without proving a watermark for them.
pub fn unproved_regions(&self) -> BTreeSet<u64> {
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<u64, u64> {
self.watermarks
@@ -313,22 +287,16 @@ impl TreeNodeRewriter for ZeroRowTimeIndexRewriter {
/// 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.
/// The sample must reach **every** participating region, because a region states its watermark
/// through its own terminal metrics and only once its read finishes. With `parallelism = 1` a
/// single `LIMIT` stops after the first region's first batch (the remaining region clients are
/// never opened, which is how watermarks went missing), and `LIMIT 0` is rewritten into an
/// `EmptyRelation` by `EliminateLimit`, so no region opens at all. The plan therefore carries no
/// truncating operator and the caller drains it 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.
/// Draining must not read business rows, so the sample pins the time index below every
/// representable value: the storage layer prunes everything against it, and each region's read
/// still opens (binding the scan-open snapshot the watermark proves) and finishes at once.
fn region_watermark_sample_plan(
input: LogicalPlan,
time_index_column: &str,
+3 -5
View File
@@ -290,11 +290,9 @@ impl BatchingTask {
.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.
// The owner of the cursor proved its expression slices: send them instead
// of the region projection, so a reader of an adopted file can filter its
// rows by the slice the file belongs to.
Some(
query::options::encode_incremental_after_seqs(shards).map_err(|err| {
UnexpectedSnafu {
-78
View File
@@ -5075,84 +5075,6 @@ fn test_region_watermark_sample_plan_has_no_truncation_and_keeps_sources() {
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<AtomicBool>,
}
#[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<Output, BoxedError> {
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<dyn crate::batching_mode::frontend_client::GrpcQueryHandlerWithBoxedError> =
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.
@@ -54,15 +54,9 @@ fn range_expr(col_name: &str, start: i64, end: i64) -> PartitionExpr {
.and(col(col_name).lt(Value::Int64(end)))
}
/// A repartition can keep a region's own files in place: the region id survives, so the
/// bytes, the numbers and the `preserve_row_sequence` marker all stay as they are.
///
/// The staging exit re-marks the barrier of every file it makes visible, and it must not
/// clear that marker for a file this region already owned. A local file without trusted
/// per-row numbering denies the whole region its exact `(C, H]` range
/// (`read/scan_region.rs::exact_sequence_range` fails closed on it), so the rows written
/// after the repartition could never be read again — the file never left, only its
/// publisher changed.
/// A repartition can keep a region's own files in place: the region id survives, so the bytes,
/// the numbers and the `preserve_row_sequence` marker all stay as they are, and the staging exit
/// must not clear that marker for a file this region already owned.
#[tokio::test]
async fn test_apply_staging_manifest_keeps_the_marker_of_a_kept_file() {
let mut env = TestEnv::with_prefix("apply-staging-keeps-kept-file-marker").await;
@@ -694,7 +694,6 @@ async fn test_copy_region_from_clears_preserve_row_sequence_marker() {
);
}
/// Waits until `region` reaches `state`.
async fn wait_until_region_state(region: &MitoRegionRef, state: RegionLeaderState) {
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while region.state() != RegionRoleState::Leader(state) {
-6
View File
@@ -6422,7 +6422,6 @@ async fn test_read_row_sequence_filters_each_creator_expression_by_its_own_curso
.await
.unwrap();
// The right slice of the creator's domain, holding the numbers 1..6.
test_util::put_rows(
&engine,
source,
@@ -6441,7 +6440,6 @@ async fn test_read_row_sequence_filters_each_creator_expression_by_its_own_curso
assert_eq!(None, right_file.partition_expr);
right_file.partition_expr = Some(partition_slice(50, 100).into());
// The left slice, holding the numbers 7..12.
test_util::put_rows(
&engine,
source,
@@ -6787,7 +6785,6 @@ async fn test_read_row_sequence_hides_substituted_rows_of_local_compaction_outpu
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// The creator's file states the numbers 1, 2 and 3.
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
// The holder of the repartition target, created the way `create_foreign_target` creates it.
@@ -6916,7 +6913,6 @@ async fn test_read_row_sequence_keeps_exact_sequence_range_of_local_file_with_cu
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// The region numbers these rows 1, 2 and 3.
test_util::put_rows(
&engine,
region_id,
@@ -7091,7 +7087,6 @@ async fn test_read_row_sequence_filters_adopted_file_without_cut_by_creator_curs
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// Five rows numbered 1..5, none of them substituted.
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
@@ -7163,7 +7158,6 @@ async fn test_read_row_sequence_ignores_holder_bounds_for_foreign_file() {
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// The creator's file states the numbers 1..=12, none of them substituted.
let (_, source_file) = build_foreign_source_file(&engine, source, 12, true).await;
create_foreign_target(&engine, target).await;
// Admitted at barrier 6: below the numbers its bytes carry, which is the whole point.
-2
View File
@@ -2639,7 +2639,6 @@ async fn test_migration_flush_retries_while_staging_ends() {
assert_eq!(0, migration_flush().await.unwrap().affected_rows);
}
/// Waits until the region reaches `state`.
async fn wait_until_region_state(region: &MitoRegionRef, state: RegionLeaderState) {
tokio::time::timeout(Duration::from_secs(5), async {
while region.state() != RegionRoleState::Leader(state) {
@@ -3003,7 +3002,6 @@ async fn test_staging_exit_rejects_writes_while_end_commit_pending() {
.any(|file_id| *file_id == imported.file_id),
"the file the retry published must be visible"
);
// 3 flushed rows + 2 staged rows + 2 imported rows.
assert_eq!(
7,
count_rows(&engine, region_id).await,
+70 -232
View File
@@ -77,7 +77,7 @@ use crate::read::series_scan::SeriesScan;
use crate::read::stream::ScanBatchStream;
use crate::read::substituted_rows::{
ObservedPartitionExprs, ObservedPartitionExprsRef, SubstitutedRowsAccumulator,
SubstitutedRowsAccumulatorRef, SubstitutedSequenceCut,
SubstitutedRowsAccumulatorRef,
};
use crate::read::unordered_scan::UnorderedScan;
use crate::read::{BoxedRecordBatchStream, RecordBatch};
@@ -478,23 +478,10 @@ impl ScanRegion {
/// Scans by series.
///
/// # A physical row-sequence read is refused here
///
/// `ScanRequest::read_row_sequence` asks a reader to keep a foreign file's own
/// `__sequence` column and to hide the rows a substitution produced, which takes both
/// the creator's cursor slice ([`ScanInput::foreign_row_sequence_filter`]) and the
/// file's substituted cut ([`ScanInput::substituted_sequence_cut`]). Neither is applied
/// on this path: the per-series readers filter a file by this region's own `(C, H]` and
/// its trust decision alone, and the legacy distributor reads the same files through
/// the plain flat reader (`SeqScan::build_flat_partition_range_read`) without any of
/// it. Both would hand Flow rows it has already consumed, or compare a foreign file's
/// numbers with a bound of another domain, so the combination is refused instead of
/// silently approximated.
///
/// This costs nothing: Flow's incremental delta — the only reader that asks for the
/// physical column — is planned as an ordered flat read and never selects this
/// distribution. The refusal reuses the shared "exactness is not provable" contract, so
/// the caller falls back exactly as it does for every other unprovable range.
/// A physical row-sequence read is refused here: neither the per-series readers nor the
/// legacy distributor (`SeqScan::build_flat_partition_range_read`) applies the creator's
/// cursor slice or the file's substituted cut, so the read fails closed with the shared
/// "exactness is not provable" error.
#[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
pub(crate) async fn series_scan(self) -> Result<SeriesScan> {
if self.request.read_row_sequence {
@@ -603,14 +590,9 @@ impl ScanRegion {
self.version.options.merge_mode(),
);
// A read that may cross an invalid boundary must see the memtable rows whose
// sequence already sits at or below its cursor: those are exactly the rows whose
// windows the cursor can no longer explain, and this read is what rediscovers
// them. A lower bound here would hide them, so the windows would never be
// reported and a repair would advance the cursor past them. This matches the
// file-level exemption of the same mode ([`exact_sequence_range`]), which prunes
// by admission barrier instead of filtering rows by sequence. The upper bound
// stays: it is the frozen `H` the caller's result must stay below.
// A read that may cross an invalid boundary applies no lower bound to memtables: the
// rows at or below the cursor are exactly the windows it rediscover. The frozen `H`
// upper bound stays.
let memtable_min_sequence = if self.request.read_across_invalid_boundary {
None
} else {
@@ -1103,18 +1085,14 @@ pub struct ScanInput {
/// Whether this scan reads the physical `__sequence` of a foreign file and hides
/// the rows a substitution produced ([`ScanRequest::read_row_sequence`]).
pub(crate) read_row_sequence: bool,
/// Cursor slices of every creator region ([`ScanRequest::creator_cursor_shards`]).
/// A file this region adopted from another one is bounded by the least advanced cursor
/// slice of its creator that may hold its rows, because its numbers belong to the
/// creator's domain.
/// Cursor slices of every creator region ([`ScanRequest::creator_cursor_shards`]): an
/// adopted file is bounded by the least advanced slice of its creator that may hold its
/// rows.
creator_cursor_shards: Option<Arc<BTreeMap<u64, Vec<CursorShard>>>>,
/// Collects the timestamp ranges of the rows this scan substituted. `None` turns the
/// whole mechanism off, which is what every reader but Flow's incremental delta
/// uses.
/// Collects the timestamp ranges of the rows this scan substituted; `None` turns it off.
pub(crate) substituted_row_ranges: Option<SubstitutedRowsAccumulatorRef>,
/// Collects the `(region, partition expression)` pairs the files this scan read state.
/// `None` turns the mechanism off, like [`Self::substituted_row_ranges`]: only the read
/// that consumes a `(region, expression)` cursor can say which of them it consumed.
/// Collects the `(region, partition expression)` pairs this scan read; `None` turns it off,
/// like [`Self::substituted_row_ranges`].
pub(crate) observed_slices: Option<ObservedPartitionExprsRef>,
/// Whether this scan is for compaction.
pub(crate) compaction: bool,
@@ -1553,7 +1531,6 @@ impl ScanInputBuilder {
self
}
/// Sets whether this read may cross an invalid boundary.
#[must_use]
pub(crate) fn with_read_across_invalid_boundary(
mut self,
@@ -1563,13 +1540,8 @@ impl ScanInputBuilder {
self
}
/// Sets whether this scan reads physical row sequences and hides substituted rows.
///
/// Turns the substituted-row collector on with it: the ranges it substitutes are the
/// only thing that tells the caller which windows to recompute. It turns the
/// observed-partition-expression collector on too, because this read is the one that
/// consumes a `(region, expression)` cursor and the only one that can report which of
/// them it read.
/// Sets whether this scan reads physical row sequences and hides substituted rows. It turns
/// the substituted-row and observed-partition-expression collectors on with it.
#[must_use]
pub(crate) fn with_read_row_sequence(mut self, read_row_sequence: bool) -> Self {
self.input.read_row_sequence = read_row_sequence;
@@ -1580,11 +1552,8 @@ impl ScanInputBuilder {
self
}
/// Sets the cursor slices of the regions that created this region's files.
///
/// Only a physical-sequence read uses them: it bounds an adopted file by the least
/// advanced cursor of the creator expression slices that may hold its rows, instead of
/// comparing the creator's numbers against this region's own cursor.
/// Sets the cursor slices of the regions that created this region's files; only a
/// physical-sequence read uses them.
#[must_use]
pub(crate) fn with_creator_cursor_shards(
mut self,
@@ -1833,16 +1802,10 @@ impl ScanInput {
};
let res = reader
.expected_metadata(Some(self.mapper.metadata().clone()))
// A read that may cross an invalid boundary virtualizes every row at the
// file's barrier instead of trusting the file's own sequence column.
.force_sequence_override(self.read_across_invalid_boundary)
// Flow's incremental delta keeps the physical column of an adopted file and
// hides the rows a substitution produced; every other read keeps the
// barrier substitution.
.read_row_sequence(self.read_row_sequence)
// The reader splits the adopted file's rows by the creator slice each row
// belongs to, so it needs the slices whose expression may hold rows of *this*
// file. A file no slice covers keeps the fail-closed path instead.
// Only the slices whose expression may hold rows of this file are passed on; a file
// no slice covers keeps the fail-closed path.
.creator_slice_cursors(self.creator_slice_cursors(file)?)
.compaction(self.compaction)
.pre_filter_mode(pre_filter_mode)
@@ -2042,23 +2005,18 @@ impl ScanInput {
self.mapper.metadata()
}
/// Returns the collector of the timestamp ranges this scan substituted, if it
/// substitutes any.
pub(crate) fn substituted_row_ranges(&self) -> Option<&SubstitutedRowsAccumulator> {
self.substituted_row_ranges.as_deref()
}
/// Returns a shared handle to the substituted-row collector of this scan.
pub(crate) fn substituted_row_ranges_ref(&self) -> Option<SubstitutedRowsAccumulatorRef> {
self.substituted_row_ranges.clone()
}
/// Returns the collector of the `(region, partition expression)` pairs this scan read.
pub(crate) fn observed_slices(&self) -> Option<&ObservedPartitionExprs> {
self.observed_slices.as_deref()
}
/// Returns a shared handle to the collector of the slices this scan read.
pub(crate) fn observed_slices_ref(&self) -> Option<ObservedPartitionExprsRef> {
self.observed_slices.clone()
}
@@ -2066,77 +2024,29 @@ impl ScanInput {
/// Returns the substituted cut `file` states for its own bytes, when this scan reads
/// physical row sequences.
///
/// The cut is a statement about the file's **bytes**, not about who allocated the
/// numbers in them, so it is applied to every file that states one. A **local** file
/// carries a substitution as well: compaction substitutes a file-level constant for
/// the rows of its foreign inputs and states the bound on its output
/// ([`crate::sst::file::substituted_up_to_after_merge`]). Leaving those rows in the
/// result delivers rows the caller already received once, because their numbers are
/// not the numbers this region published either.
///
/// The file's `preserve_row_sequence` marker takes no part: it describes whether the
/// *writer* kept per-row numbering, while an import (a repartition's staging apply
/// included) only rewrites the handle's metadata and re-marks the file, leaving its
/// bytes untouched. The cut is the only statement about which rows a substitution
/// produced, so a re-marked file that still carries one is filtered by it.
pub(crate) fn substituted_sequence_cut(
&self,
file: &FileHandle,
) -> Option<SubstitutedSequenceCut> {
/// The cut describes the file's bytes, not who allocated the numbers in them, so it applies
/// to every file that states one, local files included
/// ([`crate::sst::file::substituted_up_to_after_merge`]). The file's
/// `preserve_row_sequence` marker takes no part.
pub(crate) fn substituted_sequence_cut(&self, file: &FileHandle) -> Option<SequenceNumber> {
if !self.read_row_sequence {
return None;
}
// `None` means no row of the column was substituted; `Some(0)` means the column
// carries no per-row numbering at all, so every row is substituted.
file.meta_ref()
.substituted_up_to
.map(|cut| SubstitutedSequenceCut { cut })
file.meta_ref().substituted_up_to
}
/// The row filter of a physical-sequence read of `file`: `(candidate creator cursor,
/// +inf)`.
///
/// The numbers in an adopted file's column were allocated by the region that created
/// it, so the only cursor that bounds them is the creator's — and even that one only
/// inside the partition expression the file states, because the cursor is keyed by
/// `(region, expression)`. Several expressions may be candidates for one file (a file
/// that states none, or one spanning several), so the least advanced candidate bounds
/// the file as a whole: re-reading a consumed row can be recovered from, silently
/// dropping a live one cannot.
/// This is the candidate selection of [`cursor_slice_may_hold_file_rows`] followed by one
/// sequence range for the whole file, so a file whose expressions advanced differently is
/// read from the least advanced of them. The upper end is unbounded because no upper bound
/// of the creator's domain survives adoption.
///
/// This is a **file-level** bound, not a per-row decision: it is the candidate
/// selection of [`cursor_slice_may_hold_file_rows`] followed by one sequence range for
/// the whole file, so a file whose rows belong to different expressions at different
/// progress is read from the least advanced of them and may repeat rows of the others.
///
/// `None` means this scan has no cursor for the file's creator, or the file is not
/// foreign at all; [`Self::foreign_row_sequence_filter`] is what a reader calls, and
/// it fails closed instead of reading a foreign file without a creator cursor.
///
/// # Why the upper end is unbounded
///
/// No upper bound of the creator's domain survives adoption, so none is used here.
/// The scan's own `H` is a number this region's sequence space issued; comparing it
/// with the file's numbers silently drops live rows — a creator that has published
/// `10..=12` while its cursor sits at `9` is filtered by `(9, 6]` when the holder's
/// `H` is 6, and once the holder's cursor reaches the file's admission barrier the
/// file is pruned as well, so those three rows are never delivered at all.
///
/// The two bounds that *would* be provable are not available to the reader:
///
/// * the creator's own `committed_sequence` is not carried by the handle — admission
/// overwrites `FileMeta::sequence` with the holder's barrier
/// (`handle_copy_region`/`handle_manifest`), so the value in it is this region's;
/// * the maximum of the file's physical `__sequence` column would be provable from the
/// file, but the manifest does not record it and deriving it costs a metadata fetch
/// per foreign file on every round.
///
/// Unbounded above is therefore the conservative and provable choice: a row above the
/// creator's cursor is a row that cursor has not consumed, and the creator's watermark
/// advances exactly that cursor at the end of the round
/// ([`crate::read::scan_util`] reports which slices were read), so the read is not
/// repeated once the round commits. Rows of an adopted file were all committed before
/// the file was admitted, so no reader can observe a "future" number this way either.
/// `None` means this scan has no cursor for the file's creator, or the file is not foreign
/// at all.
pub(crate) fn creator_domain_sequence_range(
&self,
file: &FileHandle,
@@ -2197,9 +2107,8 @@ impl ScanInput {
let mut cursors = Vec::new();
for shard in shards {
let Some(identity) = shard.partition_expr.as_ref() else {
// A whole-domain cursor is the region-keyed statement of an older producer:
// it applies to every row, so the least advanced cursor of the region is the
// most precise answer available and the per-row split adds nothing.
// A whole-domain cursor applies to every row: the file-level bound is the
// most precise answer available.
return Ok(None);
};
if cursor_slice_may_hold_file_rows(shard, meta)? {
@@ -2221,20 +2130,13 @@ impl ScanInput {
/// The row filter a physical-sequence read applies to `file`.
///
/// `Ok(None)` means the file carries this region's own numbers (or this scan is not a
/// physical-sequence read at all), so the scan's own `(C, H]` bounds it as it stands
/// and the caller keeps its per-file trust decision.
/// physical-sequence read at all), so the scan's own `(C, H]` bounds it.
///
/// A foreign file is filtered by `(creator cursor, +inf)`
/// ([`Self::creator_domain_sequence_range`]), with **or without** a substituted cut in
/// the file: its rows were numbered in the creator's domain, which this region's
/// cursor does not bound. A file whose creator this scan has no cursor slice for fails
/// closed instead of falling back to the holder's `(C, H]`: comparing two sequence
/// domains silently drops live rows, and reading the file unfiltered delivers every
/// already consumed row again on every round.
///
/// The corresponding selection rule lives in [`exact_sequence_range`]: a foreign file
/// of a physical-sequence read is never pruned by this region's cursor, because
/// `C >= admission barrier` says nothing about the creator's numbering.
/// ([`Self::creator_domain_sequence_range`]), with or without a substituted cut. A file
/// whose creator this scan has no cursor slice for fails closed instead of falling back to
/// the holder's `(C, H]`. [`exact_sequence_range`] never prunes such a file by this
/// region's cursor.
pub(crate) fn foreign_row_sequence_filter(
&self,
file: &FileHandle,
@@ -2394,38 +2296,18 @@ fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode {
}
}
/// Whether `meta` **may** hold rows of the value domain the cursor slice `shard` was
/// consumed in, i.e. whether `shard.seq` is one of the candidate cursors of this file.
/// Whether `meta` may hold rows of the value domain the cursor slice `shard` was consumed in,
/// i.e. whether `shard.seq` is one of the candidate cursors of this file.
///
/// This is a *file-level* selection, not a per-row decision. The caller takes the least
/// advanced candidate cursor and bounds the whole file with it
/// ([`ScanInput::creator_domain_sequence_range`]), which is what keeps the read safe: a row
/// of a slice that was not selected is never re-read, and a row of a selected slice is only
/// re-read. Making the decision per row instead would need the file's rows evaluated
/// against each slice expression, which this reader does not do — the only per-row filter
/// of a physical-sequence read is the sequence comparison in
/// [`crate::read::scan_util::filter_flat_batch_by_sequence`].
///
/// The candidates are selected by comparing partition expressions, never by projecting them
/// onto a numeric interval: an expression this build can represent may use operators
/// (`<>`, `OR`, an iceberg hash, a non-integer value) that such a projection cannot
/// express, and approximating one there is how a live slice stops being read.
/// This is a file-level selection: the caller bounds the whole file with the least advanced
/// candidate ([`ScanInput::creator_domain_sequence_range`]).
///
/// * a whole-domain slice (`partition_expr: None`) is a candidate for every file;
/// * a file that states no expression covers its region's complete value domain, so every
/// slice of the region is a candidate — selecting only some would drop live rows;
/// * otherwise the slice is a candidate when the two expressions can be satisfied by a
/// common row, which is the overlap question the partition crate already answers for
/// repartition planning (`partition::overlap::associate_from_to`, used the same way by
/// `partition::subtask::create_subtasks`, `src/partition/src/subtask.rs:37`, over the
/// [`Collider`] atomics of `partition::overlap::atomic_exprs_overlap`,
/// `src/partition/src/overlap.rs:31`). It splits both expressions into atomic
/// alternatives and normalizes their values in one collider, so the answer does not
/// depend on how either expression is written;
/// * an expression that cannot be analysed is a candidate as well: re-reading a consumed
/// row is recoverable, dropping a live one is not.
///
/// [`Collider`]: partition::collider::Collider
/// slice of the region is a candidate;
/// * otherwise the slice is a candidate when both expressions can be satisfied by a common
/// row, which is the overlap question of `partition::overlap::associate_from_to`;
/// * an expression that cannot be analysed is a candidate as well.
fn cursor_slice_may_hold_file_rows(
shard: &CursorShard,
meta: &crate::sst::file::FileMeta,
@@ -2468,50 +2350,21 @@ fn cursor_slice_may_hold_file_rows(
/// proves Flow has already consumed the entire file, so such a file is excluded
/// before the capability check. An unknown bound cannot prove this exclusion.
///
/// A foreign file is different: outside a physical-sequence read the parquet
/// reader virtualizes every row to its target-local `FileMeta.sequence`.
/// Consequently, a present sequence is the only trust requirement for a foreign
/// file; its source marker is irrelevant. A foreign file without that barrier is
/// retained as a failed-closed error so it cannot be mistaken for a local
/// sequence domain. This check is performed even when another exact-range
/// capability condition would return `None`.
/// A foreign file only has to state a barrier: outside a physical-sequence read the parquet
/// reader virtualizes every row to its target-local `FileMeta.sequence`, which is also what
/// makes the `C >= barrier` exclusion sound for it. Its source marker is irrelevant. A foreign
/// file without a barrier fails closed.
///
/// That virtualization is also what makes the `C >= barrier` exclusion sound for a
/// foreign file in those modes: every one of its rows reads as the barrier, so a
/// barrier at or below `C` hides the whole file. A physical-sequence read
/// (`read_row_sequence`) does not virtualize; it keeps the file's own numbers, which
/// were issued in the *creator's* domain, so the barrier is nothing but an admission
/// timestamp and `C >= barrier` proves nothing about them. Such a file is never
/// excluded here — its rows are filtered by the creator's cursor instead
/// ([`ScanInput::foreign_row_sequence_filter`]) — because excluding it would drop the
/// live rows above that cursor for good.
/// A physical-sequence read (`read_row_sequence`) keeps the file's own numbers instead, so a
/// foreign file is never excluded here and is filtered by the creator's cursor
/// ([`ScanInput::foreign_row_sequence_filter`]).
///
/// The file's `preserve_row_sequence` marker does not gate a foreign file either
/// way, here or when the reader picks the sequence column. It describes whether
/// the file's *writer* kept per-row numbering, whereas an import (a repartition's
/// staging apply included) only rewrites the handle's metadata and copies the
/// bytes verbatim, so it says nothing about the column a physical-sequence read
/// finds ([`ScanInput::substituted_sequence_cut`] is what a substitution leaves
/// behind). A source file stating `preserve_row_sequence = false` with no cut
/// therefore belongs to the plateau of a source table whose option is off: Flow
/// never reads one, because it only asks for this mode on a region whose
/// `preserve_row_sequence` option is on, and the option requirement below denies
/// every other region an exact range. Such a file fails closed there instead of
/// being read as an ordinary file.
///
/// A **local** file can state that substitution fact as well: a merge substitutes a
/// file-level constant for the rows of its foreign inputs (and of a legacy all-zero
/// one) and records the bound it produced
/// ([`crate::sst::file::substituted_up_to_after_merge`]), so a local file may carry
/// `preserve_row_sequence = false` **and** a cut. A physical-sequence read hides the
/// rows at or below the cut and reports their time windows
/// ([`ScanInput::substituted_sequence_cut`]), and every row above the cut carries a
/// number this region allocated, which the reader's own `(C, H]` row filter bounds per
/// row (`read/scan_util.rs`). Such a file is attributable and must not deny the region
/// its exact range — one merge of an adopted file, repeated by every round of
/// compaction, would otherwise fail every later delta closed for good. Outside that
/// mode nothing hides the substituted rows, so a local file with neither the marker nor
/// a cut (or with a cut but no physical-sequence read) keeps failing closed.
/// A **local** file may state a substitution as well: a merge substitutes a file-level constant
/// for the rows of its foreign inputs and records the bound
/// ([`crate::sst::file::substituted_up_to_after_merge`]). Such a file is attributable — the read
/// hides the rows at or below the cut ([`ScanInput::substituted_sequence_cut`]) and the scan's
/// own `(C, H]` bounds the rest — and keeps the region's exact range. A local file with neither
/// the marker nor a cut, or a cut outside a physical-sequence read, keeps failing closed.
pub(crate) fn exact_sequence_range(
request: &ScanRequest,
version: &crate::region::version::Version,
@@ -2521,14 +2374,10 @@ pub(crate) fn exact_sequence_range(
}
if request.read_across_invalid_boundary {
// A read that may cross an invalid boundary prunes at file granularity only.
// A file whose admission barrier is at or below the cursor was fully consumed,
// so it cannot contribute to the missing windows; a file without a barrier
// cannot be proven disjoint, so it is kept (conservative). Row-level exactness
// is deliberately not requested: returning no `SequenceRange` keeps every row
// of the selected files, and the caller only needs their timestamps. The
// result may therefore be a superset of the affected windows, which is safe
// because those windows are recomputed.
// A read that may cross an invalid boundary prunes at file granularity only: a file
// whose admission barrier is at or below the cursor was fully consumed, and a file
// without a barrier is kept. No `SequenceRange` is returned, so the result is a
// superset of the affected windows.
let after = request.memtable_min_sequence;
let time_index = version.metadata.time_index_column();
let unit = time_index
@@ -2551,10 +2400,8 @@ pub(crate) fn exact_sequence_range(
})
.cloned()
.collect::<Vec<_>>();
// A file without an admission barrier cannot be pruned: keeping it would
// silently degrade discovery into a full scan, which is forbidden. Report the
// incomplete candidate set instead, using the shared "exactness unavailable"
// vocabulary so the caller can decide whether to fail or accept a superset.
// A file without an admission barrier cannot be pruned, so the candidate set is
// reported as incomplete instead of degrading into a full scan.
let unprunable = files
.iter()
.filter(|file| file.meta_ref().sequence.is_none())
@@ -2612,13 +2459,8 @@ pub(crate) fn exact_sequence_range(
.filter(|file| file_in_range(file, &time_range))
{
let meta = file.meta_ref();
// A physical-sequence read of a foreign file keeps the creator's own numbers, and
// its admission barrier belongs to this region's domain: it says when the holder
// published the file, not how far the creator's numbering has been consumed.
// `C >= barrier` therefore proves nothing about those rows, and excluding the file
// here would drop the live rows above the creator's cursor for good (they would
// never be read again, because this exclusion repeats on every round). Its rows are
// filtered by the creator's cursor instead.
// A physical-sequence read keeps the creator's numbers, which the barrier does not
// bound: the file is kept and filtered by the creator's cursor.
let keeps_foreign_sequence_domain =
request.read_row_sequence && meta.region_id != version.metadata.region_id;
let selected = (!request.exact_sequence_range
@@ -2645,12 +2487,8 @@ pub(crate) fn exact_sequence_range(
}
.fail();
}
// A local file whose marker is unset is still attributable when it states
// the cut a substitution left in its bytes: the physical-sequence read
// hides the rows at or below the cut and reports their windows, and every
// row above it carries this region's numbering, which the reader's own row
// filter bounds. Only a local file with neither the marker nor such a cut
// leaves rows this read cannot attribute.
// A local file whose marker is unset is attributable when it states a cut: the
// read hides the rows at or below it and the rest carries this region's numbering.
let cut_hides_substituted_rows =
request.read_row_sequence && meta.substituted_up_to.is_some();
if meta.region_id == version.metadata.region_id
+13 -43
View File
@@ -1533,13 +1533,10 @@ pub(crate) async fn scan_flat_file_ranges(
/// (`__primary_key`, `__sequence`, `__op_type`), so it must be applied before any
/// projection/compat conversion that drops internal columns.
///
/// `file_sequence_trusted` is the per-file trust decision. Foreign reader
/// batches have already been virtualized to the target-local file barrier, so
/// they are filtered using the effective batch sequence. A local file whose marker is
/// unset is left untouched only when it has no substituted cut: the exact-range
/// capability excludes such a file from the region's range before row filtering. A
/// local file that states a cut is filtered like a trusted one, because its cut already
/// hid the rows a substitution produced.
/// `file_sequence_trusted` is the per-file trust decision. Foreign batches have already been
/// virtualized to the target-local file barrier, so they are filtered by the effective batch
/// sequence. A local file whose marker is unset is filtered like a trusted one only when it
/// states a substituted cut, which already hid the rows a substitution produced.
pub(crate) fn filter_flat_batch_by_sequence(
record_batch: RecordBatch,
sequence_range: Option<SequenceRange>,
@@ -1625,30 +1622,16 @@ pub fn build_flat_file_range_scan_stream(
.substituted_sequence_cut(range.file_handle())
.map(|cut| (cut, windows))
});
// Which rows of this file this round has already consumed, and which ones it
// may still report:
//
// * a local file's rows were admitted by this region, so the scan's own `(C, H]`
// applies as it stands; the rows a substitution produced in it are taken out by
// the cut above, which is why that cut is not "foreign files only";
// * a foreign file's rows were numbered in the creator's domain, which this
// region's cursor does not bound. The creator's cursor slice the file belongs
// to is the filter a physical-sequence read (`read_row_sequence`) asks for,
// and it applies with or without a substituted cut: without it the file would
// be read whole and every already consumed row delivered again. A foreign
// file whose creator has no cursor slice fails closed.
// Which rows of this file this round has already consumed: a local file uses the
// scan's own `(C, H]` on top of the cut above, a foreign file uses the creator's
// cursor slice (with or without a cut) and fails closed when it has none.
let (file_sequence_range, file_sequence_trusted) =
match stream_ctx.input.foreign_row_sequence_filter(range.file_handle())? {
Some(creator_range) => (Some(creator_range), true),
None => (
stream_ctx.input.sequence_range,
// A local file whose marker is unset is attributable above its
// substituted cut: the cut was applied just above (it is only
// computed when a physical-sequence read hides those rows and
// reports their windows), and what is left carries this region's
// own numbering. Skipping the row filter here would deliver rows
// the caller already consumed, which is exactly the row the
// exact-range capability promises not to do.
// substituted cut, which was applied just above.
range
.file_handle()
.is_effective_target_sequence_trusted(
@@ -1658,19 +1641,9 @@ pub fn build_flat_file_range_scan_stream(
),
};
// Which `(region, partition expression)` this read observed: the creator of
// the file and the expression the file states for its own rows. A cursor entry
// keyed by a region alone cannot say which part of that region's domain a
// round consumed, so the owner of the cursor learns the narrower key from the
// read itself. The expression travels as its own identity, never as an
// interval projected out of it: a projection would have to guess a comparison
// semantics for every operator it cannot express, and a file that states no
// expression at all is the only case that covers the complete domain.
//
// A local file is reported too: its numbers belong to this region's own
// domain, and a reader that reported only adopted files would leave a
// region's slices unobservable as soon as compaction rewrote them into local
// ones, which would stall the cursor instead of advancing it.
// Which `(region, partition expression)` this read observed. Local files are
// reported too, so a region's own slices stay observable after compaction rewrote
// adopted rows into local ones.
if let Some(observed) = stream_ctx.input.observed_slices() {
let meta = range.file_handle().meta_ref();
observed.record(meta.region_id.as_u64(), meta.partition_expr.as_deref())?;
@@ -1681,11 +1654,8 @@ pub fn build_flat_file_range_scan_stream(
// occupy, so the caller recomputes exactly those windows.
let record_batch = match substituted_cut {
Some((cut, windows)) => {
let Some(record_batch) = filter_flat_batch_by_substituted_sequence(
record_batch,
Some(cut),
windows,
)?
let Some(record_batch) =
filter_flat_batch_by_substituted_sequence(record_batch, Some(cut), windows)?
else {
continue;
};
+19 -50
View File
@@ -14,19 +14,12 @@
//! Rows a substitution produced, which a scan drops instead of delivering.
//!
//! A region that adopted a file from another region cannot tell, row by row, which of
//! the adopted rows its incremental consumers already saw: an assigned barrier makes
//! all of them look published by the edit. A scan that asks for the physical sequence
//! column (`ScanRequest::read_row_sequence`) therefore drops every row whose number
//! is at or below the file's own substituted cut
//! ([`FileMeta::substituted_up_to`](crate::sst::file::FileMeta::substituted_up_to)) and
//! reports the timestamps of the dropped rows here. Flow recomputes exactly the windows
//! that intersect them instead of double counting the rows it did see.
//!
//! The same read reports which `(region, partition expression)` pairs it read at all
//! ([`ObservedPartitionExprs`], one [`ObservedPartitionExpr`] per pair): a cursor entry keyed
//! by a region alone cannot say which part of the region's value domain a round consumed, so
//! the owner of the cursor has to learn it from the read that consumed it.
//! A physical-sequence read (`ScanRequest::read_row_sequence`) drops every row whose number is
//! at or below the file's own substituted cut
//! ([`FileMeta::substituted_up_to`](crate::sst::file::FileMeta::substituted_up_to)) and records
//! the timestamps of the dropped rows here, so the caller recomputes those windows. The same
//! read records which `(region, partition expression)` pairs it read
//! ([`ObservedPartitionExprs`]).
use std::collections::BTreeSet;
use std::pin::Pin;
@@ -52,22 +45,10 @@ use crate::error::{ComputeArrowSnafu, Result, SerializePartitionExprSnafu};
use crate::read::timestamp_array_to_i64_slice;
use crate::sst::parquet::flat_format::{sequence_column_index, time_index_column_index};
/// The substituted cut a file states for its own bytes.
///
/// Rows whose physical sequence is at or below `cut` carry a number a substitution
/// produced, so a scan that reads physical sequences drops them and reports their
/// timestamps.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SubstitutedSequenceCut {
/// Inclusive upper bound of the substituted numbers.
pub(crate) cut: SequenceNumber,
}
/// Accumulates the timestamp ranges of the rows a scan substituted.
///
/// Shared by every reader of one scan: the ranges are keyed in milliseconds since the
/// Unix epoch and merged when read, so the caller sees a sorted, non-overlapping set of
/// `[start, end]` ranges per region.
/// Shared by every reader of one scan: ranges are merged when read, so the caller sees a sorted,
/// non-overlapping set per region.
#[derive(Debug, Default)]
pub(crate) struct SubstitutedRowsAccumulator {
/// Raw `(start_millis, end_millis)` ranges, both inclusive.
@@ -77,7 +58,6 @@ pub(crate) struct SubstitutedRowsAccumulator {
pub(crate) type SubstitutedRowsAccumulatorRef = Arc<SubstitutedRowsAccumulator>;
impl SubstitutedRowsAccumulator {
/// Creates an empty accumulator.
pub(crate) fn new() -> Self {
Self::default()
}
@@ -125,13 +105,10 @@ impl SubstitutedRowsAccumulator {
}
}
/// Accumulates the partition expressions of the regions a physical-sequence read
/// observed, i.e. one [`ObservedPartitionExpr`] per `(region, partition expression)` pair.
/// Accumulates the partition expressions of the regions a physical-sequence read observed, one
/// [`ObservedPartitionExpr`] per `(region, partition expression)` pair.
///
/// Shared by every reader of one scan and deduplicated on insert, so the caller sees each
/// pair once however many files (and partitions) stated it. A pair states the creator of
/// the file that was read and the identity of the partition expression that file states
/// for its own rows; a file that states none observed its region's complete value domain.
/// Shared by every reader of one scan and deduplicated on insert.
#[derive(Debug, Default)]
pub(crate) struct ObservedPartitionExprs {
slices: Mutex<BTreeSet<ObservedPartitionExpr>>,
@@ -140,19 +117,14 @@ pub(crate) struct ObservedPartitionExprs {
pub(crate) type ObservedPartitionExprsRef = Arc<ObservedPartitionExprs>;
impl ObservedPartitionExprs {
/// Creates an empty accumulator.
pub(crate) fn new() -> Self {
Self::default()
}
/// Records that rows of `(region_id, partition_expr)` were read.
///
/// The expression is recorded as the identity the cursor format carries
/// (`PartitionExpr::as_json_str()`), canonicalized first because that is the form
/// `PartitionExpr::from_json_str` hands back: an identity recorded here then compares
/// equal to the cursor entry of the same expression instead of only to a byte-identical
/// rewrite of it. `None` is the region's complete value domain, which is what a file
/// stating no expression observed.
/// The expression is stored as its canonical identity (`PartitionExpr::as_json_str()`),
/// which is the form a cursor entry carries. `None` is the region's complete value domain.
pub(crate) fn record(
&self,
region_id: u64,
@@ -190,10 +162,10 @@ impl ObservedPartitionExprs {
/// which time windows it has to recompute.
pub(crate) fn filter_flat_batch_by_substituted_sequence(
record_batch: RecordBatch,
substituted: Option<SubstitutedSequenceCut>,
cut: Option<SequenceNumber>,
ranges: &SubstitutedRowsAccumulator,
) -> Result<Option<RecordBatch>> {
let Some(SubstitutedSequenceCut { cut }) = substituted else {
let Some(cut) = cut else {
return Ok(Some(record_batch));
};
if record_batch.num_rows() == 0 {
@@ -210,10 +182,8 @@ pub(crate) fn filter_flat_batch_by_substituted_sequence(
}
.build()
})?;
// `Some(0)` is the file's own statement that its column carries no per-row numbering at
// all (a legacy import), not a bound it only partly reaches: every row is substituted, even
// when a producer left real numbers behind. Dropping all of them can only make the caller
// recompute the whole file.
// `Some(0)` says the column carries no per-row numbering at all (a legacy import): every row
// is substituted, even when a producer left real numbers behind.
let substituted_all = cut == 0;
// `true` keeps the row: its number is above every substituted number, so this region never
// manufactured it from a substitution.
@@ -268,9 +238,8 @@ fn record_substituted_time_range(
return Ok(());
};
// Report in milliseconds so a consumer that owns time windows can align them without
// knowing this region's time unit. The start floors and the end ceils, which can only
// widen the range: a caller recomputes a superset, never misses a substituted row.
// Report in milliseconds so a consumer can align them without knowing this region's time
// unit. The start floors and the end ceils, so the range only widens.
let start_millis = Timestamp::new(start, unit)
.convert_to(TimeUnit::Millisecond)
.map(|ts| ts.value())
+32 -78
View File
@@ -556,18 +556,12 @@ impl MitoRegion {
}
/// Opens the `Editing` window a background publication holds while it allocates its
/// boundary, persists it and makes it visible.
/// boundary, persists it and makes it visible. While it is open the worker loop queues
/// writes and edits, so the boundary is allocated above every sequence already attributed
/// to a row.
///
/// While the window is open the worker loop queues write and bulk-write requests
/// instead of admitting them (see `worker::handle_write`), and region edits are
/// queued behind it as well. A publication that reassigns which rows the region
/// owns therefore allocates its boundary without any write being attributed a
/// sequence at or below it, and the queued writes are only admitted after the new
/// layout is visible, so they obtain a sequence strictly above the boundary.
///
/// **Call this from the worker loop.** Only the loop can prove that no write
/// context is in flight when the window opens, which is what makes the boundary it
/// allocates afterwards strictly above every sequence already attributed to a row.
/// **Call this from the worker loop.** Only the loop can prove that no write context is in
/// flight when the window opens.
pub(crate) fn begin_publish_window(&self, expect: RegionLeaderState) -> Result<()> {
self.manifest_ctx
.open_staging_window(self.region_id, expect, RegionLeaderState::Editing)
@@ -1377,18 +1371,13 @@ impl MitoRegion {
self.publish_staged_manifests(manager).await
}
/// Merges the staged actions and publishes the merged layout at the boundary `B`,
/// then releases the publish window.
/// Merges the staged actions and publishes the merged layout at the boundary `B`, then
/// releases the publish window.
///
/// A successful publish makes the layout visible, so the window is released to
/// `Writable` and the writes it queued are admitted afterwards: they allocate
/// `B + 1` or later. A failure publishes nothing: the region returns to `Staging`, which
/// keeps the staged edits — and, when its commit may have landed, the bytes to retry with
/// (see [`RegionManifestManager::commit_staged`]) — unless the failure ends its leadership.
/// A conflict with another writer, an expired Leader lease or a downgrade that began while
/// the window was open release the window to `Follower` or `Downgrading`, which is where an
/// end of staging that cannot retry has to land (see
/// [`ManifestContext::leave_ending_staging`]).
/// On success the window goes to `Writable` and the queued writes allocate `B + 1` or later.
/// On failure the region returns to `Staging` and keeps the staged edits, unless the failure
/// ends its leadership (conflict, expired lease, downgrade) — then the window goes to
/// `Follower` or `Downgrading` (see [`ManifestContext::leave_ending_staging`]).
async fn publish_staged_manifests(
&self,
manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
@@ -1496,42 +1485,22 @@ impl MitoRegion {
);
}
// A region that still awaits its Leader lease may not own the region yet, so it
// allocates no boundary and persists nothing: this error returns it to `Staging`, which
// keeps the staged layout for a retry, unless a downgrade began meanwhile or its Leader
// deadline passed (see [`ManifestContext::leave_ending_staging`]). Nothing was sent to
// the manifest here, so the write gate stays as the previous attempt left it.
// A region that still awaits its Leader lease owns nothing yet: it allocates no
// boundary and persists nothing, and `leave_ending_staging` returns it to `Staging` for
// a retry unless a downgrade began or the deadline passed.
self.manifest_ctx
.ensure_leader_lease_or_downgrading(self.region_id)?;
// The staging exit may reassign which rows this region owns: rows moved
// between regions and, optionally, a new partition range. Allocate the holder's
// admission `B = last_sequence + 1` **before** persisting and write a committed
// watermark of at least `B` into the merged edit, so the manifest and the in-memory
// `Version` agree and a later full rebuild returns `H >= B`.
// Allocate the holder's admission `B = last_sequence + 1` before persisting, and write a
// committed watermark of at least `B` into the merged edit, so the manifest and the
// in-memory `Version` agree. The publish window, opened in the worker loop before `B` is
// allocated, is what makes `B` sit above every sequence already attributed to a row.
//
// The publish window is what makes the re-mark valid: it is opened in the worker loop
// before `B` is allocated, so no write context is mid-flight and every ordinary write is
// queued until the layout is visible. `B` is therefore above every sequence already
// attributed to a row of this region, and every write admitted afterwards obtains
// `B + 1` or later.
//
// The staging exit publishes no sequence boundary: a repartition rewrites no bytes and
// substitutes no row number. What it does publish is the holder's re-mark on every file
// it makes visible (see below), which is exactly why an earlier substitution must survive
// it: `FileMeta::substituted_up_to` is copied verbatim and never cleared here. That per-file
// record is the only statement the engine keeps about substituted rows. The re-mark
// clears `preserve_row_sequence` only for the files that changed hands: a file this
// region already owned keeps it, because its numbers are still the ones this region
// allocated.
//
// The in-memory `last_sequence` is deliberately **not** advanced here: the edit
// raises it to `B` through `committed_sequence` when it is applied, so a failed
// manifest write cannot leave an advanced allocation behind.
//
// An attempt whose delta may have landed already froze this payload: it is re-sent as
// it is, so neither the merge nor the allocation of `B` nor the re-marking of the files
// runs again, and a retry cannot publish a second admission.
// The re-mark must keep `FileMeta::substituted_up_to` verbatim: a repartition rewrites no
// bytes. The in-memory `last_sequence` is deliberately **not** advanced here — the edit
// raises it to `B` when it is applied, so a failed write cannot leave an advanced
// allocation behind. A frozen payload is re-sent as it is, so a retry publishes no second
// admission.
let retried = manager.staged_attempt_pending();
if retried {
info!(
@@ -1545,22 +1514,11 @@ impl MitoRegion {
.committed_sequence
.map_or(boundary, |committed| committed.max(boundary)),
);
// Re-mark every file this publish makes visible at `B`: a stale barrier
// below `B` would let file-level pruning skip data that only becomes
// visible now. The re-mark is a statement about the *handle* in this
// region's domain; the bytes keep their numbering.
//
// `preserve_row_sequence` is judged by **ownership**, not by the publish.
// Only a file that changed hands is re-marked as untrusted: its `region_id`
// belongs to another region, so the rows carry numbers this region never
// allocated and are attributed by the creator's cursor and by the file's own
// `substituted_up_to` cut instead of by that marker. A file this region
// already owned (`region_id == self.region_id`) kept its bytes *and* its
// numbers: a repartition that leaves it here changes who publishes it, not
// what its rows say, so the marker is kept exactly as the payload states it.
// Clearing it would make every later exact `(C, H]` read of this region fail
// closed (`read/scan_region.rs::exact_sequence_range`) although the file
// never left, so its new rows could never be read again.
// Re-mark every file this publish makes visible at `B`: a stale barrier below `B`
// would let file-level pruning skip data that only becomes visible now.
// `preserve_row_sequence` is judged by **ownership**: only a file that changed hands
// is cleared, so a file that never left keeps serving the region's exact `(C, H]`
// read.
for file in &mut merged_edit.files_to_add {
file.sequence = std::num::NonZeroU64::new(boundary);
if file.region_id != self.region_id {
@@ -4286,14 +4244,10 @@ mod tests {
assert_eq!(Some(0), published.substituted_up_to);
}
/// The staging exit re-marks the files it makes visible at the holder's admission, but
/// the `preserve_row_sequence` marker is judged by **ownership**: a repartition that
/// leaves a file in the region it already belonged to changes the partition expression
/// and who publishes the layout, not the numbers in the bytes. Clearing the marker of
/// such a file would deny every later exact `(C, H]` read of the region
/// (`read/scan_region.rs::exact_sequence_range` fails closed on a local file without it)
/// even though the file never left. A file adopted from another region still has its
/// marker cleared: its rows carry numbers this region never allocated.
/// The staging exit re-marks the files it makes visible at the holder's admission, but the
/// `preserve_row_sequence` marker is judged by **ownership**: a file that stayed in the
/// region it already belonged to keeps its marker, and a file adopted from another region
/// has it cleared.
#[tokio::test]
async fn test_end_staging_keeps_the_marker_of_a_file_it_already_owned() {
let env = SchedulerEnv::new().await;
-2
View File
@@ -1239,9 +1239,7 @@ pub(crate) enum BackgroundNotify {
/// Notifies that the staged layout of a region must be published.
#[derive(Debug)]
pub(crate) struct ExitStagingRequest {
/// Region id.
pub(crate) region_id: RegionId,
/// Result sender of the apply staging request.
pub(crate) sender: OptionOutputTx,
}
+19 -28
View File
@@ -393,17 +393,15 @@ pub struct FileMeta {
/// restore this capability for untrusted inputs.
#[serde(default, skip_serializing_if = "is_false")]
pub preserve_row_sequence: bool,
/// Upper bound of the physical `__sequence` values that a compaction *substituted*
/// with a file-level constant. Rows at or below it may carry a number this region
/// never allocated for them, so a reader may not compare them with a cursor.
/// `Some(0)` = the column carries no per-row numbering at all (legacy import).
/// Upper bound of the physical `__sequence` values that a compaction *substituted* with a
/// file-level constant. Rows at or below it may carry a number this region never allocated
/// for them, so a reader may not compare them with a cursor. `Some(0)` = the column carries
/// no per-row numbering at all (legacy import). `None` (and the value of every older
/// manifest) means no row of the column was substituted.
///
/// The value is a bound, not a verdict: a row above it still carries a number its
/// writer allocated. A merge takes the maximum of the constants its own reader
/// substituted (see [`substituted_row_constant`]) and of the bounds its inputs
/// already carried, so an output never loses a substitution an input had.
/// `None` (also the value of every older manifest that lacks the field) means no
/// row of the column was substituted.
/// The value is a bound, not a verdict: a row above it still carries a number its writer
/// allocated. A merge states the maximum of the constants it substituted and of the bounds
/// its inputs carried ([`substituted_up_to_after_merge`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub substituted_up_to: Option<SequenceNumber>,
/// Physical encoding, omitted for legacy Parquet files.
@@ -731,16 +729,13 @@ pub(crate) fn known_max_input_sequence<'a>(
max
}
/// Returns the constant a reader substitutes for *every* row of `input` when it reads
/// the file inside `target_region_id`'s sequence domain, or `None` when the physical
/// column is kept as it is.
/// Returns the constant a reader substitutes for *every* row of `input` when it reads the file
/// inside `target_region_id`'s sequence domain, or `None` when the physical column is kept.
///
/// Mirrors the two substituting branches of the Parquet reader in their order
/// (`sst/parquet/reader.rs`): a **foreign** file (`region_id` of another region) and a
/// local file whose per-row numbering is not trusted and whose footer proves an
/// all-zero `__sequence` column. `footer_all_zero` is that footer fact
/// ([`need_override_sequence`](crate::sst::parquet::format::need_override_sequence)),
/// which is a property of the statistics and never of the rows.
/// Mirrors the two substituting branches of the Parquet reader (`sst/parquet/reader.rs`): a
/// foreign file, and a local file whose per-row numbering is not trusted and whose footer proves
/// an all-zero `__sequence` column ([`need_override_sequence`], a property of the statistics and
/// never of the rows).
pub(crate) fn substituted_row_constant(
input: &FileMeta,
target_region_id: RegionId,
@@ -754,16 +749,12 @@ pub(crate) fn substituted_row_constant(
input.sequence.map(|sequence| sequence.get())
}
/// Returns the [`FileMeta::substituted_up_to`] bound the merge of `inputs` states on its
/// output: the maximum of every constant the merge's own reader substituted and of every
/// bound the inputs already carried, or `None` when neither exists.
/// Returns the [`FileMeta::substituted_up_to`] bound the merge of `inputs` states on its output:
/// the maximum of every constant the merge's own reader substituted and of every bound the
/// inputs already carried, or `None` when neither exists.
///
/// `footer_all_zero` is the input's own all-zero `__sequence` footer fact, in the same
/// order as `inputs` ([`substituted_row_constant`] takes it per input).
///
/// Inheriting an input's bound is not optional: a row substituted by an earlier merge
/// stays substituted, and taking only this round's constants would re-expose it as a
/// number a cursor may be compared with whenever this round's constants are smaller.
/// `footer_all_zero` is each input's all-zero `__sequence` footer fact, in input order. An
/// input's bound must be inherited: a row substituted by an earlier merge stays substituted.
pub(crate) fn substituted_up_to_after_merge<'a>(
target_region_id: RegionId,
inputs: impl IntoIterator<Item = (&'a FileMeta, bool)>,
+4 -19
View File
@@ -582,25 +582,10 @@ impl ParquetReaderBuilder {
// sequence that can be trusted.
file_meta.sequence.map(|sequence| sequence.get())
} else if self.read_row_sequence && is_foreign {
// A physical-sequence read keeps an adopted file's own column: the foreign
// branch below would make every row look published by the import, which is
// exactly what the caller needs to split apart.
//
// `preserve_row_sequence` deliberately takes no part here. It describes
// whether the *writer* kept per-row numbering, whereas an import (including
// a repartition's staging apply) only re-marks the handle and copies the
// bytes: the column still holds the numbers their creator allocated. Flow
// judges which rows a substitution produced by the file's own
// `substituted_up_to` cut, not by the marker, so a file an import re-marked
// with `preserve_row_sequence = false` still carries a readable column.
//
// A source file stating `preserve_row_sequence = false` and no cut is
// outside the model (the plateau of a source table whose option is off):
// its column may carry no per-row numbering at all, and there is no cut to
// hide those rows with. Flow never asks for such a region — the region-level
// `preserve_row_sequence` option still denies it the exact range before this
// reader runs — so this branch never sees one; it must not be treated as an
// ordinary file if it ever does.
// A physical-sequence read keeps an adopted file's own column instead of the
// substitution below. `preserve_row_sequence` takes no part: an import only
// re-marks the handle and copies the bytes, and the file's own
// `substituted_up_to` cut is what states a substitution.
None
} else if is_foreign {
file_meta.sequence.map(|sequence| sequence.get())
+3 -13
View File
@@ -439,19 +439,9 @@ impl<S: LogStore> RegionWorkerLoop<S> {
waiters.reply_with(|| Err(error.clone()).context(EditRegionSnafu { region_id }));
return RegionEditDispatch::Rejected;
}
// An edit re-homes files; it records no region-level sequence boundary. The
// numbers an imported file carries are its creator's, and a substitution is
// stated per file by `FileMeta::substituted_up_to`, which the holder-side
// re-mark keeps verbatim: the re-mark re-stamps `sequence` and clears
// `preserve_row_sequence` for the files that changed hands, but it never invents
// or clears a cut. That per-file record is the only statement of that kind the
// engine keeps.
//
// `prepare_region_edit` already assigned the destination sequence to the
// added files (keeping the source sequence of adopted shared files) and cleared
// `preserve_row_sequence` only for the files whose `region_id` is another
// region's; a file this region already owned keeps the marker it states, because
// its row numbers were allocated here.
// An edit re-homes files; it records no region-level sequence boundary. The re-mark
// re-stamps `sequence` and clears `preserve_row_sequence` only for the files that changed
// hands; `FileMeta::substituted_up_to` is kept verbatim.
// Allow retrieving `is_staging` before spawn the edit region task.
let is_staging = region.is_staging();
let expect_state = if is_staging {
+10 -27
View File
@@ -47,17 +47,12 @@ pub const FLOW_REPAIR_MODE: &str = "flow.repair_mode";
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.
/// Reads the physical `__sequence` column of a file this region adopted from another region,
/// instead of virtualizing every row at the handle's admission barrier. The scan then hides the
/// rows whose number is at or below the file's own substituted cut
/// (`FileMeta::substituted_up_to`) and reports their time ranges in `substituted_row_ranges`.
///
/// 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.
/// Only Flow's `sequence_range` incremental delta sets it.
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.
@@ -465,12 +460,8 @@ fn should_collect_region_watermark(
return_region_seq || has_incremental_after_seqs
}
/// 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.
/// Version marker of the expression-keyed cursor form. A reader refuses a version it does not
/// know.
const CURSOR_SHARD_VERSION_KEY: &str = "version";
/// The version this build writes and reads: one partition expression per slice.
const CURSOR_SHARD_VERSION: u64 = 2;
@@ -615,11 +606,8 @@ fn parse_cursor_shard(region_id: u64, shard: &serde_json::Value) -> Result<Curso
}
/// 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.
/// 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<String> {
match partition::expr::PartitionExpr::from_json_str(expr) {
Ok(Some(parsed)) => Ok(parsed.as_json_str().map_err(|e| {
@@ -663,12 +651,7 @@ fn parse_cursor_seq(region_id: u64, raw: &serde_json::Value) -> Result<u64> {
/// 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`.
/// A whole-domain slice is written as an explicit `"expr": null`.
pub fn encode_incremental_after_seqs(cursors: &BTreeMap<u64, Vec<CursorShard>>) -> Result<String> {
let encoded = cursors
.iter()
+30 -114
View File
@@ -48,32 +48,16 @@ pub enum TimeSeriesDistribution {
/// One slice of an incremental cursor: the partition expression selecting a region's value
/// domain together with the last sequence consumed inside it.
///
/// 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.
/// Identity (`PartitionExpr::as_json_str()`) of the expression selecting this slice's
/// value domain, or `None` for the creator region's complete value domain.
pub partition_expr: Option<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,
@@ -121,113 +105,45 @@ pub struct ScanRequest {
pub skip_sst_files: bool,
/// Whether to bind the effective snapshot upper bound when opening the scan.
pub snapshot_on_scan: bool,
/// Explicit intent to read an exact row-level sequence delta `(min, max]`
/// across memtables and all SST files (Flow's `sequence_range` incremental
/// mode). The engine performs exact row-level filtering only when the region
/// preserves per-row sequences and every participating SST file is trusted.
///
/// 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.
/// Explicit intent to read an exact row-level sequence delta `(min, max]` across memtables
/// and all SST files (Flow's `sequence_range` incremental mode). Exact row-level filtering
/// happens only when the region preserves per-row sequences and every participating SST
/// file is trusted; otherwise the read **fails closed** with `SequenceRangeUnsupported`
/// (status `InvalidArguments`, retry hint `FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE`).
///
/// Historical `memtable_only` reads must never set this flag.
pub exact_sequence_range: bool,
/// Whether this scan reads the **physical** `__sequence` column of a foreign file
/// and hides the rows whose number a substitution produced.
/// 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.
/// The reader then keeps the column of any foreign file, filters its rows by
/// [`Self::creator_cursor_shards`] (**fails closed** with `SequenceRangeUnsupported` when
/// the creator's cursor is unknown), and hides the rows at or below the file's own
/// `FileMeta::substituted_up_to` cut, reporting their timestamp ranges as
/// `substituted_row_ranges`. Every other reader, compaction included, leaves this `false`.
pub read_row_sequence: bool,
/// Per-creator-region cursor slices a physical-sequence read filters with
/// ([`Self::read_row_sequence`]), keyed by the region that allocated the numbers.
/// ([`Self::read_row_sequence`]), keyed by the region that allocated the numbers. The least
/// advanced slice is the file-level bound; each row is compared against the slice that
/// selects it.
///
/// 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`.
/// Empty or absent means no cursor of the creator's domain is known, and an adopted file
/// then **fails closed** with `SequenceRangeUnsupported`.
pub creator_cursor_shards: Option<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.
/// Whether this read may cross an invalid boundary: rows whose sequence the region can no
/// longer vouch for are returned instead of the read being refused.
///
/// 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`.
/// It applies no lower sequence bound to memtables, prunes at file granularity only
/// (**fails closed** with `SequenceRangeUnsupported` for a file stating no admission
/// barrier), requires no row-level exactness, and returns a superset of the windows a stale
/// cursor can no longer explain. Ordinary incremental deltas must leave it `false`.
pub read_across_invalid_boundary: bool,
/// 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.
/// Whether this read requires its snapshot to cover the region's flushed frontier: it reads
/// whole windows under a frozen high watermark and may only be committed while 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.
/// Unlike [`Self::read_across_invalid_boundary`] it never prunes at file granularity and
/// never forces a row-sequence override.
pub require_flushed_frontier: bool,
/// Optional hint for the distribution of time-series data.
pub distribution: Option<TimeSeriesDistribution>,