You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
api: AppState and the operation executors hold a Db, not a PgPool - #2689
AppState.pool is now postgres-pool's Db, and so are the last
production holders of a sqlx::PgPool in pplx-space-api. Every
statement runs on the same pool as before, in the same transactions. The
roughly 170 Db::from(state.pool.clone()) wraps that &state.pool
replaces always wrapped that same pool. Only Rust handle types change.
AppState (routes/mod.rs):
pub pool: PgPool becomes pub pool: Db. The field keeps its name, so
handlers read &state.pool where they wrapped it. The name reads oddly
in three kinds of place:
where a transaction begins on it: state.pool.begin() in routes/admin/{identity,node_groups,nodes,runtime_environments,template_visibility,templates}.rs
and routes/public/ports.rs;
wherever it is passed to a parameter named db;
in session_user and public_session_store, which pass self.pool.
from_pools_with_lifecycle still takes the PgPool, because Substrate::from_env_with_lifecycle (controllers/substrate.rs) takes &PgPool until a later change converts it. It passes that pool to the
substrate as before, then wraps it in a Db once for everything else.
#[cfg(test)] from_pool is unchanged. It hands the same PgPool to from_pools_with_lifecycle and to CredentialsPool::shared. run_with
(run.rs) is unchanged too.
Handlers: each Db::from(state.pool.clone()) becomes &state.pool. Each
handler that built one Db and passed it on (let db = ...) now passes &state.pool directly. That includes the mkdir_parent callbacks of write_file and write_file_batch (routes/public/files.rs). It covers middleware/auth.rs, routes/session_auth.rs, and the admin, debug, E2B
and native public routes under routes/. node_templates' per-node
inventory reads clone the field into each task, as they cloned the wrap.
Other holders:
public_sandbox_operations.rs: UpdateSandboxOperationExecutor, CreateSandboxOperationExecutor and SandboxLifecycleOperationExecutor
hold pool: Db, and new takes impl Into<Db>. Their internal wraps
become &self.pool.
fork_operation_executor.rs: ForkSandboxOperationExecutor::new takes impl Into<Db> and hands it to ForkOperationStore::new, which already
took one.
controllers/template.rs: TemplateController holds pool: Db, new
takes impl Into<Db>, and the private authorize_base takes &Db.
Callers outside api pass a PgPool to these constructors and compile
unchanged, including the cluster controller's ForkSandboxOperationExecutor::new. Nothing outside pplx-space-api
changes.
Test edits the compiler forced:
external_console/tests.rs, middleware/auth/native_federated_owner_tests.rs and routes/e2b/state_render_tests.rs: helpers that read through state.pool take &Db and run their statement through postgres-pool's Executor::into_sqlx. native_service_key_tests.rs and one drain_handler_tests.rs statement do the same inline. Each statement
still runs on state.pool. Two redundant Db::from wraps in state_render_tests.rs go.
routes/admin/nodes/drain_preview/tests.rs:
one test sets state.pool from a PgPool with .into();
lock_nodes takes a Db and returns a Tx, so the sealed probe
reuses it on state.pool;
a probe that deletes a stale node in a transaction on state.pool
passes it as &mut tx instead of &mut *tx, since that transaction is
now a Tx;
another probe ran register_k8s_node on a connection it acquired from state.pool. A Db has no acquire, so it now runs it in a
transaction on state.pool and commits at once.
controllers/template/tests.rs passes authorize_base a Db.
public_sandbox_operations/tests.rs imports PgPool, which it used to
get through super::*.
The test-only Kubernetes substrate builders (assemble_substrate in kubernetes/test_substrate.rs, and two helpers in kubernetes/tests.rs)
take impl Into<Db>, so a test can build one from state.pool.
Still naming sqlx in api production code:
Substrate::from_env and from_env_with_lifecycle
(controllers/substrate.rs) take &PgPool, as does KubernetesSubstrate::try_from_env
(controllers/substrate/kubernetes/mod.rs, with its use sqlx::PgPool).
A later change converts them.
routes/mod.rs: from_pools_with_lifecycle and #[cfg(test)] from_pool take the PgPool they pass to from_env_with_lifecycle and CredentialsPool::shared, and use sqlx::PgPool names it.
kubernetes/test_substrate.rs is compiled only for tests and the test-hooks feature. It still takes PgPool in with_seeded_caches
and in four helpers beside it. Other crates' tests call three of them: with_seeded_caches, retire_executions_predating_current_stop and release_stopped_evacuation_placement.
Error types and round-trips, not handles: DriverDbContext, DbErrorLike's AuthLookupError impl and the sqlx::Error
conversions. A later change removes them. CredentialsPool is
unchanged.
Two uses that are neither handles nor errors: routes/admin/node_store.rs
derives sqlx::FromRow on its private OccupancyRow, which tests decode
with query_as, and auth.rs imports OffsetDateTime through sqlx::types::time.
ci/scripts/run-rust-checks.sh fmt passes. cargo check --locked --workspace --all-targets --all-features and workspace clippy
(--all-targets --all-features -- -D warnings) pass with no warnings, so
the l50 service mains, the cluster controller and internal-api compile
unchanged. cargo clippy --locked -p pplx-space-api --lib -- -D warnings
passes with the default features, --features kubernetes and --all-features. ci/scripts/run-archcheck.sh against the merge base
reports no findings (2068 production Rust files). RUSTDOCFLAGS=-D warnings cargo doc --no-deps -p pplx-space-api --all-features fails with the same 30 errors as the base.
nextest with --all-features and a pinned Postgres image, for pplx-space-api (2990), pplx-space-cluster-controller-server (1461)
and pplx-space-internal-api-server (553): 5004 passed, and 1 skipped
(an #[ignore] benchmark).
A statement-log differential, two runs of the base and two of this
change, over the 1343 api route, auth, executor and template tests and
the cluster controller's operation-dispatcher tests, which build the api
executors. Postgres logged every statement with its binds. The app pool
and the credentials pool ran under distinct application_names, and
each test's database was named in the log. Rows are compared per test,
as (pool, statement, binds), with sql! locator lines, generated ids,
timestamps and timing values masked.
The two base runs agree: 748 of the 749 tests that issue SQL exactly,
and one dispatcher test, whose requeue binds vary, at statement level.
Both runs of this change match the base in every statement production
code sends, its binds and its pool. The only difference is in one test
named above, whose own fixture write now runs inside BEGIN/COMMIT
on the same pool.
A planted mutation: logout running delete_session on state.credentials_pool.db(). The differential shows DELETE FROM sessions moving from the app pool to the credentials pool in both tests
that log out, while every test still passes.
A local Kind bench built from this change, on the Kubernetes substrate,
with log_min_duration_statement = 0 on the control-plane Postgres and
its log streamed for the whole run. These scenarios pass: native.m1_generated_sdk_conformance (create, read, list, command,
process, pause, suspend, wake, delete), native_concurrency.create_idempotency, native_contract.completed_delete_replay, native_contract.access_wakes_idle_suspended_sandboxes (process
sessions), ecw.command_round_trip, ecw.fork_idempotency, ecw.fork_isolation and local.private_template_build_isolation
(template build). The log shows no ERROR or FATAL record, and every space-api statement ran as space_user, the app pool's login.
Not validated: the Direct substrate lane (no static storage credentials on
the host the Kind bench ran on), the full Kind suite and the release-build
lane.
Local review: round 1 (Codex + Claude), READY after fixes.
Severity and risk
Severity: does not apply; no behaviour changes.
Risk: a converted call that runs on another pool. The field and every wrap
it replaces are one pool, and the statement-log differential compares the
pool of each statement. Roll back by reverting the commit.
Rollout
No schema, protocol, metric or persisted-state change; Rust types only.
Old and new versions send the same statements on the same pool, so they
coexist. No sql! locator moves in a changed production file.
AI assistance: Claude Code drafted the code changes, the test updates, the
validation harness and this description.
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
Automatic approval is disabled by the configured approval policy for this pull request. Review comments and requests for changes continue normally.
Commit: f624b2b6db9f.
No actionable comments were generated in the recent review.
Walkthrough
The API now stores the shared Db handle in AppState. Controllers that own database handles accept convertible values or store Db, while middleware and route handlers pass the shared pool directly to database operations. Test helpers are updated to use the wrapper or convert it to a SQLx executor. The described changes retain existing route decisions, result handling, and response behavior.
Possibly related PRs
perplexityai/SPACE#2651: Changes substrate adapters and constructors to accept impl Into<Db>, which is related to the constructor handle changes here.
perplexityai/SPACE#2515: Changes substrate adapters and helpers from PgPool and SQLx transactions to Db and Tx, which shares the database-handle contract changed here.
Merge Risk: Minimal · previous review 72d26
This is a handle-type refactor in the API that keeps using the same database pool and statements. No behavior change is expected and no merge-blocking issue was found.
Security architecture risk: Minimal · up to 72d26
AppState and the sandbox operation executors now use the storage layer’s Db handle. In the paths reviewed, it wraps the existing PostgreSQL pool, keeps credential-fenced access on a separate pool, and preserves authorization and transaction ordering. No material security regression was established.
Security review details
Security Blast Radius
inferred — The common database handle gives this refactor broad code reach, but the inspected callers still use the same pool and database identity. The change does not establish additional tenant, credential-store, or service reachability.
Trust Boundaries and Controls
observed — Native and E2B authentication still pass request credentials to their respective API-surface lookups. Native federated resolution and owner-scoped sandbox reads and grant updates retain their existing inputs; the inspected changes replace only the database handle argument.
Pre-merge checks: 7
Check name
Status
Explanation
Title check
The title "api: AppState and the operation executors hold a Db, not a PgPool" uses the required lowercase area prefix with a colon, and the summary starts with a capitalized proper noun/code identifie…
Description Follows The Pr Template
The pull request description contains all four required items, each with real content: 1. "## Summary" section: Present. It states that AppState.pool and the remaining production pool holders in…
Bug Fixes Name A Regression Test
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, not a bug fix. Evidence: - The title states a type ch…
Weakened Safeguards Are Justified
The check fails only if the diff removes, disables, narrows, or weakens a test, assertion, lint, CI check, or repository guard without a stated reason. This PR does not do that. Evidence: - The review…
Agent Tooling Runs No New Commands
The check applies only when the diff adds or changes agent plugin manifests, skills, or guideline files that run commands or start servers. The pull request changes 56 files. I listed them with `git d…
External Code Sources Need A Person
The check fails only if the diff adds or changes an external code source: a Cargo.toml dependency source key (git, rev, branch, tag, registry, or an out-of-repo path), a container image reference, a d…
Public-Safe Content
Public-safe content check: no sensitive content found in the diff, title, or description. Evidence: - The diff (56 changed files, all under crates/l40_api/api/src/) was scanned for added lines with …
Full details: Title check
Explanation
The title "api: AppState and the operation executors hold a Db, not a PgPool" uses the required lowercase area prefix with a colon, and the summary starts with a capitalized proper noun/code identifier (AppState), which the requirements allow. It describes the main change: AppState.pool, the operation executors, and TemplateController moving from PgPool to postgres-pool's Db. It has no trailing period, ticket ID, or link. The title is accurate to the changeset and meets the format requirement.
Full details: Description Follows The Pr Template
Explanation
The pull request description contains all four required items, each with real content: 1. "## Summary" section: Present. It states that AppState.pool and the remaining production pool holders in pplx-space-api change from sqlx::PgPool to Db, and that statements run on the same pool and transactions. 2. "## Validation" section: Present. It names the checks run (fmt, cargo check, clippy across feature sets, archcheck, rustdoc, nextest, a statement-log differential, a planted mutation, and a Kind bench) and reports results, including the rustdoc failure that matches the base. 3. "## Severity and risk" section: Present. It gives "Severity: does not apply; no behaviour changes." It also gives a risk: a converted call running on another pool, with the rollback path. 4. "AI assistance:" line: Present. It reads "AI assistance: Claude Code drafted the code changes, the test updates, the validation harness and this description." This check assesses description structure only. Per the instructions, presence is judged, not quality. No code evidence was needed, and none was gathered.
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, not a bug fix. Evidence: - The title states a type change: "AppState and the operation executors hold a Db, not a PgPool." - The raw summary describes signature and handle-type changes. Examples include AppState.pool: PgPool → Db, impl Into<Db> constructors, and Db::from(state.pool.clone()) wraps replaced by &state.pool. - The contributor's description says "Severity: does not apply; no behaviour changes" and "Only Rust handle types change." - The PR objectives describe the same change: statements run on the same pool and in the same transactions. - The validation section reports a statement-log differential. It found production statements, binds, and pools unchanged from the base. It also reports no new regression test, because none is needed for a non-fix. Because the PR is not an application bug fix, the check passes. No regression test is required.
Full details: Weakened Safeguards Are Justified
Explanation
The check fails only if the diff removes, disables, narrows, or weakens a test, assertion, lint, CI check, or repository guard without a stated reason. This PR does not do that. Evidence: - The reviewed range changes 80 files, all Rust files under crates/l40_api/api/src. No CI workflows, Cargo.toml lint tables, .config/nextest.toml, deny.toml, ci/ scripts, allowlists, baselines, budgets, or AGENTS/CLAUDE/CONTRIBUTING files change. - The diff adds or removes no #[allow], #[expect], #[ignore], #[test], or other attributes. It adds no skip, xfail, continue-on-error, || true, or set +e. - No assert!, assert_eq!, or should_panic line is removed. The only .expect( lines that change are .expect("...") calls moved onto new call lines. - Removed fn lines are signature changes from PgPool to Db or impl Into<Db>, such as federated_row_versions, session_exists, session_count, and lock_nodes. Their bodies keep the same queries and assertions. - The test edits in drain_preview/tests.rs replace a connection acquire() with a begin()/commit() transaction. The probe's assertions remain. The PR description states this is a forced test edit, and it does not weaken any expectation. No item in the check's list is triggered.
Full details: Agent Tooling Runs No New Commands
Explanation
The check applies only when the diff adds or changes agent plugin manifests, skills, or guideline files that run commands or start servers. The pull request changes 56 files. I listed them with git diff --name-status against the review base and head refs, and every changed file ends in .rs. None of them is a plugin manifest (plugin.json/plugin.yaml), SKILL.md, CLAUDE.md, AGENTS.md, or a file under an agent-tooling directory. A search of the added diff lines for inline shell substitution (! followed by a backtick), hooks, mcp_servers, allowed-tools, and lsp returned no matches. The pull request is a Rust handle-type refactor (PgPool to Db) in pplx-space-api, with no agent-tooling content. No failure condition applies.
Full details: External Code Sources Need A Person
Explanation
The check fails only if the diff adds or changes an external code source: a Cargo.toml dependency source key (git, rev, branch, tag, registry, or an out-of-repo path), a container image reference, a downloaded binary or archive URL/checksum, or a Helm chart dependency. Evidence: - The changed-file inventory (git diff --name-status between the review base and head refs) lists 84 entries. Every entry is M (modified). All of them are Rust source or test files under crates/l40_api/api/src/. - No Cargo.toml, Cargo.lock, Dockerfile, Chart.yaml, Chart.lock, YAML, or shell script appears in the diff. - A search of the patch for dependency-source keys, image references, URLs, and checksums in those file types returned no matching lines. The PR changes Rust handle types only (PgPool to Db, and impl Into<Db> constructors). The PR description also states that nothing outside pplx-space-api changes. No external code source is added or changed, so the check does not apply.
Full details: Public-Safe Content
Explanation
Public-safe content check: no sensitive content found in the diff, title, or description. Evidence: - The diff (56 changed files, all under crates/l40_api/api/src/) was scanned for added lines with URLs, IPv4 addresses, ARNs, 12-digit account-style numbers, long hex or base64 strings, PEM or AKIA key markers, and absolute /Users/ or /home/ paths. None were found. - Keyword hits for "token", "pool", and "prod" were code identifiers (for example token: &str, &state.pool), not secrets or sensitive values. - No string literal in the added lines looks like a credential. - The PR title and description contain no URLs, hostnames, internal trackers, chat links, or personal paths. The description names a DB login role (space_user) and a PR number (#2662). Neither is a credential or internal host. - The description reports test and validation counts and a statement-log comparison. It does not include raw production logs or query output. - The description has no "Created with ..." line. The "AI assistance" line names no link or internal value. No finding to report.
Recent review info
Automatic approval policy
Commit: f624b2b6db9f.
Setting
Effective value
Source
Automatic approvals
Disabled
Override 3
Merge risk
Moderate
Global configuration
Security risk
Not set
Global configuration
Matching overrides (numbered as in the resolved configuration):
Any matching disabled override withholds approval, regardless of risk. Otherwise, the strictest explicitly set limit wins for each score. Limits omitted by all matching overrides inherit the global configuration.
Not set means no limit was configured after inheritance. Use @coderabbitai configuration to inspect the resolved settings and their sources.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.
## Summary
`AppState.pool` is now postgres-pool's `Db`, and so are the last
production holders of a `sqlx::PgPool` in `pplx-space-api`. Every
statement runs on the same pool as before, in the same transactions. The
roughly 170 `Db::from(state.pool.clone())` wraps that `&state.pool`
replaces always wrapped that same pool. Only Rust handle types change.
`AppState` (`routes/mod.rs`):
- `pub pool: PgPool` becomes `pub pool: Db`. The field keeps its name, so
handlers read `&state.pool` where they wrapped it. The name reads oddly
in three kinds of place:
- where a transaction begins on it: `state.pool.begin()` in
`routes/admin/{identity,node_groups,nodes,runtime_environments,template_visibility,templates}.rs`
and `routes/public/ports.rs`;
- wherever it is passed to a parameter named `db`;
- in `session_user` and `public_session_store`, which pass `self.pool`.
- `from_pools_with_lifecycle` still takes the `PgPool`, because
`Substrate::from_env_with_lifecycle` (`controllers/substrate.rs`) takes
`&PgPool` until a later change converts it. It passes that pool to the
substrate as before, then wraps it in a `Db` once for everything else.
- `#[cfg(test)] from_pool` is unchanged. It hands the same `PgPool` to
`from_pools_with_lifecycle` and to `CredentialsPool::shared`. `run_with`
(`run.rs`) is unchanged too.
Handlers: each `Db::from(state.pool.clone())` becomes `&state.pool`. Each
handler that built one `Db` and passed it on (`let db = ...`) now passes
`&state.pool` directly. That includes the `mkdir_parent` callbacks of
`write_file` and `write_file_batch` (`routes/public/files.rs`). It covers
`middleware/auth.rs`, `routes/session_auth.rs`, and the admin, debug, E2B
and native public routes under `routes/`. `node_templates`' per-node
inventory reads clone the field into each task, as they cloned the wrap.
Other holders:
- `public_sandbox_operations.rs`: `UpdateSandboxOperationExecutor`,
`CreateSandboxOperationExecutor` and `SandboxLifecycleOperationExecutor`
hold `pool: Db`, and `new` takes `impl Into<Db>`. Their internal wraps
become `&self.pool`.
- `fork_operation_executor.rs`: `ForkSandboxOperationExecutor::new` takes
`impl Into<Db>` and hands it to `ForkOperationStore::new`, which already
took one.
- `controllers/template.rs`: `TemplateController` holds `pool: Db`, `new`
takes `impl Into<Db>`, and the private `authorize_base` takes `&Db`.
Callers outside api pass a `PgPool` to these constructors and compile
unchanged, including the cluster controller's
`ForkSandboxOperationExecutor::new`. Nothing outside `pplx-space-api`
changes.
Test edits the compiler forced:
- `external_console/tests.rs`,
`middleware/auth/native_federated_owner_tests.rs` and
`routes/e2b/state_render_tests.rs`: helpers that read through
`state.pool` take `&Db` and run their statement through postgres-pool's
`Executor::into_sqlx`. `native_service_key_tests.rs` and one
`drain_handler_tests.rs` statement do the same inline. Each statement
still runs on `state.pool`. Two redundant `Db::from` wraps in
`state_render_tests.rs` go.
- `routes/admin/nodes/drain_preview/tests.rs`:
- one test sets `state.pool` from a `PgPool` with `.into()`;
- `lock_nodes` takes a `Db` and returns a `Tx`, so the sealed probe
reuses it on `state.pool`;
- a probe that deletes a stale node in a transaction on `state.pool`
passes it as `&mut tx` instead of `&mut *tx`, since that transaction is
now a `Tx`;
- another probe ran `register_k8s_node` on a connection it acquired from
`state.pool`. A `Db` has no `acquire`, so it now runs it in a
transaction on `state.pool` and commits at once.
- `controllers/template/tests.rs` passes `authorize_base` a `Db`.
- `public_sandbox_operations/tests.rs` imports `PgPool`, which it used to
get through `super::*`.
- The test-only Kubernetes substrate builders (`assemble_substrate` in
`kubernetes/test_substrate.rs`, and two helpers in `kubernetes/tests.rs`)
take `impl Into<Db>`, so a test can build one from `state.pool`.
Still naming sqlx in api production code:
- `Substrate::from_env` and `from_env_with_lifecycle`
(`controllers/substrate.rs`) take `&PgPool`, as does
`KubernetesSubstrate::try_from_env`
(`controllers/substrate/kubernetes/mod.rs`, with its `use sqlx::PgPool`).
A later change converts them.
- `routes/mod.rs`: `from_pools_with_lifecycle` and `#[cfg(test)]
from_pool` take the `PgPool` they pass to `from_env_with_lifecycle` and
`CredentialsPool::shared`, and `use sqlx::PgPool` names it.
- `kubernetes/test_substrate.rs` is compiled only for tests and the
`test-hooks` feature. It still takes `PgPool` in `with_seeded_caches`
and in four helpers beside it. Other crates' tests call three of them:
`with_seeded_caches`, `retire_executions_predating_current_stop` and
`release_stopped_evacuation_placement`.
- Error types and round-trips, not handles: `DriverDbContext`,
`DbErrorLike`'s `AuthLookupError` impl and the `sqlx::Error`
conversions. A later change removes them. `CredentialsPool` is
unchanged.
- Two uses that are neither handles nor errors: `routes/admin/node_store.rs`
derives `sqlx::FromRow` on its private `OccupancyRow`, which tests decode
with `query_as`, and `auth.rs` imports `OffsetDateTime` through
`sqlx::types::time`.
## Validation
At this head, on `main` at #2662:
- `ci/scripts/run-rust-checks.sh fmt` passes. `cargo check --locked
--workspace --all-targets --all-features` and workspace clippy
(`--all-targets --all-features -- -D warnings`) pass with no warnings, so
the l50 service mains, the cluster controller and internal-api compile
unchanged. `cargo clippy --locked -p pplx-space-api --lib -- -D warnings`
passes with the default features, `--features kubernetes` and
`--all-features`. `ci/scripts/run-archcheck.sh` against the merge base
reports no findings (2068 production Rust files).
`RUSTDOCFLAGS=-D warnings cargo doc --no-deps -p pplx-space-api
--all-features` fails with the same 30 errors as the base.
- nextest with `--all-features` and a pinned Postgres image, for
`pplx-space-api` (2990), `pplx-space-cluster-controller-server` (1461)
and `pplx-space-internal-api-server` (553): 5004 passed, and 1 skipped
(an `#[ignore]` benchmark).
- A statement-log differential, two runs of the base and two of this
change, over the 1343 api route, auth, executor and template tests and
the cluster controller's operation-dispatcher tests, which build the api
executors. Postgres logged every statement with its binds. The app pool
and the credentials pool ran under distinct `application_name`s, and
each test's database was named in the log. Rows are compared per test,
as (pool, statement, binds), with `sql!` locator lines, generated ids,
timestamps and timing values masked.
- The two base runs agree: 748 of the 749 tests that issue SQL exactly,
and one dispatcher test, whose requeue binds vary, at statement level.
- Both runs of this change match the base in every statement production
code sends, its binds and its pool. The only difference is in one test
named above, whose own fixture write now runs inside `BEGIN`/`COMMIT`
on the same pool.
- A planted mutation: logout running `delete_session` on
`state.credentials_pool.db()`. The differential shows `DELETE FROM
sessions` moving from the app pool to the credentials pool in both tests
that log out, while every test still passes.
- A local Kind bench built from this change, on the Kubernetes substrate,
with `log_min_duration_statement = 0` on the control-plane Postgres and
its log streamed for the whole run. These scenarios pass:
`native.m1_generated_sdk_conformance` (create, read, list, command,
process, pause, suspend, wake, delete),
`native_concurrency.create_idempotency`,
`native_contract.completed_delete_replay`,
`native_contract.access_wakes_idle_suspended_sandboxes` (process
sessions), `ecw.command_round_trip`, `ecw.fork_idempotency`,
`ecw.fork_isolation` and `local.private_template_build_isolation`
(template build). The log shows no ERROR or FATAL record, and every
`space-api` statement ran as `space_user`, the app pool's login.
Not validated: the Direct substrate lane (no static storage credentials on
the host the Kind bench ran on), the full Kind suite and the release-build
lane.
Local review: round 1 (Codex + Claude), READY after fixes.
## Severity and risk
Severity: does not apply; no behaviour changes.
Risk: a converted call that runs on another pool. The field and every wrap
it replaces are one pool, and the statement-log differential compares the
pool of each statement. Roll back by reverting the commit.
## Rollout
No schema, protocol, metric or persisted-state change; Rust types only.
Old and new versions send the same statements on the same pool, so they
coexist. No `sql!` locator moves in a changed production file.
AI assistance: Claude Code drafted the code changes, the test updates, the
validation harness and this description.
## 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 its
reference queries' 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, which
take the driver pool that `CredentialsPool::shared` also needs.
- `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
At this head, on #2689 at `72d2650f` (on `main` at `8e0f72e3`):
- `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.
Not validated: the Kind suite and the Direct substrate lane.
## 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.
AI assistance: Claude Code drafted the code changes, the disposable proofs
and this description.
Rebased onto main at 7704d88 (#2668 edited controllers/substrate/kubernetes/tests.rs too). The patch is unchanged: git range-diff shows the commit as identical (=), 72d2650 → f624b2b. #2668's new &PgPool test helpers are called with the test database's pool, not state.pool, so they're unaffected.
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
kind-smokeRun the Kind/Firecracker smoke on this PR, whatever it changes, from its next pushtriage:pendingWaiting for a maintainer to triage
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
AppState.poolis now postgres-pool'sDb, and so are the lastproduction holders of a
sqlx::PgPoolinpplx-space-api. Everystatement runs on the same pool as before, in the same transactions. The
roughly 170
Db::from(state.pool.clone())wraps that&state.poolreplaces always wrapped that same pool. Only Rust handle types change.
AppState(routes/mod.rs):pub pool: PgPoolbecomespub pool: Db. The field keeps its name, sohandlers read
&state.poolwhere they wrapped it. The name reads oddlyin three kinds of place:
state.pool.begin()inroutes/admin/{identity,node_groups,nodes,runtime_environments,template_visibility,templates}.rsand
routes/public/ports.rs;db;session_userandpublic_session_store, which passself.pool.from_pools_with_lifecyclestill takes thePgPool, becauseSubstrate::from_env_with_lifecycle(controllers/substrate.rs) takes&PgPooluntil a later change converts it. It passes that pool to thesubstrate as before, then wraps it in a
Dbonce for everything else.#[cfg(test)] from_poolis unchanged. It hands the samePgPooltofrom_pools_with_lifecycleand toCredentialsPool::shared.run_with(
run.rs) is unchanged too.Handlers: each
Db::from(state.pool.clone())becomes&state.pool. Eachhandler that built one
Dband passed it on (let db = ...) now passes&state.pooldirectly. That includes themkdir_parentcallbacks ofwrite_fileandwrite_file_batch(routes/public/files.rs). It coversmiddleware/auth.rs,routes/session_auth.rs, and the admin, debug, E2Band native public routes under
routes/.node_templates' per-nodeinventory reads clone the field into each task, as they cloned the wrap.
Other holders:
public_sandbox_operations.rs:UpdateSandboxOperationExecutor,CreateSandboxOperationExecutorandSandboxLifecycleOperationExecutorhold
pool: Db, andnewtakesimpl Into<Db>. Their internal wrapsbecome
&self.pool.fork_operation_executor.rs:ForkSandboxOperationExecutor::newtakesimpl Into<Db>and hands it toForkOperationStore::new, which alreadytook one.
controllers/template.rs:TemplateControllerholdspool: Db,newtakes
impl Into<Db>, and the privateauthorize_basetakes&Db.Callers outside api pass a
PgPoolto these constructors and compileunchanged, including the cluster controller's
ForkSandboxOperationExecutor::new. Nothing outsidepplx-space-apichanges.
Test edits the compiler forced:
external_console/tests.rs,middleware/auth/native_federated_owner_tests.rsandroutes/e2b/state_render_tests.rs: helpers that read throughstate.pooltake&Dband run their statement through postgres-pool'sExecutor::into_sqlx.native_service_key_tests.rsand onedrain_handler_tests.rsstatement do the same inline. Each statementstill runs on
state.pool. Two redundantDb::fromwraps instate_render_tests.rsgo.routes/admin/nodes/drain_preview/tests.rs:state.poolfrom aPgPoolwith.into();lock_nodestakes aDband returns aTx, so the sealed probereuses it on
state.pool;state.poolpasses it as
&mut txinstead of&mut *tx, since that transaction isnow a
Tx;register_k8s_nodeon a connection it acquired fromstate.pool. ADbhas noacquire, so it now runs it in atransaction on
state.pooland commits at once.controllers/template/tests.rspassesauthorize_baseaDb.public_sandbox_operations/tests.rsimportsPgPool, which it used toget through
super::*.assemble_substrateinkubernetes/test_substrate.rs, and two helpers inkubernetes/tests.rs)take
impl Into<Db>, so a test can build one fromstate.pool.Still naming sqlx in api production code:
Substrate::from_envandfrom_env_with_lifecycle(
controllers/substrate.rs) take&PgPool, as doesKubernetesSubstrate::try_from_env(
controllers/substrate/kubernetes/mod.rs, with itsuse sqlx::PgPool).A later change converts them.
routes/mod.rs:from_pools_with_lifecycleand#[cfg(test)] from_pooltake thePgPoolthey pass tofrom_env_with_lifecycleandCredentialsPool::shared, anduse sqlx::PgPoolnames it.kubernetes/test_substrate.rsis compiled only for tests and thetest-hooksfeature. It still takesPgPoolinwith_seeded_cachesand in four helpers beside it. Other crates' tests call three of them:
with_seeded_caches,retire_executions_predating_current_stopandrelease_stopped_evacuation_placement.DriverDbContext,DbErrorLike'sAuthLookupErrorimpl and thesqlx::Errorconversions. A later change removes them.
CredentialsPoolisunchanged.
routes/admin/node_store.rsderives
sqlx::FromRowon its privateOccupancyRow, which tests decodewith
query_as, andauth.rsimportsOffsetDateTimethroughsqlx::types::time.Validation
At this head, on
mainat #2662:ci/scripts/run-rust-checks.sh fmtpasses.cargo check --locked --workspace --all-targets --all-featuresand workspace clippy(
--all-targets --all-features -- -D warnings) pass with no warnings, sothe l50 service mains, the cluster controller and internal-api compile
unchanged.
cargo clippy --locked -p pplx-space-api --lib -- -D warningspasses with the default features,
--features kubernetesand--all-features.ci/scripts/run-archcheck.shagainst the merge basereports no findings (2068 production Rust files).
RUSTDOCFLAGS=-D warnings cargo doc --no-deps -p pplx-space-api --all-featuresfails with the same 30 errors as the base.--all-featuresand a pinned Postgres image, forpplx-space-api(2990),pplx-space-cluster-controller-server(1461)and
pplx-space-internal-api-server(553): 5004 passed, and 1 skipped(an
#[ignore]benchmark).change, over the 1343 api route, auth, executor and template tests and
the cluster controller's operation-dispatcher tests, which build the api
executors. Postgres logged every statement with its binds. The app pool
and the credentials pool ran under distinct
application_names, andeach test's database was named in the log. Rows are compared per test,
as (pool, statement, binds), with
sql!locator lines, generated ids,timestamps and timing values masked.
and one dispatcher test, whose requeue binds vary, at statement level.
code sends, its binds and its pool. The only difference is in one test
named above, whose own fixture write now runs inside
BEGIN/COMMITon the same pool.
delete_sessiononstate.credentials_pool.db(). The differential showsDELETE FROM sessionsmoving from the app pool to the credentials pool in both teststhat log out, while every test still passes.
with
log_min_duration_statement = 0on the control-plane Postgres andits log streamed for the whole run. These scenarios pass:
native.m1_generated_sdk_conformance(create, read, list, command,process, pause, suspend, wake, delete),
native_concurrency.create_idempotency,native_contract.completed_delete_replay,native_contract.access_wakes_idle_suspended_sandboxes(processsessions),
ecw.command_round_trip,ecw.fork_idempotency,ecw.fork_isolationandlocal.private_template_build_isolation(template build). The log shows no ERROR or FATAL record, and every
space-apistatement ran asspace_user, the app pool's login.Not validated: the Direct substrate lane (no static storage credentials on
the host the Kind bench ran on), the full Kind suite and the release-build
lane.
Local review: round 1 (Codex + Claude), READY after fixes.
Severity and risk
Severity: does not apply; no behaviour changes.
Risk: a converted call that runs on another pool. The field and every wrap
it replaces are one pool, and the statement-log differential compares the
pool of each statement. Roll back by reverting the commit.
Rollout
No schema, protocol, metric or persisted-state change; Rust types only.
Old and new versions send the same statements on the same pool, so they
coexist. No
sql!locator moves in a changed production file.AI assistance: Claude Code drafted the code changes, the test updates, the
validation harness and this description.