Skip to content

perf(db): jitter pool connection retirement; configurable reader floor and lifetime - #10047

Merged
TheSentinel454 merged 10 commits into
mainfrom
jemiah/db-pool-lifetime-jitter
Dec 1, 2026
Merged

TheSentinel454 merged 10 commits into
mainfrom
jemiah/db-pool-lifetime-jitter

Conversation

@jemiahw

@jemiahw jemiahw commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Why

sqlx 0.9 retires a pool connection once it outlives one fixed max_lifetime, which is 300 s here, hard-coded for the writer and reader pools. A load burst makes every relay pod open many connections within the same few seconds. With a fixed lifetime, those connections then all close within the same few seconds. If load comes back after that, the pod re-dials the whole cohort on the request path (TCP + TLS + SCRAM for each connection). Pool metrics show this as a sawtooth in database connections: a burst, a plateau lasting exactly max_lifetime, then a cliff.

Scope. Jitter spreads retirement at release time while traffic is running, so a burst's cohort doesn't close in one cliff at max_lifetime. It does not keep capacity warm. After a lull long enough for the surplus above the floor to retire, the next burst dials that surplus again, as it would without jitter. A pool with no traffic is still closed by sqlx's reaper in one pass. Keeping burst capacity warm is a floor-sizing decision (BUZZ_DB_READ_POOL_MIN), outside this PR.

The reader pool's warm floor is also fixed at one fifth of its ceiling, with no way to raise it short of growing the whole pool.

What

  • Lifetime jitter (writer and reader). Each connection gets its own retirement point in [max_lifetime - jitter, max_lifetime] and closes the first time it is released after that point (after_release), once its request is done. On the reader, the check runs before the existing release check and skips that check's round trip. Jitter spreads when connections close, not when they are dialed again. Below the pool floor, sqlx's floor maintenance dials the replacement in the background. Above the floor, a retired connection is dialed again only when a later checkout finds the idle queue empty, so the timing of that dial depends on demand, not on the jitter window. The writer floor is 2 (the DbConfig default, not overridden by the relay); the reader floor is a fifth of the reader ceiling, or BUZZ_DB_READ_POOL_MIN. sqlx's max_lifetime still applies as before. sqlx checks it on release and in its reaper pass, not on idle checkout, so a connection past it is recycled on release or at the next reaper pass.
    • Per-connection point: a hash of the connection's creation instant at 10 µs resolution. sqlx 0.9 keeps no per-connection state that a hook can attach to. Because sqlx and this code read the clock less than a microsecond apart, the recomputed instant falls in the true bucket or the next one. So a connection's point is approximately fixed: almost always one of two candidates, both inside the window. A thread preempted between sqlx's age read and the hook's clock read gets a fresh draw, still inside the window. Connections dialed in parallel get independent points.
    • Scope: jitter on release. The point is checked only when a connection is released, so the spread depends on how often the pool hands out connections. sqlx's idle queue is FIFO, so each checkout takes the longest-idle connection, and a pool serving steady traffic cycles all its idle connections through the check well inside the window. A quiet pool does not: with 50 idle connections and one checkout every 10–30 s, only a few pass through the check during the 60 s window. sqlx's reaper closes the rest together, as it does today, and the next burst re-dials them. The reaper runs every min(max_lifetime, idle_timeout) = 300 s, so an untouched cohort closes at the first pass after 300 s, at an age of up to about 600 s. With the defaults idle_timeout (600 s) never fires, because the reaper re-queues each kept connection with a fresh idle_since; this is existing sqlx behavior. BUZZ_DB_READ_POOL_MIN is the lever for keeping a warm reader floor through quiet periods. Closing the gap fully needs a per-connection deadline in sqlx's own idle maintenance, which isn't possible without changing sqlx, so that is left as a possible follow-up if metrics still show a cliff. An earlier revision added a separate idle sweep, but review found it reset sqlx's idle timestamps, could hold a one-connection reader pool during a request's acquire budget, and outlived dropped pools, so it was removed.
    • Metrics: a new counter, buzz_db_pool_lifetime_retired_total{pool_role}, counts retirements; it is registered in describe_db_pool_metrics() and documented in deploy/charts/buzz/README.md. The audit pool reports as audit, separate from the serving writer, through a new DbConfig::writer_pool_role.
  • BUZZ_DB_MAX_LIFETIME_JITTER_SECS (default 60, 0 disables) sets the window width. It is clamped to the lifetime, and a warning is logged when it exceeds half the lifetime.
  • BUZZ_DB_MAX_LIFETIME_SECS (default 300) makes the lifetime ceiling configurable.
  • BUZZ_DB_READ_POOL_MIN (default: a fifth of the reader ceiling) overrides the reader warm floor, capped at the reader ceiling.

