#2637

api: move the sandbox controller onto postgres-pool's Db and Tx

Draftac-pplxwants to merge intofrom

Summary

The sandbox controller in pplx-space-api (controllers/sandbox/) now holds and passes postgres-pool's handles (Db, Tx) instead of the driver's (PgPool, sqlx::Transaction). Its storage errors were already on DbError (#2402, and its routes' in #2396 and #2401); this changes only the handle types. It is a refactor: HTTP and gRPC statuses, bodies and metadata, metrics, the SQL sent (apart from sql! locator comments, listed under Mixed-version safety), transaction boundaries and which pool each statement runs on are unchanged. It follows the handle rules #2484 and #2515 set.

Handles, by file (under crates/l40_api/api/src/controllers/sandbox/):

  • mod.rs: imports Db and Tx instead of sqlx::PgPool. The template gate and release resolvers (gate_template_access, resolve_template_release, resolve_create_release, resolve_original_release, release_miss, classify_release_miss, resolve_template_release_by_tag, load_create_template_defaults), the port-exposure helpers, SandboxController::sandbox_wake_signal, SandboxController::workers_not_reading_twins (which hands its Db to the substrate's TwinWorkerReader::read) and fetch_sandbox_wake_signal take &Db.
  • lifecycle.rs: every pool parameter is &Db: the delete guard (begin_delete_against_active_fork, which begins on it), its compensating restores, the resilient finalize, the wake CAS, the drain gates, delete, delete_control_plane, action and stats. The finalize's Db::from(pool.clone()) wrap goes.
  • queries.rs: create, create_with_sandbox_id, create_with_admitted_pool_claim, plan_admission_pool_claim, restore_fork_disk_as_new, upsert_federated_service_grant, list_responses, tracked_response, untracked_response, org_byok_enabled and the create helpers take &Db; PooledCreateInput holds db: &Db. commit_pooled_sandbox_claim, the pooled-create rollback (rollback_failed_pooled_create_with_substrate) and the federated grant write in create_with_sandbox_id_unboxed begin on it. The three WarmPoolStore::new(Db::from(pool.clone())) wraps become WarmPoolStore::new(db.clone()), the same pool.
  • updates.rs: update, set_network_policy, set_snapshots_enabled_desired, set_auto_lifecycle_policy, set_access_idle_timeout, rollback and rollback_created_sandbox take &Db; all but update and rollback begin on it. egress_profiles::load's wrap goes.
  • ports.rs: the port open, close and exposure functions take &Db; open_sandbox_port, close_sandbox_port and invalidate_sandbox_port_exposure_after_proxy_failure begin on it. recover_loopback_bridge_after_proxy_failure, which runs in a spawned task, takes an owned Db; the two reconcile-enqueue wraps go.
  • responses.rs: update_and_fetch_post_wake_sandbox, the action stamps and the observed-state reads take &Db. fetch_sandbox is unchanged: it already took impl Executor.
  • spaced.rs: SpacedSandboxClient holds a Db; control_runtime_client, connect_spaced_runtime_client, spaced_start_process and the other spaced_* entry points take &Db. spaced/runtime_grant.rs, org.rs and list_page/admin.rs (whose WarmPoolStore wrap becomes db.clone() too) take &Db.
  • wake_completion.rs: wake_completion_redrive takes an owned Db for its spawned future; the redrive loop and the port-reconcile enqueue take &Db, and that enqueue's wrap goes.

Transactions: insert_pooled_sandbox, upsert_pooled_federated_service_grant, enqueue_pooled_network_policy_reconcile_if_needed (queries.rs) and persist_auto_lifecycle_policy (updates.rs) take &mut Tx<'_>, since every caller now holds a Tx from Db::begin; their store verbs take &mut *tx instead of &mut **tx. Owned transactions pass &mut tx where they passed &mut *tx. Db::begin and Tx::commit return DbError, so the 24 .map_err(DbError::from) conversions after begin() and commit() go. persist_pooled_execution_claim (#2515's caller-transaction shape) now receives the Tx itself.

Callers in other areas

Each passes &Db::from(<pool>.clone()), which shares the caller's pool (an Arc clone), unless it already holds a Db over that pool:

  • public_sandbox_operations.rs (the three executors: update, action, create_with_sandbox_id, create_with_admitted_pool_claim, delete_control_plane, rollback, upsert_federated_service_grant).
  • fork_operation_executor.rs passes self.store.db(), the Db its ForkOperationStore built from a clone of the executor's pool, to delete_control_plane, org_byok_enabled, restore_fork_disk_as_new and delete. Its pool field doc now says it serves fetch_sandbox.
  • routes/admin/runtime_upgrade_campaigns.rs (workers_not_reading_twins).
  • routes/e2b/lifecycle.rs (create, action ×3, tracked_response ×7, set_auto_lifecycle_policy, set_access_idle_timeout, upsert_federated_service_grant), routes/e2b/translate.rs, routes/e2b/template_build/handlers.rs, routes/admin/sandbox_list.rs, routes/admin/sandboxes.rs, routes/public/files.rs (13 spaced_* calls; the write and batch-write retries build one Db before their closures, which return futures that borrow it), routes/public/files/access.rs, routes/public/owner_scope.rs, routes/public/ports.rs, routes/public/processes.rs, routes/public/sandboxes.rs, routes/public/sessions.rs and routes/public/timeout.rs.
  • Tests, compiler-forced only: controllers/substrate/direct/tests.rs (2), controllers/substrate/kubernetes/tests.rs (13), controllers/substrate/kubernetes/tests/substrate_scope.rs (2), controllers/substrate/kubernetes/store/k8s_store_postgres_tests.rs (5), public_sandbox_operations/tests.rs, reconcile_queue/tests.rs, routes/e2b/tests.rs, routes/e2b/state_render_tests.rs, routes/public/sandboxes/tests.rs and routes/public/timeout/tests.rs. Inside the area, eleven test modules import PgPool, which they used to get through use super::*; pooled_create_input takes a &Db, and the tests that hand their transaction to insert_pooled_sandbox begin it on that Db.

What still names sqlx in the area

  • ingress.rs: StoredAccess keeps its pool: PgPool, and ingress_activation still takes one, because routes::public::sessions::queue_implicit_wake takes &PgPool and a Db does not hand one back. Its calls into the area (action, connect_spaced_runtime_client and the drain gate) pass &Db::from(self.pool.clone()). #2630 moves that callee onto &Db and converts StoredAccess.
  • Test modules that hold the fixtures' PgPool (TestDb::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.

The statement-log differential, the mutations and the local Kind benches below ran on this change over main at d752bb3f, before #2591 added SandboxController::workers_not_reading_twins. That method's one caller, workers_hold_templates in the admin campaign routes, passes Db::from(state.pool.clone()), which shares the route's pool. kubernetes_campaigns_ignore_confirmed_gone_workers_and_fail_closed reaches it through the campaign list and the campaign GET.

Statement-log differential (a disposable harness, not committed). Each run used a fresh Postgres from the pinned CI image logging every statement (log_min_duration_statement = 0, one csvlog file, rotation off), on the base and on this change.

  • Scenarios, through the controller's entry points on the Direct substrate, each in its own database, on named pools (main for the code under test, with one connection; lock for a competing lock holder; seed for fixtures): reads (sandbox, sandbox_wake_signal, fetch_sandbox_wake_signal, org_byok_enabled, scoped_sandbox_page, list_responses, admin_sandbox_page, port listing); the update family (snapshots, auto lifecycle through persist_auto_lifecycle_policy, network policy and a stale-generation 412, update); update_and_fetch_post_wake_sandbox completing a paused row and rolling back on a failed row's CAS miss; port open, reopen, close and an unknown close; delete_control_plane, and one refused by an active fork, whose guard transaction rolls back with a 409; set_access_idle_timeout waiting on a row lock lock holds until it commits, and the same update under a 200 ms lock_timeout, which fails with 55P03, rolls back and answers 503, then succeeds; and a pooled insert whose second insert of one id violates sandboxes_pkey and rolls back. The two sides differ only in a two-line file that hands the area a PgPool on the base and a Db over the same pool here. Compared: every statement in order with its session, its BEGIN..COMMIT/ROLLBACK block, its binds and the pool it ran on, plus each call's result (status, Retry-After, message) and the final rows of every table, with generated values renamed by first appearance and sql! locators masked. The base and this change were identical in all nine scenarios, and two runs on the base were identical. Bind and execute records matched except in the two scenarios whose statement fails on purpose (the lock timeout and the unique violation), each one execute short on both sides.
  • The existing tests that reach this code: every test under controllers::sandbox::, routes::, public_sandbox_operations::, fork_operation_executor::, reconcile_queue::, ingress_activation::, controllers::substrate::direct::tests::, controllers::substrate::kubernetes::tests:: and controllers::substrate::kubernetes::store::k8s_store_postgres_tests:: (2173 per side, --all-features), each in its own process with its own application_name. 1370 of them send statements. 1218 were identical statement for statement. 120 whose fixture pools have several connections, where the base's two runs already differed in which session ran a statement, were identical as multisets of transaction units (each BEGIN..COMMIT/ROLLBACK block with its statements and binds, or one statement outside a block). The other 32 vary between runs of the base itself (concurrent tasks, poll loops, jittered retry delays): rerun six more times per side, 28 reproduced only variants the base produced, and 4 matched the base's statements and transaction shapes with their timing binds dropped. Every test passed on both sides; the only one not run is the #[ignore] benchmark benchmark_single_node_occupancy. The 47 tests whose bind and execute counts differ (statements they fail on purpose) are the same tests, short by the same counts, on both sides.

Three mutations planted on this change were each caught, and reverted:

  • update_and_fetch_post_wake_sandbox running its stamp and read on db without beginning: both calls' BEGIN..COMMIT and BEGIN..ROLLBACK blocks disappeared and the statements ran as autocommits.
  • The delete guard committing where it rolls back on the active-fork refusal: its ROLLBACK became a COMMIT.
  • fetch_sandbox_wake_signal (one of the functions the Kubernetes store's tests call with a pool) reading through a fresh Db::from(PgPool::connect_lazy_with(..)) of a second pool on the same database with the same application_name: its reads left the main pool's one session for two new ones.

Two local Kind/Firecracker benches, with every SPACE container built from that tree, one on the Kubernetes substrate and one on Direct (SPACE_KIND_SUBSTRATE=direct, SPACE_KIND_STORAGE_CREDENTIALS=static), with every statement logged (ALTER SYSTEM SET log_min_duration_statement = 0, read with kubectl logs). On both, native_concurrency.create_idempotency, native_contract.completed_delete_replay, native.network_policy_live_update, native.resident_pause, native.stopped_restart_preserves_rootfs, native_contract.access_wakes_idle_suspended_sandboxes, ecw.command_round_trip, ecw.filesystem_mutations, ecw.public_port_to_all_interfaces, ecw.timeout_update, ecw.pause_connect and ecw.sandbox_list_pagination passed. Bind and execute records were equal for every application. The cluster controller ran the delete guard as one transaction on one connection: BEGIN, the fork-source advisory lock, the active-fork check, the lifecycle row lock, the deleting update, COMMIT; the API ran the timeout update as the row lock, the execution read, the policy update and the reconcile enqueue between one BEGIN and COMMIT. The local benches ran the twelve scenarios above, not the whole smoke suite.

Local review: round 2 (Codex + Claude in round 1; round 2 checked the rebase delta), READY after fixes.

Severity and risk

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

Risk: low. Db wraps the same pool, Db::begin is the driver's begin, and Tx is the driver's transaction, so each statement runs on the same connection in the same transaction as before. To roll back, revert the commit.

Log output: rollback_created_sandbox's two warnings, for a failed begin and for a failed cleanup transaction, now format a DbError where they formatted the driver's error. DbError displays as the driver's error does, so both lines are unchanged.

Mixed-version safety: no schema, protocol, metric or persisted-state change; Rust types only. Moved sql! locators: no production statement's locator moves (the area has no sql! of its own outside tests, and no store changes). 193 test-fixture statements in 11 test files move down by 1 to 58 lines, where a test module gained a PgPool import or a reformatted call above them grew; they run only in tests.

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

Activity

3
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 check tests only the PR description's structure, and the full contributor description was supplied. All four required items are present with real content. 1. Summary: A "## Summary" section is…
Bug Fixes Name A Regression TestThis check applies only when the pull request fixes a defect in application behavior under crates/, shim/, or ui/. The pull request is not a bug fix. Its title is "api: move the sandbox controller ont…
Weakened Safeguards Are JustifiedNo weakened safeguard found in PR #2637 (perplexityai/SPACE, head ac/api2-AH3-api-area-b-handles into main, author ac-pplx). I compared HEAD (67e6c3b75) against its parent (719229c2b). - **Scope…
Agent Tooling Runs No New CommandsThe check applies to agent plugin manifests, skills, and guideline files. The diff against the merge-base with origin/main (22e9465c) touches three such files, and none adds a command-running or serve…
External Code Sources Need A PersonThe check fails only if the diff adds or changes an external code source. I compared HEAD against the merge base with origin/main (22e9465c). That diff is wider than the PR's sandbox-controller refact…
Public-Safe ContentThe Public-safe content check passes. I checked the title, the description, and the added lines of the PR diff. - Description: It contains no credentials, tokens, or private keys. It has no internal h…
Full details: Description Follows The Pr Template

Explanation

The check tests only the PR description's structure, and the full contributor description was supplied. All four required items are present with real content. 1. Summary: A "## Summary" section is present. It states that the sandbox controller now holds postgres-pool's Db and Tx handles instead of PgPool and sqlx::Transaction, and that this is a refactor with no behavior change. 2. Validation: A "## Validation" section is present. It names cargo check and clippy with 0 warnings, the statement-log differential, the existing test runs, the mutation checks, and the local benches, each with its result. 3. Severity and risk: A "## Severity and risk" section is present. It states "Severity: does not apply", and gives "Risk: low" with a rationale. 4. AI assistance: The line "AI assistance: Claude Code drafted the code changes, the disposable differential harness and this description." starts with "AI assistance:" and names the tool and the parts it drafted. No item is empty or only template comments. Presence is the only criterion, so I did not assess quality.

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/. The pull request is not a bug fix. Its title is "api: move the sandbox controller onto postgres-pool's Db and Tx". Its description states: "It is a refactor: HTTP and gRPC statuses, bodies and metadata, metrics, the SQL sent ... transaction boundaries and which pool each statement runs on are unchanged." The Severity section also says: "does not apply. This is a refactor with no behavior change." The change replaces handle types (PgPool and sqlx::Transaction with Db and Tx) in crates/l40_api/api/src/controllers/sandbox/ and its callers. It does not fix a defect. The check therefore does not apply, and the pull request passes. I did not inspect the diff. The description's own statements are sufficient to decide applicability.

Full details: Weakened Safeguards Are Justified

Explanation

No weakened safeguard found in PR #2637 (perplexityai/SPACE, head ac/api2-AH3-api-area-b-handles into main, author ac-pplx). I compared HEAD (67e6c3b75) against its parent (719229c2b). - Scope: All 56 changed files sit under crates/l40_api/api/src/. None touch CI workflows, ci/, .config/, deny.toml, clippy.toml, Cargo.toml lints, ARCHITECTURE.toml, baselines, or AGENTS/CLAUDE/CONTRIBUTING/docs/rust/db/README/.agents guidance. - Suppressions and skips: The diff adds or removes no #[allow], #[expect], #[ignore], #![...], cfg( gates, should_panic, or skip/xfail markers. - Tests: The count of #[test] and #[tokio::test] attributes is unchanged. Assertion-like calls balance: expect_err 17 added / 17 removed, expect( 8 / 8, Err( 5 / 5, is_none() and is_some() 1 / 1 each. Every removed expect_err/expect message string also appears in the added side (empty comm diff). - Production guard lines: The removed if let Ok(Some(record)) = sandbox_store::get(...) check in wake_completion.rs and the if !stamp_pooled_post_wake(...) CAS check in updates.rs remain, with pool→db and &amp;mut *tx→&amp;mut tx changes only. The enabled_pool_assignment branches in queries.rs/lifecycle.rs keep their control flow and change only the handle type. - Removed functions: sandbox_started, delete_observed_sandbox, org_byok_enabled and enqueue_open_port_exposure_reconcile still exist with Db parameters. Their signatures changed; nothing was dropped. The PR is a pool-to-Db type refactor. The description's claims about sql locator moves and DbError mapping are consistent with the diff. No item in the check's failure list applies.

Full details: Agent Tooling Runs No New Commands

Explanation

The check applies to agent plugin manifests, skills, and guideline files. The diff against the merge-base with origin/main (22e9465c) touches three such files, and none adds a command-running or server-starting entry: - .agents/plugins/pplx-space/skills/space-validation/references/smoke-testing.md: prose edits only, in the scenario-knob and smoke-testing guidance. No fenced code was added and no inline substitution appears. - infra/space/kind/AGENTS.md: prose edits only. These re-point section references, reflow text, and drop the old exception list. No command or server entry is added. - space_smoke/AGENTS.md: a new "Authoring a scenario" and "Direct state manipulation" section. This is prose and a list of existing helper names. It adds no executable content. Other evidence: - No plugin manifest (plugin.json, plugin.yaml), SKILL.md, .mcp.json, or command file is in the changed-file list. - No added line matches !`` (inline shell substitution), hooks:, mcpServers, lspServers, allowed-tools, or a "command":` key. The remaining changes are Rust sources, tests, Cargo files, and smoke scripts. Those are outside this check's scope. The check passes.

Full details: External Code Sources Need A Person

Explanation

The check fails only if the diff adds or changes an external code source. I compared HEAD against the merge base with origin/main (22e9465c). That diff is wider than the PR's sandbox-controller refactor, because it includes stacked federated-identity and token-review crate moves, so I checked all of it. - Cargo.toml (root and per-crate): every added dependency is a workspace-internal path entry under crates/ (for example pplx-space-token-review = { path = "crates/l10_foundation/token/review" } and pplx-space-federated-identity-resolver = { path = "crates/l40_api/federated/identity/resolver" }). Other changed dependencies use workspace = true. I found no git, rev, branch, tag, registry, or out-of-repo path keys, and no [patch] or [replace] changes. - Cargo.lock: the added entries are the two internal crates. No added source or checksum lines exist, so no non-crates.io source was added. - Container and download references: no changed Dockerfile, Chart.yaml, or Chart.lock. No added FROM, image:, image =, curl, wget, or archive-URL lines. The sha256:seed hit is a test fixture value, not a download checksum. The check does not apply to any of the changed code, so it passes.

Full details: Public-Safe Content

Explanation

The Public-safe content check passes. I checked the title, the description, and the added lines of the PR diff. - Description: It contains no credentials, tokens, or private keys. It has no internal hostnames or URLs, and no links to private trackers, chats, or documents. It has no cloud account IDs or ARNs, and no cluster or environment names. It has no personal workstation paths. It has no raw production logs, query output, or measurements. It has no incident details and no unfixed vulnerability description. The only links are to PR numbers in this repository (#2396, #2401, #2402, #2484, #2515, #2628, #2630). The benches and statement-log differential are local, not production. The AI assistance line names no tool link and is not a "Created with" line, so that exception does not apply. - Diff: I scanned the 13,103-line diff against origin/main for added lines matching private key blocks, AWS key IDs, ARNs, /Users/ or /home/ paths, internal or private hosts, private-tracker links, and inline secret assignments. The scan found 0 hits. - Limitation: The scan used regex patterns. It does not prove the absence of every possible sensitive value. The title is a short refactor subject with no sensitive content.

github-actions[bot]17h ago

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

CONTRIBUTING.md explains how we review outside contributions.

This pull request is a draft

Merging is unavailable until it is marked ready for review.