Skip to content

Commit edd3680

Browse files
grahamcclaude
andcommitted
fix(tracing): keep postgres.run span open across row fetch
Review finding #1: postgres.run used `#[tracing::instrument]`, whose span closed as soon as `run()` returned the result stream, so it covered only query setup (bind/execute/flush) and not the row fetching that dominates query latency. Create the span explicitly and attach it to the returned stream via `instrument_stream` so it stays entered while rows are received. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 6958f46 commit edd3680

1 file changed

Lines changed: 14 additions & 12 deletions

File tree

sqlx-postgres/src/connection/executor.rs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use futures_core::stream::BoxStream;
1616
use futures_core::Stream;
1717
use futures_util::TryStreamExt;
1818
use sqlx_core::arguments::Arguments;
19+
use sqlx_core::instrument_stream::InstrumentStream;
1920
use sqlx_core::sql_str::SqlStr;
2021
use sqlx_core::Either;
2122
use std::{pin::pin, sync::Arc};
@@ -210,24 +211,24 @@ impl PgConnection {
210211
Ok(statement)
211212
}
212213

213-
#[tracing::instrument(
214-
target = "sqlx::query",
215-
name = "postgres.run",
216-
skip_all,
217-
fields(
218-
db.system = "postgresql",
219-
db.operation.parameters = arguments.as_ref().map_or(0, |a| a.len()),
220-
db.postgresql.prepared = arguments.is_some(),
221-
),
222-
level = "debug",
223-
)]
224214
pub(crate) async fn run<'e, 'c: 'e, 'q: 'e>(
225215
&'c mut self,
226216
query: SqlStr,
227217
arguments: Option<PgArguments>,
228218
persistent: bool,
229219
metadata_opt: Option<Arc<PgStatementMetadata>>,
230220
) -> Result<impl Stream<Item = Result<Either<PgQueryResult, PgRow>, Error>> + 'e, Error> {
221+
// The span is attached to the returned stream (see `instrument_stream`)
222+
// rather than via `#[tracing::instrument]` so it stays open while rows
223+
// are fetched, not just while the query is set up.
224+
let span = tracing::debug_span!(
225+
target: "sqlx::query",
226+
"postgres.run",
227+
db.system = "postgresql",
228+
db.operation.parameters = arguments.as_ref().map_or(0, |a| a.len()),
229+
db.postgresql.prepared = arguments.is_some(),
230+
);
231+
231232
let mut logger = QueryLogger::new(query, self.inner.log_settings.clone());
232233
let sql = logger.sql().as_str();
233234

@@ -397,7 +398,8 @@ impl PgConnection {
397398
}
398399

399400
Ok(())
400-
})
401+
}
402+
.instrument_stream(span))
401403
}
402404
}
403405

0 commit comments

Comments
 (0)