fix(flow): repair the windows a delta hid instead of settling over them

An incremental delta asks the scan to read physical sequences, so a file
carrying a substituted cut hides the rows at or below it and reports their
timestamps. Nothing consumed that report: the checkpoint settled the
additive delta and advanced, so the hidden rows reached no window and a
pure OSS flow lost them.

Refuse to settle such a delta. Turn the reported inclusive ranges into
half-open flow windows (the inclusive end is widened by one millisecond so
a range ending on a bucket boundary still selects that bucket), start the
existing fenced repair over exactly those windows under the delta's own
proved high watermark, and let finish_fenced_repair promote it once a
chunk proves the fence. A range that cannot be expressed, or a fence that
cannot be proved, fails the round with the cursor untouched instead of
settling.

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-26 19:07:32 +08:00
parent 26508dcada
commit eda9d7697d
3 changed files with 542 additions and 3 deletions
+16 -1
View File
@@ -1576,7 +1576,22 @@ impl BatchingTask {
let (affected_rows, _) = res.output.extract_rows_and_cost();
let decision = {
let mut state = self.state.write().unwrap();
Self::apply_query_result_to_state(&mut state, &res, elapsed, coverage)
match self.refuse_substituted_delta(&mut state, &res, elapsed, coverage) {
Ok(Some(decision)) => decision,
Ok(None) => Self::apply_query_result_to_state(&mut state, &res, elapsed, coverage),
Err(err) => {
// The delta's DML already ran, so a scan that hid rows cannot be settled
// additively and there is no fence to recompute the affected windows
// under. Fail the round with the cursor untouched: the caller restores
// the consumed dirty signal, and the next round replays the same delta
// instead of advancing past rows no window received.
drop(state);
warn!(
"Flow {flow_id} refused to settle an incremental delta that hid rows: {err}"
);
return Err(err);
}
}
};
Self::record_checkpoint_decision(flow_id, decision);
Ok(Some((affected_rows, elapsed)))
+177 -1
View File
@@ -12,19 +12,24 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use std::time::Duration;
use client::OutputWithMetrics;
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use common_recordbatch::adapter::SubstitutedRowRanges;
use common_telemetry::tracing::warn;
use common_telemetry::{debug, info};
use common_time::Timestamp;
use common_time::timestamp::TimeUnit;
use crate::batching_mode::checkpoint::{
FlowCheckpointDecision, FlowQueryFallbackReason, checkpoint_mode_label,
};
use crate::batching_mode::state::{CheckpointMode, TaskState};
use crate::batching_mode::state::{CheckpointMode, DirtyTimeWindows, TaskState};
use crate::batching_mode::task::{BatchingTask, QueryCoverage};
use crate::error::UnexpectedSnafu;
use crate::metrics::{
METRIC_FLOW_BATCHING_ENGINE_CHECKPOINT_DECISION_CNT, METRIC_FLOW_BATCHING_ENGINE_QUERY_MODE_CNT,
};
@@ -246,6 +251,177 @@ impl BatchingTask {
}
}
/// Turns the substituted row ranges a physical-sequence delta reported into the
/// complete set of half-open `[start, end)` windows a scoped recompute has to cover.
///
/// The engine reports each range as an **inclusive** `[start, end]` pair of
/// milliseconds ([`SubstitutedRowRanges`]), while a flow time window is half-open and
/// [`DirtyTimeWindows::align_time_window`] treats an end that already sits on a window
/// boundary as exclusive. The inclusive end is therefore widened by one millisecond
/// before alignment, so a row whose timestamp lies exactly on a boundary - a point
/// range `[t, t]` included - still selects the bucket that *contains* it instead of
/// ending the window just before it.
///
/// Fails when the ranges cannot be expressed as bounded windows: the caller must then
/// fail the round instead of settling a delta that hid rows it cannot recompute.
pub(super) fn substituted_repair_windows(
&self,
ranges: &[SubstitutedRowRanges],
) -> Result<Vec<(Timestamp, Timestamp)>, Error> {
let Some(time_window_expr) = &self.config.time_window_expr else {
return Err(UnexpectedSnafu {
reason: format!(
"Flow {} scan reported substituted row ranges, but the flow has no time-window expression to turn them into recompute windows",
self.config.flow_id
),
}
.build());
};
let mut windows = Vec::new();
for entry in ranges {
for range in &entry.ranges {
if range.end_millis < range.start_millis {
return Err(UnexpectedSnafu {
reason: format!(
"Flow {} scan reported the inverted substituted range [{}, {}] of region {}",
self.config.flow_id,
range.start_millis,
range.end_millis,
entry.region_id
),
}
.build());
}
let start = Timestamp::new(range.start_millis, TimeUnit::Millisecond);
// The reported end is inclusive; alignment expects a half-open end, so the
// last millisecond of the range must still fall inside the aligned end.
let end = Timestamp::new(range.end_millis.saturating_add(1), TimeUnit::Millisecond);
let (window_start, window_end) =
DirtyTimeWindows::align_time_window(start, Some(end), time_window_expr)?;
let Some(window_end) = window_end else {
return Err(UnexpectedSnafu {
reason: format!(
"Flow {} cannot align the substituted range [{}, {}] of region {} to a bounded time window",
self.config.flow_id,
range.start_millis,
range.end_millis,
entry.region_id
),
}
.build());
};
windows.push((window_start, window_end));
}
}
Ok(windows)
}
/// Refuses to settle an incremental delta whose scan hid substituted rows, and
/// replaces that delta's additive contribution with a fenced full-window recompute.
///
/// A physical-sequence delta hides every row at or below a file's substituted cut and
/// reports the hidden rows' timestamp ranges in its terminal metrics
/// ([`common_recordbatch::adapter::RecordBatchMetrics::substituted_row_ranges`]). Its
/// additive DML has already run by the time those metrics are read, so re-marking the
/// windows would only schedule work: the affected windows are recomputed as a fenced
/// full-window read over exactly the reported ranges (which reads the hidden rows, as a
/// repair read does not hide anything), under the delta's own proved high watermark
/// `H`. The delta itself is **not** settled: the checkpoints keep the pre-round cursor
/// until [`TaskState::finish_fenced_repair`] promotes `H` after the repair proved it.
///
/// `Ok(None)` means the result substituted nothing, so the caller settles it as before.
/// `Err` means the round cannot be expressed safely (no windows, or no fence to repair
/// under), so the caller must fail it without advancing the cursor.
pub(super) fn refuse_substituted_delta(
&self,
state: &mut TaskState,
res: &OutputWithMetrics,
elapsed: Duration,
coverage: &QueryCoverage,
) -> Result<Option<FlowCheckpointDecision>, Error> {
let substituted = res
.metrics
.get()
.map(|metrics| metrics.substituted_row_ranges)
.unwrap_or_default();
if substituted.is_empty() {
return Ok(None);
}
if !matches!(coverage, QueryCoverage::IncrementalDelta) {
// Only the incremental delta asks a scan to read physical sequences and to hide
// the rows a substitution produced. Any other coverage reports an empty range
// set, so a non-empty one there means a caller-owned read this wrapper cannot
// refuse on its behalf.
warn!(
"Flow {} observed substituted row ranges on a coverage that is not an incremental delta; leaving the checkpoint transition to the established path",
self.config.flow_id
);
return Ok(None);
}
let windows = self.substituted_repair_windows(&substituted)?;
if windows.is_empty() {
return Err(UnexpectedSnafu {
reason: format!(
"Flow {} delta substituted rows but reported no timestamp range to recompute",
self.config.flow_id
),
}
.build());
}
// The repair must run under the delta's own proved high watermark: that is the fence
// the repair chunks re-prove, and the only bound the affected windows may be settled at.
let participating = res.participating_regions().ok_or_else(|| {
UnexpectedSnafu {
reason: format!(
"Flow {} delta substituted rows but returned no terminal metrics to fence the repair with",
self.config.flow_id
),
}
.build()
})?;
let watermark_map = res.region_watermark_map().ok_or_else(|| {
UnexpectedSnafu {
reason: format!(
"Flow {} delta substituted rows but returned no per-region watermarks to fence the repair with",
self.config.flow_id
),
}
.build()
})?;
if !state
.can_advance_incremental_checkpoints_with_participation(&participating, &watermark_map)
{
return Err(UnexpectedSnafu {
reason: format!(
"Flow {} delta substituted rows but could not prove a high watermark over participating regions {participating:?}",
self.config.flow_id
),
}
.build());
}
state.after_query_exec(elapsed, true);
let high: BTreeMap<u64, u64> = watermark_map.into_iter().collect();
state.start_fenced_repair_windows(high, windows);
let repair = state.pending_fenced_repair().ok_or_else(|| {
UnexpectedSnafu {
reason: format!(
"Flow {} failed to start a fenced repair for its substituted row ranges",
self.config.flow_id
),
}
.build()
})?;
Ok(Some(FlowCheckpointDecision::ContinuedFencedRepair {
pending_windows: repair.pending_windows().len(),
watermarks: repair.high().len(),
}))
}
pub(super) fn record_checkpoint_decision(flow_id: FlowId, decision: FlowCheckpointDecision) {
let flow_id = flow_id.to_string();
METRIC_FLOW_BATCHING_ENGINE_CHECKPOINT_DECISION_CNT
+349 -1
View File
@@ -28,7 +28,9 @@ use common_error::mock::MockError;
use common_error::status_code::StatusCode;
use common_query::Output;
use common_recordbatch::RecordBatch;
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
use common_recordbatch::adapter::{
RecordBatchMetrics, RegionWatermarkEntry, SubstitutedRange, SubstitutedRowRanges,
};
use common_time::{TimeToLive, Timestamp};
use datatypes::data_type::ConcreteDataType as CDT;
use datatypes::schema::{ColumnSchema, Schema};
@@ -2475,6 +2477,352 @@ fn test_apply_query_result_to_state_advances_incremental_subset() {
);
}
/// Builds a delta result that proves `watermarks` and reports `substituted` as the rows
/// its scan hid, given as `(region id, inclusive [start, end] millisecond ranges)`.
fn output_with_substituted_ranges(
watermarks: impl IntoIterator<Item = (u64, Option<u64>)>,
substituted: impl IntoIterator<Item = (u64, Vec<(i64, i64)>)>,
) -> OutputWithMetrics {
let result = OutputWithMetrics::from_output(Output::new_with_affected_rows(0));
result.metrics.update(Some(RecordBatchMetrics {
region_watermarks: watermarks
.into_iter()
.map(|(region_id, watermark)| RegionWatermarkEntry {
region_id,
partition_expr: None,
watermark,
visible_foreign_file_creators: None,
})
.collect(),
substituted_row_ranges: substituted
.into_iter()
.map(|(region_id, ranges)| SubstitutedRowRanges {
region_id,
ranges: ranges
.into_iter()
.map(|(start_millis, end_millis)| SubstitutedRange {
start_millis,
end_millis,
})
.collect(),
})
.collect(),
..Default::default()
}));
result.metrics.mark_ready();
result
}
async fn new_substituted_repair_task() -> BatchingTask {
new_time_window_test_task_with_query(
"SELECT max(number) AS output_value, date_bin(INTERVAL '5 second', ts) AS output_window FROM numbers_with_ts GROUP BY output_window",
)
.await
.task
}
#[tokio::test]
async fn test_substituted_repair_windows_include_the_bucket_of_an_inclusive_end() {
let task = new_substituted_repair_task().await;
let ranges = vec![SubstitutedRowRanges {
region_id: 1,
ranges: vec![
// Rows up to and including the 10s boundary were hidden. The bucket
// `[10s, 15s)` contains the last hidden row, so it must be recomputed.
SubstitutedRange {
start_millis: 4_000,
end_millis: 10_000,
},
// A point range must select the bucket that contains it as well.
SubstitutedRange {
start_millis: 121_000,
end_millis: 121_000,
},
],
}];
let windows = task.substituted_repair_windows(&ranges).unwrap();
assert_eq!(
windows,
vec![
(Timestamp::new_second(0), Timestamp::new_second(15)),
(Timestamp::new_second(120), Timestamp::new_second(125)),
]
);
// The reported end is inclusive, so the bucket that starts exactly at it is affected:
// passing `end` through as a half-open end would stop the window at 10s and leave the
// hidden row at 10s unrecomputed.
assert!(
windows.iter().any(|(start, end)| {
*start <= Timestamp::new_second(10) && Timestamp::new_second(15) <= *end
}),
"the bucket containing the inclusive end must be recomputed, got {windows:?}"
);
}
#[tokio::test]
async fn test_substituted_repair_windows_reject_an_inverted_range() {
let task = new_substituted_repair_task().await;
let ranges = vec![SubstitutedRowRanges {
region_id: 1,
ranges: vec![SubstitutedRange {
start_millis: 10_000,
end_millis: 4_000,
}],
}];
let err = task.substituted_repair_windows(&ranges).unwrap_err();
assert!(
err.to_string().contains("inverted substituted range"),
"{err}"
);
}
#[tokio::test]
async fn test_substituted_repair_windows_need_a_time_window_expr() {
// A flow without a time-window expression cannot turn the reported ranges into
// recompute windows at all, which is the "fail the round" case.
let parts = new_test_task_engine_and_plan_with_query(
"SELECT number, ts FROM numbers_with_ts",
"numbers_with_ts",
)
.await;
let ranges = vec![SubstitutedRowRanges {
region_id: 1,
ranges: vec![SubstitutedRange {
start_millis: 4_000,
end_millis: 10_000,
}],
}];
let err = parts.task.substituted_repair_windows(&ranges).unwrap_err();
assert!(
err.to_string().contains("no time-window expression"),
"{err}"
);
}
#[tokio::test]
async fn test_delta_reporting_substituted_rows_repairs_instead_of_settling() {
let task = new_substituted_repair_task().await;
let delta =
output_with_substituted_ranges([(1_u64, Some(20_u64))], [(1_u64, vec![(4_000, 10_000)])]);
// The same terminal metrics settle a delta additively when nothing was substituted:
// this is the transition the round must not take once rows were hidden.
{
let query_ctx = QueryContext::arc();
let (_tx, rx) = tokio::sync::oneshot::channel();
let mut unsettled_state = TaskState::new(query_ctx, rx);
unsettled_state.advance_checkpoints(HashMap::from([(1_u64, 10_u64)]));
let decision = BatchingTask::apply_query_result_to_state(
&mut unsettled_state,
&delta,
std::time::Duration::from_millis(1),
&QueryCoverage::IncrementalDelta,
);
assert_eq!(
decision,
FlowCheckpointDecision::AdvancedIncremental {
participating_regions: 1,
watermarks: 1,
}
);
assert_eq!(
unsettled_state.checkpoints(),
&BTreeMap::from([(1_u64, 20_u64)])
);
}
task.state
.write()
.unwrap()
.advance_checkpoints(HashMap::from([(1_u64, 10_u64)]));
let decision = {
let mut state = task.state.write().unwrap();
task.refuse_substituted_delta(
&mut state,
&delta,
std::time::Duration::from_millis(1),
&QueryCoverage::IncrementalDelta,
)
.unwrap()
};
// The delta is refused: it is not settled additively, and the affected windows are
// queued as a fenced repair under the delta's own proved high H.
assert_eq!(
decision,
Some(FlowCheckpointDecision::ContinuedFencedRepair {
pending_windows: 1,
watermarks: 1,
})
);
let high = BTreeMap::from([(1_u64, 20_u64)]);
{
let state = task.state.read().unwrap();
assert_eq!(
state.checkpoints(),
&BTreeMap::from([(1_u64, 10_u64)]),
"the refused delta must not advance the cursor"
);
assert_eq!(state.checkpoint_mode(), CheckpointMode::FullSnapshot);
let repair = state.pending_fenced_repair().unwrap();
assert_eq!(repair.high(), &high);
assert_eq!(repair.pending_windows().len(), 1);
}
// The next round recomputes exactly the affected window, as a fenced full-window read.
let (filter, coverage) = {
let mut state = task.state.write().unwrap();
let col_name = task
.config
.time_window_expr
.as_ref()
.unwrap()
.column_name
.clone();
let filter = state
.gen_scoped_filter_exprs(
&col_name,
None,
chrono::Duration::seconds(5),
20,
1,
Some(&task),
)
.unwrap()
.unwrap();
let repair_high = state
.pending_fenced_repair()
.expect("a refused delta leaves a fenced repair pending")
.high()
.clone();
(
filter,
QueryCoverage::FencedRepairChunk { high: repair_high },
)
};
assert_eq!(
filter.time_ranges,
vec![(Timestamp::new_second(0), Timestamp::new_second(15))],
"the whole affected window is recomputed once, not a partial range"
);
match &coverage {
QueryCoverage::FencedRepairChunk {
high: coverage_high,
} => {
assert_eq!(
coverage_high, &high,
"the recompute runs under the delta's fence"
);
}
_ => panic!("the recompute of a refused delta must be a fenced repair chunk"),
}
let extensions = task
.build_flow_query_extensions(false, coverage.is_incremental_delta())
.await
.unwrap();
// A repair read names the fence and does not request `flow.read_row_sequence`, so it
// reads the rows the delta hid: the recompute delivers them to the window exactly once.
assert_eq!(
extensions,
vec![
("flow.return_region_seq", "true".to_string()),
(FLOW_REPAIR_MODE, FLOW_REPAIR_MODE_FENCED.to_string()),
]
);
// Only the fenced repair may settle: once it proves H, the cursor advances to exactly H.
let chunk = output_with_region_watermarks([(1_u64, Some(20_u64))]);
let decision = {
let mut state = task.state.write().unwrap();
BatchingTask::apply_query_result_to_state(
&mut state,
&chunk,
std::time::Duration::from_millis(1),
&coverage,
)
};
assert_eq!(
decision,
FlowCheckpointDecision::AdvancedFromFullSnapshot {
participating_regions: 1,
watermarks: 1,
}
);
let state = task.state.read().unwrap();
assert!(state.pending_fenced_repair().is_none());
assert_eq!(state.checkpoints(), &BTreeMap::from([(1_u64, 20_u64)]));
assert_eq!(state.checkpoint_mode(), CheckpointMode::Incremental);
}
#[tokio::test]
async fn test_substituted_delta_without_a_provable_fence_fails_the_round() {
let task = new_substituted_repair_task().await;
task.state
.write()
.unwrap()
.advance_checkpoints(HashMap::from([(1_u64, 10_u64), (2_u64, 10_u64)]));
// Region 2 participated but proved no watermark, so no fence covers the affected
// windows and the delta must not be settled.
let delta = output_with_substituted_ranges(
[(1_u64, Some(20_u64)), (2_u64, None)],
[(1_u64, vec![(4_000, 10_000)])],
);
let err = {
let mut state = task.state.write().unwrap();
task.refuse_substituted_delta(
&mut state,
&delta,
std::time::Duration::from_millis(1),
&QueryCoverage::IncrementalDelta,
)
.unwrap_err()
};
assert!(
err.to_string().contains("could not prove a high watermark"),
"{err}"
);
let state = task.state.read().unwrap();
assert_eq!(
state.checkpoints(),
&BTreeMap::from([(1_u64, 10_u64), (2_u64, 10_u64)])
);
assert_eq!(state.checkpoint_mode(), CheckpointMode::Incremental);
assert!(state.pending_fenced_repair().is_none());
}
#[tokio::test]
async fn test_delta_without_substituted_rows_keeps_settling_additively() {
let task = new_substituted_repair_task().await;
task.state
.write()
.unwrap()
.advance_checkpoints(HashMap::from([(1_u64, 10_u64)]));
let delta = output_with_region_watermarks([(1_u64, Some(20_u64))]);
let decision = {
let mut state = task.state.write().unwrap();
task.refuse_substituted_delta(
&mut state,
&delta,
std::time::Duration::from_millis(1),
&QueryCoverage::IncrementalDelta,
)
.unwrap()
};
assert_eq!(decision, None);
let state = task.state.read().unwrap();
assert!(state.pending_fenced_repair().is_none());
assert_eq!(state.checkpoints(), &BTreeMap::from([(1_u64, 10_u64)]));
}
#[test]
fn test_scoped_base_repair_with_dirty_backlog_starts_fenced_repair_from_full_snapshot() {
let query_ctx = QueryContext::arc();