Compatibility and rollback

  • With no env changes, the only behavior change is jitter: connections now retire somewhere in 240–300 s instead of at exactly 300 s. The mean lifetime drops from 300 s to about 270 s, which is roughly 11% more reconnects per connection. In exchange, while traffic continues, a burst's connections stop closing all at once. Jitter spreads closes only; it does not spread re-dials, because a closed connection above the floor is dialed again only when demand needs it, and it does not stop a burst from re-dialing surplus capacity after a lull.
  • The 60 s jitter default applies to every Db::new / connect_writer_pool user: buzz-admin, the deletion workers and workflow, not just the relay. Only buzz-relay reads BUZZ_DB_MAX_LIFETIME_JITTER_SECS, so the kill switch is relay-only. Elsewhere, disabling jitter means reverting the commit.
  • To restore the previous behavior exactly in the relay, set BUZZ_DB_MAX_LIFETIME_JITTER_SECS=0. Reverting the commit also restores it.
  • The test-only Db::read_pool_options(max) keeps its 1-arg signature; the configurable builder is Db::read_pool_options_with(max, min, lifetime). feat(db): record safe error and pool fields on datastore spans #9431's span_route_tests compile whichever PR merges first.
  • The audit pool reuses the writer config, so it gets the same jitter, but it is labeled audit. The fence-probe and push-enqueue side pools are unchanged.

Rollout plan

  1. Staging first, with the defaults (60 s jitter, 300 s lifetime, reader floor = ceiling/5). After a burst, check:
    • While traffic continues, buzz_db_pool_connections{pool_role} loses its 300 s plateau-then-cliff and shows a spread over the 240-300 s window instead. After traffic stops, the remaining surplus can still close in one reaper pass; that is expected.
    • buzz_db_pool_lifetime_retired_total runs at about pool size / 270 s per pod under steady load. It counts retirements at release only, not reaper closes, so a quiet pool's reaper cliff does not show up in it.
    • Writer and reader buzz_db_pool_acquire_duration_seconds don't rise.
  2. Then production, watching the same three signals.
  3. Kill switch: BUZZ_DB_MAX_LIFETIME_JITTER_SECS=0 (relay only). It needs a values change plus a pod roll, so it isn't instant. Otherwise, revert.
  4. Before raising BUZZ_DB_READ_POOL_MIN: floor x relay pods, including old and new pods overlapping during a rolling deploy, must fit under the replica's max_connections.
  5. Mixed versions: config and behavior only, with no schema or wire change, so it is safe during a rolling deploy.

