mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
fix(frontend): reject a declared flow budget at the request entry
The entry-level scope resolution discarded the edition error and relied on engine_context to reject the request, but not every statement reaches an engine context: a literal INSERT ... VALUES takes the can_extract_values fast path and never builds one, so the write proceeded instead of returning the enterprise-required error. Resolve the scope with the fallible variant at both frontend entries and propagate the error before dispatch, keeping engine_context as the backstop and flow_memory_scope_for as the infallible hint path. Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
+177
-14
@@ -748,10 +748,23 @@ impl Instance {
|
||||
|
||||
// Record the Flow memory scope before parsing, planning and table lookup
|
||||
// capture the context, so every nested execution of this request shares
|
||||
// one budget (see `QueryEngine::with_flow_memory_scope`). This is the
|
||||
// same attachment as the gRPC entry and is a no-op for a request that
|
||||
// one budget (see `QueryEngine::with_flow_memory_scope_fallible`). This is
|
||||
// the same attachment as the gRPC entry and is a no-op for a request that
|
||||
// declares no budget or whose context already carries a scope.
|
||||
let query_ctx = self.query_engine().with_flow_memory_scope(query_ctx);
|
||||
//
|
||||
// The resolution is fallible and rejects a budget this build does not
|
||||
// support *before* the statement is dispatched: not every statement
|
||||
// reaches `engine_context` (a literal `INSERT ... VALUES` is written
|
||||
// through the statement executor's fast path), so relying on the engine
|
||||
// to refuse it later would let such a statement run unbudgeted.
|
||||
let query_ctx = match self
|
||||
.query_engine()
|
||||
.with_flow_memory_scope_fallible(query_ctx)
|
||||
.context(ExecLogicalPlanSnafu)
|
||||
{
|
||||
Ok(query_ctx) => query_ctx,
|
||||
Err(e) => return vec![Err(e)],
|
||||
};
|
||||
|
||||
let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
|
||||
let query_interceptor = query_interceptor_opt.as_ref();
|
||||
@@ -3482,12 +3495,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&self) -> QueryContextRef {
|
||||
self.captured
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("the query reached execution")
|
||||
/// The context SQL execution received, or `None` when the request never
|
||||
/// got past the entry (it is refused before parsing).
|
||||
fn take(&self) -> Option<QueryContextRef> {
|
||||
self.captured.lock().unwrap().take()
|
||||
}
|
||||
|
||||
/// Like [`Self::take`], for a request that must have reached execution.
|
||||
fn take_captured(&self) -> QueryContextRef {
|
||||
self.take().expect("the query reached execution")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3535,7 +3551,7 @@ mod tests {
|
||||
|
||||
// The captured context - the one planning and table lookup see - carries
|
||||
// the scope the entry resolved, on a fork of the incoming context.
|
||||
let captured = interceptor.take();
|
||||
let captured = interceptor.take_captured();
|
||||
assert!(!Arc::ptr_eq(&captured, &query_ctx));
|
||||
let scope = captured
|
||||
.memory_scope()
|
||||
@@ -3609,15 +3625,162 @@ mod tests {
|
||||
"unexpected error: {}",
|
||||
err.output_msg()
|
||||
);
|
||||
// The request entry still never mutates the caller's context...
|
||||
// The request entry 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());
|
||||
// ...and the request is refused by the entry: SQL execution never starts,
|
||||
// so no statement can run under the budget the build cannot enforce.
|
||||
assert!(interceptor.take().is_none());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A literal `INSERT ... VALUES` is served by the statement executor's fast
|
||||
/// path, which never builds an engine context: the request entry is the only
|
||||
/// place a budget this build cannot enforce can refuse it.
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
#[tokio::test]
|
||||
async fn test_literal_insert_with_flow_memory_budget_is_rejected_at_entry() -> 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(),
|
||||
"1024".to_string(),
|
||||
)
|
||||
.build(),
|
||||
);
|
||||
let err = match insert_literal_into_target(&instance, query_ctx.clone()).await {
|
||||
Ok(_) => panic!("a budget this build cannot enforce must refuse the insert"),
|
||||
Err(TestError::ExecuteSql { source, .. }) => source,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
// The refusal is the engine's `UnsupportedFlowMemoryBudget`, surfaced by
|
||||
// the entry before the statement was even parsed.
|
||||
assert_eq!(StatusCode::Unsupported, err.status_code());
|
||||
assert!(
|
||||
matches!(
|
||||
&err,
|
||||
Error::ExecLogicalPlan {
|
||||
source: query::error::Error::UnsupportedFlowMemoryBudget { .. },
|
||||
..
|
||||
}
|
||||
),
|
||||
"unexpected error: {err:?}"
|
||||
);
|
||||
assert!(
|
||||
err.output_msg()
|
||||
.contains("flow option `max_memory` requires the enterprise edition"),
|
||||
"unexpected error: {}",
|
||||
err.output_msg()
|
||||
);
|
||||
// The statement never reached parsing - let alone the write path - so no
|
||||
// row could have been written.
|
||||
assert!(interceptor.take().is_none());
|
||||
assert_eq!(0, count_target_rows(&instance).await?);
|
||||
// The caller's context is left alone.
|
||||
assert!(query_ctx.memory_scope().is_none());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The same literal insert without a declared budget is unaffected: the entry
|
||||
/// resolution is a no-op, so the statement is dispatched exactly as before.
|
||||
#[tokio::test]
|
||||
async fn test_literal_insert_without_flow_memory_budget_is_dispatched() -> TestResult<()> {
|
||||
let interceptor = Arc::new(CapturingQueryContextInterceptor::new());
|
||||
let instance = test_instance_with_insert_select_interceptor(interceptor.clone()).await?;
|
||||
|
||||
let outcome = insert_literal_into_target(&instance, test_query_ctx(1)).await;
|
||||
|
||||
// The statement ran: parsing saw the context, so the entry did not refuse
|
||||
// a request that declares no budget.
|
||||
let captured = interceptor.take_captured();
|
||||
assert!(captured.memory_scope().is_none());
|
||||
// The test instance has no datanode to route the write to, so the insert
|
||||
// itself cannot complete here; what matters for this test is that it is
|
||||
// not refused with the enterprise-only error.
|
||||
match outcome {
|
||||
Ok(output) => assert!(matches!(output.data, OutputData::AffectedRows(_))),
|
||||
Err(TestError::ExecuteSql { source, .. }) => assert_ne!(
|
||||
StatusCode::Unsupported,
|
||||
source.status_code(),
|
||||
"a request that declares no budget must not be rejected: {source}"
|
||||
),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
assert_eq!(0, count_target_rows(&instance).await?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// On an enterprise build the declared budget is accepted, so the same
|
||||
/// literal insert is dispatched instead of being refused.
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[tokio::test]
|
||||
async fn test_literal_insert_with_flow_memory_budget_is_dispatched_on_enterprise()
|
||||
-> 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(),
|
||||
"1024".to_string(),
|
||||
)
|
||||
.set_extension(query::options::FLOW_ID.to_string(), "42".to_string())
|
||||
.build(),
|
||||
);
|
||||
let outcome = insert_literal_into_target(&instance, query_ctx).await;
|
||||
|
||||
// Accepted at the entry: the statement is executed under the Flow's pool.
|
||||
let captured = interceptor.take_captured();
|
||||
assert_eq!("flow:42", captured.memory_scope().expect("scope").label());
|
||||
match outcome {
|
||||
Ok(output) => assert!(matches!(output.data, OutputData::AffectedRows(_))),
|
||||
Err(TestError::ExecuteSql { source, .. }) => assert_ne!(
|
||||
StatusCode::Unsupported,
|
||||
source.status_code(),
|
||||
"an enterprise build accepts the budget, so it must not be rejected: {source}"
|
||||
),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The literal `INSERT ... VALUES` the entry-level budget check must cover: it
|
||||
/// takes the statement executor's fast path and never builds an engine
|
||||
/// context.
|
||||
async fn insert_literal_into_target(
|
||||
instance: &Instance,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> TestResult<Output> {
|
||||
execute_one_sql(
|
||||
instance,
|
||||
"INSERT INTO target(id, ts) VALUES (1, '2026-01-01 00:00:00')",
|
||||
query_ctx,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Counts the rows of the `target` table through the ordinary SQL path, so a
|
||||
/// test can assert that a refused insert wrote nothing.
|
||||
async fn count_target_rows(instance: &Instance) -> TestResult<u64> {
|
||||
let output =
|
||||
execute_one_sql(instance, "SELECT count(*) FROM target", test_query_ctx(7)).await?;
|
||||
let pretty = output.data.pretty_print().await;
|
||||
// The single value row is the only line that parses as a number; the
|
||||
// header and the table borders do not.
|
||||
let count = pretty
|
||||
.lines()
|
||||
.find_map(|line| line.trim().trim_matches('|').trim().parse::<u64>().ok());
|
||||
Ok(count.unwrap_or_else(|| panic!("unexpected count output:\n{pretty}")))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_write_only_grpc_sql_is_checked_after_parsing() -> TestResult<()> {
|
||||
let plugins = Plugins::new();
|
||||
|
||||
@@ -51,8 +51,8 @@ use table::table::adapter::DfTableProviderAdapter;
|
||||
use table::table_name::TableName;
|
||||
|
||||
use crate::error::{
|
||||
CatalogSnafu, DataFusionSnafu, Error, ExternalSnafu, IncompleteGrpcRequestSnafu,
|
||||
NotSupportedSnafu, PermissionSnafu, PlanStatementSnafu, Result,
|
||||
CatalogSnafu, DataFusionSnafu, Error, ExecLogicalPlanSnafu, ExternalSnafu,
|
||||
IncompleteGrpcRequestSnafu, NotSupportedSnafu, PermissionSnafu, PlanStatementSnafu, Result,
|
||||
SubstraitDecodeLogicalPlanSnafu, TableNotFoundSnafu, TableOperationSnafu,
|
||||
};
|
||||
use crate::instance::{Instance, attach_timer};
|
||||
@@ -67,17 +67,26 @@ impl GrpcQueryHandler for Instance {
|
||||
request: Request,
|
||||
ctx: QueryContextRef,
|
||||
) -> server_error::Result<Output> {
|
||||
// Resolve a Flow's declared memory budget once, here, before anything
|
||||
// captures the context: table lookup captures it (the computed
|
||||
// semantic-graph tables keep it while resolving and re-enter the engine
|
||||
// with it later), and so does every nested execution this request fans
|
||||
// out into. A scope attached only in `engine_context` never reaches a
|
||||
// context captured before `engine_context` runs, so each of those
|
||||
// executions would derive an independent full budget instead of sharing
|
||||
// one. The context is forked, never mutated in place, and comes back
|
||||
// unchanged when the request declares no budget.
|
||||
let ctx = self.query_engine().with_flow_memory_scope(ctx);
|
||||
let result: Result<Output> = async {
|
||||
// Resolve a Flow's declared memory budget once, here, before anything
|
||||
// captures the context: table lookup captures it (the computed
|
||||
// semantic-graph tables keep it while resolving and re-enter the engine
|
||||
// with it later), and so does every nested execution this request fans
|
||||
// out into. A scope attached only in `engine_context` never reaches a
|
||||
// context captured before `engine_context` runs, so each of those
|
||||
// executions would derive an independent full budget instead of sharing
|
||||
// one. The context is forked, never mutated in place, and comes back
|
||||
// unchanged when the request declares no budget.
|
||||
//
|
||||
// Resolution is fallible and runs before the statement is dispatched:
|
||||
// a budget this build does not support must fail the request here,
|
||||
// because not every statement reaches `engine_context` (a literal
|
||||
// `INSERT ... VALUES` is written through the statement executor's fast
|
||||
// path). A limit that is not enforced must not look like one that is.
|
||||
let ctx = self
|
||||
.query_engine()
|
||||
.with_flow_memory_scope_fallible(ctx)
|
||||
.context(ExecLogicalPlanSnafu)?;
|
||||
let interceptor_ref = self.plugins.get::<GrpcQueryInterceptorRef<Error>>();
|
||||
let interceptor = interceptor_ref.as_ref();
|
||||
interceptor.pre_execute(&request, ctx.clone())?;
|
||||
|
||||
+26
-26
@@ -653,28 +653,6 @@ impl DatafusionQueryEngine {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<QueryContextRef> {
|
||||
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 `Ok(None)` when the query declares
|
||||
/// no budget of its own.
|
||||
@@ -867,13 +845,33 @@ impl QueryEngine for DatafusionQueryEngine {
|
||||
// land on the same pool.
|
||||
match query_ctx.memory_scope() {
|
||||
Some(scope) => Some(scope.clone()),
|
||||
// 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.
|
||||
// This hint-style entry point cannot fail, so a budget this build
|
||||
// does not support leaves the context on the node pool here. It is
|
||||
// rejected by `with_flow_memory_scope_fallible` at the request entry
|
||||
// - the path every request goes through - and by `engine_context`
|
||||
// for an execution that is entered directly.
|
||||
None => self.flow_memory_scope(query_ctx).ok().flatten(),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_flow_memory_scope_fallible(
|
||||
&self,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<QueryContextRef> {
|
||||
// Only the resolution can fail - it rejects a budget this build does not
|
||||
// support - so an already scoped context is returned as is, without
|
||||
// re-deriving (and possibly re-creating) its pool.
|
||||
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))
|
||||
}
|
||||
|
||||
fn engine_context(&self, query_ctx: QueryContextRef) -> Result<QueryEngineContext> {
|
||||
let mut state = self.state.session_state();
|
||||
// A process-local memory scope replaces the engine-wide pool for this
|
||||
@@ -900,7 +898,9 @@ impl QueryEngine for DatafusionQueryEngine {
|
||||
//
|
||||
// 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.
|
||||
// this query here instead of running it unbudgeted. The request entry
|
||||
// rejects it first, so this is the backstop for an execution that is
|
||||
// entered directly - not the only place the promise is kept.
|
||||
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();
|
||||
|
||||
@@ -107,10 +107,10 @@ pub trait QueryEngine: Send + Sync {
|
||||
/// The default declares no scope: only engines that bound memory per unit
|
||||
/// of work override this.
|
||||
///
|
||||
/// Call this (or [`QueryEngine::with_flow_memory_scope`]) at the request
|
||||
/// entry, before anything captures the context, so every execution that
|
||||
/// re-enters the engine under it shares one budget instead of deriving one
|
||||
/// budget each.
|
||||
/// Call this (or [`QueryEngine::with_flow_memory_scope_fallible`]) at the
|
||||
/// request entry, before anything captures the context, so every execution
|
||||
/// that re-enters the engine under it shares one budget instead of deriving
|
||||
/// one budget each.
|
||||
fn flow_memory_scope_for(&self, _query_ctx: &QueryContextRef) -> Option<QueryMemoryScope> {
|
||||
None
|
||||
}
|
||||
@@ -142,6 +142,25 @@ pub trait QueryEngine: Send + Sync {
|
||||
Arc::new(forked)
|
||||
}
|
||||
|
||||
/// Fallible [`QueryEngine::with_flow_memory_scope`]: the same resolution, but
|
||||
/// a budget this build does not support is returned as an error instead of
|
||||
/// being dropped.
|
||||
///
|
||||
/// The request entry points call this one, because the entry is the last
|
||||
/// place every request goes through: a statement dispatched without ever
|
||||
/// building an engine context - a plain `INSERT ... VALUES` is written
|
||||
/// through the fast path of the statement executor - would otherwise run
|
||||
/// under a budget that is not enforced.
|
||||
///
|
||||
/// The default cannot fail: an engine that resolves no scope has nothing to
|
||||
/// reject.
|
||||
fn with_flow_memory_scope_fallible(
|
||||
&self,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<QueryContextRef> {
|
||||
Ok(self.with_flow_memory_scope(query_ctx))
|
||||
}
|
||||
|
||||
/// Retrieve the query engine state [`QueryEngineState`]
|
||||
fn engine_state(&self) -> &QueryEngineState;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user