diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index ceec21c7..70a617e0 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -542,6 +542,19 @@ impl ExecutedAsyncStatement { .await? { Some(result) => { + // If the server already auto-closed the statement + // (`state == Closed`), pre-set the shared `closed` flag so + // this handle's `close()` / `Drop` — and `invalidate_prior` + // on the parent `Statement`'s next execute — skip the + // redundant `CloseStatement` DELETE (the server returns 404 + // STATEMENT_NOT_FOUND on it). Mirrors the sync `execute()` + // path's `already_closed` short-circuit (issue #168). This + // covers both `await_result()` and `fetch_result()`, which + // funnel through here. `Succeeded` leaves the statement + // server-side, so the flag stays as-is and the close fires. + if result.status.state == crate::types::sea::StatementState::Closed { + self.closed.store(true, Ordering::Release); + } let mut stream = ResultStream::from_reader(result.reader).await?; // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index d6ee5343..14cec455 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -237,6 +237,45 @@ fn closed_body(statement_id: &str) -> String { .to_string() } +/// Like [`succeeded_inline_body`] but reports `status.state == CLOSED`. +/// A statement that auto-closed server-side can surface `CLOSED` (with +/// inline results) from a polled `GetStatementStatus` on the async path; +/// the kernel must NOT then issue a redundant `CloseStatement` (DELETE) +/// on it. See issue #168. +fn closed_inline_body(statement_id: &str, batch: &RecordBatch) -> String { + succeeded_inline_body(statement_id, batch) + .replace(r#""state":"SUCCEEDED""#, r#""state":"CLOSED""#) +} + +/// Poll `server.received_requests()` until `expected` `DELETE`s to the +/// given statement endpoint are observed, or `timeout` elapses; returns +/// the final observed count. Mirrors the sync suite's helper: a negative +/// expectation (`expected == 0`) still gives an erroneously-spawned close +/// the full window to reach the wire but breaks early the instant one +/// appears, so the negative assertion stays reliably able to fail. +async fn wait_for_close_delete( + server: &MockServer, + statement_id: &str, + expected: usize, + timeout: std::time::Duration, +) -> usize { + let delete_path = format!("/api/2.0/sql/statements/{statement_id}"); + let deadline = tokio::time::Instant::now() + timeout; + loop { + let count = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| r.method == wiremock::http::Method::DELETE && r.url.path() == delete_path) + .count(); + if count >= expected.max(1) || tokio::time::Instant::now() >= deadline { + return count; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } +} + /// Mount a single `GetStatementStatus` (GET) response for `attach`'s /// seeding call. async fn mount_status_once(server: &MockServer, statement_id: &str, body: String) { @@ -1209,3 +1248,130 @@ async fn attached_handle_cancel_errors() { assert_eq!(cerr.code, ErrorCode::InvalidArgument, "got: {cerr:?}"); tokio::time::sleep(std::time::Duration::from_millis(100)).await; } + +// ─── CloseStatement / status.state==CLOSED handling (issue #168) ─── + +/// Regression for issue #168 on the ASYNC path: when `await_result()` +/// polls and observes a terminal `status.state == CLOSED` (a statement +/// that auto-closed server-side), the statement is already closed +/// server-side and the kernel must NOT issue a redundant +/// `DELETE /api/2.0/sql/statements/` (CloseStatement) on the handle's +/// `close()` / drop — matching the sync `execute()` path. +/// +/// The submit path starts the shared `closed` flag `false` (correct: +/// `wait_timeout=0s` can't return CLOSED on submit), but reaching CLOSED +/// via a later poll must flip it so the fire-and-forget close is skipped. +#[tokio::test] +async fn await_result_closed_status_skips_close_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let batch = int64_batch("n", vec![7]); + mount_submit(&server, pending_body("stmt-async-closed")).await; + // await_result polls RUNNING → CLOSED (with inline results). The final + // CLOSED body is also served to materialise_result's own status GET. + mount_status_sequence( + &server, + "stmt-async-closed", + vec![ + running_body("stmt-async-closed"), + closed_inline_body("stmt-async-closed", &batch), + ], + ) + .await; + + // Scoped expectation: NO DELETE on the statement endpoint. + let _no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-async-closed")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 7 AS n"); + let async_exec = stmt.submit().await.expect("submit"); + let mut stream = async_exec.await_result().await.expect("await_result"); + let batches = drain(&mut stream).await; + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 7 + ); + // An explicit close() on a CLOSED statement must also be a no-op. + async_exec.close().await.expect("close"); + // async_exec (and stmt) drop here — a redundant close guard fires now. + } + + // Give any (erroneously) spawned fire-and-forget close the full window to + // reach the wire, but break early the instant one appears. + let closes = wait_for_close_delete( + &server, + "stmt-async-closed", + 0, + std::time::Duration::from_millis(500), + ) + .await; + assert_eq!(closes, 0, "CLOSED status must not trigger CloseStatement"); + // `_no_close` also verifies expect(0) when it drops at end of scope. +} + +/// Regression-guard for the async CLOSED-skip fix: a SUCCEEDED async +/// result must STILL fire exactly one `CloseStatement` on close/drop — +/// the server still owns the statement. Guards against over-correcting +/// the CLOSED-skip into a server-statement leak. +#[tokio::test] +async fn await_result_succeeded_status_still_closes_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let batch = int64_batch("n", vec![7]); + mount_submit(&server, pending_body("stmt-async-succ")).await; + mount_status_sequence( + &server, + "stmt-async-succ", + vec![ + running_body("stmt-async-succ"), + succeeded_inline_body("stmt-async-succ", &batch), + ], + ) + .await; + + // Scoped expectation: exactly one DELETE on the statement endpoint. + let _close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-async-succ")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 7 AS n"); + let async_exec = stmt.submit().await.expect("submit"); + let mut stream = async_exec.await_result().await.expect("await_result"); + let _ = drain(&mut stream).await; + async_exec.close().await.expect("close"); + // async_exec drops here — the close guard must fire the DELETE. + } + + let closes = wait_for_close_delete( + &server, + "stmt-async-succ", + 1, + std::time::Duration::from_millis(2000), + ) + .await; + assert_eq!( + closes, 1, + "SUCCEEDED status must trigger exactly one CloseStatement" + ); + // `_close` also verifies expect(1) when it drops at end of scope. +} diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 237f0ece..5756c1ed 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -140,6 +140,16 @@ fn succeeded_inline_body(statement_id: &str, batch: &RecordBatch) -> String { .to_string() } +/// Like [`succeeded_inline_body`] but reports `status.state == CLOSED`. +/// This is the inline direct-result fast path (a quick `SELECT 1` where +/// the kernel omits `wait_timeout`): the server auto-closes the statement +/// and returns `CLOSED`, so the kernel must NOT issue a follow-up +/// `CloseStatement` (DELETE) on it. See issue #168 (CLOUDFETCH-013). +fn closed_inline_body(statement_id: &str, batch: &RecordBatch) -> String { + succeeded_inline_body(statement_id, batch) + .replace(r#""state":"SUCCEEDED""#, r#""state":"CLOSED""#) +} + fn running_body(statement_id: &str) -> String { json!({ "statement_id": statement_id, @@ -148,6 +158,37 @@ fn running_body(statement_id: &str) -> String { .to_string() } +/// Poll `server.received_requests()` until `expected` `DELETE`s to the +/// given statement endpoint are observed, or `timeout` elapses; returns +/// the final observed count. Mirrors the metadata suite's helper: for a +/// positive expectation it waits only as long as needed, and for a +/// negative expectation (`expected == 0`) it still gives an +/// erroneously-spawned close the full `timeout` to reach the wire but +/// breaks early the instant one appears, so the negative assertion stays +/// reliably able to fail under CI load. +async fn wait_for_close_delete( + server: &MockServer, + statement_id: &str, + expected: usize, + timeout: std::time::Duration, +) -> usize { + let delete_path = format!("/api/2.0/sql/statements/{statement_id}"); + let deadline = tokio::time::Instant::now() + timeout; + loop { + let count = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| r.method == wiremock::http::Method::DELETE && r.url.path() == delete_path) + .count(); + if count >= expected.max(1) || tokio::time::Instant::now() >= deadline { + return count; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } +} + fn failed_body(statement_id: &str, message: &str, sql_state: &str) -> String { json!({ "statement_id": statement_id, @@ -1017,3 +1058,106 @@ async fn execute_cloudfetch_chunk0_failure_closes_statement() { .collect::>(), ); } + +// ─── CloseStatement / status.state==CLOSED handling (issue #168) ─── + +/// Regression for issue #168 (extended by CLOUDFETCH-013): when the +/// `ExecuteStatement` response for a *regular* query already reports +/// `status.state == CLOSED` (a `SELECT 1` delivered inline via direct +/// results, where the server auto-closes and returns `CLOSED`), the +/// statement is closed server-side and the kernel must NOT issue a +/// redundant `DELETE /api/2.0/sql/statements/` (CloseStatement) on +/// `ExecutedStatement::close()` or on drop. Mirrors the metadata suite's +/// `metadata_closed_response_skips_close_statement`. +#[tokio::test] +async fn execute_closed_inline_skips_close_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let batch = int64_batch("n", vec![1]); + // Inline result with status.state == CLOSED — server already closed it. + mount_execute(&server, closed_inline_body("stmt-closed", &batch)).await; + + // Scoped expectation: NO DELETE on the statement endpoint. + let _no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-closed")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt.execute().await.expect("execute"); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 1); + // An explicit close() on a CLOSED statement must also be a no-op. + exec.close().await.expect("close"); + // exec (and stmt) drop here — a redundant close guard would fire now. + } + + // Give any (erroneously) spawned fire-and-forget close the full window to + // reach the wire, but break early the instant one appears so the negative + // assertion stays reliably able to fail under CI load. + let closes = wait_for_close_delete( + &server, + "stmt-closed", + 0, + std::time::Duration::from_millis(500), + ) + .await; + assert_eq!(closes, 0, "CLOSED response must not trigger CloseStatement"); + // `_no_close` also verifies expect(0) when it drops at end of scope. +} + +/// Regression-guard for issue #168's fix on the regular-query path: when +/// the `ExecuteStatement` response reports a non-CLOSED terminal state +/// (`SUCCEEDED`), the server still owns the statement, so the kernel MUST +/// still issue exactly one `CloseStatement` (DELETE) on close/drop. Ensures +/// the CLOSED-skip does not over-correct and leak a live server statement. +#[tokio::test] +async fn execute_succeeded_inline_still_closes_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let batch = int64_batch("n", vec![1]); + // Inline result with status.state == SUCCEEDED — server still owns it. + mount_execute(&server, succeeded_inline_body("stmt-succeeded", &batch)).await; + + // Scoped expectation: exactly one DELETE on the statement endpoint. + let _close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-succeeded")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt.execute().await.expect("execute"); + let _ = drain(exec.result_stream_mut()).await; + exec.close().await.expect("close"); + // exec drops here — the close guard must fire the DELETE. + } + + // Poll until the fire-and-forget close hits the wire (bounded by a + // timeout) rather than assuming it lands within a fixed sleep. + let closes = wait_for_close_delete( + &server, + "stmt-succeeded", + 1, + std::time::Duration::from_millis(2000), + ) + .await; + assert_eq!( + closes, 1, + "SUCCEEDED response must trigger exactly one CloseStatement" + ); + // `_close` also verifies expect(1) when it drops at end of scope. +}