Testing

  • cargo test -p buzz-db --lib and cargo test -p buzz-relay --lib config:: pass. New unit tests check that:
    • retirement points stay inside the window;
    • points spread across the window for dials 10 ms apart and for a 10 ms burst of 500 dials 20 µs apart, with every connection in that burst getting its own point;
    • a connection on a bucket boundary gets points inside the window;
    • jitter is clamped, and zero jitter leaves retirement to sqlx;
    • the reader-floor override is applied and capped;
    • the production connect_read_pool applies the configured floor and lifetime;
    • env parsing works and falls back on bad values.
  • New Postgres test trickle_cycles_idle_cohort_through_jittered_retirement (writer): a writer pool warms 12 connections in one burst (4 s lifetime, 3 s jitter, floor 3), then serves one query every 20 ms. It asserts that retirements land in several separate releases spread over at least 0.5 s, and that the floor of 3 holds. With the release check disabled, it fails: all nine surplus connections close within 0.18 s of each other at about 4 s.
  • New Postgres test retiring_reader_release_skips_the_release_check (reader, local Postgres 17, passes): connections released inside an open transaction past their retirement point are counted as lifetime_retired_total retirements, never as open_transaction closes. A jitter-off control pool shows the release check does catch the same session. The test records each cohort backend's pid and waits for all 8 cohort backends to exit before asserting exact totals from the final snapshot; each backend closes only after its release hook counted it. Mutation (check-first): running the release check before the retirement decision makes it fail with 8 open_transaction and 0 retired. Mutation (both): a variant that runs both the check and the retirement fails with 8 open_transaction plus 7 retired, which the old sum-threshold exit could have missed. The existing trickle test still passes under the check-first mutation, which is why this test was needed.
  • New Postgres test reader_trickle_cycles_idle_cohort_through_jittered_retirement, built through Db::connect_read_pool (4 s lifetime, 3 s jitter, floor 3). It asserts that at least 3 retirements span at least 500 ms, the floor settles at 3, buzz_db_pool_lifetime_retired_total{pool_role="reader"} is at least 3, and buzz_db_reader_release_closed_total stays 0 because a retiring release closes before the release check. Removing the reader hook's if retire { return Ok(false) } makes it fail: all 9 retirements land in one reaper pass at 4.02-4.19 s.
  • Local runs (2026-12-01), before the latest follow-up: cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings and cargo fmt clean; buzz-db lib 234/234; the two pool Postgres suites (pool_release_postgres_tests, reader_pool_postgres_tests, 16 tests) against local Postgres 17 passed 16/16 in each of 3 runs.
  • Local runs on Postgres 17 (2026-12-01), after the latest follow-up: cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings clean; the pool suites (pool_release_postgres_tests and reader_pool_postgres_tests) 17/17; buzz-db lib 234/234.
  • After merging origin/main at 59a51c2: fmt and clippy clean, buzz-db lib 234/234, and buzz-relay config::tests:: + metrics:: 79/79.
  • The chart README now states the same scope: jitter spreads release-time retirement while traffic runs; it does not keep capacity warm through a lull; raise the floor to keep burst capacity warm.
  • Not yet done: a local relay run.

Follow-up commits

  • docs(db): drop staggered-redial claims; wait for every cohort close in the ordering test: the chart README, .env.example and buzz-db docs no longer say jitter spreads replacement dials (it spreads closes; a closed connection above the floor is dialed again only when demand needs it), and the ordering test waits for every cohort close before asserting exact totals.

🤖 Generated with Claude Code

jemiahw and others added 5 commits November 30, 2026 14:26
…r and lifetime

Each writer and reader connection retires on release at its own point in
[max_lifetime - jitter, max_lifetime], derived from its creation time, so
connections opened in one burst no longer expire and re-dial together.
Adds BUZZ_DB_MAX_LIFETIME_JITTER_SECS (default 60, 0 disables),
BUZZ_DB_MAX_LIFETIME_SECS (default 300) and BUZZ_DB_READ_POOL_MIN
(default a fifth of the reader ceiling).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
…it retirements

Add an idle sweep that returns each idle connection through the release
retirement check every tenth of the jitter window, so a cohort that warms
in a burst and then sits idle no longer closes in one sqlx reaper pass.
Derive each connection's point from its creation instant at 10 us rather
than 10 ms, so parallel dials get independent points. Thread the pool
role through DbConfig so audit-pool retirements are labeled `audit`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
…etirement

The sweep reset sqlx's idle timestamps (defeating idle_timeout when it is
shorter than the lifetime), held one-connection reader pools through the
release check inside a request's acquire budget, and kept dropped pools
alive. Idle connections already pass through the release check under any
traffic because sqlx's idle queue is FIFO; a pool with no traffic falls
back to sqlx's reaper as before. Test the trickle case instead, and pin
that a connection on a creation-bucket boundary has at most two points,
both inside the window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
Retirement points are random, so a valid run can cluster nine
retirements in under 1s (seen once in 21 local runs). Assert a 0.5s
spread instead, well above the ~0.2s a single fixed-lifetime reaper
pass produces. Also describe a connection's retirement point as
approximately fixed (one of at most two candidates in the window).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
The retirement point is checked when a connection is returned to the
pool, so a quiet pool can still close idle connections together at the
lifetime. Say so, and point at BUZZ_DB_READ_POOL_MIN for quiet periods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
@jemiahw
jemiahw marked this pull request as ready for review November 30, 2026 23:42
@jemiahw
jemiahw deployed to codex-review November 30, 2026 23:42 — with GitHub Actions Active
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 30, 2026
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

