diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index c33288b5..9cca274a 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -80,6 +80,7 @@ //! the `await`); the lifetime never leaks into a stored type. See //! addendum A2 for the rationale. +use crate::client::transport::ExecuteResult; use crate::kernel_error::{Error, Result}; use crate::metadata::sql::{LikeMatcher, SqlCommandBuilder}; use crate::metadata::static_data; @@ -90,11 +91,31 @@ use crate::metadata::thrift_shape::{ use crate::reader::{EmptyReader, InMemoryReader}; use crate::result_stream::{ResultBatch, ResultStream}; use crate::session::SessionInner; +use crate::types::sea::StatementState; use arrow_array::Array; use arrow_schema::SchemaRef; use std::sync::Arc; use tracing::{debug, Instrument}; +/// The statement id to hand to +/// [`ResultStream::from_reader_with_close`] as the close target. +/// +/// When the `ExecuteStatement` response already reported +/// `status.state == Closed`, the server has already cleaned up the +/// statement server-side, so a follow-up `CloseStatement` DELETE is +/// redundant (the server returns 404 `STATEMENT_NOT_FOUND`). In that +/// case return an empty id so `from_reader_with_close` installs no +/// close guard — mirroring the regular-query path in +/// `statement/mutable.rs`. Otherwise return the real id so the +/// server statement is reaped when the stream is dropped. +fn close_id(raw: &ExecuteResult) -> String { + if raw.status.state == StatementState::Closed { + String::new() + } else { + raw.statement_id.clone() + } +} + /// JDBC's `DatabaseMetaData` contract: metadata methods return an /// empty result set for non-existent catalogs / schemas / tables /// rather than raising. Translate `is_object_not_found` errors into @@ -295,7 +316,7 @@ impl Metadata { .transport() .list_catalogs(self.session.session_id()) .await?; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); let reshaped = ThriftReshapingReader::new( raw.reader, GET_CATALOGS_SCHEMA.clone(), @@ -339,7 +360,7 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_SCHEMAS_SCHEMA.clone(), Err).await, }; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); let reshaped = ThriftReshapingReader::new( raw.reader, GET_SCHEMAS_SCHEMA.clone(), @@ -641,7 +662,13 @@ impl Metadata { // `ExecuteResult` has no Drop-based close, so a mid-stream read // error must still close this statement or it leaks server-side // (unlike the streaming paths, which close via a StatementCloseGuard). - let stmt_id = raw.statement_id.clone(); + // + // `close_id` returns an empty id when the server already reported + // `status.state == Closed` (statement reaped server-side); skip the + // redundant CloseStatement DELETE in that case, mirroring the + // streaming metadata paths and the regular-query path in + // `statement/mutable.rs`. + let stmt_id = close_id(&raw); let mut reader = raw.reader; let read: Result> = async { let mut out = Vec::new(); @@ -655,12 +682,15 @@ impl Metadata { Ok(out) } .await; - // Best-effort close on every exit (success or error). - self.session - .transport() - .close_statement(&stmt_id) - .await - .ok(); + // Best-effort close on every exit (success or error), unless the + // statement was already closed server-side. + if !stmt_id.is_empty() { + self.session + .transport() + .close_statement(&stmt_id) + .await + .ok(); + } read } @@ -692,7 +722,7 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_TABLES_SCHEMA.clone(), Err).await, }; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); let reshaped = ThriftReshapingReader::new( raw.reader, GET_TABLES_SCHEMA.clone(), @@ -756,7 +786,7 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_COLUMNS_SCHEMA.clone(), Err).await, }; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); let reshaped = ThriftReshapingReader::new( raw.reader, GET_COLUMNS_SCHEMA.clone(), @@ -818,7 +848,7 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_PRIMARY_KEYS_SCHEMA.clone(), Err).await, }; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); let reshaped = ThriftReshapingReader::new( raw.reader, GET_PRIMARY_KEYS_SCHEMA.clone(), @@ -889,7 +919,7 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_CROSS_REFERENCE_SCHEMA.clone(), Err).await, }; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); let reshaped = ThriftReshapingReader::new( raw.reader, GET_CROSS_REFERENCE_SCHEMA.clone(), @@ -930,7 +960,7 @@ impl Metadata { name_pattern.as_ref().map(|p| p.as_str()), ) .await?; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) .await } @@ -961,7 +991,7 @@ impl Metadata { name_pattern.as_ref().map(|p| p.as_str()), ) .await?; - let stmt_id = raw.statement_id.clone(); + let stmt_id = close_id(&raw); ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) .await } diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 99eafcf6..1668c5f3 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -173,6 +173,29 @@ async fn mount_execute_expecting_sql(server: &MockServer, sql_substr: &str, body .await; } +/// Like [`succeeded_inline_response_body`] but reports +/// `status.state == CLOSED`. This is the common inline/direct-result +/// case for metadata `SHOW …` queries: the server auto-closes the +/// statement and returns `CLOSED`, so the kernel must NOT issue a +/// follow-up `CloseStatement` (DELETE) on it. +fn closed_inline_response_body(batch: &RecordBatch) -> String { + succeeded_inline_response_body(batch).replace(r#""state":"SUCCEEDED""#, r#""state":"CLOSED""#) +} + +/// Like [`succeeded_inline_response_body`] but with a caller-chosen +/// `statement_id` and `status.state`. Used by the wildcard fan-out +/// CLOSED-skip test, which stubs several statements in one call and must +/// distinguish the `SHOW CATALOGS` statement from each per-catalog +/// `SHOW TABLES` statement by id when asserting on DELETEs. +fn inline_response_body_with(batch: &RecordBatch, statement_id: &str, state: &str) -> String { + succeeded_inline_response_body(batch) + .replace( + r#""statement_id":"stmt-test""#, + &format!(r#""statement_id":"{statement_id}""#), + ) + .replace(r#""state":"SUCCEEDED""#, &format!(r#""state":"{state}""#)) +} + fn string_batch(cols: Vec<(&str, Vec>)>) -> RecordBatch { let fields: Vec = cols .iter() @@ -222,6 +245,40 @@ fn col_names(schema: &arrow_schema::Schema) -> Vec { schema.fields().iter().map(|f| f.name().clone()).collect() } +/// Poll `server.received_requests()` until `expected` `DELETE`s to the +/// `stmt-test` statement endpoint are observed, or `timeout` elapses; +/// returns the final observed count. This replaces a bare `sleep` when +/// asserting on the fire-and-forget `StatementCloseGuard`: for a positive +/// expectation it waits only as long as needed (so a close delayed past a +/// fixed window can't flake the test), 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, + expected: usize, + timeout: std::time::Duration, +) -> usize { + let deadline = tokio::time::Instant::now() + timeout; + loop { + let count = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| { + r.method.as_str() == "DELETE" && r.url.path() == "/api/2.0/sql/statements/stmt-test" + }) + .count(); + // Positive expectation met, or a spurious DELETE already appeared for a + // negative expectation — either way there is nothing more to wait for. + if count >= expected.max(1) || tokio::time::Instant::now() >= deadline { + return count; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } +} + // ─── Thrift-shape reshape tests ───────────────────────────────────── #[tokio::test] @@ -1143,3 +1200,238 @@ async fn identifier_validation_propagates_invalid_argument() { let err = LikePattern::new("with\0nul").expect_err("NUL byte rejected"); assert_eq!(err.code, ErrorCode::InvalidArgument); } + +// ─── CloseStatement / status.state==CLOSED handling (issue #168) ─── + +/// Regression for issue #168: when the `ExecuteStatement` response for a +/// metadata query already reports `status.state == CLOSED`, the statement +/// is closed server-side and the kernel must NOT issue a redundant +/// `DELETE /api/2.0/sql/statements/` (CloseStatement) on it — matching +/// the regular-query path. Before the fix, the metadata path always +/// installs a `StatementCloseGuard`, firing the redundant DELETE on stream +/// drop. +#[tokio::test] +async fn metadata_closed_response_skips_close_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let raw = string_batch(vec![("catalog", vec![Some("main")])]); + // Inline result with status.state == CLOSED — server already closed it. + mount_execute(&server, closed_inline_response_body(&raw)).await; + + // Scoped expectation: NO DELETE on the statement endpoint. + let _no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-test")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stream = session + .metadata() + .list_catalogs() + .await + .expect("list_catalogs"); + let _ = drain_stream(&mut stream).await; + // stream drops 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, 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: when the metadata +/// `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 stream drop. This +/// ensures the CLOSED-skip does not over-correct and reintroduce the +/// server-statement leak that `from_reader_with_close` guards against. +#[tokio::test] +async fn metadata_succeeded_response_still_closes_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let raw = string_batch(vec![("catalog", vec![Some("main")])]); + // Inline result with status.state == SUCCEEDED — server still owns it. + mount_execute(&server, succeeded_inline_response_body(&raw)).await; + + // Scoped expectation: exactly one DELETE on the statement endpoint. + let _close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-test")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stream = session + .metadata() + .list_catalogs() + .await + .expect("list_catalogs"); + let _ = drain_stream(&mut stream).await; + // stream 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 — a close + // delayed under CI load must not flake this positive assertion. + let closes = wait_for_close_delete(&server, 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. +} + +/// Same CLOSED-skip guarantee as +/// [`metadata_closed_response_skips_close_statement`], but exercised +/// through `list_tables()` rather than `list_catalogs()`. Unlike +/// `list_catalogs` (which takes the no-error early-`?` path), the other +/// metadata methods route the transport result through a +/// `match { Ok(r) => r, Err(e) => return not_found_or(...) }` before +/// reaching the shared `close_id` reshape. This test guards that more +/// common code shape so a future refactor that reorders the +/// `close_id`/reshape sequence on a `match`-branch method still gets +/// caught. +#[tokio::test] +async fn metadata_closed_response_skips_close_statement_on_match_branch() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let raw = string_batch(vec![ + ("namespace", vec![Some("default")]), + ("tableName", vec![Some("t1")]), + ("catalogName", vec![Some("main")]), + ("tableType", vec![Some("TABLE")]), + ]); + // Inline result with status.state == CLOSED — server already closed it. + mount_execute(&server, closed_inline_response_body(&raw)).await; + + // Scoped expectation: NO DELETE on the statement endpoint. + let _no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-test")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stream = session + .metadata() + .list_tables(None, None, None, None) + .await + .expect("list_tables"); + let _ = drain_stream(&mut stream).await; + // stream drops 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, 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. +} + +/// Same CLOSED-skip guarantee as +/// [`metadata_closed_response_skips_close_statement`], but for the +/// wildcard-catalog fan-out path +/// (`list_tables_matching_catalogs` → `fetch_tables_for_catalog`). That +/// site does NOT delegate to `from_reader_with_close`; it opens one +/// statement per catalog, computes `close_id(&raw)` (empty when the +/// server already reported `CLOSED`), and only fires an explicit +/// `close_statement()` when the id is non-empty. A wildcard pattern +/// (`comp_%`) is required to reach it — the other CLOSED-skip tests drive +/// `list_catalogs()` / `list_tables(None, …)`, which never enter the +/// fan-out. Stub `SHOW CATALOGS` + a per-catalog `SHOW TABLES` that both +/// return `state == CLOSED`, and assert zero DELETEs on the per-catalog +/// statement, so a future refactor of the bespoke `if !stmt_id.is_empty()` +/// guard that reintroduces the redundant close is caught here. +#[tokio::test] +async fn metadata_closed_response_skips_close_on_wildcard_fanout() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + // `SHOW CATALOGS` → one matching catalog, returned CLOSED. + let catalogs = string_batch(vec![("catalog", vec![Some("comp_a")])]); + mount_execute_expecting_sql( + &server, + "SHOW CATALOGS", + inline_response_body_with(&catalogs, "stmt-catalogs", "CLOSED"), + ) + .await; + + // Per-catalog `SHOW TABLES IN CATALOG comp_a`, also returned CLOSED so + // the fan-out's `close_id` yields an empty id and the explicit + // `close_statement()` must be skipped. + let tables = string_batch(vec![ + ("namespace", vec![Some("s")]), + ("tableName", vec![Some("t_a")]), + ("catalogName", vec![Some("comp_a")]), + ("tableType", vec![Some("TABLE")]), + ]); + mount_execute_expecting_sql( + &server, + "IN CATALOG `comp_a`", + inline_response_body_with(&tables, "stmt-tables-comp-a", "CLOSED"), + ) + .await; + + // Scoped expectation: NO DELETE on the per-catalog statement endpoint. + // This is the statement with the distinct close logic; the bespoke + // guard must not fire a redundant CloseStatement on it. + let _no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-tables-comp-a")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stream = session + .metadata() + .list_tables(Some(LikePattern::new("comp_%").unwrap()), None, None, None) + .await + .expect("list_tables wildcard catalog"); + let batches = drain_stream(&mut stream).await; + // Sanity: the fan-out actually produced the comp_a row (i.e. we + // exercised `fetch_tables_for_catalog`, not an empty short-circuit). + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); + } + + // Give any (erroneously) spawned fire-and-forget close the full window + // to reach the wire, but break early the instant one appears. + let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(500); + loop { + let closes = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| { + r.method.as_str() == "DELETE" + && r.url.path() == "/api/2.0/sql/statements/stmt-tables-comp-a" + }) + .count(); + assert_eq!( + closes, 0, + "CLOSED per-catalog statement must not trigger CloseStatement" + ); + if tokio::time::Instant::now() >= deadline { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + // `_no_close` also verifies expect(0) when it drops at end of scope. +}