Skip to content

api: drop the sqlx::Error round-trips and build the substrate from a Db - #2702

Draft
ac-pplx wants to merge 1 commit into
ac/api2-AH6-api-appstate-dbfrom
ac/api2-AR2-api-driver-error-round-trips
Draft

ac-pplx wants to merge 1 commit into
ac/api2-AH6-api-appstate-dbfrom
ac/api2-AR2-api-driver-error-round-trips

Conversation

@ac-pplx

@ac-pplx ac-pplx commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The sqlx::Error round-trips go from pplx-space-api production code
outside the Direct adapter, and the substrate is built from a Db. Every
converted site hands its consumer the same DbError, wrapping the same driver
error, that the round-trip used to rebuild, so statuses, bodies, error kinds
and retryability are unchanged. No SQL, transaction or pool changes. Only Rust
types change.

routes/authz.rs: every helper returns Result<_, DbError>, not
Result<_, sqlx::Error>. The three .map_err(sqlx::Error::from) calls on the
accounts store's results go, and the ? on cluster_managing_org_id no
longer converts. Callers drop the DbError::from that undid the conversion:

  • the /admin gate in routes/admin/mod.rs, which no longer imports
    DbError;
  • support::require_managing_org_admin;
  • templates::require_template_admin and query_template_releases;
  • identity.rs's three permission checks and its is_managing_org_admin
    wrapper;
  • debug::sandbox::require_managing_org_admin, which loses its
    DbError::from and the comment explaining it.

Kubernetes store (controllers/substrate/kubernetes/store/):
auto_lifecycle_policy_after_claim (execution_rows.rs) and
forget_pod_tracking_if_no_active_execution (pod_tracking.rs) read through
sandbox-store verbs that return SandboxStoreError. Each mapped it to
sqlx::Error and classified it with DriverDbContext::db_context. Each now
takes the store error's one DbError out with the irrefutable
|SandboxStoreError::Database(error)| error, as public_operations.rs does,
and classifies it with DbContext::db_context. store.rs drops its
crate::driver_db::DriverDbContext import, and its module doc no longer
mentions it.

Substrate constructors: Substrate::from_env and from_env_with_lifecycle
(controllers/substrate.rs) and KubernetesSubstrate::try_from_env
(kubernetes/mod.rs) take &Db, not &PgPool. Each clones it where it used
to clone the pool. AppState::from_pools_with_lifecycle (routes/mod.rs)
wraps its pool in a Db before building the substrate instead of after, and
passes the substrate that same handle. Its comment now says so. The cluster
controller (crates/l40_api/cluster/controller/server/src/lib.rs) wraps its
space_user pool for Substrate::from_env, with
&Db::from(pool.clone()). That is the only edit outside api. A Db clone
shares the pool it wraps, so the substrate runs on the same pool as before.

Smaller cleanups:

  • auth.rs imports time::OffsetDateTime, not the same type through
    sqlx::types::time.
  • routes/admin/node_store.rs: production builds OccupancyRow only from
    admin_occupancy::NodeOccupancyCounts, so the FromRow derive and its
    import leave production. single_node_occupancy/tests.rs still decodes the
    single-node and fleet statements' rows into OccupancyRow, so the derive
    stays for tests
    as #[cfg_attr(test, derive(sqlx::FromRow))].
  • Doc comments in controllers/mod.rs and routes/public/error.rs that told
    a caller to hold or convert a sqlx::Error now say "database error", or
    drop the sentence.

Test edits the compiler forced:

  • controllers/sandbox/org/owner_scope_tests.rs passes from_env a Db.
  • kubernetes/test_substrate.rs, kubernetes/pod_ops/read/tests.rs and
    kubernetes/wait_ready/tests.rs import sqlx::PgPool, which they used to
    get from kubernetes/mod.rs through super::*.