🔐 Codex Security Review

Note: This is an automated, security-focused review generated by Codex.
Use it as a supplement to human review; false positives are possible.

Scope

  • Exact PR diff: a12a9995c458e45c4901763f029fd2ec006f610d...98433047067c5dbbbf5e01d2a69dc0eae1458f23
  • Model: gpt-6.1-sol

💡 Click "edited" above to see earlier reviews for this PR.


Review Summary

Overall Risk: NONE

No concrete security, correctness, or reliability findings were identified in the authorized PR range after tracing the pool configuration, retirement hooks, reader validation, and callers.

Findings

No concrete security, correctness, or reliability findings were identified.

Notes

  • Review used read-only static inspection. Builds and tests were not run.

Generated by Codex Security Review |
Requested by: @jemiahw |
Workflow run

Comment thread crates/buzz-db/src/runtime/mod.rs Resolved
sqlx checks connection age only on release and in its reaper pass, not
on idle checkout, so max_lifetime is not a hard ceiling. Reword the
DbConfig and ConnectionLifetime docs to say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
@jemiahw
jemiahw deployed to codex-review December 1, 2026 16:05 — with GitHub Actions Active
@github-actions github-actions Bot added codex-security-review-current The posted Codex security review matches its recorded range. and removed codex-security-review-current The posted Codex security review matches its recorded range. labels Dec 1, 2026
jemiahw and others added 2 commits December 1, 2026 11:01
- Add a reader-pool trickle test through Db::connect_read_pool that
  asserts jittered retirement spreads, the floor holds, retirements
  count under pool_role=reader, and retiring releases skip the
  release check.
- Keep the test-only Db::read_pool_options(max) signature; the
  configurable builder is now read_pool_options_with, so this merges
  cleanly with #9431's span_route_tests in either order.
- Describe buzz_db_pool_lifetime_retired_total and document it in
  the chart README.
- Correct lifetime docs (replacement dials above the floor, reaper
  cadence on quiet pools) and warn when jitter exceeds half the
  lifetime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Jemiah9000 <9424fd1a46ba04715d24ac3967d4a66d3cfcddd5fbe56a229c8386b4159810bf@buzz.block.builderlab.xyz>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
…me-jitter

Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Dec 1, 2026
@jemiahw
jemiahw deployed to codex-review December 1, 2026 19:26 — with GitHub Actions Active
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Dec 1, 2026
…e jitter docs

- Add retiring_reader_release_skips_the_release_check: connections
  released inside an open transaction past their retirement point are
  counted as lifetime retirements, never as open_transaction closes; a
  jitter-off control pool shows the check catches the same session.
- Chart README: jitter spreads release-time retirement while traffic
  runs; it does not keep capacity warm through a lull, and a quiet pool
  is still closed by sqlx's reaper in one pass. Raise the floor to keep
  burst capacity warm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Jemiah9000 <9424fd1a46ba04715d24ac3967d4a66d3cfcddd5fbe56a229c8386b4159810bf@buzz.block.builderlab.xyz>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Dec 1, 2026
@jemiahw
jemiahw deployed to codex-review December 1, 2026 20:09 — with GitHub Actions Active
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Dec 1, 2026
…n the ordering test

- Chart README, .env.example and buzz-db docs no longer say jitter
  spreads replacement dials: it spreads when connections close; a
  closed connection above the floor is dialed again only when demand
  needs it.
- retiring_reader_release_skips_the_release_check now records each
  cohort backend pid, waits until all eight have exited (each closes
  only after its release hook counted it), then asserts exact totals
  from the final snapshot.

