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