Still naming sqlx in api production code (git grep -n -w sqlx, excluding
test-only modules):

  • controllers/substrate/direct.rs (three sites): the Direct adapter's own
    conversion is a separate change.
  • driver_db.rs: DriverDbContext still serves those Direct sites and
    controllers/substrate/tests.rs. A later change deletes it once both are
    gone.
  • routes/mod.rs: use sqlx::PgPool for AppState's constructors.
    from_pools_with_lifecycle takes the driver pool its callers hold and
    wraps it in a Db at once; the test-only from_pool also hands that pool
    to CredentialsPool::shared.
  • reconcile_queue.rs: a comment about rollback on drop.
  • routes/admin/node_store.rs: the test-only cfg_attr above.

Not changed here: DbErrorLike's AuthLookupError impl, CredentialsPool,
api's Cargo.toml and architecture-baseline.toml. The substrate core's
doc comments that name pplx_space_api::driver_db are left alone too. They
stay accurate while the module exists.

Validation

Run with this change on #2689 at 72d2650f (on main at 8e0f72e3). The
current base changes none of the files this change touches, and Pull CI
covers this head:

  • ci/scripts/run-rust-checks.sh fmt passes.
  • cargo check --locked --workspace --all-targets --all-features passes
    with no warnings.
  • Workspace clippy (--all-targets --all-features -- -D warnings) passes
    with no warnings.
  • cargo clippy --locked -p pplx-space-api --lib -- -D warnings passes with
    the default features, --features kubernetes and --all-features. So does
    --all-targets --features kubernetes.
  • ci/scripts/run-archcheck.sh against the merge base (8e0f72e3) reports
    no findings (2071 production Rust files).
  • RUSTDOCFLAGS=-D warnings cargo doc --no-deps --all-features fails with
    the same errors as the base: 30 for pplx-space-api, 5 for
    pplx-space-cluster-controller-server. All are private-item links or an
    unclosed HTML tag in code this change does not touch.
  • nextest with --all-features and the pinned Postgres image: 5004 passed
    and 1 skipped (an #[ignore] test). That is pplx-space-api 2990,
    pplx-space-cluster-controller-server 1461 and
    pplx-space-internal-api-server 553.

Error classification, with a table test. The test was disposable and is
not committed. Postgres built each driver error for real, except the protocol
error. Both 55P03s came from a held row lock, one via NOWAIT and one via
lock_timeout. Uniqueness, foreign-key and check violations came from
inserts. 57014 came from statement_timeout. The pool timeout came from an
exhausted one-connection pool, and the closed pool from close(). The I/O
error came from a refused connect, and the decode error from a mismatched
column type. 40P01 and 40001 came from RAISE ... USING ERRCODE.

Each error ran twice into each converted site's final consumer:

  • through the base's round-trip: DbError::from(sqlx::Error::from(error))
    for authz, and for the Kubernetes store
    .map_err(sqlx::Error::from).db_context(..) through DriverDbContext;
  • through this change's direct path: the DbError itself, or the
    destructure and DbContext::db_context.

The consumers are the six authz arms listed above, each with its own
fallback, and for the Kubernetes sites substrate_db_error through
ControllerError and its response. The test compared these as rendered
strings:

  • status, headers and body;
  • DbError's kind, SQLSTATE, constraint, is_lock_contention and message;
  • the SubstrateError and ControllerError values.

All 120 rows are identical. Head outcomes:

Driver error DbError kind /admin gate support gate identity template gate releases debug gate Kubernetes store
55P03 (NOWAIT) LockNotAvailable, retryable 503 503 503 503 503 503 LockContention 503
55P03 (lock_timeout) LockNotAvailable, retryable 503 503 503 503 503 503 LockContention 503
40P01 Deadlock, retryable 503 503 503 503 503 503 LockContention 503
row not found NotFound, not retryable 500 500 500 500 500 500 Failed 500
23505 UniqueViolation, not retryable 500 500 500 500 500 500 Failed 500
23503 ForeignKeyViolation, not retryable 500 500 500 500 500 500 Failed 500
23514 CheckViolation, not retryable 500 500 500 500 500 500 Failed 500
40001 SerializationFailure, retryable 503 503 503 503 503 503 LockContention 503
57014 QueryCanceled, not retryable 500 500 500 500 500 500 Failed 500
pool timeout PoolTimedOut, not retryable 500 500 500 500 500 500 Failed 500
closed pool Other, not retryable 500 500 500 500 500 500 Failed 500
22P02 Other, not retryable 500 500 500 500 500 500 Failed 500
protocol error Other, not retryable 500 500 500 500 500 500 Failed 500
I/O (refused) Io, not retryable 500 500 500 500 500 500 Failed 500
decode Decode, not retryable 500 500 500 500 500 500 Failed 500

A planted mutation in the head path, which turned lock-contention errors into
plain protocol errors, fails the test with 32 mismatches: the four contention
classes times eight consumers.

Statements, with a log differential. Postgres logged every statement and
its binds (log_statement = all, csvlog). A disposable fixture patch named
each test's database after its nextest test. The comparison ran over the
whole pplx-space-api suite, two runs of the base and two of this change.
That includes every route test that reaches authz.rs, the Kubernetes
adapter tests that reach the two store sites, and every test that builds
AppState or calls Substrate::from_env. Per test, it compared the
multiset of (statement, binds) and (error severity, SQLSTATE, message), with
sql! locators, UUIDs, timestamps and database names masked.

  • All four runs passed all 2990 tests. 1751 tests issue SQL.

  • Pooling the two runs of each commit, the distinct (statement, binds,
    error) sets match in every test but one. That one is an e2b redrive test
    whose two base runs disagree with each other in the same way.

  • Counts differ in 46 tests. In 41 of them the counts also vary between two
    runs of the same commit. The other 5 vary in counts of timing-dependent
    rows only:

    • three tests' lock-wait probes on pg_stat_activity;
    • one test's 57P01, from the fixture terminating backends at database
      drop;
    • one test's operation-status poll.

    Two of those five also varied between same-commit runs of an earlier
    1950-test differential.

  • No production statement, bind or error appears or disappears.

The differential cannot tell the app pool from the credentials pool: in
tests, AppState::from_pool builds both from one PgPool. The substrate's
pool is the one AppState and the cluster controller wrap, as the code
above shows.

The Kind suite and the Direct substrate lane run only in Pull CI.

Local review: round 1 (Codex + Claude), READY after fixes.

Severity and risk

Severity: does not apply. This is a refactor with no behaviour change.

Risk: low. A consumer could classify a database error differently if a
conversion were lossy. DbError is a newtype over the driver's error, both
conversions move the same value, and the table test checks every class at
every converted consumer. Rollback is a revert.

Mixed-version safety: no schema, protocol, metric or persisted-state change;
Rust types only.

Stack

Stacks on #2689, which makes AppState.pool a Db. Merge after it.

Interacts with #2696, which prepares the Direct adapter to move into its
own crate. With both merged, crate::driver_db has no user outside the
controllers/substrate/tests.rs tests, so whichever of the two merges
second deletes driver_db.rs, moves those tests to the DbError path and
updates the substrate core's doc comments that name it.

AI assistance: Claude Code drafted the code changes, the disposable proofs
and this description.

@ac-pplx ac-pplx added the kind-smoke Run the Kind/Firecracker smoke on this PR, whatever it changes, from its next push label Dec 2, 2026
@ac-pplx ac-pplx closed this Dec 2, 2026
@ac-pplx ac-pplx reopened this Dec 2, 2026
@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Pre-merge checks: Passed 6

Check name Status Explanation
Description Follows The Pr Template Passed The PR description (PR #2702, author ac-pplx) contains all four required items. Each has real content, not only template comments. 1. "## Summary" is present. It states what merging does: the `sql…
Bug Fixes Name A Regression Test Passed The check applies only when the pull request fixes a defect in application behavior under crates/, shim/, or ui/. This pull request is a refactor. The description states: "Severity: does not apply. Th…
Weakened Safeguards Are Justified Passed The PR commit (d98f0ad, parent f624b2b) changes 21 files, all under crates/l40_api. Nothing in the diff matches the custom check's failure conditions: - No tests or assertions removed. A searc…
Agent Tooling Runs No New Commands Passed The check applies to agent plugin manifests, skills, and guideline files. This PR's own change is the head commit d98f0ad against its base commit f624b2b (the stacked base, `ac/api2-AH6-api-appsta…
External Code Sources Need A Person Passed The check fails only if the diff adds or changes where external code comes from: dependency sources in Cargo.toml, container image references, downloaded binaries or archives, or external Helm chart d…
Public-Safe Content Passed PR #2702 (perplexityai/SPACE, author ac-pplx) passes the Public-safe content check. Diff: I compared HEAD against its parent (f624b2b), which is the base commit of this PR. That gives 21 files and 5…
Full details: Description Follows The Pr Template

Explanation

The PR description (PR #2702, author ac-pplx) contains all four required items. Each has real content, not only template comments. 1. "## Summary" is present. It states what merging does: the sqlx::Error round-trips leave production code outside the Direct adapter, and the substrate is built from a Db. It also says that statuses, bodies, error kinds and retryability do not change. 2. "## Validation" is present. It names the runs and their results, including fmt, cargo check, workspace clippy, archcheck, rustdoc, nextest (5004 passed, 1 skipped), and the error-classification and statement differential tests. 3. "## Severity and risk" is present. It gives "Severity: does not apply. This is a refactor with no behaviour change." and "Risk: low", with a reason. 4. "AI assistance:" line is present. It reads "AI assistance: Claude Code drafted the code changes, the disposable proofs and this description." It names the tool and the parts it drafted. Presence is the only test here. The check does not judge quality or length, so the verdict rests on the presence of each item. No code evidence was needed for this description-format check.

Full details: Bug Fixes Name A Regression Test

Explanation

The check applies only when the pull request fixes a defect in application behavior under crates/, shim/, or ui/. This pull request is a refactor. The description states: "Severity: does not apply. This is a refactor with no behaviour change." It says statuses, bodies, error kinds, and retryability are unchanged. It changes Rust types only: sqlx::Error round-trips become DbError, and substrate constructors take &amp;Db instead of &amp;PgPool. The description does not present any fix to a defect. The check does not apply, so it passes. The disposable table test is noted, but it does not change the applicability result.

Full details: Weakened Safeguards Are Justified

Explanation

The PR commit (d98f0ad, parent f624b2b) changes 21 files, all under crates/l40_api. Nothing in the diff matches the custom check's failure conditions: - No tests or assertions removed. A search of the diff for test attributes, assert, and #[ignore] found no removed lines. The test-file edits are import additions only (sqlx::PgPool in kubernetes/test_substrate.rs, kubernetes/pod_ops/read/tests.rs, and kubernetes/wait_ready/tests.rs) plus the from_env call in owner_scope_tests.rs. - No lint, allow, or expect attributes added. The only attribute change is in routes/admin/node_store.rs. #[derive(sqlx::FromRow)] becomes #[cfg_attr(test, derive(sqlx::FromRow))]. The derive stays for test builds, and the doc comment gives the reason. This narrows production code, not a safeguard. - No CI, nextest, allowlist, baseline, or skip changes. No file under .config/, ci/, .github/, Cargo.toml, clippy.toml, deny.toml, the architecture files, AGENTS.md, CLAUDE.md, .agents/, CONTRIBUTING.md, docs/rust/, or db/README.md changed. - Comment edits do not weaken a guard. The removed doc text in kubernetes/store.rs and controllers/mod.rs is reworded to match the new code. The store module still states that DbContext::db_context is the classifier, and the two converted sites now use it. The support.rs note about the identity gate is replaced by an accurate explanation that ? goes through IdentityAdminError's From&lt;DbError&gt;. The debug/sandbox.rs and public/error.rs comment edits track the removed conversions. The contributor's description (Summary, Validation, and Stack sections) explains each removal and narrowing. The check passes.

Full details: Agent Tooling Runs No New Commands

Explanation

The check applies to agent plugin manifests, skills, and guideline files. This PR's own change is the head commit d98f0ad against its base commit f624b2b (the stacked base, ac/api2-AH6-api-appstate-db). That diff touches 21 files, all Rust sources under crates/l40_api/api/src/ plus crates/l40_api/cluster/controller/server/src/lib.rs. It adds no plugin manifest (plugin.json/plugin.yaml), no SKILL.md, no .agents/ or .claude/ file, and no AGENTS.md/CLAUDE.md file. A search of added lines for inline shell substitutions (!`), allowed-tools, hooks, mcpServers/mcp_servers, lspServers, and command keys found no matches. Nothing in the PR adds or changes content that agent tools run. The checkout's diff against main shows many agent-guideline files, but those come from stacked PRs already in the base, not from this PR. This is the reason I used the base-commit diff instead. The PR author is ac-pplx (provider-reported); the check does not depend on author identity.

Full details: External Code Sources Need A Person

Explanation

The check fails only if the diff adds or changes where external code comes from: dependency sources in Cargo.toml, container image references, downloaded binaries or archives, or external Helm chart dependencies. Evidence: - The target branch ac/api2-AH6-api-appstate-db is not present locally. The checkout is detached at PR head d98f0ade5, so I compared against its parent f624b2b6d. The 21 changed files match the PR description: crates/l40_api/api/src/** and crates/l40_api/cluster/controller/server/src/lib.rs. - No Cargo.toml, Cargo.lock, Dockerfile, shell script, Chart.yaml, Chart.lock, or other YAML/TOML/JSON file is in the changed set. - A scan of all added and removed lines for git =, rev =, branch =, tag =, registry =, path =, FROM, image:, sha256:, curl, wget, and http(s):// found no matches. The changes are Rust type and import changes inside the workspace. They match the description's statement that only Rust types change, with no dependency or image edits. Dependencies between workspace crates and images built from this repository pass the check. Caveat: the parent commit is used as the base because the target branch is not available locally. The file list matches the PR description, so this base is reasonable.

Full details: Public-Safe Content

Explanation

PR #2702 (perplexityai/SPACE, author ac-pplx) passes the Public-safe content check. Diff: I compared HEAD against its parent (f624b2b), which is the base commit of this PR. That gives 21 files and 59 added lines. I scanned every added line for credentials, private keys, AWS account IDs and ARNs, personal absolute paths, internal hostnames and URLs, and links to private trackers or chats. No matches. The added lines are Rust type changes, doc comments, and imports. The commit message also has no URLs. Description and title: the text references only PR numbers (#2689, #2696), commit hashes, and general validation results. It has no URLs, hostnames, ARNs, or personal paths. The validation section reports synthetic, disposable test results (Postgres errors built in a fixture, test counts). It does not include raw production logs, query output, or production measurements. The AI credit line ("AI assistance: Claude Code drafted ...") has no link and no sensitive value, so it does not trigger the check. Repository-wide grep hits such as /home/user paths and fake ARNs (123456789012) are in pre-existing files that this PR does not touch, so they are out of scope.

@github-actions github-actions Bot added the triage:pending Waiting for a maintainer to triage label Dec 2, 2026
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

Thanks for opening this pull request! A SPACE maintainer will take a look.

CONTRIBUTING.md explains how we review outside contributions.

@ac-pplx
ac-pplx force-pushed the ac/api2-AH6-api-appstate-db branch from 72d2650 to f624b2b Compare December 2, 2026 09:51
@ac-pplx
ac-pplx force-pushed the ac/api2-AR2-api-driver-error-round-trips branch from 9e130ef to 20b031d Compare December 2, 2026 09:52
## Summary

The `sqlx::Error` round-trips go from `pplx-space-api` production code
outside the Direct adapter, and the substrate is built from a `Db`. Every
converted site hands its consumer the same `DbError`, wrapping the same driver
error, that the round-trip used to rebuild, so statuses, bodies, error kinds
and retryability are unchanged. No SQL, transaction or pool changes. Only Rust
types change.

`routes/authz.rs`: every helper returns `Result<_, DbError>`, not
`Result<_, sqlx::Error>`. The three `.map_err(sqlx::Error::from)` calls on the
accounts store's results go, and the `?` on `cluster_managing_org_id` no
longer converts. Callers drop the `DbError::from` that undid the conversion:

- the `/admin` gate in `routes/admin/mod.rs`, which no longer imports
  `DbError`;
- `support::require_managing_org_admin`;
- `templates::require_template_admin` and `query_template_releases`;
- `identity.rs`'s three permission checks and its `is_managing_org_admin`
  wrapper;
- `debug::sandbox::require_managing_org_admin`, which loses its
  `DbError::from` and the comment explaining it.

Kubernetes store (`controllers/substrate/kubernetes/store/`):
`auto_lifecycle_policy_after_claim` (`execution_rows.rs`) and
`forget_pod_tracking_if_no_active_execution` (`pod_tracking.rs`) read through
sandbox-store verbs that return `SandboxStoreError`. Each mapped it to
`sqlx::Error` and classified it with `DriverDbContext::db_context`. Each now
takes the store error's one `DbError` out with the irrefutable
`|SandboxStoreError::Database(error)| error`, as `public_operations.rs` does,
and classifies it with `DbContext::db_context`. `store.rs` drops its
`crate::driver_db::DriverDbContext` import, and its module doc no longer
mentions it.

Substrate constructors: `Substrate::from_env` and `from_env_with_lifecycle`
(`controllers/substrate.rs`) and `KubernetesSubstrate::try_from_env`
(`kubernetes/mod.rs`) take `&Db`, not `&PgPool`. Each clones it where it used
to clone the pool. `AppState::from_pools_with_lifecycle` (`routes/mod.rs`)
wraps its pool in a `Db` before building the substrate instead of after, and
passes the substrate that same handle. Its comment now says so. The cluster
controller (`crates/l40_api/cluster/controller/server/src/lib.rs`) wraps its
`space_user` pool for `Substrate::from_env`, with
`&Db::from(pool.clone())`. That is the only edit outside api. A `Db` clone
shares the pool it wraps, so the substrate runs on the same pool as before.

Smaller cleanups:

- `auth.rs` imports `time::OffsetDateTime`, not the same type through
  `sqlx::types::time`.
- `routes/admin/node_store.rs`: production builds `OccupancyRow` only from
  `admin_occupancy::NodeOccupancyCounts`, so the `FromRow` derive and its
  import leave production. `single_node_occupancy/tests.rs` still decodes the
  single-node and fleet statements' rows into `OccupancyRow`, so the derive
  stays for tests
  as `#[cfg_attr(test, derive(sqlx::FromRow))]`.
- Doc comments in `controllers/mod.rs` and `routes/public/error.rs` that told
  a caller to hold or convert a `sqlx::Error` now say "database error", or
  drop the sentence.

Test edits the compiler forced:

- `controllers/sandbox/org/owner_scope_tests.rs` passes `from_env` a `Db`.
- `kubernetes/test_substrate.rs`, `kubernetes/pod_ops/read/tests.rs` and
  `kubernetes/wait_ready/tests.rs` import `sqlx::PgPool`, which they used to
  get from `kubernetes/mod.rs` through `super::*`.

Still naming sqlx in api production code (`git grep -n -w sqlx`, excluding
test-only modules):

- `controllers/substrate/direct.rs` (three sites): the Direct adapter's own
  conversion is a separate change.
- `driver_db.rs`: `DriverDbContext` still serves those Direct sites and
  `controllers/substrate/tests.rs`. A later change deletes it once both are
  gone.
- `routes/mod.rs`: `use sqlx::PgPool` for `AppState`'s constructors.
  `from_pools_with_lifecycle` takes the driver pool its callers hold and
  wraps it in a `Db` at once; the test-only `from_pool` also hands that pool
  to `CredentialsPool::shared`.
- `reconcile_queue.rs`: a comment about rollback on drop.
- `routes/admin/node_store.rs`: the test-only `cfg_attr` above.

Not changed here: `DbErrorLike`'s `AuthLookupError` impl, `CredentialsPool`,
api's `Cargo.toml` and `architecture-baseline.toml`. The substrate core's
doc comments that name `pplx_space_api::driver_db` are left alone too. They
stay accurate while the module exists.

## Validation

Run with this change on #2689 at `72d2650f` (on `main` at `8e0f72e3`). The
current base changes none of the files this change touches, and Pull CI
covers this head:

- `ci/scripts/run-rust-checks.sh fmt` passes.
- `cargo check --locked --workspace --all-targets --all-features` passes
  with no warnings.
- Workspace clippy (`--all-targets --all-features -- -D warnings`) passes
  with no warnings.
- `cargo clippy --locked -p pplx-space-api --lib -- -D warnings` passes with
  the default features, `--features kubernetes` and `--all-features`. So does
  `--all-targets --features kubernetes`.
- `ci/scripts/run-archcheck.sh` against the merge base (`8e0f72e3`) reports
  no findings (2071 production Rust files).
- `RUSTDOCFLAGS=-D warnings cargo doc --no-deps --all-features` fails with
  the same errors as the base: 30 for `pplx-space-api`, 5 for
  `pplx-space-cluster-controller-server`. All are private-item links or an
  unclosed HTML tag in code this change does not touch.
- nextest with `--all-features` and the pinned Postgres image: 5004 passed
  and 1 skipped (an `#[ignore]` test). That is `pplx-space-api` 2990,
  `pplx-space-cluster-controller-server` 1461 and
  `pplx-space-internal-api-server` 553.

**Error classification, with a table test.** The test was disposable and is
not committed. Postgres built each driver error for real, except the protocol
error. Both `55P03`s came from a held row lock, one via `NOWAIT` and one via
`lock_timeout`. Uniqueness, foreign-key and check violations came from
inserts. `57014` came from `statement_timeout`. The pool timeout came from an
exhausted one-connection pool, and the closed pool from `close()`. The I/O
error came from a refused connect, and the decode error from a mismatched
column type. `40P01` and `40001` came from `RAISE ... USING ERRCODE`.

Each error ran twice into each converted site's final consumer:

- through the base's round-trip: `DbError::from(sqlx::Error::from(error))`
  for authz, and for the Kubernetes store
  `.map_err(sqlx::Error::from).db_context(..)` through `DriverDbContext`;
- through this change's direct path: the `DbError` itself, or the
  destructure and `DbContext::db_context`.

The consumers are the six authz arms listed above, each with its own
fallback, and for the Kubernetes sites `substrate_db_error` through
`ControllerError` and its response. The test compared these as rendered
strings:

- status, headers and body;
- `DbError`'s kind, SQLSTATE, constraint, `is_lock_contention` and message;
- the `SubstrateError` and `ControllerError` values.

All 120 rows are identical. Head outcomes:

| Driver error | `DbError` kind | `/admin` gate | `support` gate | identity | template gate | releases | debug gate | Kubernetes store |
|---|---|---|---|---|---|---|---|---|
| `55P03` (`NOWAIT`) | LockNotAvailable, retryable | 503 | 503 | 503 | 503 | 503 | 503 | LockContention 503 |
| `55P03` (`lock_timeout`) | LockNotAvailable, retryable | 503 | 503 | 503 | 503 | 503 | 503 | LockContention 503 |
| `40P01` | Deadlock, retryable | 503 | 503 | 503 | 503 | 503 | 503 | LockContention 503 |
| row not found | NotFound, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| `23505` | UniqueViolation, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| `23503` | ForeignKeyViolation, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| `23514` | CheckViolation, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| `40001` | SerializationFailure, retryable | 503 | 503 | 503 | 503 | 503 | 503 | LockContention 503 |
| `57014` | QueryCanceled, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| pool timeout | PoolTimedOut, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| closed pool | Other, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| `22P02` | Other, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| protocol error | Other, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| I/O (refused) | Io, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |
| decode | Decode, not retryable | 500 | 500 | 500 | 500 | 500 | 500 | Failed 500 |

A planted mutation in the head path, which turned lock-contention errors into
plain protocol errors, fails the test with 32 mismatches: the four contention
classes times eight consumers.

**Statements, with a log differential.** Postgres logged every statement and
its binds (`log_statement = all`, csvlog). A disposable fixture patch named
each test's database after its nextest test. The comparison ran over the
whole `pplx-space-api` suite, two runs of the base and two of this change.
That includes every route test that reaches `authz.rs`, the Kubernetes
adapter tests that reach the two store sites, and every test that builds
`AppState` or calls `Substrate::from_env`. Per test, it compared the
multiset of (statement, binds) and (error severity, SQLSTATE, message), with
`sql!` locators, UUIDs, timestamps and database names masked.

- All four runs passed all 2990 tests. 1751 tests issue SQL.
- Pooling the two runs of each commit, the distinct (statement, binds,
  error) sets match in every test but one. That one is an e2b redrive test
  whose two base runs disagree with each other in the same way.
- Counts differ in 46 tests. In 41 of them the counts also vary between two
  runs of the same commit. The other 5 vary in counts of timing-dependent
  rows only:
  - three tests' lock-wait probes on `pg_stat_activity`;
  - one test's `57P01`, from the fixture terminating backends at database
    drop;
  - one test's operation-status poll.

  Two of those five also varied between same-commit runs of an earlier
  1950-test differential.
- No production statement, bind or error appears or disappears.

The differential cannot tell the app pool from the credentials pool: in
tests, `AppState::from_pool` builds both from one `PgPool`. The substrate's
pool is the one `AppState` and the cluster controller wrap, as the code
above shows.

The Kind suite and the Direct substrate lane run only in Pull CI.

Local review: round 1 (Codex + Claude), READY after fixes.

## Severity and risk

Severity: does not apply. This is a refactor with no behaviour change.

Risk: low. A consumer could classify a database error differently if a
conversion were lossy. `DbError` is a newtype over the driver's error, both
conversions move the same value, and the table test checks every class at
every converted consumer. Rollback is a revert.

Mixed-version safety: no schema, protocol, metric or persisted-state change;
Rust types only.

## Stack

Stacks on #2689, which makes `AppState.pool` a `Db`. Merge after it.

Interacts with #2696, which prepares the Direct adapter to move into its
own crate. With both merged, `crate::driver_db` has no user outside the
`controllers/substrate/tests.rs` tests, so whichever of the two merges
second deletes `driver_db.rs`, moves those tests to the `DbError` path and
updates the substrate core's doc comments that name it.

AI assistance: Claude Code drafted the code changes, the disposable proofs
and this description.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind-smoke Run the Kind/Firecracker smoke on this PR, whatever it changes, from its next push triage:pending Waiting for a maintainer to triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant