#2630

api: move the routes outside admin onto postgres-pool's Db and Tx

Draftac-pplxwants to merge intofrom

Summary

The pplx-space-api route modules outside routes/admin/ now hold and pass postgres-pool's handles (Db, Tx) instead of the driver's (PgPool, sqlx::Transaction), apart from the PgPool uses listed at the end of "Calls into the sandbox controller". Their storage errors were already classified on DbError, apart from the authz.rs checks, which still return sqlx::Error (see the last section). This changes only the handle types. It is a refactor. These are unchanged:

  • the SQL sent, apart from one sql! locator comment (listed under Mixed-version safety);
  • transaction boundaries, and which pool each statement runs on;
  • HTTP statuses, bodies and headers;
  • metrics.

AppState.pool stays a PgPool. Handlers pass &Db::from(state.pool.clone()), which shares the same pool (an Arc clone). Where several calls in one handler share it, the handler builds the Db once.

Handle types, by file (under crates/l40_api/api/src/routes/):

  • authz.rs: all seven checks take &Db (is_managing_org_admin, visible_org_ids, user_can_access_org, can_manage_users_in_org, can_create_user_with_role, can_update_user_profile, can_update_user_role). Every store verb they call already took impl Executor. They still return sqlx::Error (see the last section).
  • session_auth.rs: create_session_for_password, delete_session and fetch_cluster take &Db. The login transaction begins with Db::begin, and its three statements take &mut tx. The DbError::from wraps on its begin and commit became identity conversions, so they are gone. create_session builds one Db for both of its login paths.
  • debug/sources/: the begin_read_only helper is gone. Each of the seven sources (lifecycle, observed, pods, ports, quarantine, snapshots, timeline) takes &Db and opens its transaction with Db::begin_snapshot, which sends the same BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY. The module doc keeps the reason for REPEATABLE READ. debug/sandbox.rs builds one Db for the seven sources and passes one to the operator gate.
  • e2b/template_build/state.rs: TemplateBuildState holds a Db, and new takes impl Into<Db>. The PgPool caller in routes/mod.rs compiles unchanged.
  • e2b/fork.rs: prepare_fork_owner and resolve_fork_replay_org_id take &Db. The handler builds one Db for both, and the Db::from wrap around materialize_owner goes.
  • public/owner_scope.rs: authorized_sandbox takes &Db.
  • public/files.rs (its ensure_sandbox_owner and the 11 handlers that call it), public/files/access.rs, public/processes.rs and public/ports.rs pass a Db to it. public/files.rs's impl FileCallFailure for ControllerError is untouched.
  • public/ports.rs: record_idempotent_port_response begins on a Db. Its two statements take &mut tx: delete_expired_idempotency_record_tx already takes the caller-transaction shape, and insert_native_post_reply_if_absent takes impl Executor. Its three DbError::from wraps went the same way as session_auth.rs's.
  • public/network_policy.rs: ensure_sandbox_owner takes &Db.
  • public/sandboxes.rs: read_public_sandbox, delete_replay_in_owner_scope, enqueue_lifecycle_operation, ensure_sandbox_owner, fetch_public_sandbox and fetch_sandboxes_page take &Db. The two that build a PublicOperationStore pass it db.clone(). public/timeout.rs passes a Db to read_public_sandbox.
  • public/sessions.rs: enqueue_implicit_wake, queue_implicit_wake and ensure_sandbox_owner take &Db. The process-session and command handlers build one Db for the owner check and the wake.
  • public/snapshots.rs: snapshot_page, fetch_snapshot_rows and fetch_snapshot_row take &Db. public/templates.rs: fetch_template_rows and fetch_template_variants take &Db, and each handler builds one Db.

Every converted parameter is &Db, apart from the impl Into<Db> that TemplateBuildState::new and ingress_activation take. No function in these modules takes a transaction parameter, so neither &mut Tx<'_> nor the caller-transaction shape appears. The two transactions they open (session_auth.rs, public/ports.rs) and the seven snapshot transactions are local Txs, passed to verbs as &mut tx.

Callers changed in other areas

