1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
16use std::sync::{Arc, RwLock};
17use std::time::{Duration, SystemTime, UNIX_EPOCH};
18
19use api::v1::{CreateTableExpr, TableName};
20use catalog::CatalogManagerRef;
21use catalog::kvbackend::KvBackendCatalogManager;
22use client::OutputWithMetrics;
23use common_error::ext::BoxedError;
24use common_meta::key::schema_name::SchemaNameKey;
25use common_query::OutputData;
26use common_query::logical_plan::breakup_insert_plan;
27use common_telemetry::tracing::warn;
28use common_telemetry::{debug, info};
29use common_time::{TimeToLive, Timestamp};
30use datafusion::datasource::DefaultTableSource;
31use datafusion::sql::unparser::expr_to_sql;
32use datafusion_common::tree_node::{Transformed, TreeNode};
33use datafusion_common::utils::quote_identifier;
34use datafusion_common::{DFSchemaRef, ScalarValue, TableReference};
35use datafusion_expr::{DmlStatement, LogicalPlan, Projection, WriteOp, col, lit};
36use datatypes::schema::Schema;
37use datatypes::vectors::Helper;
38use futures::TryStreamExt;
39use query::QueryEngineRef;
40use query::options::{
41 FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE,
42 FLOW_RETURN_REGION_SEQ,
43};
44use query::query_engine::DefaultSerializer;
45use session::context::QueryContextRef;
46use snafu::{OptionExt, ResultExt};
47use sql::parsers::utils::is_tql;
48use store_api::mito_engine_options::MERGE_MODE_KEY;
49use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
50use table::TableRef;
51use table::table::adapter::DfTableProviderAdapter;
52use tokio::sync::oneshot::error::TryRecvError;
53use tokio::sync::{Mutex, OwnedMutexGuard, oneshot};
54use tokio::time::Instant;
55
56use crate::batching_mode::BatchingModeOptions;
57use crate::batching_mode::checkpoint::checkpoint_mode_label;
58use crate::batching_mode::eval_schedule::{EvalSchedule, select_due_scheduled_times};
59use crate::batching_mode::frontend_client::{FrontendClient, PeerDesc};
60use crate::batching_mode::state::{
61 CheckpointMode, DirtyTimeWindows, FilterExprInfo, TaskState, to_df_literal,
62};
63use crate::batching_mode::table_creator::{QueryType, create_table_with_expr};
64use crate::batching_mode::time_window::TimeWindowExpr;
65use crate::batching_mode::utils::{
66 AddFilterRewriter, ColumnMatcherRewriter, analyze_incremental_aggregate_plan, df_plan_to_sql,
67 gen_plan_with_matching_schema_and_values, get_table_info_df_schema, sql_to_df_plan,
68};
69use crate::df_optimizer::apply_df_optimizer;
70use crate::error::{
71 DatafusionSnafu, ExternalSnafu, InvalidQuerySnafu, SubstraitEncodeLogicalPlanSnafu,
72 UnexpectedSnafu,
73};
74use crate::metrics::{
75 METRIC_FLOW_BATCHING_ENGINE_ERROR_CNT, METRIC_FLOW_BATCHING_ENGINE_QUERY_TIME,
76 METRIC_FLOW_BATCHING_ENGINE_SLOW_QUERY, METRIC_FLOW_BATCHING_ENGINE_START_QUERY_CNT,
77 METRIC_FLOW_ROWS,
78};
79use crate::{Error, FlowId};
80
81mod ckpt;
82mod inc;
83
84fn wall_clock_unix_secs() -> i64 {
86 SystemTime::now()
87 .duration_since(UNIX_EPOCH)
88 .unwrap_or_default()
89 .as_secs() as i64
90}
91
92fn initial_schedule_cursor(start_secs: i64, interval_secs: i64) -> Result<i64, Error> {
100 let cursor = i128::from(start_secs) - i128::from(interval_secs);
101 i64::try_from(cursor).map_err(|_| {
102 UnexpectedSnafu {
103 reason: format!(
104 "Cannot compute the initial eval schedule cursor one interval before start {start_secs} (interval={interval_secs}): {cursor} does not fit in i64"
105 ),
106 }
107 .build()
108 })
109}
110
111fn sleep_delta_secs(next: i64, wall_now_secs: i64) -> Result<u64, Error> {
119 let delta = i128::from(next) - i128::from(wall_now_secs);
120 u64::try_from(delta).map_err(|_| {
121 UnexpectedSnafu {
122 reason: format!(
123 "Cannot sleep until the next scheduled time {next}: the delta from wall clock {wall_now_secs} is {delta} seconds, which does not fit in u64"
124 ),
125 }
126 .build()
127 })
128}
129
130fn scheduled_time_millis(scheduled_time_secs: i64) -> Result<i64, Error> {
137 scheduled_time_secs.checked_mul(1000).ok_or_else(|| {
138 UnexpectedSnafu {
139 reason: format!(
140 "Cannot convert scheduled time {scheduled_time_secs}s to milliseconds: the product exceeds i64"
141 ),
142 }
143 .build()
144 })
145}
146
147#[derive(Clone)]
149pub struct TaskConfig {
150 pub flow_id: FlowId,
151 pub query: String,
152 pub output_schema: DFSchemaRef,
154 pub time_window_expr: Option<TimeWindowExpr>,
155 pub expire_after: Option<i64>,
157 pub sink_table_name: [String; 3],
158 pub source_table_names: HashSet<[String; 3]>,
159 pub catalog_manager: CatalogManagerRef,
160 pub query_type: QueryType,
161 pub batch_opts: Arc<BatchingModeOptions>,
162 pub exact_sequence_range_required: bool,
163 pub flow_eval_interval: Option<Duration>,
164 pub eval_schedule: Option<EvalSchedule>,
166}
167
168fn determine_query_type(query: &str, query_ctx: &QueryContextRef) -> Result<QueryType, Error> {
169 let is_tql = is_tql(query_ctx.sql_dialect(), query)
170 .map_err(BoxedError::new)
171 .context(ExternalSnafu)?;
172 Ok(if is_tql {
173 QueryType::Tql
174 } else {
175 QueryType::Sql
176 })
177}
178
179fn is_merge_mode_last_non_null(options: &HashMap<String, String>) -> bool {
180 options
181 .get(MERGE_MODE_KEY)
182 .map(|mode| mode.eq_ignore_ascii_case("last_non_null"))
183 .unwrap_or(false)
184}
185
186fn encode_insert_plan_request(
187 insert_to: TableName,
188 insert_input_plan: &LogicalPlan,
189) -> Result<api::v1::QueryRequest, Error> {
190 let message = DFLogicalSubstraitConvertor {}
191 .encode(insert_input_plan, DefaultSerializer)
192 .context(SubstraitEncodeLogicalPlanSnafu)?;
193 Ok(api::v1::QueryRequest {
194 query: Some(api::v1::query_request::Query::InsertIntoPlan(
195 api::v1::InsertIntoPlan {
196 table_name: Some(insert_to),
197 logical_plan: message.to_vec(),
198 },
199 )),
200 })
201}
202
203fn recovery_aggregate_input(plan: &LogicalPlan) -> Result<LogicalPlan, Error> {
204 let plan = match plan {
205 LogicalPlan::Projection(projection) => projection.input.as_ref(),
206 _ => plan,
207 };
208 let LogicalPlan::Aggregate(aggregate) = plan else {
209 return UnexpectedSnafu {
210 reason: "Recovery timestamp projection did not find an aggregate".to_string(),
211 }
212 .fail();
213 };
214 Ok(aggregate.input.as_ref().clone())
215}
216
217fn capture_recovery_batch_windows(
218 batch: &common_recordbatch::RecordBatch,
219 time_window_expr: &TimeWindowExpr,
220 windows: &mut BTreeSet<(Timestamp, Timestamp)>,
221) -> Result<(), Error> {
222 if batch.num_columns() != 1 {
223 return UnexpectedSnafu {
224 reason: format!(
225 "Recovery timestamp projection returned {} columns instead of one",
226 batch.num_columns()
227 ),
228 }
229 .fail();
230 }
231 let values = Helper::try_into_vector(batch.column(0).clone())
232 .map_err(BoxedError::new)
233 .context(ExternalSnafu)?;
234 for index in 0..values.len() {
235 let timestamp = values.get(index).as_timestamp().context(UnexpectedSnafu {
236 reason: "Recovery timestamp projection returned a null or non-timestamp value"
237 .to_string(),
238 })?;
239 let (start, end) = time_window_expr.eval(timestamp)?;
240 let window = (
241 start.context(UnexpectedSnafu {
242 reason: "Recovery time-window expression returned no lower bound".to_string(),
243 })?,
244 end.context(UnexpectedSnafu {
245 reason: "Recovery time-window expression returned no upper bound".to_string(),
246 })?,
247 );
248 windows.insert(window);
249 }
250 Ok(())
251}
252
253fn format_insert_target_columns(plan: &LogicalPlan) -> String {
254 plan.schema()
255 .fields()
256 .iter()
257 .map(|field| quote_identifier(field.name()).to_string())
258 .collect::<Vec<_>>()
259 .join(", ")
260}
261
262pub struct BatchingExecutionGuard {
265 _lock: OwnedMutexGuard<()>,
266 restore: Option<(Arc<RwLock<TaskState>>, QueryContextRef)>,
267}
268
269impl BatchingExecutionGuard {
270 fn new(lock: OwnedMutexGuard<()>) -> Self {
271 Self {
272 _lock: lock,
273 restore: None,
274 }
275 }
276
277 fn restore_query_context(&mut self, state: Arc<RwLock<TaskState>>, old_ctx: QueryContextRef) {
278 self.restore = Some((state, old_ctx));
279 }
280}
281
282impl Drop for BatchingExecutionGuard {
283 fn drop(&mut self) {
284 if let Some((state, old_ctx)) = self.restore.take()
285 && let Ok(mut state) = state.write()
286 {
287 state.query_ctx = old_ctx;
288 }
289 }
290}
291
292#[derive(Clone)]
293pub struct BatchingTask {
294 pub config: Arc<TaskConfig>,
295 pub state: Arc<RwLock<TaskState>>,
296 execution_lock: Arc<Mutex<()>>,
300 execution: Option<Arc<dyn crate::BatchingExecution>>,
301}
302
303pub struct TaskArgs<'a> {
305 pub flow_id: FlowId,
306 pub query: &'a str,
307 pub plan: LogicalPlan,
308 pub time_window_expr: Option<TimeWindowExpr>,
309 pub expire_after: Option<i64>,
310 pub sink_table_name: [String; 3],
311 pub source_table_names: Vec<[String; 3]>,
312 pub query_ctx: QueryContextRef,
313 pub catalog_manager: CatalogManagerRef,
314 pub shutdown_rx: oneshot::Receiver<()>,
315 pub batch_opts: Arc<BatchingModeOptions>,
316 pub flow_eval_interval: Option<Duration>,
317 pub eval_schedule: Option<EvalSchedule>,
319}
320
321pub struct PlanInfo {
322 pub plan: LogicalPlan,
323 pub dirty_restore: DirtyRestore,
324 pub coverage: QueryCoverage,
325}
326
327#[derive(Clone)]
328pub enum QueryCoverage {
329 UnfilteredFull,
334 ScopedBaseRepair,
337 FencedRepairChunk { high: BTreeMap<u64, u64> },
341 IncrementalDelta,
343 FencedIncrementalDelta { high: BTreeMap<u64, u64> },
350}
351
352impl QueryCoverage {
353 fn is_incremental_delta(&self) -> bool {
356 matches!(
357 self,
358 Self::IncrementalDelta | Self::FencedIncrementalDelta { .. }
359 )
360 }
361
362 fn snapshot_seqs(&self) -> HashMap<u64, u64> {
366 match self {
367 Self::FencedRepairChunk { high } | Self::FencedIncrementalDelta { high } => {
368 high.iter().map(|(k, v)| (*k, *v)).collect()
369 }
370 _ => HashMap::new(),
371 }
372 }
373}
374
375pub enum DirtyRestore {
376 Scoped(FilterExprInfo),
379 Unscoped(DirtyTimeWindows),
386}
387
388pub struct ExecuteOnceOutcome {
389 pub new_query: Option<PlanInfo>,
390 pub result: Result<Option<(usize, Duration)>, Error>,
396}
397
398impl BatchingTask {
399 #[allow(clippy::too_many_arguments)]
400 pub fn try_new(args: TaskArgs<'_>) -> Result<Self, Error> {
401 Self::try_new_with_exact_sequence_range_required(args, false)
402 }
403
404 pub fn try_new_with_exact_sequence_range_required(
405 TaskArgs {
406 flow_id,
407 query,
408 plan,
409 time_window_expr,
410 expire_after,
411 sink_table_name,
412 source_table_names,
413 query_ctx,
414 catalog_manager,
415 shutdown_rx,
416 batch_opts,
417 flow_eval_interval,
418 eval_schedule,
419 }: TaskArgs<'_>,
420 exact_sequence_range_required: bool,
421 ) -> Result<Self, Error> {
422 let mut state = TaskState::with_dirty_time_windows(
423 query_ctx.clone(),
424 shutdown_rx,
425 DirtyTimeWindows::new(
426 batch_opts.experimental_max_filter_num_per_query,
427 batch_opts.experimental_time_window_merge_threshold,
428 ),
429 );
430 if !batch_opts.experimental_enable_incremental_read {
431 state.disable_incremental();
432 }
433
434 Ok(Self {
435 config: Arc::new(TaskConfig {
436 flow_id,
437 query: query.to_string(),
438 time_window_expr,
439 expire_after,
440 sink_table_name,
441 source_table_names: source_table_names.into_iter().collect(),
442 catalog_manager,
443 output_schema: plan.schema().clone(),
444 query_type: determine_query_type(query, &query_ctx)?,
445 exact_sequence_range_required,
446 batch_opts,
447 flow_eval_interval,
448 eval_schedule,
449 }),
450 state: Arc::new(RwLock::new(state)),
451 execution_lock: Arc::new(Mutex::new(())),
452 execution: None,
453 })
454 }
455
456 pub(crate) fn with_execution(
457 mut self,
458 execution: Option<Arc<dyn crate::BatchingExecution>>,
459 ) -> Self {
460 self.execution = execution;
461 self
462 }
463
464 pub(crate) fn stop_execution(&self) {
465 if let Some(execution) = &self.execution {
466 execution.stop();
467 }
468 }
469
470 pub fn last_execution_time_millis(&self) -> Option<i64> {
471 self.state.read().unwrap().last_execution_time_millis()
472 }
473
474 pub fn start_time_millis(&self) -> Option<i64> {
475 self.state.read().unwrap().start_time_millis()
476 }
477
478 fn frontend_extensions(&self) -> HashMap<String, String> {
481 let ctx = self.state.read().unwrap();
482 let all = ctx.query_ctx.extensions();
483 let mut flow_exts = HashMap::new();
484 if let Some(v) = all.get(query::options::FLOW_SCHEDULED_TIME_MILLIS) {
487 flow_exts.insert(
488 query::options::FLOW_SCHEDULED_TIME_MILLIS.to_string(),
489 v.clone(),
490 );
491 }
492 flow_exts
493 }
494
495 pub fn mark_all_windows_as_dirty(&self) -> Result<(), Error> {
499 let now = SystemTime::now();
500 let now = Timestamp::new_second(
501 now.duration_since(UNIX_EPOCH)
502 .expect("Time went backwards")
503 .as_secs() as _,
504 );
505 let lower_bound = self
506 .config
507 .expire_after
508 .map(|e| now.sub_duration(Duration::from_secs(e as _)))
509 .transpose()
510 .map_err(BoxedError::new)
511 .context(ExternalSnafu)?
512 .unwrap_or(Timestamp::new_second(0));
513 debug!(
514 "Flow {} mark range ({:?}, {:?}) as dirty",
515 self.config.flow_id, lower_bound, now
516 );
517 self.state
518 .write()
519 .unwrap()
520 .dirty_time_windows
521 .add_window(lower_bound, Some(now));
522 Ok(())
523 }
524
525 pub async fn check_or_create_sink_table(
527 &self,
528 engine: &QueryEngineRef,
529 frontend_client: &Arc<FrontendClient>,
530 ) -> Result<TableRef, Error> {
531 if !self.is_table_exist(&self.config.sink_table_name).await? {
532 let create_table = self.gen_create_table_expr(engine.clone()).await?;
533 info!(
534 "Try creating sink table(if not exists) with expr: {:?}",
535 create_table
536 );
537 self.create_table(frontend_client, create_table).await?;
538 info!(
539 "Sink table {}(if not exists) created",
540 self.config.sink_table_name.join(".")
541 );
542 }
543 let (table, _) = get_table_info_df_schema(
544 self.config.catalog_manager.clone(),
545 self.config.sink_table_name.clone(),
546 )
547 .await?;
548 Ok(table)
549 }
550
551 pub fn query_context_snapshot(&self) -> QueryContextRef {
553 let query_ctx = self.state.read().unwrap().query_ctx.clone();
554 Arc::new(query_ctx.fork())
555 }
556
557 pub fn recovery_retention_lower_bound(&self) -> Result<Option<Timestamp>, Error> {
559 let Some(expire_after) = self.config.expire_after else {
560 return Ok(None);
561 };
562 let expire_after = u64::try_from(expire_after).map_err(|_| {
563 UnexpectedSnafu {
564 reason: format!(
565 "Flow {} has negative expire_after {expire_after}",
566 self.config.flow_id
567 ),
568 }
569 .build()
570 })?;
571 let now = Timestamp::new_second(
572 SystemTime::now()
573 .duration_since(UNIX_EPOCH)
574 .map_err(|err| {
575 UnexpectedSnafu {
576 reason: format!("Failed to read recovery wall clock: {err}"),
577 }
578 .build()
579 })?
580 .as_secs() as i64,
581 );
582 let lower = now
583 .sub_duration(Duration::from_secs(expire_after))
584 .map_err(BoxedError::new)
585 .context(ExternalSnafu)?;
586 self.config
587 .time_window_expr
588 .as_ref()
589 .context(UnexpectedSnafu {
590 reason: "Recovery expiry requires a time-window expression".to_string(),
591 })?
592 .eval(lower)?
593 .0
594 .context(UnexpectedSnafu {
595 reason: "Recovery expiry time-window expression returned no lower bound"
596 .to_string(),
597 })
598 .map(Some)
599 }
600
601 pub async fn validate_recovery_retention(
603 &self,
604 retention_lower: Option<Timestamp>,
605 windows: &[(Timestamp, Timestamp)],
606 ) -> Result<(), Error> {
607 for name in &self.config.source_table_names {
608 let table = self
609 .config
610 .catalog_manager
611 .table(&name[0], &name[1], &name[2], None)
612 .await
613 .map_err(BoxedError::new)
614 .context(ExternalSnafu)?
615 .context(UnexpectedSnafu {
616 reason: format!(
617 "Flow {} source table {} is unavailable for recovery retention validation",
618 self.config.flow_id,
619 name.join(".")
620 ),
621 })?;
622 let ttl = if let Some(ttl) = table.table_info().meta.options.ttl {
623 ttl
624 } else {
625 let manager = self
626 .config
627 .catalog_manager
628 .as_any()
629 .downcast_ref::<KvBackendCatalogManager>()
630 .context(UnexpectedSnafu {
631 reason: format!(
632 "Flow {} cannot resolve inherited TTL for source table {} during recovery",
633 self.config.flow_id,
634 name.join(".")
635 ),
636 })?;
637 manager
638 .table_metadata_manager_ref()
639 .schema_manager()
640 .get(SchemaNameKey::new(&name[0], &name[1]))
641 .await
642 .map_err(BoxedError::new)
643 .context(ExternalSnafu)?
644 .context(UnexpectedSnafu {
645 reason: format!(
646 "Flow {} schema {}.{} is unavailable for recovery retention validation",
647 self.config.flow_id, name[0], name[1]
648 ),
649 })?
650 .ttl
651 .map(Into::into)
652 .unwrap_or(TimeToLive::Forever)
653 };
654
655 match ttl {
656 TimeToLive::Forever => {}
657 TimeToLive::Instant => {
658 return UnexpectedSnafu {
659 reason: format!(
660 "Flow {} source table {} has instant TTL and cannot be recovered",
661 self.config.flow_id,
662 name.join(".")
663 ),
664 }
665 .fail();
666 }
667 TimeToLive::Duration(ttl) => {
668 let expire_after = self.config.expire_after.context(UnexpectedSnafu {
669 reason: format!(
670 "Flow {} source table {} has TTL {ttl:?}, but recovery has no expire_after",
671 self.config.flow_id,
672 name.join(".")
673 ),
674 })?;
675 let expire_after = u64::try_from(expire_after).map_err(|_| {
676 UnexpectedSnafu {
677 reason: format!(
678 "Flow {} has negative expire_after {expire_after} during recovery retention validation",
679 self.config.flow_id
680 ),
681 }
682 .build()
683 })?;
684 if ttl <= Duration::from_secs(expire_after) {
685 return UnexpectedSnafu {
686 reason: format!(
687 "Flow {} source table {} TTL {ttl:?} must exceed expire_after {expire_after}s for recovery",
688 self.config.flow_id,
689 name.join(".")
690 ),
691 }
692 .fail();
693 }
694 let mut oldest = retention_lower.context(UnexpectedSnafu {
695 reason: format!(
696 "Flow {} source table {} has finite TTL {ttl:?}, but recovery has no retained lower bound",
697 self.config.flow_id,
698 name.join(".")
699 ),
700 })?;
701 for (start, _) in windows {
702 oldest = oldest.min(*start);
703 }
704 let cutoff = Timestamp::current_millis()
705 .sub_duration(ttl)
706 .map_err(BoxedError::new)
707 .context(ExternalSnafu)?;
708 if oldest <= cutoff {
709 return UnexpectedSnafu {
710 reason: format!(
711 "Flow {} recovery requires source table {} data from {oldest:?}, older than TTL {ttl:?} cutoff {cutoff:?}",
712 self.config.flow_id,
713 name.join(".")
714 ),
715 }
716 .fail();
717 }
718 }
719 }
720 }
721 Ok(())
722 }
723
724 pub async fn capture_recovery_windows(
728 &self,
729 engine: &QueryEngineRef,
730 frontend_client: &FrontendClient,
731 lower: &BTreeMap<u64, u64>,
732 ) -> Result<(BTreeMap<u64, u64>, Vec<(Timestamp, Timestamp)>), Error> {
733 let retention_lower = self.recovery_retention_lower_bound()?;
734 self.capture_recovery_windows_since(engine, frontend_client, lower, retention_lower)
735 .await
736 }
737
738 pub async fn capture_recovery_windows_since(
744 &self,
745 engine: &QueryEngineRef,
746 frontend_client: &FrontendClient,
747 lower: &BTreeMap<u64, u64>,
748 retention_lower: Option<Timestamp>,
749 ) -> Result<(BTreeMap<u64, u64>, Vec<(Timestamp, Timestamp)>), Error> {
750 if lower.is_empty() {
751 return UnexpectedSnafu {
752 reason: format!(
753 "Flow {} recovery window capture requires nonempty lower sequence bounds",
754 self.config.flow_id
755 ),
756 }
757 .fail();
758 }
759 if !self.sequence_range_capable().await? {
760 return UnexpectedSnafu {
761 reason: format!(
762 "Flow {} recovery window capture requires sequence_range-capable sources",
763 self.config.flow_id
764 ),
765 }
766 .fail();
767 }
768
769 let query_ctx = self.query_context_snapshot();
770 let plan = sql_to_df_plan(query_ctx, engine.clone(), &self.config.query, false).await?;
771 let input = recovery_aggregate_input(&plan)?;
772 let Some(analysis) = analyze_incremental_aggregate_plan(&plan)? else {
773 return UnexpectedSnafu {
774 reason: format!(
775 "Flow {} recovery window capture requires a supported aggregate input",
776 self.config.flow_id
777 ),
778 }
779 .fail();
780 };
781 if !analysis.unsupported_exprs.is_empty() {
782 return UnexpectedSnafu {
783 reason: format!(
784 "Flow {} recovery window capture has unsupported aggregate expressions: {:?}",
785 self.config.flow_id, analysis.unsupported_exprs
786 ),
787 }
788 .fail();
789 }
790 let time_window_expr = self
791 .config
792 .time_window_expr
793 .as_ref()
794 .context(UnexpectedSnafu {
795 reason: format!(
796 "Flow {} recovery window capture requires a time-window expression",
797 self.config.flow_id
798 ),
799 })?;
800 let input = if let Some(retention_lower) = retention_lower {
801 let mut add_filter = AddFilterRewriter::new(
802 col(&time_window_expr.column_name).gt_eq(lit(to_df_literal(retention_lower)?)),
803 );
804 input
805 .rewrite(&mut add_filter)
806 .with_context(|_| DatafusionSnafu {
807 context: "Failed to apply recovery expire_after filter".to_string(),
808 })?
809 .data
810 } else {
811 input
812 };
813 let timestamp_plan = LogicalPlan::Projection(
814 Projection::try_new(vec![col(&time_window_expr.column_name)], Arc::new(input))
815 .context(DatafusionSnafu {
816 context: "Failed to project recovery source timestamps".to_string(),
817 })?,
818 );
819 let catalog = &self.config.sink_table_name[0];
820 let schema = &self.config.sink_table_name[1];
821 let timestamp_plan = timestamp_plan
822 .clone()
823 .transform_down_with_subqueries(|p| {
824 if let LogicalPlan::TableScan(mut table_scan) = p {
825 let resolved = table_scan.table_name.resolve(catalog, schema);
826 table_scan.table_name = resolved.into();
827 Ok(Transformed::yes(LogicalPlan::TableScan(table_scan)))
828 } else {
829 Ok(Transformed::no(p))
830 }
831 })
832 .with_context(|_| DatafusionSnafu {
833 context: format!(
834 "Failed to fix table ref in recovery timestamp plan, plan={:?}",
835 timestamp_plan
836 ),
837 })?
838 .data;
839 let message = DFLogicalSubstraitConvertor {}
840 .encode(×tamp_plan, DefaultSerializer)
841 .context(SubstraitEncodeLogicalPlanSnafu)?;
842 let request = api::v1::QueryRequest {
843 query: Some(api::v1::query_request::Query::LogicalPlan(message.to_vec())),
844 };
845 let lower_json = serde_json::to_string(lower).map_err(|err| {
846 UnexpectedSnafu {
847 reason: format!("Failed to serialize recovery lower sequence bounds: {err}"),
848 }
849 .build()
850 })?;
851 let extensions = [
852 (FLOW_RETURN_REGION_SEQ, "true"),
853 (FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE),
854 (FLOW_INCREMENTAL_AFTER_SEQS, lower_json.as_str()),
855 ];
856 let mut peer_desc = None;
857 let result = frontend_client
858 .query_with_terminal_metrics(
859 catalog,
860 schema,
861 request,
862 &extensions,
863 &HashMap::new(),
864 &mut peer_desc,
865 )
866 .await?;
867 let mut aligned_windows = BTreeSet::new();
868 let metrics = result.metrics.clone();
869 match result.output.data {
870 OutputData::AffectedRows(_) => {
871 return UnexpectedSnafu {
872 reason: "Recovery timestamp projection unexpectedly returned affected rows"
873 .to_string(),
874 }
875 .fail();
876 }
877 OutputData::RecordBatches(batches) => {
878 for batch in batches.iter() {
879 capture_recovery_batch_windows(batch, time_window_expr, &mut aligned_windows)?;
880 }
881 }
882 OutputData::Stream(mut stream) => {
883 while let Some(batch) = stream
884 .try_next()
885 .await
886 .map_err(BoxedError::new)
887 .context(ExternalSnafu)?
888 {
889 capture_recovery_batch_windows(&batch, time_window_expr, &mut aligned_windows)?;
890 }
891 }
892 }
893 if !metrics.is_ready() {
894 return UnexpectedSnafu {
895 reason: "Recovery timestamp projection ended without terminal metrics".to_string(),
896 }
897 .fail();
898 }
899 let participating = metrics.participating_regions().context(UnexpectedSnafu {
900 reason: "Recovery timestamp projection has no participating-region proof".to_string(),
901 })?;
902 let high = metrics.region_watermark_map().context(UnexpectedSnafu {
903 reason: "Recovery timestamp projection has no terminal watermark proof".to_string(),
904 })?;
905 if participating.len() != lower.len()
906 || high.len() != lower.len()
907 || participating
908 .iter()
909 .any(|region| !lower.contains_key(region))
910 || lower
911 .iter()
912 .any(|(region, low)| high.get(region).is_none_or(|watermark| watermark < low))
913 || high.keys().any(|region| !participating.contains(region))
914 {
915 return UnexpectedSnafu {
916 reason: format!(
917 "Recovery timestamp projection returned incomplete or regressing terminal proof: lower={lower:?}, participating={participating:?}, high={high:?}"
918 ),
919 }
920 .fail();
921 }
922 Ok((
923 high.into_iter().collect(),
924 aligned_windows.into_iter().collect(),
925 ))
926 }
927
928 pub async fn validate_sink_table_schema(&self, engine: &QueryEngineRef) -> Result<(), Error> {
930 self.validate_sink_table_schema_with_values(engine, &BTreeMap::new())
931 .await
932 }
933
934 pub async fn validate_sink_table_schema_with_values(
936 &self,
937 engine: &QueryEngineRef,
938 values: &BTreeMap<String, ScalarValue>,
939 ) -> Result<(), Error> {
940 let (table, _) = get_table_info_df_schema(
941 self.config.catalog_manager.clone(),
942 self.config.sink_table_name.clone(),
943 )
944 .await?;
945
946 let table_meta = &table.table_info().meta;
947 let merge_mode_last_non_null =
948 is_merge_mode_last_non_null(&table_meta.options.extra_options);
949 let primary_key_indices = table_meta.primary_key_indices.clone();
950
951 gen_plan_with_matching_schema_and_values(
952 &self.config.query,
953 self.query_context_snapshot(),
954 engine.clone(),
955 table_meta.schema.clone(),
956 &primary_key_indices,
957 merge_mode_last_non_null,
958 values,
959 )
960 .await
961 .map(|_| ())
962 }
963
964 async fn is_table_exist(&self, table_name: &[String; 3]) -> Result<bool, Error> {
965 self.config
966 .catalog_manager
967 .table_exists(&table_name[0], &table_name[1], &table_name[2], None)
968 .await
969 .map_err(BoxedError::new)
970 .context(ExternalSnafu)
971 }
972
973 pub(crate) async fn execute_once_serialized(
974 &self,
975 engine: &QueryEngineRef,
976 frontend_client: &Arc<FrontendClient>,
977 max_window_cnt: Option<usize>,
978 ) -> Result<Option<(usize, Duration)>, Error> {
979 let outcome = self
980 .execute_once_serialized_with_outcome(engine, frontend_client, max_window_cnt)
981 .await;
982 outcome.result
983 }
984
985 async fn execute_once_serialized_with_outcome(
988 &self,
989 engine: &QueryEngineRef,
990 frontend_client: &Arc<FrontendClient>,
991 max_window_cnt: Option<usize>,
992 ) -> ExecuteOnceOutcome {
993 let guard = BatchingExecutionGuard::new(self.execution_lock.clone().lock_owned().await);
994 self.execute_once_with_guard(guard, engine, frontend_client, max_window_cnt)
995 .await
996 }
997
998 async fn execute_once_with_guard(
999 &self,
1000 guard: BatchingExecutionGuard,
1001 engine: &QueryEngineRef,
1002 frontend_client: &Arc<FrontendClient>,
1003 max_window_cnt: Option<usize>,
1004 ) -> ExecuteOnceOutcome {
1005 if let Some(execution) = &self.execution {
1006 return execution
1007 .clone()
1008 .execute_once(guard, self, engine, frontend_client, max_window_cnt)
1009 .await;
1010 }
1011 self.execute_once_default_unlocked(engine, frontend_client, max_window_cnt)
1012 .await
1013 }
1014
1015 async fn execute_once_default_unlocked(
1017 &self,
1018 engine: &QueryEngineRef,
1019 frontend_client: &Arc<FrontendClient>,
1020 max_window_cnt: Option<usize>,
1021 ) -> ExecuteOnceOutcome {
1022 let new_query = match self.gen_insert_plan_unlocked(engine, max_window_cnt).await {
1023 Ok(new_query) => new_query,
1024 Err(err) => {
1025 return ExecuteOnceOutcome {
1026 new_query: None,
1027 result: Err(err),
1028 };
1029 }
1030 };
1031
1032 if let Some(new_query) = new_query {
1033 debug!("Generate new query: {}", new_query.plan);
1034 let res = self
1035 .execute_logical_plan_unlocked(
1036 engine,
1037 frontend_client,
1038 &new_query.plan,
1039 &new_query.dirty_restore,
1040 &new_query.coverage,
1041 )
1042 .await;
1043 if res.is_err() {
1044 self.handle_executed_query_failure(Some(&new_query));
1045 }
1046 ExecuteOnceOutcome {
1047 new_query: Some(new_query),
1048 result: res,
1049 }
1050 } else {
1051 debug!("Generate no query");
1052 ExecuteOnceOutcome {
1053 new_query: None,
1054 result: Ok(None),
1055 }
1056 }
1057 }
1058
1059 async fn gen_insert_plan_unlocked(
1061 &self,
1062 engine: &QueryEngineRef,
1063 max_window_cnt: Option<usize>,
1064 ) -> Result<Option<PlanInfo>, Error> {
1065 self.gen_insert_plan_with_values_unlocked(engine, max_window_cnt, &BTreeMap::new(), false)
1066 .await
1067 }
1068
1069 pub async fn gen_insert_plan_with_values_unlocked(
1072 &self,
1073 engine: &QueryEngineRef,
1074 max_window_cnt: Option<usize>,
1075 values: &BTreeMap<String, ScalarValue>,
1076 force_full_snapshot: bool,
1077 ) -> Result<Option<PlanInfo>, Error> {
1078 let (table, df_schema) = get_table_info_df_schema(
1079 self.config.catalog_manager.clone(),
1080 self.config.sink_table_name.clone(),
1081 )
1082 .await?;
1083
1084 let table_meta = &table.table_info().meta;
1085 let merge_mode_last_non_null =
1086 is_merge_mode_last_non_null(&table_meta.options.extra_options);
1087 let primary_key_indices = table_meta.primary_key_indices.clone();
1088
1089 let new_query = self
1090 .gen_query_with_time_window_with_values(
1091 engine.clone(),
1092 &table.table_info().meta.schema,
1093 &primary_key_indices,
1094 merge_mode_last_non_null,
1095 max_window_cnt,
1096 values,
1097 force_full_snapshot,
1098 )
1099 .await?;
1100
1101 let Some(new_query) = new_query else {
1102 return Ok(None);
1103 };
1104
1105 let table_columns = df_schema
1108 .columns()
1109 .into_iter()
1110 .map(|c| c.name)
1111 .collect::<BTreeSet<_>>();
1112 for column in new_query.plan.schema().columns() {
1113 if !table_columns.contains(column.name()) {
1114 self.restore_dirty_windows_after_failure(&new_query);
1115 return InvalidQuerySnafu {
1116 reason: format!(
1117 "Column {} not found in sink table with columns {:?}",
1118 column, table_columns
1119 ),
1120 }
1121 .fail();
1122 }
1123 }
1124
1125 let table_provider = Arc::new(DfTableProviderAdapter::new(table));
1126 let table_source = Arc::new(DefaultTableSource::new(table_provider));
1127
1128 let plan = LogicalPlan::Dml(DmlStatement::new(
1130 datafusion_common::TableReference::Full {
1131 catalog: self.config.sink_table_name[0].clone().into(),
1132 schema: self.config.sink_table_name[1].clone().into(),
1133 table: self.config.sink_table_name[2].clone().into(),
1134 },
1135 table_source,
1136 WriteOp::Insert(datafusion_expr::dml::InsertOp::Append),
1137 Arc::new(new_query.plan.clone()),
1138 ));
1139 let insert_into_info = PlanInfo {
1140 plan,
1141 dirty_restore: new_query.dirty_restore,
1142 coverage: new_query.coverage,
1143 };
1144 let insert_into =
1145 match insert_into_info
1146 .plan
1147 .clone()
1148 .recompute_schema()
1149 .context(DatafusionSnafu {
1150 context: "Failed to recompute schema",
1151 }) {
1152 Ok(insert_into) => insert_into,
1153 Err(err) => {
1154 self.restore_dirty_windows_after_failure(&insert_into_info);
1155 return Err(err);
1156 }
1157 };
1158
1159 Ok(Some(PlanInfo {
1160 plan: insert_into,
1161 dirty_restore: insert_into_info.dirty_restore,
1162 coverage: insert_into_info.coverage,
1163 }))
1164 }
1165
1166 pub async fn create_table(
1167 &self,
1168 frontend_client: &Arc<FrontendClient>,
1169 expr: CreateTableExpr,
1170 ) -> Result<(), Error> {
1171 let catalog = &self.config.sink_table_name[0];
1172 let schema = &self.config.sink_table_name[1];
1173 frontend_client
1174 .create(expr.clone(), catalog, schema)
1175 .await?;
1176 Ok(())
1177 }
1178
1179 async fn execute_logical_plan_unlocked(
1182 &self,
1183 engine: &QueryEngineRef,
1184 frontend_client: &Arc<FrontendClient>,
1185 plan: &LogicalPlan,
1186 dirty_restore: &DirtyRestore,
1187 coverage: &QueryCoverage,
1188 ) -> Result<Option<(usize, Duration)>, Error> {
1189 let flow_id = self.config.flow_id;
1190 if matches!(coverage, QueryCoverage::FencedIncrementalDelta { .. }) {
1191 return InvalidQuerySnafu {
1192 reason: format!(
1193 "Flow {flow_id} fenced incremental delta is raw-only: its caller owns checkpoint transitions"
1194 ),
1195 }
1196 .fail();
1197 }
1198 let Some((res, elapsed)) = self
1199 .execute_plan_unlocked(engine, frontend_client, plan, dirty_restore, coverage)
1200 .await?
1201 else {
1202 return Ok(None);
1203 };
1204
1205 if let Err(err) = &res {
1206 let decision = {
1207 let mut state = self.state.write().unwrap();
1208 let reason = Self::query_failure_reason(err, coverage);
1209 Self::apply_query_failure_to_state(&mut state, elapsed, coverage, reason)
1210 };
1211 if let Some(decision) = decision {
1212 Self::record_checkpoint_decision(flow_id, decision);
1213 }
1214 }
1215
1216 let res = res?;
1217 let (affected_rows, _) = res.output.extract_rows_and_cost();
1218 let decision = {
1219 let mut state = self.state.write().unwrap();
1220 Self::apply_query_result_to_state(&mut state, &res, elapsed, coverage)
1221 };
1222 Self::record_checkpoint_decision(flow_id, decision);
1223 Ok(Some((affected_rows, elapsed)))
1224 }
1225
1226 pub async fn execute_plan_unlocked(
1234 &self,
1235 engine: &QueryEngineRef,
1236 frontend_client: &Arc<FrontendClient>,
1237 plan: &LogicalPlan,
1238 dirty_restore: &DirtyRestore,
1239 coverage: &QueryCoverage,
1240 ) -> Result<Option<(Result<OutputWithMetrics, Error>, Duration)>, Error> {
1241 let instant = Instant::now();
1242 let flow_id = self.config.flow_id;
1243
1244 if let QueryCoverage::FencedIncrementalDelta { high } = coverage {
1247 let state = self.state.read().unwrap();
1248 if state.checkpoint_mode() != CheckpointMode::Incremental
1249 || state.is_incremental_disabled()
1250 {
1251 return InvalidQuerySnafu {
1252 reason: format!(
1253 "Flow {flow_id} fenced incremental delta requires an enabled incremental flow in incremental mode"
1254 ),
1255 }
1256 .fail();
1257 }
1258 let checkpoints = state.checkpoints();
1259 if checkpoints.is_empty()
1260 || !high.keys().eq(checkpoints.keys())
1261 || high
1262 .values()
1263 .zip(checkpoints.values())
1264 .any(|(upper, lower)| upper < lower)
1265 {
1266 return InvalidQuerySnafu {
1267 reason: format!(
1268 "Flow {flow_id} fenced incremental delta bounds {high:?} must extend the checkpoint bounds {checkpoints:?} over the same regions"
1269 ),
1270 }
1271 .fail();
1272 }
1273 }
1274
1275 debug!(
1276 "Executing flow {flow_id}(expire_after={:?} secs) with query {}",
1277 self.config.expire_after, &plan
1278 );
1279
1280 let catalog = &self.config.sink_table_name[0];
1281 let schema = &self.config.sink_table_name[1];
1282
1283 let plan = plan
1285 .clone()
1286 .transform_down_with_subqueries(|p| {
1287 if let LogicalPlan::TableScan(mut table_scan) = p {
1288 let resolved = table_scan.table_name.resolve(catalog, schema);
1289 table_scan.table_name = resolved.into();
1290 Ok(Transformed::yes(LogicalPlan::TableScan(table_scan)))
1291 } else {
1292 Ok(Transformed::no(p))
1293 }
1294 })
1295 .with_context(|_| DatafusionSnafu {
1296 context: format!("Failed to fix table ref in logical plan, plan={:?}", plan),
1297 })?
1298 .data;
1299
1300 let incremental_plan = if coverage.is_incremental_delta() {
1303 self.prepare_plan_for_incremental(engine, &plan).await?
1304 } else {
1305 None
1306 };
1307 let incremental_safe = incremental_plan.is_some();
1308 if coverage.is_incremental_delta() && !incremental_safe {
1309 debug!(
1310 "Flow {flow_id} skipped unsafe incremental delta fallback; \
1311 restored dirty signal instead of executing an unfiltered full snapshot"
1312 );
1313 self.restore_dirty_windows(dirty_restore);
1314 return Ok(None);
1315 }
1316 let plan = incremental_plan.unwrap_or_else(|| plan.clone());
1317 let plan = match &self.execution {
1318 Some(execution) => execution.rewrite_plan(self, plan)?,
1319 None => plan,
1320 };
1321
1322 let extensions = self
1323 .build_flow_query_extensions(incremental_safe, coverage.is_incremental_delta())
1324 .await?;
1325 if matches!(coverage, QueryCoverage::FencedIncrementalDelta { .. })
1328 && !extensions.iter().any(|(key, value)| {
1329 *key == FLOW_INCREMENTAL_MODE && *value == FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE
1330 })
1331 {
1332 return InvalidQuerySnafu {
1333 reason: format!(
1334 "Flow {flow_id} fenced incremental delta requires {FLOW_INCREMENTAL_MODE}={FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE}"
1335 ),
1336 }
1337 .fail();
1338 }
1339 let frontend_extensions = self.frontend_extensions();
1340 let extension_refs = extensions
1341 .iter()
1342 .map(|(key, value)| (*key, value.as_str()))
1343 .chain(
1344 frontend_extensions
1345 .iter()
1346 .map(|(key, value)| (key.as_str(), value.as_str())),
1347 )
1348 .collect::<Vec<_>>();
1349 let query_mode = if extensions
1350 .iter()
1351 .any(|(key, _)| *key == FLOW_INCREMENTAL_MODE)
1352 {
1353 CheckpointMode::Incremental
1354 } else {
1355 CheckpointMode::FullSnapshot
1356 };
1357 Self::record_query_mode(flow_id, query_mode);
1358 debug!(
1359 "Flow {flow_id} executing batching query with checkpoint_mode={}, extension_count={}",
1360 checkpoint_mode_label(query_mode),
1361 extensions.len()
1362 );
1363
1364 let mut peer_desc = None;
1365 let res = {
1366 let _timer = METRIC_FLOW_BATCHING_ENGINE_QUERY_TIME
1367 .with_label_values(&[flow_id.to_string().as_str()])
1368 .start_timer();
1369
1370 let req = if let Some((insert_to, insert_input_plan)) =
1371 breakup_insert_plan(&plan, catalog, schema)
1372 {
1373 if query_mode == CheckpointMode::FullSnapshot
1374 && matches!(self.config.query_type, QueryType::Sql)
1375 && self.config.flow_eval_interval.is_some()
1376 && self.config.time_window_expr.is_none()
1377 {
1378 match df_plan_to_sql(&insert_input_plan) {
1388 Ok(select_sql) => {
1389 let target_columns = format_insert_target_columns(&insert_input_plan);
1390 let sql = format!(
1391 "INSERT INTO {} ({}) {}",
1392 TableReference::full(
1393 insert_to.catalog_name.as_str(),
1394 insert_to.schema_name.as_str(),
1395 insert_to.table_name.as_str(),
1396 )
1397 .to_quoted_string(),
1398 target_columns,
1399 select_sql
1400 );
1401 api::v1::QueryRequest {
1402 query: Some(api::v1::query_request::Query::Sql(sql)),
1403 }
1404 }
1405 Err(err) => {
1406 debug!(
1407 "Failed to unparse full-snapshot SQL flow {} plan; \
1408 falling back to InsertIntoPlan: {:?}",
1409 flow_id, err
1410 );
1411 encode_insert_plan_request(insert_to, &insert_input_plan)?
1412 }
1413 }
1414 } else {
1415 encode_insert_plan_request(insert_to, &insert_input_plan)?
1416 }
1417 } else {
1418 let message = DFLogicalSubstraitConvertor {}
1419 .encode(&plan, DefaultSerializer)
1420 .context(SubstraitEncodeLogicalPlanSnafu)?;
1421
1422 api::v1::QueryRequest {
1423 query: Some(api::v1::query_request::Query::LogicalPlan(message.to_vec())),
1424 }
1425 };
1426
1427 let snapshot_seqs = coverage.snapshot_seqs();
1428 {
1429 let mut state = self.state.write().unwrap();
1430 state.record_start_time_if_first();
1431 }
1432 frontend_client
1433 .query_with_terminal_metrics(
1434 catalog,
1435 schema,
1436 req,
1437 &extension_refs,
1438 &snapshot_seqs,
1439 &mut peer_desc,
1440 )
1441 .await
1442 };
1443
1444 let elapsed = instant.elapsed();
1445 let peer_label = peer_desc
1446 .as_ref()
1447 .map(ToString::to_string)
1448 .unwrap_or_else(|| PeerDesc::default().to_string());
1449 if let Err(err) = &res {
1450 warn!(
1454 "Failed to execute Flow {flow_id} on frontend {peer_label}, result: {err:?}, elapsed: {:?} with query: {}",
1455 elapsed, &plan
1456 );
1457 }
1458
1459 if elapsed >= self.config.batch_opts.slow_query_threshold {
1461 warn!(
1462 "Flow {flow_id} on frontend {peer_label} executed for {:?} before complete, query: {}",
1463 elapsed, &plan
1464 );
1465 let flow_id = flow_id.to_string();
1466 METRIC_FLOW_BATCHING_ENGINE_SLOW_QUERY
1467 .with_label_values(&[flow_id.as_str(), peer_label.as_str()])
1468 .observe(elapsed.as_secs_f64());
1469 }
1470
1471 match res {
1472 Ok(res) => {
1473 let (affected_rows, _) = res.output.extract_rows_and_cost();
1474 if matches!(&res.output.data, common_query::OutputData::AffectedRows(_)) {
1475 res.metrics.wait_ready().await;
1476 }
1477 if let Some(error) = res.metrics.completion_error() {
1478 warn!("Flow {flow_id} completed with terminal metrics error: {error}");
1479 }
1480 debug!(
1481 "Flow {flow_id} executed, affected_rows: {affected_rows:?}, elapsed: {:?}, watermark: {:?}",
1482 elapsed,
1483 res.region_watermark_map()
1484 );
1485 METRIC_FLOW_ROWS
1486 .with_label_values(&[format!("{}-out-batching", flow_id).as_str()])
1487 .inc_by(affected_rows as _);
1488 Ok(Some((Ok(res), elapsed)))
1489 }
1490 Err(err) => Ok(Some((Err(err), elapsed))),
1491 }
1492 }
1493
1494 pub fn restore_dirty_windows(&self, dirty_restore: &DirtyRestore) {
1498 match dirty_restore {
1499 DirtyRestore::Scoped(filter) => self.restore_scoped_dirty_windows(filter),
1500 DirtyRestore::Unscoped(dirty_windows) => self
1501 .state
1502 .write()
1503 .unwrap()
1504 .dirty_time_windows
1505 .add_dirty_windows(dirty_windows),
1506 }
1507 }
1508
1509 fn restore_dirty_windows_after_failure(&self, query: &PlanInfo) {
1512 self.restore_dirty_windows(&query.dirty_restore);
1513 }
1514
1515 fn restore_scoped_dirty_windows(&self, filter: &FilterExprInfo) {
1518 self.state.write().unwrap().restore_scoped_windows(filter);
1519 }
1520
1521 fn restore_scoped_dirty_windows_on_err<T>(
1524 &self,
1525 filter: &FilterExprInfo,
1526 result: Result<T, Error>,
1527 ) -> Result<T, Error> {
1528 result.inspect_err(|_| {
1529 self.restore_scoped_dirty_windows(filter);
1530 })
1531 }
1532
1533 fn restore_unscoped_dirty_windows(&self, dirty_windows: &DirtyTimeWindows) {
1536 self.state
1537 .write()
1538 .unwrap()
1539 .dirty_time_windows
1540 .add_dirty_windows(dirty_windows);
1541 }
1542
1543 fn restore_unscoped_dirty_windows_on_err<T>(
1546 &self,
1547 dirty_windows: &DirtyTimeWindows,
1548 result: Result<T, Error>,
1549 ) -> Result<T, Error> {
1550 result.inspect_err(|_| {
1551 self.restore_unscoped_dirty_windows(dirty_windows);
1552 })
1553 }
1554
1555 fn drain_dirty_windows_signal(&self) -> (bool, DirtyTimeWindows) {
1558 let mut state = self.state.write().unwrap();
1559 let dirty_windows_to_restore = state.dirty_time_windows.clone();
1560 let is_dirty = !dirty_windows_to_restore.is_empty();
1561 state.dirty_time_windows.clean();
1562 (is_dirty, dirty_windows_to_restore)
1563 }
1564
1565 #[allow(clippy::too_many_arguments)]
1566 async fn gen_unfiltered_plan_info(
1569 &self,
1570 engine: QueryEngineRef,
1571 query_ctx: QueryContextRef,
1572 sink_table_schema: Arc<Schema>,
1573 primary_key_indices: &[usize],
1574 allow_partial: bool,
1575 values: &BTreeMap<String, ScalarValue>,
1576 dirty_windows_to_restore: DirtyTimeWindows,
1577 retention_filter: Option<(&str, Timestamp, &'static str)>,
1578 coverage: QueryCoverage,
1579 ) -> Result<PlanInfo, Error> {
1580 let mut plan = self.restore_unscoped_dirty_windows_on_err(
1581 &dirty_windows_to_restore,
1582 gen_plan_with_matching_schema_and_values(
1583 &self.config.query,
1584 query_ctx,
1585 engine,
1586 sink_table_schema,
1587 primary_key_indices,
1588 allow_partial,
1589 values,
1590 )
1591 .await,
1592 )?;
1593
1594 if let Some((col_name, lower_bound, context)) = retention_filter {
1595 let lower = self.restore_unscoped_dirty_windows_on_err(
1596 &dirty_windows_to_restore,
1597 to_df_literal(lower_bound),
1598 )?;
1599 let retention_filter = col(col_name).gt_eq(lit(lower));
1600 let mut add_filter = AddFilterRewriter::new(retention_filter);
1601 plan = self.restore_unscoped_dirty_windows_on_err(
1602 &dirty_windows_to_restore,
1603 plan.clone()
1604 .rewrite(&mut add_filter)
1605 .with_context(|_| DatafusionSnafu {
1606 context: format!(
1607 "Failed to apply {context} expire_after filter to plan:\n {}\n",
1608 plan
1609 ),
1610 })
1611 .map(|rewrite| rewrite.data),
1612 )?;
1613 }
1614
1615 Ok(PlanInfo {
1616 plan,
1617 dirty_restore: DirtyRestore::Unscoped(dirty_windows_to_restore),
1618 coverage,
1619 })
1620 }
1621
1622 #[allow(clippy::too_many_arguments)]
1623 async fn gen_unfiltered_plan_info_if_dirty(
1626 &self,
1627 engine: QueryEngineRef,
1628 query_ctx: QueryContextRef,
1629 sink_table_schema: Arc<Schema>,
1630 primary_key_indices: &[usize],
1631 allow_partial: bool,
1632 values: &BTreeMap<String, ScalarValue>,
1633 retention_filter: Option<(&str, Timestamp, &'static str)>,
1634 coverage: QueryCoverage,
1635 ) -> Result<Option<PlanInfo>, Error> {
1636 let (is_dirty, dirty_windows_to_restore) = self.drain_dirty_windows_signal();
1637 if !is_dirty {
1638 debug!("Flow id={:?}, no new data, not update", self.config.flow_id);
1639 return Ok(None);
1640 }
1641
1642 self.gen_unfiltered_plan_info(
1643 engine,
1644 query_ctx,
1645 sink_table_schema,
1646 primary_key_indices,
1647 allow_partial,
1648 values,
1649 dirty_windows_to_restore,
1650 retention_filter,
1651 coverage,
1652 )
1653 .await
1654 .map(Some)
1655 }
1656
1657 fn handle_executed_query_failure(&self, query: Option<&PlanInfo>) {
1658 if let Some(query) = query {
1659 self.restore_dirty_windows_after_failure(query);
1660 }
1661 }
1662
1663 pub async fn start_executing_loop(
1671 &self,
1672 engine: QueryEngineRef,
1673 frontend_client: Arc<FrontendClient>,
1674 ) {
1675 if self.config.flow_eval_interval.is_some() {
1676 self.start_scheduled_loop(engine, frontend_client).await;
1677 } else {
1678 self.start_adaptive_loop(engine, frontend_client).await;
1679 }
1680 }
1681
1682 async fn start_scheduled_loop(
1692 &self,
1693 engine: QueryEngineRef,
1694 frontend_client: Arc<FrontendClient>,
1695 ) {
1696 let flow_id_str = self.config.flow_id.to_string();
1697
1698 let schedule = match &self.config.eval_schedule {
1699 Some(s) => s.clone(),
1700 None => {
1701 let eval_interval_secs = self
1702 .config
1703 .flow_eval_interval
1704 .map(|d| d.as_secs() as i64)
1705 .expect("checked by caller");
1706
1707 match EvalSchedule::from_config(Some(eval_interval_secs), None) {
1710 Ok(Some(s)) => s,
1711 Ok(None) => {
1712 warn!(
1713 "Flow {}: EVAL INTERVAL set but no schedule parsed; exiting loop",
1714 flow_id_str
1715 );
1716 return;
1717 }
1718 Err(e) => {
1719 warn!(
1720 "Flow {}: Failed to parse eval schedule: {}; exiting loop",
1721 flow_id_str, e
1722 );
1723 return;
1724 }
1725 }
1726 }
1727 };
1728
1729 let mut cursor_secs =
1734 match initial_schedule_cursor(schedule.start_secs, schedule.interval_secs) {
1735 Ok(cursor) => cursor,
1736 Err(e) => {
1737 warn!(
1738 "Flow {}: invalid eval schedule, exiting loop: {}",
1739 flow_id_str, e
1740 );
1741 return;
1742 }
1743 };
1744
1745 info!(
1746 "Flow {}: entering scheduled loop, interval={}s, start={}, anchor={}, policy={:?}, max_runs={}, max_lag={}s",
1747 flow_id_str,
1748 schedule.interval_secs,
1749 schedule.start_secs,
1750 schedule.anchor_secs,
1751 schedule.missed_tick_policy,
1752 schedule.max_runs,
1753 schedule.max_lag_secs,
1754 );
1755
1756 loop {
1757 if self.is_shutdown_signaled() {
1758 break;
1759 }
1760
1761 let wall_now_secs = wall_clock_unix_secs();
1762
1763 let due = match select_due_scheduled_times(&schedule, cursor_secs, wall_now_secs) {
1764 Ok(d) => d,
1765 Err(e) => {
1766 warn!(
1767 "Flow {}: invalid eval schedule, exiting loop: {}",
1768 flow_id_str, e
1769 );
1770 return;
1771 }
1772 };
1773
1774 if due.scheduled_times_secs.is_empty() {
1775 if due.skipped > 0 {
1776 warn!(
1777 "Flow {}: all {} due scheduled times skipped by max-lag, advancing cursor to wall-clock ({wall_now_secs}) to avoid re-skipping",
1778 flow_id_str, due.skipped
1779 );
1780 cursor_secs = wall_now_secs;
1781 continue;
1782 }
1783
1784 let next = match schedule.next_scheduled_time_after(cursor_secs) {
1786 Ok(next) => next,
1787 Err(e) => {
1788 warn!(
1789 "Flow {}: cannot advance eval schedule past cursor {cursor_secs}: {e}; exiting loop",
1790 flow_id_str
1791 );
1792 return;
1793 }
1794 };
1795 if next <= wall_now_secs {
1796 cursor_secs = wall_now_secs;
1799 continue;
1800 }
1801 let wait_secs = match sleep_delta_secs(next, wall_now_secs) {
1802 Ok(wait_secs) => wait_secs,
1803 Err(e) => {
1804 warn!(
1805 "Flow {}: cannot sleep until next scheduled time {}: {e}; exiting loop",
1806 flow_id_str, next
1807 );
1808 return;
1809 }
1810 };
1811 let wait_dur = Duration::from_secs(wait_secs);
1812 debug!(
1813 "Flow {}: no due scheduled times, sleeping for {}s until next scheduled time at {}",
1814 flow_id_str, wait_secs, next
1815 );
1816 tokio::time::sleep(wait_dur).await;
1817 continue;
1818 }
1819
1820 if due.skipped > 0 {
1821 info!(
1822 "Flow {}: {} due scheduled times, {} skipped (catch-up)",
1823 flow_id_str,
1824 due.scheduled_times_secs.len(),
1825 due.skipped
1826 );
1827 }
1828
1829 for scheduled_time_secs in &due.scheduled_times_secs {
1831 if self.is_shutdown_signaled() {
1832 break;
1833 }
1834
1835 METRIC_FLOW_BATCHING_ENGINE_START_QUERY_CNT
1836 .with_label_values(&[&flow_id_str])
1837 .inc();
1838
1839 let outcome = self
1840 .execute_once_serialized_at_scheduled_time(
1841 &engine,
1842 &frontend_client,
1843 *scheduled_time_secs,
1844 )
1845 .await;
1846
1847 cursor_secs = *scheduled_time_secs;
1849
1850 match outcome.result {
1851 Ok(Some((rows, elapsed))) => {
1852 debug!(
1853 "Flow {}: scheduled time {} completed, rows={}, elapsed={:?}",
1854 flow_id_str, scheduled_time_secs, rows, elapsed
1855 );
1856 }
1857 Ok(None) => {
1858 debug!(
1859 "Flow {}: scheduled time {} produced no query (no dirty signal or no-op)",
1860 flow_id_str, scheduled_time_secs
1861 );
1862 }
1863 Err(err) => {
1864 warn!(
1865 "Flow {}: scheduled time {} failed: {:?}",
1866 flow_id_str, scheduled_time_secs, err
1867 );
1868 METRIC_FLOW_BATCHING_ENGINE_ERROR_CNT
1869 .with_label_values(&[&flow_id_str])
1870 .inc();
1871 }
1875 }
1876 }
1877 }
1878 }
1879
1880 async fn start_adaptive_loop(
1882 &self,
1883 engine: QueryEngineRef,
1884 frontend_client: Arc<FrontendClient>,
1885 ) {
1886 let flow_id_str = self.config.flow_id.to_string();
1887 let mut max_window_cnt = None;
1888 loop {
1889 if self.is_shutdown_signaled() {
1890 break;
1891 }
1892 METRIC_FLOW_BATCHING_ENGINE_START_QUERY_CNT
1893 .with_label_values(&[&flow_id_str])
1894 .inc();
1895
1896 let min_refresh = self.config.batch_opts.experimental_min_refresh_duration;
1897
1898 let outcome = self
1899 .execute_once_serialized_with_outcome(&engine, &frontend_client, max_window_cnt)
1900 .await;
1901
1902 match outcome.result {
1903 Ok(Some(_)) => {
1904 max_window_cnt = max_window_cnt.map(|cnt| {
1905 (cnt + 1).min(self.config.batch_opts.experimental_max_filter_num_per_query)
1906 });
1907
1908 let sleep_until = {
1909 let state = self.state.write().unwrap();
1910
1911 let time_window_size = self
1912 .config
1913 .time_window_expr
1914 .as_ref()
1915 .and_then(|t| *t.time_window_size());
1916
1917 let prefer_short_incremental_cadence = state.checkpoint_mode()
1918 == CheckpointMode::Incremental
1919 && !state.is_incremental_disabled();
1920
1921 state.get_next_start_query_time(
1922 self.config.flow_id,
1923 &time_window_size,
1924 min_refresh,
1925 Some(self.config.batch_opts.query_timeout),
1926 self.config.batch_opts.experimental_max_filter_num_per_query,
1927 prefer_short_incremental_cadence,
1928 )
1929 };
1930
1931 tokio::time::sleep_until(sleep_until).await;
1932 }
1933 Ok(None) => {
1934 debug!(
1935 "Flow id = {:?} found no new data, sleep for {:?} then continue",
1936 self.config.flow_id, min_refresh
1937 );
1938 tokio::time::sleep(min_refresh).await;
1939 continue;
1940 }
1941 Err(err) => {
1942 METRIC_FLOW_BATCHING_ENGINE_ERROR_CNT
1943 .with_label_values(&[&flow_id_str])
1944 .inc();
1945 match outcome.new_query {
1946 Some(query) => {
1947 common_telemetry::error!(err; "Failed to execute query for flow={} with query: {}", self.config.flow_id, query.plan);
1948 max_window_cnt = Some(1);
1949 }
1950 None => {
1951 common_telemetry::error!(err; "Failed to generate query for flow={}", self.config.flow_id)
1952 }
1953 }
1954 tokio::time::sleep(min_refresh).await;
1955 }
1956 }
1957 }
1958 }
1959
1960 fn is_shutdown_signaled(&self) -> bool {
1962 let mut state = self.state.write().unwrap();
1963 match state.shutdown_rx.try_recv() {
1964 Ok(()) | Err(TryRecvError::Closed) => true,
1965 Err(TryRecvError::Empty) => false,
1966 }
1967 }
1968
1969 async fn execute_once_serialized_at_scheduled_time(
1976 &self,
1977 engine: &QueryEngineRef,
1978 frontend_client: &Arc<FrontendClient>,
1979 scheduled_time_secs: i64,
1980 ) -> ExecuteOnceOutcome {
1981 let mut guard = BatchingExecutionGuard::new(self.execution_lock.clone().lock_owned().await);
1982
1983 let scheduled_time_millis = match scheduled_time_millis(scheduled_time_secs) {
1987 Ok(millis) => millis,
1988 Err(e) => {
1989 return ExecuteOnceOutcome {
1990 new_query: None,
1991 result: Err(e),
1992 };
1993 }
1994 };
1995
1996 let old_ctx = {
1999 let mut state = self.state.write().unwrap();
2000 let old = state.query_ctx.clone();
2001 let mut new_ctx = (*old).clone();
2002 new_ctx.set_extension(
2003 query::options::FLOW_SCHEDULED_TIME_MILLIS,
2004 scheduled_time_millis.to_string(),
2005 );
2006 state.query_ctx = Arc::new(new_ctx);
2007 old
2008 };
2009 guard.restore_query_context(self.state.clone(), old_ctx);
2010
2011 self.execute_once_with_guard(guard, engine, frontend_client, None)
2014 .await
2015 }
2016
2017 async fn gen_create_table_expr(
2024 &self,
2025 engine: QueryEngineRef,
2026 ) -> Result<CreateTableExpr, Error> {
2027 let query_ctx = self.state.read().unwrap().query_ctx.clone();
2028 let plan =
2029 sql_to_df_plan(query_ctx.clone(), engine.clone(), &self.config.query, true).await?;
2030 create_table_with_expr(&plan, &self.config.sink_table_name, &self.config.query_type)
2031 }
2032
2033 fn should_use_unfiltered_incremental_delta(&self) -> bool {
2036 let state = self.state.read().unwrap();
2037 state.checkpoint_mode() == CheckpointMode::Incremental
2038 && !state.is_incremental_disabled()
2039 && matches!(self.config.query_type, QueryType::Sql)
2040 }
2041
2042 async fn gen_query_with_time_window(
2044 &self,
2045 engine: QueryEngineRef,
2046 sink_table_schema: &Arc<Schema>,
2047 primary_key_indices: &[usize],
2048 allow_partial: bool,
2049 max_window_cnt: Option<usize>,
2050 ) -> Result<Option<PlanInfo>, Error> {
2051 self.gen_query_with_time_window_with_values(
2052 engine,
2053 sink_table_schema,
2054 primary_key_indices,
2055 allow_partial,
2056 max_window_cnt,
2057 &BTreeMap::new(),
2058 false,
2059 )
2060 .await
2061 }
2062
2063 #[allow(clippy::too_many_arguments)]
2065 async fn gen_query_with_time_window_with_values(
2066 &self,
2067 engine: QueryEngineRef,
2068 sink_table_schema: &Arc<Schema>,
2069 primary_key_indices: &[usize],
2070 allow_partial: bool,
2071 max_window_cnt: Option<usize>,
2072 values: &BTreeMap<String, ScalarValue>,
2073 force_full_snapshot: bool,
2074 ) -> Result<Option<PlanInfo>, Error> {
2075 let query_ctx = self.state.read().unwrap().query_ctx.clone();
2076 let start = SystemTime::now();
2077 let since_the_epoch = start
2078 .duration_since(UNIX_EPOCH)
2079 .expect("Time went backwards");
2080 let low_bound = self
2081 .config
2082 .expire_after
2083 .map(|e| since_the_epoch.as_secs() - e as u64)
2084 .unwrap_or(u64::MIN);
2085
2086 let low_bound = Timestamp::new_second(low_bound as i64);
2087
2088 let expire_time_window_bound = self
2089 .config
2090 .time_window_expr
2091 .as_ref()
2092 .map(|expr| expr.eval(low_bound))
2093 .transpose()?;
2094
2095 let (expire_lower_bound, expire_upper_bound) = match (
2096 expire_time_window_bound,
2097 &self.config.query_type,
2098 ) {
2099 (Some((Some(l), Some(u))), QueryType::Sql) => (l, u),
2100 (None, QueryType::Sql) if self.config.flow_eval_interval.is_none() => {
2101 return UnexpectedSnafu {
2102 reason: format!(
2103 "Flow id={} reached execution without a time-window expression or EVAL INTERVAL; create-flow validation should have rejected it",
2104 self.config.flow_id
2105 ),
2106 }
2107 .fail();
2108 }
2109 _ => {
2110 let (_, dirty_windows_to_restore) = self.drain_dirty_windows_signal();
2116
2117 let plan_info = self
2118 .gen_unfiltered_plan_info(
2119 engine,
2120 query_ctx,
2121 sink_table_schema.clone(),
2122 primary_key_indices,
2123 allow_partial,
2124 values,
2125 dirty_windows_to_restore,
2126 None,
2127 QueryCoverage::UnfilteredFull,
2128 )
2129 .await?;
2130
2131 return Ok(Some(plan_info));
2132 }
2133 };
2134
2135 debug!(
2136 "Flow id = {:?}, found time window: precise_lower_bound={:?}, precise_upper_bound={:?} with dirty time windows: {:?}",
2137 self.config.flow_id,
2138 expire_lower_bound,
2139 expire_upper_bound,
2140 self.state.read().unwrap().dirty_time_windows
2141 );
2142 let window_size = expire_upper_bound
2143 .sub(&expire_lower_bound)
2144 .with_context(|| UnexpectedSnafu {
2145 reason: format!(
2146 "Can't get window size from {expire_upper_bound:?} - {expire_lower_bound:?}"
2147 ),
2148 })?;
2149 let col_name = self
2150 .config
2151 .time_window_expr
2152 .as_ref()
2153 .map(|expr| expr.column_name.clone())
2154 .with_context(|| UnexpectedSnafu {
2155 reason: format!(
2156 "Flow id={:?}, Failed to get column name from time window expr",
2157 self.config.flow_id
2158 ),
2159 })?;
2160
2161 if force_full_snapshot {
2162 let retention_filter = self.config.expire_after.map(|_| {
2166 (
2167 col_name.as_str(),
2168 expire_lower_bound,
2169 "forced full snapshot",
2170 )
2171 });
2172 let (_, dirty_windows_to_restore) = self.drain_dirty_windows_signal();
2173 return self
2174 .gen_unfiltered_plan_info(
2175 engine,
2176 query_ctx,
2177 sink_table_schema.clone(),
2178 primary_key_indices,
2179 allow_partial,
2180 values,
2181 dirty_windows_to_restore,
2182 retention_filter,
2183 QueryCoverage::UnfilteredFull,
2184 )
2185 .await
2186 .map(Some);
2187 }
2188
2189 if self.should_use_unfiltered_incremental_delta() {
2190 let retention_filter = self
2200 .config
2201 .expire_after
2202 .map(|_| (col_name.as_str(), expire_lower_bound, "incremental"));
2203 return self
2204 .gen_unfiltered_plan_info_if_dirty(
2205 engine,
2206 query_ctx,
2207 sink_table_schema.clone(),
2208 primary_key_indices,
2209 allow_partial,
2210 values,
2211 retention_filter,
2212 QueryCoverage::IncrementalDelta,
2213 )
2214 .await;
2215 }
2216
2217 let (expr, coverage) = {
2218 let mut state = self.state.write().unwrap();
2219 let window_cnt = max_window_cnt
2220 .unwrap_or(self.config.batch_opts.experimental_max_filter_num_per_query);
2221 let expr = state.gen_scoped_filter_exprs(
2222 &col_name,
2223 Some(expire_lower_bound),
2224 window_size,
2225 window_cnt,
2226 self.config.flow_id,
2227 Some(self),
2228 )?;
2229 let repair_high = state
2230 .pending_fenced_repair()
2231 .map(|repair| repair.high().clone());
2232 let coverage = if let Some(high) = repair_high {
2233 QueryCoverage::FencedRepairChunk { high }
2234 } else {
2235 QueryCoverage::ScopedBaseRepair
2236 };
2237 (expr, coverage)
2238 };
2239
2240 let Some(expr) = expr else {
2241 debug!("Flow id={:?}, no new data, not update", self.config.flow_id);
2243 return Ok(None);
2244 };
2245
2246 let filter_sql = expr_to_sql(&expr.expr)
2247 .map(|sql| sql.to_string())
2248 .unwrap_or_else(|err| format!("<failed to format filter expr: {err}>"));
2249
2250 debug!(
2251 "Flow id={:?}, Generated filter expr: {:?}",
2252 self.config.flow_id, filter_sql
2253 );
2254
2255 let mut add_filter = AddFilterRewriter::new(expr.expr.clone());
2256 let mut add_auto_column = ColumnMatcherRewriter::new_with_values(
2257 sink_table_schema.clone(),
2258 primary_key_indices.to_vec(),
2259 allow_partial,
2260 values.clone(),
2261 );
2262
2263 let plan = self.restore_scoped_dirty_windows_on_err(
2264 &expr,
2265 sql_to_df_plan(query_ctx.clone(), engine.clone(), &self.config.query, false).await,
2266 )?;
2267 let rewrite = self.restore_scoped_dirty_windows_on_err(
2268 &expr,
2269 plan.clone()
2270 .rewrite(&mut add_filter)
2271 .and_then(|p| p.data.rewrite(&mut add_auto_column))
2272 .with_context(|_| DatafusionSnafu {
2273 context: format!("Failed to rewrite plan:\n {}\n", plan),
2274 })
2275 .map(|rewrite| rewrite.data),
2276 )?;
2277 let new_plan = self.restore_scoped_dirty_windows_on_err(
2279 &expr,
2280 apply_df_optimizer(rewrite, &query_ctx).await,
2281 )?;
2282
2283 let info = PlanInfo {
2284 plan: new_plan.clone(),
2285 dirty_restore: DirtyRestore::Scoped(expr),
2286 coverage,
2287 };
2288
2289 Ok(Some(info))
2290 }
2291}
2292
2293#[cfg(test)]
2294mod test;