Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions napi/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,8 +486,10 @@ impl Statement {
guard.take()
};
match inner_state {
Some(AnyInner::Executed(s)) => {
s.executed.close().await.map_err(napi_err_from_kernel)?;
Some(AnyInner::Executed(mut s)) => {
ExecutedStatement::close(&mut s.executed)
.await
.map_err(napi_err_from_kernel)?;
// _parent drops here, after close has resolved.
}
// Metadata stream: just drop it.
Expand Down
2 changes: 1 addition & 1 deletion pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ impl ExecutedStatement {
return Ok(());
};
let runtime = inner.runtime.clone();
let res = run_kernel!(py, runtime, inner.exec.close());
let res = run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec));
// Drop the kernel handle regardless of close() outcome — the
// kernel's Drop impl runs fire-and-forget cleanup if close()
// failed mid-flight.
Expand Down
7 changes: 7 additions & 0 deletions src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,13 @@ impl ResultStream {
self.reader.as_ref().and_then(|reader| reader.metrics())
}

pub(crate) fn finish_telemetry(&mut self) {
let metrics = self.reader_metrics();
if let Some(telemetry) = &mut self.telemetry {
telemetry.finish(metrics, None, false);
}
}

/// Finalize telemetry once, passing the reader's terminal metrics.
/// `reader` and `telemetry` are disjoint fields, so this borrows
/// cleanly under `&mut self`. `ResultStreamTelemetry::finish` is
Expand Down
44 changes: 44 additions & 0 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2273,6 +2273,50 @@ mod is_open_tests {
);
}

#[tokio::test]
async fn statement_close_after_partial_fetch_exports_terminal_statement_event() {
let server = MockServer::start().await;
mount_session_create_delete(&server, "sess-telemetry-stmt-partial-close").await;
mount_close_any_statement(&server).await;
mount_execute(
&server,
succeeded_inline_body("stmt-telemetry-partial-close", &int64_batch("n", vec![1])),
)
.await;
let exporter = CapturingTelemetryExporter::default();
let telemetry = TelemetryConfig {
enabled: true,
..Default::default()
}
.with_exporter(std::sync::Arc::new(exporter.clone()));
let session =
telemetry_test_session(&server, "sess-telemetry-stmt-partial-close", telemetry).await;

let mut stmt = session.statement();
stmt.spec().sql("SELECT 1 AS n");
let mut exec = stmt.execute().await.expect("execute succeeds");
assert!(exec.next_batch().await.expect("first batch").is_some());
exec.close().await.expect("statement close succeeds");
session.close().await.expect("close succeeds");

let statement_logs = exported_logs(&exporter)
.into_iter()
.filter(|log| operation_type(log) == Some("EXECUTE_STATEMENT"))
.collect::<Vec<_>>();
assert_eq!(
statement_logs.len(),
1,
"partial close should emit exactly one statement telemetry event"
);
let sql_log = &statement_logs[0]["entry"]["sql_driver_log"];
assert_eq!(sql_log["sql_statement_id"], "stmt-telemetry-partial-close");
assert_eq!(sql_log["sql_operation"]["execution_result"], "INLINE_ARROW");
assert!(
sql_log["sql_operation"]["result_latency"].is_object(),
"partial close should record result latency"
);
}

