diff --git a/Cargo.lock b/Cargo.lock index 78f9cf02e81..2e13ca319c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5509,7 +5509,6 @@ dependencies = [ "datafusion-physical-expr", "datatypes", "futures", - "get-size2", "greptime-proto", "hostname 0.4.1", "humantime-serde", @@ -6056,12 +6055,6 @@ dependencies = [ "libm", ] -[[package]] -name = "get-size2" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b5034f0cabe33ffe2b0c193e283568fb0ebe93fe93f05b424ed1b751d2cf42b" - [[package]] name = "getopts" version = "0.2.23" diff --git a/src/cmd/src/standalone.rs b/src/cmd/src/standalone.rs index 0521aa9404f..0ef0d494d2e 100644 --- a/src/cmd/src/standalone.rs +++ b/src/cmd/src/standalone.rs @@ -59,7 +59,7 @@ use datanode::config::{DatanodeOptions, StorageConfig}; use datanode::datanode::{Datanode, DatanodeBuilder}; use datanode::region_server::RegionServer; use flow::{ - FlowDualEngineRef, FlownodeBuilder, FlownodeInstance, FlownodeOptions, FrontendClient, + FlownodeBuilder, FlownodeEngineRef, FlownodeInstance, FlownodeOptions, FrontendClient, GrpcQueryHandlerWithBoxedError, }; use frontend::frontend::Frontend; @@ -958,7 +958,7 @@ pub struct LeaderServicesContext { pub kv_backend: KvBackendRef, pub cache_registry: LayeredCacheRegistryRef, pub catalog_manager: CatalogManagerRef, - pub flow_engine: FlowDualEngineRef, + pub flow_engine: FlownodeEngineRef, pub frontend_client: Arc, pub node_id: Option, pub init_regions_parallelism: usize, diff --git a/src/flow/AGENTS.md b/src/flow/AGENTS.md index 266621f508f..5b098d944b8 100644 --- a/src/flow/AGENTS.md +++ b/src/flow/AGENTS.md @@ -7,29 +7,33 @@ Repo-wide rules that apply to here: [`.agents/architecture-invariants.md`](../.. ## What this crate does -Flownode provides two flow profiles: +Flownode runs **one** flow execution profile: the batching scheduler. -- **Streaming mode**: a single stateless DataFusion query profile. Each mirror - insert is materialized as a transient input table, executed against the - retained logical plan, and written directly to the sink through - `batching_mode::frontend_client::FrontendClient`. -- **Batching mode**: splits data into time windows and periodically runs - aggregation SQL through the frontend, writing results back to a sink table. +- **Batching mode** (`batching_mode`): splits data into time windows and + periodically runs aggregation SQL through the frontend, writing results back + to a sink table. A flow whose SQL has no usable time window runs as an + explicit full-query flow and needs `EVAL INTERVAL`. -Users cannot select a mode directly: `flow_type` is a reserved internal option. +The legacy streaming executor (per-insert stateless DataFusion query) has been +removed. There is no mode selection left: `FlowEngine` in +`src/flow/src/engine.rs` is implemented by `FlownodeEngine` +(`adapter/flownode_impl.rs`), which forwards everything to `BatchingEngine`. `StatementExecutor::determine_flow_type` in `src/operator/src/statement/ddl.rs` -owns current mode selection. `FlowDualEngine` defaults missing internal -`flow_type` metadata to batching for compatibility. Read those paths before -changing routing rules. +now only *validates* a flow definition and always reports batching. + +Historical `flow_type: streaming` metadata stays readable and droppable, but it +must never reach a runtime: `FlownodeEngine::create_flow` rejects it with a +"recreate this flow" error. Do not delete `FlowType::Streaming` or +`get_flow_type_from_options` — old persisted options and old procedure data +must keep deserializing. ## Module map | Module | Path | Purpose | | --- | --- | --- | | `engine` | `src/flow/src/engine.rs` | `FlowEngine` lifecycle contract | -| `adapter` | `src/flow/src/adapter.rs`, `src/flow/src/adapter/` | Stateless streaming execution, dual-engine dispatch, shared source schema/default normalization, and sink creation | +| `adapter` | `src/flow/src/adapter.rs`, `src/flow/src/adapter/` | `FlownodeEngine` (create/drop/flush/recover, insert routing), auto-column constants shared with batching, and the retained-plan → sink-schema helper | | `batching_mode` | `src/flow/src/batching_mode.rs`, `src/flow/src/batching_mode/` | `BatchingEngine`, scheduling, time windows, frontend client, and checkpoints | -| `repr` | `src/flow/src/repr.rs` | Shared row and relation schema representations | | `server` | `src/flow/src/server.rs` | gRPC `Flow` service and flownode builders | | `heartbeat` | `src/flow/src/heartbeat.rs` | Reports flownode state/stats to metasrv | @@ -38,24 +42,22 @@ Flow metadata lives in `common-meta`, not here: ## Data flow -`Frontend → Flownode (gRPC)` → `FlowService` (`server.rs`) → `FlowDualEngine` -(`adapter/flownode_impl.rs`) routes by `FlowType`: +`Frontend → Flownode (gRPC)` → `FlowService` (`server.rs`) → `FlownodeEngine` +(`adapter/flownode_impl.rs`) → `BatchingEngine`. -- Streaming: mirror rows are normalized against the source schema, evaluated by - the retained stateless DataFusion plan, and sent to the sink via - `FrontendClient`. -- Batching: marks dirty windows; a task later runs aggregation SQL via the - frontend client and writes the sink table. - -`FlowType::Streaming` and mirror routing are shared contracts; preserve both -when changing dispatch. Preserve batching behavior and the shared schema, -default, and sink-creation helpers. +- `FlowService::handle_mirror_request` → `FlowEngine::handle_flow_inserts` → + `BatchingEngine::handle_inserts_inner`. The mirrored full-row payload is how + batching marks dirty windows (and `set_dirty()` for flows without a time + window). **Keep this RPC and this path**: it is not a leftover of the removed + streaming executor. +- A flow round later runs its SQL through the frontend client and writes the + sink table. ## Public surface - gRPC `Flow` service in `src/flow/src/server.rs`. -- Local streaming sink writes and batching query execution use `Channel::Internal` - so meter collectors can account for sink writes without charging ingestion quota. +- Batching query execution uses `Channel::Internal` so meter collectors can + account for sink writes without charging ingestion quota. - `FlowEngine` trait in `src/flow/src/engine.rs`. - Started from the `cmd` crate via `FlownodeBuilder` / `FlownodeInstance`. @@ -65,12 +67,18 @@ default, and sink-creation helpers. cargo nextest run -p flow ``` -Stateless streaming tests are under `src/flow/src/adapter/stateless.rs`. +There are no stateless streaming tests left; adapter tests cover the retained +plan-to-schema helper shared with batching. ## Gotchas -- Batching and streaming differ in latency and state. Confirm the selected mode - before reasoning about a flow. -- Streaming is finite and stateless per mirror request; it has no worker graph, - background runtime, or replay state. - Internal flow timestamps and table time columns are separate contracts. +- `adapter.rs` still owns `AUTO_CREATED_PLACEHOLDER_TS_COL` / + `AUTO_CREATED_UPDATE_AT_TS_COL` and `output_column_schemas`; batching imports + them. Do not move or delete them without updating `batching_mode`. +- Recovery collects per-flow errors and logs them + (`adapter/flownode_impl.rs`): one rejected (old streaming) flow must not stop + the other flows from recovering. +- `flow_type` is still written into flow options so the metadata shape does not + change; it is a reserved internal key and must stay out of `SHOW CREATE FLOW` + rendering. diff --git a/src/flow/Cargo.toml b/src/flow/Cargo.toml index 2d9ff283aa2..2d393f327e5 100644 --- a/src/flow/Cargo.toml +++ b/src/flow/Cargo.toml @@ -39,7 +39,6 @@ datafusion-expr.workspace = true datafusion-physical-expr.workspace = true datatypes.workspace = true futures.workspace = true -get-size2 = "0.1.2" greptime-proto.workspace = true hostname.workspace = true humantime-serde.workspace = true diff --git a/src/flow/src/adapter.rs b/src/flow/src/adapter.rs index 5b15ad0a93c..ed0bbd50423 100644 --- a/src/flow/src/adapter.rs +++ b/src/flow/src/adapter.rs @@ -12,59 +12,29 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Flow source schema management and stateless streaming execution. - -use std::collections::BTreeMap; -use std::sync::Arc; -#[cfg(test)] -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::{AtomicBool, Ordering}; +//! Flow node configuration and the plan-to-schema helpers shared with batching mode. use common_base::memory_limit::MemoryLimit; use common_config::Configurable; use common_error::ext::BoxedError; -use common_meta::distributed_time_constants::BASE_HEARTBEAT_INTERVAL; -use common_meta::key::TableMetadataManagerRef; use common_options::memory::MemoryOptions; use common_recordbatch::map_dictionary_to_values_data_type; use common_stat::get_total_cpu_cores; use common_telemetry::logging::{LoggingOptions, TracingOptions}; -use common_telemetry::{error, info}; -use datafusion_common::TableReference; -use datafusion_common::tree_node::TreeNode; use datafusion_expr::logical_plan::Distinct; use datafusion_expr::{Expr, LogicalPlan}; use datatypes::schema::{ColumnSchema, SchemaRef}; -use itertools::Itertools; use meta_client::MetaClientOptions; -use query::QueryEngine; use query::options::QueryOptions; use serde::{Deserialize, Serialize}; use servers::grpc::GrpcOptions; use servers::http::HttpOptions; -use snafu::{IntoError, OptionExt, ResultExt, ensure}; -use store_api::storage::{ConcreteDataType, RegionId}; -use tokio::sync::RwLock; -use tokio::time::Instant; +use snafu::ResultExt; -use crate::adapter::stateless::StatelessFlow; -use crate::adapter::table_source::ManagedTableSource; -use crate::adapter::util::{ - relation_desc_to_column_schemas_with_fallback, table_info_value_to_relation_desc, -}; use crate::batching_mode::BatchingModeOptions; -use crate::batching_mode::frontend_client::FrontendClient; -use crate::batching_mode::utils::sql_to_df_plan; -use crate::error::{ - DatafusionSnafu, Error, ExternalSnafu, FlowNotFoundSnafu, InsertIntoFlowSnafu, InternalSnafu, - InvalidQuerySnafu, UnexpectedSnafu, -}; -use crate::repr::{ColumnType, DiffRow, RelationDesc, Row}; -use crate::{CreateFlowArgs, FlowId, TableName}; +use crate::error::{Error, ExternalSnafu}; pub(crate) mod flownode_impl; -pub(crate) mod stateless; -pub(crate) mod table_source; #[cfg(test)] mod tests; pub(crate) mod util; @@ -137,249 +107,13 @@ fn output_column_schemas( Ok((columns, lineage)) } -fn relation_desc_from_output( - columns: &[ColumnSchema], - lineage: &[Option], - source_primary_key_indices: &[usize], - plan: &LogicalPlan, -) -> RelationDesc { - let mut keys = source_primary_key_indices - .iter() - .filter_map(|source_index| { - lineage - .iter() - .position(|index| index == &Some(*source_index)) - }) - .collect_vec(); - // DISTINCT defines identity from every output tuple; the source timestamp participates - // separately as the relation time index, so it is excluded from the tag key. - if matches!(plan, LogicalPlan::Distinct(Distinct::All(_))) { - keys = columns - .iter() - .positions(|column| !column.is_time_index()) - .collect(); - } - let time_index = columns.iter().position(ColumnSchema::is_time_index); - RelationDesc { - typ: crate::repr::RelationType { - column_types: columns - .iter() - .map(|column| ColumnType::new(column.data_type.clone(), column.is_nullable())) - .collect(), - keys: if keys.is_empty() { - vec![] - } else { - vec![crate::repr::Key::from(keys)] - }, - time_index, - auto_columns: vec![], - }, - names: columns - .iter() - .map(|column| Some(column.name.clone())) - .collect(), - } -} - fn default_num_workers() -> usize { get_total_cpu_cores().div_ceil(2) } -/// Returns whether an existing sink uses the legacy explicit source-time-index layout. -/// -/// This check is deliberately separate from [`resolve_sink_layout`]: ordinary auto-column -/// resolution remains the first choice, and this compatibility path is only for a sink whose -/// trailing column is a real, user-defined time index. -pub(crate) fn is_explicit_source_timestamp_compatibility( - output_schema: &[ColumnSchema], - output_lineage: &[Option], - sink_schema: &[ColumnSchema], - source_schema: &SchemaRef, -) -> bool { - if sink_schema.len() != output_schema.len() + 1 || output_lineage.len() != output_schema.len() { - return false; - } - if !output_schema - .iter() - .zip(&sink_schema[..output_schema.len()]) - .all(|(output, sink)| output.data_type == sink.data_type) - { - return false; - } - - let Some(source_timestamp_index) = source_schema.timestamp_index() else { - return false; - }; - let sink_timestamp = &sink_schema[output_schema.len()]; - sink_timestamp.data_type == source_schema.column_schemas()[source_timestamp_index].data_type - && sink_timestamp.data_type.is_timestamp() - && sink_timestamp.is_time_index() - && sink_timestamp.default_constraint().is_some() - && sink_timestamp.name != AUTO_CREATED_UPDATE_AT_TS_COL - && sink_timestamp.name != AUTO_CREATED_PLACEHOLDER_TS_COL - && !output_lineage.contains(&Some(source_timestamp_index)) -} - pub const AUTO_CREATED_PLACEHOLDER_TS_COL: &str = "__ts_placeholder"; pub const AUTO_CREATED_UPDATE_AT_TS_COL: &str = "update_at"; -/// Resolves the columns appended by the flow, validating the complete output/sink layout. -/// -/// A sink with the same arity as the query is an ordinary sink, even when its last -/// column happens to be named `update_at`. Auto columns are only inferred from the -/// arity difference and their exact trailing layout. -pub(crate) fn resolve_sink_layout( - output_schema: &[ColumnSchema], - sink_schema: &[ColumnSchema], -) -> Result, Error> { - ensure!( - sink_schema.len() >= output_schema.len() && sink_schema.len() - output_schema.len() <= 2, - InvalidQuerySnafu { - reason: format!( - "Flow output has {} columns, but sink has {} columns; only zero, one, or two trailing auto columns are supported", - output_schema.len(), - sink_schema.len() - ) - } - ); - let suffix_len = sink_schema.len() - output_schema.len(); - for (idx, (output, sink)) in output_schema.iter().zip(sink_schema.iter()).enumerate() { - ensure!( - output.data_type == sink.data_type, - InvalidQuerySnafu { - reason: format!( - "Flow output column {idx} has type {:?}, but sink column {} has type {:?}", - output.data_type, sink.name, sink.data_type - ) - } - ); - } - let suffix = &sink_schema[output_schema.len()..]; - match suffix_len { - 0 => Ok(vec![]), - 1 => { - let column = &suffix[0]; - ensure!( - column.name == AUTO_CREATED_UPDATE_AT_TS_COL && column.data_type.is_timestamp(), - InvalidQuerySnafu { - reason: format!( - "The trailing sink column must be timestamp {}", - AUTO_CREATED_UPDATE_AT_TS_COL - ) - } - ); - Ok(suffix.to_vec()) - } - 2 => { - let update_at = &suffix[0]; - let placeholder = &suffix[1]; - ensure!( - update_at.name == AUTO_CREATED_UPDATE_AT_TS_COL - && update_at.data_type.is_timestamp() - && placeholder.name == AUTO_CREATED_PLACEHOLDER_TS_COL - && placeholder.data_type.is_timestamp() - && placeholder.is_time_index(), - InvalidQuerySnafu { - reason: "The two trailing sink columns must be timestamp update_at followed by timestamp time-index __ts_placeholder".to_string() - } - ); - Ok(suffix.to_vec()) - } - _ => unreachable!(), - } -} - -/// Legacy helper for callers that only have a sink schema. New stateless flows -/// resolve the suffix against both schemas and store it in `StatelessFlow`. -pub(crate) fn sink_output_column_count(sink_schema: &[ColumnSchema]) -> Result { - let mut count = sink_schema.len(); - if sink_schema - .last() - .is_some_and(|column| column.name == AUTO_CREATED_PLACEHOLDER_TS_COL) - { - let placeholder = &sink_schema[count - 1]; - ensure!( - placeholder.data_type.is_timestamp() && placeholder.is_time_index(), - InvalidQuerySnafu { - reason: format!( - "Auto-created sink column {} must be a timestamp time index", - AUTO_CREATED_PLACEHOLDER_TS_COL - ) - } - ); - count -= 1; - } - if sink_schema - .get(count.saturating_sub(1)) - .is_some_and(|column| column.name == AUTO_CREATED_UPDATE_AT_TS_COL) - { - ensure!( - sink_schema[count - 1].data_type.is_timestamp(), - InvalidQuerySnafu { - reason: format!( - "Auto-created sink column {} must be a timestamp", - AUTO_CREATED_UPDATE_AT_TS_COL - ) - } - ); - count -= 1; - } - Ok(count) -} - -pub(crate) fn validate_sink_layout( - output_schema: &[ColumnSchema], - sink_schema: &[ColumnSchema], -) -> Result<(), Error> { - resolve_sink_layout(output_schema, sink_schema).map(|_| ()) -} - -pub(crate) fn validate_auto_column_names(output_schema: &[ColumnSchema]) -> Result<(), Error> { - for column in output_schema { - ensure!( - column.name != AUTO_CREATED_UPDATE_AT_TS_COL - && column.name != AUTO_CREATED_PLACEHOLDER_TS_COL, - InvalidQuerySnafu { - reason: format!( - "Flow output column {} is reserved for an auto-created sink column", - column.name - ) - } - ); - } - Ok(()) -} - -pub(crate) fn validate_sink_layout_with_suffix( - output_schema: &[ColumnSchema], - sink_schema: &[ColumnSchema], - suffix: &[ColumnSchema], -) -> Result<(), Error> { - ensure!( - sink_schema.len() == output_schema.len() + suffix.len() - && sink_schema[output_schema.len()..] == *suffix, - InvalidQuerySnafu { - reason: "Stored sink auto-column layout no longer matches the sink schema".to_string() - } - ); - for (idx, (output, sink)) in output_schema - .iter() - .zip(&sink_schema[..output_schema.len()]) - .enumerate() - { - ensure!( - output.data_type == sink.data_type, - InvalidQuerySnafu { - reason: format!( - "Flow output column {idx} has type {:?}, but sink column {} has type {:?}", - output.data_type, sink.name, sink.data_type - ) - } - ); - } - Ok(()) -} - #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(default)] pub struct FlowConfig { @@ -441,809 +175,3 @@ impl Configurable for FlownodeOptions { Ok(()) } } - -pub type FlowStreamingEngineRef = Arc; - -#[derive(Default)] -struct StatelessFlowRuntime { - flow: Option>, - failed_rebuild: Option<(u32, Instant)>, -} - -struct StatelessFlowSlot { - runtime: Arc>, - /// Cleared at registry-detach time, fencing creators that already captured this slot. - active: std::sync::atomic::AtomicBool, - #[cfg(test)] - rebuild_attempts: AtomicUsize, -} - -fn validate_captured_slot( - slot: &StatelessFlowSlot, - current_source_table_id: Option, - expected_table_id: table::metadata::TableId, - flow_id: FlowId, -) -> Result<(), Error> { - ensure!( - slot.active.load(Ordering::Acquire), - FlowNotFoundSnafu { id: flow_id } - ); - let current_source_table_id = - current_source_table_id.context(FlowNotFoundSnafu { id: flow_id })?; - ensure!( - current_source_table_id == expected_table_id, - InvalidQuerySnafu { - reason: format!("Flow {flow_id} source table changed while it was selected") - } - ); - Ok(()) -} - -pub struct StreamingEngine { - pub query_engine: Arc, - pub frontend_client: Arc, - table_info_source: ManagedTableSource, - stateless_flows: RwLock>>, - pub node_id: Option, -} - -impl StreamingEngine { - pub fn new( - node_id: Option, - query_engine: Arc, - table_meta: TableMetadataManagerRef, - frontend_client: Arc, - ) -> Self { - let table_info_source = ManagedTableSource::new( - table_meta.table_info_manager().clone(), - table_meta.table_name_manager().clone(), - ); - Self { - query_engine, - frontend_client, - table_info_source, - stateless_flows: Default::default(), - node_id, - } - } - - pub async fn handle_write_request( - &self, - region_id: RegionId, - rows: Vec, - batch_datatypes: &[ConcreteDataType], - source_schema_version: u32, - ) -> Result<(), Error> { - let table_id = region_id.table_id(); - let flow_ids = self.flow_ids_for_table(table_id).await; - let mut failed_flow_ids = Vec::new(); - let mut first_error = None; - for (flow_id, slot) in flow_ids { - let result = self - .execute_flow( - flow_id, - slot, - table_id, - rows.clone(), - batch_datatypes, - source_schema_version, - ) - .await; - if let Err(err) = result { - error!(err; "Failed to insert into flow={}, region_id={}", flow_id, region_id); - failed_flow_ids.push(flow_id); - if first_error.is_none() { - first_error = Some(BoxedError::new(err)); - } - } - } - match first_error { - Some(source) => Err(InsertIntoFlowSnafu { - region_id: u64::from(region_id), - flow_ids: failed_flow_ids, - } - .into_error(source)), - None => Ok(()), - } - } - - async fn flow_ids_for_table( - &self, - table_id: table::metadata::TableId, - ) -> Vec<(FlowId, Arc)> { - let slots = self - .stateless_flows - .read() - .await - .iter() - .map(|(id, slot)| (*id, Arc::clone(slot))) - .collect::>(); - let mut flows = Vec::new(); - for (id, slot) in slots { - if slot - .runtime - .read() - .await - .flow - .as_ref() - .is_some_and(|flow| flow.source_table_id == table_id) - { - flows.push((id, slot)); - } - } - flows - } - - async fn execute_flow( - &self, - flow_id: FlowId, - slot: Arc, - expected_table_id: table::metadata::TableId, - rows: Vec, - batch_datatypes: &[ConcreteDataType], - source_schema_version: u32, - ) -> Result { - // Keep the captured lifecycle slot rather than resolving the ID again after a drop. - let mut guard = slot.runtime.clone().read_owned().await; - let current = guard - .flow - .as_ref() - .context(FlowNotFoundSnafu { id: flow_id })?; - validate_captured_slot( - &slot, - Some(current.source_table_id), - expected_table_id, - flow_id, - )?; - if current.source_schema_version != source_schema_version { - if guard - .failed_rebuild - .as_ref() - .is_some_and(|(version, until)| { - *version == source_schema_version && *until > Instant::now() - }) - { - return InvalidQuerySnafu { - reason: format!( - "Flow {flow_id} schema rebuild for source version {source_schema_version} is cooling down" - ), - } - .fail(); - } - drop(guard); - // Serialize rebuilds with definition replacement using the existing publication - // lease. Another write may already have rebuilt this schema while we waited. - let mut published = slot.runtime.clone().write_owned().await; - let current = published - .flow - .as_ref() - .context(FlowNotFoundSnafu { id: flow_id })?; - validate_captured_slot( - &slot, - Some(current.source_table_id), - expected_table_id, - flow_id, - )?; - if current.source_schema_version != source_schema_version { - if published - .failed_rebuild - .as_ref() - .is_some_and(|(version, until)| { - *version == source_schema_version && *until > Instant::now() - }) - { - return InvalidQuerySnafu { - reason: format!( - "Flow {flow_id} schema rebuild for source version {source_schema_version} is cooling down" - ), - } - .fail(); - } - #[cfg(test)] - slot.rebuild_attempts.fetch_add(1, Ordering::Relaxed); - let replacement = self - .build_stateless_flow(¤t.create_args, false) - .await - .and_then(|replacement| { - ensure!( - replacement.source_table_id == expected_table_id - && replacement.source_schema_version == source_schema_version, - InvalidQuerySnafu { - reason: format!( - "Source schema changed while rebuilding flow {flow_id}" - ) - } - ); - Ok(replacement) - }); - match replacement { - Ok(replacement) => { - published.flow = Some(Arc::new(replacement)); - published.failed_rebuild = None; - } - Err(error) => { - // Reuse the default heartbeat retry baseline; this is neither a - // negotiated interval nor a cache-freshness guarantee. - published.failed_rebuild = Some(( - source_schema_version, - Instant::now() + BASE_HEARTBEAT_INTERVAL, - )); - return Err(error); - } - } - } - // Do not open a replacement/drop gap between preparation and sink execution. - guard = tokio::sync::OwnedRwLockWriteGuard::downgrade(published); - } - let flow = guard - .flow - .as_ref() - .context(FlowNotFoundSnafu { id: flow_id })?; - // This is the last check before planning. In particular, a request normalized against - // an old source schema is never allowed to reach a newly published plan. - let latest = self - .table_info_source - .get_table_info_value(&flow.source_table_id) - .await? - .context(UnexpectedSnafu { - reason: "Source table metadata is missing", - })? - .table_info - .meta - .schema - .version(); - ensure!( - source_schema_version == latest && flow.source_schema_version == latest, - InvalidQuerySnafu { - reason: format!("Source schema version changed before flow {flow_id} execution") - } - ); - stateless::execute( - flow, - &rows, - batch_datatypes, - &self.query_engine, - &self.frontend_client, - latest, - ) - .await - } - - pub async fn remove_flow_inner(&self, flow_id: FlowId) -> Result<(), Error> { - // Detach first: this is the tombstone/linearization point. A concurrent create must - // install a different slot and can never republish into the removed one. - let slot = self - .stateless_flows - .write() - .await - .remove(&flow_id) - .context(FlowNotFoundSnafu { id: flow_id })?; - slot.active.store(false, Ordering::Release); - let mut runtime = slot.runtime.write().await; - runtime.flow.take(); - runtime.failed_rebuild = None; - Ok(()) - } - - async fn publish_initial_flow( - &self, - slot: Arc, - flow: Arc, - create_if_not_exists: bool, - or_replace: bool, - ) -> Result { - let mut runtime = slot.runtime.write().await; - ensure!( - slot.active.load(Ordering::Acquire), - FlowNotFoundSnafu { - id: flow.create_args.flow_id - } - ); - if runtime.flow.is_some() && !or_replace { - if create_if_not_exists { - return Ok(false); - } - return crate::error::FlowAlreadyExistSnafu { - id: flow.create_args.flow_id, - } - .fail(); - } - let latest = self - .table_info_source - .get_table_info_value(&flow.source_table_id) - .await? - .context(UnexpectedSnafu { - reason: "Source table metadata is missing", - })? - .table_info - .meta - .schema - .version(); - ensure!( - latest == flow.source_schema_version, - InvalidQuerySnafu { - reason: format!( - "Source schema changed while building flow: built version {}, current version {latest}", - flow.source_schema_version - ) - } - ); - runtime.flow = Some(flow); - runtime.failed_rebuild = None; - Ok(true) - } - - pub async fn create_flow_inner(&self, args: CreateFlowArgs) -> Result, Error> { - let flow_id = args.flow_id; - let flow = Arc::new(self.build_stateless_flow(&args, true).await?); - let slot = { - let mut slots = self.stateless_flows.write().await; - if let Some(slot) = slots.get(&flow_id) { - Arc::clone(slot) - } else { - let slot = Arc::new(StatelessFlowSlot { - runtime: Arc::new(RwLock::new(StatelessFlowRuntime::default())), - active: AtomicBool::new(true), - #[cfg(test)] - rebuild_attempts: AtomicUsize::new(0), - }); - slots.insert(flow_id, Arc::clone(&slot)); - slot - } - }; - let published = self - .publish_initial_flow( - slot.clone(), - flow, - args.create_if_not_exists, - args.or_replace, - ) - .await?; - ensure!( - self.stateless_flows - .read() - .await - .get(&flow_id) - .is_some_and(|current| Arc::ptr_eq(current, &slot)), - FlowNotFoundSnafu { id: flow_id } - ); - if published { - info!("Successfully create flow with id={flow_id}"); - Ok(Some(flow_id)) - } else { - Ok(None) - } - } - - async fn build_stateless_flow( - &self, - args: &CreateFlowArgs, - create_sink: bool, - ) -> Result { - let CreateFlowArgs { - flow_id, - sink_table_name, - source_table_ids, - sql, - query_ctx, - .. - } = args; - ensure!( - source_table_ids.len() == 1, - InvalidQuerySnafu { - reason: "Stateless streaming flow does not support multiple source tables", - } - ); - - let query_ctx = query_ctx.clone().map(Arc::new).context(UnexpectedSnafu { - reason: "Query context is missing", - })?; - let source_table_id = source_table_ids[0]; - let source_table_name = self - .table_info_source - .get_table_name(&source_table_id) - .await?; - let source_table_info = self - .table_info_source - .get_table_info_value(&source_table_id) - .await? - .context(UnexpectedSnafu { - reason: "Source table metadata is missing", - })?; - let flow_plan = - sql_to_df_plan(query_ctx.clone(), self.query_engine.clone(), sql, true).await?; - stateless::validate_plan(&flow_plan)?; - let source_meta = source_table_info.table_info.meta; - let source_schema = source_meta.schema; - let source_primary_key_indices = source_meta.primary_key_indices; - stateless::validate_source_scan(&flow_plan, source_table_id, &source_schema)?; - let (inferred_schema, lineage) = output_column_schemas(&flow_plan, &source_schema)?; - let inferred_relation = relation_desc_from_output( - &inferred_schema, - &lineage, - &source_primary_key_indices, - &flow_plan, - ); - let sink_exists = self.fetch_table_pk_schema(sink_table_name).await?.is_some(); - if !sink_exists { - validate_auto_column_names(&inferred_schema)?; - } - if !sink_exists - && create_sink - && !self - .create_table_from_relation( - &format!("flow-id={flow_id}"), - sink_table_name, - &inferred_relation, - ) - .await? - { - return UnexpectedSnafu { - reason: format!("Failed to create table {sink_table_name:?}"), - } - .fail(); - } - ensure!( - sink_exists || create_sink, - UnexpectedSnafu { - reason: format!("Sink table metadata is missing: {sink_table_name:?}"), - } - ); - - // Fetch the metadata after validation or auto-creation. The sink's layout is the insert - // contract: flow output aliases must not leak into the request schema. - let (sink_primary_keys, _, sink_schema) = self - .fetch_table_pk_schema(sink_table_name) - .await? - .context(UnexpectedSnafu { - reason: format!("Sink table metadata is missing: {sink_table_name:?}"), - })?; - let (auto_columns, plan) = match resolve_sink_layout(&inferred_schema, &sink_schema) { - Ok(auto_columns) => (auto_columns, flow_plan), - Err(normal_error) => { - // Appending a hidden source timestamp changes DISTINCT's key. It is therefore - // never a valid compatibility rewrite for a DISTINCT flow. - let has_distinct = { - let mut found = false; - flow_plan - .apply(|node| { - if matches!(node, LogicalPlan::Distinct(Distinct::All(_))) { - found = true; - } - Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) - }) - .context(DatafusionSnafu { - context: "Failed to inspect flow plan", - })?; - found - }; - if has_distinct - || !sink_exists - || !is_explicit_source_timestamp_compatibility( - &inferred_schema, - &lineage, - &sink_schema, - &source_schema, - ) - { - return Err(normal_error); - } - let source_timestamp_index = source_schema.timestamp_index().unwrap(); - let source_timestamp_name = - &source_schema.column_schemas()[source_timestamp_index].name; - let plan = stateless::rewrite_source_timestamp( - flow_plan, - &TableReference::full( - source_table_name[0].clone(), - source_table_name[1].clone(), - source_table_name[2].clone(), - ), - source_timestamp_name, - )?; - let (effective_output, _) = output_column_schemas(&plan, &source_schema)?; - ensure!( - effective_output.len() == sink_schema.len() - && effective_output - .iter() - .zip(&sink_schema) - .all(|(output, sink)| output.data_type == sink.data_type), - InvalidQuerySnafu { - reason: "Compatibility plan output does not match the full sink schema" - } - ); - (vec![], plan) - } - }; - - Ok(StatelessFlow { - source_table_id, - source_table_name, - source_schema_version: source_schema.version(), - source_schema, - sink_table_name: sink_table_name.clone(), - sink_schema, - sink_primary_keys, - auto_columns, - plan, - query_ctx, - create_args: args.clone(), - }) - } - - pub async fn flush_flow_inner(&self, _flow_id: FlowId) -> Result { - Ok(0) - } - - pub(crate) async fn stateless_flow_ids(&self) -> Vec { - let slots = self.stateless_flows.read().await; - let mut ids = Vec::new(); - for (id, slot) in slots.iter() { - if slot.runtime.read().await.flow.is_some() { - ids.push(*id); - } - } - ids - } - - pub async fn flow_exist_inner(&self, flow_id: FlowId) -> Result { - let slot = self.stateless_flows.read().await.get(&flow_id).cloned(); - Ok(match slot { - Some(slot) => slot.runtime.read().await.flow.is_some(), - None => false, - }) - } - - async fn fetch_table_pk_schema( - &self, - table_name: &TableName, - ) -> Result, Option, Vec)>, Error> { - if let Some(table_id) = self - .table_info_source - .get_opt_table_id_from_name(table_name) - .await? - { - let table_info = self - .table_info_source - .get_table_info_value(&table_id) - .await? - .unwrap(); - let meta = table_info.table_info.meta; - let schema = meta.schema.column_schemas().to_vec(); - let primary_keys = meta - .primary_key_indices - .into_iter() - .map(|i| schema[i].name.clone()) - .collect_vec(); - Ok(Some((primary_keys, meta.schema.timestamp_index(), schema))) - } else { - Ok(None) - } - } - - async fn adjust_auto_created_table_schema( - &self, - schema: &RelationDesc, - ) -> Result<(Vec, Vec, bool), Error> { - let primary_keys = schema - .typ() - .keys - .first() - .map(|key| { - key.column_indices - .iter() - .map(|i| { - schema - .get_name(*i) - .clone() - .unwrap_or_else(|| format!("col_{i}")) - }) - .collect_vec() - }) - .unwrap_or_default(); - let mut columns = relation_desc_to_column_schemas_with_fallback(schema); - columns.push(ColumnSchema::new( - AUTO_CREATED_UPDATE_AT_TS_COL, - ConcreteDataType::timestamp_millisecond_datatype(), - true, - )); - let no_time_index = schema.typ().time_index.is_none(); - if no_time_index { - columns.push( - ColumnSchema::new( - AUTO_CREATED_PLACEHOLDER_TS_COL, - ConcreteDataType::timestamp_millisecond_datatype(), - true, - ) - .with_time_index(true), - ); - } - Ok((primary_keys, columns, no_time_index)) - } -} - -impl StreamingEngine { - async fn handle_inserts_inner( - &self, - request: api::v1::region::InsertRequests, - ) -> Result<(), Error> { - // A mirrored envelope can contain several regions of one source. Normalize each request, - // then concatenate by source so DISTINCT is evaluated once over the complete envelope. - let mut grouped: BTreeMap<_, (_, Vec, Vec, u32)> = - BTreeMap::new(); - let mut poisoned_tables = std::collections::HashSet::new(); - let mut first_error = None; - for write_request in request.requests { - let region_id = RegionId::from(write_request.region_id); - let table_id = region_id.table_id(); - if poisoned_tables.contains(&table_id) { - continue; - } - match self.handle_insert_request(write_request).await { - Ok((rows, types, version)) => { - let entry = grouped - .entry(table_id) - .or_insert_with(|| (region_id, vec![], types.clone(), version)); - if entry.2 != types || entry.3 != version { - poisoned_tables.insert(table_id); - grouped.remove(&table_id); - let err = InvalidQuerySnafu { reason: format!("Source table {table_id} metadata changed within one insert envelope") }.build(); - let ids: Vec = self - .flow_ids_for_table(table_id) - .await - .into_iter() - .map(|(id, _)| id) - .collect(); - let err = InsertIntoFlowSnafu { - region_id: u64::from(region_id), - flow_ids: ids, - } - .into_error(BoxedError::new(err)); - error!(err; "Failed to normalize flow insert request for region_id={region_id}"); - if first_error.is_none() { - first_error = Some(err); - } - } else { - entry.1.extend(rows); - } - } - Err(err) => { - let ids: Vec = self - .flow_ids_for_table(table_id) - .await - .into_iter() - .map(|(id, _)| id) - .collect(); - poisoned_tables.insert(table_id); - grouped.remove(&table_id); - let err = InsertIntoFlowSnafu { - region_id: u64::from(region_id), - flow_ids: ids, - } - .into_error(BoxedError::new(err)); - error!(err; "Failed to normalize flow insert request for region_id={region_id}"); - if first_error.is_none() { - first_error = Some(err); - } - } - } - } - for (_, (region_id, rows, types, version)) in grouped { - if let Err(err) = self - .handle_write_request(region_id, rows, &types, version) - .await - && first_error.is_none() - { - first_error = Some(err); - } - } - match first_error { - Some(err) => Err(err), - None => Ok(()), - } - } - - async fn handle_insert_request( - &self, - write_request: api::v1::region::InsertRequest, - ) -> Result<(Vec, Vec, u32), Error> { - let region_id = write_request.region_id; - let table_id = RegionId::from(region_id).table_id(); - let (insert_schema, rows_proto) = write_request - .rows - .map(|r| (r.schema, r.rows)) - .unwrap_or_default(); - let now = common_time::util::current_time_millis(); - let (table_types, fetch_order, source_schema_version) = { - // Fetch the source metadata once for both current-schema normalization and - // retained-plan validation. In particular, do not execute a retained plan - // against rows normalized with a newer schema. - let table_info = self - .table_info_source - .get_table_info_value(&table_id) - .await? - .context(UnexpectedSnafu { - reason: format!("Table metadata is missing for table id {table_id}"), - })?; - let source_schema_version = table_info.table_info.meta.schema.version(); - let table_schema = table_info_value_to_relation_desc(table_info)?; - let defaults = table_schema - .default_values - .iter() - .zip(table_schema.relation_desc.typ().column_types.iter()) - .map(|(value, ty)| { - value.as_ref().and_then(|value| { - value.create_default(ty.scalar_type(), ty.nullable()).ok() - }) - }) - .collect_vec(); - let types = table_schema - .relation_desc - .typ() - .column_types - .iter() - .map(|ty| ty.scalar_type.clone()) - .collect_vec(); - let names = table_schema - .relation_desc - .names - .iter() - .enumerate() - .map(|(idx, name)| { - name.clone().context(InternalSnafu { - reason: format!("Column {idx} of table {table_id} has no name"), - }) - }) - .collect::, _>>()?; - let input_columns = insert_schema - .iter() - .enumerate() - .map(|(idx, column)| (&column.column_name, idx)) - .collect::>(); - let order = names - .iter() - .zip(defaults) - .map(|(name, default)| { - input_columns - .get(name) - .copied() - .map(FetchFromRow::Idx) - .or_else(|| default.map(FetchFromRow::Default)) - .with_context(|| UnexpectedSnafu { - reason: format!("Column not found: {name}"), - }) - }) - .collect::, _>>()?; - (types, order, source_schema_version) - }; - let rows = rows_proto - .into_iter() - .map(|row| { - let row = Row::from(row); - let row = fetch_order - .iter() - .map(|item| item.fetch(&row)) - .collect_vec(); - (Row::new(row), now, 1) - }) - .collect_vec(); - Ok((rows, table_types, source_schema_version)) - } -} - -#[derive(Debug, Clone)] -enum FetchFromRow { - Idx(usize), - Default(datatypes::value::Value), -} - -impl FetchFromRow { - fn fetch(&self, row: &Row) -> datatypes::value::Value { - match self { - Self::Idx(idx) => row - .get(*idx) - .cloned() - .unwrap_or(datatypes::value::Value::Null), - Self::Default(value) => value.clone(), - } - } -} diff --git a/src/flow/src/adapter/flownode_impl.rs b/src/flow/src/adapter/flownode_impl.rs index cf4b6fd2d34..1a6973f40b1 100644 --- a/src/flow/src/adapter/flownode_impl.rs +++ b/src/flow/src/adapter/flownode_impl.rs @@ -39,59 +39,55 @@ use itertools::Itertools; use operator::utils::try_to_session_query_context; use session::context::QueryContextBuilder; use snafu::{OptionExt, ResultExt, ensure}; -use store_api::storage::{RegionId, TableId}; use tokio::sync::{Mutex, RwLock}; -use crate::adapter::{CreateFlowArgs, StreamingEngine}; use crate::batching_mode::engine::BatchingEngine; use crate::engine::{FlowEngine, FlowStatProvider}; use crate::error::{ CreateFlowSnafu, ExternalSnafu, FlowNotFoundSnafu, FlowNotRecoveredSnafu, - IllegalCheckTaskStateSnafu, InternalSnafu, JoinTaskSnafu, ListFlowsSnafu, - NoAvailableFrontendSnafu, SyncCheckTaskSnafu, UnsupportedSnafu, + IllegalCheckTaskStateSnafu, InternalSnafu, ListFlowsSnafu, NoAvailableFrontendSnafu, + SyncCheckTaskSnafu, UnsupportedSnafu, }; use crate::metrics::{METRIC_FLOW_ROWS, METRIC_FLOW_TASK_COUNT}; use crate::utils::StateReportHandler; -use crate::{Error, FlowId}; +use crate::{CreateFlowArgs, Error, FlowId}; -/// Ref to [`FlowDualEngine`] -pub type FlowDualEngineRef = Arc; +/// Ref to [`FlownodeEngine`] +pub type FlownodeEngineRef = Arc; -/// Manage both streaming and batching mode engine +/// Manage the batching flow engine /// /// including create/drop/flush flow -/// and redirect insert requests to the appropriate engine -pub struct FlowDualEngine { - streaming_engine: Arc, +/// and redirect insert requests to the batching engine +pub struct FlownodeEngine { batching_engine: Arc, /// receive a oneshot sender to send state report state_report_handler: RwLock>, - /// helper struct for faster query flow by table id or vice versa - src_table2flow: RwLock, flow_metadata_manager: Arc, catalog_manager: Arc, check_task: tokio::sync::Mutex>, plugins: Plugins, + /// `Some` in distributed mode, `None` in standalone mode + node_id: Option, done_recovering: AtomicBool, } -impl FlowDualEngine { +impl FlownodeEngine { pub fn new( - streaming_engine: Arc, + node_id: Option, batching_engine: Arc, flow_metadata_manager: Arc, catalog_manager: Arc, plugins: Plugins, ) -> Self { Self { - streaming_engine, batching_engine, state_report_handler: Default::default(), - src_table2flow: RwLock::new(SrcTableToFlow::default()), flow_metadata_manager, catalog_manager, check_task: Mutex::new(None), plugins, + node_id, done_recovering: AtomicBool::new(false), } } @@ -99,7 +95,7 @@ impl FlowDualEngine { /// Set `done_recovering` to true /// indicate that we are ready to handle requests pub fn set_done_recovering(&self) { - info!("FlowDualEngine done recovering"); + info!("FlownodeEngine done recovering"); self.done_recovering .store(true, std::sync::atomic::Ordering::Release); } @@ -117,7 +113,7 @@ impl FlowDualEngine { } warn!( - "FlowDualEngine is not done recovering, {} insert request waiting for recovery", + "FlownodeEngine is not done recovering, {} insert request waiting for recovery", waiting_req_cnt ); // wait 3 seconds, check every 1 second @@ -126,7 +122,7 @@ impl FlowDualEngine { let max_retry = 3; while retry < max_retry && !self.is_recover_done() { warn!( - "FlowDualEngine is not done recovering, retry {} in 1s", + "FlownodeEngine is not done recovering, retry {} in 1s", retry ); tokio::time::sleep(std::time::Duration::from_secs(1)).await; @@ -135,7 +131,7 @@ impl FlowDualEngine { if retry == max_retry { return FlowNotRecoveredSnafu.fail(); } else { - info!("FlowDualEngine is done recovering"); + info!("FlownodeEngine is done recovering"); } // TODO(discord9): also put to centralized logging for flow once it implemented Ok(()) @@ -147,11 +143,7 @@ impl FlowDualEngine { /// Determine if the engine is in distributed mode pub fn is_distributed(&self) -> bool { - self.streaming_engine.node_id.is_some() - } - - pub fn streaming_engine(&self) -> Arc { - self.streaming_engine.clone() + self.node_id.is_some() } pub fn batching_engine(&self) -> Arc { @@ -278,7 +270,7 @@ impl FlowDualEngine { allow_drop: bool, ) -> Result<(), Error> { // use nodeid to determine if this is standalone/distributed mode, and retrieve all flows in this node(in distributed mode)/or all flows(in standalone mode) - let nodeid = self.streaming_engine.node_id; + let nodeid = self.node_id; let should_exists: Vec<_> = if let Some(nodeid) = nodeid { // nodeid is available, so we only need to check flows on this node // which also means we are in distributed mode @@ -493,7 +485,7 @@ struct ConsistentCheckTask { } impl ConsistentCheckTask { - async fn start_check_task(engine: &Arc) -> Result { + async fn start_check_task(engine: &Arc) -> Result { let engine = engine.clone(); let min_refresh_duration = engine .batching_engine() @@ -586,230 +578,89 @@ impl ConsistentCheckTask { } } -#[derive(Default)] -struct SrcTableToFlow { - /// mapping of table ids to flow ids for streaming mode - stream: HashMap>, - /// mapping of table ids to flow ids for batching mode - batch: HashMap>, - /// mapping of flow ids to (flow type, source table ids) - flow_infos: HashMap)>, -} - -impl SrcTableToFlow { - fn in_stream(&self, table_id: TableId) -> bool { - self.stream.contains_key(&table_id) - } - fn in_batch(&self, table_id: TableId) -> bool { - self.batch.contains_key(&table_id) - } - fn add_flow(&mut self, flow_id: FlowId, flow_type: FlowType, src_table_ids: Vec) { - let mapping = match flow_type { - FlowType::Streaming => &mut self.stream, - FlowType::Batching => &mut self.batch, - }; - - for src_table in src_table_ids.clone() { - mapping - .entry(src_table) - .and_modify(|flows| { - flows.insert(flow_id); - }) - .or_insert_with(|| { - let mut set = HashSet::new(); - set.insert(flow_id); - set - }); - } - self.flow_infos.insert(flow_id, (flow_type, src_table_ids)); - } - - fn remove_flow(&mut self, flow_id: FlowId) { - let mapping = match self.get_flow_type(flow_id) { - Some(FlowType::Streaming) => &mut self.stream, - Some(FlowType::Batching) => &mut self.batch, - None => return, - }; - if let Some((_, src_table_ids)) = self.flow_infos.remove(&flow_id) { - for src_table in src_table_ids { - if let Some(flows) = mapping.get_mut(&src_table) { - flows.remove(&flow_id); - } - } - } - } - - fn get_flow_type(&self, flow_id: FlowId) -> Option { - self.flow_infos - .get(&flow_id) - .map(|(flow_type, _)| flow_type) - .cloned() - } -} - -impl FlowEngine for FlowDualEngine { +impl FlowEngine for FlownodeEngine { async fn create_flow(&self, args: CreateFlowArgs) -> Result, Error> { - let flow_type = args - .flow_options - .get(FlowType::FLOW_TYPE_KEY) - .map(|s| s.as_str()); - - let flow_type = match flow_type { - Some(FlowType::BATCHING) => FlowType::Batching, - Some(FlowType::STREAMING) => FlowType::Streaming, - None => FlowType::Batching, - Some(flow_type) => { - return InternalSnafu { - reason: format!("Invalid flow type: {}", flow_type), + if let Some(flow_type) = args.flow_options.get(FlowType::FLOW_TYPE_KEY) { + match flow_type.as_str() { + FlowType::BATCHING => {} + FlowType::STREAMING => { + return UnsupportedSnafu { + reason: format!( + "Flow {} was created with the legacy streaming flow type, which is no longer supported; drop and recreate the flow so it runs with the batching scheduler", + args.flow_id + ), + } + .fail(); + } + other => { + return UnsupportedSnafu { + reason: format!( + "Flow {} has unknown flow type `{other}`; only batching flows are supported, drop and recreate the flow", + args.flow_id + ), + } + .fail(); } - .fail(); } - }; + } - let flow_id = args.flow_id; - let src_table_ids = args.source_table_ids.clone(); - - let res = match flow_type { - FlowType::Batching => self.batching_engine.create_flow(args).await, - FlowType::Streaming => self.streaming_engine.create_flow(args).await, - }?; - - self.src_table2flow - .write() - .await - .add_flow(flow_id, flow_type, src_table_ids); - - Ok(res) + self.batching_engine.create_flow(args).await } async fn remove_flow(&self, flow_id: FlowId) -> Result<(), Error> { - let flow_type = self.src_table2flow.read().await.get_flow_type(flow_id); - let flow_type = match flow_type { - Some(flow_type) => Some(flow_type), - None if self.streaming_engine.flow_exist(flow_id).await? => Some(FlowType::Streaming), - None => None, - }; + if !self.batching_engine.flow_exist(flow_id).await? { + // this can happen if flownode just restart, and is stilling creating the flow + // since now that this flow should dropped, we need to trigger the consistent check and allow drop + // this rely on drop flow ddl delete metadata first, see src/common/meta/src/ddl/drop_flow.rs + warn!( + "Flow {} is not exist in the underlying engine, but exist in metadata", + flow_id + ); + self.try_sync_with_check_task(flow_id, true).await?; - match flow_type { - Some(FlowType::Batching) => self.batching_engine.remove_flow(flow_id).await, - Some(FlowType::Streaming) => self.streaming_engine.remove_flow(flow_id).await, - None => { - // this can happen if flownode just restart, and is stilling creating the flow - // since now that this flow should dropped, we need to trigger the consistent check and allow drop - // this rely on drop flow ddl delete metadata first, see src/common/meta/src/ddl/drop_flow.rs - warn!( - "Flow {} is not exist in the underlying engine, but exist in metadata", - flow_id - ); - self.try_sync_with_check_task(flow_id, true).await?; + return Ok(()); + } - Ok(()) - } - }?; - // remove mapping - self.src_table2flow.write().await.remove_flow(flow_id); - Ok(()) + self.batching_engine.remove_flow(flow_id).await } async fn flush_flow(&self, flow_id: FlowId) -> Result { // sync with check task self.try_sync_with_check_task(flow_id, false).await?; - let flow_type = self.src_table2flow.read().await.get_flow_type(flow_id); - match flow_type { - Some(FlowType::Batching) => self.batching_engine.flush_flow(flow_id).await, - Some(FlowType::Streaming) => self.streaming_engine.flush_flow(flow_id).await, - None => { - warn!( - "Currently flow={flow_id} doesn't exist in flownode, ignore flush_flow request" - ); - Ok(0) - } + if !self.batching_engine.flow_exist(flow_id).await? { + warn!("Currently flow={flow_id} doesn't exist in flownode, ignore flush_flow request"); + return Ok(0); } + + self.batching_engine.flush_flow(flow_id).await } async fn flow_exist(&self, flow_id: FlowId) -> Result { - let flow_type = self.src_table2flow.read().await.get_flow_type(flow_id); - // Check the underlying registry so stateless flows survive a missing - // routing-map entry during recovery. - match flow_type { - Some(FlowType::Batching) => self.batching_engine.flow_exist(flow_id).await, - Some(FlowType::Streaming) => self.streaming_engine.flow_exist(flow_id).await, - None => self.streaming_engine.flow_exist(flow_id).await, - } + self.batching_engine.flow_exist(flow_id).await } async fn list_flows(&self) -> Result, Error> { - let stream_flows = self.streaming_engine.list_flows().await?; - let batch_flows = self.batching_engine.list_flows().await?; - - Ok(stream_flows.into_iter().chain(batch_flows)) + self.batching_engine.list_flows().await } + /// Handle mirrored inserts: the batching engine uses them to mark dirty windows, so this + /// path must be kept even though there is no streaming executor anymore. async fn handle_flow_inserts( &self, request: api::v1::region::InsertRequests, ) -> Result<(), Error> { self.wait_for_all_flow_recover(request.requests.len()) .await?; - // TODO(discord9): make as little clone as possible - let mut to_stream_engine = Vec::with_capacity(request.requests.len()); - let mut to_batch_engine = request.requests; - - let mut batching_row_cnt = 0; - let mut streaming_row_cnt = 0; - - { - // not locking this, or recover flows will be starved when also handling flow inserts - let src_table2flow = self.src_table2flow.read().await; - to_batch_engine.retain(|req| { - let region_id = RegionId::from(req.region_id); - let table_id = region_id.table_id(); - let is_in_stream = src_table2flow.in_stream(table_id); - let is_in_batch = src_table2flow.in_batch(table_id); - if is_in_stream { - streaming_row_cnt += req.rows.as_ref().map(|rs| rs.rows.len()).unwrap_or(0); - to_stream_engine.push(req.clone()); - } - if is_in_batch { - batching_row_cnt += req.rows.as_ref().map(|rs| rs.rows.len()).unwrap_or(0); - return true; - } - if !is_in_batch && !is_in_stream { - // TODO(discord9): also put to centralized logging for flow once it implemented - warn!("Table {} is not any flow's source table", table_id) - } - false - }); - // drop(src_table2flow); - // can't use drop due to https://github.com/rust-lang/rust/pull/128846 - } - - METRIC_FLOW_ROWS - .with_label_values(&["in-streaming"]) - .inc_by(streaming_row_cnt as u64); - + let row_cnt = request + .requests + .iter() + .map(|req| req.rows.as_ref().map(|rows| rows.rows.len()).unwrap_or(0)) + .sum::(); METRIC_FLOW_ROWS .with_label_values(&["in-batching"]) - .inc_by(batching_row_cnt as u64); + .inc_by(row_cnt as u64); - let streaming_engine = self.streaming_engine.clone(); - let stream_handler: JoinHandle> = - common_runtime::spawn_global(async move { - streaming_engine - .handle_flow_inserts(api::v1::region::InsertRequests { - requests: to_stream_engine, - }) - .await?; - Ok(()) - }); - self.batching_engine - .handle_flow_inserts(api::v1::region::InsertRequests { - requests: to_batch_engine, - }) - .await?; - stream_handler.await.context(JoinTaskSnafu)??; - - Ok(()) + self.batching_engine.handle_flow_inserts(request).await } async fn handle_mark_window_dirty( @@ -821,7 +672,7 @@ impl FlowEngine for FlowDualEngine { } #[async_trait::async_trait] -impl common_meta::node_manager::Flownode for FlowDualEngine { +impl common_meta::node_manager::Flownode for FlownodeEngine { async fn handle(&self, request: FlowRequest) -> MetaResult { let query_ctx = request .header @@ -969,54 +820,102 @@ fn to_meta_err( } } -impl FlowEngine for StreamingEngine { - async fn create_flow(&self, args: CreateFlowArgs) -> Result, Error> { - self.create_flow_inner(args).await - } - - async fn remove_flow(&self, flow_id: FlowId) -> Result<(), Error> { - self.remove_flow_inner(flow_id).await - } - - async fn flush_flow(&self, flow_id: FlowId) -> Result { - self.flush_flow_inner(flow_id).await - } - - async fn flow_exist(&self, flow_id: FlowId) -> Result { - self.flow_exist_inner(flow_id).await - } - - async fn list_flows(&self) -> Result, Error> { - Ok(self.stateless_flow_ids().await) - } - - async fn handle_flow_inserts( - &self, - request: api::v1::region::InsertRequests, - ) -> Result<(), Error> { - self.handle_inserts_inner(request).await - } - - async fn handle_mark_window_dirty( - &self, - _req: api::v1::flow::DirtyWindowRequests, - ) -> Result<(), Error> { - UnsupportedSnafu { - reason: "handle_mark_window_dirty in streaming engine", - } - .fail() - } -} - #[cfg(test)] mod tests { use std::collections::HashMap; + use std::sync::Arc; + use catalog::memory::new_memory_catalog_manager; + use common_base::Plugins; use common_meta::ddl::create_flow::INTERNAL_EVAL_SCHEDULE_KEY; + use common_meta::key::TableMetadataManager; + use common_meta::key::flow::FlowMetadataManager; + use common_meta::kv_backend::memory::MemoryKvBackend; + use query::options::QueryOptions; - use super::decode_internal_eval_schedule; + use super::{FlownodeEngine, decode_internal_eval_schedule}; + use crate::CreateFlowArgs; + use crate::batching_mode::BatchingModeOptions; + use crate::batching_mode::engine::BatchingEngine; + use crate::batching_mode::frontend_client::FrontendClient; + use crate::engine::FlowEngine; use crate::error::Error; + async fn new_test_engine() -> FlownodeEngine { + let kv_backend = Arc::new(MemoryKvBackend::new()); + let table_meta = Arc::new(TableMetadataManager::new(kv_backend.clone())); + table_meta.init().await.unwrap(); + let flow_meta = Arc::new(FlowMetadataManager::new(kv_backend)); + let catalog_manager = new_memory_catalog_manager().unwrap(); + let query_engine = crate::test_utils::create_test_query_engine(); + let (frontend_client, _handler) = + FrontendClient::from_empty_grpc_handler(QueryOptions::default()); + let batching = Arc::new(BatchingEngine::new( + Arc::new(frontend_client), + query_engine, + flow_meta.clone(), + table_meta, + catalog_manager.clone(), + BatchingModeOptions::default(), + )); + + FlownodeEngine::new(None, batching, flow_meta, catalog_manager, Plugins::new()) + } + + fn create_flow_args(flow_type: Option<&str>) -> CreateFlowArgs { + let mut flow_options = HashMap::new(); + if let Some(flow_type) = flow_type { + flow_options.insert("flow_type".to_string(), flow_type.to_string()); + } + + CreateFlowArgs { + flow_id: 1024, + sink_table_name: [ + "greptime_public".to_string(), + "public".to_string(), + "old_sink".to_string(), + ], + source_table_ids: vec![], + create_if_not_exists: false, + or_replace: false, + expire_after: None, + eval_interval: Some(60), + comment: None, + sql: "SELECT 1".to_string(), + flow_options, + query_ctx: None, + eval_schedule: None, + } + } + + #[tokio::test] + async fn test_old_streaming_metadata_asks_for_recreation() { + let engine = new_test_engine().await; + + // A flow persisted by the removed streaming executor must not run as batching: the + // recovery path goes through `create_flow`, so it reports that the flow needs recreation + // instead of silently executing different SQL semantics. + let err = engine + .create_flow(create_flow_args(Some("streaming"))) + .await + .unwrap_err(); + assert!( + matches!(err, Error::Unsupported { .. }), + "unexpected error: {err}" + ); + let msg = err.to_string(); + assert!(msg.contains("no longer supported"), "unexpected: {msg}"); + assert!(msg.contains("recreate"), "unexpected: {msg}"); + assert!(!engine.flow_exist(1024).await.unwrap()); + + // `batching` and absent `flow_type` still reach the batching engine. + for flow_type in [Some("batching"), None] { + let err = engine.create_flow(create_flow_args(flow_type)).await; + let msg = err.err().map(|err| err.to_string()).unwrap_or_default(); + assert!(!msg.contains("no longer supported"), "unexpected: {msg}"); + } + } + #[test] fn test_malformed_internal_eval_schedule_json_is_error() { let mut flow_options = HashMap::new(); diff --git a/src/flow/src/adapter/stateless.rs b/src/flow/src/adapter/stateless.rs deleted file mode 100644 index 1c1090a0ccc..00000000000 --- a/src/flow/src/adapter/stateless.rs +++ /dev/null @@ -1,730 +0,0 @@ -// 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. - -//! Stateless DataFusion execution for streaming flows. - -use std::collections::HashSet; -use std::sync::Arc; - -use api::helper::{to_grpc_value, vectors_to_rows}; -use api::v1::greptime_request::Request; -use api::v1::{RowInsertRequest, RowInsertRequests, Rows}; -use common_error::ext::BoxedError; -use common_query::OutputData; -use common_recordbatch::{RecordBatch, RecordBatches, map_dictionary_to_values_data_type}; -use common_time::Timestamp; -use datafusion::catalog::MemTable; -use datafusion::datasource::{TableProvider, provider_as_source, source_as_provider}; -use datafusion_common::tree_node::{Transformed, TreeNode}; -use datafusion_common::{Column, DFSchema, TableReference}; -use datafusion_expr::logical_plan::{Distinct, Projection}; -use datafusion_expr::{Expr, LogicalPlan}; -use datatypes::schema::{ColumnSchema, SchemaRef}; -use datatypes::value::Value; -use query::QueryEngine; -use session::context::QueryContextRef; -use snafu::{OptionExt, ResultExt, ensure}; -use table::metadata::TableId; -use table::table::adapter::DfTableProviderAdapter; - -use crate::TableName; -use crate::adapter::util::column_schemas_to_proto; -use crate::batching_mode::frontend_client::FrontendClient; -use crate::error::{DatafusionSnafu, Error, ExternalSnafu, InvalidQuerySnafu, UnexpectedSnafu}; -use crate::repr::DiffRow; - -/// The validated, immutable part of one streaming flow. -#[derive(Clone)] -pub(crate) struct StatelessFlow { - pub(crate) source_table_id: TableId, - pub(crate) source_table_name: TableName, - pub(crate) source_schema: SchemaRef, - pub(crate) source_schema_version: u32, - pub(crate) sink_table_name: TableName, - pub(crate) sink_schema: Vec, - pub(crate) sink_primary_keys: Vec, - /// The exact trailing columns resolved when the flow was created. - pub(crate) auto_columns: Vec, - pub(crate) plan: LogicalPlan, - pub(crate) query_ctx: QueryContextRef, - pub(crate) create_args: crate::CreateFlowArgs, -} - -/// Per-request input provider. It owns no catalog or storage state. -#[cfg(test)] -fn test_source_plan(table_name: TableReference, provider: Arc) -> LogicalPlan { - datafusion_expr::LogicalPlanBuilder::scan(table_name, provider_as_source(provider), None) - .unwrap() - .filter(datafusion_expr::col("number").gt(datafusion_expr::lit(1))) - .unwrap() - .project(vec![datafusion_expr::col("number")]) - .unwrap() - .build() - .unwrap() -} - -fn input_provider(batch: &RecordBatch) -> Result, Error> { - let arrow_batch = batch.df_record_batch().clone(); - let provider = MemTable::try_new(arrow_batch.schema(), vec![vec![arrow_batch]]).context( - DatafusionSnafu { - context: "Failed to create transient flow input provider", - }, - )?; - Ok(Arc::new(provider)) -} - -/// Adds the source timestamp to every supported plan node that has to carry it through a -/// filter or projection. The expression is appended only after the visible expressions, so the -/// sink contract remains positional. -pub(crate) fn rewrite_source_timestamp( - plan: LogicalPlan, - source_name: &TableReference, - source_timestamp_name: &str, -) -> Result { - let mut names = HashSet::new(); - plan.apply(|node| { - names.extend( - node.schema() - .fields() - .iter() - .map(|field| field.name().clone()), - ); - Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) - }) - .context(DatafusionSnafu { - context: "Failed to inspect streaming flow plan schema", - })?; - let mut hidden_name = "__flow_source_timestamp".to_string(); - let mut suffix = 0; - while !names.insert(hidden_name.clone()) { - suffix += 1; - hidden_name = format!("__flow_source_timestamp_{suffix}"); - } - let visible_count = plan.schema().fields().len(); - let source_timestamp = Column::from_name(source_timestamp_name); - let mut plan = plan - .transform_up_with_subqueries(|node| match node { - LogicalPlan::TableScan(mut scan) => { - if scan.table_name.resolved_eq(source_name) - && let Some(projection) = &mut scan.projection - { - let timestamp_index = scan - .source - .schema() - .index_of(source_timestamp_name) - .map_err(|_| { - datafusion::error::DataFusionError::Plan( - "Source timestamp is absent from source scan".into(), - ) - })?; - if !projection.contains(×tamp_index) { - projection.push(timestamp_index); - let schema = scan.source.schema(); - scan.projected_schema = Arc::new(DFSchema::new_with_metadata( - projection - .iter() - .map(|index| { - ( - Some(scan.table_name.clone()), - Arc::new(schema.field(*index).clone()), - ) - }) - .collect(), - schema.metadata().clone(), - )?); - } - } - Ok(Transformed::yes(LogicalPlan::TableScan(scan))) - } - LogicalPlan::Projection(mut projection) => { - let hidden_expr = if projection - .input - .schema() - .fields() - .iter() - .any(|field| field.name() == &hidden_name) - { - Expr::Column(Column::from_name(hidden_name.clone())) - } else { - Expr::Column(source_timestamp.clone()) - }; - projection.expr.push(hidden_expr.alias(hidden_name.clone())); - let projection = Projection::try_new(projection.expr, projection.input)?; - Ok(Transformed::yes(LogicalPlan::Projection(projection))) - } - _ => Ok(Transformed::no(node)), - }) - .context(DatafusionSnafu { - context: "Failed to add source timestamp to streaming flow plan", - })? - .data; - - // A plan ending at a scan or filter has no projection at which to give the carried value its - // hidden name. Add one only in that case; a projection below a filter already carries it. - if !plan - .schema() - .fields() - .iter() - .any(|field| field.name() == &hidden_name) - { - let expressions = plan - .schema() - .fields() - .iter() - .take(visible_count) - .map(|field| Expr::Column(Column::from_name(field.name()))) - .chain(std::iter::once( - Expr::Column(source_timestamp).alias(hidden_name), - )) - .collect::>(); - plan = Projection::try_new(expressions, Arc::new(plan)) - .map(LogicalPlan::Projection) - .context(DatafusionSnafu { - context: "Failed to finalize source timestamp in streaming flow plan", - })?; - } - Ok(plan) -} - -fn replace_source( - plan: LogicalPlan, - source_name: &TableReference, - provider: Arc, -) -> Result { - let mut scan_count = 0; - let mut replaced_scan_count = 0; - let plan = plan - .transform_up_with_subqueries(|node| match node { - LogicalPlan::TableScan(mut scan) => { - scan_count += 1; - if scan.table_name.resolved_eq(source_name) { - replaced_scan_count += 1; - scan.source = provider_as_source(provider.clone()); - let schema = scan.source.schema(); - scan.projected_schema = if let Some(projection) = &scan.projection { - Arc::new(DFSchema::new_with_metadata( - projection - .iter() - .map(|index| { - ( - Some(scan.table_name.clone()), - Arc::new(schema.field(*index).clone()), - ) - }) - .collect(), - schema.metadata().clone(), - )?) - } else { - Arc::new(DFSchema::try_from_qualified_schema( - scan.table_name.clone(), - &schema, - )?) - }; - Ok(Transformed::yes(LogicalPlan::TableScan(scan))) - } else { - Ok(Transformed::no(LogicalPlan::TableScan(scan))) - } - } - LogicalPlan::Join(_) | LogicalPlan::Aggregate(_) => { - Err(datafusion::error::DataFusionError::Plan( - "Streaming flow supports only a single projection/filter source".into(), - )) - } - _ => Ok(Transformed::no(node)), - }) - .context(DatafusionSnafu { - context: "Failed to substitute transient flow input provider", - })? - .data; - ensure!( - scan_count == 1 && replaced_scan_count == 1, - InvalidQuerySnafu { - reason: format!( - "Expected one source scan matching {:?}, found {scan_count} scans and {replaced_scan_count} matches", - source_name - ) - } - ); - Ok(plan) -} - -/// Validates the deliberately small stateless streaming SQL subset. -pub(crate) fn validate_plan(plan: &LogicalPlan) -> Result<(), Error> { - let mut scans = 0; - plan.apply(|node| { - match node { - LogicalPlan::TableScan(_) => scans += 1, - LogicalPlan::Projection(_) | LogicalPlan::Filter(_) => {} - LogicalPlan::Aggregate(_) => { - return Err(datafusion::error::DataFusionError::Plan( - "Aggregation is unsupported in streaming flows. Recreate the flow to select batching mode. A source table with TTL=instant must use persisted retention first. Aggregation SQL without a time window requires EVAL INTERVAL.".into(), - )); - } - // DISTINCT is evaluated against this request's transient input only. DISTINCT ON - // has ordering/selection semantics beyond the supported stateless subset. - LogicalPlan::Distinct(Distinct::All(_)) => {} - _ => { - return Err(datafusion::error::DataFusionError::Plan( - "Streaming flow supports only projection and filter over one source scan" - .into(), - )); - } - } - Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) - }) - .context(DatafusionSnafu { - context: "Failed to validate streaming flow plan", - })?; - ensure!( - scans == 1, - InvalidQuerySnafu { - reason: format!("Expected one source scan, found {scans}") - } - ); - Ok(()) -} - -/// Ensures the retained scan was planned against the source metadata captured for this flow. -pub(crate) fn validate_source_scan( - plan: &LogicalPlan, - source_table_id: TableId, - source_schema: &SchemaRef, -) -> Result<(), Error> { - plan.apply(|node| { - if let LogicalPlan::TableScan(scan) = node { - let provider = source_as_provider(&scan.source)?; - let provider = provider - .downcast_ref::() - .ok_or_else(|| { - datafusion::error::DataFusionError::Plan( - "Streaming flow source scan does not use a table provider".into(), - ) - })?; - let table_info = provider.table().table_info(); - if table_info.ident.table_id != source_table_id - || table_info.meta.schema.as_ref() != source_schema.as_ref() - { - return Err(datafusion::error::DataFusionError::Plan(format!( - "Streaming flow source scan does not match source table {source_table_id} schema version {}", - source_schema.version() - ))); - } - } - Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) - }) - .context(DatafusionSnafu { - context: "Failed to validate streaming flow source scan", - })?; - Ok(()) -} - -/// Rejects execution when the source metadata changed after the flow plan was retained. -/// The outer adapter replans a flow when it observes a new source schema version; this guard -/// rejects a request if the version changes again before execution. -fn validate_source_schema_version( - retained_version: u32, - current_version: u32, -) -> Result<(), Error> { - ensure!( - retained_version == current_version, - InvalidQuerySnafu { - reason: format!( - "Source schema version changed from {retained_version} to {current_version}; recreate or recover the flow before writing" - ) - } - ); - Ok(()) -} - -fn synthesize_auto_values(columns: &[ColumnSchema], now: Timestamp) -> Result, Error> { - columns - .iter() - .map(|column| { - let timestamp_type = column.data_type.as_timestamp().context(InvalidQuerySnafu { - reason: format!("Auto sink column {} is not a timestamp", column.name), - })?; - let value = if column.name == crate::adapter::AUTO_CREATED_UPDATE_AT_TS_COL { - now.convert_to(timestamp_type.unit()) - .context(InvalidQuerySnafu { - reason: "Current timestamp cannot be represented in sink timestamp unit", - })? - } else if column.name == crate::adapter::AUTO_CREATED_PLACEHOLDER_TS_COL { - Timestamp::new(0, timestamp_type.unit()) - } else { - return InvalidQuerySnafu { - reason: format!("Unsupported auto sink column {}", column.name), - } - .fail(); - }; - Ok(Value::Timestamp(value)) - }) - .collect() -} - -/// Executes one mirror write using only the supplied batch and writes its output. -pub(crate) async fn execute( - flow: &StatelessFlow, - rows: &[DiffRow], - batch_datatypes: &[datatypes::data_type::ConcreteDataType], - query_engine: &Arc, - frontend_client: &Arc, - current_source_schema_version: u32, -) -> Result { - validate_source_schema_version(flow.source_schema_version, current_source_schema_version)?; - let values = rows.iter().map(|(row, _, _)| row.clone()).collect(); - let batch = crate::expr::Batch::try_from_rows_with_types(values, batch_datatypes) - .map_err(BoxedError::new) - .context(ExternalSnafu)?; - let batch = RecordBatch::new(flow.source_schema.clone(), batch.batch().to_vec()) - .map_err(BoxedError::new) - .context(ExternalSnafu)?; - let provider = input_provider(&batch)?; - let source_ref = TableReference::full( - flow.source_table_name[0].clone(), - flow.source_table_name[1].clone(), - flow.source_table_name[2].clone(), - ); - let plan = replace_source(flow.plan.clone(), &source_ref, provider)?; - let output = query_engine - .execute(plan, flow.query_ctx.clone()) - .await - .map_err(BoxedError::new) - .context(ExternalSnafu)?; - let batches = match output.data { - OutputData::RecordBatches(batches) => batches, - OutputData::Stream(stream) => RecordBatches::try_collect(stream) - .await - .map_err(BoxedError::new) - .context(ExternalSnafu)?, - OutputData::AffectedRows(_) => { - return UnexpectedSnafu { - reason: "Streaming flow query returned affected rows", - } - .fail(); - } - }; - - let output_schema = batches - .schema() - .column_schemas() - .iter() - .cloned() - .map(|mut column| { - column.data_type = map_dictionary_to_values_data_type(&column.data_type); - column - }) - .collect::>(); - crate::adapter::validate_sink_layout_with_suffix( - &output_schema, - &flow.sink_schema, - &flow.auto_columns, - )?; - let mut output_rows = Vec::new(); - for batch in batches { - let vectors = datatypes::vectors::Helper::try_into_vectors(batch.columns()) - .map_err(BoxedError::new) - .context(ExternalSnafu)?; - output_rows.extend(vectors_to_rows(vectors.iter(), batch.num_rows())); - } - if output_rows.is_empty() { - return Ok(0); - } - - // Auto columns are deliberately synthesized here rather than in the query plan. This keeps - // one current timestamp for the whole request and preserves the sink's timestamp precision. - let auto_values = synthesize_auto_values(&flow.auto_columns, Timestamp::current_millis())? - .into_iter() - .map(to_grpc_value) - .collect::>(); - for row in &mut output_rows { - row.values.extend(auto_values.iter().cloned()); - } - - let output_row_count = output_rows.len(); - let proto_schema = column_schemas_to_proto(flow.sink_schema.clone(), &flow.sink_primary_keys)?; - let request = Request::RowInserts(RowInsertRequests { - inserts: vec![RowInsertRequest { - table_name: flow.sink_table_name[2].clone(), - rows: Some(Rows { - schema: proto_schema, - rows: output_rows, - }), - }], - }); - let mut peer = None; - frontend_client - .handle_insert_once( - request, - &flow.sink_table_name[0], - &flow.sink_table_name[1], - &mut peer, - ) - .await - .map_err(BoxedError::new) - .context(ExternalSnafu)?; - Ok(output_row_count) -} - -#[cfg(test)] -mod tests { - use datafusion::catalog::MemTable; - use datafusion::logical_expr::LogicalPlanBuilder; - use datatypes::data_type::ConcreteDataType; - use datatypes::schema::{ColumnSchema, Schema}; - use datatypes::vectors::{Int32Vector, TimestampMillisecondVector}; - use session::context::QueryContext; - - use super::*; - - #[test] - fn validation_accepts_distinct_over_one_source() { - let schema = Arc::new(Schema::new(vec![ColumnSchema::new( - "number", - ConcreteDataType::int32_datatype(), - false, - )])); - let plan = LogicalPlanBuilder::scan( - TableReference::bare("source"), - provider_as_source(provider(&schema, 1)), - None, - ) - .unwrap() - .project(vec![datafusion_expr::col("number")]) - .unwrap() - .distinct() - .unwrap() - .build() - .unwrap(); - assert!(validate_plan(&plan).is_ok()); - } - - #[test] - fn validation_rejects_plan_without_source_scan() { - let plan = LogicalPlan::EmptyRelation(datafusion_expr::logical_plan::EmptyRelation { - produce_one_row: false, - schema: Arc::new(DFSchema::empty()), - }); - assert!(validate_plan(&plan).is_err()); - } - - fn provider(schema: &SchemaRef, value: i32) -> Arc { - let batch = RecordBatch::new( - schema.clone(), - vec![Arc::new(Int32Vector::from_slice([value])) as datatypes::prelude::VectorRef], - ) - .unwrap(); - let arrow = batch.df_record_batch().clone(); - Arc::new(MemTable::try_new(arrow.schema(), vec![vec![arrow]]).unwrap()) - } - - #[test] - fn source_schema_version_must_match_retained_plan() { - assert!(validate_source_schema_version(7, 7).is_ok()); - - let error = validate_source_schema_version(7, 8).unwrap_err(); - assert!(matches!(error, Error::InvalidQuery { reason, .. } if - reason.contains("Source schema version changed from 7 to 8") - && reason.contains("recreate or recover") - )); - } - - #[test] - fn auto_values_use_the_sink_timestamp_units() { - let update_at = ColumnSchema::new( - crate::adapter::AUTO_CREATED_UPDATE_AT_TS_COL, - datatypes::data_type::ConcreteDataType::timestamp_second_datatype(), - true, - ); - let placeholder = ColumnSchema::new( - crate::adapter::AUTO_CREATED_PLACEHOLDER_TS_COL, - datatypes::data_type::ConcreteDataType::timestamp_nanosecond_datatype(), - true, - ); - let values = synthesize_auto_values( - &[update_at], - Timestamp::new(1_234, common_time::timestamp::TimeUnit::Millisecond), - ) - .unwrap(); - assert_eq!(values.len(), 1); - assert_eq!( - values[0].as_timestamp().unwrap().unit(), - common_time::timestamp::TimeUnit::Second - ); - assert!(values[0].as_timestamp().unwrap().value() > 0); - - let values = synthesize_auto_values( - &[ - ColumnSchema::new( - crate::adapter::AUTO_CREATED_UPDATE_AT_TS_COL, - datatypes::data_type::ConcreteDataType::timestamp_microsecond_datatype(), - true, - ), - placeholder, - ], - Timestamp::new(1_234, common_time::timestamp::TimeUnit::Millisecond), - ) - .unwrap(); - assert_eq!(values[1].as_timestamp().unwrap().value(), 0); - assert_eq!( - values[1].as_timestamp().unwrap().unit(), - common_time::timestamp::TimeUnit::Nanosecond - ); - } - - #[test] - fn auto_values_reject_arbitrary_columns() { - let column = ColumnSchema::new( - "other", - datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(), - true, - ); - assert!(synthesize_auto_values(&[column], Timestamp::current_millis()).is_err()); - } - - #[test] - fn rewrite_source_timestamp_appends_collision_free_hidden_output() { - let schema = Arc::new(Schema::new(vec![ - ColumnSchema::new("number", ConcreteDataType::int32_datatype(), false), - ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true), - ColumnSchema::new( - "__flow_source_timestamp", - ConcreteDataType::int32_datatype(), - false, - ), - ])); - let batch = RecordBatch::new( - schema.clone(), - vec![ - Arc::new(Int32Vector::from_slice([2])) as datatypes::prelude::VectorRef, - Arc::new(TimestampMillisecondVector::from_slice([42])) - as datatypes::prelude::VectorRef, - Arc::new(Int32Vector::from_slice([7])) as datatypes::prelude::VectorRef, - ], - ) - .unwrap(); - let plan = datafusion_expr::LogicalPlanBuilder::scan( - TableReference::bare("source"), - provider_as_source(input_provider(&batch).unwrap()), - None, - ) - .unwrap() - .filter(datafusion_expr::col("number").gt(datafusion_expr::lit(1))) - .unwrap() - .project(vec![datafusion_expr::col("number")]) - .unwrap() - .build() - .unwrap(); - let rewritten = - rewrite_source_timestamp(plan, &TableReference::bare("source"), "ts").unwrap(); - assert_eq!(rewritten.schema().fields().len(), 2); - assert!( - rewritten - .schema() - .field(1) - .name() - .starts_with("__flow_source_timestamp") - ); - } - - #[tokio::test] - async fn finite_projection_filter_does_not_retain_previous_batch() { - let schema = Arc::new(Schema::new(vec![ColumnSchema::new( - "number", - ConcreteDataType::int32_datatype(), - false, - )])); - let initial_provider = provider(&schema, 0); - let plan = test_source_plan(TableReference::bare("source"), initial_provider); - assert!(validate_plan(&plan).is_ok()); - - let engine = crate::test_utils::create_test_query_engine(); - let run = |input: Arc| { - let engine = engine.clone(); - let plan = plan.clone(); - async move { - let plan = replace_source(plan, &TableReference::bare("source"), input).unwrap(); - let output = engine.execute(plan, QueryContext::arc()).await.unwrap(); - match output.data { - OutputData::Stream(stream) => RecordBatches::try_collect(stream) - .await - .unwrap() - .iter() - .map(|batch| batch.num_rows()) - .sum(), - OutputData::RecordBatches(batches) => { - batches.iter().map(|batch| batch.num_rows()).sum() - } - OutputData::AffectedRows(_) => 0, - } - } - }; - - assert_eq!(run(provider(&schema, 1)).await, 0); - assert_eq!(run(provider(&schema, 2)).await, 1); - } - - #[tokio::test] - async fn finite_distinct_collapses_duplicates_per_request() { - let schema = Arc::new(Schema::new(vec![ColumnSchema::new( - "number", - ConcreteDataType::int32_datatype(), - false, - )])); - let input = |values: &[i32]| { - let batch = RecordBatch::new( - schema.clone(), - vec![Arc::new(Int32Vector::from_slice(values)) as datatypes::prelude::VectorRef], - ) - .unwrap(); - input_provider(&batch).unwrap() - }; - let plan = LogicalPlanBuilder::scan( - TableReference::bare("source"), - provider_as_source(input(&[1])), - None, - ) - .unwrap() - .project(vec![datafusion_expr::col("number")]) - .unwrap() - .distinct() - .unwrap() - .build() - .unwrap(); - assert!(validate_plan(&plan).is_ok()); - - let engine = crate::test_utils::create_test_query_engine(); - let run = |provider: Arc| { - let engine = engine.clone(); - let plan = plan.clone(); - async move { - let plan = replace_source(plan, &TableReference::bare("source"), provider).unwrap(); - let output = engine.execute(plan, QueryContext::arc()).await.unwrap(); - let batches = match output.data { - OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(), - OutputData::RecordBatches(batches) => batches, - OutputData::AffectedRows(_) => panic!("unexpected affected rows"), - }; - batches.iter().map(|batch| batch.num_rows()).sum::() - } - }; - - assert_eq!(run(input(&[1, 1, 2])).await, 2); - assert_eq!(run(input(&[1, 1])).await, 1); - } -} diff --git a/src/flow/src/adapter/table_source.rs b/src/flow/src/adapter/table_source.rs deleted file mode 100644 index ca0858df276..00000000000 --- a/src/flow/src/adapter/table_source.rs +++ /dev/null @@ -1,350 +0,0 @@ -// 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. - -//! How to query table information from database - -use common_error::ext::BoxedError; -use common_meta::key::table_info::{TableInfoManager, TableInfoValue}; -use common_meta::key::table_name::{TableNameKey, TableNameManager}; -use datatypes::schema::ColumnDefaultConstraint; -use serde::{Deserialize, Serialize}; -use snafu::{OptionExt, ResultExt}; -use table::metadata::TableId; - -use crate::adapter::TableName; -use crate::adapter::util::table_info_value_to_relation_desc; -use crate::error::{ - Error, ExternalSnafu, TableNotFoundMetaSnafu, TableNotFoundSnafu, UnexpectedSnafu, -}; -use crate::repr::RelationDesc; - -/// Table description, include relation desc and default values, which is the minimal information flow needed for table -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct TableDesc { - pub relation_desc: RelationDesc, - pub default_values: Vec>, -} - -impl TableDesc { - pub fn new( - relation_desc: RelationDesc, - default_values: Vec>, - ) -> Self { - Self { - relation_desc, - default_values, - } - } - - pub fn new_no_default(relation_desc: RelationDesc) -> Self { - Self { - relation_desc, - default_values: vec![], - } - } -} - -/// Table source but for flow, provide table schema by table name/id -#[async_trait::async_trait] -pub trait FlowTableSource: Send + Sync + std::fmt::Debug { - async fn table_name_from_id(&self, table_id: &TableId) -> Result; - async fn table_id_from_name(&self, name: &TableName) -> Result; - - /// Get the table schema by table name - async fn table(&self, name: &TableName) -> Result { - let id = self.table_id_from_name(name).await?; - self.table_from_id(&id).await - } - async fn table_from_id(&self, table_id: &TableId) -> Result; -} - -/// managed table source information, query from table info manager and table name manager -#[derive(Clone)] -pub struct ManagedTableSource { - /// for query `TableId -> TableName` mapping - table_info_manager: TableInfoManager, - table_name_manager: TableNameManager, -} - -#[async_trait::async_trait] -impl FlowTableSource for ManagedTableSource { - async fn table_from_id(&self, table_id: &TableId) -> Result { - let table_info_value = self - .get_table_info_value(table_id) - .await? - .with_context(|| TableNotFoundSnafu { - name: format!("TableId = {:?}, Can't found table info", table_id), - })?; - let desc = table_info_value_to_relation_desc(table_info_value)?; - - Ok(desc) - } - async fn table_name_from_id(&self, table_id: &TableId) -> Result { - self.get_table_name(table_id).await - } - async fn table_id_from_name(&self, name: &TableName) -> Result { - self.get_opt_table_id_from_name(name) - .await? - .with_context(|| TableNotFoundSnafu { - name: name.join("."), - }) - } -} - -impl ManagedTableSource { - pub fn new(table_info_manager: TableInfoManager, table_name_manager: TableNameManager) -> Self { - ManagedTableSource { - table_info_manager, - table_name_manager, - } - } - - /// Get the time index column from table id - pub async fn get_time_index_column_from_table_id( - &self, - table_id: TableId, - ) -> Result<(usize, datatypes::schema::ColumnSchema), Error> { - let info = self - .table_info_manager - .get(table_id) - .await - .map_err(BoxedError::new) - .context(ExternalSnafu)? - .context(UnexpectedSnafu { - reason: format!("Table id = {:?}, couldn't found table info", table_id), - })?; - let schema = &info.table_info.meta.schema; - let Some(ts_index) = schema.timestamp_index() else { - UnexpectedSnafu { - reason: format!("Table id = {:?}, couldn't found timestamp index", table_id), - } - .fail()? - }; - let col_schema = schema.column_schemas()[ts_index].clone(); - Ok((ts_index, col_schema)) - } - - pub async fn get_table_id_from_proto_name( - &self, - name: &greptime_proto::v1::TableName, - ) -> Result { - self.table_name_manager - .get(TableNameKey::new( - &name.catalog_name, - &name.schema_name, - &name.table_name, - )) - .await - .with_context(|_| TableNotFoundMetaSnafu { - msg: format!("Table name = {:?}, couldn't found table id", name), - })? - .with_context(|| UnexpectedSnafu { - reason: format!("Table name = {:?}, couldn't found table id", name), - }) - .map(|id| id.table_id()) - } - - /// If the table haven't been created in database, the tableId returned would be null - pub async fn get_opt_table_id_from_name( - &self, - name: &TableName, - ) -> Result, Error> { - let ret = self - .table_name_manager - .get(TableNameKey::new(&name[0], &name[1], &name[2])) - .await - .with_context(|_| TableNotFoundMetaSnafu { - msg: format!("Table name = {:?}, couldn't found table id", name), - })? - .map(|id| id.table_id()); - Ok(ret) - } - - /// query metasrv about the table name and table id - pub async fn get_table_name(&self, table_id: &TableId) -> Result { - self.table_info_manager - .get(*table_id) - .await - .map_err(BoxedError::new) - .context(ExternalSnafu)? - .with_context(|| UnexpectedSnafu { - reason: format!("Table id = {:?}, couldn't found table name", table_id), - }) - .map(|name| name.table_name()) - .map(|name| [name.catalog_name, name.schema_name, name.table_name]) - } - - /// query metasrv about the `TableInfoValue` and table id - pub async fn get_table_info_value( - &self, - table_id: &TableId, - ) -> Result, Error> { - Ok(self - .table_info_manager - .get(*table_id) - .await - .with_context(|_| TableNotFoundMetaSnafu { - msg: format!("TableId = {:?}, couldn't found table name", table_id), - })? - .map(|v| v.into_inner())) - } - - pub async fn get_table_name_schema( - &self, - table_id: &TableId, - ) -> Result<(TableName, TableDesc), Error> { - let table_info_value = self - .get_table_info_value(table_id) - .await? - .with_context(|| TableNotFoundSnafu { - name: format!("TableId = {:?}, Can't found table info", table_id), - })?; - - let table_name = table_info_value.table_name(); - let table_name = [ - table_name.catalog_name, - table_name.schema_name, - table_name.table_name, - ]; - - let desc = table_info_value_to_relation_desc(table_info_value)?; - Ok((table_name, desc)) - } - - pub async fn check_table_exist(&self, table_id: &TableId) -> Result { - self.table_info_manager - .exists(*table_id) - .await - .map_err(BoxedError::new) - .context(ExternalSnafu) - } -} - -impl std::fmt::Debug for ManagedTableSource { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("KvBackendTableSource").finish() - } -} - -#[cfg(test)] -pub(crate) mod test { - use std::collections::HashMap; - - use datatypes::data_type::ConcreteDataType as CDT; - - use super::*; - use crate::repr::{ColumnType, RelationType}; - - pub struct FlowDummyTableSource { - pub id_names_to_desc: Vec<(TableId, TableName, TableDesc)>, - id_to_idx: HashMap, - name_to_idx: HashMap, - } - - impl Default for FlowDummyTableSource { - fn default() -> Self { - let id_names_to_desc = vec![ - ( - 1024, - [ - "greptime".to_string(), - "public".to_string(), - "numbers".to_string(), - ], - TableDesc::new_no_default( - RelationType::new(vec![ColumnType::new(CDT::uint32_datatype(), false)]) - .into_named(vec![Some("number".to_string())]), - ), - ), - ( - 1025, - [ - "greptime".to_string(), - "public".to_string(), - "numbers_with_ts".to_string(), - ], - TableDesc::new_no_default( - RelationType::new(vec![ - ColumnType::new(CDT::uint32_datatype(), false), - ColumnType::new(CDT::timestamp_millisecond_datatype(), false), - ]) - .into_named(vec![Some("number".to_string()), Some("ts".to_string())]), - ), - ), - ]; - let id_to_idx = id_names_to_desc - .iter() - .enumerate() - .map(|(idx, (id, _name, _desc))| (*id, idx)) - .collect(); - let name_to_idx = id_names_to_desc - .iter() - .enumerate() - .map(|(idx, (_id, name, _desc))| (name.clone(), idx)) - .collect(); - Self { - id_names_to_desc, - id_to_idx, - name_to_idx, - } - } - } - - #[async_trait::async_trait] - impl FlowTableSource for FlowDummyTableSource { - async fn table_from_id(&self, table_id: &TableId) -> Result { - let idx = self.id_to_idx.get(table_id).context(TableNotFoundSnafu { - name: format!("Table id = {:?}, couldn't found table desc", table_id), - })?; - let desc = self - .id_names_to_desc - .get(*idx) - .map(|x| x.2.clone()) - .context(TableNotFoundSnafu { - name: format!("Table id = {:?}, couldn't found table desc", table_id), - })?; - Ok(desc) - } - - async fn table_name_from_id(&self, table_id: &TableId) -> Result { - let idx = self.id_to_idx.get(table_id).context(TableNotFoundSnafu { - name: format!("Table id = {:?}, couldn't found table desc", table_id), - })?; - self.id_names_to_desc - .get(*idx) - .map(|x| x.1.clone()) - .context(TableNotFoundSnafu { - name: format!("Table id = {:?}, couldn't found table desc", table_id), - }) - } - - async fn table_id_from_name(&self, name: &TableName) -> Result { - for (id, table_name, _desc) in &self.id_names_to_desc { - if name == table_name { - return Ok(*id); - } - } - TableNotFoundSnafu { - name: format!("Table name = {:?}, couldn't found table id", name), - } - .fail()? - } - } - - impl std::fmt::Debug for FlowDummyTableSource { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("DummyTableSource").finish() - } - } -} diff --git a/src/flow/src/adapter/tests.rs b/src/flow/src/adapter/tests.rs index 6a2bf5ed816..52867bcf760 100644 --- a/src/flow/src/adapter/tests.rs +++ b/src/flow/src/adapter/tests.rs @@ -12,197 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Mock test for adapter module -//! TODO(discord9): write mock test +//! Tests for the plan-to-schema helpers shared with batching mode. + +use std::sync::Arc; -use api::v1::SemanticType; use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit}; use datafusion::catalog::MemTable; use datafusion::datasource::provider_as_source; use datafusion_common::TableReference; -use datafusion_expr::{LogicalPlan, LogicalPlanBuilder}; -use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema, Schema, SchemaBuilder}; -use store_api::storage::{ConcreteDataType, TableId}; -use table::metadata::{TableInfo, TableInfoBuilder, TableMetaBuilder}; +use datafusion_expr::{LogicalPlanBuilder, col}; +use datatypes::schema::{ColumnSchema, Schema}; +use store_api::storage::ConcreteDataType; -use super::*; +use super::output_column_schemas; -#[test] -fn stateless_output_aliases_are_matched_by_position() { - let output = vec![ColumnSchema::new( - "output_alias", - ConcreteDataType::int32_datatype(), - false, - )]; - let sink = vec![ColumnSchema::new( - "sink_column", - ConcreteDataType::int32_datatype(), - false, - )]; - assert!(validate_sink_layout(&output, &sink).is_ok()); - let proto = crate::adapter::util::column_schemas_to_proto(sink, &[]).unwrap(); - assert_eq!(proto[0].column_name, "sink_column"); -} - -#[test] -fn stateless_sink_schema_has_tag_and_timestamp_semantics() { - let schema = vec![ - ColumnSchema::new("host", ConcreteDataType::string_datatype(), false), - ColumnSchema::new("ts", ConcreteDataType::timestamp_second_datatype(), false) - .with_time_index(true), - ]; - let proto = - crate::adapter::util::column_schemas_to_proto(schema, &["host".to_string()]).unwrap(); - assert_eq!(proto[0].semantic_type, SemanticType::Tag as i32); - assert_eq!(proto[1].semantic_type, SemanticType::Timestamp as i32); -} - -#[test] -fn stateless_resolves_suffix_by_output_arity() { - let ordinary = ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false); - let update_at = ColumnSchema::new( - AUTO_CREATED_UPDATE_AT_TS_COL, - ConcreteDataType::timestamp_second_datatype(), - true, - ); - // Equal arity is an ordinary sink, despite the reserved-looking name. - assert!( - resolve_sink_layout( - &[ordinary.clone(), update_at.clone()], - &[ordinary.clone(), update_at.clone()] - ) - .unwrap() - .is_empty() - ); - assert_eq!( - resolve_sink_layout( - std::slice::from_ref(&ordinary), - &[ordinary.clone(), update_at] - ) - .unwrap() - .len(), - 1 - ); -} - -#[test] -fn stateless_explicit_timestamp_compatibility_requires_default_and_lineage_absence() { - let source = Arc::new(Schema::new(vec![ - ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false), - ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true), - ])); - let output = vec![ColumnSchema::new( - "value", - ConcreteDataType::int32_datatype(), - false, - )]; - let sink_ts = ColumnSchema::new( - "event_time", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true) - .with_default_constraint(Some(ColumnDefaultConstraint::Function("now()".into()))) - .unwrap(); - assert!(is_explicit_source_timestamp_compatibility( - &output, - &[Some(0)], - &[output[0].clone(), sink_ts.clone()], - &source, - )); - assert!(!is_explicit_source_timestamp_compatibility( - &output, - &[Some(1)], - &[output[0].clone(), sink_ts], - &source, - )); - let sink_ts_without_default = ColumnSchema::new( - "event_time", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true); - assert!(!is_explicit_source_timestamp_compatibility( - &output, - &[Some(0)], - &[output[0].clone(), sink_ts_without_default], - &source, - )); -} - -#[test] -fn stateless_rejects_reserved_auto_names_for_auto_sink() { - assert!( - validate_auto_column_names(&[ColumnSchema::new( - AUTO_CREATED_UPDATE_AT_TS_COL, - ConcreteDataType::int32_datatype(), - true, - )]) - .is_err() - ); - assert!( - validate_auto_column_names(&[ColumnSchema::new( - AUTO_CREATED_PLACEHOLDER_TS_COL, - ConcreteDataType::int32_datatype(), - true, - )]) - .is_err() - ); -} - -#[test] -fn stateless_distinct_preserves_direct_column_lineage() { - let source = Arc::new(Schema::new(vec![ +fn source_schema() -> Arc { + Arc::new(Schema::new(vec![ ColumnSchema::new("number", ConcreteDataType::int32_datatype(), false), - ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true), - ])); - let provider = MemTable::try_new( - Arc::new(datafusion::arrow::datatypes::Schema::new(vec![ - Field::new("number", ArrowDataType::Int32, false), - Field::new( - "ts", - ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None), - false, - ), - ])), - vec![vec![]], - ) - .unwrap(); - let plan = LogicalPlanBuilder::scan( - TableReference::bare("source"), - provider_as_source(Arc::new(provider)), - None, - ) - .unwrap() - .project(vec![datafusion_expr::col("number").alias("dis")]) - .unwrap() - .distinct() - .unwrap() - .build() - .unwrap(); - - let (output, lineage) = super::output_column_schemas(&plan, &source).unwrap(); - assert_eq!(output[0].name, "dis"); - assert_eq!(lineage, vec![Some(0)]); - let relation = super::relation_desc_from_output(&output, &lineage, &[0], &plan); - assert_eq!(relation.typ.keys[0].column_indices, vec![0]); -} - -#[test] -fn stateless_distinct_output_is_always_the_sink_key() { - let source = Arc::new(Schema::new(vec![ - ColumnSchema::new("v", ConcreteDataType::int32_datatype(), true), - ColumnSchema::new("k", ConcreteDataType::int32_datatype(), true), ColumnSchema::new("other", ConcreteDataType::int32_datatype(), true), ColumnSchema::new( "ts", @@ -210,13 +36,14 @@ fn stateless_distinct_output_is_always_the_sink_key() { false, ) .with_time_index(true), - ])); - // All cases share one provider so the key assertions exercise only plan/output metadata. - let provider = Arc::new( + ])) +} + +fn source_provider() -> Arc { + Arc::new( MemTable::try_new( Arc::new(datafusion::arrow::datatypes::Schema::new(vec![ - Field::new("v", ArrowDataType::Int32, true), - Field::new("k", ArrowDataType::Int32, true), + Field::new("number", ArrowDataType::Int32, false), Field::new("other", ArrowDataType::Int32, true), Field::new( "ts", @@ -227,105 +54,59 @@ fn stateless_distinct_output_is_always_the_sink_key() { vec![vec![]], ) .unwrap(), - ); - let make_plan = |expressions: Vec, distinct: bool| { - let builder = LogicalPlanBuilder::scan( - TableReference::bare("source"), - provider_as_source(provider.clone()), - None, - ) - .unwrap() - .project(expressions) - .unwrap(); - if distinct { - builder.distinct().unwrap().build().unwrap() - } else { - builder.build().unwrap() - } - }; - let assert_key = |plan: &LogicalPlan, source_keys: &[usize], expected: &[usize]| { - let (output, lineage) = super::output_column_schemas(plan, &source).unwrap(); - let relation = super::relation_desc_from_output(&output, &lineage, source_keys, plan); - assert_eq!( - relation - .typ - .keys - .iter() - .map(|key| key.column_indices.clone()) - .collect::>(), - if expected.is_empty() { - vec![] - } else { - vec![expected.to_vec()] - } - ); - relation - }; - - // No source PK: all distinct output fields form the key. - assert_key(&make_plan(vec![datafusion_expr::col("v")], true), &[], &[0]); - // A surviving subset of a composite source PK cannot identify projected DISTINCT tuples. - assert_key( - &make_plan( - vec![datafusion_expr::col("v"), datafusion_expr::col("other")], - true, - ), - &[0, 1], - &[0, 1], - ); - // Even a retained source PK needs the additional selected fields in the DISTINCT key. - assert_key( - &make_plan( - vec![datafusion_expr::col("v"), datafusion_expr::col("other")], - true, - ), - &[0], - &[0, 1], - ); - // Aliases and computed output expressions are included by output position. - let alias_plan = make_plan( - vec![ - datafusion_expr::col("v").alias("renamed"), - (datafusion_expr::col("v") + datafusion_expr::col("other")).alias("computed"), - ], - true, - ); - let (output, lineage) = super::output_column_schemas(&alias_plan, &source).unwrap(); - let relation = super::relation_desc_from_output(&output, &lineage, &[0], &alias_plan); - assert_eq!( - output - .iter() - .map(|column| column.name.as_str()) - .collect_vec(), - ["renamed", "computed"] - ); - assert_eq!(relation.typ.keys[0].column_indices, vec![0, 1]); - - // A selected time index remains the relation time index, not part of the tag key. - let relation = assert_key( - &make_plan( - vec![datafusion_expr::col("v"), datafusion_expr::col("ts")], - true, - ), - &[0], - &[0], - ); - assert_eq!(relation.typ.time_index, Some(1)); - - // Non-DISTINCT plans retain only inherited source-key lineage (or no key if none survives). - let ordinary = make_plan( - vec![datafusion_expr::col("v"), datafusion_expr::col("other")], - false, - ); - assert_key(&ordinary, &[0, 1], &[0]); - assert_key(&ordinary, &[], &[]); + ) } #[test] -fn stateless_normalizes_dictionary_output_type() { +fn output_column_schemas_keeps_direct_column_lineage() { + let source = source_schema(); + let plan = LogicalPlanBuilder::scan( + TableReference::bare("source"), + provider_as_source(source_provider()), + None, + ) + .unwrap() + .project(vec![col("number").alias("dis")]) + .unwrap() + .distinct() + .unwrap() + .build() + .unwrap(); + + let (output, lineage) = output_column_schemas(&plan, &source).unwrap(); + // The output alias is kept, while the source column semantics and lineage survive. + assert_eq!(output[0].name, "dis"); + assert_eq!(lineage, vec![Some(0)]); +} + +#[test] +fn output_column_schemas_marks_computed_expressions_without_lineage() { + let source = source_schema(); + let plan = LogicalPlanBuilder::scan( + TableReference::bare("source"), + provider_as_source(source_provider()), + None, + ) + .unwrap() + .project(vec![ + col("number"), + (col("number") + col("other")).alias("computed"), + ]) + .unwrap() + .build() + .unwrap(); + + let (output, lineage) = output_column_schemas(&plan, &source).unwrap(); + assert_eq!(lineage, vec![Some(0), None]); + // A computed expression must not inherit the source timestamp semantics. + assert!(!output[1].is_time_index()); +} + +#[test] +fn output_column_schemas_normalizes_dictionary_output_type() { let field = Field::new_dictionary("host", ArrowDataType::UInt32, ArrowDataType::Utf8, true); let arrow_schema = Arc::new(datafusion::arrow::datatypes::Schema::new(vec![field])); - let provider = MemTable::try_new(arrow_schema.clone(), vec![vec![]]).unwrap(); + let provider = MemTable::try_new(arrow_schema, vec![vec![]]).unwrap(); let plan = LogicalPlanBuilder::scan( TableReference::bare("source"), provider_as_source(Arc::new(provider)), @@ -339,922 +120,8 @@ fn stateless_normalizes_dictionary_output_type() { ConcreteDataType::string_datatype(), true, )])); - let (output, lineage) = super::output_column_schemas(&plan, &source).unwrap(); + + let (output, lineage) = output_column_schemas(&plan, &source).unwrap(); assert_eq!(output[0].data_type, ConcreteDataType::string_datatype()); assert_eq!(lineage, vec![Some(0)]); - - let relation = super::relation_desc_from_output(&output, &lineage, &[0], &plan); - assert_eq!(relation.typ.keys[0].column_indices, vec![0]); -} - -#[test] -fn stateless_allows_only_trailing_auto_columns() { - let ordinary = ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false); - let update_at = ColumnSchema::new( - AUTO_CREATED_UPDATE_AT_TS_COL, - ConcreteDataType::timestamp_second_datatype(), - true, - ); - let placeholder = ColumnSchema::new( - AUTO_CREATED_PLACEHOLDER_TS_COL, - ConcreteDataType::timestamp_microsecond_datatype(), - true, - ) - .with_time_index(true); - - assert_eq!( - sink_output_column_count(&[ordinary.clone(), update_at.clone()]).unwrap(), - 1 - ); - assert_eq!( - sink_output_column_count(&[ordinary.clone(), update_at, placeholder]).unwrap(), - 1 - ); - assert!( - validate_sink_layout( - std::slice::from_ref(&ordinary), - std::slice::from_ref(&ordinary) - ) - .is_ok() - ); - assert!( - validate_sink_layout( - &[ordinary], - &[ - ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false), - ColumnSchema::new("unexpected", ConcreteDataType::int32_datatype(), false), - ] - ) - .is_err() - ); -} - -pub fn new_test_table_info_with_name>( - table_id: TableId, - table_name: &str, - _region_numbers: I, -) -> TableInfo { - let column_schemas = vec![ - ColumnSchema::new("number", ConcreteDataType::int32_datatype(), true), - ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true), - ]; - let schema = SchemaBuilder::try_from(column_schemas) - .unwrap() - .version(123) - .build() - .unwrap(); - - let meta = TableMetaBuilder::empty() - .schema(Arc::new(schema)) - .primary_key_indices(vec![0]) - .engine("engine") - .next_column_id(3) - .build() - .unwrap(); - TableInfoBuilder::default() - .table_id(table_id) - .table_version(5) - .name(table_name) - .meta(meta) - .build() - .unwrap() -} - -/// Create a mock harness for flow node manager -/// -/// containing several default table info and schema -fn mock_harness_flow_node_manager() {} - -#[test] -fn stateless_captured_slot_rejects_inactive_or_detached_slot() { - let slot = super::StatelessFlowSlot { - runtime: Arc::new(tokio::sync::RwLock::new( - super::StatelessFlowRuntime::default(), - )), - active: std::sync::atomic::AtomicBool::new(false), - rebuild_attempts: std::sync::atomic::AtomicUsize::new(0), - }; - - assert!(super::validate_captured_slot(&slot, None, 1, 42).is_err()); -} - -#[test] -fn stateless_captured_slot_rejects_source_mismatch() { - let slot = super::StatelessFlowSlot { - runtime: Arc::new(tokio::sync::RwLock::new( - super::StatelessFlowRuntime::default(), - )), - active: std::sync::atomic::AtomicBool::new(true), - rebuild_attempts: std::sync::atomic::AtomicUsize::new(0), - }; - - assert!(super::validate_captured_slot(&slot, Some(2), 1, 42).is_err()); -} - -#[derive(Default)] -struct RecordingSink { - inserts: std::sync::Mutex>, - failed_calls: std::sync::atomic::AtomicUsize, -} - -#[async_trait::async_trait] -impl crate::batching_mode::frontend_client::GrpcQueryHandlerWithBoxedError for RecordingSink { - async fn do_query( - &self, - request: api::v1::greptime_request::Request, - _: session::context::QueryContextRef, - ) -> std::result::Result { - let api::v1::greptime_request::Request::RowInserts(request) = request else { - panic!("unexpected frontend request"); - }; - if request - .inserts - .iter() - .any(|insert| insert.table_name == "failed_sink") - { - self.failed_calls - .fetch_add(1, std::sync::atomic::Ordering::Relaxed); - return Err(BoxedError::new( - InvalidQuerySnafu { - reason: "injected sink failure", - } - .build(), - )); - } - let count = request - .inserts - .iter() - .map(|insert| insert.rows.as_ref().unwrap().rows.len()) - .sum(); - self.inserts.lock().unwrap().extend(request.inserts); - Ok(common_query::Output::new_with_affected_rows(count)) - } -} - -struct StreamingHarness { - engine: StreamingEngine, - metadata: TableMetadataManagerRef, - catalog: Arc, - sink: Arc, -} - -impl StreamingHarness { - async fn new() -> Self { - let metadata = Arc::new(common_meta::key::TableMetadataManager::new(Arc::new( - common_meta::kv_backend::memory::MemoryKvBackend::new(), - ))); - metadata.init().await.unwrap(); - let catalog = catalog::memory::new_memory_catalog_manager().unwrap(); - let query = query::QueryEngineFactory::new( - catalog.clone(), - None, - None, - None, - None, - false, - QueryOptions::default(), - ) - .query_engine(); - let sink = Arc::new(RecordingSink::default()); - let handler: Arc< - dyn crate::batching_mode::frontend_client::GrpcQueryHandlerWithBoxedError, - > = sink.clone(); - let frontend = - FrontendClient::from_grpc_handler(Arc::downgrade(&handler), QueryOptions::default()); - Self { - engine: StreamingEngine::new(None, query, metadata.clone(), Arc::new(frontend)), - metadata, - catalog, - sink, - } - } - - async fn table(&self, id: u32, name: &str) -> TableInfo { - let info = new_test_table_info_with_name(id, name, []); - self.metadata - .create_table_metadata( - info.clone(), - common_meta::key::table_route::TableRouteValue::physical(vec![]), - Default::default(), - ) - .await - .unwrap(); - self.register(&info); - info - } - - fn register(&self, info: &TableInfo) { - self.catalog - .register_table_sync(catalog::RegisterTableRequest { - catalog: info.catalog_name.clone(), - schema: info.schema_name.clone(), - table_name: info.name.clone(), - table_id: info.ident.table_id, - table: table::test_util::EmptyTable::from_table_info(info), - }) - .unwrap(); - } - - async fn flow(&self, id: FlowId, source: u32, sink: &str, sql: &str) { - self.engine - .create_flow_inner(CreateFlowArgs { - flow_id: id, - source_table_ids: vec![source], - sink_table_name: ["greptime".into(), "public".into(), sink.into()], - create_if_not_exists: false, - or_replace: false, - expire_after: None, - eval_interval: None, - comment: None, - sql: sql.into(), - flow_options: Default::default(), - query_ctx: Some(session::context::QueryContext::arc().as_ref().clone()), - eval_schedule: None, - }) - .await - .unwrap(); - } - - fn take_numbers(&self) -> Vec<(String, Vec)> { - let inserts = std::mem::take(&mut *self.sink.inserts.lock().unwrap()); - inserts - .into_iter() - .map(|insert| { - let mut values = insert - .rows - .unwrap() - .rows - .into_iter() - .map(|row| { - let Some(api::v1::value::ValueData::I32Value(value)) = - row.values[0].value_data - else { - panic!("expected int32 output"); - }; - value - }) - .collect::>(); - values.sort_unstable(); - (insert.table_name, values) - }) - .collect() - } -} - -fn mirror_request(table: u32, region: u32, values: &[i32]) -> api::v1::region::InsertRequest { - use api::v1::value::ValueData; - api::v1::region::InsertRequest { - region_id: RegionId::new(table, region).as_u64(), - rows: Some(api::v1::Rows { - schema: util::column_schemas_to_proto( - vec![ - ColumnSchema::new("number", ConcreteDataType::int32_datatype(), true), - ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true), - ], - &["number".into()], - ) - .unwrap(), - rows: values - .iter() - .map(|value| api::v1::Row { - values: vec![ - api::v1::Value { - value_data: Some(ValueData::I32Value(*value)), - }, - api::v1::Value { - value_data: Some(ValueData::TimestampMillisecondValue(1)), - }, - ], - }) - .collect(), - }), - ..Default::default() - } -} - -#[tokio::test] -async fn stateless_rejects_aggregate_flow_with_actionable_diagnostic() { - let h = StreamingHarness::new().await; - h.table(1, "source").await; - - let err = h - .engine - .create_flow_inner(CreateFlowArgs { - flow_id: 1, - source_table_ids: vec![1], - sink_table_name: ["greptime".into(), "public".into(), "sink".into()], - create_if_not_exists: true, - or_replace: true, - expire_after: None, - eval_interval: None, - comment: None, - sql: "SELECT number, count(*) FROM source GROUP BY number".into(), - flow_options: Default::default(), - query_ctx: Some(session::context::QueryContext::arc().as_ref().clone()), - eval_schedule: None, - }) - .await - .unwrap_err(); - - let message = err.to_string(); - assert!(message.contains( - "Aggregation is unsupported in streaming flows. Recreate the flow to select batching mode." - )); - assert!( - message.contains("A source table with TTL=instant must use persisted retention first.") - ); - assert!(message.contains("Aggregation SQL without a time window requires EVAL INTERVAL.")); - assert!(!h.engine.flow_exist_inner(1).await.unwrap()); - assert!(h.take_numbers().is_empty()); -} - -#[tokio::test] -async fn stateless_failed_flow_and_table_do_not_starve_healthy_sinks() { - let h = StreamingHarness::new().await; - h.table(1, "source_a").await; - h.table(2, "source_b").await; - h.table(3, "failed_sink").await; - h.table(4, "healthy_a").await; - h.table(5, "healthy_b").await; - h.flow(1, 1, "failed_sink", "SELECT number, ts FROM source_a") - .await; - h.flow(2, 1, "healthy_a", "SELECT number, ts FROM source_a") - .await; - h.flow(3, 2, "healthy_b", "SELECT number, ts FROM source_b") - .await; - assert!( - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[11]), mirror_request(2, 0, &[22])], - }) - .await - .is_err() - ); - assert_eq!( - h.take_numbers(), - vec![ - ("healthy_a".into(), vec![11]), - ("healthy_b".into(), vec![22]) - ] - ); - let failed_slot = h - .engine - .flow_ids_for_table(1) - .await - .into_iter() - .find(|(id, _)| *id == 1) - .unwrap() - .1; - assert!(failed_slot.runtime.read().await.failed_rebuild.is_none()); - assert!( - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[12])], - }) - .await - .is_err() - ); - assert_eq!(h.take_numbers(), vec![("healthy_a".into(), vec![12])]); - assert_eq!( - h.sink - .failed_calls - .load(std::sync::atomic::Ordering::Relaxed), - 2 - ); - assert!(failed_slot.runtime.read().await.failed_rebuild.is_none()); - - let mut malformed = mirror_request(1, 1, &[99]); - malformed.rows.as_mut().unwrap().schema.pop(); - assert!( - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![ - mirror_request(1, 0, &[33]), - malformed, - mirror_request(1, 2, &[44]), - mirror_request(2, 0, &[55]) - ], - }) - .await - .is_err() - ); - assert_eq!(h.take_numbers(), vec![("healthy_b".into(), vec![55])]); - h.engine.remove_flow_inner(1).await.unwrap(); - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[66])], - }) - .await - .unwrap(); - assert_eq!(h.take_numbers(), vec![("healthy_a".into(), vec![66])]); -} - -#[tokio::test] -async fn stateless_distinct_groups_regions_without_retaining_previous_envelope() { - let h = StreamingHarness::new().await; - h.table(1, "source").await; - h.table(2, "sink").await; - h.flow( - 1, - 1, - "sink", - "SELECT DISTINCT number AS value, ts FROM source", - ) - .await; - for _ in 0..2 { - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[1, 2]), mirror_request(1, 1, &[2, 3])], - }) - .await - .unwrap(); - assert_eq!(h.take_numbers(), vec![("sink".into(), vec![1, 2, 3])]); - } -} - -#[tokio::test] -async fn stateless_schema_bump_rebuilds_for_current_and_subsequent_writes() { - let h = StreamingHarness::new().await; - let mut source = h.table(1, "source").await; - h.table(2, "sink").await; - h.flow(1, 1, "sink", "SELECT number, ts FROM source").await; - let current = h - .metadata - .table_info_manager() - .get(1) - .await - .unwrap() - .unwrap(); - let mut columns = source.meta.schema.column_schemas().to_vec(); - columns.push(ColumnSchema::new( - "extra", - ConcreteDataType::int32_datatype(), - true, - )); - source.meta.schema = Arc::new( - SchemaBuilder::try_from(columns) - .unwrap() - .version(124) - .build() - .unwrap(), - ); - h.metadata - .update_table_info(¤t, None, source.clone()) - .await - .unwrap(); - // The metadata is newer than the catalog provider: do not publish a plan - // carrying old column indices under the new version. - assert!( - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[99])], - }) - .await - .is_err() - ); - assert!(h.take_numbers().is_empty()); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: source.catalog_name.clone(), - schema: source.schema_name.clone(), - table_name: source.name.clone(), - }) - .unwrap(); - h.register(&source); - let slot = h - .engine - .flow_ids_for_table(1) - .await - .into_iter() - .find(|(id, _)| *id == 1) - .unwrap() - .1; - assert_eq!( - slot.runtime - .read() - .await - .flow - .as_ref() - .unwrap() - .source_schema_version, - 123 - ); - // The stale-provider failure above is cooled down; expire this private test deadline - // after repairing the catalog so the existing rebuild behavior remains deterministic. - slot.runtime.write().await.failed_rebuild = Some((124, tokio::time::Instant::now())); - let (left_rows, types, version) = h - .engine - .handle_insert_request(mirror_request(1, 0, &[5])) - .await - .unwrap(); - let (right_rows, _, _) = h - .engine - .handle_insert_request(mirror_request(1, 1, &[6])) - .await - .unwrap(); - // Queue both readers behind a writer. Releasing it grants both readers, - // so neither rebuild can publish before both writes observe the old runtime. - let lease = slot.runtime.write().await; - let left = h - .engine - .execute_flow(1, slot.clone(), 1, left_rows, &types, version); - let right = h - .engine - .execute_flow(1, slot.clone(), 1, right_rows, &types, version); - tokio::pin!(left, right); - assert!(futures::poll!(&mut left).is_pending()); - assert!(futures::poll!(&mut right).is_pending()); - drop(lease); - let (left, right) = tokio::join!(left, right); - left.unwrap(); - right.unwrap(); - let mut inserted = h.take_numbers(); - inserted.sort(); - assert_eq!( - inserted, - vec![("sink".into(), vec![5]), ("sink".into(), vec![6])] - ); - assert_eq!( - slot.runtime - .read() - .await - .flow - .as_ref() - .unwrap() - .source_schema_version, - 124 - ); - for number in [7, 8] { - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[number])], - }) - .await - .unwrap(); - assert_eq!(h.take_numbers(), vec![("sink".into(), vec![number])]); - } -} - -#[tokio::test] -async fn stateless_failed_schema_rebuild_is_cooled_down_and_retried() { - let h = StreamingHarness::new().await; - let mut source = h.table(1, "source").await; - let mut sink = h.table(2, "sink").await; - h.table(3, "healthy_sink").await; - h.flow(1, 1, "sink", "SELECT * FROM source").await; - h.flow(2, 1, "healthy_sink", "SELECT number, ts FROM source") - .await; - let slot = h - .engine - .flow_ids_for_table(1) - .await - .into_iter() - .find(|(id, _)| *id == 1) - .unwrap() - .1; - let current = h - .metadata - .table_info_manager() - .get(1) - .await - .unwrap() - .unwrap(); - let mut columns = source.meta.schema.column_schemas().to_vec(); - columns.push(ColumnSchema::new( - "extra", - ConcreteDataType::int32_datatype(), - true, - )); - source.meta.schema = Arc::new( - SchemaBuilder::try_from(columns.clone()) - .unwrap() - .version(124) - .build() - .unwrap(), - ); - h.metadata - .update_table_info(¤t, None, source.clone()) - .await - .unwrap(); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: source.catalog_name.clone(), - schema: source.schema_name.clone(), - table_name: source.name.clone(), - }) - .unwrap(); - h.register(&source); - - // Queue two stale runtimes before either can take the publication writer. The second - // must recheck the failed attempt under the writer rather than rebuilding again. - let (left_rows, types, version) = h - .engine - .handle_insert_request(mirror_request(1, 0, &[1])) - .await - .unwrap(); - let (right_rows, _, _) = h - .engine - .handle_insert_request(mirror_request(1, 1, &[2])) - .await - .unwrap(); - let lease = slot.runtime.write().await; - let left = h - .engine - .execute_flow(1, slot.clone(), 1, left_rows, &types, version); - let right = h - .engine - .execute_flow(1, slot.clone(), 1, right_rows, &types, version); - tokio::pin!(left, right); - assert!(futures::poll!(&mut left).is_pending()); - assert!(futures::poll!(&mut right).is_pending()); - drop(lease); - let (left, right) = tokio::join!(left, right); - let errors = [ - left.unwrap_err().to_string(), - right.unwrap_err().to_string(), - ]; - assert!( - errors - .iter() - .any(|error| error.contains("Flow output has 3 columns, but sink has 2 columns")) - ); - assert!(errors.iter().any(|error| { - error.contains("Flow 1 schema rebuild for source version 124 is cooling down") - })); - assert_eq!( - slot.rebuild_attempts - .load(std::sync::atomic::Ordering::Relaxed), - 1 - ); - let deadline = slot.runtime.read().await.failed_rebuild.unwrap(); - - // SELECT * is still invalid, while the sibling flow keeps producing output. - assert!( - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[3])], - }) - .await - .is_err() - ); - assert_eq!(h.take_numbers(), vec![("healthy_sink".into(), vec![3])]); - assert_eq!(slot.runtime.read().await.failed_rebuild, Some(deadline)); - assert_eq!( - slot.rebuild_attempts - .load(std::sync::atomic::Ordering::Relaxed), - 1 - ); - - // A new source version bypasses the old version's cooldown immediately. - let current = h - .metadata - .table_info_manager() - .get(1) - .await - .unwrap() - .unwrap(); - source.meta.schema = Arc::new( - SchemaBuilder::try_from(columns.clone()) - .unwrap() - .version(125) - .build() - .unwrap(), - ); - h.metadata - .update_table_info(¤t, None, source.clone()) - .await - .unwrap(); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: source.catalog_name.clone(), - schema: source.schema_name.clone(), - table_name: source.name.clone(), - }) - .unwrap(); - h.register(&source); - assert!( - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[5])], - }) - .await - .is_err() - ); - assert_eq!( - slot.rebuild_attempts - .load(std::sync::atomic::Ordering::Relaxed), - 2 - ); - assert_eq!(h.take_numbers(), vec![("healthy_sink".into(), vec![5])]); - - // Make the rebuilt SELECT * layout valid, then expire only this test's private deadline. - let current_sink = h - .metadata - .table_info_manager() - .get(2) - .await - .unwrap() - .unwrap(); - sink.meta.schema = Arc::new( - SchemaBuilder::try_from(columns) - .unwrap() - .version(124) - .build() - .unwrap(), - ); - h.metadata - .update_table_info(¤t_sink, None, sink.clone()) - .await - .unwrap(); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: source.catalog_name.clone(), - schema: source.schema_name.clone(), - table_name: source.name.clone(), - }) - .unwrap(); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: sink.catalog_name.clone(), - schema: sink.schema_name.clone(), - table_name: sink.name.clone(), - }) - .unwrap(); - h.register(&source); - h.register(&sink); - slot.runtime.write().await.failed_rebuild = Some((125, tokio::time::Instant::now())); - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[6])], - }) - .await - .unwrap(); - assert_eq!( - slot.rebuild_attempts - .load(std::sync::atomic::Ordering::Relaxed), - 3 - ); - assert!(slot.runtime.read().await.failed_rebuild.is_none()); - let mut inserted = h.take_numbers(); - inserted.sort(); - assert_eq!( - inserted, - vec![("healthy_sink".into(), vec![6]), ("sink".into(), vec![6])] - ); - - // IF NOT EXISTS is a no-op and preserves cooldown; a successful replacement clears it. - let current = h - .metadata - .table_info_manager() - .get(1) - .await - .unwrap() - .unwrap(); - let mut columns = source.meta.schema.column_schemas().to_vec(); - columns.push(ColumnSchema::new( - "extra2", - ConcreteDataType::int32_datatype(), - true, - )); - source.meta.schema = Arc::new( - SchemaBuilder::try_from(columns) - .unwrap() - .version(126) - .build() - .unwrap(), - ); - h.metadata - .update_table_info(¤t, None, source.clone()) - .await - .unwrap(); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: source.catalog_name.clone(), - schema: source.schema_name.clone(), - table_name: source.name.clone(), - }) - .unwrap(); - h.register(&source); - assert!( - h.engine - .handle_inserts_inner(api::v1::region::InsertRequests { - requests: vec![mirror_request(1, 0, &[7])], - }) - .await - .is_err() - ); - assert_eq!(h.take_numbers(), vec![("healthy_sink".into(), vec![7])]); - let cooldown = slot.runtime.read().await.failed_rebuild.unwrap(); - let mut args = slot - .runtime - .read() - .await - .flow - .as_ref() - .unwrap() - .create_args - .clone(); - args.or_replace = true; - assert!(h.engine.create_flow_inner(args.clone()).await.is_err()); - assert_eq!(slot.runtime.read().await.failed_rebuild, Some(cooldown)); - let current_sink = h - .metadata - .table_info_manager() - .get(2) - .await - .unwrap() - .unwrap(); - sink.meta.schema = source.meta.schema.clone(); - h.metadata - .update_table_info(¤t_sink, None, sink.clone()) - .await - .unwrap(); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: source.catalog_name.clone(), - schema: source.schema_name.clone(), - table_name: source.name.clone(), - }) - .unwrap(); - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: sink.catalog_name.clone(), - schema: sink.schema_name.clone(), - table_name: sink.name.clone(), - }) - .unwrap(); - h.register(&source); - h.register(&sink); - args.or_replace = false; - args.create_if_not_exists = true; - h.engine.create_flow_inner(args.clone()).await.unwrap(); - assert_eq!(slot.runtime.read().await.failed_rebuild, Some(cooldown)); - args.create_if_not_exists = false; - args.or_replace = true; - h.engine.create_flow_inner(args).await.unwrap(); - assert!(slot.runtime.read().await.failed_rebuild.is_none()); -} - -#[tokio::test] -async fn stateless_rejects_wrong_provider_identity_and_detached_lifecycle() { - let h = StreamingHarness::new().await; - let source = h.table(1, "source").await; - h.table(2, "sink").await; - h.flow(1, 1, "sink", "SELECT number, ts FROM source").await; - let old_slot = h.engine.flow_ids_for_table(1).await.pop().unwrap().1; - old_slot.runtime.write().await.failed_rebuild = Some((123, tokio::time::Instant::now())); - let (rows, types, version) = h - .engine - .handle_insert_request(mirror_request(1, 0, &[9])) - .await - .unwrap(); - h.engine.remove_flow_inner(1).await.unwrap(); - h.flow(1, 1, "sink", "SELECT number, ts FROM source").await; - let fresh_slot = h.engine.flow_ids_for_table(1).await.pop().unwrap().1; - assert!(fresh_slot.runtime.read().await.failed_rebuild.is_none()); - assert!( - h.engine - .execute_flow(1, old_slot, 1, rows, &types, version) - .await - .is_err() - ); - assert!(h.take_numbers().is_empty()); - - h.catalog - .deregister_table_sync(catalog::DeregisterTableRequest { - catalog: source.catalog_name.clone(), - schema: source.schema_name.clone(), - table_name: source.name.clone(), - }) - .unwrap(); - let mut wrong = source.clone(); - wrong.ident.table_id = 99; - h.register(&wrong); - let args = h - .engine - .stateless_flows - .read() - .await - .get(&1) - .unwrap() - .runtime - .read() - .await - .flow - .as_ref() - .unwrap() - .create_args - .clone(); - assert!(h.engine.build_stateless_flow(&args, false).await.is_err()); - assert!(h.take_numbers().is_empty()); } diff --git a/src/flow/src/adapter/util.rs b/src/flow/src/adapter/util.rs index f4b1d0396d6..0c069b5cdcf 100644 --- a/src/flow/src/adapter/util.rs +++ b/src/flow/src/adapter/util.rs @@ -15,134 +15,11 @@ //! Util functions for adapter use api::helper::ColumnDataTypeWrapper; -use api::v1::column_def::options_from_column_schema; -use api::v1::{ColumnDataType, ColumnDataTypeExtension, SemanticType}; use common_error::ext::BoxedError; -use common_meta::key::table_info::TableInfoValue; use datatypes::prelude::ConcreteDataType; -use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; -use itertools::Itertools; -use operator::expr_helper; use snafu::ResultExt; -use table::table_reference::TableReference; -use crate::StreamingEngine; -use crate::adapter::table_source::TableDesc; -use crate::adapter::{AUTO_CREATED_PLACEHOLDER_TS_COL, TableName}; use crate::error::{Error, ExternalSnafu}; -use crate::repr::{ColumnType, RelationDesc, RelationType}; -impl StreamingEngine { - /// Create table from given schema(will adjust to add auto column if needed), return true if table is created - pub(crate) async fn create_table_from_relation( - &self, - flow_name: &str, - table_name: &TableName, - relation_desc: &RelationDesc, - ) -> Result { - if self.fetch_table_pk_schema(table_name).await?.is_some() { - return Ok(false); - } - let (pks, tys, _) = self.adjust_auto_created_table_schema(relation_desc).await?; - - //create sink table using pks, column types and is_ts_auto - - let proto_schema = column_schemas_to_proto(tys.clone(), &pks)?; - - // create sink table - let create_expr = expr_helper::create_table_expr_by_column_schemas( - &TableReference { - catalog: &table_name[0], - schema: &table_name[1], - table: &table_name[2], - }, - &proto_schema, - "mito", - Some(&format!("Sink table for flow {}", flow_name)), - ) - .map_err(BoxedError::new) - .context(ExternalSnafu)?; - - self.frontend_client - .create(create_expr, &table_name[0], &table_name[1]) - .await?; - Ok(true) - } - - /// Try fetch table with adjusted schema(added auto column if needed) - pub(crate) async fn try_fetch_existing_table( - &self, - table_name: &TableName, - ) -> Result)>, Error> { - if let Some((primary_keys, time_index, schema)) = - self.fetch_table_pk_schema(table_name).await? - { - // check if the last column is the auto created timestamp column, hence the table is auto created from - // flow's plan type - let is_auto_create = { - let correct_name = schema - .last() - .map(|s| s.name == AUTO_CREATED_PLACEHOLDER_TS_COL) - .unwrap_or(false); - let correct_time_index = time_index == Some(schema.len() - 1); - correct_name && correct_time_index - }; - let proto_schema = column_schemas_to_proto(schema, &primary_keys)?; - Ok(Some((is_auto_create, proto_schema))) - } else { - Ok(None) - } - } -} - -pub fn table_info_value_to_relation_desc( - table_info_value: TableInfoValue, -) -> Result { - let raw_schema = table_info_value.table_info.meta.schema; - let (column_types, col_names): (Vec<_>, Vec<_>) = raw_schema - .column_schemas() - .to_vec() - .into_iter() - .map(|col| { - ( - ColumnType { - nullable: col.is_nullable(), - scalar_type: col.data_type, - }, - Some(col.name), - ) - }) - .unzip(); - - let key = table_info_value.table_info.meta.primary_key_indices; - let keys = vec![crate::repr::Key::from(key)]; - - let time_index = raw_schema.timestamp_index(); - let relation_desc = RelationDesc { - typ: RelationType { - column_types, - keys, - time_index, - // by default table schema's column are all non-auto - auto_columns: vec![], - }, - names: col_names, - }; - let default_values = raw_schema - .column_schemas() - .iter() - .map(|c| { - c.default_constraint().cloned().or_else(|| { - if c.is_nullable() { - Some(ColumnDefaultConstraint::null_value()) - } else { - None - } - }) - }) - .collect_vec(); - - Ok(TableDesc::new(relation_desc, default_values)) -} pub fn from_proto_to_data_type( column_schema: &api::v1::ColumnSchema, @@ -157,68 +34,3 @@ pub fn from_proto_to_data_type( Ok(cdt) } - -/// convert `ColumnSchema` lists to it's corresponding proto type -pub fn column_schemas_to_proto( - column_schemas: Vec, - primary_keys: &[String], -) -> Result, Error> { - let column_datatypes: Vec<(ColumnDataType, Option)> = column_schemas - .iter() - .map(|c| { - ColumnDataTypeWrapper::try_from(c.data_type.clone()) - .map(|w| w.to_parts()) - .map_err(BoxedError::new) - .context(ExternalSnafu) - }) - .try_collect()?; - - let ret = column_schemas - .iter() - .zip(column_datatypes) - .map(|(schema, datatype)| { - let semantic_type = if schema.is_time_index() { - SemanticType::Timestamp - } else if primary_keys.contains(&schema.name) { - SemanticType::Tag - } else { - SemanticType::Field - } as i32; - - api::v1::ColumnSchema { - column_name: schema.name.clone(), - datatype: datatype.0 as i32, - semantic_type, - datatype_extension: datatype.1, - options: options_from_column_schema(schema), - } - }) - .collect(); - Ok(ret) -} - -/// Convert `RelationDesc` to `ColumnSchema` list, -/// if the column name is not present, use `col_{idx}` as the column name -pub fn relation_desc_to_column_schemas_with_fallback(schema: &RelationDesc) -> Vec { - schema - .typ() - .column_types - .clone() - .into_iter() - .enumerate() - .map(|(idx, typ)| { - let name = schema - .names - .get(idx) - .cloned() - .flatten() - .unwrap_or(format!("col_{}", idx)); - let ret = ColumnSchema::new(name, typ.scalar_type, typ.nullable); - if schema.typ().time_index == Some(idx) { - ret.with_time_index(true) - } else { - ret - } - }) - .collect_vec() -} diff --git a/src/flow/src/batching_mode/frontend_client.rs b/src/flow/src/batching_mode/frontend_client.rs index 6e1184490aa..8ef99101930 100644 --- a/src/flow/src/batching_mode/frontend_client.rs +++ b/src/flow/src/batching_mode/frontend_client.rs @@ -586,87 +586,6 @@ impl FrontendClient { } } - /// Handle an insert request with one attempt. - /// - /// Unlike [`Self::handle`], this does not use the batching retry policy. It - /// is intended for stateless streaming sinks, where retrying an insert can - /// duplicate rows. - pub(crate) async fn handle_insert_once( - &self, - req: api::v1::greptime_request::Request, - catalog: &str, - schema: &str, - peer_desc: &mut Option, - ) -> Result { - match self { - FrontendClient::Distributed { .. } => { - let db = self.get_random_active_frontend(catalog, schema).await?; - - *peer_desc = Some(PeerDesc::Dist { - peer: db.peer.clone(), - }); - - db.database - .handle(req.clone()) - .await - .with_context(|_| InvalidRequestSnafu { - context: format!("Failed to handle request at {:?}: {:?}", db.peer, req), - }) - } - FrontendClient::Standalone { - database_client, - query, - .. - } => { - let ctx = QueryContextBuilder::default() - .current_catalog(catalog.to_string()) - .current_schema(schema.to_string()) - .channel(Channel::Internal) - .extensions(if query.parallelism > 0 { - HashMap::from([( - QUERY_PARALLELISM_HINT.to_string(), - query.parallelism.to_string(), - )]) - } else { - HashMap::new() - }) - .build(); - let ctx = Arc::new(ctx); - let database_client = { - database_client - .handler - .lock() - .unwrap() - .as_ref() - .context(UnexpectedSnafu { - reason: "Standalone's frontend instance is not set", - })? - .upgrade() - .context(UnexpectedSnafu { - reason: "Failed to upgrade database client", - })? - }; - let resp: common_query::Output = database_client - .do_query(req, ctx) - .await - .map_err(BoxedError::new) - .context(ExternalSnafu)?; - match resp.data { - common_query::OutputData::AffectedRows(rows) => rows.try_into().map_err(|_| { - UnexpectedSnafu { - reason: format!("Failed to convert rows to u32: {}", rows), - } - .build() - }), - _ => UnexpectedSnafu { - reason: "Unexpected output data", - } - .fail(), - } - } - } - } - /// Handle a request to frontend pub(crate) async fn handle( &self, @@ -819,7 +738,6 @@ impl std::fmt::Display for PeerDesc { #[cfg(test)] mod tests { use std::pin::Pin; - use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::{Context, Poll}; use std::time::Duration; @@ -893,11 +811,6 @@ mod tests { #[derive(Debug)] struct MetricsHandler; - #[derive(Debug)] - struct InsertOnceHandler { - calls: Arc, - } - #[derive(Debug)] struct ExtensionAwareHandler; @@ -933,19 +846,6 @@ mod tests { } } - #[async_trait::async_trait] - impl GrpcQueryHandlerWithBoxedError for InsertOnceHandler { - async fn do_query( - &self, - _query: Request, - ctx: QueryContextRef, - ) -> std::result::Result { - assert_eq!(ctx.channel(), Channel::Internal); - self.calls.fetch_add(1, Ordering::SeqCst); - Ok(Output::new_with_affected_rows(1)) - } - } - #[async_trait::async_trait] impl GrpcQueryHandlerWithBoxedError for MetricsHandler { async fn do_query( @@ -1195,31 +1095,6 @@ mod tests { ); } - #[tokio::test] - async fn test_handle_insert_once_calls_standalone_handler_once() { - let calls = Arc::new(AtomicUsize::new(0)); - let handler: Arc = Arc::new(InsertOnceHandler { - calls: calls.clone(), - }); - let client = - FrontendClient::from_grpc_handler(Arc::downgrade(&handler), QueryOptions::default()); - let mut peer_desc = None; - - let affected_rows = client - .handle_insert_once( - Request::RowInserts(api::v1::RowInsertRequests { inserts: vec![] }), - "greptime", - "public", - &mut peer_desc, - ) - .await - .unwrap(); - - assert_eq!(affected_rows, 1); - assert_eq!(calls.load(Ordering::SeqCst), 1); - assert!(peer_desc.is_none()); - } - #[tokio::test] async fn test_query_with_terminal_metrics_tracks_watermark_in_standalone_mode() { let handler: Arc = Arc::new(MetricsHandler); diff --git a/src/flow/src/engine.rs b/src/flow/src/engine.rs index 3a139a898a9..c83766222cd 100644 --- a/src/flow/src/engine.rs +++ b/src/flow/src/engine.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Define a trait for flow engine, which is used by both streaming engine and batch engine +//! Defines the flow engine trait implemented by the flownode engine use std::collections::HashMap; diff --git a/src/flow/src/error.rs b/src/flow/src/error.rs index 8f3cec0763e..91b0160cf61 100644 --- a/src/flow/src/error.rs +++ b/src/flow/src/error.rs @@ -36,19 +36,6 @@ use crate::FlowId; #[snafu(visibility(pub))] #[stack_trace_debug] pub enum Error { - #[snafu(display( - "Failed to insert into flow: region_id={}, flow_ids={:?}", - region_id, - flow_ids - ))] - InsertIntoFlow { - region_id: u64, - flow_ids: Vec, - source: BoxedError, - #[snafu(implicit)] - location: Location, - }, - #[snafu(display("Flow engine is still recovering"))] FlowNotRecovered { #[snafu(implicit)] @@ -309,7 +296,6 @@ impl ErrorExt for Error { match self { Self::JoinTask { .. } | Self::Datafusion { .. } - | Self::InsertIntoFlow { .. } | Self::NoAvailableFrontend { .. } | Self::FlowNotRecovered { .. } => StatusCode::Internal, Self::FlowAlreadyExist { .. } => StatusCode::TableAlreadyExists, @@ -354,8 +340,7 @@ impl ErrorExt for Error { RetryHint::Retryable } - Self::InsertIntoFlow { source, .. } - | Self::CreateFlow { source, .. } + Self::CreateFlow { source, .. } | Self::CreateSinkTable { source, .. } | Self::External { source, .. } => source.retry_hint(), diff --git a/src/flow/src/expr.rs b/src/flow/src/expr.rs deleted file mode 100644 index 6c7f7609f1e..00000000000 --- a/src/flow/src/expr.rs +++ /dev/null @@ -1,89 +0,0 @@ -// 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. - -//! Small row-batch conversion helper used by stateless streaming. - -pub(crate) mod error; -use common_recordbatch::RecordBatch; -use datatypes::data_type::DataType; -use datatypes::prelude::ConcreteDataType; -use datatypes::vectors::{Helper, VectorRef}; -use itertools::Itertools; -use snafu::{ResultExt, ensure}; - -use crate::Error; -use crate::error::DatatypesSnafu; -use crate::repr::Row; - -#[derive(Debug, Clone)] -pub struct Batch { - batch: Vec, - row_count: usize, -} - -impl TryFrom for Batch { - type Error = Error; - fn try_from(value: RecordBatch) -> Result { - Ok(Self { - batch: Helper::try_into_vectors(value.columns()).context(DatatypesSnafu { - extra: "failed to convert Arrow array to vector", - })?, - row_count: value.num_rows(), - }) - } -} - -impl Batch { - pub fn try_from_rows_with_types( - rows: Vec, - types: &[ConcreteDataType], - ) -> Result { - if rows.is_empty() { - return Ok(Self { - batch: vec![], - row_count: 0, - }); - } - let len = rows.len(); - let mut builders = types - .iter() - .map(|ty| ty.create_mutable_vector(len)) - .collect_vec(); - ensure!( - rows.iter().all(|row| row.len() == builders.len()), - error::InvalidArgumentSnafu { - reason: "row length does not match schema".to_string() - } - ); - for row in rows { - for (idx, value) in row.iter().enumerate() { - builders[idx] - .try_push_value_ref(&value.as_value_ref()) - .context(error::DataTypeSnafu { - msg: "failed to convert rows to columns", - })?; - } - } - Ok(Self { - batch: builders.into_iter().map(|mut b| b.to_vector()).collect(), - row_count: len, - }) - } - pub fn batch(&self) -> &[VectorRef] { - &self.batch - } - pub fn row_count(&self) -> usize { - self.row_count - } -} diff --git a/src/flow/src/expr/error.rs b/src/flow/src/expr/error.rs deleted file mode 100644 index ac5319314aa..00000000000 --- a/src/flow/src/expr/error.rs +++ /dev/null @@ -1,133 +0,0 @@ -// 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. - -//! Error handling for expression evaluation. - -use std::any::Any; - -use arrow_schema::ArrowError; -use common_error::ext::{BoxedError, ErrorExt}; -use common_error::status_code::StatusCode; -use common_macro::stack_trace_debug; -use datafusion_common::DataFusionError; -use datatypes::data_type::ConcreteDataType; -use snafu::{Location, Snafu}; - -/// EvalError is about errors happen on columnar evaluation -/// -/// TODO(discord9): add detailed location of column/operator(instead of code) to errors tp help identify related column -#[derive(Snafu)] -#[snafu(visibility(pub))] -#[stack_trace_debug] -pub enum EvalError { - #[snafu(display("Type mismatch: expected {expected}, actual {actual}"))] - TypeMismatch { - expected: ConcreteDataType, - actual: ConcreteDataType, - #[snafu(implicit)] - location: Location, - }, - - /// can't nest datatypes error because EvalError need to be store in map and serialization - #[snafu(display("Fail to unpack from value to given type: {msg}"))] - TryFromValue { - msg: String, - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("Fail to cast value of type {from} to given type {to}"))] - CastValue { - from: ConcreteDataType, - to: ConcreteDataType, - source: datatypes::Error, - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("{msg}"))] - DataType { - msg: String, - source: datatypes::Error, - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("Invalid argument: {reason}"))] - InvalidArgument { - reason: String, - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("Internal error: {reason}"))] - Internal { - reason: String, - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("Overflowed during evaluation"))] - Overflow { - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("Arrow error: {error:?}, context: {context}"))] - Arrow { - #[snafu(source)] - error: ArrowError, - context: String, - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("DataFusion error: {error:?}, context: {context}"))] - Datafusion { - #[snafu(source)] - error: DataFusionError, - context: String, - #[snafu(implicit)] - location: Location, - }, - - #[snafu(display("External error"))] - External { - #[snafu(implicit)] - location: Location, - source: BoxedError, - }, -} - -impl ErrorExt for EvalError { - fn status_code(&self) -> StatusCode { - use EvalError::*; - match self { - TypeMismatch { .. } - | TryFromValue { .. } - | InvalidArgument { .. } - | Overflow { .. } => StatusCode::InvalidArguments, - - CastValue { source, .. } | DataType { source, .. } => source.status_code(), - - Internal { .. } | Arrow { .. } | Datafusion { .. } | External { .. } => { - StatusCode::Internal - } - } - } - - fn as_any(&self) -> &dyn Any { - self - } -} diff --git a/src/flow/src/lib.rs b/src/flow/src/lib.rs index 36dc7c21818..ca915c0bc76 100644 --- a/src/flow/src/lib.rs +++ b/src/flow/src/lib.rs @@ -26,18 +26,16 @@ pub(crate) mod batching_mode; mod df_optimizer; pub(crate) mod engine; pub mod error; -mod expr; pub mod heartbeat; mod metrics; -mod repr; mod server; mod utils; #[cfg(test)] mod test_utils; -pub use adapter::flownode_impl::FlowDualEngineRef; -pub use adapter::{FlowConfig, FlowStreamingEngineRef, StreamingEngine}; +pub use adapter::FlowConfig; +pub use adapter::flownode_impl::FlownodeEngineRef; pub use batching_mode::BatchingModeOptions; pub use batching_mode::batching_execution::{BatchingExecution, BatchingExecutionFactory}; pub use batching_mode::frontend_client::{ diff --git a/src/flow/src/repr.rs b/src/flow/src/repr.rs deleted file mode 100644 index 42c1eafd50b..00000000000 --- a/src/flow/src/repr.rs +++ /dev/null @@ -1,262 +0,0 @@ -// 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. - -//! basically a wrapper around the `datatype` crate -//! for basic Data Representation - -mod relation; - -use api::helper::{pb_value_to_value_ref, to_grpc_value}; -use api::v1::Row as ProtoRow; -use datatypes::data_type::ConcreteDataType; -use datatypes::types::cast; -use datatypes::value::Value; -use get_size2::GetSize; -use itertools::Itertools; -pub(crate) use relation::{ColumnType, Key, RelationDesc, RelationType}; -use serde::{Deserialize, Serialize}; -use snafu::ResultExt; - -use crate::expr::error::{CastValueSnafu, EvalError, InvalidArgumentSnafu}; -use crate::utils::get_value_heap_size; - -/// System-wide Record count difference type. Useful for capture data change -/// -/// i.e. +1 means insert one record, -1 means remove, -/// and +/-n means insert/remove multiple duplicate records. -pub type Diff = i64; - -/// System-wide default timestamp type, in milliseconds -pub type Timestamp = i64; - -/// System-wide default duration type, in milliseconds -pub type Duration = i64; - -/// Default type for a repr of changes to a collection. -pub type DiffRow = (Row, Timestamp, Diff); - -/// Row with key-value pair, timestamp and diff -pub type KeyValDiffRow = ((Row, Row), Timestamp, Diff); - -/// broadcast channel capacity, can be important to memory consumption, since this influence how many -/// updates can be buffered in memory in the entire dataflow -/// TODO(discord9): add config for this, so cpu&mem usage can be balanced and configured by this -pub const BROADCAST_CAP: usize = 1024; - -/// The maximum capacity of the send buffer, to prevent the buffer from growing too large -pub const SEND_BUF_CAP: usize = BROADCAST_CAP * 2; - -/// Batch size used by the batching execution path. -pub const BATCH_SIZE: usize = 32 * 16384; - -/// Convert a value that is or can be converted to Datetime to internal timestamp -/// -/// support types are: `Date`, `DateTime`, `TimeStamp`, `i64` -pub fn value_to_internal_ts(value: Value) -> Result { - let is_supported_time_type = |arg: &Value| { - let ty = arg.data_type(); - matches!( - ty, - ConcreteDataType::Date(..) | ConcreteDataType::Timestamp(..) - ) - }; - match value { - Value::Int64(ts) => Ok(ts), - arg if is_supported_time_type(&arg) => { - let arg_ty = arg.data_type(); - let res = cast(arg, &ConcreteDataType::timestamp_millisecond_datatype()).context({ - CastValueSnafu { - from: arg_ty, - to: ConcreteDataType::timestamp_millisecond_datatype(), - } - })?; - if let Value::Timestamp(ts) = res { - Ok(ts.value()) - } else { - unreachable!() - } - } - _ => InvalidArgumentSnafu { - reason: format!("Expect a time type or i64, got {:?}", value.data_type()), - } - .fail(), - } -} - -/// A row is a vector of values. -/// -/// TODO(discord9): use a more efficient representation -/// i.e. more compact like raw u8 of \[tag0, value0, tag1, value1, ...\] -#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)] -pub struct Row { - /// The inner vector of values - pub inner: Vec, -} - -impl GetSize for Row { - fn get_heap_size(&self) -> usize { - self.inner.iter().map(get_value_heap_size).sum() - } -} - -impl Row { - /// Create an empty row - pub fn empty() -> Self { - Self { inner: vec![] } - } - - /// Returns true if the Row contains no elements. - pub fn is_empty(&self) -> bool { - self.inner.is_empty() - } - - /// Create a row from a vector of values - pub fn new(row: Vec) -> Self { - Self { inner: row } - } - - /// Get the value at the given index - pub fn get(&self, idx: usize) -> Option<&Value> { - self.inner.get(idx) - } - - /// Clear the row - pub fn clear(&mut self) { - self.inner.clear(); - } - - /// clear and return the inner vector - /// - /// useful if you want to reuse the vector as a buffer - pub fn packer(&mut self) -> &mut Vec { - self.inner.clear(); - &mut self.inner - } - - /// pack a iterator of values into a row - pub fn pack(iter: I) -> Row - where - I: IntoIterator, - { - Self { - inner: iter.into_iter().collect(), - } - } - - /// unpack a row into a vector of values - pub fn unpack(self) -> Vec { - self.inner - } - - /// extend the row with values from an iterator - pub fn extend(&mut self, iter: I) - where - I: IntoIterator, - { - self.inner.extend(iter); - } - - /// Creates a consuming iterator, that is, one that moves each value out of the `Row` (from start to end). The `Row` cannot be used after calling this - pub fn into_iter(self) -> impl Iterator { - self.inner.into_iter() - } - - /// Returns an iterator over the slice. - pub fn iter(&self) -> impl Iterator { - self.inner.iter() - } - - /// Returns the number of elements in the row, also known as its 'length'. - pub fn len(&self) -> usize { - self.inner.len() - } -} - -impl From> for Row { - fn from(row: Vec) -> Self { - Row::new(row) - } -} - -impl From for Row { - fn from(row: ProtoRow) -> Self { - Row::pack( - row.values - .iter() - .map(|pb_val| -> Value { pb_value_to_value_ref(pb_val, None).into() }), - ) - } -} - -impl From for ProtoRow { - fn from(row: Row) -> Self { - let values = row.unpack().into_iter().map(to_grpc_value).collect_vec(); - ProtoRow { values } - } -} -#[cfg(test)] -mod test { - use common_time::{Date, Timestamp}; - - use super::*; - - #[test] - fn test_row() { - let row = Row::empty(); - let row_1 = Row::new(vec![]); - assert_eq!(row, row_1); - let mut row_2 = Row::new(vec![Value::Int32(1), Value::Int32(2)]); - assert_eq!(row_2.get(0), Some(&Value::Int32(1))); - row_2.clear(); - assert_eq!(row_2.get(0), None); - row_2 - .packer() - .extend(vec![Value::Int32(1), Value::Int32(2)]); - assert_eq!(row_2.get(0), Some(&Value::Int32(1))); - row_2.extend(vec![Value::Int32(1), Value::Int32(2)]); - assert_eq!(row_2.len(), 4); - let row_3 = Row::pack(row_2.into_iter()); - assert_eq!(row_3.len(), 4); - let row_4 = Row::pack(row_3.iter().cloned()); - assert_eq!(row_3, row_4); - } - - #[test] - fn test_cast_to_internal_ts() { - { - let a = Value::from(1i32); - let b = Value::from(1i64); - let c = Value::Timestamp(Timestamp::new_millisecond(1i64)); - let d = Value::from(1.0); - - assert!(value_to_internal_ts(a).is_err()); - assert_eq!(value_to_internal_ts(b).unwrap(), 1i64); - assert_eq!(value_to_internal_ts(c).unwrap(), 1i64); - assert!(value_to_internal_ts(d).is_err()); - } - - { - // time related type - let a = Value::Date(Date::new(1)); - assert_eq!(value_to_internal_ts(a).unwrap(), 86400 * 1000i64); - let b = Value::Timestamp(common_time::Timestamp::new_second(1)); - assert_eq!(value_to_internal_ts(b).unwrap(), 1000i64); - let c = Value::Time(common_time::time::Time::new_second(1)); - assert!(matches!( - value_to_internal_ts(c), - Err(EvalError::InvalidArgument { .. }) - )); - } - } -} diff --git a/src/flow/src/repr/relation.rs b/src/flow/src/repr/relation.rs deleted file mode 100644 index 296f1bb4178..00000000000 --- a/src/flow/src/repr/relation.rs +++ /dev/null @@ -1,457 +0,0 @@ -// 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. - -use datafusion_common::DFSchema; -use datatypes::data_type::DataType; -use datatypes::prelude::ConcreteDataType; -use serde::{Deserialize, Serialize}; -use snafu::{ResultExt, ensure}; - -use crate::error::{DatafusionSnafu, InternalSnafu, InvalidQuerySnafu, Result}; - -/// a set of column indices that are "keys" for the collection. -#[derive(Default, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)] -pub struct Key { - /// indicate whose column form key - pub column_indices: Vec, -} - -impl Key { - /// create a new Key - pub fn new() -> Self { - Default::default() - } - - /// create a new Key from a vector of column indices - pub fn from(mut column_indices: Vec) -> Self { - column_indices.sort_unstable(); - Self { column_indices } - } - - /// Add a column to Key - pub fn add_col(&mut self, col: usize) { - self.column_indices.push(col); - } - - /// Remove a column from Key - pub fn remove_col(&mut self, col: usize) { - self.column_indices.retain(|&r| r != col); - } - - /// get all columns in Key - pub fn get(&self) -> &Vec { - &self.column_indices - } - - /// True if Key is empty - pub fn is_empty(&self) -> bool { - self.column_indices.is_empty() - } - - /// True if all columns in self are also in other - pub fn subset_of(&self, other: &Key) -> bool { - self.column_indices - .iter() - .all(|c| other.column_indices.contains(c)) - } -} - -/// The type of a relation. -#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)] -pub struct RelationType { - /// The type for each column, in order. - pub column_types: Vec, - /// Sets of indices that are "keys" for the collection. - /// - /// Each element in this list is a set of column indices, each with the - /// property that the collection contains at most one record with each - /// distinct set of values for each column. Alternately, for a specific set - /// of values assigned to the these columns there is at most one record. - /// - /// A collection can contain multiple sets of keys, although it is common to - /// have either zero or one sets of key indices. - pub keys: Vec, - /// optionally indicate the column that is TIME INDEX - pub time_index: Option, - /// mark all the columns that are added automatically by flow, but are not present in original sql - pub auto_columns: Vec, -} - -impl RelationType { - pub fn with_autos(mut self, auto_cols: &[usize]) -> Self { - self.auto_columns = auto_cols.to_vec(); - self - } - - /// Constructs a `RelationType` representing the relation with no columns and - /// no keys. - pub fn empty() -> Self { - RelationType::new(vec![]) - } - - /// Constructs a new `RelationType` from specified column types. - /// - /// The `RelationType` will have no keys. - pub fn new(column_types: Vec) -> Self { - RelationType { - column_types, - keys: Vec::new(), - time_index: None, - auto_columns: vec![], - } - } - - /// Adds a new key for the relation. Also sorts the key indices. - /// - /// will ignore empty key - pub fn with_key(mut self, mut indices: Vec) -> Self { - if indices.is_empty() { - return self; - } - indices.sort_unstable(); - let key = Key::from(indices); - if !self.keys.contains(&key) { - self.keys.push(key); - } - self - } - - /// Adds new keys for the relation. Also sorts the key indices. - /// - /// will ignore empty keys - pub fn with_keys(mut self, keys: Vec>) -> Self { - for key in keys { - self = self.with_key(key) - } - self - } - - /// will also remove time index from keys if it's in keys - pub fn with_time_index(mut self, time_index: Option) -> Self { - self.time_index = time_index; - for key in &mut self.keys { - key.remove_col(time_index.unwrap_or(usize::MAX)); - } - // remove empty keys - self.keys.retain(|key| !key.is_empty()); - self - } - - /// Computes the number of columns in the relation. - pub fn arity(&self) -> usize { - self.column_types.len() - } - - /// Gets the index of the columns used when creating a default index. - pub fn default_key(&self) -> Vec { - if let Some(key) = self.keys.first() { - if key.is_empty() { - (0..self.column_types.len()).collect() - } else { - key.get().clone() - } - } else { - (0..self.column_types.len()).collect() - } - } - - /// True if any collection described by `self` could safely be described by `other`. - /// - /// In practice this means checking that the scalar types match exactly, and that the - /// nullability of `self` is at least as strict as `other`, and that all keys of `other` - /// contain some key of `self` (as a set of key columns is less strict than any subset). - pub fn subtypes(&self, other: &RelationType) -> bool { - if self.column_types.len() != other.column_types.len() { - return false; - } - - for (col1, col2) in self.column_types.iter().zip(other.column_types.iter()) { - if col1.nullable && !col2.nullable { - return false; - } - if col1.scalar_type != col2.scalar_type { - return false; - } - } - - let all_keys = other - .keys - .iter() - .all(|key1| self.keys.iter().any(|key2| key1.subset_of(key2))); - if !all_keys { - return false; - } - - true - } - - /// Return relation describe with column names - pub fn into_named(self, names: Vec>) -> RelationDesc { - RelationDesc { typ: self, names } - } - - /// Return relation describe without column names - pub fn into_unnamed(self) -> RelationDesc { - RelationDesc { - names: vec![None; self.column_types.len()], - typ: self, - } - } -} - -/// The type of a `Value` -/// -/// [`ColumnType`] bundles information about the scalar type of a datum (e.g., -/// Int32 or String) with its nullability. -/// -/// To construct a column type, either initialize the struct directly, or -/// use the [`ScalarType::nullable`] method. -#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)] -pub struct ColumnType { - /// The underlying scalar type (e.g., Int32 or String) of this column. - pub scalar_type: ConcreteDataType, - /// Whether this datum can be null. - #[serde(default = "return_true")] - pub nullable: bool, -} - -impl ColumnType { - /// Constructs a new `ColumnType` from a scalar type and a nullability flag. - pub fn new(scalar_type: ConcreteDataType, nullable: bool) -> Self { - ColumnType { - scalar_type, - nullable, - } - } - - /// Constructs a new `ColumnType` from a scalar type, with nullability set to - /// ***true*** - pub fn new_nullable(scalar_type: ConcreteDataType) -> Self { - ColumnType { - scalar_type, - nullable: true, - } - } - - /// Returns the scalar type of this column. - pub fn scalar_type(&self) -> &ConcreteDataType { - &self.scalar_type - } - - /// Returns true if this column can be null. - pub fn nullable(&self) -> bool { - self.nullable - } -} - -/// This method exists solely for the purpose of making ColumnType nullable by -/// default in unit tests. The default value of a bool is false, and the only -/// way to make an object take on any other value by default is to pass it a -/// function that returns the desired default value. See -/// -#[inline(always)] -fn return_true() -> bool { - true -} - -/// A description of the shape of a relation. -/// -/// It bundles a [`RelationType`] with the name of each column in the relation. -/// Individual column names are optional. -#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)] -pub struct RelationDesc { - pub typ: RelationType, - pub names: Vec>, -} - -impl RelationDesc { - pub fn len(&self) -> Result { - ensure!( - self.typ.column_types.len() == self.names.len(), - InternalSnafu { - reason: "Expect typ and names field to be of same length" - } - ); - Ok(self.names.len()) - } - - pub fn to_df_schema(&self) -> Result { - let fields: Vec<_> = self - .iter() - .enumerate() - .map(|(i, (name, typ))| { - let name = name.clone().unwrap_or(format!("Col_{i}")); - let nullable = typ.nullable; - let data_type = typ.scalar_type.clone().as_arrow_type(); - arrow_schema::Field::new(name, data_type, nullable) - }) - .collect(); - let arrow_schema = arrow_schema::Schema::new(fields); - - DFSchema::try_from(arrow_schema.clone()).with_context(|_e| DatafusionSnafu { - context: format!("Error when converting to DFSchema: {:?}", arrow_schema), - }) - } -} - -impl RelationDesc { - /// Constructs a new `RelationDesc` that represents the empty relation - /// with no columns and no keys. - pub fn empty() -> Self { - RelationDesc { - typ: RelationType::empty(), - names: vec![], - } - } - - /// Constructs a new `RelationDesc` from a `RelationType` and an iterator - /// over column names. - /// - pub fn try_new(typ: RelationType, names: I) -> Result - where - I: IntoIterator, - N: Into>, - { - let names: Vec<_> = names.into_iter().map(|name| name.into()).collect(); - ensure!( - typ.arity() == names.len(), - InvalidQuerySnafu { - reason: format!( - "Length mismatch between RelationType {:?} and column names {:?}", - typ.column_types, names - ) - } - ); - Ok(RelationDesc { typ, names }) - } - - /// Constructs a new `RelationDesc` from a `RelationType` and an iterator - /// over column names. - /// - /// # Panics - /// - /// Panics if the arity of the `RelationType` is not equal to the number of - /// items in `names`. - pub fn new_unchecked(typ: RelationType, names: I) -> Self - where - I: IntoIterator, - N: Into>, - { - let names: Vec<_> = names.into_iter().map(|name| name.into()).collect(); - assert_eq!(typ.arity(), names.len()); - RelationDesc { typ, names } - } - - pub fn from_names_and_types(iter: I) -> Self - where - I: IntoIterator, - T: Into, - N: Into>, - { - let (names, types): (Vec<_>, Vec<_>) = iter.into_iter().unzip(); - let types = types.into_iter().map(Into::into).collect(); - let typ = RelationType::new(types); - Self::new_unchecked(typ, names) - } - /// Concatenates a `RelationDesc` onto the end of this `RelationDesc`. - pub fn concat(mut self, other: Self) -> Self { - let self_len = self.typ.column_types.len(); - self.names.extend(other.names); - self.typ.column_types.extend(other.typ.column_types); - for k in other.typ.keys { - let k = k - .column_indices - .into_iter() - .map(|idx| idx + self_len) - .collect(); - self = self.with_key(k); - } - self - } - - /// Appends a column with the specified name and type. - pub fn with_column(mut self, name: N, column_type: ColumnType) -> Self - where - N: Into>, - { - self.typ.column_types.push(column_type); - self.names.push(name.into()); - self - } - - /// Adds a new key for the relation. - pub fn with_key(mut self, indices: Vec) -> Self { - self.typ = self.typ.with_key(indices); - self - } - - /// Builds a new relation description with the column names replaced with - /// new names. - /// - pub fn try_with_names(self, names: I) -> Result - where - I: IntoIterator, - N: Into>, - { - Self::try_new(self.typ, names) - } - - /// Computes the number of columns in the relation. - pub fn arity(&self) -> usize { - self.typ.arity() - } - - /// Returns the relation type underlying this relation description. - pub fn typ(&self) -> &RelationType { - &self.typ - } - - /// Returns an iterator over the columns in this relation. - pub fn iter(&self) -> impl Iterator, &ColumnType)> { - self.iter_names().zip(self.iter_types()) - } - - /// Returns an iterator over the types of the columns in this relation. - pub fn iter_types(&self) -> impl Iterator { - self.typ.column_types.iter() - } - - /// Returns an iterator over the names of the columns in this relation. - pub fn iter_names(&self) -> impl Iterator> { - self.names.iter() - } - - /// Finds a column by name. - /// - /// Returns the index and type of the column named `name`. If no column with - /// the specified name exists, returns `None`. If multiple columns have the - /// specified name, the leftmost column is returned. - pub fn get_by_name(&self, name: &ColumnName) -> Option<(usize, &ColumnType)> { - self.iter_names() - .position(|n| n.as_ref() == Some(name)) - .map(|i| (i, &self.typ.column_types[i])) - } - - /// Gets the name of the `i`th column. - /// - /// # Panics - /// - /// Panics if `i` is not a valid column index. - pub fn get_name(&self, i: usize) -> &Option { - &self.names[i] - } -} - -/// The name of a column in a [`RelationDesc`]. -pub type ColumnName = String; diff --git a/src/flow/src/server.rs b/src/flow/src/server.rs index 63dc8aefa0a..ed2699c50a4 100644 --- a/src/flow/src/server.rs +++ b/src/flow/src/server.rs @@ -38,7 +38,7 @@ use snafu::ResultExt; use tonic::codec::CompressionEncoding; use tonic::{Request, Response, Status}; -use crate::adapter::flownode_impl::{FlowDualEngine, FlowDualEngineRef}; +use crate::adapter::flownode_impl::{FlownodeEngine, FlownodeEngineRef}; use crate::batching_mode::engine::BatchingEngine; use crate::error::{ DatafusionSnafu, ExternalSnafu, ListFlowsSnafu, ParseAddrSnafu, ShutdownServerSnafu, @@ -47,20 +47,18 @@ use crate::error::{ use crate::heartbeat::HeartbeatTask; use crate::metrics::{METRIC_FLOW_PROCESSING_TIME, METRIC_FLOW_ROWS}; use crate::utils::{SizeReportSender, StateReportHandler}; -use crate::{BatchingExecutionFactory, Error, FlownodeOptions, FrontendClient, StreamingEngine}; +use crate::{BatchingExecutionFactory, Error, FlownodeOptions, FrontendClient}; pub const FLOW_NODE_SERVER_NAME: &str = "FLOW_NODE_SERVER"; /// wrapping flow node manager to avoid orphan rule with Arc<...> #[derive(Clone)] pub struct FlowService { - pub dual_engine: FlowDualEngineRef, + pub engine: FlownodeEngineRef, } impl FlowService { - pub fn new(manager: FlowDualEngineRef) -> Self { - Self { - dual_engine: manager, - } + pub fn new(engine: FlownodeEngineRef) -> Self { + Self { engine } } } @@ -75,7 +73,7 @@ impl flow_server::Flow for FlowService { .start_timer(); let request = request.into_inner(); - self.dual_engine + self.engine .handle(request) .await .map_err(|err| { @@ -117,7 +115,7 @@ impl flow_server::Flow for FlowService { .with_label_values(&["in"]) .inc_by(row_count as u64); - self.dual_engine + self.engine .handle_inserts(request) .await .map(Response::new) @@ -128,7 +126,7 @@ impl flow_server::Flow for FlowService { &self, reqs: Request, ) -> Result, Status> { - self.dual_engine + self.engine .handle_mark_window_dirty(reqs.into_inner()) .await .map(Response::new) @@ -238,8 +236,8 @@ impl FlownodeInstance { &self.flownode_server } - pub fn flow_engine(&self) -> FlowDualEngineRef { - self.flownode_server.inner.flow_service.dual_engine.clone() + pub fn flow_engine(&self) -> FlownodeEngineRef { + self.flownode_server.inner.flow_service.engine.clone() } pub fn setup_services(&mut self, services: ServerHandlers) { @@ -332,7 +330,6 @@ impl FlownodeBuilder { .context(DatafusionSnafu { context: "Failed to build query engine", })?; - let manager = Arc::new(self.build_manager(query_engine_factory.query_engine())); let batching = Arc::new(BatchingEngine::new_with_execution( self.frontend_client.clone(), query_engine_factory.query_engine(), @@ -342,18 +339,18 @@ impl FlownodeBuilder { self.opts.flow.batching_mode.clone(), self.plugins.get::>(), )); - let dual = Arc::new(FlowDualEngine::new( - manager.clone(), + let engine = Arc::new(FlownodeEngine::new( + self.opts.node_id.map(|id| id as u32), batching, self.flow_metadata_manager.clone(), self.catalog_manager.clone(), self.plugins.clone(), )); if let Some(handler) = self.state_report_handler.take() { - dual.set_state_report_handler(handler).await; + engine.set_state_report_handler(handler).await; } - let server = FlownodeServer::new(FlowService::new(dual)); + let server = FlownodeServer::new(FlowService::new(engine)); let heartbeat_task = self.heartbeat_task; @@ -366,15 +363,6 @@ impl FlownodeBuilder { }; Ok(instance) } - - fn build_manager(&self, query_engine: Arc) -> StreamingEngine { - StreamingEngine::new( - self.opts.node_id.map(|id| id as u32), - query_engine, - self.table_meta.clone(), - self.frontend_client.clone(), - ) - } } /// Useful in distributed mode @@ -532,12 +520,6 @@ mod tests { let query_engine = crate::test_utils::create_test_query_engine(); let frontend_client = Arc::new(frontend_client); - let streaming_engine = Arc::new(StreamingEngine::new( - node_id, - query_engine.clone(), - table_meta.clone(), - frontend_client.clone(), - )); let batching_engine = Arc::new(BatchingEngine::new( frontend_client, query_engine, @@ -546,8 +528,8 @@ mod tests { catalog_manager.clone(), batching_opts, )); - let dual_engine = Arc::new(FlowDualEngine::new( - streaming_engine, + let engine = Arc::new(FlownodeEngine::new( + node_id, batching_engine, flow_meta, catalog_manager, @@ -555,9 +537,9 @@ mod tests { )); let (report_sender, report_handler) = SizeReportSender::new(); - dual_engine.set_state_report_handler(report_handler).await; + engine.set_state_report_handler(report_handler).await; - let server = FlownodeServer::new(FlowService::new(dual_engine)); + let server = FlownodeServer::new(FlowService::new(engine)); (server, report_sender) } } diff --git a/src/flow/src/utils.rs b/src/flow/src/utils.rs index 575be9138f3..9410ca159e3 100644 --- a/src/flow/src/utils.rs +++ b/src/flow/src/utils.rs @@ -13,20 +13,10 @@ // limitations under the License. use common_meta::key::flow::flow_state::FlowStat; -use datatypes::value::Value; use tokio::sync::{mpsc, oneshot}; use crate::error::InternalSnafu; -pub fn get_value_heap_size(value: &Value) -> usize { - match value { - Value::Binary(v) => v.len(), - Value::String(v) => v.len(), - Value::List(v) => v.items().iter().map(get_value_heap_size).sum(), - _ => 0, - } -} - #[derive(Clone)] pub struct SizeReportSender { inner: mpsc::Sender>, diff --git a/src/operator/src/statement/ddl.rs b/src/operator/src/statement/ddl.rs index 40a83613a56..97a45b1dd7e 100644 --- a/src/operator/src/statement/ddl.rs +++ b/src/operator/src/statement/ddl.rs @@ -289,16 +289,12 @@ fn determine_flow_type_for_source_state( flow_options: &HashMap, has_missing_source_table: bool, has_instant_ttl_source_table: bool, - force_batching: bool, ) -> Result> { - if has_instant_ttl_source_table && force_batching { - // The batching scheduler cannot read instant-TTL source tables, so - // reject this combination even when another source table is missing. + if has_instant_ttl_source_table { + // The batching scheduler cannot read instant-TTL source tables, and it is the + // only scheduler left, so reject the flow even when another source is missing. return InvalidSqlSnafu { - err_msg: format!( - "flow '{}' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode; use a TTL longer than the flush interval", - flow_name - ), + err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(), } .fail(); } @@ -326,29 +322,9 @@ fn determine_flow_type_for_source_state( Ok(None) } -/// The stateless streaming runtime accepts only a single source scan wrapped by -/// projections and filters. Keep this check local to the operator: the flow -/// validator is intentionally private to the flow crate. -fn is_stateless_flow_plan(plan: &LogicalPlan) -> bool { - let mut scans = 0; - let mut supported_nodes = true; - let result = plan.apply_with_subqueries(|node| { - match node { - LogicalPlan::TableScan(_) => scans += 1, - LogicalPlan::Projection(_) | LogicalPlan::Filter(_) => {} - LogicalPlan::Distinct(Distinct::All(_)) => {} - _ => supported_nodes = false, - } - Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) - }); +const INSTANT_TTL_FLOW_QUERY_ERROR: &str = "instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval"; - result.is_ok() && supported_nodes && scans == 1 -} - -const INSTANT_TTL_FLOW_QUERY_ERROR: &str = "instant-TTL flow sources support only stateless projection/filter queries over one source; non-stateless queries require a persisted source"; - -const STATELESS_FLOW_QUERY_ERROR: &str = - "flow streaming supports only stateless projection/filter queries over one source"; +const DISTINCT_ON_FLOW_QUERY_ERROR: &str = "DISTINCT ON is not supported in flow queries"; impl StatementExecutor { pub fn catalog_manager(&self) -> CatalogManagerRef { @@ -972,18 +948,17 @@ impl StatementExecutor { .context(error::ExecuteDdlSnafu) } - /// Determines the flow type from source-table state, schedule requirements, - /// and SQL shape. + /// Validates a flow definition against its source tables. /// - /// Aggregates and persisted-source DISTINCT use batching. Plain DISTINCT is request-local only - /// for instant-TTL sources, where it retains the legacy streaming compatibility behavior. + /// The batching scheduler is the only execution profile, so this no longer selects a mode. + /// It keeps the source-table checks that must happen before the DDL procedure runs + /// (missing source opt-in, instant-TTL rejection, `DISTINCT ON` rejection) and always + /// reports [`FlowType::Batching`]. async fn determine_flow_type( &self, expr: &CreateFlowExpr, query_ctx: QueryContextRef, ) -> Result { - let has_eval_interval = expr.eval_interval.is_some(); - let mut has_missing_source_table = false; let mut has_instant_ttl_source_table = false; @@ -1007,18 +982,13 @@ impl StatementExecutor { if table.table_info().meta.options.ttl == Some(common_time::TimeToLive::Instant) { warn!( - "Source table `{}` for flow `{}`'s ttl=instant, {}", + "Source table `{}` for flow `{}`'s ttl=instant, rejecting flow because instant-TTL sources are not supported as flow sources", format_full_table_name( &src_table_name.catalog_name, &src_table_name.schema_name, &src_table_name.table_name ), expr.flow_name, - if has_eval_interval { - "rejecting flow because EVAL INTERVAL requires the batching scheduler which does not support instant TTL" - } else { - "fallback to streaming mode" - } ); has_instant_ttl_source_table = true; } @@ -1029,17 +999,14 @@ impl StatementExecutor { &expr.flow_options, has_missing_source_table, has_instant_ttl_source_table, - has_eval_interval, )? { return Ok(flow_type); } - // A flow with `EVAL INTERVAL` (and therefore possibly `EVAL OFFSET`) - // always uses the batching scheduler: the fixed epoch-phase schedule is - // only honored by the batching scheduler, regardless of the SQL shape. - // Non-aggregate SQL is supported as an explicit full-query flow (the - // batching engine requires a time-window expression or EVAL INTERVAL). - if has_eval_interval { + // A flow with `EVAL INTERVAL` (and therefore possibly `EVAL OFFSET`) already runs as an + // explicit full-query batching flow, whatever its SQL shape, so there is no schedule-less + // request-local shape left to reject here. + if expr.eval_interval.is_some() { return Ok(FlowType::Batching); } @@ -1064,27 +1031,11 @@ impl StatementExecutor { .map_err(BoxedError::new) .context(ExternalSnafu)?; if is_tql_query { - if has_instant_ttl_source_table { - return InvalidSqlSnafu { - err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(), - } - .fail(); - } return Ok(FlowType::Batching); } - // Plan before selecting a mode. In particular, instant-TTL sources - // must not bypass validation of the stateless streaming subset. let plan = match stmt { - Statement::Tql(_) => { - if has_instant_ttl_source_table { - return InvalidSqlSnafu { - err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(), - } - .fail(); - } - return Ok(FlowType::Batching); - } + Statement::Tql(_) => return Ok(FlowType::Batching), _ => engine .planner() .plan(&QueryStatement::Sql(stmt.clone()), query_ctx) @@ -1093,74 +1044,39 @@ impl StatementExecutor { .context(ExternalSnafu)?, }; - /// Visitor to classify aggregation and DISTINCT separately. Plain DISTINCT is request - /// local only for instant-TTL sources; persisted-source DISTINCT keeps batching semantics. - struct FindQueryShape { - is_aggr: bool, - is_distinct: bool, + /// Visitor that only detects `DISTINCT ON`, which has no batching implementation. + struct FindDistinctOn { has_distinct_on: bool, } - impl TreeNodeVisitor<'_> for FindQueryShape { + impl TreeNodeVisitor<'_> for FindDistinctOn { type Node = LogicalPlan; fn f_down( &mut self, node: &Self::Node, ) -> datafusion_common::Result { - match node { - LogicalPlan::Aggregate(_) => self.is_aggr = true, - LogicalPlan::Distinct(Distinct::All(_)) => self.is_distinct = true, - LogicalPlan::Distinct(Distinct::On(_)) => self.has_distinct_on = true, - _ => (), + if matches!(node, LogicalPlan::Distinct(Distinct::On(_))) { + self.has_distinct_on = true; } Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) } } - let mut query_shape = FindQueryShape { - is_aggr: false, - is_distinct: false, + let mut query_shape = FindDistinctOn { has_distinct_on: false, }; plan.visit_with_subqueries(&mut query_shape) .context(BuildDfLogicalPlanSnafu)?; - if query_shape.has_distinct_on { - return InvalidSqlSnafu { - err_msg: if has_instant_ttl_source_table { - INSTANT_TTL_FLOW_QUERY_ERROR.to_string() - } else { - STATELESS_FLOW_QUERY_ERROR.to_string() - }, - } - .fail(); - } - if query_shape.is_aggr { - return if has_instant_ttl_source_table { - InvalidSqlSnafu { - err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(), - } - .fail() - } else { - Ok(FlowType::Batching) - }; - } - if query_shape.is_distinct && !has_instant_ttl_source_table { - return Ok(FlowType::Batching); - } - ensure!( - is_stateless_flow_plan(&plan), + !query_shape.has_distinct_on, InvalidSqlSnafu { - err_msg: if has_instant_ttl_source_table { - INSTANT_TTL_FLOW_QUERY_ERROR.to_string() - } else { - STATELESS_FLOW_QUERY_ERROR.to_string() - }, + err_msg: DISTINCT_ON_FLOW_QUERY_ERROR.to_string(), } ); - Ok(FlowType::Streaming) + + Ok(FlowType::Batching) } #[tracing::instrument(skip_all)] @@ -3151,7 +3067,6 @@ mod test { #[cfg(feature = "enterprise")] use api::v1::meta::{ProcedureDetailResponse, ReconcileRequest, ReconcileResponse}; - use arrow::datatypes::{DataType as ArrowDataType, Field as ArrowField}; #[cfg(feature = "enterprise")] use common_meta::cache_invalidator::{CacheInvalidator, CacheInvalidatorRef}; #[cfg(feature = "enterprise")] @@ -3174,9 +3089,6 @@ mod test { use common_meta::rpc::procedure::{ MigrateRegionRequest, MigrateRegionResponse, ProcedureStateResponse, }; - use datafusion::functions_aggregate::expr_fn::count; - use datafusion::logical_expr::builder::LogicalTableSource; - use datafusion::logical_expr::{LogicalPlanBuilder, col}; use session::context::QueryContext; use sql::dialect::GreptimeDbDialect; use sql::parser::{ParseOptions, ParserContext}; @@ -3598,77 +3510,6 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;"; ); } - fn stateless_test_scan(name: &str) -> LogicalPlan { - let schema = arrow::datatypes::Schema::new(vec![ArrowField::new( - "value", - ArrowDataType::Int32, - true, - )]); - LogicalPlanBuilder::scan( - name, - Arc::new(LogicalTableSource::new(Arc::new(schema))), - None, - ) - .unwrap() - .build() - .unwrap() - } - - #[test] - fn test_is_stateless_flow_plan_accepts_scan_projection_and_filter() { - let scan = stateless_test_scan("source"); - assert!(is_stateless_flow_plan(&scan)); - - let projection = LogicalPlanBuilder::from(scan.clone()) - .project(vec![col("value")]) - .unwrap() - .build() - .unwrap(); - assert!(is_stateless_flow_plan(&projection)); - - let filter = LogicalPlanBuilder::from(projection) - .filter(col("value").gt(datafusion_expr::lit(0))) - .unwrap() - .build() - .unwrap(); - assert!(is_stateless_flow_plan(&filter)); - } - - #[test] - fn test_is_stateless_flow_plan_rejects_aggregate_and_multiple_scans() { - let scan = stateless_test_scan("source"); - let aggregate = LogicalPlanBuilder::from(scan.clone()) - .aggregate( - Vec::::new(), - vec![count(col("value"))], - ) - .unwrap() - .build() - .unwrap(); - assert!(!is_stateless_flow_plan(&aggregate)); - - let distinct = LogicalPlanBuilder::from(scan.clone()) - .distinct() - .unwrap() - .build() - .unwrap(); - assert!(is_stateless_flow_plan(&distinct)); - - let distinct_on_aggregate = LogicalPlanBuilder::from(aggregate) - .distinct() - .unwrap() - .build() - .unwrap(); - assert!(!is_stateless_flow_plan(&distinct_on_aggregate)); - - let multiple_scans = LogicalPlanBuilder::from(stateless_test_scan("left")) - .cross_join(stateless_test_scan("right")) - .unwrap() - .build() - .unwrap(); - assert!(!is_stateless_flow_plan(&multiple_scans)); - } - // --- Schedule option tests --- #[test] @@ -3765,9 +3606,8 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;"; #[test] fn test_determine_flow_type_for_source_state_missing_sources_require_opt_in() { - let err = - determine_flow_type_for_source_state("my_flow", &HashMap::new(), true, false, false) - .unwrap_err(); + let err = determine_flow_type_for_source_state("my_flow", &HashMap::new(), true, false) + .unwrap_err(); assert!(err.to_string().contains( "missing source tables for flow 'my_flow'; use WITH (defer_on_missing_source = true) to create a pending flow" @@ -3780,39 +3620,32 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;"; HashMap::from([(DEFER_ON_MISSING_SOURCE_KEY.to_string(), "true".to_string())]); assert_eq!( - determine_flow_type_for_source_state("my_flow", &flow_options, true, true, false) - .unwrap(), + determine_flow_type_for_source_state("my_flow", &flow_options, true, false).unwrap(), Some(FlowType::Batching) ); - let err = determine_flow_type_for_source_state("my_flow", &flow_options, true, true, true) - .unwrap_err(); - assert!(err.to_string().contains( - "flow 'my_flow' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode" - )); + // An instant-TTL source is rejected even when another source is missing. + let err = + determine_flow_type_for_source_state("my_flow", &flow_options, true, true).unwrap_err(); + assert!(err.to_string().contains(INSTANT_TTL_FLOW_QUERY_ERROR)); } #[test] fn test_determine_flow_type_for_source_state_existing_sources_require_plan() { assert_eq!( - determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true, false) - .unwrap(), + determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, false).unwrap(), None ); } #[test] - fn test_determine_flow_type_for_source_state_instant_ttl_with_eval_interval_is_rejected() { - // A flow with `EVAL INTERVAL` is forced onto the batching scheduler, - // which cannot read instant-TTL source tables: reject instead of - // silently falling back to streaming (where the schedule/offset would - // be ignored). - let err = - determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true, true) - .unwrap_err(); + fn test_determine_flow_type_for_source_state_instant_ttl_is_rejected() { + // The batching scheduler is the only execution profile left and it + // cannot read instant-TTL source tables, so reject them for every flow + // instead of silently degrading. + let err = determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true) + .unwrap_err(); assert!( - err.to_string().contains( - "flow 'my_flow' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode" - ), + err.to_string().contains(INSTANT_TTL_FLOW_QUERY_ERROR), "unexpected error: {err}" ); } diff --git a/src/standalone/src/information_extension.rs b/src/standalone/src/information_extension.rs index 083fabadeb8..3ab4e013102 100644 --- a/src/standalone/src/information_extension.rs +++ b/src/standalone/src/information_extension.rs @@ -26,7 +26,7 @@ use common_procedure::{ProcedureInfo, ProcedureManagerRef}; use common_query::request::QueryRequest; use common_stat::{ResourceStatImpl, ResourceStatRef}; use datanode::region_server::RegionServer; -use flow::FlowDualEngineRef; +use flow::FlownodeEngineRef; use snafu::ResultExt; use store_api::storage::RegionId; use tokio::sync::RwLock; @@ -35,7 +35,7 @@ pub struct StandaloneInformationExtension { region_server: RegionServer, procedure_manager: ProcedureManagerRef, start_time_ms: u64, - flow_engine: RwLock>, + flow_engine: RwLock>, resource_stat: ResourceStatRef, } @@ -53,7 +53,7 @@ impl StandaloneInformationExtension { } /// Set the flow engine for the standalone instance. - pub async fn set_flow_engine(&self, flow_engine: FlowDualEngineRef) { + pub async fn set_flow_engine(&self, flow_engine: FlownodeEngineRef) { let mut guard = self.flow_engine.write().await; *guard = Some(flow_engine); } diff --git a/tests/cases/standalone/common/comment.result b/tests/cases/standalone/common/comment.result index e800beb5eef..5cfe09ddcf8 100644 --- a/tests/cases/standalone/common/comment.result +++ b/tests/cases/standalone/common/comment.result @@ -180,6 +180,7 @@ Affected Rows: 0 CREATE FLOW flow_comment_test SINK TO flow_sink_comment_test +EVAL INTERVAL '1h' AS SELECT desc_str, ts FROM flow_source_comment_test; @@ -197,6 +198,7 @@ SHOW CREATE FLOW flow_comment_test; +-------------------+------------------------------------------------------+ | flow_comment_test | CREATE FLOW IF NOT EXISTS flow_comment_test | | | SINK TO public.flow_sink_comment_test | +| | EVAL INTERVAL '3600 s' | | | COMMENT 'flow level description' | | | AS SELECT desc_str, ts FROM flow_source_comment_test | +-------------------+------------------------------------------------------+ @@ -223,6 +225,7 @@ SHOW CREATE FLOW flow_comment_test; +-------------------+------------------------------------------------------+ | flow_comment_test | CREATE FLOW IF NOT EXISTS flow_comment_test | | | SINK TO public.flow_sink_comment_test | +| | EVAL INTERVAL '3600 s' | | | AS SELECT desc_str, ts FROM flow_source_comment_test | +-------------------+------------------------------------------------------+ diff --git a/tests/cases/standalone/common/comment.sql b/tests/cases/standalone/common/comment.sql index d64f11e32aa..04f0daf53f0 100644 --- a/tests/cases/standalone/common/comment.sql +++ b/tests/cases/standalone/common/comment.sql @@ -66,6 +66,7 @@ CREATE TABLE flow_sink_comment_test ( CREATE FLOW flow_comment_test SINK TO flow_sink_comment_test +EVAL INTERVAL '1h' AS SELECT desc_str, ts FROM flow_source_comment_test; diff --git a/tests/cases/standalone/common/flow/flow_advance_ttl.result b/tests/cases/standalone/common/flow/flow_advance_ttl.result index 27a28babebf..8065f222ea2 100644 --- a/tests/cases/standalone/common/flow/flow_advance_ttl.result +++ b/tests/cases/standalone/common/flow/flow_advance_ttl.result @@ -8,210 +8,44 @@ CREATE TABLE distinct_basic ( Affected Rows: 0 --- request-local DISTINCT is supported in streaming mode --- SQLNESS REPLACE id=\d+ id=REDACTED +-- Instant-TTL source tables are no longer accepted as flow sources: a +-- stateless projection/DISTINCT query is rejected like any other flow. CREATE FLOW test_distinct_basic SINK TO out_distinct_basic AS SELECT DISTINCT number as dis FROM distinct_basic; -Affected Rows: 0 +Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval --- instant-TTL sources reject non-stateless LIMIT plans -CREATE FLOW test_limit_instant_rejected SINK TO out_limit_instant_rejected AS +-- An aggregate query over an instant-TTL source is rejected as well. +CREATE FLOW test_aggr_instant_rejected SINK TO out_aggr_instant_rejected AS SELECT - number + max(number) AS max_number FROM - distinct_basic -LIMIT 1; + distinct_basic; -Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL flow sources support only stateless projection/filter queries over one source; non-stateless queries require a persisted source +Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval --- flow_options should have a flow_type:streaming --- since source table's ttl=instant and DISTINCT is request-local -SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS; - -+---------------------+---------------------------+ -| flow_name | options | -+---------------------+---------------------------+ -| test_distinct_basic | {"flow_type":"streaming"} | -+---------------------+---------------------------+ - -SHOW CREATE TABLE distinct_basic; - -+----------------+-----------------------------------------------------------+ -| Table | Create Table | -+----------------+-----------------------------------------------------------+ -| distinct_basic | CREATE TABLE IF NOT EXISTS "distinct_basic" ( | -| | "number" INT NULL, | -| | "ts" TIMESTAMP(3) NOT NULL DEFAULT current_timestamp(), | -| | TIME INDEX ("ts"), | -| | PRIMARY KEY ("number") | -| | ) | -| | | -| | ENGINE=mito | -| | WITH( | -| | ttl = 'instant' | -| | ) | -+----------------+-----------------------------------------------------------+ - --- SQLNESS REPLACE \d{4} REDACTED -SHOW CREATE TABLE out_distinct_basic; - -+--------------------+---------------------------------------------------+ -| Table | Create Table | -+--------------------+---------------------------------------------------+ -| out_distinct_basic | CREATE TABLE IF NOT EXISTS "out_distinct_basic" ( | -| | "dis" INT NULL, | -| | "update_at" TIMESTAMP(3) NULL, | -| | "__ts_placeholder" TIMESTAMP(3) NOT NULL, | -| | TIME INDEX ("__ts_placeholder"), | -| | PRIMARY KEY ("dis") | -| | ) | -| | | -| | ENGINE=mito | -| | WITH( | -| | 'comment' = 'Sink table for flow flow-id=REDACTED' | -| | ) | -+--------------------+---------------------------------------------------+ - --- SQLNESS SLEEP 3s -INSERT INTO - distinct_basic -VALUES - (20, "2021-07-01 00:00:00.200"), - (20, "2021-07-01 00:00:00.200"), - (22, "2021-07-01 00:00:00.600"); - -Affected Rows: 0 - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_basic'); - -+-----------------------------------------+ -| ADMIN FLUSH_FLOW('test_distinct_basic') | -+-----------------------------------------+ -| FLOW_FLUSHED | -+-----------------------------------------+ - -SELECT - dis -FROM - out_distinct_basic; - -+-----+ -| dis | -+-----+ -| 20 | -| 22 | -+-----+ - -SELECT number FROM distinct_basic; - -+--------+ -| number | -+--------+ -+--------+ - -ADMIN FLUSH_TABLE('distinct_basic'); - -+-------------------------------------+ -| ADMIN FLUSH_TABLE('distinct_basic') | -+-------------------------------------+ -| 0 | -+-------------------------------------+ - --- Recover the persisted streaming DISTINCT flow, then replan its first write --- against an extended source schema without recreating the flow. --- SQLNESS ARG restart=true -SELECT 1; - -+----------+ -| Int64(1) | -+----------+ -| 1 | -+----------+ - -ALTER TABLE distinct_basic ADD COLUMN extra INT NULL; - -Affected Rows: 0 - -INSERT INTO - distinct_basic (number, ts) -VALUES - (23, "2021-07-01 00:00:01.600"), - (23, "2021-07-01 00:00:01.600"); - -Affected Rows: 0 - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_basic'); - -+-----------------------------------------+ -| ADMIN FLUSH_FLOW('test_distinct_basic') | -+-----------------------------------------+ -| FLOW_FLUSHED | -+-----------------------------------------+ - -SELECT - dis -FROM - out_distinct_basic; - -+-----+ -| dis | -+-----+ -| 20 | -| 22 | -| 23 | -+-----+ - -SELECT number FROM distinct_basic; - -+--------+ -| number | -+--------+ -+--------+ - -DROP FLOW test_distinct_basic; - -Affected Rows: 0 - -DROP TABLE distinct_basic; - -Affected Rows: 0 - -DROP TABLE out_distinct_basic; - -Affected Rows: 0 - --- test ttl = instant with EVAL INTERVAL must be rejected --- since the batching scheduler cannot read instant-TTL source tables and the --- streaming engine cannot honor the schedule -CREATE TABLE distinct_basic ( - "number" INT, - ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY(number), - TIME INDEX(ts) -)WITH ('ttl' = 'instant'); - -Affected Rows: 0 - --- SQLNESS REPLACE id=\d+ id=REDACTED -CREATE FLOW test_distinct_basic SINK TO out_distinct_basic EVAL INTERVAL '1m' AS +-- EVAL INTERVAL does not bypass the rejection: the batching scheduler is the +-- only execution profile left and it cannot read instant-TTL source tables. +CREATE FLOW test_scheduled_instant_rejected +SINK TO out_scheduled_instant_rejected +EVAL INTERVAL '1m' +AS SELECT DISTINCT number as dis FROM distinct_basic; -Error: 1004(InvalidArguments), Invalid SQL, error: flow 'test_distinct_basic' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode; use a TTL longer than the flush interval +Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval -SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'test_distinct_basic'; +SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS +WHERE flow_name IN ( + 'test_distinct_basic', + 'test_aggr_instant_rejected', + 'test_scheduled_instant_rejected' +); +----------+ | count(*) | @@ -223,7 +57,7 @@ DROP TABLE distinct_basic; Affected Rows: 0 --- test ttl = 5s (DISTINCT remains batching for persisted sources) +-- test ttl = 5s (persisted sources use the batching scheduler) CREATE TABLE distinct_basic ( "number" INT, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, @@ -233,8 +67,8 @@ CREATE TABLE distinct_basic ( Affected Rows: 0 --- Without a schedule, persisted DISTINCT must reach batching validation, --- not silently become request-local streaming. +-- Without a schedule, a window-less flow must reach batching validation +-- instead of silently becoming a request-local query. CREATE FLOW test_distinct_persisted_unscheduled SINK TO out_distinct_persisted_unscheduled AS SELECT DISTINCT number AS dis FROM distinct_basic; @@ -258,7 +92,6 @@ FROM Affected Rows: 0 -- flow_options should have a flow_type:batching --- persisted-source DISTINCT retains batching semantics SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS; +---------------------+--------------------------+ @@ -414,110 +247,3 @@ DROP TABLE out_distinct_basic; Affected Rows: 0 --- Streaming DISTINCT auto-sink retains all 1000 output tuples. -CREATE TABLE distinct_auto_sink ( - v INT, - ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX -) WITH ('ttl' = 'instant'); - -Affected Rows: 0 - -CREATE FLOW test_distinct_auto_sink SINK TO out_distinct_auto_sink AS -SELECT DISTINCT v FROM distinct_auto_sink; - -Affected Rows: 0 - -INSERT INTO distinct_auto_sink (v) -SELECT number FROM numbers LIMIT 1000; - -Affected Rows: 0 - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_auto_sink'); - -+---------------------------------------------+ -| ADMIN FLUSH_FLOW('test_distinct_auto_sink') | -+---------------------------------------------+ -| FLOW_FLUSHED | -+---------------------------------------------+ - -SELECT count(*) AS rows, count(DISTINCT v) AS distinct_values, min(v) AS min_v, max(v) AS max_v -FROM out_distinct_auto_sink; - -+------+-----------------+-------+-------+ -| rows | distinct_values | min_v | max_v | -+------+-----------------+-------+-------+ -| 1000 | 1000 | 0 | 999 | -+------+-----------------+-------+-------+ - -DROP FLOW test_distinct_auto_sink; - -Affected Rows: 0 - -DROP TABLE distinct_auto_sink; - -Affected Rows: 0 - -DROP TABLE out_distinct_auto_sink; - -Affected Rows: 0 - -CREATE TABLE distinct_auto_sink_pk ( - v INT, - k INT, - extra_value INT, - ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX, - PRIMARY KEY (v, k) -) WITH ('ttl' = 'instant'); - -Affected Rows: 0 - -CREATE FLOW test_distinct_auto_sink_pk SINK TO out_distinct_auto_sink_pk AS -SELECT DISTINCT v, extra_value FROM distinct_auto_sink_pk; - -Affected Rows: 0 - -INSERT INTO distinct_auto_sink_pk (v, k, extra_value) -SELECT number % 10 AS v, number AS k, number AS extra_value FROM numbers LIMIT 1000; - -Affected Rows: 0 - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_auto_sink_pk'); - -+------------------------------------------------+ -| ADMIN FLUSH_FLOW('test_distinct_auto_sink_pk') | -+------------------------------------------------+ -| FLOW_FLUSHED | -+------------------------------------------------+ - -SELECT - count(*) AS rows, - count(DISTINCT extra_value) AS distinct_values, - min(extra_value) AS min_value, - max(extra_value) AS max_value, - sum(CASE WHEN v = extra_value % 10 THEN 0 ELSE 1 END) AS mismatched_keys -FROM out_distinct_auto_sink_pk; - -+------+-----------------+-----------+-----------+-----------------+ -| rows | distinct_values | min_value | max_value | mismatched_keys | -+------+-----------------+-----------+-----------+-----------------+ -| 1000 | 1000 | 0 | 999 | 0 | -+------+-----------------+-----------+-----------+-----------------+ - -DROP FLOW test_distinct_auto_sink_pk; - -Affected Rows: 0 - -DROP TABLE distinct_auto_sink_pk; - -Affected Rows: 0 - -DROP TABLE out_distinct_auto_sink_pk; - -Affected Rows: 0 - diff --git a/tests/cases/standalone/common/flow/flow_advance_ttl.sql b/tests/cases/standalone/common/flow/flow_advance_ttl.sql index 72356d96372..136b3798605 100644 --- a/tests/cases/standalone/common/flow/flow_advance_ttl.sql +++ b/tests/cases/standalone/common/flow/flow_advance_ttl.sql @@ -6,104 +6,42 @@ CREATE TABLE distinct_basic ( TIME INDEX(ts) )WITH ('ttl' = 'instant'); --- request-local DISTINCT is supported in streaming mode --- SQLNESS REPLACE id=\d+ id=REDACTED +-- Instant-TTL source tables are no longer accepted as flow sources: a +-- stateless projection/DISTINCT query is rejected like any other flow. CREATE FLOW test_distinct_basic SINK TO out_distinct_basic AS SELECT DISTINCT number as dis FROM distinct_basic; --- instant-TTL sources reject non-stateless LIMIT plans -CREATE FLOW test_limit_instant_rejected SINK TO out_limit_instant_rejected AS +-- An aggregate query over an instant-TTL source is rejected as well. +CREATE FLOW test_aggr_instant_rejected SINK TO out_aggr_instant_rejected AS SELECT - number + max(number) AS max_number FROM - distinct_basic -LIMIT 1; + distinct_basic; --- flow_options should have a flow_type:streaming --- since source table's ttl=instant and DISTINCT is request-local -SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS; - -SHOW CREATE TABLE distinct_basic; - --- SQLNESS REPLACE \d{4} REDACTED -SHOW CREATE TABLE out_distinct_basic; - --- SQLNESS SLEEP 3s -INSERT INTO - distinct_basic -VALUES - (20, "2021-07-01 00:00:00.200"), - (20, "2021-07-01 00:00:00.200"), - (22, "2021-07-01 00:00:00.600"); - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_basic'); - -SELECT - dis -FROM - out_distinct_basic; - -SELECT number FROM distinct_basic; - -ADMIN FLUSH_TABLE('distinct_basic'); - --- Recover the persisted streaming DISTINCT flow, then replan its first write --- against an extended source schema without recreating the flow. --- SQLNESS ARG restart=true -SELECT 1; - -ALTER TABLE distinct_basic ADD COLUMN extra INT NULL; - -INSERT INTO - distinct_basic (number, ts) -VALUES - (23, "2021-07-01 00:00:01.600"), - (23, "2021-07-01 00:00:01.600"); - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_basic'); - -SELECT - dis -FROM - out_distinct_basic; - -SELECT number FROM distinct_basic; - -DROP FLOW test_distinct_basic; -DROP TABLE distinct_basic; -DROP TABLE out_distinct_basic; - --- test ttl = instant with EVAL INTERVAL must be rejected --- since the batching scheduler cannot read instant-TTL source tables and the --- streaming engine cannot honor the schedule -CREATE TABLE distinct_basic ( - "number" INT, - ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY(number), - TIME INDEX(ts) -)WITH ('ttl' = 'instant'); - --- SQLNESS REPLACE id=\d+ id=REDACTED -CREATE FLOW test_distinct_basic SINK TO out_distinct_basic EVAL INTERVAL '1m' AS +-- EVAL INTERVAL does not bypass the rejection: the batching scheduler is the +-- only execution profile left and it cannot read instant-TTL source tables. +CREATE FLOW test_scheduled_instant_rejected +SINK TO out_scheduled_instant_rejected +EVAL INTERVAL '1m' +AS SELECT DISTINCT number as dis FROM distinct_basic; -SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'test_distinct_basic'; +SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS +WHERE flow_name IN ( + 'test_distinct_basic', + 'test_aggr_instant_rejected', + 'test_scheduled_instant_rejected' +); DROP TABLE distinct_basic; --- test ttl = 5s (DISTINCT remains batching for persisted sources) +-- test ttl = 5s (persisted sources use the batching scheduler) CREATE TABLE distinct_basic ( "number" INT, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, @@ -111,8 +49,8 @@ CREATE TABLE distinct_basic ( TIME INDEX(ts) )WITH ('ttl' = '5s'); --- Without a schedule, persisted DISTINCT must reach batching validation, --- not silently become request-local streaming. +-- Without a schedule, a window-less flow must reach batching validation +-- instead of silently becoming a request-local query. CREATE FLOW test_distinct_persisted_unscheduled SINK TO out_distinct_persisted_unscheduled AS SELECT DISTINCT number AS dis FROM distinct_basic; @@ -127,7 +65,6 @@ FROM distinct_basic; -- flow_options should have a flow_type:batching --- persisted-source DISTINCT retains batching semantics SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS; -- SQLNESS ARG restart=true @@ -179,58 +116,3 @@ SELECT number FROM distinct_basic; DROP FLOW test_distinct_basic; DROP TABLE distinct_basic; DROP TABLE out_distinct_basic; - --- Streaming DISTINCT auto-sink retains all 1000 output tuples. -CREATE TABLE distinct_auto_sink ( - v INT, - ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX -) WITH ('ttl' = 'instant'); - -CREATE FLOW test_distinct_auto_sink SINK TO out_distinct_auto_sink AS -SELECT DISTINCT v FROM distinct_auto_sink; - -INSERT INTO distinct_auto_sink (v) -SELECT number FROM numbers LIMIT 1000; - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_auto_sink'); - -SELECT count(*) AS rows, count(DISTINCT v) AS distinct_values, min(v) AS min_v, max(v) AS max_v -FROM out_distinct_auto_sink; - -DROP FLOW test_distinct_auto_sink; -DROP TABLE distinct_auto_sink; -DROP TABLE out_distinct_auto_sink; - -CREATE TABLE distinct_auto_sink_pk ( - v INT, - k INT, - extra_value INT, - ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX, - PRIMARY KEY (v, k) -) WITH ('ttl' = 'instant'); - -CREATE FLOW test_distinct_auto_sink_pk SINK TO out_distinct_auto_sink_pk AS -SELECT DISTINCT v, extra_value FROM distinct_auto_sink_pk; - -INSERT INTO distinct_auto_sink_pk (v, k, extra_value) -SELECT number % 10 AS v, number AS k, number AS extra_value FROM numbers LIMIT 1000; - --- Mirror inserts reach the flownode asynchronously; wait before flushing. --- SQLNESS SLEEP 3s --- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | -ADMIN FLUSH_FLOW('test_distinct_auto_sink_pk'); - -SELECT - count(*) AS rows, - count(DISTINCT extra_value) AS distinct_values, - min(extra_value) AS min_value, - max(extra_value) AS max_value, - sum(CASE WHEN v = extra_value % 10 THEN 0 ELSE 1 END) AS mismatched_keys -FROM out_distinct_auto_sink_pk; - -DROP FLOW test_distinct_auto_sink_pk; -DROP TABLE distinct_auto_sink_pk; -DROP TABLE out_distinct_auto_sink_pk; diff --git a/tests/cases/standalone/common/flow/flow_legacy_streaming.result b/tests/cases/standalone/common/flow/flow_legacy_streaming.result new file mode 100644 index 00000000000..397ec8790ff --- /dev/null +++ b/tests/cases/standalone/common/flow/flow_legacy_streaming.result @@ -0,0 +1,91 @@ +-- The streaming runtime is gone, so the batching scheduler is the only execution +-- profile left. A flow whose SQL has no time window is exactly the shape the +-- streaming executor used to handle: it is now rejected, and the supported +-- migration is to recreate the flow with an explicit `EVAL INTERVAL`. +CREATE TABLE legacy_flow_src ( + host STRING, + val DOUBLE, + ts TIMESTAMP TIME INDEX +); + +Affected Rows: 0 + +CREATE TABLE legacy_flow_sink ( + host STRING, + val DOUBLE, + ts TIMESTAMP TIME INDEX +); + +Affected Rows: 0 + +CREATE FLOW legacy_flow SINK TO legacy_flow_sink AS +SELECT host, val, ts FROM legacy_flow_src; + +Error: 3001(EngineExecuteQuery), Invalid query: SQL batching flow without a time-window expression must specify EVAL INTERVAL to run as an explicit full-query flow + +SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow'; + ++----------+ +| count(*) | ++----------+ +| 0 | ++----------+ + +-- Recreating the flow with a schedule is the supported migration. +CREATE FLOW legacy_flow SINK TO legacy_flow_sink EVAL INTERVAL '1h' AS +SELECT host, val, ts FROM legacy_flow_src; + +Affected Rows: 0 + +-- The persisted option is still `batching`, so the metadata shape is unchanged. +SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow'; + ++-------------+--------------------------+ +| flow_name | options | ++-------------+--------------------------+ +| legacy_flow | {"flow_type":"batching"} | ++-------------+--------------------------+ + +INSERT INTO legacy_flow_src VALUES ('host_a', 1.0, '2024-01-01 00:00:00'); + +Affected Rows: 1 + +-- Mirror inserts reach the flownode asynchronously; wait before flushing. +-- SQLNESS SLEEP 3s +-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | +ADMIN FLUSH_FLOW('legacy_flow'); + ++---------------------------------+ +| ADMIN FLUSH_FLOW('legacy_flow') | ++---------------------------------+ +| FLOW_FLUSHED | ++---------------------------------+ + +SELECT host, val, ts FROM legacy_flow_sink ORDER BY ts; + ++--------+-----+---------------------+ +| host | val | ts | ++--------+-----+---------------------+ +| host_a | 1.0 | 2024-01-01T00:00:00 | ++--------+-----+---------------------+ + +DROP FLOW legacy_flow; + +Affected Rows: 0 + +SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow'; + ++----------+ +| count(*) | ++----------+ +| 0 | ++----------+ + +DROP TABLE legacy_flow_src; + +Affected Rows: 0 + +DROP TABLE legacy_flow_sink; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/flow/flow_legacy_streaming.sql b/tests/cases/standalone/common/flow/flow_legacy_streaming.sql new file mode 100644 index 00000000000..6b1c4f89d3d --- /dev/null +++ b/tests/cases/standalone/common/flow/flow_legacy_streaming.sql @@ -0,0 +1,44 @@ +-- The streaming runtime is gone, so the batching scheduler is the only execution +-- profile left. A flow whose SQL has no time window is exactly the shape the +-- streaming executor used to handle: it is now rejected, and the supported +-- migration is to recreate the flow with an explicit `EVAL INTERVAL`. +CREATE TABLE legacy_flow_src ( + host STRING, + val DOUBLE, + ts TIMESTAMP TIME INDEX +); + +CREATE TABLE legacy_flow_sink ( + host STRING, + val DOUBLE, + ts TIMESTAMP TIME INDEX +); + +CREATE FLOW legacy_flow SINK TO legacy_flow_sink AS +SELECT host, val, ts FROM legacy_flow_src; + +SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow'; + +-- Recreating the flow with a schedule is the supported migration. +CREATE FLOW legacy_flow SINK TO legacy_flow_sink EVAL INTERVAL '1h' AS +SELECT host, val, ts FROM legacy_flow_src; + +-- The persisted option is still `batching`, so the metadata shape is unchanged. +SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow'; + +INSERT INTO legacy_flow_src VALUES ('host_a', 1.0, '2024-01-01 00:00:00'); + +-- Mirror inserts reach the flownode asynchronously; wait before flushing. +-- SQLNESS SLEEP 3s +-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED | +ADMIN FLUSH_FLOW('legacy_flow'); + +SELECT host, val, ts FROM legacy_flow_sink ORDER BY ts; + +DROP FLOW legacy_flow; + +SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow'; + +DROP TABLE legacy_flow_src; + +DROP TABLE legacy_flow_sink; diff --git a/tests/cases/standalone/common/flow/flow_no_aggr.result b/tests/cases/standalone/common/flow/flow_no_aggr.result index 7ae7846e868..50bcab55b47 100644 --- a/tests/cases/standalone/common/flow/flow_no_aggr.result +++ b/tests/cases/standalone/common/flow/flow_no_aggr.result @@ -12,8 +12,11 @@ CREATE TABLE sink ( Affected Rows: 0 +-- A projection/filter flow has no time window, so it runs as an explicit +-- full-query flow on the batching scheduler and needs a schedule. CREATE FLOW filter_out SINK TO sink +EVAL INTERVAL '1h' AS SELECT desc_str, ts FROM base WHERE desc_str IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); @@ -22,11 +25,11 @@ Affected Rows: 0 SELECT options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'filter_out'; -+---------------------------+ -| options | -+---------------------------+ -| {"flow_type":"streaming"} | -+---------------------------+ ++--------------------------+ +| options | ++--------------------------+ +| {"flow_type":"batching"} | ++--------------------------+ INSERT INTO base VALUES ('a', '2023-01-01 00:00:00'), @@ -83,6 +86,7 @@ Affected Rows: 0 CREATE FLOW filter_out SINK TO sink +EVAL INTERVAL '1h' AS SELECT desc_str, ts FROM base WHERE desc_str NOT IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); @@ -91,11 +95,11 @@ Affected Rows: 0 SELECT options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'filter_out'; -+---------------------------+ -| options | -+---------------------------+ -| {"flow_type":"streaming"} | -+---------------------------+ ++--------------------------+ +| options | ++--------------------------+ +| {"flow_type":"batching"} | ++--------------------------+ INSERT INTO base VALUES ('a', '2023-01-01 00:00:00'), diff --git a/tests/cases/standalone/common/flow/flow_no_aggr.sql b/tests/cases/standalone/common/flow/flow_no_aggr.sql index b0016dacf9b..dc7be1efb0b 100644 --- a/tests/cases/standalone/common/flow/flow_no_aggr.sql +++ b/tests/cases/standalone/common/flow/flow_no_aggr.sql @@ -8,8 +8,11 @@ CREATE TABLE sink ( ts TIMESTAMP TIME INDEX ); +-- A projection/filter flow has no time window, so it runs as an explicit +-- full-query flow on the batching scheduler and needs a schedule. CREATE FLOW filter_out SINK TO sink +EVAL INTERVAL '1h' AS SELECT desc_str, ts FROM base WHERE desc_str IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); @@ -44,6 +47,7 @@ CREATE TABLE sink ( CREATE FLOW filter_out SINK TO sink +EVAL INTERVAL '1h' AS SELECT desc_str, ts FROM base WHERE desc_str NOT IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); diff --git a/tests/cases/standalone/common/flow/flow_null.result b/tests/cases/standalone/common/flow/flow_null.result index a141b9e03ab..c2b50b202d6 100644 --- a/tests/cases/standalone/common/flow/flow_null.result +++ b/tests/cases/standalone/common/flow/flow_null.result @@ -242,7 +242,7 @@ CREATE TABLE out_nullable_pk ( Affected Rows: 0 -CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk AS +CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk EVAL INTERVAL '1h' AS SELECT pid, client, diff --git a/tests/cases/standalone/common/flow/flow_null.sql b/tests/cases/standalone/common/flow/flow_null.sql index 6c1219df2db..4f768e98204 100644 --- a/tests/cases/standalone/common/flow/flow_null.sql +++ b/tests/cases/standalone/common/flow/flow_null.sql @@ -149,7 +149,7 @@ CREATE TABLE out_nullable_pk ( PRIMARY KEY (pid, client) ); -CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk AS +CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk EVAL INTERVAL '1h' AS SELECT pid, client, diff --git a/tests/cases/standalone/common/flow/show_create_flow.result b/tests/cases/standalone/common/flow/show_create_flow.result index d451c552ec3..de6ac2e49f3 100644 --- a/tests/cases/standalone/common/flow/show_create_flow.result +++ b/tests/cases/standalone/common/flow/show_create_flow.result @@ -29,7 +29,7 @@ SHOW FLOWS LIKE 'filter_numbers_show'; +-------+ +-------+ -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number FROM numbers_input_show where number > 10; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number FROM numbers_input_show where number > 10; Affected Rows: 0 @@ -40,6 +40,7 @@ SHOW CREATE FLOW filter_numbers_show; +---------------------+------------------------------------------------------------+ | filter_numbers_show | CREATE FLOW IF NOT EXISTS filter_numbers_show | | | SINK TO public.out_num_cnt_show | +| | EVAL INTERVAL '3600 s' | | | AS SELECT number FROM numbers_input_show WHERE number > 10 | +---------------------+------------------------------------------------------------+ @@ -50,6 +51,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number FROM numbers_input_show WHERE number > 10 | | +---------------------+---------------+------------------------------------------------------------+------------------------------------+ @@ -81,7 +83,7 @@ SHOW FLOWS LIKE 'filter_numbers_show'; -- also test `CREATE OR REPLACE` and `IF NOT EXISTS` -- (flow exists, replace, if not exists)=(false, false, false) -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 10; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 10; Affected Rows: 0 @@ -92,12 +94,13 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > 10 | | +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ -- this one should error out -- (flow exists, replace, if not exists)=(true, false, false) -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 15; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 15; Error: 8000(FlowAlreadyExists), Flow already exists: greptime.filter_numbers_show @@ -108,6 +111,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > 10 | | +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ @@ -138,7 +142,7 @@ SELECT number, ts FROM out_num_cnt_show; -- after this one, the flow SHOULD NOT be replaced -- (flow exists, replace, if not exists)=(true, false, true) -CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 5; +CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 5; Affected Rows: 0 @@ -149,6 +153,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > 10 | | +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ @@ -180,7 +185,7 @@ SELECT number, ts FROM out_num_cnt_show; -- after this, the flow SHOULD be replaced -- (flow exists, replace, if not exists)=(true, true, false) -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 3; +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 3; Affected Rows: 0 @@ -191,6 +196,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+---------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > 3 | | +---------------------+---------------+---------------------------------------------------------------+------------------------------------+ @@ -216,6 +222,9 @@ SELECT number, ts FROM out_num_cnt_show; | number | ts | +--------+-------------------------+ | 4 | 1970-01-01T00:00:00.002 | +| 4 | 1970-01-01T00:00:00.004 | +| 5 | 1970-01-01T00:00:00.004 | +| 10 | 1970-01-01T00:00:00 | | 10 | 1970-01-01T00:00:00.003 | | 11 | 1970-01-01T00:00:00.004 | | 15 | 1970-01-01T00:00:00.001 | @@ -235,6 +244,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+---------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > 3 | | +---------------------+---------------+---------------------------------------------------------------+------------------------------------+ @@ -260,7 +270,7 @@ Error: 8001(FlowNotFound), Flow not found: greptime.filter_numbers_show -- following always create since didn't exist -- (flow exists, replace, if not exists)=(false, true, false) -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -2; +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -2; Affected Rows: 0 @@ -271,6 +281,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > -2 | | +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ @@ -279,7 +290,7 @@ DROP FLOW filter_numbers_show; Affected Rows: 0 -- (flow exists, replace, if not exists)=(false, false, true) -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -3; +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -3; Affected Rows: 0 @@ -290,6 +301,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > -3 | | +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ @@ -311,6 +323,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ | filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | | | SINK TO public.out_num_cnt_show | | +| | | EVAL INTERVAL '3600 s' | | | | | AS SELECT number, ts FROM numbers_input_show WHERE number > -3 | | +---------------------+---------------+----------------------------------------------------------------+------------------------------------+ @@ -320,6 +333,9 @@ SELECT * FROM out_num_cnt_show; | number | ts | +--------+-------------------------+ | 4 | 1970-01-01T00:00:00.002 | +| 4 | 1970-01-01T00:00:00.004 | +| 5 | 1970-01-01T00:00:00.004 | +| 10 | 1970-01-01T00:00:00 | | 10 | 1970-01-01T00:00:00.003 | | 11 | 1970-01-01T00:00:00.004 | | 15 | 1970-01-01T00:00:00.001 | @@ -348,7 +364,11 @@ SELECT * FROM out_num_cnt_show; +--------+-------------------------+ | -2 | 1970-01-01T00:00:00.002 | | -1 | 1970-01-01T00:00:00.003 | +| 3 | 1970-01-01T00:00:00.001 | | 4 | 1970-01-01T00:00:00.002 | +| 4 | 1970-01-01T00:00:00.004 | +| 5 | 1970-01-01T00:00:00.004 | +| 10 | 1970-01-01T00:00:00 | | 10 | 1970-01-01T00:00:00.003 | | 11 | 1970-01-01T00:00:00.004 | | 15 | 1970-01-01T00:00:00.001 | @@ -384,7 +404,7 @@ create table out_num_cnt_show ( Affected Rows: 0 -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number as n1 FROM numbers_input_show where number > 10; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number as n1 FROM numbers_input_show where number > 10; Affected Rows: 0 @@ -412,15 +432,20 @@ SELECT number FROM out_num_cnt_show; | 16 | +--------+ +-- The sink schema mismatch is detected on the flownode. In distributed mode the +-- error crosses gRPC and loses its source chain, so normalize the trailing chain +-- to keep both environments comparable; the rejection itself is identical. -- should mismatch, hence the old flow remains -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15; +-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15; -Error: 3001(EngineExecuteQuery), Invalid query: Flow output column 1 has type Int32(Int32Type), but sink column ts has type Timestamp(Millisecond(TimestampMillisecondType)) +Error: 3001(EngineExecuteQuery), Datafusion error: Plan("Cannot match flow output column 'n2' to sink column 'ts' by position: incompatible data types, flow output type is Int32(Int32Type), sink column type is Timestamp(Millisecond(TimestampMillisecondType)). Flow output schema does not match sink table schema: found 2 flow output columns and 2 sink table columns. flow output columns: [\"n1\", \"n2\"], sink table columns: [\"number\", \"ts\"], extra flow columns not in sink: [\"n1\", \"n2\"], missing sink columns from flow output: [\"number\", \"ts\"]") in context: Failed to rewrite plan -- should mismatch, hence the old flow remains -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15; +-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15; -Error: 3001(EngineExecuteQuery), Invalid query: Flow output has 3 columns, but sink has 2 columns; only zero, one, or two trailing auto columns are supported +Error: 3001(EngineExecuteQuery), Datafusion error: Plan("Flow output schema does not match sink table schema: found 3 flow output columns and 2 sink table columns. flow output columns: [\"n1\", \"n2\", \"n3\"], sink table columns: [\"number\", \"ts\"], extra flow columns not in sink: [\"n1\", \"n2\", \"n3\"], missing sink columns from flow output: [\"number\", \"ts\"]") in context: Failed to rewrite plan SELECT flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; @@ -429,6 +454,7 @@ SELECT flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE f +------------------------------------------------------------------+------------------------------------+ | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show | | SINK TO public.out_num_cnt_show | | +| EVAL INTERVAL '3600 s' | | | AS SELECT number AS n1 FROM numbers_input_show WHERE number > 10 | | +------------------------------------------------------------------+------------------------------------+ @@ -457,6 +483,7 @@ SELECT number FROM out_num_cnt_show; | 15 | | 15 | | 16 | +| 16 | | 18 | +--------+ @@ -466,6 +493,7 @@ Affected Rows: 0 CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show +EVAL INTERVAL '1h' WITH (defer_on_missing_source = true) AS SELECT number AS n1 FROM numbers_input_show where number > 10; @@ -478,6 +506,7 @@ SHOW CREATE FLOW filter_numbers_show; +---------------------+------------------------------------------------------------------+ | filter_numbers_show | CREATE FLOW IF NOT EXISTS filter_numbers_show | | | SINK TO public.out_num_cnt_show | +| | EVAL INTERVAL '3600 s' | | | WITH (defer_on_missing_source = 'true') | | | AS SELECT number AS n1 FROM numbers_input_show WHERE number > 10 | +---------------------+------------------------------------------------------------------+ @@ -489,6 +518,7 @@ SELECT flow_definition FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_num +------------------------------------------------------------------+ | CREATE FLOW IF NOT EXISTS filter_numbers_show | | SINK TO public.out_num_cnt_show | +| EVAL INTERVAL '3600 s' | | WITH (defer_on_missing_source = 'true') | | AS SELECT number AS n1 FROM numbers_input_show WHERE number > 10 | +------------------------------------------------------------------+ diff --git a/tests/cases/standalone/common/flow/show_create_flow.sql b/tests/cases/standalone/common/flow/show_create_flow.sql index a2bcc4c06d9..188d60afbb8 100644 --- a/tests/cases/standalone/common/flow/show_create_flow.sql +++ b/tests/cases/standalone/common/flow/show_create_flow.sql @@ -15,7 +15,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM SHOW FLOWS LIKE 'filter_numbers_show'; -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number FROM numbers_input_show where number > 10; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number FROM numbers_input_show where number > 10; SHOW CREATE FLOW filter_numbers_show; @@ -32,13 +32,13 @@ SHOW FLOWS LIKE 'filter_numbers_show'; -- also test `CREATE OR REPLACE` and `IF NOT EXISTS` -- (flow exists, replace, if not exists)=(false, false, false) -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 10; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 10; SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; -- this one should error out -- (flow exists, replace, if not exists)=(true, false, false) -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 15; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 15; SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; @@ -54,7 +54,7 @@ SELECT number, ts FROM out_num_cnt_show; -- after this one, the flow SHOULD NOT be replaced -- (flow exists, replace, if not exists)=(true, false, true) -CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 5; +CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 5; SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; @@ -70,7 +70,7 @@ SELECT number, ts FROM out_num_cnt_show; -- after this, the flow SHOULD be replaced -- (flow exists, replace, if not exists)=(true, true, false) -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 3; +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 3; SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; @@ -101,14 +101,14 @@ DROP FLOW filter_numbers_show; -- following always create since didn't exist -- (flow exists, replace, if not exists)=(false, true, false) -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -2; +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -2; SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; DROP FLOW filter_numbers_show; -- (flow exists, replace, if not exists)=(false, false, true) -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -3; +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -3; SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; @@ -149,7 +149,7 @@ create table out_num_cnt_show ( PRIMARY KEY(number), ); -CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number as n1 FROM numbers_input_show where number > 10; +CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number as n1 FROM numbers_input_show where number > 10; INSERT INTO numbers_input_show VALUES (10, 0),(15, 1),(16, 2); @@ -160,11 +160,16 @@ ADMIN FLUSH_FLOW('filter_numbers_show'); SELECT number FROM out_num_cnt_show; +-- The sink schema mismatch is detected on the flownode. In distributed mode the +-- error crosses gRPC and loses its source chain, so normalize the trailing chain +-- to keep both environments comparable; the rejection itself is identical. -- should mismatch, hence the old flow remains -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15; +-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15; -- should mismatch, hence the old flow remains -CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15; +-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan +CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15; SELECT flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show'; @@ -182,6 +187,7 @@ DROP FLOW filter_numbers_show; CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show +EVAL INTERVAL '1h' WITH (defer_on_missing_source = true) AS SELECT number AS n1 FROM numbers_input_show where number > 10;