diff --git a/src/client/sea.rs b/src/client/sea.rs index 12a420d6..f0d6f37c 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -369,10 +369,15 @@ impl SeaRestTransport { let response = self.wait_for_completion(response).await?; let reader_factory = self.reader_factory()?; let reader = reader_factory.create_reader(&response.statement_id, &response)?; + // `server_state` carries the terminal state forward so the + // executed handle can skip a redundant CloseStatement when + // the server already cleaned up (state=Closed). + let server_state = response.status.state; Ok(ExecuteResult { statement_id: response.statement_id, reader, manifest: response.manifest, + server_state, }) } } @@ -505,10 +510,12 @@ impl Transport for SeaRestTransport { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; let reader = reader_factory.create_reader(&r.statement_id, &r)?; + let server_state = r.status.state; Ok(Some(ExecuteResult { statement_id: r.statement_id, reader, manifest: r.manifest, + server_state, })) } StatementOutcome::NotReady(_) => Ok(None), diff --git a/src/client/transport.rs b/src/client/transport.rs index 1eea2897..f85d988d 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -27,7 +27,7 @@ use crate::kernel_error::Result; use crate::reader::ResultReader; use crate::types::cloudfetch::CloudFetchLink; -use crate::types::sea::{ExecuteParams, ResultManifest, StatementStatus}; +use crate::types::sea::{ExecuteParams, ResultManifest, StatementState, StatementStatus}; use async_trait::async_trait; use std::collections::HashMap; use std::time::Duration; @@ -72,6 +72,17 @@ pub(crate) struct ExecuteResult { pub statement_id: String, pub reader: Box, pub manifest: Option, + /// Terminal state the server reported in its final response. + /// `Closed` means the server has already cleaned up the + /// statement on its end — the kernel must NOT issue a + /// separate `CloseStatement` for it (the server returns 404 + /// `STATEMENT_NOT_FOUND` on such redundant closes). This is + /// the common case when the kernel omits `wait_timeout` from + /// the execute request: the server holds the connection for + /// its default wait, returns inline data with `state=CLOSED`, + /// and is done. Setting a concrete `wait_timeout` yields + /// `Succeeded` instead and requires an explicit close. + pub server_state: StatementState, } impl std::fmt::Debug for ExecuteResult { @@ -80,6 +91,7 @@ impl std::fmt::Debug for ExecuteResult { .field("statement_id", &self.statement_id) .field("reader", &"") .field("manifest", &self.manifest) + .field("server_state", &self.server_state) .finish() } } diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 95549d8d..92f383b9 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -547,7 +547,7 @@ mod tests { use super::*; use crate::client::{ExecuteResult, SessionInfo}; use crate::reader::EmptyReader; - use crate::types::sea::ExecuteParams; + use crate::types::sea::{ExecuteParams, StatementState}; use arrow_schema::Schema; use std::collections::HashMap; use std::sync::Arc as StdArc; @@ -591,6 +591,7 @@ mod tests { statement_id: "mock-statement".to_string(), reader: Box::new(EmptyReader::new(StdArc::new(Schema::empty()))), manifest: None, + server_state: StatementState::Succeeded, }) } diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 2940df53..710029e9 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -56,18 +56,26 @@ pub struct ExecutedStatement { impl ExecutedStatement { /// Crate-internal constructor. Built by [`Statement::execute`]. + /// + /// `closed` is a shared flag — the parent [`Statement`] owns the + /// same `Arc` so that flipping `closed` here also short-circuits + /// the lifecycle-owner's `invalidate_prior` cleanup path. The + /// parent pre-sets the flag to `true` when the server returned + /// `state=CLOSED` in its execute response, so neither side fires + /// the redundant `CloseStatement` round-trip. pub(crate) fn new( session: Arc, statement_id: String, valid: ValidityFlag, result_stream: ResultStream, + closed: Arc, ) -> Self { Self { session, statement_id, valid, result_stream, - closed: Arc::new(AtomicBool::new(false)), + closed, } } @@ -139,8 +147,13 @@ impl ExecutedStatementHandle for ExecutedStatement { impl Drop for ExecutedStatement { fn drop(&mut self) { - // If close() already ran, nothing to do. - if self.closed.load(Ordering::Acquire) { + // `swap` (not `load`) so the shared `closed` flag — held by the + // parent `Statement::last_closed` — reflects that Drop is now + // handling cleanup. Without this, a `drop(executed) → execute() + // again` sequence would have `invalidate_prior` fire a redundant + // `CloseStatement` racing the one we're about to spawn. The + // server is idempotent so it's harmless, but a wasted RPC. + if self.closed.swap(true, Ordering::AcqRel) { return; } // Fire-and-forget CloseStatement. Drop must not panic and diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 35b90d36..5b1fdd9e 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -122,16 +122,24 @@ pub struct ExecutedAsyncStatement { impl ExecutedAsyncStatement { /// Crate-internal constructor. Built by [`Statement::submit`]. + /// + /// `closed` is shared with the parent [`Statement`] so flipping it + /// here also short-circuits the lifecycle-owner's + /// `invalidate_prior` cleanup path. The submit path always sends + /// `wait_timeout=0s`, so the server returns `Pending`/`Running` and + /// the flag starts `false`; the share-and-flip pattern still + /// applies once the caller (or `Drop`) closes either handle. pub(crate) fn new( session: Arc, statement_id: String, valid: ValidityFlag, + closed: Arc, ) -> Self { Self { session, statement_id, valid, - closed: Arc::new(AtomicBool::new(false)), + closed, } } @@ -373,7 +381,11 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { - if self.closed.load(Ordering::Acquire) { + // `swap` (not `load`) so the shared `closed` flag — held by the + // parent `Statement::last_closed` — reflects that Drop is now + // handling cleanup, preventing a duplicate `CloseStatement` + // from `invalidate_prior` on the next `execute()` / `submit()`. + if self.closed.swap(true, Ordering::AcqRel) { return; } // Fire-and-forget close on the session's runtime — mirrors diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 0bdd3107..46b8bb13 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -61,7 +61,8 @@ use crate::statement::executed_async::ExecutedAsyncStatement; use crate::statement::params::typed_value_to_sea_parameter; use crate::statement::spec::{ResultFormat, StatementSpec}; use crate::statement::validity::ValidityFlag; -use crate::types::sea::ExecuteParams; +use crate::types::sea::{ExecuteParams, StatementState}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tracing::warn; @@ -83,6 +84,13 @@ pub struct Statement { /// after `Drop`. See `validity::ValidityFlag` for the /// Acquire/Release contract. last_valid: Option, + /// `closed` flag shared with the most recent `ExecutedStatement`. + /// Pre-set to `true` when the server returned `state=CLOSED` in its + /// execute response (the inline-result fast path), and flipped to + /// `true` by `ExecutedStatement::close`. Lets `invalidate_prior` + /// skip the CancelStatement + CloseStatement round-trips when the + /// server side is already gone. + last_closed: Option>, } impl Statement { @@ -94,6 +102,7 @@ impl Statement { spec: StatementSpec::new(), last_statement_id: None, last_valid: None, + last_closed: None, } } @@ -108,9 +117,17 @@ impl Statement { &self.spec } - /// Wait-for-result execution. Sends ExecuteStatement with - /// `wait_timeout=10s`; the kernel polls internally if the server - /// does not finish in 10s. Returns when results are ready. + /// Wait-for-result execution. The kernel sends ExecuteStatement + /// **without** a `wait_timeout` field — the SEA server's + /// default behaviour is to hold the connection for up to 10s, + /// same wait as `wait_timeout=10s`, but it auto-closes the + /// statement on success and returns `state=CLOSED`. Setting + /// `wait_timeout=10s` explicitly returns `state=SUCCEEDED` + /// (statement still alive server-side, requires a separate + /// `CloseStatement`) and adds ~150–260ms to the response — + /// observed against Dogfood; see PR description for the bench + /// numbers. The kernel polls internally if the query needs + /// longer than 10s. /// /// If a prior executed handle is still tracked by this `Statement`, /// it is auto-cancelled and closed before issuing the new @@ -122,14 +139,14 @@ impl Statement { let _g = self.session.log_span().clone().entered(); self.invalidate_prior().await; - let (sql, exec_params) = self.prepare_for_dispatch("10s")?; + let (sql, exec_params) = self.prepare_for_dispatch(None)?; let cancel_state = MidExecuteCancelState::new(Arc::clone(&self.session)); let guard = cancel_state.guard(); // SeaRestTransport::execute_statement polls to completion - // (10s server-side wait_timeout, then GetStatementStatus - // loop until terminal). + // (server's default ~10s wait, then GetStatementStatus loop + // until terminal). let result = self .session .transport() @@ -140,8 +157,18 @@ impl Statement { guard.defuse(); let valid = ValidityFlag::new(); + // Only `Closed` triggers the short-circuit. `Succeeded` means + // the server still owns the statement and we must issue + // CloseStatement. `Failed` / `Canceled` are terminal but still + // server-side-tracked — also fall through to the standard close + // path. See `prepare_for_dispatch` for why omitting + // `wait_timeout` typically yields `Closed` on the inline-result + // fast path. + let already_closed = result.server_state == StatementState::Closed; + let closed = Arc::new(AtomicBool::new(already_closed)); self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); + self.last_closed = Some(Arc::clone(&closed)); let result_stream = ResultStream::from_reader(result.reader)?; Ok(ExecutedStatement::new( @@ -149,6 +176,7 @@ impl Statement { result.statement_id, valid, result_stream, + closed, )) } @@ -164,7 +192,7 @@ impl Statement { let _g = self.session.log_span().clone().entered(); self.invalidate_prior().await; - let (sql, exec_params) = self.prepare_for_dispatch("0s")?; + let (sql, exec_params) = self.prepare_for_dispatch(Some("0s"))?; let cancel_state = MidExecuteCancelState::new(Arc::clone(&self.session)); let guard = cancel_state.guard(); @@ -179,13 +207,19 @@ impl Statement { guard.defuse(); let valid = ValidityFlag::new(); + // submit path always uses wait_timeout=0s, so the server can't + // return CLOSED yet; start the flag false and let later close() + // calls flip it. + let closed = Arc::new(AtomicBool::new(false)); self.last_statement_id = Some(response.statement_id.clone()); self.last_valid = Some(valid.clone()); + self.last_closed = Some(Arc::clone(&closed)); Ok(ExecutedAsyncStatement::new( Arc::clone(&self.session), response.statement_id, valid, + closed, )) } @@ -224,9 +258,21 @@ impl Statement { /// Shared spec-validation + `ExecuteParams` builder used by both /// [`execute`](Self::execute) and [`submit`](Self::submit). /// - /// `wait_timeout_secs` is the textual SEA wait-timeout - /// (`"10s"` for sync, `"0s"` for async submit). - fn prepare_for_dispatch(&self, wait_timeout_secs: &str) -> Result<(String, ExecuteParams)> { + /// `wait_timeout_secs`: + /// - `Some("0s")` — async submit; server returns immediately. + /// - `None` — sync execute; omit the field so the server uses + /// its default wait (up to ~10s, auto-closes on success and + /// returns `state=CLOSED`). Setting `Some("10s")` explicitly + /// produces equivalent wait behaviour but the server then + /// returns `state=SUCCEEDED` (statement still alive) and is + /// ~150–260ms slower per request on Dogfood — verified by + /// probe. + /// - Other concrete values (e.g. `Some("5s")`) are valid for + /// callers that want explicit control. + fn prepare_for_dispatch( + &self, + wait_timeout_secs: Option<&str>, + ) -> Result<(String, ExecuteParams)> { let sql = self .spec .sql @@ -245,9 +291,13 @@ impl Statement { )); } + // `wait_timeout = None` means "omit the field"; the server + // applies its default (~10s wait + auto-close on success). + // `on_wait_timeout` only matters when wait_timeout is set, + // so mirror the presence. let mut exec_params = ExecuteParams { - wait_timeout: Some(wait_timeout_secs.to_string()), - on_wait_timeout: Some("CONTINUE".to_string()), + wait_timeout: wait_timeout_secs.map(|s| s.to_string()), + on_wait_timeout: wait_timeout_secs.map(|_| "CONTINUE".to_string()), ..ExecuteParams::default() }; for (i, value) in self.spec.positional_params.iter().enumerate() { @@ -266,7 +316,20 @@ impl Statement { if let Some(valid) = self.last_valid.take() { valid.invalidate(); } + // If the shared `closed` flag is already set, the server side + // is gone (either the server auto-closed on the inline-result + // fast path, or the caller already closed the executed + // handle). Flip it to claim the cleanup duty in case it + // wasn't set yet, and skip the round-trips. + let already_closed = self + .last_closed + .take() + .map(|f| f.swap(true, Ordering::AcqRel)) + .unwrap_or(false); if let Some(prior_id) = self.last_statement_id.take() { + if already_closed { + return; + } // Best-effort cancel + close. We don't await the cancel // separately — close is idempotent and the server // releases resources on close regardless of cancel