Co-authored-by: Jemiah9000 <9424fd1a46ba04715d24ac3967d4a66d3cfcddd5fbe56a229c8386b4159810bf@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Dec 1, 2026
@jemiahw
jemiahw deployed to codex-review December 1, 2026 20:33 — with GitHub Actions Active
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Dec 1, 2026

@TheSentinel454 TheSentinel454 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Approving at 9843304. The reader retirement tests, the metric docs, and the lifetime wording address the earlier feedback. The new reader tests run in the required PostgreSQL lane. This head also merges cleanly with #9431 in either order.

@TheSentinel454
TheSentinel454 merged commit b9cccf8 into main Dec 1, 2026
94 checks passed
@TheSentinel454
TheSentinel454 deleted the jemiah/db-pool-lifetime-jitter branch December 1, 2026 21:09
jemiahw added a commit that referenced this pull request Dec 1, 2026
## Summary

Datastore spans recorded only `otel.status_code=ERROR` on failure, so a
trace could not tell a statement timeout from a pool timeout, a missing
row, or a unique violation, or show which pool served the call. This
adds fixed, non-sensitive error and pool fields to every
`#[datastore_span]`. No error text reaches a span.

| field | value |
|---|---|
| `error.type` | a constant per error variant, e.g. `pool_timed_out`,
`io_connection_reset`, `row_not_found`, `database`,
`channel_name_taken`, `created_at_floor_rejected` |
| `db.response.status_code` | Postgres SQLSTATE, e.g. `57014`, `55P03`,
`40001`, `23505` |
| `db.error.constraint` | the Postgres constraint name for constraint
violations |
| `db.pool.role` | `writer` (default), `reader`, `audit`, `search` |
| `db.route.decision` / `db.route.reason` | for replica-routed reads,
the same labels as `buzz_db_route_decision` |

Two behavior changes to be aware of:

- **Client-visible error text.** `sqlx_error_kind` now returns specific
names for variants that used to report `other`: `configuration`,
`invalid_argument`, `type_not_found`, `column_not_found`,
`worker_crashed`, `migrate`, `invalid_savepoint_statement`,
`begin_failed`. That string reaches clients through `DbError::kind()`,
e.g. `IngestError::Internal(format!("error: {}", e.kind()))` in
`ingest.rs` and in `pins.rs`. These are fixed labels, so nothing leaks,
but the client-visible text changes.
- **Two new datastore spans:** `acquire_reader` (one per routed read)
and `begin_event_write_transaction` (one per event write). They add two
`operation` values to `buzz_db_operation_duration_seconds` and add span
volume.

### How it stays safe

- The macro calls `buzz_db::datastore_span::record_error`, which records
only what `DatastoreSpanError` returns: an `&'static str` class, plus
SQLSTATE and constraint name from a driver error. A `#[datastore_span]`
function whose error type doesn't implement the trait fails to compile.
Error `Display`, Postgres `message`/`detail`/`hint`, and variant
payloads (`ChannelNameTaken(String)`, `NotFound(String)`, …) are never
read.
- `DbError`'s classification is an exhaustive match with no `_` arm, so
every new variant must pick a name.
- SQLSTATE is recorded only if it is five `[0-9A-Z]` characters. The
constraint name is recorded only if it is a plain lowercase identifier
of at most 63 bytes. Anything else is dropped.
- `tests/runtime.rs` puts a bound value in a Postgres error's message
and in a `DbError` payload, and asserts it appears nowhere in the
exported spans.

### Pool role, recorded once

Recording a span field a second time does not replace the first value.
tracing-opentelemetry appends another attribute with the same key, so a
span could export both `db.pool.role=writer` and `db.pool.role=reader`.
To avoid that, each datastore span gets a task-local route slot
(`buzz_db::datastore_span::scoped`). `Db::record_route` and the
`ReadSession` methods write the route to that slot. A later decision,
such as a writer re-run after a replica failure, replaces an earlier
one. The macro records `db.pool.role` and the route fields exactly once,
whether the operation finishes or is dropped unfinished, so a cancelled
datastore operation still exports its pool and route. A routed read
dropped before its route is decided (during admission, reader checkout
or proof) records `db.pool.role=reader` with no `db.route.decision` or
`db.route.reason`.

