Merge branch 'feat/flow-memory-option' into feat/flow-memory-scope

This commit is contained in:
discord9
2026-11-05 17:42:50 +08:00
9 changed files with 593 additions and 14 deletions
+47 -2
View File
@@ -16,12 +16,14 @@ mod metadata;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::str::FromStr;
use api::v1::ExpireAfter;
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};
use common_base::readable_size::ReadableSize;
use common_catalog::format_full_flow_name;
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
use common_procedure::{
@@ -466,6 +468,14 @@ pub fn get_flow_type_from_options(flow_task: &CreateFlowTask) -> Result<FlowType
/// The flow option key for creating pending flow metadata when source tables do not exist.
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
/// `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";
/// 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
@@ -556,11 +566,12 @@ 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 => {}
unknown => {
return InvalidFlowOptionSnafu {
err_msg: format!(
"unknown flow option '{unknown}', supported options: {DEFER_ON_MISSING_SOURCE_KEY}, {FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY}"
"unknown flow option '{unknown}', supported options: {DEFER_ON_MISSING_SOURCE_KEY}, {FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY}, {FLOW_MAX_MEMORY_OPTION_KEY}"
),
}
.fail();
@@ -583,8 +594,42 @@ pub fn validate_flow_options(flow_task: &CreateFlowTask) -> Result<()> {
})?;
}
if let Some(value) = flow_task.flow_options.get(FLOW_MAX_MEMORY_OPTION_KEY) {
let bytes = ReadableSize::from_str(value).map_err(|_| {
InvalidFlowOptionSnafu {
err_msg: format!(
"Invalid flow option '{FLOW_MAX_MEMORY_OPTION_KEY}': {value}, expect a size like '512MB'"
),
}
.build()
})?;
if bytes.as_bytes() == 0 {
return InvalidFlowOptionSnafu {
err_msg: format!(
"Invalid flow option '{FLOW_MAX_MEMORY_OPTION_KEY}': {value}, the memory budget must be positive"
),
}
.fail();
}
}
defer_on_missing_source(flow_task)?;
get_flow_type_from_options(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)
{
return InvalidFlowOptionSnafu {
err_msg: format!(
"flow option '{FLOW_MAX_MEMORY_OPTION_KEY}' is only supported for batching flows"
),
}
.fail();
}
Ok(())
}
+88 -3
View File
@@ -27,8 +27,8 @@ use table::table_name::TableName;
use crate::ddl::DdlContext;
use crate::ddl::create_flow::{
CreateFlowData, CreateFlowProcedure, CreateFlowState, DEFER_ON_MISSING_SOURCE_KEY,
FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType, ceil_to_whole_sec,
defer_on_missing_source, effective_eval_schedule_from_flow_info,
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,
resolve_schedule_defaults_into_task, validate_flow_options,
};
use crate::ddl::test_util::create_table::test_create_table_task;
@@ -342,12 +342,97 @@ 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());
assert_eq!(
"Invalid SQL, error: unknown flow option 'foo', supported options: defer_on_missing_source, experimental_enable_incremental_read",
"Invalid SQL, error: unknown flow option 'foo', supported options: defer_on_missing_source, experimental_enable_incremental_read, max_memory",
err.output_msg()
);
assert!(!err.output_msg().contains("sensitive-value"));
}
#[test]
fn test_validate_flow_options_accepts_max_memory() {
for value in ["512MB", "1073741824", "1GiB"] {
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(FLOW_MAX_MEMORY_OPTION_KEY.to_string(), value.to_string());
validate_flow_options(&task).unwrap();
}
}
#[test]
fn test_validate_flow_options_rejects_invalid_max_memory() {
for value in ["not-a-size", "0", "0B"] {
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(FLOW_MAX_MEMORY_OPTION_KEY.to_string(), value.to_string());
let err = validate_flow_options(&task).unwrap_err();
assert_eq!(StatusCode::InvalidArguments, err.status_code());
assert!(
err.output_msg()
.contains(&format!("Invalid flow option 'max_memory': {value}")),
"unexpected error for {value}: {err}"
);
}
}
#[test]
fn test_validate_flow_options_rejects_max_memory_for_streaming_flows() {
let mut streaming = test_create_flow_task(
"my_flow",
vec![],
TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "my_sink_table"),
false,
);
streaming.flow_options.insert(
FlowType::FLOW_TYPE_KEY.to_string(),
FlowType::STREAMING.to_string(),
);
streaming
.flow_options
.insert(FLOW_MAX_MEMORY_OPTION_KEY.to_string(), "512MB".to_string());
let err = validate_flow_options(&streaming).unwrap_err();
assert_eq!(StatusCode::InvalidArguments, err.status_code());
assert!(
err.output_msg()
.contains("flow option 'max_memory' is only supported for batching flows"),
"unexpected error: {err}"
);
// The same option on a batching flow (explicit or default) stays accepted,
// with or without the `max_memory` option itself.
for flow_type in [Some(FlowType::BATCHING), None] {
let mut batching = test_create_flow_task(
"my_flow",
vec![],
TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "my_sink_table"),
false,
);
if let Some(flow_type) = flow_type {
batching
.flow_options
.insert(FlowType::FLOW_TYPE_KEY.to_string(), flow_type.to_string());
}
validate_flow_options(&batching).unwrap();
batching
.flow_options
.insert(FLOW_MAX_MEMORY_OPTION_KEY.to_string(), "512MB".to_string());
validate_flow_options(&batching).unwrap();
}
}
#[test]
fn test_validate_flow_options_rejects_schedule_and_internal_keys_as_unknown() {
for key in [
+81 -1
View File
@@ -15,15 +15,17 @@
//! Batching mode engine
use std::collections::{BTreeMap, HashMap, HashSet};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use api::v1::flow::DirtyWindowRequests;
use catalog::CatalogManagerRef;
use common_base::readable_size::ReadableSize;
use common_error::ext::BoxedError;
use common_meta::ddl::create_flow::{
FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY,
FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE, FlowType,
FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE, FLOW_MAX_MEMORY_OPTION_KEY, FlowType,
};
use common_meta::key::TableMetadataManagerRef;
use common_meta::key::flow::FlowMetadataManagerRef;
@@ -513,6 +515,39 @@ impl BatchingEngine {
Ok(Arc::new(batch_opts))
}
/// Parse the per-flow `max_memory` option into the resolved byte budget
/// carried with every query this flow issues.
///
/// 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.
pub(crate) fn max_memory_bytes_for_flow_options(
flow_options: &HashMap<String, String>,
) -> Result<Option<u64>, 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()
}
fn table_options_enable_append_mode(extra_options: &HashMap<String, String>) -> bool {
extra_options
.get(APPEND_MODE_KEY)
@@ -630,6 +665,9 @@ impl BatchingEngine {
.is_some_and(|value| value == FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_SEQUENCE_RANGE);
let batch_opts =
self.batch_opts_for_flow_options(&flow_options, exact_sequence_range_required)?;
// Resolved from this create request's flow options only, so an OR
// REPLACE picks up the new value and never inherits the old task's.
let max_memory_bytes = Self::max_memory_bytes_for_flow_options(&flow_options)?;
let mut source_table_names = Vec::with_capacity(2);
for src_id in source_table_ids {
@@ -730,6 +768,7 @@ impl BatchingEngine {
batch_opts,
flow_eval_interval: eval_interval.map(|secs| Duration::from_secs(secs as u64)),
eval_schedule,
max_memory_bytes,
};
let task = BatchingTask::try_new_with_exact_sequence_range_required(
@@ -1127,6 +1166,46 @@ 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.
#[test]
fn test_max_memory_bytes_for_flow_options() {
assert_eq!(
BatchingEngine::max_memory_bytes_for_flow_options(&HashMap::new()).unwrap(),
None
);
for (value, expected) in [
("512MB", 536_870_912_u64),
("512MiB", 536_870_912),
("1073741824", 1_073_741_824),
("1GB", 1_073_741_824),
] {
assert_eq!(
BatchingEngine::max_memory_bytes_for_flow_options(&HashMap::from([(
FLOW_MAX_MEMORY_OPTION_KEY.to_string(),
value.to_string(),
)]))
.unwrap(),
Some(expected),
"unexpected byte budget for {value}"
);
}
for value in ["not-a-size", "0", "0B", "-1MB"] {
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::InvalidQuery { .. }),
"unexpected error for {value}: {err:?}"
);
}
}
async fn new_test_engine() -> BatchingEngine {
let kv_backend = Arc::new(MemoryKvBackend::new());
let table_meta = Arc::new(TableMetadataManager::new(kv_backend.clone()));
@@ -1718,6 +1797,7 @@ GROUP BY l.number, time_window
batch_opts: Arc::new(BatchingModeOptions::default()),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
+128 -1
View File
@@ -364,11 +364,31 @@ impl FrontendClient {
}
/// Execute a SQL statement on the frontend.
pub async fn sql(&self, catalog: &str, schema: &str, sql: &str) -> Result<Output, Error> {
///
/// `extensions` are forwarded to the executing frontend exactly like
/// `query_with_terminal_metrics` does: as query context extensions in
/// standalone mode and as Flow extensions on the Flight request in
/// distributed mode.
///
/// A flow-owned SQL statement must pass the budget extensions of the flow
/// that issues it (`flow.max_memory_bytes` together with `flow.flow_id`, as
/// returned by `BatchingTask::memory_budget_extensions`); a statement that
/// omits them while the flow declares a `max_memory` budget escapes that
/// budget and can run unbounded. Callers that issue a statement not owned by
/// a flow pass an empty slice.
pub async fn sql(
&self,
catalog: &str,
schema: &str,
sql: &str,
extensions: &[(&str, &str)],
) -> Result<Output, Error> {
match self {
FrontendClient::Distributed { .. } => {
let db = self.get_random_active_frontend(catalog, schema).await?;
db.database
.flight_request()
.with_flow_extensions(extensions)
.sql(sql)
.await
.map_err(BoxedError::new)
@@ -377,9 +397,15 @@ impl FrontendClient {
FrontendClient::Standalone {
database_client, ..
} => {
let extensions = HashMap::from_iter(
extensions
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string())),
);
let ctx = QueryContextBuilder::default()
.current_catalog(catalog.to_string())
.current_schema(schema.to_string())
.extensions(extensions)
.build();
let ctx = Arc::new(ctx);
{
@@ -890,6 +916,12 @@ mod tests {
#[derive(Debug)]
struct ExtensionAwareHandler;
/// Records the extensions of every standalone query context it receives.
struct CapturingExtensionHandler {
extensions: Arc<Mutex<HashMap<String, String>>>,
calls: Arc<AtomicUsize>,
}
#[derive(Debug)]
struct SnapshotBindingHandler;
@@ -980,6 +1012,30 @@ mod tests {
}
}
#[async_trait::async_trait]
impl GrpcQueryHandlerWithBoxedError for CapturingExtensionHandler {
async fn do_query(
&self,
_query: Request,
ctx: QueryContextRef,
) -> std::result::Result<Output, BoxedError> {
self.calls.fetch_add(1, Ordering::SeqCst);
*self.extensions.lock().unwrap() = ctx.extensions();
Ok(Output::new_with_affected_rows(0))
}
}
/// The sorted `flow.*` extension keys of a query context.
fn flow_extension_keys(extensions: &HashMap<String, String>) -> Vec<&str> {
let mut keys = extensions
.keys()
.filter(|key| key.starts_with("flow."))
.map(String::as_str)
.collect::<Vec<_>>();
keys.sort_unstable();
keys
}
#[async_trait::async_trait]
impl GrpcQueryHandlerWithBoxedError for SnapshotBindingHandler {
async fn do_query(
@@ -1152,6 +1208,77 @@ mod tests {
assert!(peer_desc.is_none());
}
#[tokio::test]
async fn test_sql_forwards_given_extensions_in_standalone_mode() {
let extensions = Arc::new(Mutex::new(HashMap::new()));
let calls = Arc::new(AtomicUsize::new(0));
let handler: Arc<dyn GrpcQueryHandlerWithBoxedError> =
Arc::new(CapturingExtensionHandler {
extensions: extensions.clone(),
calls: calls.clone(),
});
let client =
FrontendClient::from_grpc_handler(Arc::downgrade(&handler), QueryOptions::default());
client
.sql(
"greptime",
"public",
"select 1",
&[
(query::options::FLOW_MAX_MEMORY_BYTES, "536870912"),
(query::options::FLOW_ID, "7"),
],
)
.await
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
let captured = extensions.lock().unwrap();
assert_eq!(
captured
.get(query::options::FLOW_MAX_MEMORY_BYTES)
.map(String::as_str),
Some("536870912")
);
assert_eq!(
captured.get(query::options::FLOW_ID).map(String::as_str),
Some("7")
);
// Nothing else is invented for the flow-owned statement. The query
// context adds unrelated internal extensions (e.g. `remote_query_id`),
// so only the flow-owned keys are inspected here.
assert_eq!(
flow_extension_keys(&captured),
["flow.flow_id", "flow.max_memory_bytes"]
);
}
#[tokio::test]
async fn test_sql_without_extensions_forwards_no_flow_extension_in_standalone_mode() {
let extensions = Arc::new(Mutex::new(HashMap::new()));
let calls = Arc::new(AtomicUsize::new(0));
let handler: Arc<dyn GrpcQueryHandlerWithBoxedError> =
Arc::new(CapturingExtensionHandler {
extensions: extensions.clone(),
calls: calls.clone(),
});
let client =
FrontendClient::from_grpc_handler(Arc::downgrade(&handler), QueryOptions::default());
client
.sql("greptime", "public", "select 1", &[])
.await
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
let captured = extensions.lock().unwrap();
assert!(
flow_extension_keys(&captured).is_empty(),
"a caller without extensions must not forward any flow extension: {captured:?}"
);
}
#[tokio::test]
async fn test_query_with_terminal_metrics_tracks_watermark_in_standalone_mode() {
let handler: Arc<dyn GrpcQueryHandlerWithBoxedError> = Arc::new(MetricsHandler);
+55 -2
View File
@@ -163,6 +163,10 @@ pub struct TaskConfig {
pub flow_eval_interval: Option<Duration>,
/// Typed schedule configuration, pre-parsed at task creation time.
pub eval_schedule: Option<EvalSchedule>,
/// 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.
pub max_memory_bytes: Option<u64>,
}
fn determine_query_type(query: &str, query_ctx: &QueryContextRef) -> Result<QueryType, Error> {
@@ -316,6 +320,9 @@ pub struct TaskArgs<'a> {
pub flow_eval_interval: Option<Duration>,
/// Typed schedule configuration pre-parsed from `CreateFlowArgs`.
pub eval_schedule: Option<EvalSchedule>,
/// Resolved per-flow memory budget in bytes, parsed from the `max_memory`
/// flow option by the engine.
pub max_memory_bytes: Option<u64>,
}
pub struct PlanInfo {
@@ -416,6 +423,7 @@ impl BatchingTask {
batch_opts,
flow_eval_interval,
eval_schedule,
max_memory_bytes,
}: TaskArgs<'_>,
exact_sequence_range_required: bool,
) -> Result<Self, Error> {
@@ -446,6 +454,7 @@ impl BatchingTask {
batch_opts,
flow_eval_interval,
eval_schedule,
max_memory_bytes,
}),
state: Arc::new(RwLock::new(state)),
execution_lock: Arc::new(Mutex::new(())),
@@ -476,7 +485,8 @@ impl BatchingTask {
}
/// Collect flow-related extensions from the task's query context that should be
/// forwarded to the frontend (e.g. scheduled time).
/// forwarded to the frontend (e.g. scheduled time), plus the fixed per-flow
/// memory budget resolved at creation time.
fn frontend_extensions(&self) -> HashMap<String, String> {
let ctx = self.state.read().unwrap();
let all = ctx.query_ctx.extensions();
@@ -489,9 +499,42 @@ impl BatchingTask {
v.clone(),
);
}
flow_exts.extend(self.memory_budget_extensions());
flow_exts
}
/// The per-flow memory budget extensions that every Flow-owned query
/// executed on a frontend must carry: `flow.max_memory_bytes` and the
/// `flow.flow_id` identity the budget is keyed on.
///
/// The budget is part of the task config, not the mutable query context, so
/// the extensions are only returned when the flow was created with an
/// explicit `max_memory` option. The flow identity is returned together with
/// it so the execution side can key the budget on the flow, and is
/// deliberately absent otherwise: flows without the option keep sending
/// exactly the extensions they sent before.
///
/// Every Flow-owned query path must merge these in (see
/// `frontend_extensions` and [`Self::capture_recovery_windows_since`], plus
/// flow-owned statements issued through `FrontendClient::sql`); a path that
/// drops them while a budget is configured escapes the budget and can run
/// unbounded.
pub fn memory_budget_extensions(&self) -> Vec<(String, String)> {
let Some(max_memory_bytes) = self.config.max_memory_bytes else {
return Vec::new();
};
vec![
(
query::options::FLOW_MAX_MEMORY_BYTES.to_string(),
max_memory_bytes.to_string(),
),
(
query::options::FLOW_ID.to_string(),
self.config.flow_id.to_string(),
),
]
}
/// mark time window range (now - expire_after, now) as dirty (or (0, now) if expire_after not set)
///
/// useful for flush_flow to flush dirty time windows range
@@ -848,11 +891,21 @@ impl BatchingTask {
}
.build()
})?;
let extensions = [
let fixed_extensions = [
(FLOW_RETURN_REGION_SEQ, "true"),
(FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE),
(FLOW_INCREMENTAL_AFTER_SEQS, lower_json.as_str()),
];
// This is a Flow-owned query too: it must carry the per-flow memory
// budget extensions, otherwise a bounded flow could read unbounded
// regions through recovery window capture.
let budget_extensions = self.memory_budget_extensions();
let mut extensions: Vec<(&str, &str)> = fixed_extensions.to_vec();
extensions.extend(
budget_extensions
.iter()
.map(|(key, value)| (key.as_str(), value.as_str())),
);
let mut peer_desc = None;
let result = frontend_client
.query_with_terminal_metrics(
+167 -2
View File
@@ -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;
use common_meta::ddl::create_flow::FLOW_MAX_MEMORY_OPTION_KEY;
use common_query::Output;
use common_recordbatch::RecordBatch;
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
@@ -38,8 +39,9 @@ use datatypes::vectors::{
use pretty_assertions::assert_eq;
use prost::Message;
use query::options::{
FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY,
FLOW_SCHEDULED_TIME_MILLIS, FLOW_SINK_TABLE_ID, QueryOptions,
FLOW_ID, FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE,
FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY, FLOW_MAX_MEMORY_BYTES, FLOW_SCHEDULED_TIME_MILLIS,
FLOW_SINK_TABLE_ID, QueryOptions,
};
use session::context::QueryContext;
use snafu::ResultExt;
@@ -53,6 +55,7 @@ use crate::batching_mode::checkpoint::{
CHECKPOINT_DECISION_ADVANCE, CHECKPOINT_DECISION_FALLBACK, CHECKPOINT_REASON_NONE,
FlowCheckpointDecision, FlowQueryFallbackReason,
};
use crate::batching_mode::engine::BatchingEngine;
use crate::batching_mode::eval_schedule::{FlowMissedTickPolicy, FlowScheduleConfig};
use crate::batching_mode::state::CheckpointMode;
use crate::batching_mode::time_window::find_time_window_expr;
@@ -559,6 +562,7 @@ async fn new_test_task_engine_and_plan_with_query_and_opts_and_required(
batch_opts,
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
},
exact_sequence_range_required,
)
@@ -633,6 +637,7 @@ async fn test_non_aggregate_scheduled_sql_honors_eval_offset_phase() {
batch_opts: Arc::new(BatchingModeOptions::default()),
flow_eval_interval: Some(Duration::from_secs(3600)),
eval_schedule: Some(schedule),
max_memory_bytes: None,
})
.unwrap();
@@ -758,6 +763,7 @@ async fn new_time_window_test_task_with_query(query: &str) -> TestTaskParts {
batch_opts: incremental_batch_opts(),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
@@ -1430,6 +1436,67 @@ impl crate::batching_mode::frontend_client::GrpcQueryHandlerWithBoxedError
}
}
/// Asserts that recovery window capture carries the fixed sequence-range
/// extensions plus exactly the per-flow memory budget extensions it expects:
/// `flow.max_memory_bytes` and `flow.flow_id` when the flow declares
/// `max_memory`, and neither of them otherwise.
struct RecoveryBudgetCaptureHandler {
lower: String,
max_memory_bytes: Option<u64>,
flow_id: crate::FlowId,
}
#[async_trait::async_trait]
impl crate::batching_mode::frontend_client::GrpcQueryHandlerWithBoxedError
for RecoveryBudgetCaptureHandler
{
async fn do_query(
&self,
query: api::v1::greptime_request::Request,
ctx: QueryContextRef,
) -> std::result::Result<Output, BoxedError> {
// The three fixed extensions are unchanged.
assert_eq!(ctx.extension(FLOW_INCREMENTAL_MODE), Some("sequence_range"));
assert_eq!(
ctx.extension(FLOW_INCREMENTAL_AFTER_SEQS),
Some(self.lower.as_str())
);
assert_eq!(
ctx.extension(query::options::FLOW_RETURN_REGION_SEQ),
Some("true")
);
match self.max_memory_bytes {
Some(max_memory_bytes) => {
let expected_max_memory = max_memory_bytes.to_string();
let expected_flow_id = self.flow_id.to_string();
assert_eq!(
ctx.extension(FLOW_MAX_MEMORY_BYTES),
Some(expected_max_memory.as_str())
);
assert_eq!(ctx.extension(FLOW_ID), Some(expected_flow_id.as_str()));
}
None => {
assert_eq!(ctx.extension(FLOW_MAX_MEMORY_BYTES), None);
assert_eq!(ctx.extension(FLOW_ID), None);
}
}
let api::v1::greptime_request::Request::Query(request) = query else {
panic!("recovery capture must issue a query request");
};
let Some(api::v1::query_request::Query::LogicalPlan(_plan)) = request.query else {
panic!("recovery capture must issue a logical plan read");
};
// Terminal proof that the requested bounds are already complete.
Ok(recovery_stream_output(
vec![],
Some(vec![(1, Some(10))]),
false,
))
}
}
fn recovery_timestamp_schema() -> Arc<Schema> {
Arc::new(Schema::new(vec![
ColumnSchema::new("ts", CDT::timestamp_millisecond_datatype(), true).with_time_index(true),
@@ -1665,6 +1732,7 @@ async fn test_scheduled_time_ctx_restored_on_no_dirty_windows() {
batch_opts: incremental_batch_opts(),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
@@ -1710,6 +1778,52 @@ async fn test_scheduled_time_ctx_restored_on_no_dirty_windows() {
);
}
/// The resolved per-flow memory budget (`max_memory` flow option) and the flow
/// identity are forwarded to the frontend as the `flow.max_memory_bytes` /
/// `flow.flow_id` extensions, and both are absent when the flow was created
/// without that option.
#[tokio::test]
async fn test_frontend_extensions_carry_max_memory_bytes() {
let TestTaskParts { mut task, .. } = new_test_task_engine_and_plan_with_query(
"SELECT number, ts FROM numbers_with_ts",
"max_memory_sink",
)
.await;
// No `max_memory` option: nothing memory-related is forwarded, not even the
// flow identity.
assert_eq!(task.config.max_memory_bytes, None);
let extensions = task.frontend_extensions();
assert!(
!extensions.contains_key(FLOW_MAX_MEMORY_BYTES),
"flow.max_memory_bytes must not be forwarded without the max_memory option"
);
assert!(
!extensions.contains_key(FLOW_ID),
"flow.flow_id must not be forwarded without the max_memory option"
);
// `max_memory = '512MB'` as resolved by the batching engine.
let max_memory_bytes = BatchingEngine::max_memory_bytes_for_flow_options(&HashMap::from([(
FLOW_MAX_MEMORY_OPTION_KEY.to_string(),
"512MB".to_string(),
)]))
.unwrap();
assert_eq!(max_memory_bytes, Some(536_870_912));
Arc::get_mut(&mut task.config).unwrap().max_memory_bytes = max_memory_bytes;
let expected_flow_id = task.config.flow_id.to_string();
let extensions = task.frontend_extensions();
assert_eq!(
extensions.get(FLOW_MAX_MEMORY_BYTES).map(String::as_str),
Some("536870912")
);
assert_eq!(
extensions.get(FLOW_ID).map(String::as_str),
Some(expected_flow_id.as_str())
);
}
#[tokio::test]
async fn test_scheduled_time_now_is_bound_to_selected_attempt() {
let query_engine = create_test_query_engine();
@@ -1743,6 +1857,7 @@ async fn test_scheduled_time_now_is_bound_to_selected_attempt() {
batch_opts: incremental_batch_opts(),
flow_eval_interval: Some(Duration::from_secs(1)),
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
@@ -1960,6 +2075,52 @@ async fn test_capture_recovery_windows_since_uses_supplied_retention_lower() {
assert_eq!(*handler.expiry_lower.lock().unwrap(), Some(retention_lower));
}
/// Recovery window capture is a Flow-owned query: when the flow declares
/// `max_memory` it must carry `flow.max_memory_bytes` and `flow.flow_id`, and
/// when it does not, the extension set must stay exactly as before.
#[tokio::test]
async fn test_capture_recovery_windows_carries_max_memory_budget_extensions() {
for max_memory_bytes in [Some(536_870_912_u64), None] {
let TestTaskParts {
mut task,
query_engine,
..
} = new_time_window_test_task_with_query(
"SELECT max(number) AS output_value, date_bin(INTERVAL '5 second', ts) AS output_window FROM numbers_with_ts WHERE number = 42 GROUP BY output_window",
)
.await;
configure_source_capability(&query_engine, "mito", true).await;
let flow_id = task.config.flow_id;
Arc::get_mut(&mut task.config)
.expect("test task config should be uniquely owned")
.max_memory_bytes = max_memory_bytes;
let lower = BTreeMap::from([(1, 10)]);
let handler = Arc::new(RecoveryBudgetCaptureHandler {
lower: serde_json::to_string(&lower).unwrap(),
max_memory_bytes,
flow_id,
});
let frontend = FrontendClient::from_grpc_handler(
Arc::downgrade(
&(handler.clone()
as Arc<
dyn crate::batching_mode::frontend_client::GrpcQueryHandlerWithBoxedError,
>),
),
QueryOptions::default(),
);
let (high, windows) = task
.capture_recovery_windows_since(&query_engine, &frontend, &lower, None)
.await
.unwrap();
assert_eq!(high, lower);
assert!(windows.is_empty());
}
}
#[tokio::test]
async fn test_capture_recovery_windows_terminal_proof_cases_leave_state_unchanged() {
struct Case {
@@ -3749,6 +3910,7 @@ async fn test_exact_required_unsupported_plan_keeps_exact_retry_state() {
batch_opts: incremental_batch_opts(),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
},
true,
)
@@ -3841,6 +4003,7 @@ async fn test_prepare_plan_for_incremental_disables_on_non_aggregate() {
batch_opts: incremental_batch_opts(),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
@@ -3922,6 +4085,7 @@ async fn test_unsafe_incremental_plan_skip_restores_dirty_without_query() {
batch_opts: incremental_batch_opts(),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
@@ -4012,6 +4176,7 @@ async fn test_prepare_plan_for_incremental_group_by_without_merge_columns_uses_o
batch_opts: incremental_batch_opts(),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
+1
View File
@@ -934,6 +934,7 @@ async fn test_validate_sink_table_schema_rejects_existing_sink_missing_flow_colu
batch_opts: Arc::new(BatchingModeOptions::default()),
flow_eval_interval: None,
eval_schedule: None,
max_memory_bytes: None,
})
.unwrap();
+18 -3
View File
@@ -41,8 +41,8 @@ use common_error::ext::BoxedError;
use common_meta::cache_invalidator::CacheInvalidatorRef;
use common_meta::cache_invalidator::Context;
use common_meta::ddl::create_flow::{
DEFER_ON_MISSING_SOURCE_KEY, FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType,
INTERNAL_EVAL_OFFSET_KEY, INTERNAL_EVAL_SCHEDULE_KEY,
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,
};
use common_meta::instruction::CacheIdent;
#[cfg(feature = "enterprise")]
@@ -144,9 +144,10 @@ impl Default for DdlSubmitOptions {
}
#[cfg(not(feature = "enterprise"))]
const ALLOWED_FLOW_OPTIONS: [&str; 2] = [
const ALLOWED_FLOW_OPTIONS: [&str; 3] = [
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<Output> {
@@ -239,6 +240,8 @@ fn validate_and_normalize_flow_options(
DEFER_ON_MISSING_SOURCE_KEY | FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY => {
normalize_flow_bool_option(&key, &value)?
}
// A `ReadableSize` string such as `512MB`; validated by meta.
FLOW_MAX_MEMORY_OPTION_KEY => value,
#[cfg(feature = "enterprise")]
_ => value,
#[cfg(not(feature = "enterprise"))]
@@ -3514,6 +3517,18 @@ mod test {
);
}
#[test]
fn test_validate_and_normalize_flow_options_accepts_max_memory() {
let options =
HashMap::from([(FLOW_MAX_MEMORY_OPTION_KEY.to_string(), "512MB".to_string())]);
// The size string is passed through unchanged; meta validates it.
assert_eq!(
validate_and_normalize_flow_options(options.clone(), None).unwrap(),
options
);
}
#[cfg(not(feature = "enterprise"))]
#[test]
fn test_validate_and_normalize_flow_options_unknown_option() {
+8
View File
@@ -50,6 +50,14 @@ pub const FLOW_ID: &str = "flow.flow_id";
/// Query planning, SQL/TQL parsing, range-select rewrite and DataFusion
/// execution read this extension so `now()` is stable for the whole attempt.
pub const FLOW_SCHEDULED_TIME_MILLIS: &str = "flow.scheduled_time_millis";
/// Resolved per-flow memory budget in decimal bytes, carried with a flow's own
/// query. The value comes from the flow's `max_memory` option and is only
/// transported here; it is interpreted and enforced by the execution side.
pub const FLOW_MAX_MEMORY_BYTES: &str = "flow.max_memory_bytes";
/// Identity of the flow that issues the query, as a decimal flow id. Lets the
/// execution side key a per-flow memory budget on the flow rather than on the
/// individual query. Forwarded together with [`FLOW_MAX_MEMORY_BYTES`].
pub const FLOW_ID: &str = "flow.flow_id";
/// Enable by default, set to false to explicitly disable.
pub const QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN: &str =
"query.enable_remote_dynamic_filter_pushdown";