These are compiler-forced, one wrap each, because the caller still holds a PgPool. Each passes &pplx_space_postgres_pool::Db::from(..clone()):

  • routes/admin/identity.rs: can_create_user_with_role, can_update_user_profile, can_update_user_role, is_managing_org_admin.
  • routes/admin/mod.rs (require_admin_auth) and routes/admin/support.rs (require_managing_org_admin): is_managing_org_admin.
  • routes/admin/templates.rs: is_managing_org_admin (require_template_admin) and visible_org_ids (query_template_releases).
  • routes/admin/sandboxes/guest_access.rs: snapshot_page.
  • In tests, controllers/sandbox/queries/create_postgres_tests.rs: read_public_sandbox.

This area's own tests pass &Db::from(db.pool.clone()) where they call a converted function: debug/sources/pods/tests.rs, e2b/fork/tests.rs, e2b/state_render_tests.rs, public/sandboxes/tests.rs, public/sandboxes/tests/substrate_scope.rs, public/sessions/tests.rs and session_auth/tests.rs. debug/sources/pods/tests.rs and e2b/template_build/state/tests.rs now import the PgPool they used to get through use super::*. session_auth/tests.rs and e2b/state_render_tests.rs import Db.

Calls into the sandbox controller

The sandbox controller takes &Db (#2637), so the calls this area makes into it pass the handler's Db:

  • SandboxController methods: tracked_response, scoped_sandbox, scoped_sandbox_page and action; upsert_federated_service_grant, set_access_idle_timeout, set_auto_lifecycle_policy and stats; ensure_sandbox_port_exposure_applied, open_sandbox_port, close_sandbox_port and list_sandbox_port_exposures; the spaced_* file and process calls, and spaced_runtime_grant; create and plan_admission_pool_claim. The free functions resolve_template_release_by_tag and gate_template_access likewise.
  • Each handler that makes more than one such call, or one beside its own converted calls, builds one Db and passes it to all of them: public/files.rs (stat_file, list_files, read_file, write_file, write_file_batch, mkdir_file, remove_file, rename_file, enable_file_change_tracking, disable_file_change_tracking, modified_files), public/owner_scope.rs (authorize_request), public/ports.rs (apply_port_action), public/sessions.rs (create_port_session, create_protocol_session), public/timeout.rs (set_timeout), e2b/lifecycle.rs (connect_sandbox_inner, action_sandbox_e2b, timeout_sandbox), and e2b/template_build/handlers.rs (check_alias).
  • public/sandboxes.rs: create_native_sandbox_operation takes &Db. It passes it to plan_admission_pool_claim and gives PublicOperationStore::new db.clone(); the create handler passes &Db::from(state.pool.clone()), and its tests (public/sandboxes/tests.rs, admission_test_fixture.rs, inline_create/tests.rs) a Db over their pool. public/sandboxes/tests.rs now imports the PgPool it used to get through use super::*.
  • controllers/sandbox/ingress.rs: StoredAccess holds a Db, and ingress_activation takes impl Into<Db>, so its caller in ingress_activation.rs passes state.pool.clone() unchanged. Its fetch_sandbox and restore_owner_active reads, its queue_implicit_wake call, the drain gate, action and connect_spaced_runtime_client take &self.db. Its tests build the field from Db::from(db.pool.clone()), and ingress/tests.rs imports PgPool.
  • CreateSandboxOperationExecutor in public_sandbox_operations.rs keeps the PgPool that public/sandboxes/inline_create.rs builds it from: that is the operation executors' own handle type, and its controller calls wrap it.

Some calls still pass &state.pool to functions that take impl Executor, through postgres-pool's transitional Executor implementation for &PgPool: fetch_sandbox in public/sandboxes.rs, public/timeout.rs, public/network_policy.rs and public/operations.rs; organization_has_local_owner in public/owner_scope.rs; find_live_native_post_reply in public/ports.rs; bind_idempotency_key in public/files/key_binding.rs; and ecw_credential_epochs::advance in ecw_credential_epoch.rs. They accept either handle, so they need no change here. Some also hand a clone of state.pool to PublicOperationStore::new, which takes impl Into<Db> and wraps the same pool.

Validation

At this head:

  • cargo check --locked --workspace --all-targets --all-features: 0 warnings.
  • ci/scripts/run-rust-checks.sh clippy: 0 warnings.

At the top of the stack (#2628, which contains this change), fmt, archcheck, the lib-only checks and nextest also passed; #2628 lists them.

Statement-log differential

A disposable harness, not committed, ran on main (the base, below) and on this area's conversion applied to main without #2637 (this change, below), where the calls into the sandbox controller still passed the pool. The section "The calls into the sandbox controller" below says what was checked for those calls. Each side ran against a fresh Postgres from the pinned CI image that logged every statement (log_min_duration_statement = 0, one log file, rotation off). The two copies differ in one function, which hands the converted functions a &PgPool on the base and a Db over the same pool on this change.

Each scenario family ran alone in its own database. The AppState had three pools with their own application_name: its pool, a separate credentials pool, and the harness's own pool, which held the lock holders. Calls went through the crate's routers (shared_host_router) or, for private helpers, the handler-side functions:

  • login, including a wrong password and an unknown email (both roll back), a lock wait behind a held user row that then succeeds, and one that times out (503); cluster read and logout;
  • the admin routes whose gates call authz: org list, user create and its duplicate (unique violation, 409), user update and role change, template releases, templates, operations, the guest-access snapshot list, a member refused (403), and a lock timeout on clusters (503);
  • the sandbox debug route: a full read, a missing sandbox, a lock timeout on sandboxes (503), and snapshots locked so the sources that read it fail partway through and roll back;
  • the native routes: list, get, foreign and missing get, templates, a template, the snapshot list and one snapshot, network policy, file stat, process list, :set_timeout, update with its replay and key conflict, :start and its replay, delete and its replay, a lock timeout, and a list that waits out a held lock;
  • queue_implicit_wake for a suspended and a stopped sandbox, and under a lock timeout;
  • resolve_fork_replay_org_id and prepare_fork_owner, through the owner's materialization and replay, a missing grant, and a lock timeout;
  • TemplateBuildState::record_blob and lookup_blob, including another org's conflicting record;
  • record_idempotent_port_response: a new reply, an existing one, a same-key insert that waits for a concurrent one and then replays it, one that times out partway through and rolls back, and the port-open route.

Each run produced, for every scenario:

  • each transaction unit, BEGIN to COMMIT or ROLLBACK, or one autocommit statement, with its SQL, binds and errors in order;
  • the pool that ran it;
  • the responses;
  • the final rows of every table.

Units are compared as a set within a scenario, because the debug route runs its sources on several connections at once. Generated ids, tokens and timestamps were renamed by first appearance, and sql! locators masked. Two values are masked further:

  • the admin audit row's wall-clock duration_ms;
  • the parse position of a lock-timeout error, and the parameter context Postgres adds to one that lands at execute. A lock timeout lands at parse or at execute depending on a pooled connection's statement cache.

Two runs of the base were identical, and the base and this change were identical. Bind records equal execute records, except the three statements that failed after binding on purpose (lock timeouts), each of which ends in its error. Both sides sent 16 BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY statements and no SET TRANSACTION.

Three mutations planted on this change, each reverted, show what the differential catches:

  • the debug lifecycle read run on the Db without beginning its snapshot transaction: its statement becomes an autocommit unit;
  • the unknown-email login committing instead of rolling back: ROLLBACK becomes COMMIT;
  • one template-variant read run on a fresh Db of the credentials pool: the statement moves from the API pool's application_name to the credentials pool's.

Local Kubernetes bench

A local Kind cluster built from the same conversion on main ran on the Kubernetes substrate, with Postgres logging every statement (log_min_duration_statement = 0 via ALTER SYSTEM, read with kubectl logs). These typed space_smoke scenarios reach the converted code:

  • passed:
    • native_contract.tenant_isolation;
    • native_contract.completed_delete_replay;
    • native_contract.access_wakes_idle_suspended_sandboxes;
    • native_contract.command_on_sandbox_not_running;
    • native_contract.file_operations_match_on_the_data_plane;
    • native.network_policy_live_update;
    • native.stopped_restart_preserves_rootfs;
    • ecw.fork_idempotency;
    • ecw.timeout_update;
    • local.console_turns_away_non_operators;
    • local.ecw_template_build_from_oci_boots.
  • failed: local.console_sandbox_detail_complete_in_every_state, twice, on its operations-card check. The scenario sums the admin operations list queried by the sbx_ id and by the bare UUID. admin_target_id_forms in public_operations.rs, which this change does not touch, expands both queries to both forms, so every operation is counted twice. This scenario was not run against main, and this pull request's Kind run in Pull CI withheld it with the other browser scenarios. The cause above comes from reading the code, not from a run on main. The same page rendered every debug section. Its 21 debug-source transactions in the log (seven sources, three page loads) each ran BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY from Db::begin_snapshot, then its statements and COMMIT, on one backend. That is one statement in 15 of them, two (quarantine) in 3, and three (snapshots) in 3.

In the log, a smoke runner's password login ran BEGIN, the users read FOR SHARE, the organizations read, the sessions insert and COMMIT. All five ran on one space-api backend in one transaction.

The Direct substrate was not run: a Direct bench needs static storage credentials, and this one had none.

The calls into the sandbox controller

The create_native_sandbox_operation and StoredAccess conversions ran against #2637, the layer below, through this crate's tests: every test under routes::public::sandboxes:: (native creates with and without a warm-pool admission claim, and inline creates) and controllers::sandbox::ingress::. The ingress tests that build a StoredAccess reach its observe and access paths; none reaches its queued-wake or reachability path. Each test ran in its own process with its own application_name, against a Postgres from the pinned CI image logging every statement. Of the 51 tests that send statements, 42 were identical statement for statement, sessions and transaction blocks included. 7 were identical as multisets of transaction units, where the lower layer's two runs already differed in which pooled connection ran a statement. The other 2, rerun six more times per side, reproduced only variants the lower layer produced, one of them with its timing binds dropped. The one test that fails a statement on purpose is short by the same count on both.

The corpus did not include the handlers in the second bullet of "Calls into the sandbox controller". Each now passes one Db it builds to the calls that took a fresh Db per call. A Db shares the pool it wraps, so each call runs on the same pool as before.

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

Severity and risk

Severity: does not apply, as this is a refactor.

Risk: a converted call that ran a statement outside its transaction, or on another pool, would change what concurrent requests see. The differentials under Validation cover that for each converted function family, apart from what "The calls into the sandbox controller" says its corpus did not reach. To roll back, revert the commit; nothing persisted depends on it.

Stack

Lands after #2637.

Mixed-version safety

There is no schema, protocol, metric or persisted-state change; only Rust types change. Old and new versions send the same statements in the same transactions.

One production sql! locator moved, because Db::begin_snapshot owns the statement now: the debug route's BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY was /*pplx_space_api::routes::debug::sources:20*/ and is /*pplx_space_postgres_pool::db:168*/. 23 test-fixture statements in five test files (debug/sources/pods/tests.rs, e2b/template_build/state/tests.rs, public/sandboxes/tests.rs, public/sessions/tests.rs and session_auth/tests.rs) move down by 1 to 49 lines; they run only in tests.

What still names sqlx here

  • routes/mod.rs: AppState.pool and its constructors (from_pool, from_pools_with_lifecycle) keep the PgPool. They convert with AppState.
  • routes/authz.rs: the seven checks still return sqlx::Error. That is their error type, not a handle. Their admin callers convert it with DbError::from, and so does debug/sandbox.rs's gate.
  • A doc comment in routes/public/error.rs, and tests' own fixtures.

AI assistance: Claude Code drafted the code changes, the tests' call-site updates, the disposable differential harness and this description.

Activity

9
github-actions[bot]18h ago

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

CONTRIBUTING.md explains how we review outside contributions.

coderabbitai[bot]17h ago

IMPORTANT

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
Pre-merge checks: 6

Check nameStatusExplanation
Description Follows The Pr TemplateThe PR description contains all four required items, each with real content: 1. "## Summary": Present. It states that the change swaps the route modules outside routes/admin/ from the driver han…
Bug Fixes Name A Regression TestThis check applies only when the pull request fixes a defect in application behavior under crates/, shim/, or ui/. PR #2630 does not fix a defect. The title is "api: move the routes outside admin onto…
Weakened Safeguards Are JustifiedI checked the PR commit (99e89cc41, parent 67e6c3b75) against its parent. The diff covers 45 files, all Rust under crates/l40_api/api/src/routes and controllers/sandbox. It is a type refactor that swa…
Agent Tooling Runs No New CommandsThe check fails only when the diff adds or changes agent-tooling content that runs commands or starts processes. I found none. Evidence: - The PR base branch (ac/api2-AH3-api-area-b-handles) is not pr…
External Code Sources Need A PersonThe check passes. This PR does not add or change any external code source. Evidence: - The PR's own commits in the local checkout are 67e6c3b75 and 99e89cc41. Together they form the range HEAD~2..HEAD…
Public-Safe ContentThe Public-safe content check passes for PR #2630 (perplexityai/SPACE, author login ac-pplx). Scope of the scan: - The PR base branch (ac/api2-AH3-api-area-b-handles) is not in the local clone. I scan…
Full details: Description Follows The Pr Template

Explanation

The PR description contains all four required items, each with real content: 1. "## Summary": Present. It states that the change swaps the route modules outside routes/admin/ from the driver handles (PgPool, sqlx::Transaction) to postgres-pool's Db and Tx, and it lists what stays the same. 2. "## Validation": Present. It names the runs and results, including cargo check --locked --workspace --all-targets --all-features (0 warnings), ci/scripts/run-rust-checks.sh clippy (0 warnings), and a statement-log differential with its outcome. 3. "## Severity and risk": Present. It gives "Severity: does not apply, as this is a refactor." and a risk: a converted call that runs outside its transaction or on another pool would change what concurrent requests see. 4. "AI assistance:" line: Present. It reads "AI assistance: Claude Code drafted the code changes, the tests' call-site updates, the disposable differential harness and this description." No section contains only template HTML comments. Per the check, presence is the only test, so quality and length do not count. Evidence: the &lt;pr_description&gt; content supplied with this run, which the verdict relies on. No repository tool calls were needed for this check.

Full details: Bug Fixes Name A Regression Test

Explanation

This check applies only when the pull request fixes a defect in application behavior under crates/, shim/, or ui/. PR #2630 does not fix a defect. The title is "api: move the routes outside admin onto postgres-pool's Db and Tx". The description says the change "only changes the handle types. It is a refactor." It lists the behavior that stays the same: SQL, transaction boundaries, pools, HTTP responses, and metrics. Its "Severity and risk" section says "Severity: does not apply, as this is a refactor." The check therefore does not apply, and the PR passes by its own terms. I did not inspect the diff. The description's own refactor claim is enough to decide applicability.

Full details: Weakened Safeguards Are Justified

Explanation

I checked the PR commit (99e89cc41, parent 67e6c3b75) against its parent. The diff covers 45 files, all Rust under crates/l40_api/api/src/routes and controllers/sandbox. It is a type refactor that swaps PgPool/sqlx::Transaction for postgres-pool's Db/Tx. Findings against the check's failure conditions: - No added #[allow], #[expect], #[ignore], skip, xfail, || true, set +e, continue-on-error, or [lints] changes. - No removed test attribute (#[test], tokio::test, #[should_panic]) and no removed assert line. The removed-line scan returned zero matches for these patterns. - No file under ci/, .config/, .github/, deny.toml, clippy.toml, Cargo.toml, baselines, skip files, AGENTS.md, CLAUDE.md, CONTRIBUTING.md, docs/rust/, db/README.md, or ARCHITECTURE.toml is touched. No file is deleted. - Test-file edits are call-site updates: ensure_sandbox_owner(&amp;state.pool, ...) becomes &amp;Db, and PgPool imports are added. No assertion is dropped. - The removed pool.begin_with(sql!("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY")) line is moved into Db::begin_snapshot, as the description states. The isolation level is kept. This is a relocation, not a weakening. The description also says the SQL and transaction boundaries are unchanged. No failure condition is matched. Scope: I inspected only this commit's diff. The sibling branches named as base/head are not present in the checkout, and the cross-crate Db::begin_snapshot body is outside this diff.

Full details: Agent Tooling Runs No New Commands

Explanation

The check fails only when the diff adds or changes agent-tooling content that runs commands or starts processes. I found none. Evidence: - The PR base branch (ac/api2-AH3-api-area-b-handles) is not present locally, so the exact PR patch could not be recomputed. The local HEAD is 99e89cc41, the PR head commit. I compared 719229c2b..HEAD, which covers the two recent commits 67e6c3b75 and 99e89cc41. - Both commits change only Rust source and test files under crates/l40_api/api/src/. Neither touches .agents/, .claude-plugin/, AGENTS.md, CLAUDE.md, SKILL.md, plugin.json, plugin.yaml, or .mcp.json. - A pattern search over the non-Rust added lines of that range found no inline shell substitution (!...), no hooks, allowed-tools, mcpServers, lspServers, or command entries. - The PR description describes a Rust handle-type refactor (PgPool/sqlx::Transaction to postgres-pool Db/Tx). It states no change to agent tooling. Residual gap: the PR author is ac-pplx, which does not affect this check. The exact PR base is unavailable, so a change made only in commits outside 719229c2b..HEAD cannot be ruled out by this diff. The agent-tooling files present in the tree were not changed in that range.

Full details: External Code Sources Need A Person

Explanation

The check passes. This PR does not add or change any external code source. Evidence: - The PR's own commits in the local checkout are 67e6c3b75 and 99e89cc41. Together they form the range HEAD~2..HEAD. Every file in that range is a .rs file under crates/l40_api/api/src/routes/. There are no changes to Cargo.toml, Cargo.lock, Dockerfiles, Chart.yaml/Chart.lock, YAML, or shell scripts. - Added lines in that range contain no git, rev, branch, tag, registry, path, [patch], or [replace] keys. They also contain no image:, FROM, curl, wget, sha256, checksum, repository:, or chart references. - The PR description describes only Rust handle-type changes (PgPool/sqlx::Transaction to Db/Tx). It states there is no schema, protocol, or packaging change. Context and limits: - The local origin/main..HEAD range also includes earlier stack commits. Two of them add path = ... dependencies (pplx-space-token-review, pplx-space-federated-identity-resolver). Both paths point inside this repository. The check allows workspace-internal path dependencies, so these pass even if they fall inside the PR's base comparison. - The PR's head and base branch names do not exist locally. I could not compare against the exact base branch. I assessed the top two commits, which match the PR description. - Neither the summary nor the description reports a change to external sources.

Full details: Public-Safe Content

Explanation

The Public-safe content check passes for PR #2630 (perplexityai/SPACE, author login ac-pplx). Scope of the scan: - The PR base branch (ac/api2-AH3-api-area-b-handles) is not in the local clone. I scanned the added lines of the commits from 719229c2b to HEAD (99e89cc41). That range is 87 files, and it includes the stacked commit 67e6c3b75 and the PR commit itself. It may not match the PR's exact base diff. - The added lines contain no private keys, AWS key or ARN patterns, API-key or token-shaped strings, hard-coded password literals, URLs, internal hostnames (.internal, .corp, cluster-local DNS), private IP ranges, 12-digit account-ID patterns, or absolute personal paths (/Users/, /home/<name>/). - Every touched file is a .rs file. No docs, configs, or logs were changed. - The only keyword hits were Rust identifiers such as token_hash, raw_token, delete_session and Db::from. These are not credentials. Title and description: - No credentials, tokens, keys, internal URLs, or hostnames appear. - Repository and PR references (#2628, #2637) are public. - The Kind cluster, local bench, and statement-log differential are described in general terms. They ran on disposable or local Postgres and a local Kind cluster. They are not production logs or production measurements. The quoted SQL is generic. - The description does not describe an unfixed security vulnerability or an incident. - The AI-assistance line ("Claude Code drafted ...") is not a "Created with ..." line. It has no link and holds no sensitive value, so it does not trigger the check. No failure condition in the custom check was matched.

This pull request is a draft

Merging is unavailable until it is marked ready for review.