1use std::collections::{BTreeMap, HashMap, HashSet};
18use std::sync::Arc;
19use std::time::Duration;
20
21use api::v1::flow::DirtyWindowRequests;
22use catalog::CatalogManagerRef;
23use common_error::ext::BoxedError;
24use common_meta::ddl::create_flow::{
25 FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY,
26 FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE, FlowType,
27};
28use common_meta::key::TableMetadataManagerRef;
29use common_meta::key::flow::FlowMetadataManagerRef;
30use common_meta::key::flow::flow_state::FlowStat;
31use common_meta::key::table_info::{TableInfoManager, TableInfoValue};
32use common_runtime::JoinHandle;
33use common_telemetry::tracing::warn;
34use common_telemetry::{debug, info};
35use common_time::TimeToLive;
36use datafusion_common::tree_node::{TreeNodeRecursion, TreeNodeVisitor};
37use datafusion_expr::LogicalPlan;
38use datatypes::prelude::ConcreteDataType;
39use query::QueryEngineRef;
40use session::context::QueryContext;
41use snafu::{OptionExt, ResultExt, ensure};
42use sql::parsers::utils::is_tql;
43use store_api::metric_engine_consts::is_metric_engine_internal_column;
44use store_api::mito_engine_options::APPEND_MODE_KEY;
45use store_api::storage::{RegionId, TableId};
46use table::table_reference::TableReference;
47use tokio::sync::{RwLock, oneshot};
48
49use crate::batching_mode::BatchingModeOptions;
50use crate::batching_mode::eval_schedule::EvalSchedule;
51use crate::batching_mode::frontend_client::FrontendClient;
52use crate::batching_mode::state::DirtyTimeWindows;
53use crate::batching_mode::task::{BatchingTask, TaskArgs};
54use crate::batching_mode::time_window::{TimeWindowExpr, find_time_window_expr};
55use crate::batching_mode::utils::sql_to_df_plan;
56use crate::engine::{FlowEngine, FlowStatProvider};
57use crate::error::{
58 CreateFlowSnafu, DatafusionSnafu, ExternalSnafu, FlowAlreadyExistSnafu, FlowNotFoundSnafu,
59 InvalidQuerySnafu, JoinTaskSnafu, TableNotFoundMetaSnafu, UnexpectedSnafu, UnsupportedSnafu,
60};
61use crate::metrics::METRIC_FLOW_BATCHING_ENGINE_BULK_MARK_TIME_WINDOW;
62use crate::{CreateFlowArgs, Error, FlowId, TableName};
63
64pub struct BatchingEngine {
68 runtime: RwLock<FlowRuntimeRegistry>,
69 pub(crate) frontend_client: Arc<FrontendClient>,
71 flow_metadata_manager: FlowMetadataManagerRef,
72 table_meta: TableMetadataManagerRef,
73 catalog_manager: CatalogManagerRef,
74 query_engine: QueryEngineRef,
75 pub(crate) batch_opts: Arc<BatchingModeOptions>,
78 execution_factory: Option<Arc<dyn crate::BatchingExecutionFactory>>,
79}
80
81#[derive(Default)]
82struct FlowRuntimeRegistry {
83 tasks: BTreeMap<FlowId, BatchingTask>,
84 shutdown_txs: BTreeMap<FlowId, oneshot::Sender<()>>,
85}
86
87impl FlowRuntimeRegistry {
88 fn insert(
89 &mut self,
90 flow_id: FlowId,
91 task: BatchingTask,
92 shutdown_tx: oneshot::Sender<()>,
93 ) -> (Option<BatchingTask>, Option<oneshot::Sender<()>>) {
94 (
95 self.tasks.insert(flow_id, task),
96 self.shutdown_txs.insert(flow_id, shutdown_tx),
97 )
98 }
99
100 fn remove(&mut self, flow_id: FlowId) -> Option<(BatchingTask, Option<oneshot::Sender<()>>)> {
101 let task = self.tasks.remove(&flow_id)?;
102 let shutdown_tx = self.shutdown_txs.remove(&flow_id);
103 Some((task, shutdown_tx))
104 }
105
106 fn remove_if_current(
107 &mut self,
108 flow_id: FlowId,
109 task: &BatchingTask,
110 ) -> (Option<BatchingTask>, Option<oneshot::Sender<()>>) {
111 if self
112 .tasks
113 .get(&flow_id)
114 .is_some_and(|current| Arc::ptr_eq(¤t.state, &task.state))
115 {
116 let Some((removed_task, removed_shutdown_tx)) = self.remove(flow_id) else {
117 return (None, None);
118 };
119 (Some(removed_task), removed_shutdown_tx)
120 } else {
121 (None, None)
122 }
123 }
124}
125
126impl BatchingEngine {
127 pub fn new(
128 frontend_client: Arc<FrontendClient>,
129 query_engine: QueryEngineRef,
130 flow_metadata_manager: FlowMetadataManagerRef,
131 table_meta: TableMetadataManagerRef,
132 catalog_manager: CatalogManagerRef,
133 batch_opts: BatchingModeOptions,
134 ) -> Self {
135 Self::new_with_execution(
136 frontend_client,
137 query_engine,
138 flow_metadata_manager,
139 table_meta,
140 catalog_manager,
141 batch_opts,
142 None,
143 )
144 }
145
146 pub fn new_with_execution(
147 frontend_client: Arc<FrontendClient>,
148 query_engine: QueryEngineRef,
149 flow_metadata_manager: FlowMetadataManagerRef,
150 table_meta: TableMetadataManagerRef,
151 catalog_manager: CatalogManagerRef,
152 batch_opts: BatchingModeOptions,
153 execution_factory: Option<Arc<dyn crate::BatchingExecutionFactory>>,
154 ) -> Self {
155 Self {
156 runtime: Default::default(),
157 frontend_client,
158 flow_metadata_manager,
159 table_meta,
160 catalog_manager,
161 query_engine,
162 batch_opts: Arc::new(batch_opts),
163 execution_factory,
164 }
165 }
166
167 pub async fn get_last_exec_time_map(&self) -> BTreeMap<FlowId, i64> {
169 let runtime = self.runtime.read().await;
170 runtime
171 .tasks
172 .iter()
173 .filter_map(|(flow_id, task)| {
174 task.last_execution_time_millis()
175 .map(|timestamp| (*flow_id, timestamp))
176 })
177 .collect()
178 }
179
180 pub async fn handle_mark_dirty_time_window(
186 &self,
187 reqs: DirtyWindowRequests,
188 ) -> Result<(), Error> {
189 let table_info_mgr = self.table_meta.table_info_manager();
190
191 let mut group_by_table_id: HashMap<u32, (Vec<i64>, Vec<api::v1::flow::TimeRange>)> =
192 HashMap::new();
193 for r in reqs.requests {
194 let tid = TableId::from(r.table_id);
195 let entry = group_by_table_id.entry(tid).or_default();
196 entry.0.extend(r.timestamps);
197 entry.1.extend(r.time_ranges);
198 }
199 let tids = group_by_table_id.keys().cloned().collect::<Vec<TableId>>();
200 let table_infos =
201 table_info_mgr
202 .batch_get(&tids)
203 .await
204 .with_context(|_| TableNotFoundMetaSnafu {
205 msg: format!("Failed to get table info for table ids: {:?}", tids),
206 })?;
207
208 let group_by_table_name = group_by_table_id
209 .into_iter()
210 .filter_map(|(id, (timestamps, time_ranges))| {
211 let table_name = table_infos.get(&id).map(|info| info.table_name());
212 let Some(table_name) = table_name else {
213 warn!("Failed to get table infos for table id: {:?}", id);
214 return None;
215 };
216 let table_name = [
217 table_name.catalog_name,
218 table_name.schema_name,
219 table_name.table_name,
220 ];
221 let schema = &table_infos.get(&id).unwrap().table_info.meta.schema;
222 let time_index_unit = schema.column_schemas()[schema.timestamp_index().unwrap()]
223 .data_type
224 .as_timestamp()
225 .unwrap()
226 .unit();
227 Some((table_name, (timestamps, time_ranges, time_index_unit)))
228 })
229 .collect::<HashMap<_, _>>();
230
231 let group_by_table_name = Arc::new(group_by_table_name);
232
233 let tasks = self
234 .runtime
235 .read()
236 .await
237 .tasks
238 .values()
239 .cloned()
240 .collect::<Vec<_>>();
241 let mut handles = Vec::new();
242
243 for task in tasks {
244 let src_table_names = &task.config.source_table_names;
245
246 if src_table_names
247 .iter()
248 .all(|name| !group_by_table_name.contains_key(name))
249 {
250 continue;
251 }
252
253 let group_by_table_name = group_by_table_name.clone();
254 let task = task.clone();
255 let handle: JoinHandle<Result<(), Error>> = tokio::spawn(async move {
256 let src_table_names = &task.config.source_table_names;
257 let mut all_dirty_windows = HashSet::new();
258 let mut all_dirty_ranges = Vec::new();
259 let mut is_dirty = false;
260 for src_table_name in src_table_names {
261 if let Some((timestamps, time_ranges, unit)) =
262 group_by_table_name.get(src_table_name)
263 {
264 let Some(expr) = &task.config.time_window_expr else {
265 is_dirty = true;
266 continue;
267 };
268 for timestamp in timestamps {
269 let align_start = expr
270 .eval(common_time::Timestamp::new(*timestamp, *unit))?
271 .0
272 .context(UnexpectedSnafu {
273 reason: format!(
274 "Failed to align dirty timestamp {timestamp}: missing window lower bound"
275 ),
276 })?;
277 all_dirty_windows.insert(align_start);
278 }
279 for time_range in time_ranges {
280 if time_range.end_exclusive <= time_range.start_inclusive {
281 warn!(
282 "Ignoring invalid dirty time range with start_inclusive={} >= end_exclusive={}",
283 time_range.start_inclusive, time_range.end_exclusive
284 );
285 continue;
286 }
287 let (align_start, align_end) = DirtyTimeWindows::align_time_window(
288 common_time::Timestamp::new(time_range.start_inclusive, *unit),
289 Some(common_time::Timestamp::new(time_range.end_exclusive, *unit)),
290 expr,
291 )?;
292 all_dirty_ranges.push((align_start, align_end));
293 }
294 }
295 }
296 let mut state = task.state.write().unwrap();
297 if is_dirty {
298 state.dirty_time_windows.set_dirty();
299 }
300 let flow_id_label = task.config.flow_id.to_string();
301 for timestamp in all_dirty_windows {
302 state.dirty_time_windows.add_window(timestamp, None);
303 }
304 for (start, end) in all_dirty_ranges {
305 state.dirty_time_windows.add_window(start, end);
306 }
307
308 METRIC_FLOW_BATCHING_ENGINE_BULK_MARK_TIME_WINDOW
309 .with_label_values(&[&flow_id_label])
310 .set(state.dirty_time_windows.len() as f64);
311 Ok(())
312 });
313 handles.push(handle);
314 }
315 for handle in handles {
316 handle.await.context(JoinTaskSnafu)??;
317 }
318
319 Ok(())
320 }
321
322 pub async fn handle_inserts_inner(
323 &self,
324 request: api::v1::region::InsertRequests,
325 ) -> Result<(), Error> {
326 let table_info_mgr = self.table_meta.table_info_manager();
327 let mut group_by_table_id: HashMap<TableId, Vec<api::v1::Rows>> = HashMap::new();
328
329 for r in request.requests {
330 let tid = RegionId::from(r.region_id).table_id();
331 let entry = group_by_table_id.entry(tid).or_default();
332 if let Some(rows) = r.rows {
333 entry.push(rows);
334 }
335 }
336
337 let tids = group_by_table_id.keys().cloned().collect::<Vec<TableId>>();
338 let table_infos =
339 table_info_mgr
340 .batch_get(&tids)
341 .await
342 .with_context(|_| TableNotFoundMetaSnafu {
343 msg: format!("Failed to get table info for table ids: {:?}", tids),
344 })?;
345
346 let missing_tids = tids
347 .iter()
348 .filter(|id| !table_infos.contains_key(id))
349 .collect::<Vec<_>>();
350 if !missing_tids.is_empty() {
351 warn!(
352 "Failed to get all the table info for table ids, expected table ids: {:?}, those table doesn't exist: {:?}",
353 tids, missing_tids
354 );
355 }
356
357 let group_by_table_name = group_by_table_id
358 .into_iter()
359 .filter_map(|(id, rows)| {
360 let table_name = table_infos.get(&id).map(|info| info.table_name());
361 let Some(table_name) = table_name else {
362 warn!("Failed to get table infos for table id: {:?}", id);
363 return None;
364 };
365 let table_name = [
366 table_name.catalog_name,
367 table_name.schema_name,
368 table_name.table_name,
369 ];
370 Some((table_name, rows))
371 })
372 .collect::<HashMap<_, _>>();
373
374 let group_by_table_name = Arc::new(group_by_table_name);
375
376 let tasks = self
377 .runtime
378 .read()
379 .await
380 .tasks
381 .values()
382 .cloned()
383 .collect::<Vec<_>>();
384 let mut handles = Vec::new();
385 for task in tasks {
386 let src_table_names = &task.config.source_table_names;
387
388 if src_table_names
389 .iter()
390 .all(|name| !group_by_table_name.contains_key(name))
391 {
392 continue;
393 }
394
395 let group_by_table_name = group_by_table_name.clone();
396 let task = task.clone();
397
398 let handle: JoinHandle<Result<(), Error>> = tokio::spawn(async move {
399 let src_table_names = &task.config.source_table_names;
400
401 let mut is_dirty = false;
402
403 for src_table_name in src_table_names {
404 if let Some(entry) = group_by_table_name.get(src_table_name) {
405 let Some(expr) = &task.config.time_window_expr else {
406 is_dirty = true;
407 continue;
408 };
409 let involved_time_windows = expr.handle_rows(entry.clone()).await?;
410 let mut state = task.state.write().unwrap();
411 state
412 .dirty_time_windows
413 .add_lower_bounds(involved_time_windows.into_iter());
414 }
415 }
416 if is_dirty {
417 task.state.write().unwrap().dirty_time_windows.set_dirty();
418 }
419
420 Ok(())
421 });
422 handles.push(handle);
423 }
424
425 for handle in handles {
426 match handle.await {
427 Err(e) => {
428 warn!("Failed to handle inserts: {e}");
429 }
430 Ok(Ok(())) => (),
431 Ok(Err(e)) => {
432 warn!("Failed to handle inserts: {e}");
433 }
434 }
435 }
436 Ok(())
437 }
438}
439
440impl FlowStatProvider for BatchingEngine {
441 async fn flow_stat(&self) -> FlowStat {
442 let runtime = self.runtime.read().await;
443 let mut last_exec_time_map = BTreeMap::new();
444 let mut start_time_map = BTreeMap::new();
445
446 for (flow_id, task) in runtime.tasks.iter() {
447 let id = *flow_id as u32;
448 if let Some(ts) = task.last_execution_time_millis() {
449 last_exec_time_map.insert(id, ts);
450 }
451 if let Some(ts) = task.start_time_millis() {
452 start_time_map.insert(id, ts);
453 }
454 }
455
456 FlowStat {
457 state_size: BTreeMap::new(),
458 last_exec_time_map,
459 start_time_map,
460 }
461 }
462}
463
464async fn get_table_name(
465 table_info: &TableInfoManager,
466 table_id: &TableId,
467) -> Result<TableName, Error> {
468 get_table_info(table_info, table_id).await.map(|info| {
469 let name = info.table_name();
470 [name.catalog_name, name.schema_name, name.table_name]
471 })
472}
473
474async fn get_table_info(
475 table_info: &TableInfoManager,
476 table_id: &TableId,
477) -> Result<TableInfoValue, Error> {
478 table_info
479 .get(*table_id)
480 .await
481 .map_err(BoxedError::new)
482 .context(ExternalSnafu)?
483 .with_context(|| UnexpectedSnafu {
484 reason: format!("Table id = {:?}, couldn't found table name", table_id),
485 })
486 .map(|info| info.into_inner())
487}
488
489impl BatchingEngine {
490 fn batch_opts_for_flow_options(
491 &self,
492 flow_options: &HashMap<String, String>,
493 exact_sequence_range_required: bool,
494 ) -> Result<Arc<BatchingModeOptions>, Error> {
495 let mut batch_opts = (*self.batch_opts).clone();
496 if let Some(enable_incremental_read) =
497 flow_options.get(FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY)
498 {
499 batch_opts.experimental_enable_incremental_read = if exact_sequence_range_required {
500 true
501 } else {
502 enable_incremental_read.parse::<bool>().map_err(|_| {
503 InvalidQuerySnafu {
504 reason: format!(
505 "Invalid flow option {FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY}: {enable_incremental_read}"
506 ),
507 }
508 .build()
509 })?
510 };
511 }
512
513 Ok(Arc::new(batch_opts))
514 }
515
516 fn table_options_enable_append_mode(extra_options: &HashMap<String, String>) -> bool {
517 extra_options
518 .get(APPEND_MODE_KEY)
519 .is_some_and(|value| value.eq_ignore_ascii_case("true"))
520 }
521
522 fn ensure_sql_flow_has_twe_or_eval_interval(
525 eval_interval: Option<i64>,
526 has_time_window_expr: bool,
527 ) -> Result<(), Error> {
528 ensure!(
529 eval_interval.is_some() || has_time_window_expr,
530 InvalidQuerySnafu {
531 reason: "SQL batching flow without a time-window expression must specify EVAL INTERVAL to run as an explicit full-query flow"
532 .to_string(),
533 }
534 );
535 Ok(())
536 }
537
538 fn ensure_incremental_source_append_only(
539 batch_opts: &BatchingModeOptions,
540 table_name: &[String; 3],
541 extra_options: &HashMap<String, String>,
542 ) -> Result<(), Error> {
543 if batch_opts.experimental_enable_incremental_read {
544 ensure!(
545 Self::table_options_enable_append_mode(extra_options),
546 UnsupportedSnafu {
547 reason: format!(
548 "Flow incremental read requires append-only source table, but source table `{}` is not append-only. Consider setting append_mode='true' on the source table or disabling experimental_enable_incremental_read",
549 table_name.join(".")
550 ),
551 }
552 );
553 }
554
555 Ok(())
556 }
557
558 pub async fn create_flow_inner(&self, args: CreateFlowArgs) -> Result<Option<FlowId>, Error> {
559 let CreateFlowArgs {
560 flow_id,
561 sink_table_name,
562 source_table_ids,
563 create_if_not_exists,
564 or_replace,
565 expire_after,
566 eval_interval,
567 comment: _,
568 sql,
569 flow_options,
570 query_ctx,
571 eval_schedule: eval_schedule_config,
572 } = args;
573
574 {
576 let is_exist = self.runtime.read().await.tasks.contains_key(&flow_id);
577 match (create_if_not_exists, or_replace, is_exist) {
578 (_, true, true) => {
580 info!("Replacing flow with id={}", flow_id);
581 }
582 (false, false, true) => FlowAlreadyExistSnafu { id: flow_id }.fail()?,
583 (true, false, true) => {
585 info!("Flow with id={} already exists, do nothing", flow_id);
586 return Ok(None);
587 }
588
589 (_, _, false) => (),
591 }
592 }
593
594 let query_ctx = query_ctx.context({
595 UnexpectedSnafu {
596 reason: "Query context is None".to_string(),
597 }
598 })?;
599 let query_ctx = Arc::new(query_ctx);
600 let is_tql = is_tql(query_ctx.sql_dialect(), &sql)
601 .map_err(BoxedError::new)
602 .context(CreateFlowSnafu { sql: &sql })?;
603
604 if eval_interval.is_none() && is_tql {
606 InvalidQuerySnafu {
607 reason: "TQL query requires EVAL INTERVAL to be set".to_string(),
608 }
609 .fail()?;
610 }
611
612 let flow_type = flow_options.get(FlowType::FLOW_TYPE_KEY);
613
614 ensure!(
615 match flow_type {
616 None => true,
617 Some(ty) if ty == FlowType::BATCHING => true,
618 _ => false,
619 },
620 UnexpectedSnafu {
621 reason: format!("Flow type is not batching nor None, got {flow_type:?}")
622 }
623 );
624
625 let exact_sequence_range_required = flow_options
629 .get(FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY)
630 .is_some_and(|value| value == FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE);
631 let batch_opts =
632 self.batch_opts_for_flow_options(&flow_options, exact_sequence_range_required)?;
633
634 let mut source_table_names = Vec::with_capacity(2);
635 for src_id in source_table_ids {
636 let table_name = get_table_name(self.table_meta.table_info_manager(), &src_id).await?;
638 let table_info = get_table_info(self.table_meta.table_info_manager(), &src_id).await?;
639 ensure!(
640 table_info.table_info.meta.options.ttl != Some(TimeToLive::Instant),
641 UnsupportedSnafu {
642 reason: format!(
643 "Source table `{}`(id={}) has instant TTL, Instant TTL is not supported under batching mode. Consider using a TTL longer than flush interval",
644 table_name.join("."),
645 src_id
646 ),
647 }
648 );
649 Self::ensure_incremental_source_append_only(
650 &batch_opts,
651 &table_name,
652 &table_info.table_info.meta.options.extra_options,
653 )?;
654
655 source_table_names.push(table_name);
656 }
657
658 let (tx, rx) = oneshot::channel();
659
660 let plan = sql_to_df_plan(query_ctx.clone(), self.query_engine.clone(), &sql, true).await?;
661
662 if is_tql {
663 self.check_is_tql_table(&plan, &query_ctx).await?;
664 }
665
666 let phy_expr = if !is_tql {
667 let (column_name, time_window_expr, _, df_schema) = find_time_window_expr(
668 &plan,
669 self.query_engine.engine_state().catalog_manager().clone(),
670 query_ctx.clone(),
671 )
672 .await?;
673 time_window_expr
674 .map(|expr| {
675 TimeWindowExpr::from_expr(
676 &expr,
677 &column_name,
678 &df_schema,
679 &self.query_engine.engine_state().session_state(),
680 )
681 })
682 .transpose()?
683 } else {
684 None
686 };
687
688 debug!(
689 "Flow id={}, found time window expr={}",
690 flow_id,
691 phy_expr
692 .as_ref()
693 .map(|phy_expr| phy_expr.to_string())
694 .unwrap_or("None".to_string())
695 );
696
697 if !is_tql {
698 Self::ensure_sql_flow_has_twe_or_eval_interval(eval_interval, phy_expr.is_some())?;
699 }
700
701 let eval_schedule = {
703 let interval = eval_interval;
704 let config = eval_schedule_config.as_ref();
705 match EvalSchedule::from_config(interval, config) {
706 Ok(s) => s,
707 Err(e) => {
708 return UnexpectedSnafu {
709 reason: format!(
710 "Failed to build eval schedule for flow {}: {}",
711 flow_id, e
712 ),
713 }
714 .fail();
715 }
716 }
717 };
718
719 let task_args = TaskArgs {
720 flow_id,
721 query: &sql,
722 plan,
723 time_window_expr: phy_expr,
724 expire_after,
725 sink_table_name,
726 source_table_names,
727 query_ctx,
728 catalog_manager: self.catalog_manager.clone(),
729 shutdown_rx: rx,
730 batch_opts,
731 flow_eval_interval: eval_interval.map(|secs| Duration::from_secs(secs as u64)),
732 eval_schedule,
733 };
734
735 let allow_sink_create = flow_options
736 .get(common_meta::ddl::create_flow::INTERNAL_ALLOW_SINK_CREATE_KEY)
737 .map(String::as_str)
738 != Some("false");
739 let task = BatchingTask::try_new_with_exact_sequence_range_required(
740 task_args,
741 exact_sequence_range_required,
742 )?
743 .with_allow_sink_create(allow_sink_create);
744
745 if task.config.exact_sequence_range_required {
746 ensure!(
747 task.sequence_range_capable().await?,
748 UnsupportedSnafu {
749 reason: format!(
750 "Flow {flow_id} requires exact sequence-range reads, but a source table lacks the Mito preserve_row_sequence capability"
751 ),
752 }
753 );
754 }
755
756 let engine = self.query_engine.clone();
757 let frontend = self.frontend_client.clone();
758
759 let table = task.check_or_create_sink_table(&engine, &frontend).await?;
762 let execution = if let Some(factory) = &self.execution_factory {
763 factory.create(&task, table, &engine, &frontend).await?
764 } else {
765 None
766 };
767 if execution.is_none() {
768 task.validate_sink_table_schema(&engine).await?;
769 }
770 let task = task.with_execution(execution);
771 let task_inner = task.clone();
772
773 let (start_tx, start_rx) = oneshot::channel();
774
775 let handle = common_runtime::spawn_global(async move {
777 if start_rx.await.is_ok() {
778 task_inner.start_executing_loop(engine, frontend).await;
779 }
780 });
781 task.state.write().unwrap().task_handle = Some(handle);
782 let task_for_rollback = task.clone();
783
784 let (replaced_old_task_opt, replaced_old_shutdown_tx) = {
789 let mut runtime = self.runtime.write().await;
790
791 let is_exist = runtime.tasks.contains_key(&flow_id);
792 match (create_if_not_exists, or_replace, is_exist) {
793 (_, true, true) => {
794 info!(
795 "Replacing flow with id={} after final registry check",
796 flow_id
797 );
798 }
799 (false, false, true) => {
800 abort_flow_task(flow_id, Some(task), "unregistered");
801 return FlowAlreadyExistSnafu { id: flow_id }.fail();
802 }
803 (true, false, true) => {
804 info!(
805 "Flow with id={} already exists at final registry check, do nothing",
806 flow_id
807 );
808 abort_flow_task(flow_id, Some(task), "unregistered");
809 return Ok(None);
810 }
811 (_, _, false) => (),
812 }
813
814 runtime.insert(flow_id, task, tx)
815 };
816
817 notify_flow_shutdown(flow_id, replaced_old_shutdown_tx, "replaced");
818 abort_flow_task(flow_id, replaced_old_task_opt, "replaced");
819 if start_tx.send(()).is_err() {
820 self.rollback_flow_runtime_if_current(flow_id, &task_for_rollback)
821 .await;
822 UnexpectedSnafu {
823 reason: format!("Failed to start flow {flow_id} due to task already dropped"),
824 }
825 .fail()?;
826 }
827
828 Ok(Some(flow_id))
829 }
830
831 async fn check_is_tql_table(
832 &self,
833 query: &LogicalPlan,
834 query_ctx: &QueryContext,
835 ) -> Result<(), Error> {
836 struct CollectTableRef {
837 table_refs: HashSet<datafusion_common::TableReference>,
838 }
839
840 impl TreeNodeVisitor<'_> for CollectTableRef {
841 type Node = LogicalPlan;
842 fn f_down(
843 &mut self,
844 node: &Self::Node,
845 ) -> datafusion_common::Result<TreeNodeRecursion> {
846 if let LogicalPlan::TableScan(scan) = node {
847 self.table_refs.insert(scan.table_name.clone());
848 }
849 Ok(TreeNodeRecursion::Continue)
850 }
851 }
852 let mut table_refs = CollectTableRef {
853 table_refs: HashSet::new(),
854 };
855 query
856 .visit_with_subqueries(&mut table_refs)
857 .context(DatafusionSnafu {
858 context: "Checking if all source tables are TQL tables",
859 })?;
860
861 let default_catalog = query_ctx.current_catalog();
862 let default_schema = query_ctx.current_schema();
863 let default_schema = &default_schema;
864
865 for table_ref in table_refs.table_refs {
866 let table_ref = match &table_ref {
867 datafusion_common::TableReference::Bare { table } => {
868 TableReference::full(default_catalog, default_schema, table)
869 }
870 datafusion_common::TableReference::Partial { schema, table } => {
871 TableReference::full(default_catalog, schema, table)
872 }
873 datafusion_common::TableReference::Full {
874 catalog,
875 schema,
876 table,
877 } => TableReference::full(catalog, schema, table),
878 };
879
880 let table_id = self
881 .table_meta
882 .table_name_manager()
883 .get(table_ref.into())
884 .await
885 .map_err(BoxedError::new)
886 .context(ExternalSnafu)?
887 .with_context(|| UnexpectedSnafu {
888 reason: format!("Failed to get table id for table: {}", table_ref),
889 })?
890 .table_id();
891 let table_info =
892 get_table_info(self.table_meta.table_info_manager(), &table_id).await?;
893 let value_cols = table_info
895 .table_info
896 .meta
897 .schema
898 .column_schemas()
899 .iter()
900 .filter(|col| col.data_type == ConcreteDataType::float64_datatype())
901 .collect::<Vec<_>>();
902 ensure!(
903 value_cols.len() == 1,
904 InvalidQuerySnafu {
905 reason: format!(
906 "TQL query only supports one f64 value column, table `{}`(id={}) has {} f64 value columns, columns are: {:?}",
907 table_ref,
908 table_id,
909 value_cols.len(),
910 value_cols
911 ),
912 }
913 );
914 let pk_idxs = table_info
916 .table_info
917 .meta
918 .primary_key_indices
919 .iter()
920 .collect::<HashSet<_>>();
921
922 for (idx, col) in table_info
923 .table_info
924 .meta
925 .schema
926 .column_schemas()
927 .iter()
928 .enumerate()
929 {
930 if is_metric_engine_internal_column(&col.name) {
931 continue;
932 }
933 let is_pk: bool = pk_idxs.contains(&&idx);
939
940 ensure!(
941 col.data_type == ConcreteDataType::float64_datatype()
942 || col.data_type.is_timestamp()
943 || (col.data_type == ConcreteDataType::string_datatype() && is_pk),
944 InvalidQuerySnafu {
945 reason: format!(
946 "TQL query only supports f64 value column, timestamp column and string tag columns, table `{}`(id={}) has column `{}` with type {:?} which is not supported",
947 table_ref, table_id, col.name, col.data_type
948 ),
949 }
950 );
951 }
952 }
953 Ok(())
954 }
955
956 pub async fn remove_flow_inner(&self, flow_id: FlowId) -> Result<(), Error> {
957 let (task, shutdown_tx) = {
958 let mut runtime = self.runtime.write().await;
959 let Some((task, shutdown_tx)) = runtime.remove(flow_id) else {
960 warn!("Flow {flow_id} not found in tasks");
961 FlowNotFoundSnafu { id: flow_id }.fail()?
962 };
963 (task, shutdown_tx)
964 };
965
966 let had_shutdown_tx = notify_flow_shutdown(flow_id, shutdown_tx, "removed");
967 abort_flow_task(flow_id, Some(task), "removed");
968
969 if !had_shutdown_tx {
970 UnexpectedSnafu {
971 reason: format!("Can't found shutdown tx for flow {flow_id}"),
972 }
973 .fail()?
974 }
975
976 Ok(())
977 }
978
979 pub async fn flush_flow_inner(&self, flow_id: FlowId) -> Result<usize, Error> {
982 debug!("Try flush flow {flow_id}");
983 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
987 let task = self.runtime.read().await.tasks.get(&flow_id).cloned();
988 let task = task.with_context(|| FlowNotFoundSnafu { id: flow_id })?;
989
990 let time_window_size = task
991 .config
992 .time_window_expr
993 .as_ref()
994 .and_then(|expr| *expr.time_window_size());
995
996 let cur_dirty_window_cnt = time_window_size.map(|time_window_size| {
997 task.state
998 .read()
999 .unwrap()
1000 .dirty_time_windows
1001 .effective_count(&time_window_size)
1002 });
1003
1004 let res = task
1005 .execute_once_serialized(
1006 &self.query_engine,
1007 &self.frontend_client,
1008 cur_dirty_window_cnt,
1009 )
1010 .await?;
1011
1012 let affected_rows = res.map(|(r, _)| r).unwrap_or_default();
1013 debug!(
1014 "Successfully flush flow {flow_id}, affected rows={}",
1015 affected_rows
1016 );
1017 Ok(affected_rows)
1018 }
1019
1020 pub async fn flow_exist_inner(&self, flow_id: FlowId) -> bool {
1022 self.runtime.read().await.tasks.contains_key(&flow_id)
1023 }
1024
1025 async fn rollback_flow_runtime_if_current(&self, flow_id: FlowId, task: &BatchingTask) {
1026 let (removed_task, removed_shutdown_tx) = {
1027 let mut runtime = self.runtime.write().await;
1028 runtime.remove_if_current(flow_id, task)
1029 };
1030
1031 notify_flow_shutdown(flow_id, removed_shutdown_tx, "rolled back");
1032 abort_flow_task(flow_id, removed_task, "rolled back");
1033 }
1034}
1035
1036fn notify_flow_shutdown(flow_id: FlowId, tx: Option<oneshot::Sender<()>>, action: &str) -> bool {
1037 let Some(tx) = tx else {
1038 return false;
1039 };
1040
1041 if tx.send(()).is_err() {
1042 warn!(
1043 "Fail to shutdown {action} flow {flow_id} due to receiver already dropped, maybe flow {flow_id} is already dropped?"
1044 );
1045 }
1046
1047 true
1048}
1049
1050fn abort_flow_task(flow_id: FlowId, task: Option<BatchingTask>, action: &str) -> bool {
1051 let Some(task) = task else {
1052 return false;
1053 };
1054
1055 task.stop_execution();
1056
1057 if let Some(handle) = task.state.write().unwrap().task_handle.take() {
1058 handle.abort();
1059 debug!("Aborted {action} flow task {flow_id}");
1060 return true;
1061 }
1062
1063 false
1064}
1065
1066impl FlowEngine for BatchingEngine {
1067 async fn create_flow(&self, args: CreateFlowArgs) -> Result<Option<FlowId>, Error> {
1068 self.create_flow_inner(args).await
1069 }
1070 async fn remove_flow(&self, flow_id: FlowId) -> Result<(), Error> {
1071 self.remove_flow_inner(flow_id).await
1072 }
1073 async fn flush_flow(&self, flow_id: FlowId) -> Result<usize, Error> {
1074 self.flush_flow_inner(flow_id).await
1075 }
1076 async fn flow_exist(&self, flow_id: FlowId) -> Result<bool, Error> {
1077 Ok(self.flow_exist_inner(flow_id).await)
1078 }
1079 async fn list_flows(&self) -> Result<impl IntoIterator<Item = FlowId>, Error> {
1080 Ok(self
1081 .runtime
1082 .read()
1083 .await
1084 .tasks
1085 .keys()
1086 .cloned()
1087 .collect::<Vec<_>>())
1088 }
1089 async fn handle_flow_inserts(
1090 &self,
1091 request: api::v1::region::InsertRequests,
1092 ) -> Result<(), Error> {
1093 self.handle_inserts_inner(request).await
1094 }
1095 async fn handle_mark_window_dirty(
1096 &self,
1097 req: api::v1::flow::DirtyWindowRequests,
1098 ) -> Result<(), Error> {
1099 self.handle_mark_dirty_time_window(req).await
1100 }
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105 use api::v1::flow::{DirtyWindowRequest, TimeRange};
1106 use catalog::RegisterTableRequest;
1107 use catalog::memory::{MemoryCatalogManager, new_memory_catalog_manager};
1108 use common_meta::key::TableMetadataManager;
1109 use common_meta::key::flow::FlowMetadataManager;
1110 use common_meta::key::table_route::TableRouteValue;
1111 use common_meta::key::test_utils::new_test_table_info_with_name;
1112 use common_meta::kv_backend::memory::MemoryKvBackend;
1113 use common_recordbatch::RecordBatch;
1114 use common_time::timestamp::TimeUnit;
1115 use datatypes::schema::{ColumnSchema, Schema};
1116 use datatypes::vectors::{TimestampMillisecondVector, UInt32Vector, VectorRef};
1117 use query::options::QueryOptions;
1118 use session::context::QueryContext;
1119 use tokio::sync::Notify;
1120
1121 use super::*;
1122 use crate::ExecuteOnceOutcome;
1123 use crate::test_utils::create_test_query_engine;
1124
1125 struct DropNotify(Option<oneshot::Sender<()>>);
1126
1127 impl Drop for DropNotify {
1128 fn drop(&mut self) {
1129 if let Some(tx) = self.0.take() {
1130 let _ = tx.send(());
1131 }
1132 }
1133 }
1134
1135 async fn new_test_engine() -> BatchingEngine {
1136 let kv_backend = Arc::new(MemoryKvBackend::new());
1137 let table_meta = Arc::new(TableMetadataManager::new(kv_backend.clone()));
1138 table_meta.init().await.unwrap();
1139 let flow_meta = Arc::new(FlowMetadataManager::new(kv_backend));
1140 let catalog_manager = new_memory_catalog_manager().unwrap();
1141 let query_engine = create_test_query_engine();
1142 let (frontend_client, _handler) =
1143 FrontendClient::from_empty_grpc_handler(QueryOptions::default());
1144
1145 BatchingEngine::new(
1146 Arc::new(frontend_client),
1147 query_engine,
1148 flow_meta,
1149 table_meta,
1150 catalog_manager,
1151 BatchingModeOptions::default(),
1152 )
1153 }
1154
1155 async fn new_test_engine_with_execution(
1156 execution_factory: Option<Arc<dyn crate::BatchingExecutionFactory>>,
1157 ) -> BatchingEngine {
1158 let kv_backend = Arc::new(MemoryKvBackend::new());
1159 let table_meta = Arc::new(TableMetadataManager::new(kv_backend.clone()));
1160 table_meta.init().await.unwrap();
1161 let flow_meta = Arc::new(FlowMetadataManager::new(kv_backend));
1162 let query_engine = create_test_query_engine();
1163 let catalog_manager = query_engine.engine_state().catalog_manager().clone();
1164 let (frontend_client, _handler) =
1165 FrontendClient::from_empty_grpc_handler(QueryOptions::default());
1166
1167 let engine = BatchingEngine::new_with_execution(
1168 Arc::new(frontend_client),
1169 query_engine,
1170 flow_meta,
1171 table_meta,
1172 catalog_manager,
1173 BatchingModeOptions::default(),
1174 execution_factory,
1175 );
1176 engine
1177 .table_meta
1178 .create_table_metadata(
1179 new_test_table_info_with_name(1, "numbers_with_ts"),
1180 TableRouteValue::physical(vec![]),
1181 HashMap::new(),
1182 )
1183 .await
1184 .unwrap();
1185 engine
1186 }
1187
1188 fn register_sink_with_schema(engine: &BatchingEngine, name: &str) {
1189 let schema = Arc::new(Schema::new(vec![
1190 ColumnSchema::new("number", ConcreteDataType::uint32_datatype(), false),
1191 ColumnSchema::new(
1192 "ts",
1193 ConcreteDataType::timestamp_millisecond_datatype(),
1194 false,
1195 )
1196 .with_time_index(true),
1197 ]));
1198 let recordbatch = RecordBatch::new(
1199 schema,
1200 vec![
1201 Arc::new(UInt32Vector::from_slice([1_u32])) as VectorRef,
1202 Arc::new(TimestampMillisecondVector::from_slice([0_i64])) as VectorRef,
1203 ],
1204 )
1205 .unwrap();
1206 engine
1207 .catalog_manager
1208 .as_any()
1209 .downcast_ref::<MemoryCatalogManager>()
1210 .unwrap()
1211 .register_table_sync(RegisterTableRequest {
1212 catalog: "greptime".to_string(),
1213 schema: "public".to_string(),
1214 table_name: name.to_string(),
1215 table_id: 9000,
1216 table: table::test_util::MemTable::table(name, recordbatch),
1217 })
1218 .unwrap();
1219 }
1220
1221 fn register_number_only_sink(engine: &BatchingEngine, name: &str) {
1222 let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1223 "number",
1224 ConcreteDataType::uint32_datatype(),
1225 false,
1226 )]));
1227 let recordbatch = RecordBatch::new(
1228 schema,
1229 vec![Arc::new(UInt32Vector::from_slice([1_u32])) as VectorRef],
1230 )
1231 .unwrap();
1232 engine
1233 .catalog_manager
1234 .as_any()
1235 .downcast_ref::<MemoryCatalogManager>()
1236 .unwrap()
1237 .register_table_sync(RegisterTableRequest {
1238 catalog: "greptime".to_string(),
1239 schema: "public".to_string(),
1240 table_name: name.to_string(),
1241 table_id: 9001,
1242 table: table::test_util::MemTable::table(name, recordbatch),
1243 })
1244 .unwrap();
1245 }
1246
1247 fn flow_create_args(flow_id: FlowId, sink: &str) -> CreateFlowArgs {
1248 CreateFlowArgs {
1249 flow_id,
1250 sink_table_name: [
1251 "greptime".to_string(),
1252 "public".to_string(),
1253 sink.to_string(),
1254 ],
1255 source_table_ids: vec![1],
1256 create_if_not_exists: false,
1257 or_replace: false,
1258 expire_after: None,
1259 eval_interval: Some(10),
1260 comment: None,
1261 sql: "SELECT number, ts FROM numbers_with_ts".to_string(),
1262 flow_options: HashMap::new(),
1263 query_ctx: Some(QueryContext::arc().as_ref().clone()),
1264 eval_schedule: None,
1265 }
1266 }
1267
1268 struct TestExecution {
1269 manual_calls: std::sync::atomic::AtomicUsize,
1270 stops: std::sync::atomic::AtomicUsize,
1271 }
1272
1273 #[async_trait::async_trait]
1274 impl crate::BatchingExecution for TestExecution {
1275 async fn execute_once(
1276 self: Arc<Self>,
1277 _guard: crate::BatchingExecutionGuard,
1278 task: &BatchingTask,
1279 _engine: &QueryEngineRef,
1280 _frontend: &Arc<FrontendClient>,
1281 _max_window_cnt: Option<usize>,
1282 ) -> ExecuteOnceOutcome {
1283 if task
1284 .state
1285 .read()
1286 .unwrap()
1287 .query_ctx
1288 .extension(query::options::FLOW_SCHEDULED_TIME_MILLIS)
1289 .is_none()
1290 {
1291 self.manual_calls
1292 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1293 }
1294 ExecuteOnceOutcome {
1295 new_query: None,
1296 result: Ok(None),
1297 }
1298 }
1299
1300 fn stop(&self) {
1301 self.stops.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1302 }
1303 }
1304
1305 type TestExecutionResult = crate::Result<Option<Arc<dyn crate::BatchingExecution>>>;
1306
1307 struct TestExecutionFactory {
1308 entered: Option<Arc<Notify>>,
1309 release: Option<Arc<Notify>>,
1310 result: std::sync::Mutex<Option<TestExecutionResult>>,
1311 }
1312
1313 #[async_trait::async_trait]
1314 impl crate::BatchingExecutionFactory for TestExecutionFactory {
1315 async fn create(
1316 &self,
1317 _task: &BatchingTask,
1318 _sink: table::TableRef,
1319 _engine: &QueryEngineRef,
1320 _frontend: &Arc<FrontendClient>,
1321 ) -> crate::Result<Option<Arc<dyn crate::BatchingExecution>>> {
1322 if let Some(entered) = &self.entered {
1323 entered.notify_one();
1324 }
1325 if let Some(release) = &self.release {
1326 release.notified().await;
1327 }
1328 self.result
1329 .lock()
1330 .unwrap()
1331 .take()
1332 .expect("execution factory should only be called once")
1333 }
1334 }
1335
1336 #[tokio::test]
1337 async fn test_execution_factory_finishes_before_task_publication() {
1338 const GATE_TIMEOUT: Duration = Duration::from_secs(1);
1339
1340 let execution = Arc::new(TestExecution {
1341 manual_calls: Default::default(),
1342 stops: Default::default(),
1343 });
1344 let entered = Arc::new(Notify::new());
1345 let release = Arc::new(Notify::new());
1346 let factory = Arc::new(TestExecutionFactory {
1347 entered: Some(entered.clone()),
1348 release: Some(release.clone()),
1349 result: std::sync::Mutex::new(Some(Ok(Some(execution.clone())))),
1350 });
1351 let engine = Arc::new(new_test_engine_with_execution(Some(factory)).await);
1352 register_sink_with_schema(&engine, "factory_sink");
1353
1354 let entered_wait = entered.notified();
1355 let mut args = flow_create_args(6, "factory_sink");
1356 args.eval_interval = Some(86_400);
1357 let mut create = tokio::spawn({
1358 let engine = engine.clone();
1359 async move { engine.create_flow_inner(args).await }
1360 });
1361 if tokio::time::timeout(GATE_TIMEOUT, entered_wait)
1362 .await
1363 .is_err()
1364 {
1365 release.notify_one();
1366 if tokio::time::timeout(GATE_TIMEOUT, &mut create)
1367 .await
1368 .is_err()
1369 {
1370 create.abort();
1371 }
1372 panic!("execution factory should be entered");
1373 }
1374 let unpublished = {
1375 let runtime = engine.runtime.read().await;
1376 !runtime.tasks.contains_key(&6) && !runtime.shutdown_txs.contains_key(&6)
1377 };
1378
1379 release.notify_one();
1380 assert!(unpublished);
1381 let created = tokio::time::timeout(GATE_TIMEOUT, &mut create)
1382 .await
1383 .expect("flow creation should finish after factory release");
1384 created.unwrap().unwrap();
1385 assert!(engine.flow_exist_inner(6).await);
1386 let calls_before_flush = execution
1387 .manual_calls
1388 .load(std::sync::atomic::Ordering::SeqCst);
1389 assert_eq!(engine.flush_flow_inner(6).await.unwrap(), 0);
1390 assert_eq!(
1391 execution
1392 .manual_calls
1393 .load(std::sync::atomic::Ordering::SeqCst),
1394 calls_before_flush + 1
1395 );
1396 engine.remove_flow_inner(6).await.unwrap();
1397 }
1398
1399 #[tokio::test]
1400 async fn test_execution_factory_result_controls_sink_validation_and_publication() {
1401 let no_factory_engine = new_test_engine_with_execution(None).await;
1402 register_number_only_sink(&no_factory_engine, "no_factory_sink");
1403 assert!(
1404 no_factory_engine
1405 .create_flow_inner(flow_create_args(7, "no_factory_sink"))
1406 .await
1407 .is_err()
1408 );
1409 assert!(!no_factory_engine.flow_exist_inner(7).await);
1410
1411 let declined_engine =
1412 new_test_engine_with_execution(Some(Arc::new(TestExecutionFactory {
1413 entered: None,
1414 release: None,
1415 result: std::sync::Mutex::new(Some(Ok(None))),
1416 })))
1417 .await;
1418 register_number_only_sink(&declined_engine, "declined_factory_sink");
1419 assert!(
1420 declined_engine
1421 .create_flow_inner(flow_create_args(8, "declined_factory_sink"))
1422 .await
1423 .is_err()
1424 );
1425 assert!(!declined_engine.flow_exist_inner(8).await);
1426
1427 let accepted_engine =
1428 new_test_engine_with_execution(Some(Arc::new(TestExecutionFactory {
1429 entered: None,
1430 release: None,
1431 result: std::sync::Mutex::new(Some(Ok(Some(Arc::new(TestExecution {
1432 manual_calls: Default::default(),
1433 stops: Default::default(),
1434 }))))),
1435 })))
1436 .await;
1437 register_number_only_sink(&accepted_engine, "accepted_factory_sink");
1438 accepted_engine
1439 .create_flow_inner(flow_create_args(9, "accepted_factory_sink"))
1440 .await
1441 .unwrap();
1442 assert!(accepted_engine.flow_exist_inner(9).await);
1443 accepted_engine.remove_flow_inner(9).await.unwrap();
1444
1445 let error_engine = new_test_engine_with_execution(Some(Arc::new(TestExecutionFactory {
1446 entered: None,
1447 release: None,
1448 result: std::sync::Mutex::new(Some(
1449 UnexpectedSnafu {
1450 reason: "test execution factory failure".to_string(),
1451 }
1452 .fail(),
1453 )),
1454 })))
1455 .await;
1456 register_sink_with_schema(&error_engine, "error_factory_sink");
1457 assert!(
1458 error_engine
1459 .create_flow_inner(flow_create_args(10, "error_factory_sink"))
1460 .await
1461 .is_err()
1462 );
1463 assert!(!error_engine.flow_exist_inner(10).await);
1464 }
1465
1466 #[tokio::test]
1467 async fn test_flow_option_overrides_incremental_read_switch() {
1468 let engine = new_test_engine().await;
1469
1470 let default_opts = engine
1471 .batch_opts_for_flow_options(&HashMap::new(), false)
1472 .unwrap();
1473 assert!(!default_opts.experimental_enable_incremental_read);
1474
1475 let enabled_opts = engine
1476 .batch_opts_for_flow_options(
1477 &HashMap::from([(
1478 FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY.to_string(),
1479 "true".to_string(),
1480 )]),
1481 false,
1482 )
1483 .unwrap();
1484 assert!(enabled_opts.experimental_enable_incremental_read);
1485
1486 let exact_opts = engine
1487 .batch_opts_for_flow_options(
1488 &HashMap::from([(
1489 FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY.to_string(),
1490 FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE.to_string(),
1491 )]),
1492 true,
1493 )
1494 .unwrap();
1495 assert!(exact_opts.experimental_enable_incremental_read);
1496 }
1497
1498 #[test]
1499 fn test_table_options_enable_append_mode() {
1500 assert!(!BatchingEngine::table_options_enable_append_mode(
1501 &HashMap::new()
1502 ));
1503 assert!(!BatchingEngine::table_options_enable_append_mode(
1504 &HashMap::from([(APPEND_MODE_KEY.to_string(), "false".to_string())])
1505 ));
1506 assert!(BatchingEngine::table_options_enable_append_mode(
1507 &HashMap::from([(APPEND_MODE_KEY.to_string(), "TRUE".to_string())])
1508 ));
1509 }
1510
1511 #[test]
1512 fn test_sql_flow_requires_time_window_or_eval_interval() {
1513 BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(None, true)
1514 .expect("SQL flow with a time-window expression should be accepted");
1515 BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(Some(10), false).expect(
1516 "SQL flow with EVAL INTERVAL should be accepted as an explicit full-query flow",
1517 );
1518
1519 let err = BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(None, false)
1520 .expect_err("SQL flow without a time-window expression or EVAL INTERVAL should fail");
1521 assert!(matches!(err, Error::InvalidQuery { .. }), "{err}");
1522 assert!(
1523 err.to_string().contains("must specify EVAL INTERVAL"),
1524 "{err}"
1525 );
1526 }
1527
1528 #[tokio::test]
1529 async fn test_complex_sql_without_eval_interval_is_rejected_as_no_twe() {
1530 let query_engine = create_test_query_engine();
1531 let ctx = QueryContext::arc();
1532 let plan = sql_to_df_plan(
1533 ctx.clone(),
1534 query_engine.clone(),
1535 r#"
1536SELECT
1537 l.number,
1538 date_bin('5 minutes', l.ts) AS time_window
1539FROM numbers_with_ts l
1540JOIN numbers_with_ts r ON l.number = r.number
1541GROUP BY l.number, time_window
1542"#,
1543 true,
1544 )
1545 .await
1546 .unwrap();
1547
1548 let (_, time_window_expr, _, _) = find_time_window_expr(
1549 &plan,
1550 query_engine.engine_state().catalog_manager().clone(),
1551 ctx,
1552 )
1553 .await
1554 .unwrap();
1555 assert!(
1556 time_window_expr.is_none(),
1557 "complex SQL should be classified as having no safe TWE"
1558 );
1559
1560 BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(Some(10), false)
1561 .expect("complex SQL can run as an explicit full-query flow when EVAL INTERVAL is set");
1562 let err = BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(None, false)
1563 .expect_err("complex SQL without EVAL INTERVAL should fail creation");
1564 assert!(matches!(err, Error::InvalidQuery { .. }), "{err}");
1565 }
1566
1567 #[test]
1568 fn test_incremental_source_append_only_enforcement() {
1569 let table_name = [
1570 "greptime".to_string(),
1571 "public".to_string(),
1572 "numbers".to_string(),
1573 ];
1574 let disabled_opts = BatchingModeOptions::default();
1575 let enabled_opts = BatchingModeOptions {
1576 experimental_enable_incremental_read: true,
1577 ..Default::default()
1578 };
1579 let non_append_options = HashMap::new();
1580 let append_options = HashMap::from([(APPEND_MODE_KEY.to_string(), "true".to_string())]);
1581
1582 BatchingEngine::ensure_incremental_source_append_only(
1583 &disabled_opts,
1584 &table_name,
1585 &non_append_options,
1586 )
1587 .expect("disabled incremental read should not require append-only source");
1588 BatchingEngine::ensure_incremental_source_append_only(
1589 &enabled_opts,
1590 &table_name,
1591 &append_options,
1592 )
1593 .expect("append-only source should be accepted when incremental read is enabled");
1594
1595 let err = BatchingEngine::ensure_incremental_source_append_only(
1596 &enabled_opts,
1597 &table_name,
1598 &non_append_options,
1599 )
1600 .expect_err("non-append source should be rejected when incremental read is enabled");
1601 assert!(
1602 err.to_string()
1603 .contains("Flow incremental read requires append-only source table"),
1604 "{err}"
1605 );
1606 }
1607
1608 async fn new_test_task(flow_id: FlowId) -> (BatchingTask, oneshot::Sender<()>) {
1609 new_test_task_for_source(flow_id, "numbers_with_ts", None).await
1610 }
1611
1612 async fn new_test_task_with_time_window_expr(
1613 flow_id: FlowId,
1614 time_window_expr: Option<TimeWindowExpr>,
1615 ) -> (BatchingTask, oneshot::Sender<()>) {
1616 new_test_task_for_source(flow_id, "numbers_with_ts", time_window_expr).await
1617 }
1618
1619 fn test_table_info_with_ts_unit(
1620 table_id: TableId,
1621 table_name: &str,
1622 unit: TimeUnit,
1623 ) -> table::metadata::TableInfo {
1624 use datatypes::schema::{ColumnSchema, SchemaBuilder};
1625 use table::metadata::{TableInfoBuilder, TableMetaBuilder};
1626
1627 let ts_type = match unit {
1628 TimeUnit::Second => ConcreteDataType::timestamp_second_datatype(),
1629 TimeUnit::Millisecond => ConcreteDataType::timestamp_millisecond_datatype(),
1630 TimeUnit::Microsecond => ConcreteDataType::timestamp_microsecond_datatype(),
1631 TimeUnit::Nanosecond => ConcreteDataType::timestamp_nanosecond_datatype(),
1632 };
1633 let column_schemas = vec![
1634 ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
1635 ColumnSchema::new("ts", ts_type, false).with_time_index(true),
1636 ];
1637 let schema = SchemaBuilder::try_from(column_schemas)
1638 .unwrap()
1639 .build()
1640 .unwrap();
1641 let meta = TableMetaBuilder::empty()
1642 .schema(Arc::new(schema))
1643 .primary_key_indices(vec![0])
1644 .engine("engine")
1645 .next_column_id(3)
1646 .build()
1647 .unwrap();
1648 TableInfoBuilder::default()
1649 .table_id(table_id)
1650 .table_version(0)
1651 .name(table_name)
1652 .catalog_name("greptime")
1653 .schema_name("public")
1654 .meta(meta)
1655 .build()
1656 .unwrap()
1657 }
1658
1659 async fn test_time_window_expr() -> TimeWindowExpr {
1661 let query_engine = create_test_query_engine();
1662 let ctx = QueryContext::arc();
1663 let plan = sql_to_df_plan(
1664 ctx.clone(),
1665 query_engine.clone(),
1666 "SELECT date_bin(INTERVAL '5 second', ts) AS time_window FROM numbers_with_ts GROUP BY time_window",
1667 true,
1668 )
1669 .await
1670 .unwrap();
1671 let (column_name, time_window_expr, _, df_schema) = find_time_window_expr(
1672 &plan,
1673 query_engine.engine_state().catalog_manager().clone(),
1674 ctx,
1675 )
1676 .await
1677 .unwrap();
1678 TimeWindowExpr::from_expr(
1679 &time_window_expr.unwrap(),
1680 &column_name,
1681 &df_schema,
1682 &query_engine.engine_state().session_state(),
1683 )
1684 .unwrap()
1685 }
1686
1687 async fn new_test_task_for_source(
1688 flow_id: FlowId,
1689 source_table_name: &str,
1690 time_window_expr: Option<TimeWindowExpr>,
1691 ) -> (BatchingTask, oneshot::Sender<()>) {
1692 let query_engine = create_test_query_engine();
1693 let ctx = QueryContext::arc();
1694 let plan = sql_to_df_plan(
1695 ctx.clone(),
1696 query_engine.clone(),
1697 "SELECT number, ts FROM numbers_with_ts",
1698 true,
1699 )
1700 .await
1701 .unwrap();
1702 let (tx, rx) = oneshot::channel();
1703
1704 let task = BatchingTask::try_new(TaskArgs {
1705 flow_id,
1706 query: "SELECT number, ts FROM numbers_with_ts",
1707 plan,
1708 time_window_expr,
1709 expire_after: None,
1710 sink_table_name: [
1711 "greptime".to_string(),
1712 "public".to_string(),
1713 "sink".to_string(),
1714 ],
1715 source_table_names: vec![[
1716 "greptime".to_string(),
1717 "public".to_string(),
1718 source_table_name.to_string(),
1719 ]],
1720 query_ctx: ctx,
1721 catalog_manager: query_engine.engine_state().catalog_manager().clone(),
1722 shutdown_rx: rx,
1723 batch_opts: Arc::new(BatchingModeOptions::default()),
1724 flow_eval_interval: None,
1725 eval_schedule: None,
1726 })
1727 .unwrap();
1728
1729 (task, tx)
1730 }
1731
1732 #[tokio::test]
1733 async fn test_handle_mark_dirty_time_window_with_time_ranges() {
1734 let engine = new_test_engine().await;
1735
1736 let mut table_info = new_test_table_info_with_name(1, "numbers_with_ts");
1739 table_info.catalog_name = "greptime".to_string();
1740 table_info.schema_name = "public".to_string();
1741 engine
1742 .table_meta
1743 .create_table_metadata(
1744 table_info,
1745 TableRouteValue::physical(vec![]),
1746 HashMap::new(),
1747 )
1748 .await
1749 .unwrap();
1750
1751 let (task, shutdown_tx) =
1753 new_test_task_with_time_window_expr(1, Some(test_time_window_expr().await)).await;
1754 let task_identity = task.clone();
1755 engine.runtime.write().await.insert(1, task, shutdown_tx);
1756
1757 engine
1758 .handle_mark_dirty_time_window(DirtyWindowRequests {
1759 requests: vec![DirtyWindowRequest {
1760 table_id: 1,
1761 timestamps: vec![],
1762 time_ranges: vec![
1763 TimeRange {
1765 start_inclusive: 3_000,
1766 end_exclusive: 11_000,
1767 },
1768 TimeRange {
1770 start_inclusive: 5_000,
1771 end_exclusive: 5_000,
1772 },
1773 TimeRange {
1774 start_inclusive: 9_000,
1775 end_exclusive: 4_000,
1776 },
1777 ],
1778 }],
1779 })
1780 .await
1781 .unwrap();
1782
1783 let state = task_identity.state.read().unwrap();
1784 assert_eq!(1, state.dirty_time_windows.len());
1785 assert_eq!(
1786 Duration::from_secs(15),
1787 state.dirty_time_windows.window_size()
1788 );
1789 }
1790
1791 #[tokio::test]
1796 async fn test_handle_mark_dirty_time_window_time_index_units() {
1797 let engine = new_test_engine().await;
1798
1799 let cases = [
1800 (TimeUnit::Second, 1u32, "t_sec", 3i64, 11i64),
1801 (TimeUnit::Millisecond, 2, "t_ms", 3_000, 11_000),
1802 (TimeUnit::Microsecond, 3, "t_us", 3_000_000, 11_000_000),
1803 (
1804 TimeUnit::Nanosecond,
1805 4,
1806 "t_ns",
1807 3_000_000_000,
1808 11_000_000_000,
1809 ),
1810 ];
1811
1812 let mut task_identities = vec![];
1813 let mut requests = vec![];
1814 for (unit, table_id, table_name, start_inclusive, end_exclusive) in cases {
1815 engine
1816 .table_meta
1817 .create_table_metadata(
1818 test_table_info_with_ts_unit(table_id, table_name, unit),
1819 TableRouteValue::physical(vec![]),
1820 HashMap::new(),
1821 )
1822 .await
1823 .unwrap();
1824
1825 let (task, shutdown_tx) = new_test_task_for_source(
1826 table_id as FlowId,
1827 table_name,
1828 Some(test_time_window_expr().await),
1829 )
1830 .await;
1831 task_identities.push((table_id, task.clone()));
1832 engine
1833 .runtime
1834 .write()
1835 .await
1836 .insert(table_id as FlowId, task, shutdown_tx);
1837
1838 requests.push(DirtyWindowRequest {
1839 table_id,
1840 timestamps: vec![],
1841 time_ranges: vec![TimeRange {
1842 start_inclusive,
1843 end_exclusive,
1844 }],
1845 });
1846 }
1847
1848 engine
1849 .handle_mark_dirty_time_window(DirtyWindowRequests { requests })
1850 .await
1851 .unwrap();
1852
1853 for (table_id, task) in task_identities {
1854 let state = task.state.read().unwrap();
1855 assert_eq!(1, state.dirty_time_windows.len(), "table id = {table_id}");
1856 assert_eq!(
1857 Duration::from_secs(15),
1858 state.dirty_time_windows.window_size(),
1859 "table id = {table_id}"
1860 );
1861 }
1862 }
1863
1864 #[tokio::test]
1865 async fn test_handle_mark_dirty_time_window_returns_error_on_alignment_failure() {
1866 let engine = new_test_engine().await;
1867 let table_id = 10;
1868 let table_name = "t_bad_timestamp";
1869
1870 engine
1871 .table_meta
1872 .create_table_metadata(
1873 test_table_info_with_ts_unit(table_id, table_name, TimeUnit::Second),
1874 TableRouteValue::physical(vec![]),
1875 HashMap::new(),
1876 )
1877 .await
1878 .unwrap();
1879
1880 let (task, shutdown_tx) = new_test_task_for_source(
1881 table_id as FlowId,
1882 table_name,
1883 Some(test_time_window_expr().await),
1884 )
1885 .await;
1886 engine
1887 .runtime
1888 .write()
1889 .await
1890 .insert(table_id as FlowId, task, shutdown_tx);
1891
1892 let result = engine
1893 .handle_mark_dirty_time_window(DirtyWindowRequests {
1894 requests: vec![DirtyWindowRequest {
1895 table_id,
1896 timestamps: vec![i64::MAX],
1897 time_ranges: vec![],
1898 }],
1899 })
1900 .await;
1901
1902 assert!(
1903 result.is_err(),
1904 "invalid timestamp alignment should be returned to the caller"
1905 );
1906 }
1907
1908 async fn install_abort_observed_handle(task: &BatchingTask) -> oneshot::Receiver<()> {
1909 let (drop_tx, drop_rx) = oneshot::channel();
1910 let (entered_tx, entered_rx) = oneshot::channel();
1911 let handle = tokio::spawn(async move {
1912 let _guard = DropNotify(Some(drop_tx));
1913 let _ = entered_tx.send(());
1914 std::future::pending::<()>().await;
1915 });
1916 task.state.write().unwrap().task_handle = Some(handle);
1917 tokio::time::timeout(Duration::from_secs(1), entered_rx)
1918 .await
1919 .expect("test task handle should start")
1920 .expect("test task handle should report start");
1921 drop_rx
1922 }
1923
1924 #[tokio::test]
1925 async fn test_notify_flow_shutdown_sends_signal() {
1926 let (tx, rx) = oneshot::channel();
1927
1928 assert!(notify_flow_shutdown(42, Some(tx), "test"));
1929
1930 rx.await.expect("replaced flow should receive shutdown");
1931 }
1932
1933 #[test]
1934 fn test_notify_flow_shutdown_accepts_missing_sender() {
1935 assert!(!notify_flow_shutdown(42, None, "test"));
1936 }
1937
1938 #[tokio::test]
1939 async fn test_abort_flow_task_stops_execution_without_loop_handle() {
1940 let (task, _shutdown_tx) = new_test_task(42).await;
1941 let execution = Arc::new(TestExecution {
1942 manual_calls: Default::default(),
1943 stops: Default::default(),
1944 });
1945 let task = task.with_execution(Some(execution.clone()));
1946
1947 assert!(!abort_flow_task(42, Some(task), "test"));
1948 assert_eq!(execution.stops.load(std::sync::atomic::Ordering::SeqCst), 1);
1949 }
1950
1951 #[tokio::test]
1952 async fn test_abort_flow_task_stops_execution_before_aborting_handle() {
1953 let (task, _shutdown_tx) = new_test_task(42).await;
1954 let execution = Arc::new(TestExecution {
1955 manual_calls: Default::default(),
1956 stops: Default::default(),
1957 });
1958 let task = task.with_execution(Some(execution.clone()));
1959 let drop_rx = install_abort_observed_handle(&task).await;
1960
1961 assert!(abort_flow_task(42, Some(task), "test"));
1962 assert_eq!(execution.stops.load(std::sync::atomic::Ordering::SeqCst), 1);
1963
1964 tokio::time::timeout(Duration::from_secs(1), drop_rx)
1965 .await
1966 .expect("aborted task should be dropped")
1967 .expect("drop notifier should fire");
1968 }
1969
1970 #[tokio::test]
1971 async fn test_remove_flow_inner_aborts_registered_task() {
1972 let engine = new_test_engine().await;
1973 let (task, shutdown_tx) = new_test_task(42).await;
1974 let drop_rx = install_abort_observed_handle(&task).await;
1975
1976 engine.runtime.write().await.insert(42, task, shutdown_tx);
1977
1978 engine.remove_flow_inner(42).await.unwrap();
1979
1980 tokio::time::timeout(Duration::from_secs(1), drop_rx)
1981 .await
1982 .expect("removed task should be dropped")
1983 .expect("drop notifier should fire");
1984 assert!(!engine.flow_exist_inner(42).await);
1985 assert!(!engine.runtime.read().await.shutdown_txs.contains_key(&42));
1986 }
1987
1988 #[tokio::test]
1989 async fn test_or_replace_flow_runtime_replaces_old_handles_and_keeps_new_task() {
1990 let engine = new_test_engine().await;
1991 let (old_task, old_shutdown_tx) = new_test_task(42).await;
1992 let old_task_identity = old_task.clone();
1993 let old_drop_rx = install_abort_observed_handle(&old_task).await;
1994 let (new_task, new_shutdown_tx) = new_test_task(42).await;
1995 let new_task_identity = new_task.clone();
1996
1997 engine
1998 .runtime
1999 .write()
2000 .await
2001 .insert(42, old_task, old_shutdown_tx);
2002 let (replaced_old_task, replaced_old_shutdown_tx) =
2003 engine
2004 .runtime
2005 .write()
2006 .await
2007 .insert(42, new_task, new_shutdown_tx);
2008
2009 let replaced_old_task = replaced_old_task.expect("old task should be returned");
2010 assert!(Arc::ptr_eq(
2011 &replaced_old_task.state,
2012 &old_task_identity.state
2013 ));
2014 assert!(notify_flow_shutdown(
2015 42,
2016 replaced_old_shutdown_tx,
2017 "replaced"
2018 ));
2019 old_task_identity
2020 .state
2021 .write()
2022 .unwrap()
2023 .shutdown_rx
2024 .try_recv()
2025 .expect("old shutdown receiver should receive signal");
2026 assert!(abort_flow_task(42, Some(replaced_old_task), "replaced"));
2027
2028 tokio::time::timeout(Duration::from_secs(1), old_drop_rx)
2029 .await
2030 .expect("replaced task should be dropped")
2031 .expect("drop notifier should fire");
2032
2033 let runtime = engine.runtime.read().await;
2034 assert_eq!(1, runtime.tasks.len());
2035 assert_eq!(1, runtime.shutdown_txs.len());
2036 let registered_task = runtime.tasks.get(&42).expect("new task should remain");
2037 assert!(Arc::ptr_eq(
2038 ®istered_task.state,
2039 &new_task_identity.state
2040 ));
2041 assert!(runtime.shutdown_txs.contains_key(&42));
2042 assert!(matches!(
2043 new_task_identity
2044 .state
2045 .write()
2046 .unwrap()
2047 .shutdown_rx
2048 .try_recv(),
2049 Err(oneshot::error::TryRecvError::Empty)
2050 ));
2051 }
2052
2053 #[tokio::test]
2054 async fn test_rollback_flow_runtime_if_current_removes_matching_task_only() {
2055 let engine = new_test_engine().await;
2056 let (old_task, _old_shutdown_tx) = new_test_task(42).await;
2057 let (current_task, current_shutdown_tx) = new_test_task(42).await;
2058 let current_task_identity = current_task.clone();
2059
2060 engine
2061 .runtime
2062 .write()
2063 .await
2064 .insert(42, current_task, current_shutdown_tx);
2065
2066 engine.rollback_flow_runtime_if_current(42, &old_task).await;
2067
2068 let registered_task = engine.runtime.read().await.tasks.get(&42).cloned().unwrap();
2069 assert!(Arc::ptr_eq(
2070 ®istered_task.state,
2071 ¤t_task_identity.state
2072 ));
2073 assert!(engine.runtime.read().await.shutdown_txs.contains_key(&42));
2074
2075 engine
2076 .rollback_flow_runtime_if_current(42, ¤t_task_identity)
2077 .await;
2078 assert!(!engine.flow_exist_inner(42).await);
2079 assert!(!engine.runtime.read().await.shutdown_txs.contains_key(&42));
2080 }
2081}