- Spans without a route use the macro's `pool` argument: `writer` by
default, `audit` / `search` for those services, and `reader` for the
Aurora identity probe, which runs on a reader connection.
- `route_read` labels replica work as `reader` as soon as it proves a
replica, so early error returns from replica work are not attributed to
the writer.
- A child datastore span's route stays on the child.
- `scoped` boxes the wrapped future. Without that, nesting it inside
`tracing::Instrumented` enlarged every datastore future enough to
overflow the 2 MiB test-thread stack in debug builds (37 Postgres-lane
tests).

Tests fail on any repeated span attribute: `attributes()` in
`tests/runtime.rs` and `span_route_tests` in `runtime/mod.rs`.

### Follow-up commits: error text in `buzz-db` logs, and CI selection

The error-log change is a separate commit so it can be reverted on its
own. `buzz-db` logged the full error on several user-query paths (`error
= %e`, `%error`, or `{e}` in the message). For Postgres errors that text
can repeat a bound value, e.g. `invalid input syntax for type uuid:
"<value>"`. These sites now log `error_kind` (`DbError::kind()` /
`sqlx_error_kind`); the serde event-reconstruct warning logs `category =
?e.classify()`.

- **Changed:** replica fallback warnings in feed, event, thread,
thread_window, relay_members and event_hydration; the `ReadSession`
degrade; the fleet sweep; mention insert; push enqueue; channel TTL
refresh; parameterized-replace savepoint rollback.
- **Unchanged:** infrastructure-only sites (heartbeat probe, readiness,
reader boot ping and acquire). Their statements bind no user values, and
their I/O text helps operators.
- **Guarded:** `store_logs_never_format_error_text` in
`tests/observability_source.rs` fails if a `src/store` tracing call
formats error text again.

`0d877f9f` (review follow-up, McKeon) then tightens the guard and puts
the privacy tests in the blocking lanes. Before, they ran only in the
advisory Flake Check.

- **CI selection.** `just test-unit` now runs `cargo nextest run -p
buzz-datastore-tracing`, which covers the macro's lib tests and
`tests/runtime.rs` (the bound-value and error-text leak tests). The
relay unit-lane filter adds
`test(/^handlers::command_executor::span_tests::/)`. The Cargo fallback
in `scripts/run-tests.sh` mirrors both.
- **Stronger guard.** `store_logs_never_format_error_text` now also
scans bare `trace!` through `error!` calls (not only
`tracing::`-prefixed ones), flags positional formatting (`"{}", e` /
`err` / `error`), skips only path components that end in `tests` (not
any path containing "test"), and asserts that it scanned some calls.
- **Latent bug fixed.** The scan cut each call at `);` and dropped the
`)`, so patterns like `%e)` never matched a final argument. A planted
`warn!("planted {}", error);` now fails the test; before this change it
passed. The doc comment states the scan's real scope: an error bound to
another name, or formatted before the call, is not caught.

`efcfbeb7` merges `origin/main`.

`31b0b64a` (span error fields on command writes, and routes of cancelled
spans) then closes two gaps in the span fields above:

- **Command writes.** `persist_command_event`'s span now records the
typed `DbError` behind an insert or parameterized-replacement failure
(class and SQLSTATE), not only `ingest_internal`. A command write that
fails after checkout records the database error's class and SQLSTATE on
`persist_command_event`. The client response is unchanged. Begin
failures stay on `begin_event_write_transaction`'s own span.
- **Cancelled operations.** `#[datastore_span]` records `db.pool.role`
and the route exactly once whether the operation finishes or is dropped
unfinished. A cancelled datastore operation still records its pool and
route once, so cancelled sibling reads still export their pool.
- **Tests.** A Postgres test cancels a workflow update by statement
timeout on the replacement lock and asserts `error.type=database`,
SQLSTATE `57014`, and no error text. A unit test drops a routed read
mid-flight and asserts its route is recorded once.

