diff --git a/src/common/meta/src/ddl/create_flow.rs b/src/common/meta/src/ddl/create_flow.rs index a618bf9bea0..948ec914440 100644 --- a/src/common/meta/src/ddl/create_flow.rs +++ b/src/common/meta/src/ddl/create_flow.rs @@ -16,6 +16,7 @@ mod metadata; use std::collections::{BTreeMap, HashMap}; use std::fmt; +#[cfg(feature = "enterprise")] use std::str::FromStr; use api::v1::ExpireAfter; @@ -23,6 +24,7 @@ use api::v1::flow::flow_request::Body as PbFlowRequest; use api::v1::flow::{CreateRequest, FlowRequest, FlowRequestHeader}; use async_trait::async_trait; use chrono::{DateTime, Utc}; +#[cfg(feature = "enterprise")] use common_base::readable_size::ReadableSize; use common_catalog::format_full_flow_name; use common_procedure::error::{FromJsonSnafu, ToJsonSnafu}; @@ -470,12 +472,32 @@ pub const DEFER_ON_MISSING_SOURCE_KEY: &str = "defer_on_missing_source"; /// The flow option key for the maximum memory one Flow's query execution may use. /// -/// The value is a [`ReadableSize`] string such as `"512MB"` (binary units, so +/// The value is a `ReadableSize` string such as `"512MB"` (binary units, so /// `512MB` == 536870912 bytes), interpreted as the memory budget of this Flow's /// query execution. The parsed byte budget is persisted with the flow options /// and carried with every query the flow executes. pub const FLOW_MAX_MEMORY_OPTION_KEY: &str = "max_memory"; +/// The error message reported when [`FLOW_MAX_MEMORY_OPTION_KEY`] is used in a +/// build that does not support it. +/// +/// `max_memory` is an enterprise flow option, so a build compiled without the +/// `enterprise` feature must reject it rather than silently run the flow without +/// its budget. Shared with the query engine and the flownode so the wording +/// cannot drift between the layers that have to refuse it. +pub const FLOW_MAX_MEMORY_UNSUPPORTED_MSG: &str = + "flow option `max_memory` requires the enterprise edition"; + +/// Flow options that only the `enterprise` feature supports, listed after the +/// always supported ones in the unknown-option error. +#[cfg(feature = "enterprise")] +const ENTERPRISE_FLOW_OPTIONS: [&str; 1] = [FLOW_MAX_MEMORY_OPTION_KEY]; + +/// The default build supports no enterprise-only flow option, so `max_memory` is +/// never advertised as supported here. +#[cfg(not(feature = "enterprise"))] +const ENTERPRISE_FLOW_OPTIONS: [&str; 0] = []; + /// Internal transient key used to pass the typed `EVAL OFFSET` (whole seconds) /// from the operator to meta through `CreateFlowExpr.flow_options`. Inserted by /// the operator only after user option validation; parsed and stripped by @@ -523,6 +545,22 @@ pub fn defer_on_missing_source(flow_task: &CreateFlowTask) -> Result { .map(|value| value.unwrap_or(false)) } +/// The flow options this build supports, in the order the unknown-option error +/// lists them. +/// +/// [`FLOW_MAX_MEMORY_OPTION_KEY`] is an enterprise flow option, so it only shows +/// up here when the `enterprise` feature is enabled - a default build rejects it +/// as an unknown option and must not advertise it. +fn supported_flow_options() -> String { + [ + DEFER_ON_MISSING_SOURCE_KEY, + FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, + ] + .into_iter() + .chain(ENTERPRISE_FLOW_OPTIONS) + .join(", ") +} + pub fn validate_flow_options(flow_task: &CreateFlowTask) -> Result<()> { // Reject non-positive eval_interval_secs (zero or negative). if let Some(secs) = flow_task.eval_interval_secs @@ -566,12 +604,16 @@ pub fn validate_flow_options(flow_task: &CreateFlowTask) -> Result<()> { match key.as_str() { DEFER_ON_MISSING_SOURCE_KEY | FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY - | FLOW_MAX_MEMORY_OPTION_KEY | FlowType::FLOW_TYPE_KEY => {} + // Enterprise-only flow option: the default build rejects it through + // the unknown-option branch below. + #[cfg(feature = "enterprise")] + FLOW_MAX_MEMORY_OPTION_KEY => {} unknown => { return InvalidFlowOptionSnafu { err_msg: format!( - "unknown flow option '{unknown}', supported options: {DEFER_ON_MISSING_SOURCE_KEY}, {FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY}, {FLOW_MAX_MEMORY_OPTION_KEY}" + "unknown flow option '{unknown}', supported options: {}", + supported_flow_options() ), } .fail(); @@ -594,6 +636,9 @@ pub fn validate_flow_options(flow_task: &CreateFlowTask) -> Result<()> { })?; } + // `max_memory` is an enterprise flow option: parse and validate its value + // only where it is supported. + #[cfg(feature = "enterprise")] if let Some(value) = flow_task.flow_options.get(FLOW_MAX_MEMORY_OPTION_KEY) { let bytes = ReadableSize::from_str(value).map_err(|_| { InvalidFlowOptionSnafu { @@ -614,21 +659,27 @@ pub fn validate_flow_options(flow_task: &CreateFlowTask) -> Result<()> { } defer_on_missing_source(flow_task)?; - let flow_type = get_flow_type_from_options(flow_task)?; // The memory budget is only enforced on the batching execution path, and // streaming flows ignore `flow_options` entirely (see // `src/flow/src/adapter.rs`), so accepting it there would be a silent no-op. - if flow_type == FlowType::Streaming - && flow_task - .flow_options - .contains_key(FLOW_MAX_MEMORY_OPTION_KEY) + // Only reachable with the enterprise feature, the only build that accepts + // `max_memory` at all. `get_flow_type_from_options` is also applied by the + // procedure itself, so skipping it here loses no validation. + #[cfg(feature = "enterprise")] { - return InvalidFlowOptionSnafu { - err_msg: format!( - "flow option '{FLOW_MAX_MEMORY_OPTION_KEY}' is only supported for batching flows" - ), + let flow_type = get_flow_type_from_options(flow_task)?; + if flow_type == FlowType::Streaming + && flow_task + .flow_options + .contains_key(FLOW_MAX_MEMORY_OPTION_KEY) + { + return InvalidFlowOptionSnafu { + err_msg: format!( + "flow option '{FLOW_MAX_MEMORY_OPTION_KEY}' is only supported for batching flows" + ), + } + .fail(); } - .fail(); } Ok(()) } diff --git a/src/common/meta/src/ddl/tests/create_flow.rs b/src/common/meta/src/ddl/tests/create_flow.rs index 06c03e53e7d..081c55f9c2b 100644 --- a/src/common/meta/src/ddl/tests/create_flow.rs +++ b/src/common/meta/src/ddl/tests/create_flow.rs @@ -25,10 +25,12 @@ use common_procedure_test::execute_procedure_until_done; use table::table_name::TableName; use crate::ddl::DdlContext; +#[cfg(feature = "enterprise")] +use crate::ddl::create_flow::FLOW_MAX_MEMORY_OPTION_KEY; use crate::ddl::create_flow::{ CreateFlowData, CreateFlowProcedure, CreateFlowState, DEFER_ON_MISSING_SOURCE_KEY, - FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FLOW_MAX_MEMORY_OPTION_KEY, FlowType, - ceil_to_whole_sec, defer_on_missing_source, effective_eval_schedule_from_flow_info, + FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType, ceil_to_whole_sec, + defer_on_missing_source, effective_eval_schedule_from_flow_info, resolve_schedule_defaults_into_task, validate_flow_options, }; use crate::ddl::test_util::create_table::test_create_table_task; @@ -341,13 +343,46 @@ fn test_validate_flow_options_unknown_option_matches_invalid_sql_error() { let err = validate_flow_options(&task).unwrap_err(); assert_eq!(StatusCode::InvalidArguments, err.status_code()); + // `max_memory` is an enterprise-only flow option, so the supported list (and + // therefore the whole message) depends on the build. + let supported = if cfg!(feature = "enterprise") { + "defer_on_missing_source, experimental_enable_incremental_read, max_memory" + } else { + "defer_on_missing_source, experimental_enable_incremental_read" + }; assert_eq!( - "Invalid SQL, error: unknown flow option 'foo', supported options: defer_on_missing_source, experimental_enable_incremental_read, max_memory", + format!("Invalid SQL, error: unknown flow option 'foo', supported options: {supported}"), err.output_msg() ); assert!(!err.output_msg().contains("sensitive-value")); } +/// A default build does not support the `max_memory` flow option: it must be +/// rejected as an unknown option, and the error must not advertise it. +#[cfg(not(feature = "enterprise"))] +#[test] +fn test_validate_flow_options_rejects_max_memory_on_default_build() { + // The key is spelled out on purpose: the constant is only exported as a + // supported option by the enterprise build. + let mut task = test_create_flow_task( + "my_flow", + vec![], + TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "my_sink_table"), + false, + ); + task.flow_options + .insert("max_memory".to_string(), "512MB".to_string()); + + let err = validate_flow_options(&task).unwrap_err(); + assert_eq!(StatusCode::InvalidArguments, err.status_code()); + assert_eq!( + "Invalid SQL, error: unknown flow option 'max_memory', supported options: defer_on_missing_source, experimental_enable_incremental_read", + err.output_msg() + ); + assert!(!err.output_msg().contains("max_memory, ")); +} + +#[cfg(feature = "enterprise")] #[test] fn test_validate_flow_options_accepts_max_memory() { for value in ["512MB", "1073741824", "1GiB"] { @@ -364,6 +399,7 @@ fn test_validate_flow_options_accepts_max_memory() { } } +#[cfg(feature = "enterprise")] #[test] fn test_validate_flow_options_rejects_invalid_max_memory() { for value in ["not-a-size", "0", "0B"] { @@ -386,6 +422,7 @@ fn test_validate_flow_options_rejects_invalid_max_memory() { } } +#[cfg(feature = "enterprise")] #[test] fn test_validate_flow_options_rejects_max_memory_for_streaming_flows() { let mut streaming = test_create_flow_task( diff --git a/src/flow/src/batching_mode/engine.rs b/src/flow/src/batching_mode/engine.rs index 750c1ebaf77..ba5f9663170 100644 --- a/src/flow/src/batching_mode/engine.rs +++ b/src/flow/src/batching_mode/engine.rs @@ -15,12 +15,14 @@ //! Batching mode engine use std::collections::{BTreeMap, HashMap, HashSet}; +#[cfg(feature = "enterprise")] use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use api::v1::flow::DirtyWindowRequests; use catalog::CatalogManagerRef; +#[cfg(feature = "enterprise")] use common_base::readable_size::ReadableSize; use common_error::ext::BoxedError; use common_meta::ddl::create_flow::{ @@ -521,31 +523,53 @@ impl BatchingEngine { /// Meta already validates the option, so this is defense in depth: an /// unparsable or non-positive value fails flow creation instead of being /// silently dropped. + /// + /// # Enterprise gating + /// + /// `max_memory` is an enterprise flow option. A build without the + /// `enterprise` feature must not start the flow unbudgeted either: a flownode + /// can be handed persisted flow options directly when it recreates flows + /// after a restart (`FlowDualEngine::recover`), which bypasses the meta + /// validator, so the option is refused with [`Error::Unsupported`] here. The + /// refusal surfaces as that flow's recovery error instead of as a running + /// flow whose declared limit is silently ignored. pub(crate) fn max_memory_bytes_for_flow_options( flow_options: &HashMap, ) -> Result, Error> { - flow_options - .get(FLOW_MAX_MEMORY_OPTION_KEY) - .map(|value| { - let bytes = ReadableSize::from_str(value).map_err(|_| { - InvalidQuerySnafu { - reason: format!( - "Invalid flow option {FLOW_MAX_MEMORY_OPTION_KEY}: {value}, expect a size like '512MB'" - ), - } - .build() - })?; - ensure!( - bytes.as_bytes() > 0, - InvalidQuerySnafu { - reason: format!( - "Invalid flow option {FLOW_MAX_MEMORY_OPTION_KEY}: {value}, the memory budget must be positive" - ), - } - ); - Ok(bytes.as_bytes()) - }) - .transpose() + #[cfg(not(feature = "enterprise"))] + { + if flow_options.contains_key(FLOW_MAX_MEMORY_OPTION_KEY) { + return UnsupportedSnafu { + reason: common_meta::ddl::create_flow::FLOW_MAX_MEMORY_UNSUPPORTED_MSG + .to_string(), + } + .fail(); + } + Ok(None) + } + #[cfg(feature = "enterprise")] + { + let Some(value) = flow_options.get(FLOW_MAX_MEMORY_OPTION_KEY) else { + return Ok(None); + }; + let bytes = ReadableSize::from_str(value).map_err(|_| { + InvalidQuerySnafu { + reason: format!( + "Invalid flow option {FLOW_MAX_MEMORY_OPTION_KEY}: {value}, expect a size like '512MB'" + ), + } + .build() + })?; + ensure!( + bytes.as_bytes() > 0, + InvalidQuerySnafu { + reason: format!( + "Invalid flow option {FLOW_MAX_MEMORY_OPTION_KEY}: {value}, the memory budget must be positive" + ), + } + ); + Ok(Some(bytes.as_bytes())) + } } fn table_options_enable_append_mode(extra_options: &HashMap) -> bool { @@ -1169,6 +1193,7 @@ mod tests { /// `max_memory` is resolved from the flow options at creation time; an /// absent option yields no budget, an unparsable or non-positive value /// fails creation instead of silently dropping the limit. + #[cfg(feature = "enterprise")] #[test] fn test_max_memory_bytes_for_flow_options() { assert_eq!( @@ -1206,6 +1231,57 @@ mod tests { } } + /// A default build does not support the enterprise-only `max_memory` option: + /// an absent option still yields no budget, a declared one is refused instead + /// of dropping the limit. + #[cfg(not(feature = "enterprise"))] + #[test] + fn test_max_memory_bytes_for_flow_options_requires_enterprise() { + assert_eq!( + BatchingEngine::max_memory_bytes_for_flow_options(&HashMap::new()).unwrap(), + None + ); + + for value in ["512MB", "not-a-size", "0"] { + let err = BatchingEngine::max_memory_bytes_for_flow_options(&HashMap::from([( + FLOW_MAX_MEMORY_OPTION_KEY.to_string(), + value.to_string(), + )])) + .unwrap_err(); + assert!( + matches!(err, Error::Unsupported { .. }), + "unexpected error for {value}: {err:?}" + ); + assert_eq!( + "Unsupported: flow option `max_memory` requires the enterprise edition", + err.to_string() + ); + } + } + + /// The flownode can be handed persisted flow options directly - flow recovery + /// recreates each flow from its `FlowInfoValue.options` - so the create path + /// itself must refuse the unsupported option rather than start the flow + /// without its budget. + #[cfg(not(feature = "enterprise"))] + #[tokio::test] + async fn test_create_flow_rejects_max_memory_on_default_build() { + let engine = new_test_engine().await; + let mut args = flow_create_args(11, "max_memory_rejected"); + args.flow_options + .insert(FLOW_MAX_MEMORY_OPTION_KEY.to_string(), "512MB".to_string()); + + let err = engine.create_flow_inner(args).await.unwrap_err(); + assert!( + matches!(err, Error::Unsupported { .. }), + "unexpected error: {err:?}" + ); + assert_eq!( + "Unsupported: flow option `max_memory` requires the enterprise edition", + err.to_string() + ); + } + async fn new_test_engine() -> BatchingEngine { let kv_backend = Arc::new(MemoryKvBackend::new()); let table_meta = Arc::new(TableMetadataManager::new(kv_backend.clone())); diff --git a/src/flow/src/batching_mode/task.rs b/src/flow/src/batching_mode/task.rs index a3b7597b6cb..8513d44627e 100644 --- a/src/flow/src/batching_mode/task.rs +++ b/src/flow/src/batching_mode/task.rs @@ -166,6 +166,12 @@ pub struct TaskConfig { /// Resolved per-flow memory budget in bytes, parsed from the flow's /// `max_memory` option at creation time. Carried to the frontend as the /// `flow.max_memory_bytes` extension with every query this task issues. + /// + /// Never set on a build without the `enterprise` feature: + /// `BatchingEngine::max_memory_bytes_for_flow_options` refuses the option + /// there, so the field - and therefore the extension below - stays `None` / + /// empty. It is kept ungated because it is the mechanism the enterprise build + /// activates, and gating it would fork the task's runtime behaviour. pub max_memory_bytes: Option, } @@ -519,6 +525,11 @@ impl BatchingTask { /// flow-owned statements issued through `FrontendClient::sql`); a path that /// drops them while a budget is configured escapes the budget and can run /// unbounded. + /// + /// Unreachable on a build without the `enterprise` feature: a flow whose + /// options contain `max_memory` fails to be created or restored there, so + /// [`TaskConfig::max_memory_bytes`] is always `None`. Kept ungated because it + /// is the mechanism the enterprise build drives. pub fn memory_budget_extensions(&self) -> Vec<(String, String)> { let Some(max_memory_bytes) = self.config.max_memory_bytes else { return Vec::new(); diff --git a/src/flow/src/batching_mode/task/test.rs b/src/flow/src/batching_mode/task/test.rs index 5b84b0edbd3..69769c3378f 100644 --- a/src/flow/src/batching_mode/task/test.rs +++ b/src/flow/src/batching_mode/task/test.rs @@ -26,6 +26,7 @@ use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; use common_error::ext::BoxedError; use common_error::mock::MockError; use common_error::status_code::StatusCode; +#[cfg(feature = "enterprise")] use common_meta::ddl::create_flow::FLOW_MAX_MEMORY_OPTION_KEY; use common_query::Output; use common_recordbatch::RecordBatch; @@ -55,6 +56,7 @@ use crate::batching_mode::checkpoint::{ CHECKPOINT_DECISION_ADVANCE, CHECKPOINT_DECISION_FALLBACK, CHECKPOINT_REASON_NONE, FlowCheckpointDecision, FlowQueryFallbackReason, }; +#[cfg(feature = "enterprise")] use crate::batching_mode::engine::BatchingEngine; use crate::batching_mode::eval_schedule::{FlowMissedTickPolicy, FlowScheduleConfig}; use crate::batching_mode::state::CheckpointMode; @@ -1803,12 +1805,18 @@ async fn test_frontend_extensions_carry_max_memory_bytes() { "flow.flow_id must not be forwarded without the max_memory option" ); - // `max_memory = '512MB'` as resolved by the batching engine. + // `max_memory = '512MB'` as resolved by the batching engine, which is an + // enterprise-only step: a default build refuses the option itself (see + // `max_memory_bytes_for_flow_options`), so the resolved budget is set + // directly there. Forwarding it stays part of the mechanism in both builds. + #[cfg(feature = "enterprise")] let max_memory_bytes = BatchingEngine::max_memory_bytes_for_flow_options(&HashMap::from([( FLOW_MAX_MEMORY_OPTION_KEY.to_string(), "512MB".to_string(), )])) .unwrap(); + #[cfg(not(feature = "enterprise"))] + let max_memory_bytes = Some(536_870_912_u64); assert_eq!(max_memory_bytes, Some(536_870_912)); Arc::get_mut(&mut task.config).unwrap().max_memory_bytes = max_memory_bytes; diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index 62335cf089a..72c7bf5127c 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -3507,6 +3507,7 @@ mod tests { /// A Flow's declared memory budget must be resolved at the request entry: the /// context is captured during table lookup - before `engine_context` runs - /// and re-entered later, so a scope attached only there would never reach it. + #[cfg(feature = "enterprise")] #[tokio::test] async fn test_grpc_do_query_attaches_flow_memory_scope_before_execution() -> TestResult<()> { let interceptor = Arc::new(CapturingQueryContextInterceptor::new()); @@ -3572,6 +3573,51 @@ mod tests { Ok(()) } + /// `max_memory` is an enterprise flow option: a default build must fail a + /// request that declares a budget instead of running it on the node pool, + /// where the missing limit would be invisible. + #[cfg(not(feature = "enterprise"))] + #[tokio::test] + async fn test_grpc_do_query_rejects_flow_memory_budget_on_default_build() -> TestResult<()> { + let interceptor = Arc::new(CapturingQueryContextInterceptor::new()); + let instance = test_instance_with_insert_select_interceptor(interceptor.clone()).await?; + + let query_ctx = Arc::new( + QueryContextBuilder::default() + .set_extension( + query::options::FLOW_MAX_MEMORY_BYTES.to_string(), + "4096".to_string(), + ) + .set_extension(query::options::FLOW_ID.to_string(), "42".to_string()) + .build(), + ); + let request = Request::Query(api::v1::QueryRequest { + query: Some(Query::Sql("SELECT 1".to_string())), + }); + let err = servers::query_handler::grpc::GrpcQueryHandler::do_query( + &instance, + request, + query_ctx.clone(), + ) + .await + .unwrap_err(); + + assert_eq!(StatusCode::Unsupported, err.status_code()); + assert!( + err.output_msg() + .contains("flow option `max_memory` requires the enterprise edition"), + "unexpected error: {}", + err.output_msg() + ); + // The request entry still never mutates the caller's context... + assert!(query_ctx.memory_scope().is_none()); + // ...and the context planning saw carries no scope either: the refusal + // happens when the engine resolves the budget, not at the entry. + assert!(interceptor.take().memory_scope().is_none()); + + Ok(()) + } + #[tokio::test] async fn test_write_only_grpc_sql_is_checked_after_parsing() -> TestResult<()> { let plugins = Plugins::new(); diff --git a/src/operator/src/statement/ddl.rs b/src/operator/src/statement/ddl.rs index 3eb7c91455c..bef97fe40a9 100644 --- a/src/operator/src/statement/ddl.rs +++ b/src/operator/src/statement/ddl.rs @@ -40,9 +40,11 @@ use common_error::ext::BoxedError; #[cfg(feature = "enterprise")] use common_meta::cache_invalidator::CacheInvalidatorRef; use common_meta::cache_invalidator::Context; +#[cfg(feature = "enterprise")] +use common_meta::ddl::create_flow::FLOW_MAX_MEMORY_OPTION_KEY; use common_meta::ddl::create_flow::{ - DEFER_ON_MISSING_SOURCE_KEY, FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, - FLOW_MAX_MEMORY_OPTION_KEY, FlowType, INTERNAL_EVAL_OFFSET_KEY, INTERNAL_EVAL_SCHEDULE_KEY, + DEFER_ON_MISSING_SOURCE_KEY, FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType, + INTERNAL_EVAL_OFFSET_KEY, INTERNAL_EVAL_SCHEDULE_KEY, }; use common_meta::instruction::CacheIdent; #[cfg(feature = "enterprise")] @@ -143,11 +145,17 @@ impl Default for DdlSubmitOptions { } } +/// Flow option keys the operator accepts, in the order the unknown-option error +/// lists them. +/// +/// Only the default build needs this list: it is what the unknown-option error +/// advertises, while the enterprise build passes every unknown option through to +/// meta. `max_memory` is an enterprise flow option, so it is deliberately absent +/// here - the default build rejects it as unknown and must not advertise it. #[cfg(not(feature = "enterprise"))] -const ALLOWED_FLOW_OPTIONS: [&str; 3] = [ +const ALLOWED_FLOW_OPTIONS: [&str; 2] = [ DEFER_ON_MISSING_SOURCE_KEY, FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, - FLOW_MAX_MEMORY_OPTION_KEY, ]; fn build_procedure_id_output(procedure_id: &str) -> Result { @@ -241,6 +249,8 @@ fn validate_and_normalize_flow_options( normalize_flow_bool_option(&key, &value)? } // A `ReadableSize` string such as `512MB`; validated by meta. + // Enterprise-only: the default build rejects it as unknown below. + #[cfg(feature = "enterprise")] FLOW_MAX_MEMORY_OPTION_KEY => value, #[cfg(feature = "enterprise")] _ => value, @@ -3517,6 +3527,7 @@ mod test { ); } + #[cfg(feature = "enterprise")] #[test] fn test_validate_and_normalize_flow_options_accepts_max_memory() { let options = @@ -3529,6 +3540,25 @@ mod test { ); } + /// `max_memory` is an enterprise flow option: a default build rejects it as + /// unknown, and the error must not list it among the supported options. + #[cfg(not(feature = "enterprise"))] + #[test] + fn test_validate_and_normalize_flow_options_rejects_max_memory() { + let err = validate_and_normalize_flow_options( + // Spelled out on purpose: the default build does not expose the key. + HashMap::from([("max_memory".to_string(), "512MB".to_string())]), + None, + ) + .unwrap_err(); + + assert_eq!( + "Invalid SQL, error: unknown flow option 'max_memory', supported options: \ + defer_on_missing_source, experimental_enable_incremental_read", + err.to_string() + ); + } + #[cfg(not(feature = "enterprise"))] #[test] fn test_validate_and_normalize_flow_options_unknown_option() { diff --git a/src/query/src/datafusion.rs b/src/query/src/datafusion.rs index a2f4770488f..d69a3d6fa4e 100644 --- a/src/query/src/datafusion.rs +++ b/src/query/src/datafusion.rs @@ -21,7 +21,10 @@ mod planner; use std::any::Any; use std::collections::HashMap; -use std::sync::{Arc, LazyLock, Mutex}; +use std::sync::Arc; +#[cfg(feature = "enterprise")] +use std::sync::{LazyLock, Mutex}; +#[cfg(feature = "enterprise")] use std::time::{Duration, Instant}; use async_trait::async_trait; @@ -37,6 +40,7 @@ use common_telemetry::tracing; use datafusion::catalog::TableFunction; use datafusion::dataframe::DataFrame; use datafusion::execution::SessionStateBuilder; +#[cfg(feature = "enterprise")] use datafusion::execution::memory_pool::MemoryLimit as DfMemoryLimit; use datafusion::physical_plan::ExecutionPlan; use datafusion::physical_plan::analyze::AnalyzeExec; @@ -59,6 +63,8 @@ use tracing::Span; use crate::analyze::DistAnalyzeExec; pub use crate::datafusion::planner::DfContextProviderAdapter; use crate::dist_plan::{MergeScanLogicalPlan, RemoteDynFilterReceiverInjectorRef}; +#[cfg(not(feature = "enterprise"))] +use crate::error::UnsupportedFlowMemoryBudgetSnafu; use crate::error::{ CatalogSnafu, CreateRecordBatchSnafu, MissingTableMutationHandlerSnafu, MissingTimestampColumnSnafu, QueryExecutionSnafu, Result, TableMutationSnafu, @@ -70,14 +76,14 @@ use crate::metrics::{ should_collect_region_watermark_from_query_ctx, }; use crate::optimizer::expr_depth; -use crate::options::{ - FLOW_ID, FLOW_MAX_MEMORY_BYTES, QueryMemoryPoolPolicy, ScheduledTimeExtension, -}; +#[cfg(feature = "enterprise")] +use crate::options::{FLOW_ID, QueryMemoryPoolPolicy}; +use crate::options::{FLOW_MAX_MEMORY_BYTES, ScheduledTimeExtension}; use crate::physical_wrapper::PhysicalPlanWrapperRef; use crate::planner::{DfLogicalPlanner, LogicalPlanner}; -use crate::query_engine::{ - DescribeResult, QueryEngineContext, QueryEngineState, new_flow_memory_pool, -}; +#[cfg(feature = "enterprise")] +use crate::query_engine::new_flow_memory_pool; +use crate::query_engine::{DescribeResult, QueryEngineContext, QueryEngineState}; use crate::{QueryEngine, metrics}; /// Query parallelism hint key. @@ -150,17 +156,24 @@ pub struct DatafusionQueryEngine { plugins: Plugins, } -/// Longest client-supplied extension value a log line keeps verbatim. +// The invalid-budget warning machinery below belongs to the Flow memory budget +// derivation, which only the `enterprise` feature activates. It is gated with it +// so a default build carries no unused items. +// +// Longest client-supplied extension value a log line keeps verbatim. +#[cfg(feature = "enterprise")] const MAX_LOGGED_VALUE_CHARS: usize = 64; /// How long a malformed-budget warning stays suppressed for the same Flow and /// value. This runs once per engine execution (an `InsertIntoPlan` request /// builds two query contexts), so a client that always sends the same broken /// budget would otherwise write one line per execution. +#[cfg(feature = "enterprise")] const INVALID_BUDGET_WARN_WINDOW: Duration = Duration::from_secs(60); /// Caps the number of `(flow id, value)` pairs the warning limiter remembers, /// so a client rotating keys cannot grow the map without bound. +#[cfg(feature = "enterprise")] const MAX_TRACKED_INVALID_BUDGET_WARNINGS: usize = 1024; /// Renders a client-supplied extension value for a log line, keeping at most @@ -168,6 +181,7 @@ const MAX_TRACKED_INVALID_BUDGET_WARNINGS: usize = 1024; /// /// Bounded by characters rather than bytes: the value is arbitrary client input /// and slicing on a byte offset would panic inside a multi-byte character. +#[cfg(feature = "enterprise")] fn truncate_for_log(raw: &str) -> String { match raw.char_indices().nth(MAX_LOGGED_VALUE_CHARS) { Some((cut, _)) => format!("{}...", &raw[..cut]), @@ -182,11 +196,13 @@ fn truncate_for_log(raw: &str) -> String { /// map is pruned on every decision, so its size is bounded by the distinct keys /// of one window. A window that fills up is cleared outright instead of being /// allowed to grow. +#[cfg(feature = "enterprise")] #[derive(Default)] struct WarnRateLimiter { last_emitted: Mutex>, } +#[cfg(feature = "enterprise")] impl WarnRateLimiter { /// Records `key` at `now` and reports whether the caller should log it. /// @@ -218,12 +234,14 @@ impl WarnRateLimiter { } } +#[cfg(feature = "enterprise")] static INVALID_BUDGET_WARNINGS: LazyLock = LazyLock::new(WarnRateLimiter::default); /// Reports a budget declaration that does not denote a positive byte count. /// /// The value is client-supplied, so it is truncated before it reaches the log /// and repeated identical reports are rate limited. +#[cfg(feature = "enterprise")] fn warn_invalid_flow_budget(flow_id: &str, raw: &str) { let logged_value = truncate_for_log(raw); // NUL separates the two parts, which neither part can contain in a way that @@ -598,9 +616,72 @@ impl DatafusionQueryEngine { Ok(optimized_plan) } + /// Resolves the Flow-scoped memory pool declared by the extensions of + /// `query_ctx`, or `Ok(None)` when the query declares no budget of its own. + /// + /// The derivation itself is documented on + /// [`Self::enterprise_flow_memory_scope`]. + /// + /// # Enterprise gating + /// + /// `max_memory` is an enterprise flow option, so a build without the + /// `enterprise` feature does not support it. Such a build must not silently + /// run the query on the node-wide pool either: a declared budget is refused + /// with the `UnsupportedFlowMemoryBudget` query error, so a limit that is not + /// enforced cannot be mistaken for one that is. Only a query that declares no + /// budget runs on the node pool, exactly as before the option existed. + /// + /// The mechanism around this derivation - [`QueryMemoryScope`], + /// `NestedMemoryPool`, `QueryEngineState::runtime_env_with_memory_pool` and + /// the hook below - stays compiled in every build: it is where an enterprise + /// build plugs in, and gating it would fork the runtime behaviour. + fn flow_memory_scope(&self, query_ctx: &QueryContextRef) -> Result> { + #[cfg(not(feature = "enterprise"))] + { + if query_ctx.extensions().contains_key(FLOW_MAX_MEMORY_BYTES) { + return UnsupportedFlowMemoryBudgetSnafu { + reason: common_meta::ddl::create_flow::FLOW_MAX_MEMORY_UNSUPPORTED_MSG + .to_string(), + } + .fail(); + } + Ok(None) + } + #[cfg(feature = "enterprise")] + { + self.enterprise_flow_memory_scope(query_ctx) + } + } + + /// Fallible [`QueryEngine::with_flow_memory_scope`]: returns `query_ctx` with + /// the memory scope it resolves to recorded on it, propagating the error of a + /// budget this build does not support. + /// + /// [`QueryEngine::with_flow_memory_scope`] itself cannot fail - it runs at the + /// request entry, before there is anything to report an error to - so it only + /// records the scope, while every execution resolves (and can reject) it here. + fn with_flow_memory_scope_fallible( + &self, + query_ctx: QueryContextRef, + ) -> Result { + if query_ctx.memory_scope().is_some() { + return Ok(query_ctx); + } + let Some(scope) = self.flow_memory_scope(&query_ctx)? else { + return Ok(query_ctx); + }; + let mut forked = query_ctx.fork(); + forked.set_memory_scope(scope); + Ok(Arc::new(forked)) + } + /// Builds the process-local memory scope a Flow asked for through the query - /// extensions of `query_ctx`, or returns `None` when the query declares no - /// budget of its own. + /// extensions of `query_ctx`, or returns `Ok(None)` when the query declares + /// no budget of its own. + /// + /// Only compiled with the `enterprise` feature: [`Self::flow_memory_scope`] + /// is the entry point, and it rejects a declared budget on every other + /// build. /// /// A Flow declares its budget with [`FLOW_MAX_MEMORY_BYTES`] (a decimal /// byte count) and names itself with [`FLOW_ID`]. Turning that declaration @@ -658,9 +739,15 @@ impl DatafusionQueryEngine { /// `experimental_memory_pool_policy` is consumed while the runtime /// environment is built and is not retained in [`QueryEngineState`], so it /// is not reachable from here. - fn flow_memory_scope(&self, query_ctx: &QueryContextRef) -> Option { + #[cfg(feature = "enterprise")] + fn enterprise_flow_memory_scope( + &self, + query_ctx: &QueryContextRef, + ) -> Result> { let extensions = query_ctx.extensions(); - let raw = extensions.get(FLOW_MAX_MEMORY_BYTES)?; + let Some(raw) = extensions.get(FLOW_MAX_MEMORY_BYTES) else { + return Ok(None); + }; // `-` keeps log lines parseable when the optional id is absent. let flow_id = extensions.get(FLOW_ID).map(String::as_str).unwrap_or("-"); @@ -670,7 +757,7 @@ impl DatafusionQueryEngine { // Fail open: a Flow with a malformed budget must still run, but // the operator must not believe it was ever bounded. warn_invalid_flow_budget(flow_id, raw); - return None; + return Ok(None); } }; @@ -709,10 +796,10 @@ impl DatafusionQueryEngine { requested ); - Some(QueryMemoryScope::new( + Ok(Some(QueryMemoryScope::new( label, new_flow_memory_pool(effective, QueryMemoryPoolPolicy::Greedy), - )) + ))) } } @@ -780,7 +867,10 @@ impl QueryEngine for DatafusionQueryEngine { // land on the same pool. match query_ctx.memory_scope() { Some(scope) => Some(scope.clone()), - None => self.flow_memory_scope(query_ctx), + // A budget this build does not support is reported by + // `engine_context`, which every execution goes through; this entry + // point cannot fail, so it leaves the context on the node pool. + None => self.flow_memory_scope(query_ctx).ok().flatten(), } } @@ -807,7 +897,11 @@ impl QueryEngine for DatafusionQueryEngine { // declared through query extensions, because the extension is only a // request from whoever issued the query. Queries with neither run on the // engine pool unchanged. - let query_ctx = self.with_flow_memory_scope(query_ctx); + // + // Resolution is fallible: a build without the `enterprise` feature does + // not support the `max_memory` flow option, so a declared budget fails + // this query here instead of running it unbudgeted. + let query_ctx = self.with_flow_memory_scope_fallible(query_ctx)?; if let Some(pool) = query_ctx.memory_scope().map(QueryMemoryScope::pool) { let session_id = state.session_id().to_string(); let runtime_env = self.state.runtime_env_with_memory_pool(pool); @@ -982,7 +1076,9 @@ mod tests { use common_recordbatch::{ EmptyRecordBatchStream, RecordBatch, SendableRecordBatchStream, util, }; - use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool}; + #[cfg(feature = "enterprise")] + use datafusion::execution::memory_pool::MemoryPool; + use datafusion::execution::memory_pool::{MemoryConsumer, MemoryLimit as DfMemoryLimit}; use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType}; use datafusion::physical_plan::expressions::PhysicalSortExpr; use datafusion::physical_plan::joins::{HashJoinExec, JoinOn, PartitionMode}; @@ -1005,10 +1101,10 @@ mod tests { use table::table::scan::RegionScanExec; use super::*; - use crate::options::QueryOptions; + use crate::options::{FLOW_ID, QueryMemoryPoolPolicy, QueryOptions}; use crate::parser::{QueryLanguageParser, QueryStatement}; use crate::part_sort::PartSortExec; - use crate::query_engine::{QueryEngineFactory, QueryEngineRef}; + use crate::query_engine::{QueryEngineFactory, QueryEngineRef, new_flow_memory_pool}; #[derive(Debug)] struct RecordingScanner { @@ -2036,6 +2132,7 @@ mod tests { } /// The process-wide pool every query of the engine is charged to. + #[cfg(feature = "enterprise")] fn node_memory_pool(engine: &QueryEngineRef) -> Arc { engine .engine_state() @@ -2045,6 +2142,52 @@ mod tests { .clone() } + /// `max_memory` is an enterprise flow option, so a default build refuses a + /// query that declares a budget instead of silently running it on the node + /// pool: a limit that is not enforced must not look like one that is. + #[cfg(not(feature = "enterprise"))] + #[test] + fn engine_context_rejects_flow_memory_budget_on_default_build() { + let engine = query_engine_with_node_memory_pool(8192); + let query_ctx = Arc::new( + QueryContextBuilder::default() + .set_extension(FLOW_MAX_MEMORY_BYTES.to_string(), "4096".to_string()) + .set_extension(FLOW_ID.to_string(), "42".to_string()) + .build(), + ); + + let err = engine.engine_context(query_ctx.clone()).unwrap_err(); + assert!( + matches!( + &err, + crate::error::Error::UnsupportedFlowMemoryBudget { .. } + ), + "unexpected error: {err:?}" + ); + assert_eq!( + "flow option `max_memory` requires the enterprise edition", + err.to_string() + ); + + // The caller's shared context is left alone and the request-entry hook + // stays a no-op: the error is reported by the execution itself. + assert!(query_ctx.memory_scope().is_none()); + let scoped = engine.with_flow_memory_scope(query_ctx.clone()); + assert!(Arc::ptr_eq(&scoped, &query_ctx)); + + // The rejected declaration never resizes the node pool. + assert!(matches!( + engine + .engine_state() + .session_state() + .runtime_env() + .memory_pool + .memory_limit(), + DfMemoryLimit::Finite(8192) + )); + } + + #[cfg(feature = "enterprise")] #[test] fn engine_context_installs_flow_memory_pool_from_extension() { let engine = query_engine_with_node_memory_pool(8192); @@ -2104,6 +2247,7 @@ mod tests { /// `engine_context` again, so the resolved scope must be recorded on the /// context they share - otherwise every one of them would derive a fresh, /// independent full budget for the same request. + #[cfg(feature = "enterprise")] #[test] fn engine_context_shares_one_flow_budget_across_re_entries() { let engine = query_engine_with_node_memory_pool(8192); @@ -2157,6 +2301,7 @@ mod tests { /// A context captured before execution - as the computed semantic-graph /// tables capture it during table lookup - already carries the scope, so the /// engine contexts built from it later all use one and the same pool. + #[cfg(feature = "enterprise")] #[test] fn captured_context_keeps_one_flow_pool_before_execution() { let engine = query_engine_with_node_memory_pool(8192); @@ -2180,6 +2325,7 @@ mod tests { } } + #[cfg(feature = "enterprise")] #[test] fn invalid_flow_budget_warning_is_truncated_and_rate_limited() { // A client-supplied value never reaches the log verbatim. @@ -2220,6 +2366,7 @@ mod tests { assert!(tracked <= MAX_TRACKED_INVALID_BUDGET_WARNINGS, "{tracked}"); } + #[cfg(feature = "enterprise")] #[test] fn engine_context_clamps_flow_memory_pool_to_node_pool() { let engine = query_engine_with_node_memory_pool(1024); @@ -2276,6 +2423,7 @@ mod tests { assert_eq!(7, ctx.state().config().options().optimizer.max_passes); } + #[cfg(feature = "enterprise")] #[test] fn engine_context_flow_pool_cannot_exceed_the_node_pool() { let engine = query_engine_with_node_memory_pool(4096); @@ -2348,6 +2496,7 @@ mod tests { assert_eq!(2048, explicit.reserved()); } + #[cfg(feature = "enterprise")] #[tokio::test] async fn test_invalid_flow_memory_budget_keeps_query_on_node_pool() { let engine = query_engine_with_node_memory_pool(4 * 1024 * 1024); diff --git a/src/query/src/error.rs b/src/query/src/error.rs index 919ef67b94f..46d35d4e778 100644 --- a/src/query/src/error.rs +++ b/src/query/src/error.rs @@ -382,6 +382,16 @@ pub enum Error { location: Location, }, + /// A `Flow` declared a memory budget that this build does not support: the + /// `max_memory` flow option is an enterprise feature, so the query is refused + /// instead of silently running without the limit it asked for. + #[snafu(display("{}", reason))] + UnsupportedFlowMemoryBudget { + reason: String, + #[snafu(implicit)] + location: Location, + }, + #[snafu(transparent)] Datatypes { source: datatypes::error::Error, @@ -417,6 +427,8 @@ impl ErrorExt for Error { | InvalidQueryContextExtension { .. } | ConflictingSnapshotSequence { .. } => StatusCode::InvalidArguments, + UnsupportedFlowMemoryBudget { .. } => StatusCode::Unsupported, + BuildBackend { source, .. } => source.status_code(), ListObjects { .. } => StatusCode::StorageUnavailable, diff --git a/tests/cases/standalone/common/flow/show_create_flow.result b/tests/cases/standalone/common/flow/show_create_flow.result index b7cbbb0a9c5..d451c552ec3 100644 --- a/tests/cases/standalone/common/flow/show_create_flow.result +++ b/tests/cases/standalone/common/flow/show_create_flow.result @@ -498,7 +498,7 @@ SINK TO out_num_cnt_show WITH (access_key_id = [true]) AS SELECT number AS n1 FROM numbers_input_show where number > 10; -Error: 1004(InvalidArguments), Invalid SQL, error: unknown flow option 'access_key_id', supported options: defer_on_missing_source, experimental_enable_incremental_read, max_memory +Error: 1004(InvalidArguments), Invalid SQL, error: unknown flow option 'access_key_id', supported options: defer_on_missing_source, experimental_enable_incremental_read DROP FLOW filter_numbers_show;