From d4dc86db4ca32a95cf6b92d3eaa5b928cc1f83e3 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 8 Jun 2026 13:30:11 +0000 Subject: [PATCH] fix(session): make attached async handles truly non-owning; tighten http_error envelope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses review feedback on #139 (attach_async_statement). The attached handle was documented as a read-only adopt but still had paths that could tear down the statement its owner controls. P1 — attach must not tear down the owner's statement: - Add an `owning` flag to ExecutedAsyncStatement (true for submit, false for attach via the new `new_attached` constructor). - `await_result()` only arms the drop-cancel guard when `owning`. A non-owning handle whose await future is dropped mid-poll (e.g. a passive observer wrapping it in `tokio::time::timeout`) no longer fires `cancel_statement` against the owner's query. The owning submit path keeps the DBU-safety drop-cancel behaviour. - `ExecutedAsyncStatement::cancel()` and the derived `AsyncStatementCanceller::cancel()` error (InvalidArgument) on a non-owning handle instead of cancelling a statement the caller doesn't own. `owning` is inherited by the canceller so the footgun doesn't just move. P1 — http_error SQLSTATE validation: - Require the canonical 5-char SQLSTATE shape (`len() == 5`) before attaching it, matching `terminal_outcome` — was `!is_empty()`, which let junk like "X" through onto Error.sql_state. P2: - attach_async_statement stamps the statement id onto the NotFound error (with_query_id), matching terminal_outcome. - http_error parses the body once into serde_json::Value, then tries both envelope shapes off it (was two full string parses). - When the envelope has an error_code but no message, synthesize "server returned error_code " instead of folding the raw JSON body into the human-readable message. Tests: - attached_handle_await_result_drop_does_not_cancel_statement: a dropped await on an attached handle fires zero cancels (the owning await_result_drop_fires_cancel_statement pins the contrast). - attached_handle_cancel_errors: cancel() and the derived canceller both error on an attached handle, with zero cancels on the wire. Deferred (its own follow-up — needs a live system-table fixture to verify the exact server casing): list_table_types() advertises "SYSTEM TABLE" (space) while SHOW TABLES emits "SYSTEM_TABLE" (underscore); reconciling the canonical list is out of scope here. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- src/client/http.rs | 43 ++++++++---- src/session.rs | 48 ++++++------- src/statement/executed_async.rs | 108 +++++++++++++++++++++++++++-- tests/v0_async_execute_wiremock.rs | 91 ++++++++++++++++++++++++ 4 files changed, 245 insertions(+), 45 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 486ac680..799fa81c 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -53,32 +53,47 @@ fn http_error(status: u16, body: &str, context: impl std::fmt::Display) -> Error struct ErrorWrapper { error: ServiceError, } - // Try the bare envelope first, then the `{"error": ...}` wrapper. - let svc: Option = serde_json::from_str::(body) + // Parse the body once into a `Value`, then try both envelope shapes + // off it (bare `ServiceError`, then the `{"error": ...}` wrapper) — + // avoids re-walking the raw string twice. + let svc: Option = serde_json::from_str::(body) .ok() - .filter(|e| e.error_code.is_some() || e.message.is_some() || e.sql_state.is_some()) - .or_else(|| { - serde_json::from_str::(body) + .and_then(|v| { + serde_json::from_value::(v.clone()) .ok() - .map(|w| w.error) + .filter(|e| e.error_code.is_some() || e.message.is_some() || e.sql_state.is_some()) + .or_else(|| { + serde_json::from_value::(v) + .ok() + .map(|w| w.error) + }) }); let mut err = Error::from_http_status(status); match svc { Some(svc) => { - // Prefer the server's structured message; keep the caller - // context as a prefix for continuity with existing logs. - let msg = svc.message.as_deref().unwrap_or(body); + let error_code = svc.error_code.as_deref().filter(|s| !s.is_empty()); + // Prefer the server's structured message. If it's absent but + // an error_code is present, synthesize a readable message + // rather than folding the raw JSON body in. Only fall back to + // the raw body when neither is available. + let msg = match (svc.message.as_deref(), error_code) { + (Some(m), _) => m.to_string(), + (None, Some(ec)) => format!("server returned error_code {ec}"), + (None, None) => body.to_string(), + }; err = err.message(format!("{context}: {msg}")); - if let Some(ec) = svc.error_code.as_deref().filter(|s| !s.is_empty()) { + if let Some(ec) = error_code { err = err.with_error_code(ec); } - // SQL state: explicit field, else the "SQLSTATE: XXXXX" - // pattern in the message — same precedence as terminal_outcome. + // SQL state: explicit field (must be the canonical 5-char + // shape — same predicate as terminal_outcome, so we don't + // surface junk like "X" or "garbage"), else the + // "SQLSTATE: XXXXX" pattern in the message. let sql_state = svc .sql_state - .filter(|s| !s.is_empty()) - .or_else(|| crate::kernel_error::extract_sqlstate_from_message(msg)); + .filter(|s| s.len() == 5) + .or_else(|| crate::kernel_error::extract_sqlstate_from_message(&msg)); if let Some(s) = sql_state { err = err.with_sql_state(s); } diff --git a/src/session.rs b/src/session.rs index 21c759d8..81cda453 100644 --- a/src/session.rs +++ b/src/session.rs @@ -65,9 +65,7 @@ use crate::metadata_v0::Metadata; use crate::reader::ResultReaderFactory; use crate::statement::executed_async::ExecutedAsyncStatement; use crate::statement::mutable::Statement; -use crate::statement::validity::ValidityFlag; use std::collections::HashMap; -use std::sync::atomic::AtomicBool; use std::sync::Arc; use std::time::Duration; use tracing::{info_span, Instrument, Span}; @@ -373,10 +371,12 @@ impl Session { /// [`status`] surfaces the real server state. /// /// The returned handle is standalone and **non-owning**: its - /// [`ValidityFlag`] is fresh (not shared with any parent - /// `Statement`, since there is none), and it does **not** close the - /// server statement on `Drop` or via [`close`] — attach is a - /// read-only adopt. The statement's lifecycle stays with whatever + /// validity flag is fresh (not shared with any parent `Statement`, + /// since there is none), and it does **not** close the server + /// statement on `Drop` or via [`close`], does **not** cancel it on a + /// dropped `await_result()` poll, and its [`cancel`] errors — attach + /// is a read-only adopt. The statement's lifecycle stays with + /// whatever /// submitted it (or an explicit `close_statement`); a transient /// handle a poller creates and drops must not tear it down. (This is /// what lets `get_query_state` re-attach on every poll without the @@ -384,6 +384,7 @@ impl Session { /// /// [`status`]: ExecutedAsyncStatement::status /// [`close`]: ExecutedAsyncStatement::close + /// [`cancel`]: ExecutedAsyncStatement::cancel /// [`ErrorCode::NotFound`]: crate::kernel_error::ErrorCode::NotFound pub async fn attach_async_statement( &self, @@ -395,32 +396,27 @@ impl Session { // Seed initial_status from the wire — the same RPC // `ExecutedAsyncStatement::status` makes. Surfaces NotFound // here (rather than on the caller's first poll) for an - // unknown/expired id. + // unknown/expired id. Stamp the statement id onto the error + // (mirrors `terminal_outcome`, which sets query_id on every + // error it builds) so callers can correlate which id was not + // found. let response = self .inner .transport() .statement_status(&statement_id) - .await?; - Ok(ExecutedAsyncStatement::new( + .await + .map_err(|e| e.with_query_id(&statement_id))?; + // NON-OWNING read-only adopt: `new_attached` gives the handle + // a fresh standalone `ValidityFlag`, `closed=true` (so `Drop` + // / `close()` never fire `close_statement`), and + // `owning=false` (so `await_result` doesn't arm the + // drop-cancel guard and `cancel()` errors). The statement's + // lifecycle stays with whoever submitted it; a poller that + // re-attaches each tick can't tear down the statement it's + // watching. + Ok(ExecutedAsyncStatement::new_attached( Arc::clone(&self.inner), statement_id, - // Standalone handle: no parent Statement to share the - // flag with, so a re-execute elsewhere can't invalidate - // it. Starts valid. - ValidityFlag::new(), - // NON-OWNING: start `closed=true` so this handle never - // closes the server statement — neither on `Drop` (its - // `swap(true)` sees already-closed and skips the - // fire-and-forget `close_statement`) nor via an explicit - // `close()` (which short-circuits on the flag). Attach is - // a *read-only adopt*: the statement's lifecycle is owned - // by whatever submitted it (or by an explicit - // `close_statement`), NOT by a transient handle a poller - // creates and drops. Without this, every `status()` poll - // through a fresh attached handle would close the very - // statement it's polling on Drop — turning a poll loop - // into a self-close. - Arc::new(AtomicBool::new(true)), response.status, )) } diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 7458388c..1cac1586 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -187,6 +187,23 @@ pub struct ExecutedAsyncStatement { /// short-circuited) `close()`. Tells `Drop` to skip its /// fire-and-forget cleanup. closed: Arc, + /// Whether this handle *owns* the server statement's lifecycle. + /// + /// `true` for handles produced by [`Statement::submit`] (the + /// submitting handle): they may close the statement on `Drop` / + /// `close()`, cancel it on a dropped `await_result()` poll (the + /// drop-cancel DBU-safety guard), and `cancel()` actively + /// terminates it. + /// + /// `false` for handles produced by + /// [`Session::attach_async_statement`](crate::Session::attach_async_statement) + /// — a *read-only adopt* of a statement someone else owns. A + /// non-owning handle must never tear the statement down out from + /// under its owner: it does not arm the `await_result` drop-cancel + /// guard, and `cancel()` returns an error instead of firing a + /// server-side cancel. (`Drop` / `close()` are already inert on + /// attached handles via `closed=true`.) + owning: bool, /// Last SEA `StatementStatus` observed by this handle (initial /// `submit_statement` response or any subsequent `status()` / /// `await_result` poll). Read by the `num_modified_rows()` / @@ -236,6 +253,40 @@ impl ExecutedAsyncStatement { statement_id, valid, closed, + // The submitting handle owns the statement lifecycle. + owning: true, + latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + } + } + + /// Crate-internal constructor for a **non-owning** (read-only + /// adopt) handle, built by + /// [`Session::attach_async_statement`](crate::Session::attach_async_statement). + /// + /// The handle observes a statement someone else owns, so it must + /// never tear it down: + /// - `valid` is a fresh standalone [`ValidityFlag`] — no parent + /// `Statement` to share with, so a re-execute elsewhere can't + /// invalidate it. + /// - `closed` starts `true` so `Drop` and `close()` are inert (they + /// never fire `close_statement`). + /// - `owning` is `false` so `await_result()` does not arm the + /// drop-cancel guard and `cancel()` errors instead of firing a + /// server-side cancel. + /// + /// `initial_status` is seeded from the `GetStatementStatus` the + /// attach path already issued. + pub(crate) fn new_attached( + session: Arc, + statement_id: String, + initial_status: crate::types::sea::StatementStatus, + ) -> Self { + Self { + session, + statement_id, + valid: ValidityFlag::new(), + closed: Arc::new(AtomicBool::new(true)), + owning: false, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), } } @@ -379,8 +430,21 @@ impl ExecutedAsyncStatement { // best-effort `cancel_statement` so the server stops // charging DBUs on a now-orphaned query. Defused once we // reach a terminal state on the success or error path. - let cancel_guard = - AwaitResultCancelGuard::new(Arc::clone(&self.session), self.statement_id.clone()); + // + // ONLY for owning handles. A non-owning (attached) handle is + // a read-only adopt of a statement someone else owns — + // dropping its `await_result()` mid-poll (e.g. a passive + // observer wrapping it in a `tokio::time::timeout`) must NOT + // cancel the owner's statement. Leaving the guard `None` + // makes the drop a true no-op. + let mut cancel_guard = if self.owning { + Some(AwaitResultCancelGuard::new( + Arc::clone(&self.session), + self.statement_id.clone(), + )) + } else { + None + }; loop { self.valid.check()?; @@ -395,17 +459,23 @@ impl ExecutedAsyncStatement { self.record_latest_status(response.status.clone()); match StatementStatus::from_sea_response(&response) { StatementStatus::Succeeded | StatementStatus::Closed => { - cancel_guard.defuse(); + if let Some(g) = cancel_guard.take() { + g.defuse(); + } return self.materialise_result().await; } StatementStatus::Failed(e) => { // Server already decided this is terminal — no // need to fire a redundant cancel. - cancel_guard.defuse(); + if let Some(g) = cancel_guard.take() { + g.defuse(); + } return Err(e); } StatementStatus::Cancelled => { - cancel_guard.defuse(); + if let Some(g) = cancel_guard.take() { + g.defuse(); + } // Carry the SEA extended status fields onto // the returned Error — mirrors the sync // `terminal_outcome::Canceled` arm so the @@ -563,6 +633,17 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { async fn cancel(&self) -> Result<()> { async { self.valid.check()?; + // A non-owning (attached) handle must not cancel a statement + // it merely adopted to observe — that would terminate the + // owner's query. Refuse rather than silently firing the + // server-side cancel. + if !self.owning { + return Err(Error::invalid_state().message( + "cancel() is not permitted on an attached (read-only) \ + ExecutedAsyncStatement; the statement is owned by whoever \ + submitted it", + )); + } self.session .transport() .cancel_statement(&self.statement_id) @@ -628,6 +709,11 @@ impl ExecutedAsyncStatement { session: Arc::clone(&self.session), statement_id: self.statement_id.clone(), valid: self.valid.clone(), + // Inherit ownership: a canceller derived from an attached + // (read-only) handle must not cancel the owner's statement + // either — otherwise the footgun just moves to the detached + // canceller. + owning: self.owning, } } } @@ -647,6 +733,11 @@ pub struct AsyncStatementCanceller { session: Arc, statement_id: String, valid: ValidityFlag, + /// Inherited from the producing handle — `false` for a canceller + /// derived from an attached (read-only) handle, which must not + /// cancel a statement it doesn't own. See + /// [`ExecutedAsyncStatement::owning`]. + owning: bool, } impl AsyncStatementCanceller { @@ -663,6 +754,13 @@ impl AsyncStatementCanceller { pub async fn cancel(&self) -> Result<()> { async { self.valid.check()?; + if !self.owning { + return Err(Error::invalid_state().message( + "cancel() is not permitted on a canceller derived from an \ + attached (read-only) ExecutedAsyncStatement; the statement \ + is owned by whoever submitted it", + )); + } self.session .transport() .cancel_statement(&self.statement_id) diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 94f12e0d..d6ee5343 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -1118,3 +1118,94 @@ async fn attached_handle_drop_does_not_close_statement() { tokio::time::sleep(std::time::Duration::from_millis(150)).await; // `_no_close` verifies expect(0) when it drops at end of scope. } + +#[tokio::test] +async fn attached_handle_await_result_drop_does_not_cancel_statement() { + // P1: an attached (non-owning) handle must NOT fire cancel_statement + // when its await_result() future is dropped mid-poll. The owning + // submit path *does* (await_result_drop_fires_cancel_statement pins + // that); attach is a read-only adopt, so a passive observer wrapping + // await_result() in a timeout must never cancel the owner's query. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + // Server stays RUNNING forever so await_result() loops until dropped. + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-attach-noclancel")) + .respond_with( + ResponseTemplate::new(200).set_body_string(running_body("stmt-attach-noclancel")), + ) + .mount(&server) + .await; + // Scoped expectation: ZERO cancels on this statement. + let _no_cancel = Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-attach-noclancel/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + let async_exec = session + .attach_async_statement("stmt-attach-noclancel") + .await + .expect("attach"); + + // Drop the await_result future via timeout. + let outcome = tokio::time::timeout( + std::time::Duration::from_millis(150), + async_exec.await_result(), + ) + .await; + assert!(outcome.is_err(), "timeout should fire"); + + // Give any (erroneously) spawned cancel a chance to hit the wire + // before the scoped mock verifies expect(0) on drop. + tokio::time::sleep(std::time::Duration::from_millis(150)).await; + // `_no_cancel` verifies expect(0) when it drops at end of scope. +} + +#[tokio::test] +async fn attached_handle_cancel_errors() { + // P1: cancel() on an attached (read-only) handle must refuse rather + // than terminate a statement it doesn't own. No cancel reaches the + // server. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_status_once( + &server, + "stmt-attach-cancel", + running_body("stmt-attach-cancel"), + ) + .await; + let _no_cancel = Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-attach-cancel/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + let async_exec = session + .attach_async_statement("stmt-attach-cancel") + .await + .expect("attach"); + + let err = async_exec + .cancel() + .await + .expect_err("cancel() on an attached handle must error"); + assert_eq!(err.code, ErrorCode::InvalidArgument, "got: {err:?}"); + + // Same for a canceller derived from the attached handle. + let canceller = async_exec.canceller(); + let cerr = canceller + .cancel() + .await + .expect_err("canceller from an attached handle must error"); + assert_eq!(cerr.code, ErrorCode::InvalidArgument, "got: {cerr:?}"); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; +}