Skip to main content

flow/batching_mode/
engine.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Batching mode engine
16
17use 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
64/// Batching mode Engine, responsible for driving all the batching mode tasks
65///
66/// TODO(discord9): determine how to configure refresh rate
67pub struct BatchingEngine {
68    runtime: RwLock<FlowRuntimeRegistry>,
69    /// frontend client for insert request
70    pub(crate) frontend_client: Arc<FrontendClient>,
71    flow_metadata_manager: FlowMetadataManagerRef,
72    table_meta: TableMetadataManagerRef,
73    catalog_manager: CatalogManagerRef,
74    query_engine: QueryEngineRef,
75    /// Batching mode options for control how batching mode query works
76    ///
77    pub(crate) batch_opts: Arc<BatchingModeOptions>,
78}
79
80#[derive(Default)]
81struct FlowRuntimeRegistry {
82    tasks: BTreeMap<FlowId, BatchingTask>,
83    shutdown_txs: BTreeMap<FlowId, oneshot::Sender<()>>,
84}
85
86impl FlowRuntimeRegistry {
87    fn insert(
88        &mut self,
89        flow_id: FlowId,
90        task: BatchingTask,
91        shutdown_tx: oneshot::Sender<()>,
92    ) -> (Option<BatchingTask>, Option<oneshot::Sender<()>>) {
93        (
94            self.tasks.insert(flow_id, task),
95            self.shutdown_txs.insert(flow_id, shutdown_tx),
96        )
97    }
98
99    fn remove(&mut self, flow_id: FlowId) -> Option<(BatchingTask, Option<oneshot::Sender<()>>)> {
100        let task = self.tasks.remove(&flow_id)?;
101        let shutdown_tx = self.shutdown_txs.remove(&flow_id);
102        Some((task, shutdown_tx))
103    }
104
105    fn remove_if_current(
106        &mut self,
107        flow_id: FlowId,
108        task: &BatchingTask,
109    ) -> (Option<BatchingTask>, Option<oneshot::Sender<()>>) {
110        if self
111            .tasks
112            .get(&flow_id)
113            .is_some_and(|current| Arc::ptr_eq(&current.state, &task.state))
114        {
115            let Some((removed_task, removed_shutdown_tx)) = self.remove(flow_id) else {
116                return (None, None);
117            };
118            (Some(removed_task), removed_shutdown_tx)
119        } else {
120            (None, None)
121        }
122    }
123}
124
125impl BatchingEngine {
126    pub fn new(
127        frontend_client: Arc<FrontendClient>,
128        query_engine: QueryEngineRef,
129        flow_metadata_manager: FlowMetadataManagerRef,
130        table_meta: TableMetadataManagerRef,
131        catalog_manager: CatalogManagerRef,
132        batch_opts: BatchingModeOptions,
133    ) -> Self {
134        Self {
135            runtime: Default::default(),
136            frontend_client,
137            flow_metadata_manager,
138            table_meta,
139            catalog_manager,
140            query_engine,
141            batch_opts: Arc::new(batch_opts),
142        }
143    }
144
145    /// Returns last execution timestamps (millisecond) for all batching flows.
146    pub async fn get_last_exec_time_map(&self) -> BTreeMap<FlowId, i64> {
147        let runtime = self.runtime.read().await;
148        runtime
149            .tasks
150            .iter()
151            .filter_map(|(flow_id, task)| {
152                task.last_execution_time_millis()
153                    .map(|timestamp| (*flow_id, timestamp))
154            })
155            .collect()
156    }
157
158    /// Mark dirty time windows for batching flows.
159    ///
160    /// Both `timestamps` and `time_ranges` (`[start_inclusive, end_exclusive)`)
161    /// in each `DirtyWindowRequest` are bare `i64`s interpreted in the source
162    /// table's time index column native unit, resolved via table metadata.
163    pub async fn handle_mark_dirty_time_window(
164        &self,
165        reqs: DirtyWindowRequests,
166    ) -> Result<(), Error> {
167        let table_info_mgr = self.table_meta.table_info_manager();
168
169        let mut group_by_table_id: HashMap<u32, (Vec<i64>, Vec<api::v1::flow::TimeRange>)> =
170            HashMap::new();
171        for r in reqs.requests {
172            let tid = TableId::from(r.table_id);
173            let entry = group_by_table_id.entry(tid).or_default();
174            entry.0.extend(r.timestamps);
175            entry.1.extend(r.time_ranges);
176        }
177        let tids = group_by_table_id.keys().cloned().collect::<Vec<TableId>>();
178        let table_infos =
179            table_info_mgr
180                .batch_get(&tids)
181                .await
182                .with_context(|_| TableNotFoundMetaSnafu {
183                    msg: format!("Failed to get table info for table ids: {:?}", tids),
184                })?;
185
186        let group_by_table_name = group_by_table_id
187            .into_iter()
188            .filter_map(|(id, (timestamps, time_ranges))| {
189                let table_name = table_infos.get(&id).map(|info| info.table_name());
190                let Some(table_name) = table_name else {
191                    warn!("Failed to get table infos for table id: {:?}", id);
192                    return None;
193                };
194                let table_name = [
195                    table_name.catalog_name,
196                    table_name.schema_name,
197                    table_name.table_name,
198                ];
199                let schema = &table_infos.get(&id).unwrap().table_info.meta.schema;
200                let time_index_unit = schema.column_schemas()[schema.timestamp_index().unwrap()]
201                    .data_type
202                    .as_timestamp()
203                    .unwrap()
204                    .unit();
205                Some((table_name, (timestamps, time_ranges, time_index_unit)))
206            })
207            .collect::<HashMap<_, _>>();
208
209        let group_by_table_name = Arc::new(group_by_table_name);
210
211        let tasks = self
212            .runtime
213            .read()
214            .await
215            .tasks
216            .values()
217            .cloned()
218            .collect::<Vec<_>>();
219        let mut handles = Vec::new();
220
221        for task in tasks {
222            let src_table_names = &task.config.source_table_names;
223
224            if src_table_names
225                .iter()
226                .all(|name| !group_by_table_name.contains_key(name))
227            {
228                continue;
229            }
230
231            let group_by_table_name = group_by_table_name.clone();
232            let task = task.clone();
233            let handle: JoinHandle<Result<(), Error>> = tokio::spawn(async move {
234                let src_table_names = &task.config.source_table_names;
235                let mut all_dirty_windows = HashSet::new();
236                let mut all_dirty_ranges = Vec::new();
237                let mut is_dirty = false;
238                for src_table_name in src_table_names {
239                    if let Some((timestamps, time_ranges, unit)) =
240                        group_by_table_name.get(src_table_name)
241                    {
242                        let Some(expr) = &task.config.time_window_expr else {
243                            is_dirty = true;
244                            continue;
245                        };
246                        for timestamp in timestamps {
247                            let align_start = expr
248                                .eval(common_time::Timestamp::new(*timestamp, *unit))?
249                                .0
250                                .context(UnexpectedSnafu {
251                                    reason: format!(
252                                        "Failed to align dirty timestamp {timestamp}: missing window lower bound"
253                                    ),
254                                })?;
255                            all_dirty_windows.insert(align_start);
256                        }
257                        for time_range in time_ranges {
258                            if time_range.end_exclusive <= time_range.start_inclusive {
259                                warn!(
260                                    "Ignoring invalid dirty time range with start_inclusive={} >= end_exclusive={}",
261                                    time_range.start_inclusive, time_range.end_exclusive
262                                );
263                                continue;
264                            }
265                            let (align_start, align_end) = DirtyTimeWindows::align_time_window(
266                                common_time::Timestamp::new(time_range.start_inclusive, *unit),
267                                Some(common_time::Timestamp::new(time_range.end_exclusive, *unit)),
268                                expr,
269                            )?;
270                            all_dirty_ranges.push((align_start, align_end));
271                        }
272                    }
273                }
274                let mut state = task.state.write().unwrap();
275                if is_dirty {
276                    state.dirty_time_windows.set_dirty();
277                }
278                let flow_id_label = task.config.flow_id.to_string();
279                for timestamp in all_dirty_windows {
280                    state.dirty_time_windows.add_window(timestamp, None);
281                }
282                for (start, end) in all_dirty_ranges {
283                    state.dirty_time_windows.add_window(start, end);
284                }
285
286                METRIC_FLOW_BATCHING_ENGINE_BULK_MARK_TIME_WINDOW
287                    .with_label_values(&[&flow_id_label])
288                    .set(state.dirty_time_windows.len() as f64);
289                Ok(())
290            });
291            handles.push(handle);
292        }
293        for handle in handles {
294            handle.await.context(JoinTaskSnafu)??;
295        }
296
297        Ok(())
298    }
299
300    pub async fn handle_inserts_inner(
301        &self,
302        request: api::v1::region::InsertRequests,
303    ) -> Result<(), Error> {
304        let table_info_mgr = self.table_meta.table_info_manager();
305        let mut group_by_table_id: HashMap<TableId, Vec<api::v1::Rows>> = HashMap::new();
306
307        for r in request.requests {
308            let tid = RegionId::from(r.region_id).table_id();
309            let entry = group_by_table_id.entry(tid).or_default();
310            if let Some(rows) = r.rows {
311                entry.push(rows);
312            }
313        }
314
315        let tids = group_by_table_id.keys().cloned().collect::<Vec<TableId>>();
316        let table_infos =
317            table_info_mgr
318                .batch_get(&tids)
319                .await
320                .with_context(|_| TableNotFoundMetaSnafu {
321                    msg: format!("Failed to get table info for table ids: {:?}", tids),
322                })?;
323
324        let missing_tids = tids
325            .iter()
326            .filter(|id| !table_infos.contains_key(id))
327            .collect::<Vec<_>>();
328        if !missing_tids.is_empty() {
329            warn!(
330                "Failed to get all the table info for table ids, expected table ids: {:?}, those table doesn't exist: {:?}",
331                tids, missing_tids
332            );
333        }
334
335        let group_by_table_name = group_by_table_id
336            .into_iter()
337            .filter_map(|(id, rows)| {
338                let table_name = table_infos.get(&id).map(|info| info.table_name());
339                let Some(table_name) = table_name else {
340                    warn!("Failed to get table infos for table id: {:?}", id);
341                    return None;
342                };
343                let table_name = [
344                    table_name.catalog_name,
345                    table_name.schema_name,
346                    table_name.table_name,
347                ];
348                Some((table_name, rows))
349            })
350            .collect::<HashMap<_, _>>();
351
352        let group_by_table_name = Arc::new(group_by_table_name);
353
354        let tasks = self
355            .runtime
356            .read()
357            .await
358            .tasks
359            .values()
360            .cloned()
361            .collect::<Vec<_>>();
362        let mut handles = Vec::new();
363        for task in tasks {
364            let src_table_names = &task.config.source_table_names;
365
366            if src_table_names
367                .iter()
368                .all(|name| !group_by_table_name.contains_key(name))
369            {
370                continue;
371            }
372
373            let group_by_table_name = group_by_table_name.clone();
374            let task = task.clone();
375
376            let handle: JoinHandle<Result<(), Error>> = tokio::spawn(async move {
377                let src_table_names = &task.config.source_table_names;
378
379                let mut is_dirty = false;
380
381                for src_table_name in src_table_names {
382                    if let Some(entry) = group_by_table_name.get(src_table_name) {
383                        let Some(expr) = &task.config.time_window_expr else {
384                            is_dirty = true;
385                            continue;
386                        };
387                        let involved_time_windows = expr.handle_rows(entry.clone()).await?;
388                        let mut state = task.state.write().unwrap();
389                        state
390                            .dirty_time_windows
391                            .add_lower_bounds(involved_time_windows.into_iter());
392                    }
393                }
394                if is_dirty {
395                    task.state.write().unwrap().dirty_time_windows.set_dirty();
396                }
397
398                Ok(())
399            });
400            handles.push(handle);
401        }
402
403        for handle in handles {
404            match handle.await {
405                Err(e) => {
406                    warn!("Failed to handle inserts: {e}");
407                }
408                Ok(Ok(())) => (),
409                Ok(Err(e)) => {
410                    warn!("Failed to handle inserts: {e}");
411                }
412            }
413        }
414        Ok(())
415    }
416}
417
418impl FlowStatProvider for BatchingEngine {
419    async fn flow_stat(&self) -> FlowStat {
420        let runtime = self.runtime.read().await;
421        let mut last_exec_time_map = BTreeMap::new();
422        let mut start_time_map = BTreeMap::new();
423
424        for (flow_id, task) in runtime.tasks.iter() {
425            let id = *flow_id as u32;
426            if let Some(ts) = task.last_execution_time_millis() {
427                last_exec_time_map.insert(id, ts);
428            }
429            if let Some(ts) = task.start_time_millis() {
430                start_time_map.insert(id, ts);
431            }
432        }
433
434        FlowStat {
435            state_size: BTreeMap::new(),
436            last_exec_time_map,
437            start_time_map,
438        }
439    }
440}
441
442async fn get_table_name(
443    table_info: &TableInfoManager,
444    table_id: &TableId,
445) -> Result<TableName, Error> {
446    get_table_info(table_info, table_id).await.map(|info| {
447        let name = info.table_name();
448        [name.catalog_name, name.schema_name, name.table_name]
449    })
450}
451
452async fn get_table_info(
453    table_info: &TableInfoManager,
454    table_id: &TableId,
455) -> Result<TableInfoValue, Error> {
456    table_info
457        .get(*table_id)
458        .await
459        .map_err(BoxedError::new)
460        .context(ExternalSnafu)?
461        .with_context(|| UnexpectedSnafu {
462            reason: format!("Table id = {:?}, couldn't found table name", table_id),
463        })
464        .map(|info| info.into_inner())
465}
466
467impl BatchingEngine {
468    fn batch_opts_for_flow_options(
469        &self,
470        flow_options: &HashMap<String, String>,
471        exact_sequence_range_required: bool,
472    ) -> Result<Arc<BatchingModeOptions>, Error> {
473        let mut batch_opts = (*self.batch_opts).clone();
474        if let Some(enable_incremental_read) =
475            flow_options.get(FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY)
476        {
477            batch_opts.experimental_enable_incremental_read = if exact_sequence_range_required {
478                true
479            } else {
480                enable_incremental_read.parse::<bool>().map_err(|_| {
481                    InvalidQuerySnafu {
482                        reason: format!(
483                            "Invalid flow option {FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY}: {enable_incremental_read}"
484                        ),
485                    }
486                    .build()
487                })?
488            };
489        }
490
491        Ok(Arc::new(batch_opts))
492    }
493
494    fn table_options_enable_append_mode(extra_options: &HashMap<String, String>) -> bool {
495        extra_options
496            .get(APPEND_MODE_KEY)
497            .is_some_and(|value| value.eq_ignore_ascii_case("true"))
498    }
499
500    /// SQL flows without a usable time-window expression can only run as an
501    /// explicit full-query flow, so require `EVAL INTERVAL` at creation time.
502    fn ensure_sql_flow_has_twe_or_eval_interval(
503        eval_interval: Option<i64>,
504        has_time_window_expr: bool,
505    ) -> Result<(), Error> {
506        ensure!(
507            eval_interval.is_some() || has_time_window_expr,
508            InvalidQuerySnafu {
509                reason: "SQL batching flow without a time-window expression must specify EVAL INTERVAL to run as an explicit full-query flow"
510                    .to_string(),
511            }
512        );
513        Ok(())
514    }
515
516    fn ensure_incremental_source_append_only(
517        batch_opts: &BatchingModeOptions,
518        table_name: &[String; 3],
519        extra_options: &HashMap<String, String>,
520    ) -> Result<(), Error> {
521        if batch_opts.experimental_enable_incremental_read {
522            ensure!(
523                Self::table_options_enable_append_mode(extra_options),
524                UnsupportedSnafu {
525                    reason: format!(
526                        "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",
527                        table_name.join(".")
528                    ),
529                }
530            );
531        }
532
533        Ok(())
534    }
535
536    pub async fn create_flow_inner(&self, args: CreateFlowArgs) -> Result<Option<FlowId>, Error> {
537        let CreateFlowArgs {
538            flow_id,
539            sink_table_name,
540            source_table_ids,
541            create_if_not_exists,
542            or_replace,
543            expire_after,
544            eval_interval,
545            comment: _,
546            sql,
547            flow_options,
548            query_ctx,
549            eval_schedule: eval_schedule_config,
550        } = args;
551
552        // or replace logic
553        {
554            let is_exist = self.runtime.read().await.tasks.contains_key(&flow_id);
555            match (create_if_not_exists, or_replace, is_exist) {
556                // if replace, ignore that old flow exists
557                (_, true, true) => {
558                    info!("Replacing flow with id={}", flow_id);
559                }
560                (false, false, true) => FlowAlreadyExistSnafu { id: flow_id }.fail()?,
561                // already exists, and not replace, return None
562                (true, false, true) => {
563                    info!("Flow with id={} already exists, do nothing", flow_id);
564                    return Ok(None);
565                }
566
567                // continue as normal
568                (_, _, false) => (),
569            }
570        }
571
572        let query_ctx = query_ctx.context({
573            UnexpectedSnafu {
574                reason: "Query context is None".to_string(),
575            }
576        })?;
577        let query_ctx = Arc::new(query_ctx);
578        let is_tql = is_tql(query_ctx.sql_dialect(), &sql)
579            .map_err(BoxedError::new)
580            .context(CreateFlowSnafu { sql: &sql })?;
581
582        // optionally set a eval interval for the flow
583        if eval_interval.is_none() && is_tql {
584            InvalidQuerySnafu {
585                reason: "TQL query requires EVAL INTERVAL to be set".to_string(),
586            }
587            .fail()?;
588        }
589
590        let flow_type = flow_options.get(FlowType::FLOW_TYPE_KEY);
591
592        ensure!(
593            match flow_type {
594                None => true,
595                Some(ty) if ty == FlowType::BATCHING => true,
596                _ => false,
597            },
598            UnexpectedSnafu {
599                reason: format!("Flow type is not batching nor None, got {flow_type:?}")
600            }
601        );
602
603        // The meta layer validates this reserved sentinel before it reaches the
604        // flownode. Derive the requirement once and pass it directly to task
605        // config; query-context extensions are irrelevant.
606        let exact_sequence_range_required = flow_options
607            .get(FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY)
608            .is_some_and(|value| value == FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE);
609        let batch_opts =
610            self.batch_opts_for_flow_options(&flow_options, exact_sequence_range_required)?;
611
612        let mut source_table_names = Vec::with_capacity(2);
613        for src_id in source_table_ids {
614            // also check table option to see if ttl!=instant
615            let table_name = get_table_name(self.table_meta.table_info_manager(), &src_id).await?;
616            let table_info = get_table_info(self.table_meta.table_info_manager(), &src_id).await?;
617            ensure!(
618                table_info.table_info.meta.options.ttl != Some(TimeToLive::Instant),
619                UnsupportedSnafu {
620                    reason: format!(
621                        "Source table `{}`(id={}) has instant TTL, Instant TTL is not supported under batching mode. Consider using a TTL longer than flush interval",
622                        table_name.join("."),
623                        src_id
624                    ),
625                }
626            );
627            Self::ensure_incremental_source_append_only(
628                &batch_opts,
629                &table_name,
630                &table_info.table_info.meta.options.extra_options,
631            )?;
632
633            source_table_names.push(table_name);
634        }
635
636        let (tx, rx) = oneshot::channel();
637
638        let plan = sql_to_df_plan(query_ctx.clone(), self.query_engine.clone(), &sql, true).await?;
639
640        if is_tql {
641            self.check_is_tql_table(&plan, &query_ctx).await?;
642        }
643
644        let phy_expr = if !is_tql {
645            let (column_name, time_window_expr, _, df_schema) = find_time_window_expr(
646                &plan,
647                self.query_engine.engine_state().catalog_manager().clone(),
648                query_ctx.clone(),
649            )
650            .await?;
651            time_window_expr
652                .map(|expr| {
653                    TimeWindowExpr::from_expr(
654                        &expr,
655                        &column_name,
656                        &df_schema,
657                        &self.query_engine.engine_state().session_state(),
658                    )
659                })
660                .transpose()?
661        } else {
662            // tql control by `EVAL INTERVAL`, no need to find time window expr
663            None
664        };
665
666        debug!(
667            "Flow id={}, found time window expr={}",
668            flow_id,
669            phy_expr
670                .as_ref()
671                .map(|phy_expr| phy_expr.to_string())
672                .unwrap_or("None".to_string())
673        );
674
675        if !is_tql {
676            Self::ensure_sql_flow_has_twe_or_eval_interval(eval_interval, phy_expr.is_some())?;
677        }
678
679        // Compute typed EvalSchedule from FlowScheduleConfig.
680        let eval_schedule = {
681            let interval = eval_interval;
682            let config = eval_schedule_config.as_ref();
683            match EvalSchedule::from_config(interval, config) {
684                Ok(s) => s,
685                Err(e) => {
686                    return UnexpectedSnafu {
687                        reason: format!(
688                            "Failed to build eval schedule for flow {}: {}",
689                            flow_id, e
690                        ),
691                    }
692                    .fail();
693                }
694            }
695        };
696
697        let task_args = TaskArgs {
698            flow_id,
699            query: &sql,
700            plan,
701            time_window_expr: phy_expr,
702            expire_after,
703            sink_table_name,
704            source_table_names,
705            query_ctx,
706            catalog_manager: self.catalog_manager.clone(),
707            shutdown_rx: rx,
708            batch_opts,
709            flow_eval_interval: eval_interval.map(|secs| Duration::from_secs(secs as u64)),
710            eval_schedule,
711        };
712
713        let task = BatchingTask::try_new_with_exact_sequence_range_required(
714            task_args,
715            exact_sequence_range_required,
716        )?;
717
718        if task.config.exact_sequence_range_required {
719            ensure!(
720                task.sequence_range_capable().await?,
721                UnsupportedSnafu {
722                    reason: format!(
723                        "Flow {flow_id} requires exact sequence-range reads, but a source table lacks the Mito preserve_row_sequence capability"
724                    ),
725                }
726            );
727        }
728
729        let task_inner = task.clone();
730        let engine = self.query_engine.clone();
731        let frontend = self.frontend_client.clone();
732
733        // Create sink table if needed, then validate an existing/created sink schema before
734        // spawning the background task. This catches user-created sink schema mismatches at
735        // CREATE FLOW time instead of surfacing them later in the execution loop.
736        task.check_or_create_sink_table(&engine, &frontend).await?;
737        task.validate_sink_table_schema(&engine).await?;
738
739        let (start_tx, start_rx) = oneshot::channel();
740
741        // TODO(discord9): use time wheel or what for better
742        let handle = common_runtime::spawn_global(async move {
743            if start_rx.await.is_ok() {
744                task_inner.start_executing_loop(engine, frontend).await;
745            }
746        });
747        task.state.write().unwrap().task_handle = Some(handle);
748        let task_for_rollback = task.clone();
749
750        // Only replace here, not earlier, because we want the old one intact if
751        // something went wrong before this line. Keep the task and shutdown
752        // sender in one registry lock so create/remove can't observe one
753        // without the other.
754        let (replaced_old_task_opt, replaced_old_shutdown_tx) = {
755            let mut runtime = self.runtime.write().await;
756
757            let is_exist = runtime.tasks.contains_key(&flow_id);
758            match (create_if_not_exists, or_replace, is_exist) {
759                (_, true, true) => {
760                    info!(
761                        "Replacing flow with id={} after final registry check",
762                        flow_id
763                    );
764                }
765                (false, false, true) => {
766                    abort_flow_task(flow_id, Some(task), "unregistered");
767                    return FlowAlreadyExistSnafu { id: flow_id }.fail();
768                }
769                (true, false, true) => {
770                    info!(
771                        "Flow with id={} already exists at final registry check, do nothing",
772                        flow_id
773                    );
774                    abort_flow_task(flow_id, Some(task), "unregistered");
775                    return Ok(None);
776                }
777                (_, _, false) => (),
778            }
779
780            runtime.insert(flow_id, task, tx)
781        };
782
783        notify_flow_shutdown(flow_id, replaced_old_shutdown_tx, "replaced");
784        abort_flow_task(flow_id, replaced_old_task_opt, "replaced");
785        if start_tx.send(()).is_err() {
786            self.rollback_flow_runtime_if_current(flow_id, &task_for_rollback)
787                .await;
788            UnexpectedSnafu {
789                reason: format!("Failed to start flow {flow_id} due to task already dropped"),
790            }
791            .fail()?;
792        }
793
794        Ok(Some(flow_id))
795    }
796
797    async fn check_is_tql_table(
798        &self,
799        query: &LogicalPlan,
800        query_ctx: &QueryContext,
801    ) -> Result<(), Error> {
802        struct CollectTableRef {
803            table_refs: HashSet<datafusion_common::TableReference>,
804        }
805
806        impl TreeNodeVisitor<'_> for CollectTableRef {
807            type Node = LogicalPlan;
808            fn f_down(
809                &mut self,
810                node: &Self::Node,
811            ) -> datafusion_common::Result<TreeNodeRecursion> {
812                if let LogicalPlan::TableScan(scan) = node {
813                    self.table_refs.insert(scan.table_name.clone());
814                }
815                Ok(TreeNodeRecursion::Continue)
816            }
817        }
818        let mut table_refs = CollectTableRef {
819            table_refs: HashSet::new(),
820        };
821        query
822            .visit_with_subqueries(&mut table_refs)
823            .context(DatafusionSnafu {
824                context: "Checking if all source tables are TQL tables",
825            })?;
826
827        let default_catalog = query_ctx.current_catalog();
828        let default_schema = query_ctx.current_schema();
829        let default_schema = &default_schema;
830
831        for table_ref in table_refs.table_refs {
832            let table_ref = match &table_ref {
833                datafusion_common::TableReference::Bare { table } => {
834                    TableReference::full(default_catalog, default_schema, table)
835                }
836                datafusion_common::TableReference::Partial { schema, table } => {
837                    TableReference::full(default_catalog, schema, table)
838                }
839                datafusion_common::TableReference::Full {
840                    catalog,
841                    schema,
842                    table,
843                } => TableReference::full(catalog, schema, table),
844            };
845
846            let table_id = self
847                .table_meta
848                .table_name_manager()
849                .get(table_ref.into())
850                .await
851                .map_err(BoxedError::new)
852                .context(ExternalSnafu)?
853                .with_context(|| UnexpectedSnafu {
854                    reason: format!("Failed to get table id for table: {}", table_ref),
855                })?
856                .table_id();
857            let table_info =
858                get_table_info(self.table_meta.table_info_manager(), &table_id).await?;
859            // first check if it's only one f64 value column
860            let value_cols = table_info
861                .table_info
862                .meta
863                .schema
864                .column_schemas()
865                .iter()
866                .filter(|col| col.data_type == ConcreteDataType::float64_datatype())
867                .collect::<Vec<_>>();
868            ensure!(
869                value_cols.len() == 1,
870                InvalidQuerySnafu {
871                    reason: format!(
872                        "TQL query only supports one f64 value column, table `{}`(id={}) has {} f64 value columns, columns are: {:?}",
873                        table_ref,
874                        table_id,
875                        value_cols.len(),
876                        value_cols
877                    ),
878                }
879            );
880            // TODO(discord9): do need to check rest columns is string and is tag column?
881            let pk_idxs = table_info
882                .table_info
883                .meta
884                .primary_key_indices
885                .iter()
886                .collect::<HashSet<_>>();
887
888            for (idx, col) in table_info
889                .table_info
890                .meta
891                .schema
892                .column_schemas()
893                .iter()
894                .enumerate()
895            {
896                if is_metric_engine_internal_column(&col.name) {
897                    continue;
898                }
899                // three cases:
900                // 1. val column
901                // 2. timestamp column
902                // 3. tag column (string)
903
904                let is_pk: bool = pk_idxs.contains(&&idx);
905
906                ensure!(
907                    col.data_type == ConcreteDataType::float64_datatype()
908                        || col.data_type.is_timestamp()
909                        || (col.data_type == ConcreteDataType::string_datatype() && is_pk),
910                    InvalidQuerySnafu {
911                        reason: format!(
912                            "TQL query only supports f64 value column, timestamp column and string tag columns, table `{}`(id={}) has column `{}` with type {:?} which is not supported",
913                            table_ref, table_id, col.name, col.data_type
914                        ),
915                    }
916                );
917            }
918        }
919        Ok(())
920    }
921
922    pub async fn remove_flow_inner(&self, flow_id: FlowId) -> Result<(), Error> {
923        let (task, shutdown_tx) = {
924            let mut runtime = self.runtime.write().await;
925            let Some((task, shutdown_tx)) = runtime.remove(flow_id) else {
926                warn!("Flow {flow_id} not found in tasks");
927                FlowNotFoundSnafu { id: flow_id }.fail()?
928            };
929            (task, shutdown_tx)
930        };
931
932        let had_shutdown_tx = notify_flow_shutdown(flow_id, shutdown_tx, "removed");
933        abort_flow_task(flow_id, Some(task), "removed");
934
935        if !had_shutdown_tx {
936            UnexpectedSnafu {
937                reason: format!("Can't found shutdown tx for flow {flow_id}"),
938            }
939            .fail()?
940        }
941
942        Ok(())
943    }
944
945    /// Only flush the dirty windows of the flow task with given flow id, by running the query on it.
946    /// As flush the whole time range is usually prohibitively expensive.
947    pub async fn flush_flow_inner(&self, flow_id: FlowId) -> Result<usize, Error> {
948        debug!("Try flush flow {flow_id}");
949        // need to wait a bit to ensure previous mirror insert is handled
950        // this is only useful for the case when we are flushing the flow right after inserting data into it
951        // TODO(discord9): find a better way to ensure the data is ready, maybe inform flownode from frontend?
952        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
953        let task = self.runtime.read().await.tasks.get(&flow_id).cloned();
954        let task = task.with_context(|| FlowNotFoundSnafu { id: flow_id })?;
955
956        let time_window_size = task
957            .config
958            .time_window_expr
959            .as_ref()
960            .and_then(|expr| *expr.time_window_size());
961
962        let cur_dirty_window_cnt = time_window_size.map(|time_window_size| {
963            task.state
964                .read()
965                .unwrap()
966                .dirty_time_windows
967                .effective_count(&time_window_size)
968        });
969
970        let res = task
971            .execute_once_serialized(
972                &self.query_engine,
973                &self.frontend_client,
974                cur_dirty_window_cnt,
975            )
976            .await?;
977
978        let affected_rows = res.map(|(r, _)| r).unwrap_or_default();
979        debug!(
980            "Successfully flush flow {flow_id}, affected rows={}",
981            affected_rows
982        );
983        Ok(affected_rows)
984    }
985
986    /// Determine if the batching mode flow task exists with given flow id
987    pub async fn flow_exist_inner(&self, flow_id: FlowId) -> bool {
988        self.runtime.read().await.tasks.contains_key(&flow_id)
989    }
990
991    async fn rollback_flow_runtime_if_current(&self, flow_id: FlowId, task: &BatchingTask) {
992        let (removed_task, removed_shutdown_tx) = {
993            let mut runtime = self.runtime.write().await;
994            runtime.remove_if_current(flow_id, task)
995        };
996
997        notify_flow_shutdown(flow_id, removed_shutdown_tx, "rolled back");
998        abort_flow_task(flow_id, removed_task, "rolled back");
999    }
1000}
1001
1002fn notify_flow_shutdown(flow_id: FlowId, tx: Option<oneshot::Sender<()>>, action: &str) -> bool {
1003    let Some(tx) = tx else {
1004        return false;
1005    };
1006
1007    if tx.send(()).is_err() {
1008        warn!(
1009            "Fail to shutdown {action} flow {flow_id} due to receiver already dropped, maybe flow {flow_id} is already dropped?"
1010        );
1011    }
1012
1013    true
1014}
1015
1016fn abort_flow_task(flow_id: FlowId, task: Option<BatchingTask>, action: &str) -> bool {
1017    let Some(task) = task else {
1018        return false;
1019    };
1020
1021    if let Some(handle) = task.state.write().unwrap().task_handle.take() {
1022        handle.abort();
1023        debug!("Aborted {action} flow task {flow_id}");
1024        return true;
1025    }
1026
1027    false
1028}
1029
1030impl FlowEngine for BatchingEngine {
1031    async fn create_flow(&self, args: CreateFlowArgs) -> Result<Option<FlowId>, Error> {
1032        self.create_flow_inner(args).await
1033    }
1034    async fn remove_flow(&self, flow_id: FlowId) -> Result<(), Error> {
1035        self.remove_flow_inner(flow_id).await
1036    }
1037    async fn flush_flow(&self, flow_id: FlowId) -> Result<usize, Error> {
1038        self.flush_flow_inner(flow_id).await
1039    }
1040    async fn flow_exist(&self, flow_id: FlowId) -> Result<bool, Error> {
1041        Ok(self.flow_exist_inner(flow_id).await)
1042    }
1043    async fn list_flows(&self) -> Result<impl IntoIterator<Item = FlowId>, Error> {
1044        Ok(self
1045            .runtime
1046            .read()
1047            .await
1048            .tasks
1049            .keys()
1050            .cloned()
1051            .collect::<Vec<_>>())
1052    }
1053    async fn handle_flow_inserts(
1054        &self,
1055        request: api::v1::region::InsertRequests,
1056    ) -> Result<(), Error> {
1057        self.handle_inserts_inner(request).await
1058    }
1059    async fn handle_mark_window_dirty(
1060        &self,
1061        req: api::v1::flow::DirtyWindowRequests,
1062    ) -> Result<(), Error> {
1063        self.handle_mark_dirty_time_window(req).await
1064    }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069    use api::v1::flow::{DirtyWindowRequest, TimeRange};
1070    use catalog::memory::new_memory_catalog_manager;
1071    use common_meta::key::TableMetadataManager;
1072    use common_meta::key::flow::FlowMetadataManager;
1073    use common_meta::key::table_route::TableRouteValue;
1074    use common_meta::key::test_utils::new_test_table_info_with_name;
1075    use common_meta::kv_backend::memory::MemoryKvBackend;
1076    use common_time::timestamp::TimeUnit;
1077    use query::options::QueryOptions;
1078    use session::context::QueryContext;
1079
1080    use super::*;
1081    use crate::test_utils::create_test_query_engine;
1082
1083    struct DropNotify(Option<oneshot::Sender<()>>);
1084
1085    impl Drop for DropNotify {
1086        fn drop(&mut self) {
1087            if let Some(tx) = self.0.take() {
1088                let _ = tx.send(());
1089            }
1090        }
1091    }
1092
1093    async fn new_test_engine() -> BatchingEngine {
1094        let kv_backend = Arc::new(MemoryKvBackend::new());
1095        let table_meta = Arc::new(TableMetadataManager::new(kv_backend.clone()));
1096        table_meta.init().await.unwrap();
1097        let flow_meta = Arc::new(FlowMetadataManager::new(kv_backend));
1098        let catalog_manager = new_memory_catalog_manager().unwrap();
1099        let query_engine = create_test_query_engine();
1100        let (frontend_client, _handler) =
1101            FrontendClient::from_empty_grpc_handler(QueryOptions::default());
1102
1103        BatchingEngine::new(
1104            Arc::new(frontend_client),
1105            query_engine,
1106            flow_meta,
1107            table_meta,
1108            catalog_manager,
1109            BatchingModeOptions::default(),
1110        )
1111    }
1112
1113    #[tokio::test]
1114    async fn test_flow_option_overrides_incremental_read_switch() {
1115        let engine = new_test_engine().await;
1116
1117        let default_opts = engine
1118            .batch_opts_for_flow_options(&HashMap::new(), false)
1119            .unwrap();
1120        assert!(!default_opts.experimental_enable_incremental_read);
1121
1122        let enabled_opts = engine
1123            .batch_opts_for_flow_options(
1124                &HashMap::from([(
1125                    FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY.to_string(),
1126                    "true".to_string(),
1127                )]),
1128                false,
1129            )
1130            .unwrap();
1131        assert!(enabled_opts.experimental_enable_incremental_read);
1132
1133        let exact_opts = engine
1134            .batch_opts_for_flow_options(
1135                &HashMap::from([(
1136                    FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY.to_string(),
1137                    FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE.to_string(),
1138                )]),
1139                true,
1140            )
1141            .unwrap();
1142        assert!(exact_opts.experimental_enable_incremental_read);
1143    }
1144
1145    #[test]
1146    fn test_table_options_enable_append_mode() {
1147        assert!(!BatchingEngine::table_options_enable_append_mode(
1148            &HashMap::new()
1149        ));
1150        assert!(!BatchingEngine::table_options_enable_append_mode(
1151            &HashMap::from([(APPEND_MODE_KEY.to_string(), "false".to_string())])
1152        ));
1153        assert!(BatchingEngine::table_options_enable_append_mode(
1154            &HashMap::from([(APPEND_MODE_KEY.to_string(), "TRUE".to_string())])
1155        ));
1156    }
1157
1158    #[test]
1159    fn test_sql_flow_requires_time_window_or_eval_interval() {
1160        BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(None, true)
1161            .expect("SQL flow with a time-window expression should be accepted");
1162        BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(Some(10), false).expect(
1163            "SQL flow with EVAL INTERVAL should be accepted as an explicit full-query flow",
1164        );
1165
1166        let err = BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(None, false)
1167            .expect_err("SQL flow without a time-window expression or EVAL INTERVAL should fail");
1168        assert!(matches!(err, Error::InvalidQuery { .. }), "{err}");
1169        assert!(
1170            err.to_string().contains("must specify EVAL INTERVAL"),
1171            "{err}"
1172        );
1173    }
1174
1175    #[tokio::test]
1176    async fn test_complex_sql_without_eval_interval_is_rejected_as_no_twe() {
1177        let query_engine = create_test_query_engine();
1178        let ctx = QueryContext::arc();
1179        let plan = sql_to_df_plan(
1180            ctx.clone(),
1181            query_engine.clone(),
1182            r#"
1183SELECT
1184    l.number,
1185    date_bin('5 minutes', l.ts) AS time_window
1186FROM numbers_with_ts l
1187JOIN numbers_with_ts r ON l.number = r.number
1188GROUP BY l.number, time_window
1189"#,
1190            true,
1191        )
1192        .await
1193        .unwrap();
1194
1195        let (_, time_window_expr, _, _) = find_time_window_expr(
1196            &plan,
1197            query_engine.engine_state().catalog_manager().clone(),
1198            ctx,
1199        )
1200        .await
1201        .unwrap();
1202        assert!(
1203            time_window_expr.is_none(),
1204            "complex SQL should be classified as having no safe TWE"
1205        );
1206
1207        BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(Some(10), false)
1208            .expect("complex SQL can run as an explicit full-query flow when EVAL INTERVAL is set");
1209        let err = BatchingEngine::ensure_sql_flow_has_twe_or_eval_interval(None, false)
1210            .expect_err("complex SQL without EVAL INTERVAL should fail creation");
1211        assert!(matches!(err, Error::InvalidQuery { .. }), "{err}");
1212    }
1213
1214    #[test]
1215    fn test_incremental_source_append_only_enforcement() {
1216        let table_name = [
1217            "greptime".to_string(),
1218            "public".to_string(),
1219            "numbers".to_string(),
1220        ];
1221        let disabled_opts = BatchingModeOptions::default();
1222        let enabled_opts = BatchingModeOptions {
1223            experimental_enable_incremental_read: true,
1224            ..Default::default()
1225        };
1226        let non_append_options = HashMap::new();
1227        let append_options = HashMap::from([(APPEND_MODE_KEY.to_string(), "true".to_string())]);
1228
1229        BatchingEngine::ensure_incremental_source_append_only(
1230            &disabled_opts,
1231            &table_name,
1232            &non_append_options,
1233        )
1234        .expect("disabled incremental read should not require append-only source");
1235        BatchingEngine::ensure_incremental_source_append_only(
1236            &enabled_opts,
1237            &table_name,
1238            &append_options,
1239        )
1240        .expect("append-only source should be accepted when incremental read is enabled");
1241
1242        let err = BatchingEngine::ensure_incremental_source_append_only(
1243            &enabled_opts,
1244            &table_name,
1245            &non_append_options,
1246        )
1247        .expect_err("non-append source should be rejected when incremental read is enabled");
1248        assert!(
1249            err.to_string()
1250                .contains("Flow incremental read requires append-only source table"),
1251            "{err}"
1252        );
1253    }
1254
1255    async fn new_test_task(flow_id: FlowId) -> (BatchingTask, oneshot::Sender<()>) {
1256        new_test_task_for_source(flow_id, "numbers_with_ts", None).await
1257    }
1258
1259    async fn new_test_task_with_time_window_expr(
1260        flow_id: FlowId,
1261        time_window_expr: Option<TimeWindowExpr>,
1262    ) -> (BatchingTask, oneshot::Sender<()>) {
1263        new_test_task_for_source(flow_id, "numbers_with_ts", time_window_expr).await
1264    }
1265
1266    fn test_table_info_with_ts_unit(
1267        table_id: TableId,
1268        table_name: &str,
1269        unit: TimeUnit,
1270    ) -> table::metadata::TableInfo {
1271        use datatypes::schema::{ColumnSchema, SchemaBuilder};
1272        use table::metadata::{TableInfoBuilder, TableMetaBuilder};
1273
1274        let ts_type = match unit {
1275            TimeUnit::Second => ConcreteDataType::timestamp_second_datatype(),
1276            TimeUnit::Millisecond => ConcreteDataType::timestamp_millisecond_datatype(),
1277            TimeUnit::Microsecond => ConcreteDataType::timestamp_microsecond_datatype(),
1278            TimeUnit::Nanosecond => ConcreteDataType::timestamp_nanosecond_datatype(),
1279        };
1280        let column_schemas = vec![
1281            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
1282            ColumnSchema::new("ts", ts_type, false).with_time_index(true),
1283        ];
1284        let schema = SchemaBuilder::try_from(column_schemas)
1285            .unwrap()
1286            .build()
1287            .unwrap();
1288        let meta = TableMetaBuilder::empty()
1289            .schema(Arc::new(schema))
1290            .primary_key_indices(vec![0])
1291            .engine("engine")
1292            .next_column_id(3)
1293            .build()
1294            .unwrap();
1295        TableInfoBuilder::default()
1296            .table_id(table_id)
1297            .table_version(0)
1298            .name(table_name)
1299            .catalog_name("greptime")
1300            .schema_name("public")
1301            .meta(meta)
1302            .build()
1303            .unwrap()
1304    }
1305
1306    /// A 5-second `date_bin` time window expr over the test table's `ts` column.
1307    async fn test_time_window_expr() -> TimeWindowExpr {
1308        let query_engine = create_test_query_engine();
1309        let ctx = QueryContext::arc();
1310        let plan = sql_to_df_plan(
1311            ctx.clone(),
1312            query_engine.clone(),
1313            "SELECT date_bin(INTERVAL '5 second', ts) AS time_window FROM numbers_with_ts GROUP BY time_window",
1314            true,
1315        )
1316        .await
1317        .unwrap();
1318        let (column_name, time_window_expr, _, df_schema) = find_time_window_expr(
1319            &plan,
1320            query_engine.engine_state().catalog_manager().clone(),
1321            ctx,
1322        )
1323        .await
1324        .unwrap();
1325        TimeWindowExpr::from_expr(
1326            &time_window_expr.unwrap(),
1327            &column_name,
1328            &df_schema,
1329            &query_engine.engine_state().session_state(),
1330        )
1331        .unwrap()
1332    }
1333
1334    async fn new_test_task_for_source(
1335        flow_id: FlowId,
1336        source_table_name: &str,
1337        time_window_expr: Option<TimeWindowExpr>,
1338    ) -> (BatchingTask, oneshot::Sender<()>) {
1339        let query_engine = create_test_query_engine();
1340        let ctx = QueryContext::arc();
1341        let plan = sql_to_df_plan(
1342            ctx.clone(),
1343            query_engine.clone(),
1344            "SELECT number, ts FROM numbers_with_ts",
1345            true,
1346        )
1347        .await
1348        .unwrap();
1349        let (tx, rx) = oneshot::channel();
1350
1351        let task = BatchingTask::try_new(TaskArgs {
1352            flow_id,
1353            query: "SELECT number, ts FROM numbers_with_ts",
1354            plan,
1355            time_window_expr,
1356            expire_after: None,
1357            sink_table_name: [
1358                "greptime".to_string(),
1359                "public".to_string(),
1360                "sink".to_string(),
1361            ],
1362            source_table_names: vec![[
1363                "greptime".to_string(),
1364                "public".to_string(),
1365                source_table_name.to_string(),
1366            ]],
1367            query_ctx: ctx,
1368            catalog_manager: query_engine.engine_state().catalog_manager().clone(),
1369            shutdown_rx: rx,
1370            batch_opts: Arc::new(BatchingModeOptions::default()),
1371            flow_eval_interval: None,
1372            eval_schedule: None,
1373        })
1374        .unwrap();
1375
1376        (task, tx)
1377    }
1378
1379    #[tokio::test]
1380    async fn test_handle_mark_dirty_time_window_with_time_ranges() {
1381        let engine = new_test_engine().await;
1382
1383        // Register the source table info so the engine can resolve the table
1384        // name and the time index unit (millisecond).
1385        let mut table_info = new_test_table_info_with_name(1, "numbers_with_ts");
1386        table_info.catalog_name = "greptime".to_string();
1387        table_info.schema_name = "public".to_string();
1388        engine
1389            .table_meta
1390            .create_table_metadata(
1391                table_info,
1392                TableRouteValue::physical(vec![]),
1393                HashMap::new(),
1394            )
1395            .await
1396            .unwrap();
1397
1398        // Build a task with a 5-second time window expr.
1399        let (task, shutdown_tx) =
1400            new_test_task_with_time_window_expr(1, Some(test_time_window_expr().await)).await;
1401        let task_identity = task.clone();
1402        engine.runtime.write().await.insert(1, task, shutdown_tx);
1403
1404        engine
1405            .handle_mark_dirty_time_window(DirtyWindowRequests {
1406                requests: vec![DirtyWindowRequest {
1407                    table_id: 1,
1408                    timestamps: vec![],
1409                    time_ranges: vec![
1410                        // [3s, 11s) aligns to window start 0s and window end 15s.
1411                        TimeRange {
1412                            start_inclusive: 3_000,
1413                            end_exclusive: 11_000,
1414                        },
1415                        // Empty and reversed ranges are invalid and skipped.
1416                        TimeRange {
1417                            start_inclusive: 5_000,
1418                            end_exclusive: 5_000,
1419                        },
1420                        TimeRange {
1421                            start_inclusive: 9_000,
1422                            end_exclusive: 4_000,
1423                        },
1424                    ],
1425                }],
1426            })
1427            .await
1428            .unwrap();
1429
1430        let state = task_identity.state.read().unwrap();
1431        assert_eq!(1, state.dirty_time_windows.len());
1432        assert_eq!(
1433            Duration::from_secs(15),
1434            state.dirty_time_windows.window_size()
1435        );
1436    }
1437
1438    /// Dirty timestamps and time ranges are interpreted in the source table's
1439    /// time index native unit. The same physical range [3s, 11s) expressed in
1440    /// second/millisecond/microsecond/nanosecond units must align to the same
1441    /// dirty window [0s, 15s).
1442    #[tokio::test]
1443    async fn test_handle_mark_dirty_time_window_time_index_units() {
1444        let engine = new_test_engine().await;
1445
1446        let cases = [
1447            (TimeUnit::Second, 1u32, "t_sec", 3i64, 11i64),
1448            (TimeUnit::Millisecond, 2, "t_ms", 3_000, 11_000),
1449            (TimeUnit::Microsecond, 3, "t_us", 3_000_000, 11_000_000),
1450            (
1451                TimeUnit::Nanosecond,
1452                4,
1453                "t_ns",
1454                3_000_000_000,
1455                11_000_000_000,
1456            ),
1457        ];
1458
1459        let mut task_identities = vec![];
1460        let mut requests = vec![];
1461        for (unit, table_id, table_name, start_inclusive, end_exclusive) in cases {
1462            engine
1463                .table_meta
1464                .create_table_metadata(
1465                    test_table_info_with_ts_unit(table_id, table_name, unit),
1466                    TableRouteValue::physical(vec![]),
1467                    HashMap::new(),
1468                )
1469                .await
1470                .unwrap();
1471
1472            let (task, shutdown_tx) = new_test_task_for_source(
1473                table_id as FlowId,
1474                table_name,
1475                Some(test_time_window_expr().await),
1476            )
1477            .await;
1478            task_identities.push((table_id, task.clone()));
1479            engine
1480                .runtime
1481                .write()
1482                .await
1483                .insert(table_id as FlowId, task, shutdown_tx);
1484
1485            requests.push(DirtyWindowRequest {
1486                table_id,
1487                timestamps: vec![],
1488                time_ranges: vec![TimeRange {
1489                    start_inclusive,
1490                    end_exclusive,
1491                }],
1492            });
1493        }
1494
1495        engine
1496            .handle_mark_dirty_time_window(DirtyWindowRequests { requests })
1497            .await
1498            .unwrap();
1499
1500        for (table_id, task) in task_identities {
1501            let state = task.state.read().unwrap();
1502            assert_eq!(1, state.dirty_time_windows.len(), "table id = {table_id}");
1503            assert_eq!(
1504                Duration::from_secs(15),
1505                state.dirty_time_windows.window_size(),
1506                "table id = {table_id}"
1507            );
1508        }
1509    }
1510
1511    #[tokio::test]
1512    async fn test_handle_mark_dirty_time_window_returns_error_on_alignment_failure() {
1513        let engine = new_test_engine().await;
1514        let table_id = 10;
1515        let table_name = "t_bad_timestamp";
1516
1517        engine
1518            .table_meta
1519            .create_table_metadata(
1520                test_table_info_with_ts_unit(table_id, table_name, TimeUnit::Second),
1521                TableRouteValue::physical(vec![]),
1522                HashMap::new(),
1523            )
1524            .await
1525            .unwrap();
1526
1527        let (task, shutdown_tx) = new_test_task_for_source(
1528            table_id as FlowId,
1529            table_name,
1530            Some(test_time_window_expr().await),
1531        )
1532        .await;
1533        engine
1534            .runtime
1535            .write()
1536            .await
1537            .insert(table_id as FlowId, task, shutdown_tx);
1538
1539        let result = engine
1540            .handle_mark_dirty_time_window(DirtyWindowRequests {
1541                requests: vec![DirtyWindowRequest {
1542                    table_id,
1543                    timestamps: vec![i64::MAX],
1544                    time_ranges: vec![],
1545                }],
1546            })
1547            .await;
1548
1549        assert!(
1550            result.is_err(),
1551            "invalid timestamp alignment should be returned to the caller"
1552        );
1553    }
1554
1555    async fn install_abort_observed_handle(task: &BatchingTask) -> oneshot::Receiver<()> {
1556        let (drop_tx, drop_rx) = oneshot::channel();
1557        let (entered_tx, entered_rx) = oneshot::channel();
1558        let handle = tokio::spawn(async move {
1559            let _guard = DropNotify(Some(drop_tx));
1560            let _ = entered_tx.send(());
1561            std::future::pending::<()>().await;
1562        });
1563        task.state.write().unwrap().task_handle = Some(handle);
1564        tokio::time::timeout(Duration::from_secs(1), entered_rx)
1565            .await
1566            .expect("test task handle should start")
1567            .expect("test task handle should report start");
1568        drop_rx
1569    }
1570
1571    #[tokio::test]
1572    async fn test_notify_flow_shutdown_sends_signal() {
1573        let (tx, rx) = oneshot::channel();
1574
1575        assert!(notify_flow_shutdown(42, Some(tx), "test"));
1576
1577        rx.await.expect("replaced flow should receive shutdown");
1578    }
1579
1580    #[test]
1581    fn test_notify_flow_shutdown_accepts_missing_sender() {
1582        assert!(!notify_flow_shutdown(42, None, "test"));
1583    }
1584
1585    #[tokio::test]
1586    async fn test_abort_flow_task_aborts_handle() {
1587        let (task, _shutdown_tx) = new_test_task(42).await;
1588        let drop_rx = install_abort_observed_handle(&task).await;
1589
1590        assert!(abort_flow_task(42, Some(task), "test"));
1591
1592        tokio::time::timeout(Duration::from_secs(1), drop_rx)
1593            .await
1594            .expect("aborted task should be dropped")
1595            .expect("drop notifier should fire");
1596    }
1597
1598    #[tokio::test]
1599    async fn test_remove_flow_inner_aborts_registered_task() {
1600        let engine = new_test_engine().await;
1601        let (task, shutdown_tx) = new_test_task(42).await;
1602        let drop_rx = install_abort_observed_handle(&task).await;
1603
1604        engine.runtime.write().await.insert(42, task, shutdown_tx);
1605
1606        engine.remove_flow_inner(42).await.unwrap();
1607
1608        tokio::time::timeout(Duration::from_secs(1), drop_rx)
1609            .await
1610            .expect("removed task should be dropped")
1611            .expect("drop notifier should fire");
1612        assert!(!engine.flow_exist_inner(42).await);
1613        assert!(!engine.runtime.read().await.shutdown_txs.contains_key(&42));
1614    }
1615
1616    #[tokio::test]
1617    async fn test_or_replace_flow_runtime_replaces_old_handles_and_keeps_new_task() {
1618        let engine = new_test_engine().await;
1619        let (old_task, old_shutdown_tx) = new_test_task(42).await;
1620        let old_task_identity = old_task.clone();
1621        let old_drop_rx = install_abort_observed_handle(&old_task).await;
1622        let (new_task, new_shutdown_tx) = new_test_task(42).await;
1623        let new_task_identity = new_task.clone();
1624
1625        engine
1626            .runtime
1627            .write()
1628            .await
1629            .insert(42, old_task, old_shutdown_tx);
1630        let (replaced_old_task, replaced_old_shutdown_tx) =
1631            engine
1632                .runtime
1633                .write()
1634                .await
1635                .insert(42, new_task, new_shutdown_tx);
1636
1637        let replaced_old_task = replaced_old_task.expect("old task should be returned");
1638        assert!(Arc::ptr_eq(
1639            &replaced_old_task.state,
1640            &old_task_identity.state
1641        ));
1642        assert!(notify_flow_shutdown(
1643            42,
1644            replaced_old_shutdown_tx,
1645            "replaced"
1646        ));
1647        old_task_identity
1648            .state
1649            .write()
1650            .unwrap()
1651            .shutdown_rx
1652            .try_recv()
1653            .expect("old shutdown receiver should receive signal");
1654        assert!(abort_flow_task(42, Some(replaced_old_task), "replaced"));
1655
1656        tokio::time::timeout(Duration::from_secs(1), old_drop_rx)
1657            .await
1658            .expect("replaced task should be dropped")
1659            .expect("drop notifier should fire");
1660
1661        let runtime = engine.runtime.read().await;
1662        assert_eq!(1, runtime.tasks.len());
1663        assert_eq!(1, runtime.shutdown_txs.len());
1664        let registered_task = runtime.tasks.get(&42).expect("new task should remain");
1665        assert!(Arc::ptr_eq(
1666            &registered_task.state,
1667            &new_task_identity.state
1668        ));
1669        assert!(runtime.shutdown_txs.contains_key(&42));
1670        assert!(matches!(
1671            new_task_identity
1672                .state
1673                .write()
1674                .unwrap()
1675                .shutdown_rx
1676                .try_recv(),
1677            Err(oneshot::error::TryRecvError::Empty)
1678        ));
1679    }
1680
1681    #[tokio::test]
1682    async fn test_rollback_flow_runtime_if_current_removes_matching_task_only() {
1683        let engine = new_test_engine().await;
1684        let (old_task, _old_shutdown_tx) = new_test_task(42).await;
1685        let (current_task, current_shutdown_tx) = new_test_task(42).await;
1686        let current_task_identity = current_task.clone();
1687
1688        engine
1689            .runtime
1690            .write()
1691            .await
1692            .insert(42, current_task, current_shutdown_tx);
1693
1694        engine.rollback_flow_runtime_if_current(42, &old_task).await;
1695
1696        let registered_task = engine.runtime.read().await.tasks.get(&42).cloned().unwrap();
1697        assert!(Arc::ptr_eq(
1698            &registered_task.state,
1699            &current_task_identity.state
1700        ));
1701        assert!(engine.runtime.read().await.shutdown_txs.contains_key(&42));
1702
1703        engine
1704            .rollback_flow_runtime_if_current(42, &current_task_identity)
1705            .await;
1706        assert!(!engine.flow_exist_inner(42).await);
1707        assert!(!engine.runtime.read().await.shutdown_txs.contains_key(&42));
1708    }
1709}