`22e21a29e` (name the reader on reads cancelled before their route is
decided) closes the remaining cancellation gap:

- **Reads dropped before routing.** `route_read` marks the span as
waiting on the reader once its prechecks pass, so a read dropped during
admission, reader checkout or proof exports `db.pool.role=reader` with
no route decision, instead of the macro's `writer` default. Every later
decision replaces the mark.
- **`thread_window_aux`.** It records its replica-session route before
awaiting the scan, as `ReadSession::query_events` already does. The
degrade and cancel paths still override it.
- **Tests.** A unit test drops `query_events_routed` mid reader
checkout. A Postgres test drops `thread_window_aux` while the replica
scan waits on a lock.

The PR head is `22e21a29e`.

### Notes

- The macro now emits `::buzz_db::datastore_span::…`, so every macro
user must depend on `buzz-db`; all current users already do. `buzz-db`
adds `extern crate self as buzz_db;` so the path resolves inside it.
`buzz-datastore-tracing` gains a `buzz-db` dev-dependency for its
runtime tests; that dev-dependency cycle is allowed by Cargo.
- `crates/buzz-audit/src/error.rs` has a test asserting audit error
*text* never contains constraint names. This change doesn't affect that
text. It records the constraint name as a separate span field, which was
explicitly approved: it's a schema object name, not tenant data.
- **Merge order with #10047:** no fix-up is needed in either PR. #10047
keeps `Db::read_pool_options(max)`'s 1-arg test signature, so this PR's
`span_route_tests` compile in either order.

## Rollout plan

- There is no flag. It turns on at deploy, and rollback means a revert.
- The fields are additive, with no schema or wire change, so mixed
versions during a rolling deploy are safe.
- **Staging check:** after the staging deploy, check in Datadog APM
(BuilderBot org) that `buzz_datastore` spans carry `error.type` and
`db.pool.role` exactly once each, and that no span carries error text or
bound values. Use the next real `pool_timed_out`, or trigger a statement
timeout on a single staging pod.
- **Span volume:** compare ingested span counts before and after,
because of the two new spans. The default sampler is
`parentbased_always_on`; check the production sampler setting in bpci
before the production deploy.
- **Then production**, with the same checks.

## Testing

Local runs (2026-12-01, Postgres 17) on the latest follow-up commit
`22e21a29e`:

- New unit test
`runtime::span_route_tests::routed_read_cancelled_in_reader_checkout_names_the_reader`:
passes, and fails with `db.pool.role=writer` if its fix is reverted.
- New Postgres test
`runtime::postgres_tests::cancelled_thread_window_aux_names_the_replica_session`:
passes, and fails with `db.pool.role=writer` if its fix is reverted.
- `cargo fmt --check` and `cargo clippy -p buzz-db -p buzz-relay -p
buzz-datastore-tracing --all-targets -- -D warnings` clean.
- buzz-datastore-tracing 7/7, buzz-db lib 231/231,
`observability_source` 47/47, relay `span_tests` 1/1.
- buzz-db `runtime::postgres_tests`: 71/73. The 2 failures
(`migration_schema_operator_listener_outbox_is_not_tenant_scoped` and
`serving_write_guard_insert_indexes_mentions_in_event_transaction`) need
a migrated base test database. They fail the same way locally on the
previous head, `31b0b64a9`.

Earlier runs on `31b0b64a9`:

- New Postgres test
`handlers::command_executor::postgres_tests::post_checkout_statement_timeout_exports_sqlstate_on_command_persistence`:
passes, and fails if the fix is reverted.
- New unit test
`runtime::span_route_tests::cancelled_operation_records_its_route_once`:
passes, and fails if route recording happens only on completion.
- `cargo nextest run -p buzz-datastore-tracing`: 7/7.
- buzz-db lib 230/230, `observability_source` 47/47.
- relay `span_tests` 1/1, relay `command_executor::postgres_tests` 3/3.
- `cargo clippy -p buzz-db -p buzz-relay -p buzz-datastore-tracing
--all-targets -- -D warnings` clean.

Earlier runs on the CI-selection follow-up commit, after merging
`origin/main` (`efcfbeb7`):

