fix(flow): make row-local delta rounds independent of dirty notifications

Three correctness gaps found in review:

- A delta round was gated on the dirty signal, but `insert.rs` dispatches
  the flow mirror before the source write commits and can drop it while the
  insert still succeeds. A round could therefore consume the signal, scan a
  range that excluded the not-yet-committed write, and never be told again,
  leaving those rows permanently absent from the sink. The range scan now
  runs on every scheduled evaluation; an empty range is the no-op.

- The non-append sink contract was checked only at creation, yet
  `ALTER TABLE ... SET (append_mode='true')` is allowed on a live sink.
  A later replay would then duplicate history into the append sink. The
  contract is now revalidated before every plan and write.

- The unoptimized retained plan and the self-referential-sink rejection ran
  for every flow, so leaving the opt-in off was no longer identical to the
  previous behavior. Both are now gated on the opt-in path.

Also state the retention and key-collapse limits of the guarantee in the
module doc.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
discord9
2026-10-19 21:09:44 +08:00
parent a16b6ea04b
commit 433707ad19
3 changed files with 144 additions and 11 deletions
+101 -9
View File
@@ -522,8 +522,12 @@ impl BatchingEngine {
/// Enforces the sink half of the opt-in row-local incremental-read contract: a delta round is
/// written as a keyed materialization, so an append-mode sink would accumulate replayed
/// history instead of overwriting the keys it has already materialized.
fn ensure_simple_source_delta_sink(task: &BatchingTask, sink: &TableRef) -> Result<(), Error> {
/// history instead of overwriting the keys it has already materialized. Also called per
/// round, because `append_mode` can be switched on after creation.
pub(crate) fn ensure_simple_source_delta_sink(
task: &BatchingTask,
sink: &TableRef,
) -> Result<(), Error> {
ensure!(
!Self::table_options_enable_append_mode(&sink.table_info().meta.options.extra_options),
UnsupportedSnafu {
@@ -723,8 +727,14 @@ impl BatchingEngine {
// a round executes: `gen_plan_with_matching_schema_and_values` replans the SQL without the
// flow optimizer, where `now()` and other stable expressions are still time-dependent.
// The optimized plan above remains the source for TQL/time-window/table analysis.
let retained_plan =
sql_to_df_plan(query_ctx.clone(), self.query_engine.clone(), &sql, false).await?;
// Only the opt-in row-local delta feature needs that replan; every other flow keeps the
// optimized plan so that leaving the option off stays byte-identical to the previous
// behavior, without an extra fallible planning pass.
let retained_plan = if batch_opts.experimental_enable_incremental_read {
sql_to_df_plan(query_ctx.clone(), self.query_engine.clone(), &sql, false).await?
} else {
plan.clone()
};
if is_tql {
self.check_is_tql_table(&plan, &query_ctx).await?;
@@ -855,8 +865,9 @@ impl BatchingEngine {
}
// A source whose table id equals the sink id scans without incremental bounds, so delta
// coverage would silently become an unbounded full scan. DDL already rejects equal
// source/sink names; this keeps the fail-closed guarantee local to the flow.
{
// source/sink names; this keeps the fail-closed guarantee local to the flow. It is only
// needed by the opt-in row-local delta path, so other flows see no new rejection.
if task.config.simple_source_delta {
let sink_table_id = table.table_info().table_id();
ensure!(
!source_table_ids_seen.contains(&sink_table_id),
@@ -1232,6 +1243,7 @@ mod tests {
use crate::adapter::AUTO_CREATED_UPDATE_AT_TS_COL;
use crate::test_utils::create_test_query_engine;
use datatypes::schema::SchemaBuilder;
use store_api::mito_engine_options::PRESERVE_ROW_SEQUENCE;
use table::metadata::FilterPushDownType;
use table::test_util::MemTable;
@@ -2066,11 +2078,41 @@ GROUP BY l.number, time_window
],
)
.unwrap();
engine
let source = MemTable::new_with_catalog(
"self_source",
recordbatch.clone(),
SELF_SINK_ID,
"greptime".to_string(),
"public".to_string(),
);
// The rejection only protects the row-local delta guarantee, so this flow must opt in, and
// the delta path requires an append-only source that preserves row sequences.
let mut source_info = (*source.table_info()).clone();
source_info.meta.options.extra_options = HashMap::from([
(APPEND_MODE_KEY.to_string(), "true".to_string()),
(PRESERVE_ROW_SEQUENCE.to_string(), "true".to_string()),
]);
let source = Arc::new(table::Table::new(
Arc::new(source_info),
FilterPushDownType::Unsupported,
source.data_source(),
));
let catalog_manager = engine
.catalog_manager
.as_any()
.downcast_ref::<MemoryCatalogManager>()
.unwrap()
.unwrap();
catalog_manager
.register_table_sync(RegisterTableRequest {
catalog: "greptime".to_string(),
schema: "public".to_string(),
table_name: "self_source".to_string(),
table_id: SELF_SINK_ID,
table: source,
})
.unwrap();
// The sink stays non-append, which is what makes the delta round idempotent.
catalog_manager
.register_table_sync(RegisterTableRequest {
catalog: "greptime".to_string(),
schema: "public".to_string(),
@@ -2085,10 +2127,13 @@ GROUP BY l.number, time_window
),
})
.unwrap();
let mut source_meta = new_test_table_info_with_name(SELF_SINK_ID, "self_source");
source_meta.meta.options.extra_options =
HashMap::from([(APPEND_MODE_KEY.to_string(), "true".to_string())]);
engine
.table_meta
.create_table_metadata(
new_test_table_info_with_name(SELF_SINK_ID, "self_sink"),
source_meta,
TableRouteValue::physical(vec![]),
HashMap::new(),
)
@@ -2099,6 +2144,10 @@ GROUP BY l.number, time_window
// bounds, so delta coverage must fail closed at creation time.
let mut args = flow_create_args(11, "self_sink");
args.source_table_ids = vec![SELF_SINK_ID];
args.flow_options = HashMap::from([(
FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY.to_string(),
"true".to_string(),
)]);
let err = engine
.create_flow_inner(args)
.await
@@ -2134,6 +2183,49 @@ GROUP BY l.number, time_window
.expect("a non-append sink is accepted");
}
#[tokio::test]
async fn test_simple_source_delta_rejects_append_mode_sink_each_round() {
// `append_mode` can be switched on after creation (`ALTER TABLE ... SET (append_mode='true')`),
// so the sink contract must be revalidated when a round plan is generated, not only at
// create time.
let (task, query_engine) =
new_simple_delta_task("SELECT number, ts FROM numbers_with_ts", "delta_sink", true)
.await;
assert!(task.config.simple_source_delta);
let append_sink = sink_with_extra_options(
"delta_sink",
HashMap::from([(APPEND_MODE_KEY.to_string(), "true".to_string())]),
);
query_engine
.engine_state()
.catalog_manager()
.as_any()
.downcast_ref::<MemoryCatalogManager>()
.expect("test catalog manager is a memory catalog")
.register_table_sync(RegisterTableRequest {
catalog: "greptime".to_string(),
schema: "public".to_string(),
table_name: "delta_sink".to_string(),
table_id: 9501,
table: append_sink,
})
.unwrap();
let err = match task
.gen_insert_plan_with_values_unlocked(&query_engine, None, &BTreeMap::new(), false)
.await
{
Ok(_) => panic!("an append-mode sink must be rejected at round generation"),
Err(err) => err,
};
assert!(
err.to_string()
.contains("incremental read requires a non-append sink table"),
"{err}"
);
}
#[tokio::test]
async fn test_simple_source_delta_requires_derivable_sink_keys() {
// Dropping the source time index makes the auto-created sink keyless for a delta round.
@@ -18,6 +18,13 @@
//! rows written since the last checkpoint. That is correct only because the projection is a
//! deterministic, row-local function of a single source row, and because a delta round is written
//! as a keyed materialization: rows sharing the sink key collapse under ordinary sink semantics.
//!
//! The guarantee covers only source rows still retained in the source table: a finite source TTL
//! plus compaction can remove rows this flow never read, for example while it is paused or down,
//! and that loss is not detected here. This path also applies no `expire_after` filtering, because
//! a window-less flow has no time-window expression to evaluate. Finally, because the keyed
//! materialization keeps one row per key, rows that project to identical sink keys collapse, so a
//! "delta read" does not promise to preserve every historical source write.
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion_expr::{Expr, LogicalPlan, Volatility};
+36 -2
View File
@@ -55,6 +55,7 @@ use tokio::time::Instant;
use crate::batching_mode::BatchingModeOptions;
use crate::batching_mode::checkpoint::checkpoint_mode_label;
use crate::batching_mode::engine::BatchingEngine;
use crate::batching_mode::eval_schedule::{EvalSchedule, select_due_scheduled_times};
use crate::batching_mode::frontend_client::{FrontendClient, PeerDesc};
use crate::batching_mode::simple_delta;
@@ -1112,6 +1113,13 @@ impl BatchingTask {
)
.await?;
// `ALTER TABLE ... SET (append_mode = 'true')` is allowed after creation, so the sink
// contract that makes a delta round idempotent must be revalidated before every plan and
// write, not only when the flow was created.
if self.config.simple_source_delta {
BatchingEngine::ensure_simple_source_delta_sink(self, &table)?;
}
let table_meta = &table.table_info().meta;
let merge_mode_last_non_null =
is_merge_mode_last_non_null(&table_meta.options.extra_options);
@@ -1610,7 +1618,10 @@ impl BatchingTask {
#[allow(clippy::too_many_arguments)]
/// Build an unfiltered plan only when the live dirty signal was present;
/// otherwise skip this round without querying.
/// otherwise skip this round without querying. `run_when_clean` runs the
/// round anyway: the row-local delta path cannot depend on the dirty
/// notification, which can arrive before the source write commits or be
/// dropped, so an empty sequence range is its natural no-op.
async fn gen_unfiltered_plan_info_if_dirty(
&self,
engine: QueryEngineRef,
@@ -1621,9 +1632,10 @@ impl BatchingTask {
values: &BTreeMap<String, ScalarValue>,
retention_filter: Option<(&str, Timestamp, &'static str)>,
coverage: QueryCoverage,
run_when_clean: bool,
) -> Result<Option<PlanInfo>, Error> {
let (is_dirty, dirty_windows_to_restore) = self.drain_dirty_windows_signal();
if !is_dirty {
if !is_dirty && !run_when_clean {
debug!("Flow id={:?}, no new data, not update", self.config.flow_id);
return Ok(None);
}
@@ -2142,6 +2154,9 @@ impl BatchingTask {
&& self.config.simple_source_delta
&& self.should_use_unfiltered_incremental_delta()
{
// The dirty notification is only bookkeeping here: it is dispatched before
// the source write commits and may be dropped with the mirror, so the round
// must run regardless and let an empty sequence range be the natural no-op.
return self
.gen_unfiltered_plan_info_if_dirty(
engine,
@@ -2152,6 +2167,7 @@ impl BatchingTask {
values,
None,
QueryCoverage::IncrementalDelta,
true,
)
.await;
}
@@ -2259,6 +2275,7 @@ impl BatchingTask {
values,
retention_filter,
QueryCoverage::IncrementalDelta,
false,
)
.await;
}
@@ -2838,6 +2855,23 @@ mod simple_source_delta_tests {
);
assert!(task.state.read().unwrap().dirty_time_windows.is_empty());
// The dirty notification can be dropped or arrive before the source write commits, so a
// clean delta round must still produce a plan: the empty sequence range is the no-op.
let clean = task
.gen_query_with_time_window(query_engine.clone(), &sink_schema, &[], false, None)
.await
.unwrap()
.expect("a clean delta round must still generate a plan");
assert!(
matches!(clean.coverage, QueryCoverage::IncrementalDelta),
"a clean delta round must stay an IncrementalDelta plan, got {}",
clean.plan
);
assert!(
task.state.read().unwrap().dirty_time_windows.is_empty(),
"the empty dirty signal must stay consumed"
);
// A forced full snapshot (durable recovery) stays a full snapshot.
add_dirty_window(&task);
let forced = task