#[tokio::test]
async fn statement_execute_failure_exports_sanitized_error_without_sql_text() {
let server = MockServer::start().await;
Expand Down
68 changes: 41 additions & 27 deletions src/statement/executed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,46 @@ impl ExecutedStatement {
Ok(None)
}

/// Explicit close for concrete sync statements.
///
/// This finalizes result-stream telemetry before the server-side
/// `CloseStatement` RPC so partial-result closes emit the same terminal

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — ExecutedStatement now has two identically-named close methods with divergent behavior: the inherent close(&mut self) (this line) finalizes result-stream telemetry before CloseStatement, while the trait impl ExecutedStatementHandle::close(&self) (executed.rs:339) only calls close_server_statement() and relies on drop-time finalization. Method resolution silently picks one based on the receiver's mutability/import context — which is exactly why the pyo3/napi call sites had to be rewritten to fully-qualified Type::close(&mut ...) form to hit the finalizing path.

This is a maintenance footgun: a future caller that acquires the handle behind the trait object (or an &self binding) will get the non-finalizing path and lose the "terminal statement event emitted before close" guarantee this PR establishes — the event would still fire at Drop, but the ordering/timing contract in the inherent method's doc comment would be quietly broken. Consider a doc note on the trait impl pointing at the inherent method, or (better) unifying so both paths finalize telemetry. Not a correctness bug today since Drop backstops finalization and the two shipped call sites are correct.

/// statement event as full result exhaustion.
pub async fn close(&mut self) -> Result<()> {
self.result_stream.finish_telemetry();
self.close_server_statement().await
}

async fn close_server_statement(&self) -> Result<()> {
// Idempotent on success: a prior successful close sets
// `closed=true` and subsequent calls short-circuit.
//
// On wire failure we deliberately keep `closed=false` so that
// `Drop`'s fire-and-forget retry path runs as a fallback —
// otherwise a transient close failure would silently leak the
// server-side statement until session expiry. Mirrors
// `Session::close`.
//
// The `&self` signature allows two callers to race and both
// hit the wire. The server-side close is idempotent (it
// returns the same Ok for duplicate close_statement calls),
// so the only cost of the race is one redundant RPC — far
// better than dropping the retry contract.
async {
if self.closed.load(Ordering::Acquire) {
return Ok(());
}
self.session
.transport()
.close_statement(&self.statement_id)
.await?;
self.closed.store(true, Ordering::Release);
Ok(())
}
.instrument(self.session.log_span().clone())
.await
}

/// Spawn a fire-and-forget `CloseStatement` unless the statement is
/// already closed (`closed` flag). Shared by [`Self::next_batch`]'s
/// auto-close-on-drain and `Drop`. The `swap` makes whichever fires
Expand Down Expand Up @@ -297,33 +337,7 @@ impl ExecutedStatementHandle for ExecutedStatement {
}

async fn close(&self) -> Result<()> {
// Idempotent on success: a prior successful close sets
// `closed=true` and subsequent calls short-circuit.
//
// On wire failure we deliberately keep `closed=false` so that
// `Drop`'s fire-and-forget retry path runs as a fallback —
// otherwise a transient close failure would silently leak the
// server-side statement until session expiry. Mirrors
// `Session::close`.
//
// The `&self` signature allows two callers to race and both
// hit the wire. The server-side close is idempotent (it
// returns the same Ok for duplicate close_statement calls),
// so the only cost of the race is one redundant RPC — far
// better than dropping the retry contract.
async {
if self.closed.load(Ordering::Acquire) {
return Ok(());
}
self.session
.transport()
.close_statement(&self.statement_id)
.await?;
self.closed.store(true, Ordering::Release);
Ok(())
}
.instrument(self.session.log_span().clone())
.await
self.close_server_statement().await

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The new inherent ExecutedStatement::close(&mut self) finalizes result-stream telemetry (finish_telemetry()) before the server close, but the trait method ExecutedStatementHandle::close(&self) only calls close_server_statement() — it structurally cannot finalize telemetry (it takes &self, while ResultStream::finish_telemetry needs &mut self).

The two in-tree explicit-close call sites (PyO3, NAPI) now route through the concrete &mut path, so they're fixed. But ExecutedStatementHandle is re-exported publicly (lib.rs:146), so a Rust consumer closing via Arc<dyn ExecutedStatementHandle> still gets the pre-fix behavior: the terminal EXECUTE_STATEMENT event is deferred to drop-time finalization rather than emitted on explicit close — exactly the reliability gap this PR closes for the binding paths.

Not a regression (the trait method's behavior is unchanged) and drop-time finalization remains a backstop, so severity is low. Worth a doc note on the trait close pointing callers who want the explicit-close telemetry guarantee at the concrete &mut close, so the divergence isn't a silent footgun.

(Anchored to the nearest changed line — see the description for the exact location.)

}
}

Expand Down
Loading