- `cargo nextest run -p buzz-datastore-tracing`: 7/7.
- relay `handlers::command_executor::span_tests`: 1/1.
- buzz-db `observability_source::store_logs_never_format_error_text`:
pass. The planted-violation mutation fails as expected.
- `cargo fmt --check` clean. `cargo clippy -p buzz-db -p buzz-relay -p
buzz-datastore-tracing --all-targets -- -D warnings` clean.
- buzz-db lib 229/229, `observability_source` 47/47.

Earlier runs on the first two commits:

- `cargo test -p buzz-datastore-tracing`: span policy tests, including
the leak test and the repeated-attribute check. A mutation check
confirmed the leak test fails if SQLSTATE validation is removed.
- `cargo test -p buzz-db` (lib and `observability_source`), `-p
buzz-search`, `-p buzz-audit`: all pass. These include
`span_route_tests` and the new log guard. A mutation check confirmed the
guard fails when an `error = %e` is restored.
- `scripts/postgres-test-run.sh -p buzz-db -p buzz-search -p buzz-audit
--lib --tests`: 792/796 passed. The 4 failures were timing checks
(reader connect within 5s, reader pool settle, a 2s plan headroom check,
a lock timing check), and all 4 pass when rerun on their own.
- `cargo nextest run -p buzz-relay --lib --bin buzz-relay`: 1789/1791
passed. The 2 `pubsub_fanout::audit_*` failures seed `communities` in
the local dev database, which doesn't have that table (42P01). That's an
environment problem, not something this change causes.

### Manual check

Run Jaeger (`docker run -d -p 16686:16686 -p 4317:4317
jaegertracing/all-in-one`), then start the relay with
`OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 just relay`.
Optionally add `READ_DATABASE_URL` pointing at the same database to
exercise routed reads.

- **Connection failure:** `docker pause buzz-postgres` during a request
should give `error.type=pool_timed_out`.
- **Statement timeout:** `BUZZ_DB_STATEMENT_TIMEOUT_MS=1` should give
`db.response.status_code=57014`.
- **Privacy:** no SQL, message text or bound values should appear on any
span.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Jemiah9000 <9424fd1a46ba04715d24ac3967d4a66d3cfcddd5fbe56a229c8386b4159810bf@buzz.block.builderlab.xyz>
wpfleger96 added a commit that referenced this pull request Dec 2, 2026
…xpires

* origin/main: (24 commits)
  fix(db): remove the duplicate tracing-subscriber dev-dependency (#10094)
  chore(lint): ban raw calls that review keeps catching (#10077)
  fix(deletion): log a request the drain blocks at claim (#10078)
  fix(deletion): skip unlisted tenant tables instead of blocking (#10074)
  fix(deletion): purge PostgreSQL in bounded batches (#10081)
  feat(db): record safe error and pool fields on datastore spans (#9431)
  perf(relay): share identical in-flight author lookups on POST /query (#10044)
  Republish channel discovery events a failed emission left missing (#9805)
  perf(db): jitter pool connection retirement; configurable reader floor and lifetime (#10047)
  feat(search): people-only search filter, and the agent owner on each indexed message (#10021)
  fix(search): drop the community label from indexer metrics (#10019)
  relay: advertise the build's source SHA in NIP-11 (#9827)
  feat(mobile): record a push baseline when Android enrolls (#10038)
  Show deletion evidence to the requester (#10076)
  Give single photos the stack card style in mobile chat (#10071)
  fix(search): do not return expired AWS credentials after a failed reload (#10042)
  feat(mobile): unify the Android conversation composer (#10015)
  feat(mobile): check the relay key on Android push channel titles (#10037)
  chore(devex): streamline local OpenSearch and Postgres test workflows (#10034)
  feat(mobile): record messages the app shows so Android wakes skip them (#10039)
  ...

Signed-off-by: Will Pfleger <wpfleger@block.xyz>

This branch was successfully deployed

1 active deployment
codex-review — 98433047 Deployed Dec 1, 2026 by jemiahw via Run Codex Security Review #19055
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex-security-review-current The posted Codex security review matches its recorded range.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants