Skip to content
Closed
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
95 changes: 94 additions & 1 deletion src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1859,8 +1859,10 @@ mod is_open_tests {
use serde_json::Value;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use wiremock::matchers::{method, path, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};

/// `Session::is_open` reports true for a freshly-opened session and
/// false once its server-side delete has been initiated. This is the
Expand Down Expand Up @@ -2398,6 +2400,97 @@ mod is_open_tests {
);
}

#[tokio::test]
async fn async_statement_retryable_status_error_then_success_exports_one_success_event() {
let server = MockServer::start().await;
mount_session_create_delete(&server, "sess-telemetry-transient-status").await;
mount_close_any_statement(&server).await;
mount_execute(&server, running_body("stmt-telemetry-transient-status")).await;

let status_calls = Arc::new(AtomicUsize::new(0));
let status_calls_for_mock = Arc::clone(&status_calls);
Mock::given(method("GET"))
.and(path(
"/api/2.0/sql/statements/stmt-telemetry-transient-status",
))
.respond_with(move |_request: &Request| {
if status_calls_for_mock.fetch_add(1, Ordering::SeqCst) == 0 {
ResponseTemplate::new(503).set_body_string(
r#"{"error_code":"TEMPORARILY_UNAVAILABLE","message":"retry status"}"#,
)
} else {
ResponseTemplate::new(200).set_body_string(succeeded_inline_body(
"stmt-telemetry-transient-status",
&int64_batch("n", vec![1]),
))
}
})
.mount(&server)
.await;

let exporter = CapturingTelemetryExporter::default();
let telemetry = TelemetryConfig {
enabled: true,
..Default::default()
}
.with_exporter(std::sync::Arc::new(exporter.clone()));
let http = HttpConfig {
retry_max_retries: 0,
..Default::default()
};
let session = Session::builder()
.connection(
ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh")
.expect("valid http_path"),
)
.auth(AuthConfig::Pat {
token: "dapi_test_token".into(),
identity_federation_client_id: None,
})
.http(http)
.telemetry(telemetry)
.open()
.await
.expect("session must open");

let mut stmt = session.statement();
stmt.spec().sql("SELECT 1 AS n");
let async_exec = stmt.submit().await.expect("submit succeeds");
let err = async_exec
.status()
.await
.expect_err("first status should surface transient RPC failure");
assert!(err.retryable, "status error should be retryable: {err}");

let status = async_exec.status().await.expect("retry status succeeds");
assert!(
matches!(status, crate::statement::StatementStatus::Succeeded),
"retry should observe terminal success"
);
let mut stream = async_exec.fetch_result().await.expect("fetch succeeds");
while stream.next_batch().await.expect("drain result").is_some() {}
session.close().await.expect("close succeeds");

let async_statement_logs = exported_logs(&exporter)
.into_iter()
.filter(|log| operation_type(log) == Some("EXECUTE_STATEMENT_ASYNC"))
.collect::<Vec<_>>();
assert_eq!(
async_statement_logs.len(),
1,
"transient status failure plus successful retry should export one terminal event"
);
let sql_log = &async_statement_logs[0]["entry"]["sql_driver_log"];
assert_eq!(
sql_log["sql_statement_id"],
"stmt-telemetry-transient-status"
);
assert!(
sql_log.get("error_info").is_none(),
"retryable polling failure must not consume the terminal telemetry event"
);
}

#[tokio::test]
async fn async_statement_status_failure_exports_error_telemetry() {
let server = MockServer::start().await;
Expand Down
35 changes: 33 additions & 2 deletions src/statement/executed_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,14 @@ impl ExecutedAsyncStatement {
crate::kernel_error::carry_extended_status(error, status)
}

fn should_finalize_poll_error(error: &Error) -> bool {
// A retryable status RPC failure is not a terminal statement
// outcome. Surface it to the caller, but leave telemetry open
// so a later poll/fetch can still emit the actual terminal
// statement result.
!error.retryable
}

/// One-shot status check. Non-blocking. Issues a single
/// GetStatementStatus RPC. Returns `Err(InvalidStatementHandle)`
/// locally — without hitting the wire — if the parent `Statement`
Expand Down Expand Up @@ -417,6 +425,9 @@ impl ExecutedAsyncStatement {
.instrument(span)
.await;
if let Err(error) = &result {
if !Self::should_finalize_poll_error(error) {

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 — Leaving telemetry open on a retryable poll error changes the telemetry outcome for an abandoned statement from error to success.

Before this PR, a caller that polled status() (or await_result()), received a retryable RPC error, and then gave up (dropped the handle without a successful retry) produced a terminal telemetry event carrying that error (finalize(Some(error))). After this change, the retryable branch returns early without finalizing, so the only finalize that runs is Drop's fallback self.statement_telemetry.finalize(None) — which emits a success event for a statement that never completed for this client.

This is consistent with the existing "submit-and-drop emits success" convention in Drop, so it may be acceptable, but it does mean a statement abandoned mid-poll due to transient failures is now reported as a successful async statement operation. Worth confirming that's the intended telemetry semantics — if not, the abandoned-after-retryable case would need to distinguish "never reached terminal" from "succeeded" at drop time.

return result;
}
self.statement_telemetry.finalize(Some(error));
}
result
Expand Down Expand Up @@ -444,6 +455,7 @@ impl ExecutedAsyncStatement {
/// server-side cancel; attached read-only handles do not cancel.
pub async fn await_result(&self) -> Result<ResultStream> {
let span = self.session.log_span().clone();
let mut retryable_poll_error = false;
let result = async {
self.valid.check()?;

Expand Down Expand Up @@ -477,11 +489,27 @@ impl ExecutedAsyncStatement {
loop {
self.valid.check()?;
let status_started = std::time::Instant::now();
let response = self
let response = match self
.session
.transport()
.statement_status(&self.statement_id)
.await?;
.await
{
Ok(response) => response,
Err(error) => {
retryable_poll_error = error.retryable;
if retryable_poll_error {
// Returning a retryable poll RPC error is
// not caller abandonment; keep the server
// query alive so the caller can retry and
// eventually fetch the real terminal result.
if let Some(g) = cancel_guard.take() {
g.defuse();
}
}
return Err(error);
}
};
self.statement_telemetry
.record_poll(status_started.elapsed());
// Cache the wire status so the extended-field
Expand Down Expand Up @@ -544,6 +572,9 @@ impl ExecutedAsyncStatement {
.instrument(span)
.await;
if let Err(error) = &result {
if retryable_poll_error && !Self::should_finalize_poll_error(error) {
return result;
}
self.statement_telemetry.finalize(Some(error));
}
result
Expand Down
Loading