Skip to content

api: AppState and the operation executors hold a Db, not a PgPool - #2689

Open
ac-pplx wants to merge 1 commit into
mainfrom
ac/api2-AH6-api-appstate-db
Open

ac-pplx wants to merge 1 commit into
mainfrom
ac/api2-AH6-api-appstate-db

Conversation

@ac-pplx

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

Copy link
Copy Markdown
Contributor

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_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 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

Explain Change →

Automatic approval withheld

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: Passed 7

Check name Status Explanation
Title check Passed 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 Passed 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 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, not a bug fix. Evidence: - The title states a type ch…
Weakened Safeguards Are Justified Passed 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 Passed 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 Passed 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 Passed 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&lt;Db&gt; constructors, and Db::from(state.pool.clone()) wraps replaced by &amp;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&lt;Db&gt;, 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&lt;Db&gt; 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: &amp;str, &amp;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):

  • Override 3 — any author; paths: .coderabbit.yaml, .coderabbit.yml, coderabbit.yaml, coderabbit.yml, .coderabbit.config.ts, .github/**, ci/scripts/ci-image.sh, ci/scripts/mirror-images.sh, ci/scripts/lib/test-deps.sh, ci/scripts/run-space-bundle-builds.py, ci/scripts/ensure-uv.sh, ci/scripts/tfswitch-lite.sh, ci/scripts/notify-main-ci-failure.sh, templates/firecracker/kernel/ci.sh, ci/Dockerfile.ci, ci/mirrored-images.txt, ci/scripts/pull-ci-reuse.py, .claude/settings*.json, **/.mcp.json, **/hooks.json, .agents/plugins/**/hooks/**, .agents/plugins/**/scripts/**, .agents/plugins/**/commands/**, .agents/plugins/**/agents/**, **/skills/**/hooks/**, **/skills/**/scripts/**, **/skills/**/commands/**, **/skills/**/agents/**, .claude/commands/**, .claude/agents/**, **/marketplace.json, .pre-commit-config.yaml, lefthook.yaml, .cargo/**, rust-toolchain.toml, supply-chain/**, **/pyproject.toml, **/uv.lock, **/package.json, **/package-lock.json, **/go.mod, **/go.sum, **/requirements*.txt, **/requirements*.in, db/**, !db/README.md, proto/**, docs/versioning.md, ci/guest-update-required-since, crates/l40_api/api/src/auth.rs, crates/l40_api/api/src/auth/**, crates/l40_api/api/src/middleware/auth*, crates/l40_api/api/src/middleware/auth/**, crates/l40_api/api/src/routes/authz.rs, crates/l10_foundation/bearer/**, crates/l10_foundation/rustls/**, crates/l10_foundation/guest/**, crates/l10_foundation/pii/**, infra/space/aws/**, infra/space/cluster/**, infra/space/identity/**, infra/space/observability/**, infra/space/packer/**, LICENSE, SECURITY.md; automatic approvals: disabled.

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.

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 8e0f72e and 72d2650.

Files selected for processing: 56

  • crates/l40_api/api/src/controllers/substrate/kubernetes/test_substrate.rs
  • crates/l40_api/api/src/controllers/substrate/kubernetes/tests.rs
  • crates/l40_api/api/src/controllers/template.rs
  • crates/l40_api/api/src/controllers/template/tests.rs
  • crates/l40_api/api/src/external_console/tests.rs
  • crates/l40_api/api/src/fork_operation_executor.rs
  • crates/l40_api/api/src/middleware/auth.rs
  • crates/l40_api/api/src/middleware/auth/native_federated_owner_tests.rs
  • crates/l40_api/api/src/middleware/auth/native_service_key_tests.rs
  • crates/l40_api/api/src/public_sandbox_operations.rs
  • crates/l40_api/api/src/public_sandbox_operations/tests.rs
  • crates/l40_api/api/src/routes/admin/api_keys.rs
  • crates/l40_api/api/src/routes/admin/audit.rs
  • crates/l40_api/api/src/routes/admin/firewall_rules.rs
  • crates/l40_api/api/src/routes/admin/identity.rs
  • crates/l40_api/api/src/routes/admin/mod.rs
  • crates/l40_api/api/src/routes/admin/node_groups.rs
  • crates/l40_api/api/src/routes/admin/node_maintenance.rs
  • crates/l40_api/api/src/routes/admin/node_maintenance/node_status.rs
  • crates/l40_api/api/src/routes/admin/node_maintenance/node_templates.rs
  • crates/l40_api/api/src/routes/admin/nodes.rs
  • crates/l40_api/api/src/routes/admin/nodes/drain_handler_tests.rs
  • crates/l40_api/api/src/routes/admin/nodes/drain_preview.rs
  • crates/l40_api/api/src/routes/admin/nodes/drain_preview/tests.rs
  • crates/l40_api/api/src/routes/admin/nodes/drain_v2.rs
  • crates/l40_api/api/src/routes/admin/nodes/holds.rs
  • crates/l40_api/api/src/routes/admin/nodes/read_state.rs
  • crates/l40_api/api/src/routes/admin/operations.rs
  • crates/l40_api/api/src/routes/admin/runtime_environments.rs
  • crates/l40_api/api/src/routes/admin/runtime_upgrade_campaigns.rs
  • crates/l40_api/api/src/routes/admin/sandbox_list.rs
  • crates/l40_api/api/src/routes/admin/sandboxes.rs
  • crates/l40_api/api/src/routes/admin/sandboxes/guest_access.rs
  • crates/l40_api/api/src/routes/admin/template_visibility.rs
  • crates/l40_api/api/src/routes/admin/templates.rs
  • crates/l40_api/api/src/routes/admin/warm_pools.rs
  • crates/l40_api/api/src/routes/debug/sandbox.rs
  • crates/l40_api/api/src/routes/e2b/fork.rs
  • crates/l40_api/api/src/routes/e2b/lifecycle.rs
  • crates/l40_api/api/src/routes/e2b/state_render_tests.rs
  • crates/l40_api/api/src/routes/e2b/template_build/handlers.rs
  • crates/l40_api/api/src/routes/e2b/translate.rs
  • crates/l40_api/api/src/routes/mod.rs
  • crates/l40_api/api/src/routes/public/credential_references.rs
  • crates/l40_api/api/src/routes/public/files.rs
  • crates/l40_api/api/src/routes/public/files/access.rs
  • crates/l40_api/api/src/routes/public/network_policy.rs
  • crates/l40_api/api/src/routes/public/owner_scope.rs
  • crates/l40_api/api/src/routes/public/ports.rs
  • crates/l40_api/api/src/routes/public/processes.rs
  • crates/l40_api/api/src/routes/public/sandboxes.rs
  • crates/l40_api/api/src/routes/public/sessions.rs
  • crates/l40_api/api/src/routes/public/snapshots.rs
  • crates/l40_api/api/src/routes/public/templates.rs
  • crates/l40_api/api/src/routes/public/timeout.rs
  • crates/l40_api/api/src/routes/session_auth.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@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 2 times, most recently from 1888f86 to 72d2650 Compare December 2, 2026 08:42
@ac-pplx
ac-pplx marked this pull request as ready for review December 2, 2026 09:02
## 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.
@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 added a commit that referenced this pull request Dec 2, 2026
## 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.
@ac-pplx

ac-pplx commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

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
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