mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
feat(flow): support incremental source reads for simple SQL flows
Window-less single-source SQL flows with a row-local projection/filter currently rescan all history on every evaluation interval. Add an opt-in path that reads only the source delta since the last checkpoint, keeping the existing batching scheduler, sequence-range scan capability and checkpoint watermark proof. Eligibility is decided on the plan a round actually executes: the retained plan is now built without the flow optimizer, because constant folding would turn a time-dependent expression such as `now()` into a literal and hide it from the predicate. The delta path reuses the existing (checkpoint, scan-open snapshot] sequence range. It fails closed: a row-local delta flow that cannot build incremental extensions restores its dirty signal instead of running an unfiltered scan, a source without `preserve_row_sequence` is a hard error rather than falling back to memtable-only reads, and an append-mode sink is rejected because a restarted flow replays a full snapshot. Auto-created sinks derive their time index and primary keys from source column lineage, so rows of different entities that share a timestamp no longer collapse into one. The sink remains a keyed materialization: it does not promise to preserve every original source write. Everything is gated on `experimental_enable_incremental_read`, so flows that do not opt in keep their existing behavior and sink layout. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
@@ -72,7 +72,7 @@ pub(crate) mod util;
|
||||
/// Converts a retained plan's output to logical schemas. Only a direct source
|
||||
/// column (optionally wrapped in an alias) carries source semantics; computed
|
||||
/// expressions deliberately use the physical output field metadata instead.
|
||||
fn output_column_schemas(
|
||||
pub(crate) fn output_column_schemas(
|
||||
plan: &LogicalPlan,
|
||||
source_schema: &SchemaRef,
|
||||
) -> Result<(Vec<ColumnSchema>, Vec<Option<usize>>), Error> {
|
||||
|
||||
@@ -25,6 +25,7 @@ pub(crate) mod checkpoint;
|
||||
pub(crate) mod engine;
|
||||
mod eval_schedule;
|
||||
pub(crate) mod frontend_client;
|
||||
pub(crate) mod simple_delta;
|
||||
pub(crate) mod state;
|
||||
mod table_creator;
|
||||
pub(crate) mod task;
|
||||
|
||||
@@ -43,6 +43,7 @@ use sql::parsers::utils::is_tql;
|
||||
use store_api::metric_engine_consts::is_metric_engine_internal_column;
|
||||
use store_api::mito_engine_options::APPEND_MODE_KEY;
|
||||
use store_api::storage::{RegionId, TableId};
|
||||
use table::TableRef;
|
||||
use table::table_reference::TableReference;
|
||||
use tokio::sync::{RwLock, oneshot};
|
||||
|
||||
@@ -519,6 +520,23 @@ impl BatchingEngine {
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("true"))
|
||||
}
|
||||
|
||||
/// Enforces the sink half of the opt-in row-local incremental-read contract: a delta round is
|
||||
/// written as a keyed materialization, so an append-mode sink would accumulate replayed
|
||||
/// history instead of overwriting the keys it has already materialized.
|
||||
fn ensure_simple_source_delta_sink(task: &BatchingTask, sink: &TableRef) -> Result<(), Error> {
|
||||
ensure!(
|
||||
!Self::table_options_enable_append_mode(&sink.table_info().meta.options.extra_options),
|
||||
UnsupportedSnafu {
|
||||
reason: format!(
|
||||
"Flow {} incremental read requires a non-append sink table, but sink `{}` is append-only. A restarted flow replays a full snapshot, which would duplicate history in an append-mode sink",
|
||||
task.config.flow_id,
|
||||
task.config.sink_table_name.join(".")
|
||||
),
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// SQL flows without a usable time-window expression can only run as an
|
||||
/// explicit full-query flow, so require `EVAL INTERVAL` at creation time.
|
||||
fn ensure_sql_flow_has_twe_or_eval_interval(
|
||||
@@ -658,6 +676,12 @@ impl BatchingEngine {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
let plan = sql_to_df_plan(query_ctx.clone(), self.query_engine.clone(), &sql, true).await?;
|
||||
// The retained task plan is judged for row-local delta eligibility, so it must match what
|
||||
// a round executes: `gen_plan_with_matching_schema_and_values` replans the SQL without the
|
||||
// flow optimizer, where `now()` and other stable expressions are still time-dependent.
|
||||
// The optimized plan above remains the source for TQL/time-window/table analysis.
|
||||
let retained_plan =
|
||||
sql_to_df_plan(query_ctx.clone(), self.query_engine.clone(), &sql, false).await?;
|
||||
|
||||
if is_tql {
|
||||
self.check_is_tql_table(&plan, &query_ctx).await?;
|
||||
@@ -719,7 +743,10 @@ impl BatchingEngine {
|
||||
let task_args = TaskArgs {
|
||||
flow_id,
|
||||
query: &sql,
|
||||
plan,
|
||||
// Eligibility must be judged on the plan that is actually executed. Each round
|
||||
// replans the SQL without the flow optimizer, so constant folding in the optimized
|
||||
// plan must not hide time-dependent expressions such as `now()`.
|
||||
plan: retained_plan,
|
||||
time_window_expr: phy_expr,
|
||||
expire_after,
|
||||
sink_table_name,
|
||||
@@ -751,9 +778,37 @@ impl BatchingEngine {
|
||||
let engine = self.query_engine.clone();
|
||||
let frontend = self.frontend_client.clone();
|
||||
|
||||
// Opt-in row-local delta reads replay a full snapshot on restart or fallback, so an
|
||||
// append-mode sink would duplicate history instead of overwriting its keys. An
|
||||
// auto-created sink must also keep every source key, because a delta round is written as
|
||||
// a keyed materialization of the source rows. The key contract is validated before the
|
||||
// sink is created so a rejected flow leaves no keyless sink behind.
|
||||
if task.config.simple_source_delta {
|
||||
ensure!(
|
||||
task.sequence_range_capable().await?,
|
||||
UnsupportedSnafu {
|
||||
reason: format!(
|
||||
"Flow {flow_id} is a row-local delta flow, which requires exact sequence-range reads, but source table `{}` lacks the Mito preserve_row_sequence capability",
|
||||
task.config
|
||||
.source_table_names
|
||||
.iter()
|
||||
.map(|name| name.join("."))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
),
|
||||
}
|
||||
);
|
||||
}
|
||||
if task.config.simple_source_delta && !task.sink_table_exists().await? {
|
||||
task.ensure_derivable_sink_keys(&engine).await?;
|
||||
}
|
||||
|
||||
// Create the sink before asking an optional extension to own execution.
|
||||
// The default path retains the OSS schema validation.
|
||||
let table = task.check_or_create_sink_table(&engine, &frontend).await?;
|
||||
if task.config.simple_source_delta {
|
||||
Self::ensure_simple_source_delta_sink(&task, &table)?;
|
||||
}
|
||||
let execution = if let Some(factory) = &self.execution_factory {
|
||||
factory.create(&task, table, &engine, &frontend).await?
|
||||
} else {
|
||||
@@ -1724,6 +1779,133 @@ GROUP BY l.number, time_window
|
||||
(task, tx)
|
||||
}
|
||||
|
||||
/// Builds a task for the opt-in row-local delta path from the test query engine.
|
||||
async fn new_simple_delta_task(
|
||||
query: &str,
|
||||
sink_name: &str,
|
||||
incremental: bool,
|
||||
) -> (BatchingTask, QueryEngineRef) {
|
||||
let query_engine = create_test_query_engine();
|
||||
let ctx = QueryContext::arc();
|
||||
let plan = sql_to_df_plan(ctx.clone(), query_engine.clone(), query, true)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_tx, rx) = oneshot::channel();
|
||||
let batch_opts = Arc::new(BatchingModeOptions {
|
||||
experimental_enable_incremental_read: incremental,
|
||||
..Default::default()
|
||||
});
|
||||
let task = BatchingTask::try_new(TaskArgs {
|
||||
flow_id: 1,
|
||||
query,
|
||||
plan,
|
||||
time_window_expr: None,
|
||||
expire_after: None,
|
||||
sink_table_name: [
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
sink_name.to_string(),
|
||||
],
|
||||
source_table_names: vec![[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"numbers_with_ts".to_string(),
|
||||
]],
|
||||
query_ctx: ctx,
|
||||
catalog_manager: query_engine.engine_state().catalog_manager().clone(),
|
||||
shutdown_rx: rx,
|
||||
batch_opts,
|
||||
flow_eval_interval: Some(Duration::from_secs(60)),
|
||||
eval_schedule: None,
|
||||
})
|
||||
.unwrap();
|
||||
(task, query_engine)
|
||||
}
|
||||
|
||||
/// Builds a sink table ref whose extra options match `extra_options`.
|
||||
fn sink_with_extra_options(
|
||||
name: &str,
|
||||
extra_options: HashMap<String, String>,
|
||||
) -> table::TableRef {
|
||||
use table::metadata::FilterPushDownType;
|
||||
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("number", ConcreteDataType::uint32_datatype(), false),
|
||||
ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
]));
|
||||
let recordbatch = RecordBatch::new(
|
||||
schema,
|
||||
vec![
|
||||
Arc::new(UInt32Vector::from_slice([1_u32])) as VectorRef,
|
||||
Arc::new(TimestampMillisecondVector::from_slice([0_i64])) as VectorRef,
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let table = table::test_util::MemTable::table(name, recordbatch);
|
||||
let mut info = (*table.table_info()).clone();
|
||||
info.meta.options.extra_options = extra_options;
|
||||
Arc::new(table::Table::new(
|
||||
Arc::new(info),
|
||||
FilterPushDownType::Unsupported,
|
||||
table.data_source(),
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_rejects_append_mode_sink() {
|
||||
let (task, _) =
|
||||
new_simple_delta_task("SELECT number, ts FROM numbers_with_ts", "delta_sink", true)
|
||||
.await;
|
||||
assert!(task.config.simple_source_delta);
|
||||
|
||||
let append_sink = sink_with_extra_options(
|
||||
"delta_sink",
|
||||
HashMap::from([(APPEND_MODE_KEY.to_string(), "true".to_string())]),
|
||||
);
|
||||
let err = BatchingEngine::ensure_simple_source_delta_sink(&task, &append_sink)
|
||||
.expect_err("an append-mode sink must be rejected for a row-local delta flow");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("incremental read requires a non-append sink table"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
let keyed_sink = sink_with_extra_options("delta_sink", HashMap::new());
|
||||
BatchingEngine::ensure_simple_source_delta_sink(&task, &keyed_sink)
|
||||
.expect("a non-append sink is accepted");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_requires_derivable_sink_keys() {
|
||||
// Dropping the source time index makes the auto-created sink keyless for a delta round.
|
||||
let (task, query_engine) =
|
||||
new_simple_delta_task("SELECT number FROM numbers_with_ts", "delta_sink", true).await;
|
||||
assert!(task.config.simple_source_delta);
|
||||
|
||||
let err = task
|
||||
.ensure_derivable_sink_keys(&query_engine)
|
||||
.await
|
||||
.expect_err("a projection without the source time index has no derivable sink keys");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("Create a compatible keyed sink table explicitly"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
let (keyed_task, keyed_engine) =
|
||||
new_simple_delta_task("SELECT number, ts FROM numbers_with_ts", "delta_sink", true)
|
||||
.await;
|
||||
keyed_task
|
||||
.ensure_derivable_sink_keys(&keyed_engine)
|
||||
.await
|
||||
.expect("a projection keeping the source keys is accepted");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_handle_mark_dirty_time_window_with_time_ranges() {
|
||||
let engine = new_test_engine().await;
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Row-local source delta support for simple SQL flows.
|
||||
//!
|
||||
//! A flow whose plan is one source scan plus a projection/alias/filter can read only the source
|
||||
//! rows written since the last checkpoint. That is correct only because the projection is a
|
||||
//! deterministic, row-local function of a single source row, and because a delta round is written
|
||||
//! as a keyed materialization: rows sharing the sink key collapse under ordinary sink semantics.
|
||||
|
||||
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
|
||||
use datafusion_expr::{Expr, LogicalPlan, Volatility};
|
||||
use datatypes::schema::{ColumnSchema, SchemaRef};
|
||||
|
||||
use crate::adapter::output_column_schemas;
|
||||
|
||||
/// Source-key layout of a flow output, expressed as output positions.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct SinkKeys {
|
||||
/// Output position of the source time index.
|
||||
pub(crate) time_index: usize,
|
||||
/// Output positions of the source primary keys, in source order.
|
||||
pub(crate) primary_keys: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Returns whether `plan` can be replayed from a source delta: at most one projection on top of
|
||||
/// zero or more filters over exactly one table scan, and every expression is row-local and
|
||||
/// immutable. Any other node (aggregate, join, distinct, sort, limit, union, subquery) makes the
|
||||
/// plan not row-local, hence unsupported.
|
||||
pub(crate) fn is_simple_source_delta_plan(plan: &LogicalPlan) -> bool {
|
||||
let mut is_row_local = true;
|
||||
let mut node = plan;
|
||||
// The optimizer may fold the projection into `TableScan.projection`, so a bare scan is a
|
||||
// valid shape too.
|
||||
if let LogicalPlan::Projection(projection) = node {
|
||||
is_row_local &= projection.expr.iter().all(expr_is_row_local);
|
||||
node = projection.input.as_ref();
|
||||
}
|
||||
while let LogicalPlan::Filter(filter) = node {
|
||||
is_row_local &= expr_is_row_local(&filter.predicate);
|
||||
node = filter.input.as_ref();
|
||||
}
|
||||
let LogicalPlan::TableScan(scan) = node else {
|
||||
return false;
|
||||
};
|
||||
// `LIMIT n` pushdown folds into `TableScan.fetch`, which truncates rows
|
||||
// non-deterministically and is not a row-local delta.
|
||||
// Pushed-down scan filters, in contrast, are ordinary `WHERE` predicates over
|
||||
// the same source row, so they stay part of the accepted shape.
|
||||
scan.fetch.is_none() && is_row_local && scan.filters.iter().all(expr_is_row_local)
|
||||
}
|
||||
|
||||
/// Derives the sink keys of `plan` from source-column lineage: the output column that carries the
|
||||
/// source time index and the output columns that carry the source primary keys, in source order.
|
||||
///
|
||||
/// Returns `None` when the source time index or any source primary key is not a direct
|
||||
/// `Column`/`Alias(Column)` of the source, or when one source key maps to more than one output
|
||||
/// column.
|
||||
pub(crate) fn derive_sink_keys(
|
||||
plan: &LogicalPlan,
|
||||
source_schema: &SchemaRef,
|
||||
source_pk_indices: &[usize],
|
||||
) -> Option<SinkKeys> {
|
||||
let (_, lineage) = output_column_schemas(plan, source_schema).ok()?;
|
||||
let source_time_index = source_schema
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.position(ColumnSchema::is_time_index)?;
|
||||
|
||||
let time_index = output_position(&lineage, source_time_index)?;
|
||||
let primary_keys = source_pk_indices
|
||||
.iter()
|
||||
.map(|source_index| output_position(&lineage, *source_index))
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(SinkKeys {
|
||||
time_index,
|
||||
primary_keys,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the single output position whose lineage is `source_index`. Two output columns sharing
|
||||
/// one source key would make the sink key ambiguous, so that case returns `None`.
|
||||
fn output_position(lineage: &[Option<usize>], source_index: usize) -> Option<usize> {
|
||||
let mut positions = lineage
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, index)| **index == Some(source_index))
|
||||
.map(|(position, _)| position);
|
||||
let position = positions.next()?;
|
||||
positions.next().is_none().then_some(position)
|
||||
}
|
||||
|
||||
/// Returns whether `expr` is a row-local, immutable function of its input row: no window
|
||||
/// function, subquery, aggregate, scalar variable, or volatile/stable scalar function.
|
||||
fn expr_is_row_local(expr: &Expr) -> bool {
|
||||
let mut is_row_local = true;
|
||||
let _ = expr.apply(|expr| match expr {
|
||||
Expr::WindowFunction(_)
|
||||
| Expr::Exists(_)
|
||||
| Expr::InSubquery(_)
|
||||
| Expr::ScalarSubquery(_)
|
||||
| Expr::AggregateFunction(_)
|
||||
| Expr::ScalarVariable(_, _) => {
|
||||
is_row_local = false;
|
||||
Ok(TreeNodeRecursion::Stop)
|
||||
}
|
||||
Expr::ScalarFunction(function)
|
||||
if function.func.signature().volatility != Volatility::Immutable =>
|
||||
{
|
||||
is_row_local = false;
|
||||
Ok(TreeNodeRecursion::Stop)
|
||||
}
|
||||
_ => Ok(TreeNodeRecursion::Continue),
|
||||
});
|
||||
is_row_local
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::sync::Arc;
|
||||
|
||||
use catalog::RegisterTableRequest;
|
||||
use catalog::memory::MemoryCatalogManager;
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
use common_recordbatch::RecordBatch;
|
||||
use datafusion_common::tree_node::Transformed;
|
||||
use datafusion_expr::{Expr, LogicalPlan, Projection};
|
||||
use datatypes::arrow::datatypes::DataType;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnSchema, Schema, SchemaRef};
|
||||
use datatypes::vectors::{Float64Vector, StringVector, TimestampMillisecondVector, VectorRef};
|
||||
use query::QueryEngineRef;
|
||||
use session::context::QueryContext;
|
||||
use table::test_util::MemTable;
|
||||
|
||||
use super::*;
|
||||
use crate::batching_mode::utils::sql_to_df_plan;
|
||||
use crate::test_utils::create_test_query_engine;
|
||||
|
||||
const SOURCE_TABLE: &str = "simple_delta_source";
|
||||
|
||||
/// Registers `simple_delta_source` (`host` primary key, `ts` time index, one other timestamp
|
||||
/// column and one value column) and returns its schema with the source primary key positions.
|
||||
fn register_source_table(query_engine: &QueryEngineRef) -> (SchemaRef, Vec<usize>) {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
|
||||
ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
ColumnSchema::new(
|
||||
"other_ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
),
|
||||
ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
|
||||
]));
|
||||
let columns: Vec<VectorRef> = vec![
|
||||
Arc::new(StringVector::from_slice(&["a"])),
|
||||
Arc::new(TimestampMillisecondVector::from_slice([1_i64])),
|
||||
Arc::new(TimestampMillisecondVector::from_slice([2_i64])),
|
||||
Arc::new(Float64Vector::from_slice([1.0])),
|
||||
];
|
||||
let recordbatch = RecordBatch::new(schema.clone(), columns).unwrap();
|
||||
let table = MemTable::table(SOURCE_TABLE, recordbatch);
|
||||
let catalog_manager = query_engine.engine_state().catalog_manager();
|
||||
let memory_catalog = catalog_manager
|
||||
.as_any()
|
||||
.downcast_ref::<MemoryCatalogManager>()
|
||||
.unwrap();
|
||||
memory_catalog
|
||||
.register_table_sync(RegisterTableRequest {
|
||||
catalog: DEFAULT_CATALOG_NAME.to_string(),
|
||||
schema: DEFAULT_SCHEMA_NAME.to_string(),
|
||||
table_name: SOURCE_TABLE.to_string(),
|
||||
table_id: 9101,
|
||||
table,
|
||||
})
|
||||
.unwrap();
|
||||
(schema, vec![0])
|
||||
}
|
||||
|
||||
async fn plan(query_engine: &QueryEngineRef, sql: &str, optimize: bool) -> LogicalPlan {
|
||||
sql_to_df_plan(QueryContext::arc(), query_engine.clone(), sql, optimize)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_plan_accepts_scan_projection_and_filter() {
|
||||
let query_engine = create_test_query_engine();
|
||||
for (case, sql, optimize) in [
|
||||
("bare scan", "SELECT number, ts FROM numbers_with_ts", true),
|
||||
(
|
||||
"scan with where",
|
||||
"SELECT number, ts FROM numbers_with_ts WHERE number > 1",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"projection over filter",
|
||||
"SELECT number + 1 AS n, ts FROM numbers_with_ts WHERE number > 1",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"unoptimized projection",
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let plan = plan(&query_engine, sql, optimize).await;
|
||||
assert!(
|
||||
is_simple_source_delta_plan(&plan),
|
||||
"{case} should be accepted:\n{plan}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_plan_rejects_other_shapes() {
|
||||
let query_engine = create_test_query_engine();
|
||||
for (case, sql, optimize) in [
|
||||
(
|
||||
"aggregate",
|
||||
"SELECT max(number) AS number, ts FROM numbers_with_ts GROUP BY ts",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"join",
|
||||
"SELECT a.number, a.ts FROM numbers_with_ts a JOIN numbers b ON a.number = b.number",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"distinct",
|
||||
"SELECT DISTINCT number, ts FROM numbers_with_ts",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"sort",
|
||||
"SELECT number, ts FROM numbers_with_ts ORDER BY ts",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"limit",
|
||||
"SELECT number, ts FROM numbers_with_ts LIMIT 1",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"union",
|
||||
"SELECT number, ts FROM numbers_with_ts UNION ALL SELECT number, ts FROM numbers_with_ts",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"nested projection",
|
||||
"SELECT number FROM (SELECT number, ts FROM numbers_with_ts) t",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"scalar subquery",
|
||||
"SELECT number, ts FROM numbers_with_ts WHERE number > (SELECT 1)",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"volatile function",
|
||||
"SELECT random() AS number, ts FROM numbers_with_ts",
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let plan = plan(&query_engine, sql, optimize).await;
|
||||
assert!(
|
||||
!is_simple_source_delta_plan(&plan),
|
||||
"{case} should be rejected:\n{plan}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_plan_rejects_scan_fetch() {
|
||||
let query_engine = create_test_query_engine();
|
||||
let ctx = QueryContext::arc();
|
||||
|
||||
// `LIMIT` may fold into `TableScan.fetch` (DataFusion limit pushdown), which leaves a
|
||||
// bare accepted scan that truncates rows. The scan is built directly because this
|
||||
// engine's optimizer does not always push the fetch down.
|
||||
for sql in [
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
"SELECT number FROM numbers_with_ts",
|
||||
] {
|
||||
let plan = sql_to_df_plan(ctx.clone(), query_engine.clone(), sql, false)
|
||||
.await
|
||||
.unwrap();
|
||||
let with_fetch = plan
|
||||
.transform_down(|node| {
|
||||
Ok(match node {
|
||||
LogicalPlan::TableScan(mut scan) => {
|
||||
scan.fetch = Some(1);
|
||||
Transformed::yes(LogicalPlan::TableScan(scan))
|
||||
}
|
||||
other => Transformed::no(other),
|
||||
})
|
||||
})
|
||||
.unwrap()
|
||||
.data;
|
||||
assert!(
|
||||
!is_simple_source_delta_plan(&with_fetch),
|
||||
"a scan carrying a pushed-down fetch must be rejected:\n{with_fetch}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_derive_sink_keys_keeps_projected_source_keys() {
|
||||
let query_engine = create_test_query_engine();
|
||||
let (source_schema, source_pk_indices) = register_source_table(&query_engine);
|
||||
|
||||
let plan = plan(
|
||||
&query_engine,
|
||||
"SELECT ts, host, value FROM simple_delta_source",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
let keys = derive_sink_keys(&plan, &source_schema, &source_pk_indices).unwrap();
|
||||
assert_eq!(
|
||||
SinkKeys {
|
||||
time_index: 0,
|
||||
primary_keys: vec![1],
|
||||
},
|
||||
keys
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_derive_sink_keys_uses_source_time_index_not_first_timestamp() {
|
||||
let query_engine = create_test_query_engine();
|
||||
let (source_schema, source_pk_indices) = register_source_table(&query_engine);
|
||||
|
||||
// `other_ts` is projected before the real time index `ts`.
|
||||
let plan = plan(
|
||||
&query_engine,
|
||||
"SELECT host, other_ts, ts FROM simple_delta_source",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
let keys = derive_sink_keys(&plan, &source_schema, &source_pk_indices).unwrap();
|
||||
assert_eq!(
|
||||
SinkKeys {
|
||||
time_index: 2,
|
||||
primary_keys: vec![0],
|
||||
},
|
||||
keys
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds `Projection(exprs)` over a scan of the test source table.
|
||||
async fn projection_over_source(
|
||||
query_engine: &QueryEngineRef,
|
||||
exprs: Vec<Expr>,
|
||||
) -> LogicalPlan {
|
||||
let scan = plan(
|
||||
query_engine,
|
||||
"SELECT host, ts, value FROM simple_delta_source",
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
LogicalPlan::Projection(
|
||||
Projection::try_new(exprs, Arc::new(scan)).expect("test projection should be valid"),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_derive_sink_keys_rejects_computed_source_key() {
|
||||
let query_engine = create_test_query_engine();
|
||||
let (source_schema, source_pk_indices) = register_source_table(&query_engine);
|
||||
|
||||
// A computed column loses source lineage even when it is the only output column and
|
||||
// keeps the source key name, so name-based lineage would wrongly accept it.
|
||||
let shadowing = projection_over_source(
|
||||
&query_engine,
|
||||
vec![
|
||||
Expr::Cast(datafusion_expr::Cast::new(
|
||||
Box::new(Expr::Column("host".into())),
|
||||
DataType::Utf8,
|
||||
))
|
||||
.alias("host"),
|
||||
Expr::Column("ts".into()),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
derive_sink_keys(&shadowing, &source_schema, &source_pk_indices).is_none(),
|
||||
"a computed source key must not be inherited by naming:\n{shadowing}"
|
||||
);
|
||||
|
||||
// `upper(host)` projected into a differently named column also inherits nothing, so the
|
||||
// source primary key is missing from the output.
|
||||
let computed = plan(
|
||||
&query_engine,
|
||||
"SELECT upper(host) AS upper_host, ts FROM simple_delta_source",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
derive_sink_keys(&computed, &source_schema, &source_pk_indices).is_none(),
|
||||
"a computed source key must not be inherited:\n{computed}"
|
||||
);
|
||||
|
||||
// A second output column carrying the same source key leaves the sink key ambiguous.
|
||||
let duplicated = plan(
|
||||
&query_engine,
|
||||
"SELECT host AS h1, host AS h2, ts FROM simple_delta_source",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
derive_sink_keys(&duplicated, &source_schema, &source_pk_indices).is_none(),
|
||||
"ambiguous source key lineage must be rejected:\n{duplicated}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_derive_sink_keys_returns_none_for_dropped_source_key() {
|
||||
let query_engine = create_test_query_engine();
|
||||
let (source_schema, source_pk_indices) = register_source_table(&query_engine);
|
||||
|
||||
for sql in [
|
||||
// dropped primary key
|
||||
"SELECT ts, value FROM simple_delta_source",
|
||||
// dropped time index
|
||||
"SELECT host, value FROM simple_delta_source",
|
||||
] {
|
||||
let plan = plan(&query_engine, sql, true).await;
|
||||
assert!(
|
||||
derive_sink_keys(&plan, &source_schema, &source_pk_indices).is_none(),
|
||||
"a plan that drops a source key has no derivable sink keys:\n{plan}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ use snafu::ResultExt;
|
||||
|
||||
use crate::Error;
|
||||
use crate::adapter::{AUTO_CREATED_PLACEHOLDER_TS_COL, AUTO_CREATED_UPDATE_AT_TS_COL};
|
||||
use crate::batching_mode::simple_delta::SinkKeys;
|
||||
use crate::batching_mode::utils::FindGroupByFinalName;
|
||||
use crate::error::{ConvertColumnSchemaSnafu, DatafusionSnafu};
|
||||
|
||||
@@ -35,16 +36,20 @@ pub enum QueryType {
|
||||
}
|
||||
|
||||
// auto created table have a auto added column `update_at`, and optional have a `AUTO_CREATED_PLACEHOLDER_TS_COL` column for time index placeholder if no timestamp column is specified
|
||||
// `derived` carries source-key lineage for an opt-in row-local flow and overrides the first-timestamp fallback of `build_by_sql_schema`
|
||||
// TODO(discord9): for now no default value is set for auto added column for compatibility reason with streaming mode, but this might change in favor of simpler code?
|
||||
pub(super) fn create_table_with_expr(
|
||||
plan: &LogicalPlan,
|
||||
sink_table_name: &[String; 3],
|
||||
query_type: &QueryType,
|
||||
derived: Option<SinkKeys>,
|
||||
) -> Result<CreateTableExpr, Error> {
|
||||
let table_def = match query_type {
|
||||
&QueryType::Sql => {
|
||||
if let Some(def) = build_pk_from_aggr(plan)? {
|
||||
def
|
||||
} else if let Some(def) = build_by_derived_keys(plan, derived) {
|
||||
def
|
||||
} else {
|
||||
build_by_sql_schema(plan)?
|
||||
}
|
||||
@@ -153,6 +158,21 @@ fn build_by_sql_schema(plan: &LogicalPlan) -> Result<TableDef, Error> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a keyed sink layout from source-key lineage: the output column carrying the source time
|
||||
/// index becomes the time index, and the output columns carrying the source primary keys become
|
||||
/// primary keys. Such a sink materializes a source delta key by key.
|
||||
fn build_by_derived_keys(plan: &LogicalPlan, derived: Option<SinkKeys>) -> Option<TableDef> {
|
||||
let derived = derived?;
|
||||
let fields = plan.schema().fields();
|
||||
let ts_col = Some(fields.get(derived.time_index)?.name().clone());
|
||||
let pks = derived
|
||||
.primary_keys
|
||||
.iter()
|
||||
.map(|position| fields.get(*position).map(|field| field.name().clone()))
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(TableDef { ts_col, pks })
|
||||
}
|
||||
|
||||
/// Return first timestamp column found in output schema and all string columns
|
||||
fn build_by_tql_schema(plan: &LogicalPlan) -> Result<TableDef, Error> {
|
||||
let first_time_stamp = plan.schema().fields().iter().find_map(|f| {
|
||||
@@ -300,6 +320,7 @@ mod test {
|
||||
"sink".to_string(),
|
||||
],
|
||||
&QueryType::Tql,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let columns = expr
|
||||
@@ -399,6 +420,7 @@ mod test {
|
||||
"sink".to_string(),
|
||||
],
|
||||
&QueryType::Tql,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let columns = expr
|
||||
@@ -537,6 +559,7 @@ mod test {
|
||||
tc.sink_table_name.clone(),
|
||||
],
|
||||
&QueryType::Sql,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
// TODO(discord9): assert expr
|
||||
@@ -550,4 +573,46 @@ mod test {
|
||||
assert_eq!(tc.time_index, expr.time_index, "{:?}", tc.sql);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sql_sink_uses_derived_sink_keys() {
|
||||
let query_engine = create_test_query_engine();
|
||||
let ctx = QueryContext::arc();
|
||||
let plan = sql_to_df_plan(
|
||||
ctx.clone(),
|
||||
query_engine.clone(),
|
||||
// `number` is the derived source primary key and `ts` the derived time index, even
|
||||
// though `ts` is not the first column of the output.
|
||||
"SELECT ts, number FROM numbers_with_ts",
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let expr = create_table_with_expr(
|
||||
&plan,
|
||||
&[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"new_table".to_string(),
|
||||
],
|
||||
&QueryType::Sql,
|
||||
Some(SinkKeys {
|
||||
time_index: 0,
|
||||
primary_keys: vec![1],
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(vec!["number".to_string()], expr.primary_keys);
|
||||
assert_eq!("ts", expr.time_index);
|
||||
let columns = expr
|
||||
.column_defs
|
||||
.iter()
|
||||
.map(|c| try_as_column_schema(c).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!("ts", columns[0].name);
|
||||
assert!(columns[0].is_time_index());
|
||||
assert_eq!("number", columns[1].name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ use query::options::{
|
||||
};
|
||||
use query::query_engine::DefaultSerializer;
|
||||
use session::context::QueryContextRef;
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use sql::parsers::utils::is_tql;
|
||||
use store_api::mito_engine_options::MERGE_MODE_KEY;
|
||||
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
|
||||
@@ -57,6 +57,7 @@ use crate::batching_mode::BatchingModeOptions;
|
||||
use crate::batching_mode::checkpoint::checkpoint_mode_label;
|
||||
use crate::batching_mode::eval_schedule::{EvalSchedule, select_due_scheduled_times};
|
||||
use crate::batching_mode::frontend_client::{FrontendClient, PeerDesc};
|
||||
use crate::batching_mode::simple_delta;
|
||||
use crate::batching_mode::state::{
|
||||
CheckpointMode, DirtyTimeWindows, FilterExprInfo, TaskState, to_df_literal,
|
||||
};
|
||||
@@ -69,7 +70,7 @@ use crate::batching_mode::utils::{
|
||||
use crate::df_optimizer::apply_df_optimizer;
|
||||
use crate::error::{
|
||||
DatafusionSnafu, ExternalSnafu, InvalidQuerySnafu, SubstraitEncodeLogicalPlanSnafu,
|
||||
UnexpectedSnafu,
|
||||
UnexpectedSnafu, UnsupportedSnafu,
|
||||
};
|
||||
use crate::metrics::{
|
||||
METRIC_FLOW_BATCHING_ENGINE_ERROR_CNT, METRIC_FLOW_BATCHING_ENGINE_QUERY_TIME,
|
||||
@@ -160,6 +161,10 @@ pub struct TaskConfig {
|
||||
pub query_type: QueryType,
|
||||
pub batch_opts: Arc<BatchingModeOptions>,
|
||||
pub exact_sequence_range_required: bool,
|
||||
/// Whether this flow opted in to row-local source delta reads, i.e. incremental
|
||||
/// reads are enabled and the plan is a single-source, row-local projection/filter
|
||||
/// over a table scan with no time window.
|
||||
pub simple_source_delta: bool,
|
||||
pub flow_eval_interval: Option<Duration>,
|
||||
/// Typed schedule configuration, pre-parsed at task creation time.
|
||||
pub eval_schedule: Option<EvalSchedule>,
|
||||
@@ -418,6 +423,16 @@ impl BatchingTask {
|
||||
state.disable_incremental();
|
||||
}
|
||||
|
||||
let query_type = determine_query_type(query, &query_ctx)?;
|
||||
// Opt-in row-local delta reads need a window-less SQL plan over exactly one source whose
|
||||
// every expression is a deterministic function of the scanned row. The flag is opt-in
|
||||
// only, so a flow that never enabled incremental reads keeps its previous behavior.
|
||||
let simple_source_delta = batch_opts.experimental_enable_incremental_read
|
||||
&& matches!(query_type, QueryType::Sql)
|
||||
&& time_window_expr.is_none()
|
||||
&& source_table_names.len() == 1
|
||||
&& simple_delta::is_simple_source_delta_plan(&plan);
|
||||
|
||||
Ok(Self {
|
||||
config: Arc::new(TaskConfig {
|
||||
flow_id,
|
||||
@@ -428,8 +443,9 @@ impl BatchingTask {
|
||||
source_table_names: source_table_names.into_iter().collect(),
|
||||
catalog_manager,
|
||||
output_schema: plan.schema().clone(),
|
||||
query_type: determine_query_type(query, &query_ctx)?,
|
||||
query_type,
|
||||
exact_sequence_range_required,
|
||||
simple_source_delta,
|
||||
batch_opts,
|
||||
flow_eval_interval,
|
||||
eval_schedule,
|
||||
@@ -535,6 +551,34 @@ impl BatchingTask {
|
||||
Ok(table)
|
||||
}
|
||||
|
||||
/// Whether the sink table already exists, i.e. whether this flow will not auto-create it.
|
||||
pub(crate) async fn sink_table_exists(&self) -> Result<bool, Error> {
|
||||
self.is_table_exist(&self.config.sink_table_name).await
|
||||
}
|
||||
|
||||
/// Enforces the sink contract of opt-in row-local incremental reads for a sink this flow has
|
||||
/// just auto-created: a delta round is a keyed materialization, so the sink must keep the
|
||||
/// source time index and every source primary key as direct columns or rows sharing a source
|
||||
/// row's key would silently collapse. An explicitly provided sink owns its own key design.
|
||||
pub(crate) async fn ensure_derivable_sink_keys(
|
||||
&self,
|
||||
engine: &QueryEngineRef,
|
||||
) -> Result<(), Error> {
|
||||
let query_ctx = self.state.read().unwrap().query_ctx.clone();
|
||||
let plan = sql_to_df_plan(query_ctx, engine.clone(), &self.config.query, true).await?;
|
||||
ensure!(
|
||||
self.derive_sink_keys(&plan).await?.is_some(),
|
||||
UnsupportedSnafu {
|
||||
reason: format!(
|
||||
"Flow {} incremental read requires the auto-created sink to keep the source time index and every source primary key as direct columns, but sink `{}` does not. Create a compatible keyed sink table explicitly",
|
||||
self.config.flow_id,
|
||||
self.config.sink_table_name.join(".")
|
||||
),
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a forked snapshot of the task query context for extension-owned planning.
|
||||
pub fn query_context_snapshot(&self) -> QueryContextRef {
|
||||
let query_ctx = self.state.read().unwrap().query_ctx.clone();
|
||||
@@ -1265,6 +1309,22 @@ impl BatchingTask {
|
||||
let extensions = self
|
||||
.build_flow_query_extensions(incremental_safe, coverage.is_incremental_delta())
|
||||
.await?;
|
||||
// A delta round of an opt-in row-local flow is only correct with incremental scan
|
||||
// extensions. Without them the plan would run as an unfiltered full snapshot that the
|
||||
// delta cursor does not account for, so skip the round and retry it later instead.
|
||||
if self.config.simple_source_delta
|
||||
&& coverage.is_incremental_delta()
|
||||
&& !extensions
|
||||
.iter()
|
||||
.any(|(key, _)| *key == FLOW_INCREMENTAL_MODE)
|
||||
{
|
||||
warn!(
|
||||
"Flow {flow_id} built a delta plan without {FLOW_INCREMENTAL_MODE}; \
|
||||
restored dirty signal instead of executing an unfiltered full snapshot"
|
||||
);
|
||||
self.restore_dirty_windows(dirty_restore);
|
||||
return Ok(None);
|
||||
}
|
||||
let frontend_extensions = self.frontend_extensions();
|
||||
let extension_refs = extensions
|
||||
.iter()
|
||||
@@ -1956,7 +2016,46 @@ impl BatchingTask {
|
||||
let query_ctx = self.state.read().unwrap().query_ctx.clone();
|
||||
let plan =
|
||||
sql_to_df_plan(query_ctx.clone(), engine.clone(), &self.config.query, true).await?;
|
||||
create_table_with_expr(&plan, &self.config.sink_table_name, &self.config.query_type)
|
||||
let derived = if self.config.simple_source_delta {
|
||||
self.derive_sink_keys(&plan).await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
create_table_with_expr(
|
||||
&plan,
|
||||
&self.config.sink_table_name,
|
||||
&self.config.query_type,
|
||||
derived,
|
||||
)
|
||||
}
|
||||
|
||||
/// Derives the auto-created sink keys from the single source table's time index and primary
|
||||
/// keys. Only direct column/alias lineage counts, so a computed projection column never
|
||||
/// inherits a source key. `None` means the projection does not retain every source key.
|
||||
async fn derive_sink_keys(
|
||||
&self,
|
||||
plan: &LogicalPlan,
|
||||
) -> Result<Option<simple_delta::SinkKeys>, Error> {
|
||||
let Some(source_name) = self.config.source_table_names.iter().next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let table = match self
|
||||
.config
|
||||
.catalog_manager
|
||||
.table(&source_name[0], &source_name[1], &source_name[2], None)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?
|
||||
{
|
||||
Some(table) => table,
|
||||
None => return Ok(None),
|
||||
};
|
||||
let info = table.table_info();
|
||||
Ok(simple_delta::derive_sink_keys(
|
||||
plan,
|
||||
&info.meta.schema,
|
||||
&info.meta.primary_key_indices,
|
||||
))
|
||||
}
|
||||
|
||||
/// Incremental delta scans are unfiltered by dirty windows; the sequence
|
||||
@@ -2036,6 +2135,27 @@ impl BatchingTask {
|
||||
.fail();
|
||||
}
|
||||
_ => {
|
||||
// Opt-in row-local flows read only the source delta since the last checkpoint.
|
||||
// The first round runs as a full snapshot and advances the cursor from the
|
||||
// terminal per-region scan watermarks.
|
||||
if !force_full_snapshot
|
||||
&& self.config.simple_source_delta
|
||||
&& self.should_use_unfiltered_incremental_delta()
|
||||
{
|
||||
return self
|
||||
.gen_unfiltered_plan_info_if_dirty(
|
||||
engine,
|
||||
query_ctx,
|
||||
sink_table_schema.clone(),
|
||||
primary_key_indices,
|
||||
allow_partial,
|
||||
values,
|
||||
None,
|
||||
QueryCoverage::IncrementalDelta,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Explicit full-query flows (TQL and evaluation-interval SQL
|
||||
// plans whose shape cannot be safely dirty-window pruned) are
|
||||
// allowed to run as unfiltered full snapshots. This is distinct
|
||||
@@ -2221,3 +2341,673 @@ impl BatchingTask {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test;
|
||||
|
||||
/// Tests for the opt-in row-local source delta path (`simple_source_delta`).
|
||||
#[cfg(test)]
|
||||
mod simple_source_delta_tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use catalog::RegisterTableRequest;
|
||||
use catalog::memory::MemoryCatalogManager;
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
use common_recordbatch::RecordBatch;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::ColumnSchema;
|
||||
use datatypes::vectors::{TimestampMillisecondVector, VectorRef};
|
||||
use pretty_assertions::assert_eq;
|
||||
use query::options::{
|
||||
FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY, QueryOptions,
|
||||
};
|
||||
use session::context::QueryContext;
|
||||
use table::Table;
|
||||
use table::metadata::FilterPushDownType;
|
||||
use table::test_util::MemTable;
|
||||
|
||||
use super::*;
|
||||
use crate::batching_mode::time_window::find_time_window_expr;
|
||||
use crate::test_utils::create_test_query_engine;
|
||||
|
||||
/// Builds a task for `query` with the incremental-read option switched on or off.
|
||||
async fn new_simple_delta_task(
|
||||
query: &str,
|
||||
plan_query: &str,
|
||||
eval_interval: Option<Duration>,
|
||||
incremental: bool,
|
||||
) -> (BatchingTask, Arc<Schema>, QueryEngineRef) {
|
||||
new_simple_delta_task_with_optimize(query, plan_query, eval_interval, incremental, true)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Same as [`Self::new_simple_delta_task`], but with an explicit flow-optimizer setting so a
|
||||
/// test can plan the way the engine retains its task plan.
|
||||
async fn new_simple_delta_task_with_optimize(
|
||||
query: &str,
|
||||
plan_query: &str,
|
||||
eval_interval: Option<Duration>,
|
||||
incremental: bool,
|
||||
optimize: bool,
|
||||
) -> (BatchingTask, Arc<Schema>, QueryEngineRef) {
|
||||
let query_engine = create_test_query_engine();
|
||||
let ctx = QueryContext::arc();
|
||||
let plan = sql_to_df_plan(ctx.clone(), query_engine.clone(), plan_query, optimize)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_tx, rx) = tokio::sync::oneshot::channel();
|
||||
let batch_opts = Arc::new(BatchingModeOptions {
|
||||
experimental_enable_incremental_read: incremental,
|
||||
..Default::default()
|
||||
});
|
||||
let task = BatchingTask::try_new(TaskArgs {
|
||||
flow_id: 1,
|
||||
query,
|
||||
plan,
|
||||
time_window_expr: None,
|
||||
expire_after: None,
|
||||
sink_table_name: [
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"simple_delta_sink".to_string(),
|
||||
],
|
||||
source_table_names: vec![[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"numbers_with_ts".to_string(),
|
||||
]],
|
||||
query_ctx: ctx,
|
||||
catalog_manager: query_engine.engine_state().catalog_manager().clone(),
|
||||
shutdown_rx: rx,
|
||||
batch_opts,
|
||||
flow_eval_interval: eval_interval,
|
||||
eval_schedule: None,
|
||||
})
|
||||
.unwrap();
|
||||
(task, source_sink_schema(), query_engine)
|
||||
}
|
||||
|
||||
/// Builds a task whose retained plan carries a real time-window expression.
|
||||
async fn new_windowed_task(incremental: bool) -> (BatchingTask, Arc<Schema>, QueryEngineRef) {
|
||||
// A windowed flow needs the time window in the output, so it is an aggregate here; the
|
||||
// point is that it never becomes a source delta and keeps its scoped repair.
|
||||
let query = "SELECT number, date_bin(INTERVAL '5 second', ts) AS time_window FROM numbers_with_ts GROUP BY time_window, number";
|
||||
let query_engine = create_test_query_engine();
|
||||
let ctx = QueryContext::arc();
|
||||
let plan = sql_to_df_plan(ctx.clone(), query_engine.clone(), query, true)
|
||||
.await
|
||||
.unwrap();
|
||||
let (column_name, time_window_expr, _, df_schema) = find_time_window_expr(
|
||||
&plan,
|
||||
query_engine.engine_state().catalog_manager().clone(),
|
||||
ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let time_window_expr = time_window_expr.map(|expr| {
|
||||
TimeWindowExpr::from_expr(
|
||||
&expr,
|
||||
&column_name,
|
||||
&df_schema,
|
||||
&query_engine.engine_state().session_state(),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let (_tx, rx) = tokio::sync::oneshot::channel();
|
||||
let batch_opts = Arc::new(BatchingModeOptions {
|
||||
experimental_enable_incremental_read: incremental,
|
||||
..Default::default()
|
||||
});
|
||||
let task = BatchingTask::try_new(TaskArgs {
|
||||
flow_id: 1,
|
||||
query,
|
||||
plan,
|
||||
time_window_expr,
|
||||
expire_after: None,
|
||||
sink_table_name: [
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"simple_delta_sink".to_string(),
|
||||
],
|
||||
source_table_names: vec![[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"numbers_with_ts".to_string(),
|
||||
]],
|
||||
query_ctx: ctx,
|
||||
catalog_manager: query_engine.engine_state().catalog_manager().clone(),
|
||||
shutdown_rx: rx,
|
||||
batch_opts,
|
||||
flow_eval_interval: None,
|
||||
eval_schedule: None,
|
||||
})
|
||||
.unwrap();
|
||||
(
|
||||
task,
|
||||
Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("number", ConcreteDataType::uint32_datatype(), false),
|
||||
ColumnSchema::new(
|
||||
"time_window",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
])),
|
||||
query_engine,
|
||||
)
|
||||
}
|
||||
|
||||
fn source_sink_schema() -> Arc<Schema> {
|
||||
Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("number", ConcreteDataType::uint32_datatype(), false),
|
||||
ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
]))
|
||||
}
|
||||
|
||||
fn add_dirty_window(task: &BatchingTask) {
|
||||
task.state
|
||||
.write()
|
||||
.unwrap()
|
||||
.dirty_time_windows
|
||||
.add_window(Timestamp::new_second(0), Some(Timestamp::new_second(5)));
|
||||
}
|
||||
|
||||
/// Marks the task as having a proven checkpoint so delta coverage is eligible.
|
||||
fn mark_incremental_with_dirty_window(task: &BatchingTask) {
|
||||
let mut state = task.state.write().unwrap();
|
||||
state.advance_checkpoints(HashMap::from([(1_u64, 10_u64)]));
|
||||
state
|
||||
.dirty_time_windows
|
||||
.add_window(Timestamp::new_second(0), Some(Timestamp::new_second(5)));
|
||||
}
|
||||
|
||||
fn dml_plan(plan: LogicalPlan, sink_table: TableRef) -> LogicalPlan {
|
||||
LogicalPlan::Dml(DmlStatement::new(
|
||||
datafusion_common::TableReference::bare("simple_delta_sink"),
|
||||
Arc::new(DefaultTableSource::new(Arc::new(
|
||||
DfTableProviderAdapter::new(sink_table),
|
||||
))),
|
||||
WriteOp::Insert(datafusion_expr::dml::InsertOp::Append),
|
||||
Arc::new(plan),
|
||||
))
|
||||
}
|
||||
|
||||
async fn sink_table(query_engine: &QueryEngineRef) -> TableRef {
|
||||
get_table_info_df_schema(
|
||||
query_engine.engine_state().catalog_manager().clone(),
|
||||
[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"numbers_with_ts".to_string(),
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.0
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_flag_requires_row_local_single_source_sql() {
|
||||
for (case, query, expect) in [
|
||||
(
|
||||
"plain projection",
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"projection with filter",
|
||||
"SELECT number, ts FROM numbers_with_ts WHERE number > 1",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"aggregate",
|
||||
"SELECT max(number) AS number, ts FROM numbers_with_ts GROUP BY ts",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"join",
|
||||
"SELECT a.number, a.ts FROM numbers_with_ts a JOIN numbers b ON a.number = b.number",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let (task, _, _) =
|
||||
new_simple_delta_task(query, query, Some(Duration::from_secs(60)), true).await;
|
||||
assert_eq!(
|
||||
expect, task.config.simple_source_delta,
|
||||
"{case} simple_source_delta mismatch"
|
||||
);
|
||||
}
|
||||
|
||||
// A plan with a time-window expression keeps its scoped dirty-window repair path.
|
||||
let (task, _, _) = new_windowed_task(true).await;
|
||||
assert!(!task.config.simple_source_delta);
|
||||
}
|
||||
|
||||
/// Registers a `number`/`ts` sink table so `sink_table_id()` can resolve it.
|
||||
fn register_sink(query_engine: &QueryEngineRef, name: &str) {
|
||||
let recordbatch = RecordBatch::new(
|
||||
source_sink_schema(),
|
||||
vec![
|
||||
Arc::new(datatypes::vectors::UInt32Vector::from_slice([1_u32])) as VectorRef,
|
||||
Arc::new(TimestampMillisecondVector::from_slice([0_i64])) as VectorRef,
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let table = MemTable::table(name, recordbatch);
|
||||
let catalog_manager = query_engine.engine_state().catalog_manager();
|
||||
let memory_catalog = catalog_manager
|
||||
.as_any()
|
||||
.downcast_ref::<MemoryCatalogManager>()
|
||||
.unwrap();
|
||||
memory_catalog
|
||||
.register_table_sync(RegisterTableRequest {
|
||||
catalog: DEFAULT_CATALOG_NAME.to_string(),
|
||||
schema: DEFAULT_SCHEMA_NAME.to_string(),
|
||||
table_name: name.to_string(),
|
||||
table_id: 9103,
|
||||
table,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Registers `simple_delta_source` (primary key `host`, time index `ts`, plus `other_ts`)
|
||||
/// whose `ts` is not the first output column, so derived and legacy sink layouts differ.
|
||||
fn register_simple_delta_source(query_engine: &QueryEngineRef) {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
|
||||
ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
ColumnSchema::new(
|
||||
"other_ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
),
|
||||
]));
|
||||
let columns: Vec<VectorRef> = vec![
|
||||
Arc::new(datatypes::vectors::StringVector::from_slice(&["a"])) as VectorRef,
|
||||
Arc::new(TimestampMillisecondVector::from_slice([1_i64])) as VectorRef,
|
||||
Arc::new(TimestampMillisecondVector::from_slice([2_i64])) as VectorRef,
|
||||
];
|
||||
let recordbatch = RecordBatch::new(schema, columns).unwrap();
|
||||
let table = MemTable::table("simple_delta_source", recordbatch);
|
||||
// `MemTable::table` declares no primary key; give the source one on `host` so a derived
|
||||
// sink layout is distinguishable from the legacy first-timestamp/no-key layout.
|
||||
let mut info = (*table.table_info()).clone();
|
||||
info.meta.primary_key_indices = vec![0];
|
||||
let table = Arc::new(Table::new(
|
||||
Arc::new(info),
|
||||
FilterPushDownType::Unsupported,
|
||||
table.data_source(),
|
||||
));
|
||||
let catalog_manager = query_engine.engine_state().catalog_manager();
|
||||
let memory_catalog = catalog_manager
|
||||
.as_any()
|
||||
.downcast_ref::<MemoryCatalogManager>()
|
||||
.unwrap();
|
||||
memory_catalog
|
||||
.register_table_sync(RegisterTableRequest {
|
||||
catalog: DEFAULT_CATALOG_NAME.to_string(),
|
||||
schema: DEFAULT_SCHEMA_NAME.to_string(),
|
||||
table_name: "simple_delta_source".to_string(),
|
||||
table_id: 9102,
|
||||
table,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Builds a task over `simple_delta_source` where the projection keeps both source keys.
|
||||
async fn new_source_key_task(incremental: bool) -> (BatchingTask, QueryEngineRef) {
|
||||
let query = "SELECT ts, host FROM simple_delta_source";
|
||||
let query_engine = create_test_query_engine();
|
||||
register_simple_delta_source(&query_engine);
|
||||
let ctx = QueryContext::arc();
|
||||
let plan = sql_to_df_plan(ctx.clone(), query_engine.clone(), query, true)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_tx, rx) = tokio::sync::oneshot::channel();
|
||||
let batch_opts = Arc::new(BatchingModeOptions {
|
||||
experimental_enable_incremental_read: incremental,
|
||||
..Default::default()
|
||||
});
|
||||
let task = BatchingTask::try_new(TaskArgs {
|
||||
flow_id: 1,
|
||||
query,
|
||||
plan,
|
||||
time_window_expr: None,
|
||||
expire_after: None,
|
||||
sink_table_name: [
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"simple_delta_sink".to_string(),
|
||||
],
|
||||
source_table_names: vec![[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"simple_delta_source".to_string(),
|
||||
]],
|
||||
query_ctx: ctx,
|
||||
catalog_manager: query_engine.engine_state().catalog_manager().clone(),
|
||||
shutdown_rx: rx,
|
||||
batch_opts,
|
||||
flow_eval_interval: Some(Duration::from_secs(60)),
|
||||
eval_schedule: None,
|
||||
})
|
||||
.unwrap();
|
||||
(task, query_engine)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_row_local_delta_is_opt_in_only() {
|
||||
// Without the incremental-read option the flow must keep its previous behavior, including
|
||||
// the auto-created sink layout: first timestamp column as time index and no primary keys.
|
||||
let (task, query_engine) = new_source_key_task(false).await;
|
||||
assert!(
|
||||
!task.config.simple_source_delta,
|
||||
"the row-local delta path must stay opt-in"
|
||||
);
|
||||
|
||||
let expr = task.gen_create_table_expr(query_engine).await.unwrap();
|
||||
assert!(
|
||||
expr.primary_keys.is_empty(),
|
||||
"an opt-out flow keeps the legacy keyless sink layout, got {:?}",
|
||||
expr.primary_keys
|
||||
);
|
||||
assert_eq!("ts", expr.time_index);
|
||||
|
||||
// The same query with the option enabled derives the source keys instead.
|
||||
let (task, query_engine) = new_source_key_task(true).await;
|
||||
assert!(task.config.simple_source_delta);
|
||||
let expr = task.gen_create_table_expr(query_engine).await.unwrap();
|
||||
assert_eq!(vec!["host".to_string()], expr.primary_keys);
|
||||
assert_eq!("ts", expr.time_index);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_rejects_time_dependent_filter() {
|
||||
// The engine retains the unoptimized plan because that is what a round executes. Here
|
||||
// `now()` must stay a stable scalar function instead of being constant-folded into a
|
||||
// literal, which would wrongly look like a deterministic row-local predicate.
|
||||
let (time_dependent, _, _) = new_simple_delta_task_with_optimize(
|
||||
"SELECT number, ts FROM numbers_with_ts WHERE ts <= now()",
|
||||
"SELECT number, ts FROM numbers_with_ts WHERE ts <= now()",
|
||||
Some(Duration::from_secs(60)),
|
||||
true,
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
!time_dependent.config.simple_source_delta,
|
||||
"a time-dependent filter must not be a row-local delta plan"
|
||||
);
|
||||
|
||||
// The same planning path still classifies a genuinely row-local predicate.
|
||||
let (row_local, _, _) = new_simple_delta_task_with_optimize(
|
||||
"SELECT number, ts FROM numbers_with_ts WHERE number > 1",
|
||||
"SELECT number, ts FROM numbers_with_ts WHERE number > 1",
|
||||
Some(Duration::from_secs(60)),
|
||||
true,
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
row_local.config.simple_source_delta,
|
||||
"a row-local predicate must still be classified"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_row_local_delta_rejects_memtable_only_fallback() {
|
||||
// `numbers_with_ts` is a mito table without `preserve_row_sequence`, so it only supports
|
||||
// the historical memtable-only incremental mode.
|
||||
let (task, _, _) = new_simple_delta_task(
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
Some(Duration::from_secs(60)),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert!(task.config.simple_source_delta);
|
||||
mark_incremental_with_dirty_window(&task);
|
||||
|
||||
let err = task
|
||||
.build_flow_query_extensions(true, true)
|
||||
.await
|
||||
.expect_err("a row-local delta flow must not fall back to memtable-only reads");
|
||||
let message = err.to_string();
|
||||
assert!(
|
||||
message.contains("row-local delta flow, which requires exact sequence-range reads"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(message.contains("preserve_row_sequence"), "{message}");
|
||||
|
||||
// The historical aggregate path is unchanged: it still selects memtable-only.
|
||||
let (aggregate_task, _, query_engine) = new_windowed_task(true).await;
|
||||
register_sink(&query_engine, "simple_delta_sink");
|
||||
mark_incremental_with_dirty_window(&aggregate_task);
|
||||
let extensions = aggregate_task
|
||||
.build_flow_query_extensions(true, true)
|
||||
.await
|
||||
.expect("an aggregate flow keeps the memtable-only fallback");
|
||||
assert!(
|
||||
extensions
|
||||
.iter()
|
||||
.any(|(key, value)| *key == FLOW_INCREMENTAL_MODE
|
||||
&& value == FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY),
|
||||
"{extensions:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_routes_incremental_state_to_delta() {
|
||||
let (task, sink_schema, query_engine) = new_simple_delta_task(
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
Some(Duration::from_secs(60)),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
// First round: no proven checkpoint yet, so it runs as a full snapshot.
|
||||
add_dirty_window(&task);
|
||||
let first = task
|
||||
.gen_query_with_time_window(query_engine.clone(), &sink_schema, &[], false, None)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("first round should generate a plan");
|
||||
assert!(
|
||||
matches!(first.coverage, QueryCoverage::UnfilteredFull),
|
||||
"first round must be a full snapshot"
|
||||
);
|
||||
|
||||
// Once watermarks proved a checkpoint, a new dirty signal runs as a source delta.
|
||||
mark_incremental_with_dirty_window(&task);
|
||||
let delta = task
|
||||
.gen_query_with_time_window(query_engine.clone(), &sink_schema, &[], false, None)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("incremental round should generate a plan");
|
||||
assert!(
|
||||
matches!(delta.coverage, QueryCoverage::IncrementalDelta),
|
||||
"incremental round must use IncrementalDelta"
|
||||
);
|
||||
assert!(task.state.read().unwrap().dirty_time_windows.is_empty());
|
||||
|
||||
// A forced full snapshot (durable recovery) stays a full snapshot.
|
||||
add_dirty_window(&task);
|
||||
let forced = task
|
||||
.gen_query_with_time_window_with_values(
|
||||
query_engine,
|
||||
&sink_schema,
|
||||
&[],
|
||||
false,
|
||||
None,
|
||||
&BTreeMap::new(),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("forced full snapshot should generate a plan");
|
||||
assert!(
|
||||
matches!(forced.coverage, QueryCoverage::UnfilteredFull),
|
||||
"forced full snapshot must not become a delta"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_windowed_plan_is_not_a_source_delta() {
|
||||
// A windowed plan carries a time-window expression, so it is never a source delta and
|
||||
// keeps its previous routing: scoped dirty-window repair when incremental reads are off,
|
||||
// and the existing aggregate-delta path when they are on.
|
||||
let (task, sink_schema, query_engine) = new_windowed_task(false).await;
|
||||
assert!(!task.config.simple_source_delta);
|
||||
mark_incremental_with_dirty_window(&task);
|
||||
{
|
||||
// Rewind the task to a non-incremental state without changing the query shape.
|
||||
let mut state = task.state.write().unwrap();
|
||||
state.disable_incremental();
|
||||
}
|
||||
let repair = task
|
||||
.gen_query_with_time_window(query_engine.clone(), &sink_schema, &[], false, Some(1))
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("windowed round should generate a plan");
|
||||
assert!(
|
||||
matches!(repair.coverage, QueryCoverage::ScopedBaseRepair),
|
||||
"a non-incremental windowed flow keeps its scoped repair, got {}",
|
||||
repair.plan
|
||||
);
|
||||
assert!(repair.plan.to_string().contains("Filter:"));
|
||||
|
||||
let (incremental_task, sink_schema, query_engine) = new_windowed_task(true).await;
|
||||
assert!(!incremental_task.config.simple_source_delta);
|
||||
mark_incremental_with_dirty_window(&incremental_task);
|
||||
let delta = incremental_task
|
||||
.gen_query_with_time_window(query_engine, &sink_schema, &[], false, Some(1))
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("windowed incremental round should generate a plan");
|
||||
assert!(
|
||||
matches!(delta.coverage, QueryCoverage::IncrementalDelta),
|
||||
"a windowed flow keeps the existing aggregate-delta path, got {}",
|
||||
delta.plan
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_prepare_plan_for_incremental_keeps_simple_plan() {
|
||||
let (task, _, query_engine) = new_simple_delta_task(
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
Some(Duration::from_secs(60)),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
mark_incremental_with_dirty_window(&task);
|
||||
|
||||
let plan = sql_to_df_plan(
|
||||
QueryContext::arc(),
|
||||
query_engine.clone(),
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let dml = dml_plan(plan.clone(), sink_table(&query_engine).await);
|
||||
let prepared = task
|
||||
.prepare_plan_for_incremental(&query_engine, &dml)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("a row-local plan is incremental safe unchanged");
|
||||
assert_eq!(dml, prepared);
|
||||
assert!(
|
||||
!task.state.read().unwrap().is_incremental_disabled(),
|
||||
"a supported simple plan must not disable incremental mode"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_prepare_plan_for_incremental_disables_join_plan() {
|
||||
let query =
|
||||
"SELECT a.number, a.ts FROM numbers_with_ts a JOIN numbers b ON a.number = b.number";
|
||||
let (task, _, query_engine) =
|
||||
new_simple_delta_task(query, query, Some(Duration::from_secs(60)), true).await;
|
||||
mark_incremental_with_dirty_window(&task);
|
||||
|
||||
let plan = sql_to_df_plan(QueryContext::arc(), query_engine.clone(), query, false)
|
||||
.await
|
||||
.unwrap();
|
||||
let dml = dml_plan(plan, sink_table(&query_engine).await);
|
||||
let prepared = task
|
||||
.prepare_plan_for_incremental(&query_engine, &dml)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(prepared.is_none(), "a join plan is not incremental safe");
|
||||
assert!(
|
||||
task.state.read().unwrap().is_incremental_disabled(),
|
||||
"an unsupported non-aggregate plan keeps the existing disable path"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple_source_delta_fails_closed_without_incremental_extensions() {
|
||||
let (task, _, query_engine) = new_simple_delta_task(
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
Some(Duration::from_secs(60)),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
// Incremental mode without any proven checkpoint: the extension list carries no
|
||||
// `FLOW_INCREMENTAL_MODE`, so a delta round must not execute.
|
||||
{
|
||||
let mut state = task.state.write().unwrap();
|
||||
state.advance_checkpoints(HashMap::new());
|
||||
assert!(state.checkpoints().is_empty());
|
||||
state
|
||||
.dirty_time_windows
|
||||
.add_window(Timestamp::new_second(0), Some(Timestamp::new_second(5)));
|
||||
}
|
||||
let dirty = task.state.read().unwrap().dirty_time_windows.clone();
|
||||
|
||||
let plan = sql_to_df_plan(
|
||||
QueryContext::arc(),
|
||||
query_engine.clone(),
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let dml = dml_plan(plan, sink_table(&query_engine).await);
|
||||
let (frontend_client, _handler) =
|
||||
FrontendClient::from_empty_grpc_handler(QueryOptions::default());
|
||||
let frontend_client = Arc::new(frontend_client);
|
||||
|
||||
let result = task
|
||||
.execute_plan_unlocked(
|
||||
&query_engine,
|
||||
&frontend_client,
|
||||
&dml,
|
||||
&DirtyRestore::Unscoped(dirty),
|
||||
&QueryCoverage::IncrementalDelta,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
result.is_none(),
|
||||
"a delta round without incremental extensions must not execute"
|
||||
);
|
||||
let state = task.state.read().unwrap();
|
||||
assert_eq!(1, state.dirty_time_windows.len(), "dirty work is restored");
|
||||
assert_eq!(
|
||||
CheckpointMode::Incremental,
|
||||
state.checkpoint_mode(),
|
||||
"skipping the round keeps incremental retryable"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +118,8 @@ impl BatchingTask {
|
||||
/// rewritten delta-LEFT-JOIN-sink merge plan or the original plan. In
|
||||
/// particular, plain GROUP BY queries with no aggregate merge columns are
|
||||
/// incremental safe without a rewrite, so they return `Some(original_plan)`.
|
||||
/// Opt-in row-local single-source flows (`simple_source_delta`) are also
|
||||
/// incremental safe unchanged.
|
||||
pub(super) async fn prepare_plan_for_incremental(
|
||||
&self,
|
||||
engine: &QueryEngineRef,
|
||||
@@ -151,6 +153,12 @@ impl BatchingTask {
|
||||
// until separately supported, and incremental mode is permanently
|
||||
// disabled for this flow.
|
||||
let Some(analysis) = analyze_incremental_aggregate_plan(&inner_plan)? else {
|
||||
// A row-local single-source projection/filter is already safe to execute unfiltered:
|
||||
// source correctness comes from the sequence-range scan, and sink primary-key write
|
||||
// semantics make replayed rows idempotent.
|
||||
if self.config.simple_source_delta {
|
||||
return Ok(Some(plan.clone()));
|
||||
}
|
||||
warn!(
|
||||
"Flow {} incremental mode but plan is not an aggregate query; \
|
||||
permanently disabling incremental for this flow",
|
||||
@@ -309,6 +317,17 @@ impl BatchingTask {
|
||||
}
|
||||
.build());
|
||||
}
|
||||
// A row-local delta flow cannot use the memtable-only fallback: rows flushed to SST
|
||||
// between rounds would be silently skipped, losing data from a plain projection.
|
||||
if self.config.simple_source_delta && !capable {
|
||||
return Err(UnexpectedSnafu {
|
||||
reason: format!(
|
||||
"Flow {} is a row-local delta flow, which requires exact sequence-range reads, but a source table lacks the Mito preserve_row_sequence capability",
|
||||
self.config.flow_id
|
||||
),
|
||||
}
|
||||
.build());
|
||||
}
|
||||
let sink_table_id = self.sink_table_id().await?;
|
||||
let incremental_mode = if capable {
|
||||
debug!(
|
||||
|
||||
@@ -2984,7 +2984,12 @@ async fn test_sequence_range_producer_keeps_memtable_only_for_non_mito_source()
|
||||
)
|
||||
.await;
|
||||
configure_source_capability(&parts.query_engine, "file", true).await;
|
||||
let task = parts.task;
|
||||
let mut task = parts.task;
|
||||
// Covers the aggregate producer's memtable-only fallback; the row-local delta path rejects
|
||||
// that fallback instead of silently skipping SST rows.
|
||||
Arc::get_mut(&mut task.config)
|
||||
.expect("test task config should be uniquely owned")
|
||||
.simple_source_delta = false;
|
||||
task.state
|
||||
.write()
|
||||
.unwrap()
|
||||
@@ -3011,12 +3016,17 @@ async fn test_sequence_range_producer_keeps_memtable_only_for_non_mito_source()
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_build_flow_query_extensions_switches_with_checkpoint_mode() {
|
||||
let (task, _) = new_test_task_engine_and_plan_with_query(
|
||||
let (mut task, _) = new_test_task_engine_and_plan_with_query(
|
||||
"SELECT number, ts FROM numbers_with_ts",
|
||||
"numbers_with_ts",
|
||||
)
|
||||
.await
|
||||
.into_task_and_plan();
|
||||
// This test covers the aggregate extension producer, whose memtable-only fallback stays
|
||||
// unchanged. The row-local delta path rejects that fallback, so it is not under test here.
|
||||
Arc::get_mut(&mut task.config)
|
||||
.expect("test task config should be uniquely owned")
|
||||
.simple_source_delta = false;
|
||||
|
||||
let extensions = task.build_flow_query_extensions(false, true).await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -4024,9 +4034,16 @@ async fn test_auto_created_sql_aggregate_sink_reaches_incremental_safe() {
|
||||
let sink_table = "auto_created_aggregate_sink";
|
||||
let query = "SELECT max(number) AS number, ts FROM numbers_with_ts GROUP BY ts";
|
||||
let TestTaskParts {
|
||||
task, query_engine, ..
|
||||
mut task,
|
||||
query_engine,
|
||||
..
|
||||
} = new_test_task_engine_and_plan_with_query(query, sink_table).await;
|
||||
register_auto_created_aggregate_sink(&query_engine, sink_table);
|
||||
// The shared helper retains a plain projection plan, but this test covers the aggregate
|
||||
// extension producer, so it must not be classified as a row-local delta flow.
|
||||
Arc::get_mut(&mut task.config)
|
||||
.expect("test task config should be uniquely owned")
|
||||
.simple_source_delta = false;
|
||||
|
||||
let ctx = task.state.read().unwrap().query_ctx.clone();
|
||||
let plan = sql_to_df_plan(ctx, query_engine.clone(), query, true)
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
-- A plain projection/filter flow without a time window reads only source rows
|
||||
-- written since the last checkpoint when incremental reads are opted in.
|
||||
--
|
||||
-- `ADMIN FLUSH_FLOW` returns the number of rows the round wrote to the sink, so
|
||||
-- the numbers below are the assertion that a round read only the delta: a round
|
||||
-- that rescanned history would rewrite every already-materialized row
|
||||
-- (2 + 2 = 4 after the second round instead of 2).
|
||||
--
|
||||
-- The source must be append-only and preserve row sequence. The sink is a keyed
|
||||
-- materialization: two rows sharing the sink key collapse.
|
||||
CREATE TABLE flow_incremental_simple_input (
|
||||
host STRING,
|
||||
val DOUBLE,
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
PRIMARY KEY(host)
|
||||
) WITH (
|
||||
append_mode = 'true',
|
||||
preserve_row_sequence = 'true'
|
||||
);
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- A long interval keeps every round explicit, so the row counts are stable.
|
||||
CREATE FLOW flow_incremental_simple
|
||||
SINK TO flow_incremental_simple_sink
|
||||
EVAL INTERVAL '1h'
|
||||
WITH (experimental_enable_incremental_read = 'true')
|
||||
AS
|
||||
SELECT host, val, ts FROM flow_incremental_simple_input WHERE val >= 0;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- Both hosts share one timestamp, so the sink keeps two rows and its time index
|
||||
-- is the source time index rather than the first timestamp column it finds.
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_a', 1.0, '2024-01-01 00:00:00'),
|
||||
('host_b', 2.0, '2024-01-01 00:00:00');
|
||||
|
||||
Affected Rows: 2
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
+---------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('flow_incremental_simple') |
|
||||
+---------------------------------------------+
|
||||
| 2 |
|
||||
+---------------------------------------------+
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
+--------+-----+---------------------+
|
||||
| host | val | ts |
|
||||
+--------+-----+---------------------+
|
||||
| host_a | 1.0 | 2024-01-01T00:00:00 |
|
||||
| host_b | 2.0 | 2024-01-01T00:00:00 |
|
||||
+--------+-----+---------------------+
|
||||
|
||||
SHOW CREATE TABLE flow_incremental_simple_sink;
|
||||
|
||||
+------------------------------+-------------------------------------------------------------+
|
||||
| Table | Create Table |
|
||||
+------------------------------+-------------------------------------------------------------+
|
||||
| flow_incremental_simple_sink | CREATE TABLE IF NOT EXISTS "flow_incremental_simple_sink" ( |
|
||||
| | "host" STRING NULL, |
|
||||
| | "val" DOUBLE NULL, |
|
||||
| | "ts" TIMESTAMP(3) NOT NULL, |
|
||||
| | "update_at" TIMESTAMP(3) NULL, |
|
||||
| | TIME INDEX ("ts"), |
|
||||
| | PRIMARY KEY ("host") |
|
||||
| | ) |
|
||||
| | |
|
||||
| | ENGINE=mito |
|
||||
| | WITH( |
|
||||
| | 'comment' = 'Auto created table by flow engine' |
|
||||
| | ) |
|
||||
+------------------------------+-------------------------------------------------------------+
|
||||
|
||||
-- Move the checkpointed source rows into SST files so the next round must use
|
||||
-- the exact sequence range instead of rescanning them.
|
||||
ADMIN FLUSH_TABLE('flow_incremental_simple_sink');
|
||||
|
||||
+---------------------------------------------------+
|
||||
| ADMIN FLUSH_TABLE('flow_incremental_simple_sink') |
|
||||
+---------------------------------------------------+
|
||||
| 0 |
|
||||
+---------------------------------------------------+
|
||||
|
||||
ADMIN FLUSH_TABLE('flow_incremental_simple_input');
|
||||
|
||||
+----------------------------------------------------+
|
||||
| ADMIN FLUSH_TABLE('flow_incremental_simple_input') |
|
||||
+----------------------------------------------------+
|
||||
| 0 |
|
||||
+----------------------------------------------------+
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_a', 3.0, '2024-01-01 00:01:00'),
|
||||
('host_c', 4.0, '2024-01-01 00:01:00');
|
||||
|
||||
Affected Rows: 2
|
||||
|
||||
ADMIN FLUSH_TABLE('flow_incremental_simple_input');
|
||||
|
||||
+----------------------------------------------------+
|
||||
| ADMIN FLUSH_TABLE('flow_incremental_simple_input') |
|
||||
+----------------------------------------------------+
|
||||
| 0 |
|
||||
+----------------------------------------------------+
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
+---------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('flow_incremental_simple') |
|
||||
+---------------------------------------------+
|
||||
| 2 |
|
||||
+---------------------------------------------+
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
+--------+-----+---------------------+
|
||||
| host | val | ts |
|
||||
+--------+-----+---------------------+
|
||||
| host_a | 1.0 | 2024-01-01T00:00:00 |
|
||||
| host_a | 3.0 | 2024-01-01T00:01:00 |
|
||||
| host_b | 2.0 | 2024-01-01T00:00:00 |
|
||||
| host_c | 4.0 | 2024-01-01T00:01:00 |
|
||||
+--------+-----+---------------------+
|
||||
|
||||
-- A fully filtered round writes nothing; its scan still proves a watermark, so
|
||||
-- the checkpoint advances and the following insert must be processed.
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_a', -1.0, '2024-01-01 00:02:00');
|
||||
|
||||
Affected Rows: 1
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
+---------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('flow_incremental_simple') |
|
||||
+---------------------------------------------+
|
||||
| 0 |
|
||||
+---------------------------------------------+
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
+--------+-----+---------------------+
|
||||
| host | val | ts |
|
||||
+--------+-----+---------------------+
|
||||
| host_a | 1.0 | 2024-01-01T00:00:00 |
|
||||
| host_a | 3.0 | 2024-01-01T00:01:00 |
|
||||
| host_b | 2.0 | 2024-01-01T00:00:00 |
|
||||
| host_c | 4.0 | 2024-01-01T00:01:00 |
|
||||
+--------+-----+---------------------+
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_d', 5.0, '2024-01-01 00:03:00');
|
||||
|
||||
Affected Rows: 1
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
+---------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('flow_incremental_simple') |
|
||||
+---------------------------------------------+
|
||||
| 1 |
|
||||
+---------------------------------------------+
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
+--------+-----+---------------------+
|
||||
| host | val | ts |
|
||||
+--------+-----+---------------------+
|
||||
| host_a | 1.0 | 2024-01-01T00:00:00 |
|
||||
| host_a | 3.0 | 2024-01-01T00:01:00 |
|
||||
| host_b | 2.0 | 2024-01-01T00:00:00 |
|
||||
| host_c | 4.0 | 2024-01-01T00:01:00 |
|
||||
| host_d | 5.0 | 2024-01-01T00:03:00 |
|
||||
+--------+-----+---------------------+
|
||||
|
||||
-- Without the opt-in option a window-less flow keeps rescanning history: the same
|
||||
-- second round rewrites all four rows instead of only the two new ones.
|
||||
CREATE FLOW flow_incremental_simple_full
|
||||
SINK TO flow_incremental_simple_full_sink
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT host, val, ts FROM flow_incremental_simple_input WHERE val >= 0;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_e', 6.0, '2024-01-01 00:04:00');
|
||||
|
||||
Affected Rows: 1
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple_full');
|
||||
|
||||
+--------------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('flow_incremental_simple_full') |
|
||||
+--------------------------------------------------+
|
||||
| 6 |
|
||||
+--------------------------------------------------+
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_full_sink ORDER BY host, ts;
|
||||
|
||||
+--------+-----+---------------------+
|
||||
| host | val | ts |
|
||||
+--------+-----+---------------------+
|
||||
| host_b | 2.0 | 2024-01-01T00:00:00 |
|
||||
| host_c | 4.0 | 2024-01-01T00:01:00 |
|
||||
| host_d | 5.0 | 2024-01-01T00:03:00 |
|
||||
| host_e | 6.0 | 2024-01-01T00:04:00 |
|
||||
+--------+-----+---------------------+
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_f', 7.0, '2024-01-01 00:05:00');
|
||||
|
||||
Affected Rows: 1
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple_full');
|
||||
|
||||
+--------------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('flow_incremental_simple_full') |
|
||||
+--------------------------------------------------+
|
||||
| 7 |
|
||||
+--------------------------------------------------+
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_full_sink ORDER BY host, ts;
|
||||
|
||||
+--------+-----+---------------------+
|
||||
| host | val | ts |
|
||||
+--------+-----+---------------------+
|
||||
| host_b | 2.0 | 2024-01-01T00:00:00 |
|
||||
| host_c | 4.0 | 2024-01-01T00:01:00 |
|
||||
| host_d | 5.0 | 2024-01-01T00:03:00 |
|
||||
| host_e | 6.0 | 2024-01-01T00:04:00 |
|
||||
| host_f | 7.0 | 2024-01-01T00:05:00 |
|
||||
+--------+-----+---------------------+
|
||||
|
||||
DROP FLOW flow_incremental_simple;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP FLOW flow_incremental_simple_full;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE flow_incremental_simple_input;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE flow_incremental_simple_sink;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE flow_incremental_simple_full_sink;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
-- A plain projection/filter flow without a time window reads only source rows
|
||||
-- written since the last checkpoint when incremental reads are opted in.
|
||||
--
|
||||
-- `ADMIN FLUSH_FLOW` returns the number of rows the round wrote to the sink, so
|
||||
-- the numbers below are the assertion that a round read only the delta: a round
|
||||
-- that rescanned history would rewrite every already-materialized row
|
||||
-- (2 + 2 = 4 after the second round instead of 2).
|
||||
--
|
||||
-- The source must be append-only and preserve row sequence. The sink is a keyed
|
||||
-- materialization: two rows sharing the sink key collapse.
|
||||
CREATE TABLE flow_incremental_simple_input (
|
||||
host STRING,
|
||||
val DOUBLE,
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
PRIMARY KEY(host)
|
||||
) WITH (
|
||||
append_mode = 'true',
|
||||
preserve_row_sequence = 'true'
|
||||
);
|
||||
|
||||
-- A long interval keeps every round explicit, so the row counts are stable.
|
||||
CREATE FLOW flow_incremental_simple
|
||||
SINK TO flow_incremental_simple_sink
|
||||
EVAL INTERVAL '1h'
|
||||
WITH (experimental_enable_incremental_read = 'true')
|
||||
AS
|
||||
SELECT host, val, ts FROM flow_incremental_simple_input WHERE val >= 0;
|
||||
|
||||
-- Both hosts share one timestamp, so the sink keeps two rows and its time index
|
||||
-- is the source time index rather than the first timestamp column it finds.
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_a', 1.0, '2024-01-01 00:00:00'),
|
||||
('host_b', 2.0, '2024-01-01 00:00:00');
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
SHOW CREATE TABLE flow_incremental_simple_sink;
|
||||
|
||||
-- Move the checkpointed source rows into SST files so the next round must use
|
||||
-- the exact sequence range instead of rescanning them.
|
||||
ADMIN FLUSH_TABLE('flow_incremental_simple_sink');
|
||||
ADMIN FLUSH_TABLE('flow_incremental_simple_input');
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_a', 3.0, '2024-01-01 00:01:00'),
|
||||
('host_c', 4.0, '2024-01-01 00:01:00');
|
||||
|
||||
ADMIN FLUSH_TABLE('flow_incremental_simple_input');
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
-- A fully filtered round writes nothing; its scan still proves a watermark, so
|
||||
-- the checkpoint advances and the following insert must be processed.
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_a', -1.0, '2024-01-01 00:02:00');
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_d', 5.0, '2024-01-01 00:03:00');
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple');
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_sink ORDER BY host, ts;
|
||||
|
||||
-- Without the opt-in option a window-less flow keeps rescanning history: the same
|
||||
-- second round rewrites all four rows instead of only the two new ones.
|
||||
CREATE FLOW flow_incremental_simple_full
|
||||
SINK TO flow_incremental_simple_full_sink
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT host, val, ts FROM flow_incremental_simple_input WHERE val >= 0;
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_e', 6.0, '2024-01-01 00:04:00');
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple_full');
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_full_sink ORDER BY host, ts;
|
||||
|
||||
INSERT INTO flow_incremental_simple_input VALUES
|
||||
('host_f', 7.0, '2024-01-01 00:05:00');
|
||||
|
||||
ADMIN FLUSH_FLOW('flow_incremental_simple_full');
|
||||
|
||||
SELECT host, val, ts FROM flow_incremental_simple_full_sink ORDER BY host, ts;
|
||||
|
||||
DROP FLOW flow_incremental_simple;
|
||||
DROP FLOW flow_incremental_simple_full;
|
||||
DROP TABLE flow_incremental_simple_input;
|
||||
DROP TABLE flow_incremental_simple_sink;
|
||||
DROP TABLE flow_incremental_simple_full_sink;
|
||||
Reference in New Issue
Block a user