diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index 4aa73f35d73..5baeb968463 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -48,6 +48,7 @@ use auth::{ use catalog::CatalogManagerRef; use catalog::process_manager::{ ProcessManagerRef, QueryStatement as CatalogQueryStatement, SlowQueryRecorder, SlowQueryTimer, + Ticket, }; use client::OutputData; use common_base::Plugins; @@ -61,8 +62,8 @@ use common_meta::key::TableMetadataManagerRef; use common_meta::node_manager::NodeManagerRef; use common_meta::procedure_executor::ProcedureExecutorRef; use common_query::{Output, OutputMeta}; -use common_recordbatch::RecordBatchStreamWrapper; use common_recordbatch::error::StreamTimeoutSnafu; +use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream}; use common_telemetry::logging::SlowQueryOptions; use common_telemetry::{debug, error, tracing}; use common_time::timestamp::TimeUnit; @@ -315,23 +316,38 @@ fn validate_analyze_stream_statement(stmt: &mut Statement) -> Result<()> { } impl Instance { - fn statement_slow_query_timer( + fn slow_query_timer( &self, - stmt: &Statement, - schema_name: String, + statement: impl FnOnce() -> CatalogQueryStatement, + query_ctx: &QueryContextRef, ) -> Option { - if !should_track_statement_process(stmt) || !self.slow_query_options.enable { - return None; - } + self.slow_query_options.enable.then(|| { + SlowQueryTimer::new( + statement(), + query_ctx.current_schema(), + self.slow_query_options.threshold, + self.slow_query_options.sample_ratio, + self.slow_query_options.record_type, + self.slow_query_recorder.clone(), + ) + }) + } - Some(SlowQueryTimer::new( - CatalogQueryStatement::Sql(stmt.clone()), - schema_name, - self.slow_query_options.threshold, - self.slow_query_options.sample_ratio, - self.slow_query_options.record_type, - self.slow_query_recorder.clone(), - )) + fn register_query( + &self, + query_ctx: &QueryContextRef, + schemas: Vec, + query: String, + slow_query_timer: Option, + ) -> Ticket { + self.process_manager.register_query( + query_ctx.current_catalog().to_string(), + schemas, + query, + query_ctx.conn_info().to_string(), + Some(query_ctx.process_id()), + slow_query_timer, + ) } async fn query_statement(&self, stmt: Statement, query_ctx: QueryContextRef) -> Result { @@ -355,75 +371,26 @@ impl Instance { let query_interceptor = self.plugins.get::>(); let query_interceptor = query_interceptor.as_ref(); + let timeout = derive_timeout(stmt.is_readonly(), &query_ctx); if should_track_statement_process(&stmt) { - let catalog_name = query_ctx.current_catalog().to_string(); - let schema_name = query_ctx.current_schema(); - let slow_query_timer = self.statement_slow_query_timer(&stmt, schema_name.clone()); + let slow_query_timer = + self.slow_query_timer(|| CatalogQueryStatement::Sql(stmt.clone()), &query_ctx); let timeout_recorder = is_explain_analyze_verbose(&stmt) .then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder)) .flatten(); - - let ticket = self.process_manager.register_query( - catalog_name, - vec![schema_name], + let ticket = self.register_query( + &query_ctx, + vec![query_ctx.current_schema()], stmt.to_string(), - query_ctx.conn_info().to_string(), - Some(query_ctx.process_id()), slow_query_timer, ); - let query_fut = self.exec_statement_with_timeout( - stmt, - query_ctx.clone(), - query_interceptor, - timeout_recorder, - ); - - let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| error::CancelledSnafu.build())?; - result.map(|output| { - let Output { meta, data } = output; - let data = match data { - OutputData::Stream(stream) => { - OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket))) - } - other => other, - }; - Output { data, meta } - }) + let exec = Box::pin(self.exec_statement(stmt, query_ctx, query_interceptor)); + let query_fut = exec_with_timeout(timeout, exec, timeout_recorder); + exec_tracked(ticket, query_fut, CancellableStreamWrapper::new).await } else { - self.exec_statement_with_timeout(stmt, query_ctx, query_interceptor, None) - .await - } - } - - async fn exec_statement_with_timeout( - &self, - stmt: Statement, - query_ctx: QueryContextRef, - query_interceptor: Option<&SqlQueryInterceptorRef>, - timeout_recorder: Option, - ) -> Result { - let timeout = derive_timeout(&stmt, &query_ctx); - match timeout { - Some(timeout) => { - let start = tokio::time::Instant::now(); - let output = tokio::time::timeout( - timeout, - self.exec_statement(stmt, query_ctx, query_interceptor), - ) - .await - .map_err(|_| StatementTimeoutSnafu.build())??; - let output = map_query_output(output)?; - // compute remaining timeout - let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default(); - attach_timeout(output, remaining_timeout, timeout_recorder) - } - None => self - .exec_statement(stmt, query_ctx, query_interceptor) - .await - .and_then(map_query_output), + let exec = Box::pin(self.exec_statement(stmt, query_ctx, query_interceptor)); + exec_with_timeout(timeout, exec, None).await } } @@ -557,29 +524,55 @@ impl Instance { /// If the relevant variables are set, the timeout is enforced for all PostgreSQL statements. /// For MySQL, it applies only to read-only statements. -fn derive_timeout(stmt: &Statement, query_ctx: &QueryContextRef) -> Option { +fn derive_timeout(readonly: bool, query_ctx: &QueryContextRef) -> Option { let query_timeout = query_ctx.query_timeout()?; if query_timeout.is_zero() { return None; } match query_ctx.channel() { - Channel::Mysql if stmt.is_readonly() => Some(query_timeout), + Channel::Mysql if readonly => Some(query_timeout), Channel::Postgres => Some(query_timeout), _ => None, } } -/// Derives timeout for plan execution. -fn derive_timeout_for_plan(plan: &LogicalPlan, query_ctx: &QueryContextRef) -> Option { - let query_timeout = query_ctx.query_timeout()?; - if query_timeout.is_zero() { - return None; - } - match query_ctx.channel() { - Channel::Mysql if is_readonly_plan(plan) => Some(query_timeout), - Channel::Postgres => Some(query_timeout), - _ => None, - } +/// Runs `exec` within `timeout`, which also bounds reading a stream output. +/// +/// `exec` is boxed because an async fn keeps its future argument and the awaited copy +/// side by side, and the statement futures are large enough to overflow the stack in +/// debug builds. +async fn exec_with_timeout( + timeout: Option, + exec: Pin>>>, + timeout_recorder: Option, +) -> Result { + let Some(timeout) = timeout else { + return exec.await.and_then(map_query_output); + }; + let start = tokio::time::Instant::now(); + let output = tokio::time::timeout(timeout, exec) + .await + .map_err(|_| StatementTimeoutSnafu.build())??; + let output = map_query_output(output)?; + let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default(); + attach_timeout(output, remaining_timeout, timeout_recorder) +} + +/// Runs a query registered under `ticket` so that killing it cancels the run. A +/// stream output takes the ticket, keeping the query listed until the stream is dropped. +async fn exec_tracked( + ticket: Ticket, + query: impl Future>, + wrap_stream: fn(SendableRecordBatchStream, Ticket) -> CancellableStreamWrapper, +) -> Result { + let Output { meta, data } = CancellableFuture::new(query, ticket.cancellation_handle.clone()) + .await + .map_err(|_| error::CancelledSnafu.build())??; + let data = match data { + OutputData::Stream(stream) => OutputData::Stream(Box::pin(wrap_stream(stream, ticket))), + other => other, + }; + Ok(Output { data, meta }) } fn record_explain_analyze_timeout( @@ -833,30 +826,27 @@ impl Instance { let query_ctx = self.check_sql_permission(&stmt, &query_ctx).await?; check_permission(self.plugins.clone(), &stmt, &query_ctx)?; - let catalog_name = query_ctx.current_catalog().to_string(); - let schema_name = query_ctx.current_schema(); - let slow_query_timer = self.statement_slow_query_timer(&stmt, schema_name.clone()); - let ticket = self.process_manager.register_query( - catalog_name, - vec![schema_name], + let slow_query_timer = should_track_statement_process(&stmt) + .then(|| self.slow_query_timer(|| CatalogQueryStatement::Sql(stmt.clone()), &query_ctx)) + .flatten(); + let ticket = self.register_query( + &query_ctx, + vec![query_ctx.current_schema()], stmt.to_string(), - query_ctx.conn_info().to_string(), - Some(query_ctx.process_id()), slow_query_timer, ); - let query_fut = - self.exec_statement_with_timeout(stmt, query_ctx.clone(), query_interceptor, None); - let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| error::CancelledSnafu.build())??; - let Output { meta, data } = output; - let data = match data { - OutputData::Stream(stream) => OutputData::Stream(Box::pin( - CancellableStreamWrapper::new_cancel_on_drop(stream, ticket), - )), - other => other, - }; - query_interceptor.post_execute(Output { data, meta }, query_ctx) + let query_fut = exec_with_timeout( + derive_timeout(stmt.is_readonly(), &query_ctx), + Box::pin(self.exec_statement(stmt, query_ctx.clone(), query_interceptor)), + None, + ); + let output = exec_tracked( + ticket, + query_fut, + CancellableStreamWrapper::new_cancel_on_drop, + ) + .await?; + query_interceptor.post_execute(output, query_ctx) } async fn batch_create_logical_tables( @@ -1021,30 +1011,6 @@ impl Instance { .context(ExecLogicalPlanSnafu) } - async fn exec_plan_with_timeout( - &self, - plan: LogicalPlan, - query_ctx: QueryContextRef, - timeout_recorder: Option, - ) -> Result { - let timeout = derive_timeout_for_plan(&plan, &query_ctx); - match timeout { - Some(timeout) => { - let start = tokio::time::Instant::now(); - let output = tokio::time::timeout(timeout, self.exec_plan(plan, query_ctx)) - .await - .map_err(|_| StatementTimeoutSnafu.build())??; - let output = map_query_output(output)?; - let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default(); - attach_timeout(output, remaining_timeout, timeout_recorder) - } - None => self - .exec_plan(plan, query_ctx) - .await - .and_then(map_query_output), - } - } - async fn do_exec_plan_inner( &self, plan: LogicalPlan, @@ -1088,52 +1054,28 @@ impl Instance { .map(|s| s.to_string()) .unwrap_or_else(|| plan.display_indent().to_string()); + let timeout = derive_timeout(is_readonly_plan(&plan), &query_ctx); let result = if should_track_plan_process(stmt.as_ref(), &plan) { - let catalog_name = query_ctx.current_catalog().to_string(); - let schema_name = query_ctx.current_schema(); - let slow_query_timer = self.slow_query_options.enable.then(|| { - SlowQueryTimer::new( - CatalogQueryStatement::Plan(query.clone()), - schema_name.clone(), - self.slow_query_options.threshold, - self.slow_query_options.sample_ratio, - self.slow_query_options.record_type, - self.slow_query_recorder.clone(), - ) - }); - + let slow_query_timer = + self.slow_query_timer(|| CatalogQueryStatement::Plan(query.clone()), &query_ctx); let timeout_recorder = stmt .as_ref() .is_some_and(is_explain_analyze_verbose) .then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder)) .flatten(); - let ticket = self.process_manager.register_query( - catalog_name, - vec![schema_name], + let ticket = self.register_query( + &query_ctx, + vec![query_ctx.current_schema()], query, - query_ctx.conn_info().to_string(), - Some(query_ctx.process_id()), slow_query_timer, ); - let query_fut = self.exec_plan_with_timeout(plan, query_ctx.clone(), timeout_recorder); - - let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| error::CancelledSnafu.build())?; - result.map(|output| { - let Output { meta, data } = output; - let data = match data { - OutputData::Stream(stream) => { - OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket))) - } - other => other, - }; - Output { data, meta } - }) + let exec = Box::pin(self.exec_plan(plan, query_ctx.clone())); + let query_fut = exec_with_timeout(timeout, exec, timeout_recorder); + exec_tracked(ticket, query_fut, CancellableStreamWrapper::new).await } else { - self.exec_plan_with_timeout(plan, query_ctx.clone(), None) - .await + let exec = Box::pin(self.exec_plan(plan, query_ctx.clone())); + exec_with_timeout(timeout, exec, None).await }; result.and_then(|output| query_interceptor.post_execute(output, query_ctx)) @@ -2048,23 +1990,11 @@ impl PrometheusHandler for Instance { let query_statement = CatalogQueryStatement::Promql(eval_stmt.clone(), alias.clone()); let raw_query = query_statement.to_string(); - let slow_query_timer = self.slow_query_options.enable.then(|| { - SlowQueryTimer::new( - query_statement, - query_ctx.current_schema(), - self.slow_query_options.threshold, - self.slow_query_options.sample_ratio, - self.slow_query_options.record_type, - self.slow_query_recorder.clone(), - ) - }); - - let ticket = self.process_manager.register_query( - query_ctx.current_catalog().to_string(), + let slow_query_timer = self.slow_query_timer(|| query_statement, &query_ctx); + let ticket = self.register_query( + &query_ctx, vec![query_ctx.current_schema()], raw_query, - query_ctx.conn_info().to_string(), - Some(query_ctx.process_id()), slow_query_timer, ); @@ -4374,6 +4304,27 @@ mod tests { builder.try_build().await.context(BuildFrontendSnafu) } + async fn execute_sql_maybe_prepared( + instance: &Instance, + sql: &str, + query_ctx: QueryContextRef, + prepared: bool, + ) -> TestResult { + if !prepared { + return execute_one_sql(instance, sql, query_ctx).await; + } + let stmt = parse_one_sql(sql); + let described = instance + .do_describe_inner(stmt.clone(), query_ctx.clone()) + .await + .context(ExecuteSqlSnafu { sql })? + .unwrap(); + instance + .do_exec_plan_inner(described.logical_plan, Some(stmt), query_ctx) + .await + .context(ExecuteSqlSnafu { sql }) + } + async fn execute_one_sql( instance: &Instance, sql: &str, @@ -6018,21 +5969,9 @@ mod tests { ] { instance.slow_query_options.enable = enabled; instance.slow_query_options.threshold = threshold; - let query_ctx = test_query_ctx(42); - let output = if prepared { - let stmt = parse_one_sql(sql); - let described = instance - .do_describe_inner(stmt.clone(), query_ctx.clone()) - .await - .unwrap() - .unwrap(); - instance - .do_exec_plan_inner(described.logical_plan, Some(stmt), query_ctx) - .await - .unwrap() - } else { - execute_one_sql(&instance, sql, query_ctx).await? - }; + let output = + execute_sql_maybe_prepared(&instance, sql, test_query_ctx(42), prepared) + .await?; assert!(matches!(output.data, OutputData::AffectedRows(0))); let queries = std::mem::take(&mut *recorder.queries.lock().unwrap()); @@ -6186,6 +6125,74 @@ mod tests { Ok(()) } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_insert_select_timeout_depends_on_channel() -> TestResult<()> { + let insert_sql = "INSERT INTO target SELECT * FROM source"; + for prepared in [false, true] { + for channel in [Channel::Postgres, Channel::Mysql] { + let (source_polled_tx, source_polled_rx) = oneshot::channel(); + let instance = Arc::new( + test_instance_with_tables( + pending_table(1024, "source", source_polled_tx)?, + test_table(1025, "target")?, + ) + .await?, + ); + let query_ctx = Arc::new( + QueryContextBuilder::default() + .channel(channel) + .conn_info(ConnInfo::new(None, channel)) + .process_id(4242) + .build(), + ); + query_ctx.set_query_timeout(Duration::from_millis(100)); + + let insert_task = tokio::spawn({ + let instance = instance.clone(); + async move { + execute_sql_maybe_prepared(&instance, insert_sql, query_ctx, prepared).await + } + }); + // MySQL enforces the session timeout on read-only statements only. Postgres may time + // out before the source is polled, so only MySQL waits for the scan to start. + if channel == Channel::Mysql { + tokio::time::timeout(Duration::from_secs(5), source_polled_rx) + .await + .context(SourcePollTimeoutSnafu)? + .context(SourcePollChannelClosedSnafu)?; + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!insert_task.is_finished(), "prepared={prepared}"); + let output = + execute_one_sql(&instance, "KILL QUERY 4242", test_query_ctx(43)).await?; + assert!(matches!(output.data, OutputData::AffectedRows(1))); + } + + let insert_result = tokio::time::timeout(Duration::from_secs(5), insert_task) + .await + .context(InsertTaskTimeoutSnafu)? + .context(InsertTaskPanicSnafu)?; + let Err(TestError::ExecuteSql { source: err, .. }) = insert_result else { + return InsertSelectNotCancelledSnafu.fail(); + }; + assert!( + matches!( + (channel, &err), + (Channel::Postgres, Error::StatementTimeout { .. }) + | (Channel::Mysql, Error::Cancelled { .. }) + ), + "prepared={prepared}: {err:?}" + ); + + let output = + execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?; + let process_list = output.data.pretty_print().await; + assert!(!process_list.contains(insert_sql), "{process_list}"); + } + } + + Ok(()) + } + fn insert_dml_plan() -> LogicalPlan { let schema = SchemaRef::new(Schema::new(vec![Field::new( "value", diff --git a/src/frontend/src/instance/exemplar.rs b/src/frontend/src/instance/exemplar.rs index e3b74388c4f..2f0ba7c1444 100644 --- a/src/frontend/src/instance/exemplar.rs +++ b/src/frontend/src/instance/exemplar.rs @@ -16,7 +16,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use auth::{PermissionTableTarget, PermissionTableTargets}; -use catalog::process_manager::{QueryStatement as CatalogQueryStatement, SlowQueryTimer}; +use catalog::process_manager::QueryStatement as CatalogQueryStatement; use common_base::cancellation::CancellableFuture; use common_catalog::consts::METRICS_EXEMPLARS_TABLE; use common_error::ext::BoxedError; @@ -106,22 +106,12 @@ impl Instance { "query_exemplars({}, start_ns={}, end_ns={})", query.expression, query.bounds.0, query.bounds.1 ); - let slow_query_timer = self.slow_query_options.enable.then(|| { - SlowQueryTimer::new( - CatalogQueryStatement::Plan(raw_query.clone()), - ctx.current_schema(), - self.slow_query_options.threshold, - self.slow_query_options.sample_ratio, - self.slow_query_options.record_type, - self.slow_query_recorder.clone(), - ) - }); - let ticket = self.process_manager.register_query( - ctx.current_catalog().to_string(), + let slow_query_timer = + self.slow_query_timer(|| CatalogQueryStatement::Plan(raw_query.clone()), &ctx); + let ticket = self.register_query( + &ctx, groups.keys().cloned().collect(), raw_query, - ctx.conn_info().to_string(), - Some(ctx.process_id()), slow_query_timer, ); let cancellation = ticket.cancellation_handle.clone();