#2628

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

Draftac-pplxwants to merge intofrom

Summary

The admin routes in pplx-space-api (crates/l40_api/api/src/routes/admin/) now hold and pass postgres-pool's handles (Db, Tx) instead of the driver's (PgPool, sqlx::Transaction, PgConnection, pool.begin(), pool.acquire()). Their storage errors were already classified on DbError (#2396, #2401, #2402); this changes only the handle types, following the rules #2484 and #2515 set. It is a refactor: HTTP statuses, bodies and headers, metrics, the SQL sent, transaction boundaries and which pool each statement runs on are unchanged.

AppState::pool stays a PgPool. A handler that runs one statement passes &Db::from(state.pool.clone()); most with several build one let db = Db::from(state.pool.clone()). AdminNodeStore, AdminNodeGroupStore and PublicOperationStore take impl Into<Db>: fetch_group_or_error and three sandboxes.rs helpers pass them the Db they were given, and the other call sites pass state.pool.clone(). All of these share the state's pool (an Arc clone).

Handles, by file (under routes/admin/):

  • node_group_store.rs: AdminNodeGroupStore holds a Db, and new takes impl Into<Db>, so its callers' state.pool.clone() compiles unchanged. insert_node_group takes &Db. group_occupancy_in_tx, update_group_org_in_tx, move_default_in_tx, set_template_policy_in_tx and replace_compat_in_tx take &mut Tx<'_>, since every caller (the node_groups.rs handlers and the module's tests) holds a Tx; their store verbs take &mut *tx instead of &mut **tx.
  • node_store.rs: AdminNodeStore holds a Db (new(impl Into<Db>)). read_node_drain takes &Db; update_in_flight_drain and update_drain_phase take &mut Tx<'_>.
  • node_groups.rs: fetch_group_or_error takes &Db. The assign-org, set-default, delete, template-policy and compat handlers begin on the handler's Db and pass &mut tx (an owned Tx) to the verbs.
  • nodes.rs: the drain-action handler begins on its Db; the node-sandbox page, the force-upload pass and the per-RPC drain re-read run on a Db. nodes/drain_preview.rs, nodes/drain_v2.rs, nodes/holds.rs and nodes/read_state.rs pass a Db to their store verbs.
  • node_maintenance.rs: fetch_node, fetch_nodes and enqueue_default_node_publish take &Db (the last one's Db::from(pool.clone()) wrap goes). node_maintenance/node_status.rs: fetch_node_status_map, node_status_refresh_needed and fetch_cached_node_health take &Db. node_maintenance/node_templates.rs: delete_cached_node_template_inventory, note_node_template_deleted and list_templates_for_node take &Db; the inventory fan-out clones a Db per task where it cloned the PgPool.
  • identity.rs: the org update and user update begin on a Db and pass &mut tx where they passed tx.as_mut(). The two master-key reads pass &credentials_pool.db() where they passed credentials_pool.pool(): the same credentials pool, wrapped. The other store calls pass a Db.
  • template_visibility.rs: the visibility flip begins on a Db; its owner-encryption check passes &state.credentials_pool.db().
  • templates.rs: begin_tx takes &Db and returns Tx<'static>. managing_org_id, fetch_template, reject_deleted_template_build, hydrate_template_releases, fetch_release_tags, fetch_release_warm_pools (which hands WarmPoolStore::new its Db) and fetch_template_snapshot_defaults take &Db. reconcile_target_node_ids, enqueue_template_refs_for_nodes_tx, enqueue_template_refs_tx, requeue_reconcile_targets_tx and original_release_of take &mut Tx<'_>. The release delete begins on a Db.
  • runtime_environments.rs: already_stale, block_check and first_default_at_risk take &Db; enqueue_policy_reconcile, first_default_template_campaign (which took a PgConnection) and recheck_block take &mut Tx<'_>. The two writes begin on a Db. read_population takes &Db, and a new read_population_in_tx runs the same two store reads in the recheck's Tx: a Db and a Tx reborrow differently, and the pool path needs no transaction.
  • sandboxes.rs: admin_create_precheck, create_sandbox_for_org, enqueue_admin_update_operation, enqueue_admin_lifecycle_operation and fetch_admin_sandbox take &Db. sandboxes/guest_access.rs: resolve_sandbox passes a Db.
  • audit.rs (record_request), warm_pools.rs (store_policy) and runtime_upgrade_campaigns.rs (edges_certified) take &Db; api_keys.rs, firewall_rules.rs and mod.rs (require_admin_auth, one Db for the console resolve and the audit record) pass one.

With the handles converted, every DbError::from the area had put around a begin or commit is an identity conversion and goes: db.begin() and tx.commit() already return DbError. The DbError::from calls that remain convert the sqlx::Error that routes::authz's checks still return.

The three held connections in runtime_environments.rs

block_check and first_default_at_risk each acquired one connection and ran their policy reads (policy_store::get, and get_default first in first_default_at_risk) and the two population reads (sandbox_population, template_release_population) on it. get_runtime_environment_population read the policy on the pool, as it still does, and acquired one connection for the two population reads. postgres-pool has no held-connection handle, so each read now runs on the Db, taking a connection per statement. That is the same SQL with no transaction either way: every one of those statements is a plain SELECT (no FOR UPDATE/FOR SHARE, no advisory lock, no SET, no temporary table), each ran in autocommit, and get_record says it reads the policy in one statement so it needs no shared snapshot. A connection that fails to arrive is answered as before: the acquire error went to read_db_error, and so does the first statement's pool error (policy_read_error sends its Database variant there).

Callers in other areas

Every edit is under routes/admin/. On #2630 and #2637, routes::authz, routes::public::snapshots::snapshot_page and the sandbox controller take &Db, so the admin calls into them pass a Db:

  • support::require_managing_org_admin, templates::require_template_admin, templates::query_template_releases and sandboxes::fetch_admin_sandbox_response take &Db. query_template_releases passes it to authz::visible_org_ids, the release lookup and hydrate_template_releases, so its own Db::from(pool.clone()) goes; fetch_admin_sandbox_response passes it to SandboxController::{sandbox, tracked_response, untracked_response}.
  • identity.rs: is_managing_org_admin, require_managing_org_admin, require_org_visible and require_org_admin take the handler's &Db instead of the AppState they used only for its pool, and pass it to the authz checks.
  • The handlers that call these gates, authz or the sandbox controller build one Db and pass it to the gate and to every later call that takes a &Db of state.pool (71 handlers, in firewall_rules.rs, identity.rs, mod.rs's require_admin_auth, node_groups.rs, node_maintenance.rs and its node_status.rs and node_templates.rs, nodes.rs and nodes/holds.rs, runtime_environments.rs, runtime_upgrade_campaigns.rs, sandbox_list.rs, sandboxes.rs, template_visibility.rs, templates.rs and warm_pools.rs); none calls Db::from(state.pool.clone()) a second time. The store constructors they give state.pool.clone(), and the helpers that take &AppState (identity.rs's fetch_user, require_org_exists, fetch_cluster and the delete blockers' refine, and fetch_inventory_nodes), wrap the same pool themselves when they read it. A handler without a let db wraps state.pool once, inline, for its gate.
  • runtime_upgrade_campaigns.rs: workers_hold_templates takes the campaign handler's &Db for SandboxController::workers_not_reading_twins.
  • PublicOperationStore::new takes impl Into<Db>: operations.rs and templates.rs pass state.pool.clone() as before, and the three sandboxes.rs helpers pass their Db where they passed their PgPool.

What still names sqlx in the area

Outside tests and comments:

  • #[derive(FromRow)] and its use sqlx::FromRow on OccupancyRow (node_store.rs): production code builds it From a store row, and its tests in node_store/single_node_occupancy/tests.rs still decode it with query_as. It is not a handle.

AppState::pool itself, and the tests' PgPool fixtures, also stay.

Validation

At this head:

  • ci/scripts/run-rust-checks.sh fmt (with the error-policy guard): passed.
  • cargo check --locked --workspace --all-targets --all-features: 0 warnings.
  • ci/scripts/run-rust-checks.sh clippy: 0 warnings.
  • ci/scripts/run-archcheck.sh against the merge-base: no findings (2059 production Rust files checked).
  • cargo check --locked --lib -p pplx-space-api, default, --no-default-features and --features kubernetes: 0 warnings each.
  • cargo nextest run -p pplx-space-api -p pplx-space-cluster-controller-server --all-features with the pinned CI Postgres image, after building space-nextest-postgres-setup: 4470 passed (3009 and 1461), 1 skipped (the #[ignore] benchmark benchmark_single_node_occupancy). The Postgres setup script ran, and no test reported a dependency skip.
  • Pull CI, with its Kubernetes Kind smoke, and the Direct-substrate Kind CI lane: passed.

Statement-log differential of the conversion as first written, on main at ca3cd285, with the four gates under "Callers in other areas" still taking &PgPool (a disposable harness, not committed). Two worktrees, the base and that version, each ran against a fresh Postgres from the pinned CI image logging every statement (log_min_duration_statement = 0, one csvlog file, rotation off), each test in its own database cloned from the migrated template.

Router scenarios. A test module, identical on both sides, drove the admin router over AppState::from_pool on a one-connection pool whose connections carry their own application_name, with separate named pools for seeding and for lock holders; each scenario ran in its own database. Eleven scenarios covered node groups (create, the two unique violations, set-default, assign-org, template policy, compat, delete, and the refusals each makes inside its transaction), an assign-org that waits out another session's row lock and one that hits lock_timeout (503, rolled back), identity (org update under its branding lock, an invalid branding refused after the lock, a slug unique violation inside the update's transaction, user create, update with session delete, role, delete, the org-delete blocker, cluster), API keys, audit and operations, Direct node registration and the node reads and actions, runtime environments (block check, first default, a stale If-Match 412 rolled back, recheck, block, campaigns) including a write that waits out the policy row lock and one that times out on it, templates (create, update, visibility, base-snapshot policy, pools, releases and tags, delete), warm-pool policies, firewall rules, and admin sandbox create, read, update and lifecycle actions. For each it compared every connection's statements in order (kind, SQL, binds, and the BEGIN..COMMIT or ROLLBACK block each ran in), the pool and session each ran on, every response (status, headers, body) and the final rows of every table, with generated values renamed and sql! locators masked. The base and that version were identical in all eleven (2253 statements), and two runs of the base were identical. Bind and execute records matched except in the four scenarios whose statements fail on purpose, each short by exactly its failed statements on both sides.

The area's own tests. All 442 tests under routes::admin:: ran one at a time on both sides, their databases paired by creation order (304 databases), and were compared as multisets of transaction units, since their fixture pool has two connections. Two runs of the base differed in one database, and that version differed from the base in 17 (18 against the other base run, the extra one being that same database), all only in the driver's per-connection caches: how many statements were parsed, and where its one-time type introspection query ran. With those set aside, all 304 were identical on every pair. The 17 are the runtime-environments tests whose reads now take a connection per statement (above), which moves those caches between the pool's two connections.

Three mutations planted on that version were each caught, in the one scenario that drives the mutated code and nowhere else:

  • The user update run on the pool without beginning: its UPDATE users and DELETE FROM sessions left their BEGIN..COMMIT for autocommit.
  • The runtime-environment state write committing on its stale If-Match refusal: its ROLLBACK became a COMMIT, and the policy generation it should have discarded persisted in the final rows and later responses.
  • The node-group list read through a store on a fresh Db of a different pool: its three statements moved from the router pool's session to a new application's.

Kind reach (a local Kind/Firecracker cluster on the Kubernetes substrate, built from that first version, with every statement logged through ALTER SYSTEM SET log_min_duration_statement = 0 and read with kubectl logs). Passed: local.warm_pool_policy_follows_new_release, local.private_template_build_isolation, native.v2_drain_preview_changes_nothing and native.v2_drain_refuses_stopped_sandboxes. local.node_group_boundary_schedules failed once and passed when rerun: on the first run its proof-5 owner create answered 503 as unschedulable (the scheduler reported one cordoned node, and the worker the scenario had just dedicated was found cordoned afterwards), after the admin node-group calls had all answered as expected. The admin template create logged as one transaction on one connection: the managing-org read, then BEGIN, the template and default auto-lifecycle inserts, the live worker and builder read, the node reconcile refs and triggers, COMMIT, and the audit row on another pooled connection. The Direct lane did not run on this bench: it needs static storage credentials, which the bench did not have.

The conversions this stack adds here (the four gates, identity.rs's helpers, workers_hold_templates and the handlers that build one Db) ran against #2630, the layer below:

  • A disposable router harness, identical on both, on a one-connection pool with its own application_name. It ran the admin sandbox GET (fetch_admin_sandbox_response) for a tenant's sandbox by both id forms, a missing one (404) and a tenant admin (403). It also read the firewall rules, templates, template releases, orgs, runtime-upgrade campaigns and cluster as an operator (a managing-org admin), a managing-org member and a tenant admin; the router's admin gate refuses the last two with 403. Statements, their sessions and transaction blocks, binds and responses were identical, and two runs of the lower layer were identical. A planted mutation ran the GET's sandbox read on a second pool over the same database with the same application_name; it moved those reads off the pool's one session, and the diff caught it.
  • All 444 tests under routes::admin:: (443 ran; the #[ignore] benchmark did not). Of the 305 that send statements, 234 were identical statement for statement and 33 as multisets of transaction units. The other 38, rerun six more times per side, reproduced only variants the lower layer produced: 6 at the statement level, 29 as units, 1 with timing binds dropped. The last 2 are runtime-environment tests whose only difference is where the driver's one-time type-introspection query ran, which the connection-per-statement reads above move. The 24 tests that fail statements on purpose are short by the same counts on both.

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

Severity and risk

Severity: does not apply. This is a refactor; its one behaviour change is the connection use of the three read sequences under "The three held connections" above.

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 pool in the same transaction as before. The one change in connection use is the three read-only sequences above, which now take a connection per statement instead of holding one: up to three in block_check, up to four in first_default_at_risk, and two for the population route's population reads. Under pool exhaustion each can wait up to the pool's acquire timeout where the sequence used to wait once, and a pool error on any of them is answered through read_db_error, as the failed acquire was. To roll back, revert the commit.

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's production code holds no sql!, and the differential found none moved). Two test-fixture statements in routes/admin/node_store/in_flight_drain_tests.rs move down by one line, below the Db import the file gained; they run only in tests.

Stack

Lands after #2630.

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

Activity

3
coderabbitai[bot]18h 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

CAUTION

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore (reviewers only)

Failed checks: 1 error

Check nameStatusExplanationResolution
Description Follows The Pr TemplateThe PR description does not meet the template check. It has one ## heading other than the required ones: ## Stack. It has no ## Summary, no ## Validation, and no ## Severity and risk heading…Edit the PR description so it has these headings, each with its content under it: - ## Summary: state what merging the change does. Move the opening paragraph under this heading. - ## Validation: name each run and its result, or write "…
Passed checks: 5 passed

Check nameStatusExplanation
Bug Fixes Name A Regression TestThe check applies only when the PR fixes a defect in application behavior under crates/, shim/, or ui/. This PR is not a bug fix. The title is "api: move the admin routes onto postgres-pool's Db and T…
Weakened Safeguards Are JustifiedPR #2628 (author ac-pplx, base ac/api2-AH5-api-area-d-handles, head ac/api2-AH4-api-area-c-handles) changes one commit in the local checkout, 02a811508, which matches the PR title. It touches 33 files…
Agent Tooling Runs No New CommandsThe check fails only if the diff adds or changes agent tooling that runs commands or starts servers. This PR (#2628, author ac-pplx) changes Rust code only. Evidence: - The checked-out HEAD (02a811508…
External Code Sources Need A PersonThe check fails only if the diff adds or changes an external code source: a Cargo.toml dependency source key (git, rev, branch, tag, registry, out-of-repo path, [patch], [replace]), a container image …
Public-Safe ContentChecked the PR title, the contributor description, and the diff for the sensitive categories listed in the Public-safe content check. - Diff: I fetched the PR head (`ac/api2-AH4-api-area-c-handles…
Full details: Bug Fixes Name A Regression Test

Explanation

The check applies only when the PR fixes a defect in application behavior under crates/, shim/, or ui/. This PR is not a bug fix. The title is "api: move the admin routes onto postgres-pool's Db and Tx". The description states that this is a refactor. It changes handle types from PgPool, sqlx::Transaction, and PgConnection to Db and Tx. It says the SQL, transaction boundaries, and pool choice are unchanged. The description also states "Severity: does not apply. This is a refactor." Its one behavior change is connection use in three read-only sequences. The PR does not present that change as a fix for a defect. Because the PR is not an application bug fix, the check is inapplicable and passes.

Full details: Weakened Safeguards Are Justified

Explanation

PR #2628 (author ac-pplx, base ac/api2-AH5-api-area-d-handles, head ac/api2-AH4-api-area-c-handles) changes one commit in the local checkout, 02a811508, which matches the PR title. It touches 33 files, all under crates/l40_api/api/src/routes/admin/. I checked the commit for each item in the custom check. - No lint or allow attributes were added. A grep for #[allow, #[expect and #[ignore in routes/admin finds nothing in HEAD. - No test functions were added or removed. A per-file count of #[test] and #[tokio::test] is unchanged in every file. - The one removed assertion is assert!(store_policy(&amp;db.pool, &amp;reset).await?.disk_mib.is_none()); in warm_pools/tests.rs. It is re-added as the same assertion split over several lines, with &amp;Db::from(db.pool.clone()) in place of &amp;db.pool. The condition is unchanged. - Other test edits are mechanical handle conversions. Examples: pool.begin() becomes Db::from(pool.clone()).begin(), &amp;mut *tx becomes &amp;mut tx, and DbError::from(err) becomes err. The DbError::from case only drops an identity conversion. No expected value or assertion changed. - The commit changes no Cargo.toml, [lints] table, CI workflow, nextest config, allowlist, baseline, skip or known-failures file, or AGENTS.md, CLAUDE.md, skill or guideline file. The PR description says the change is a refactor and lists the test runs. Those statements do not affect the verdict, since no safeguard was removed or weakened.

Full details: Agent Tooling Runs No New Commands

Explanation

The check fails only if the diff adds or changes agent tooling that runs commands or starts servers. This PR (#2628, author ac-pplx) changes Rust code only. Evidence: - The checked-out HEAD (02a811508) holds a three-commit stack on top of main: 67e6c3b75, 99e89cc41 and 02a811508. The PR's own commit, 02a811508, changes 33 files, all Rust files under crates/l40_api/api/src/routes/admin/. None match agent-tooling patterns. - Across the full stack range (67e6c3b75^..HEAD, 112 files), every changed file is a .rs file. No plugin manifest, SKILL.md, command file, CLAUDE.md/AGENTS.md, .mcp.json, hooks file or .claude/ file changed. - Added lines in that range contain no inline shell substitution (! followed by a backtick), no hooks, allowed-tools, mcpServers or MCP/LSP entries. Context: vs main, the branch also contains agent-tooling edits (.agents/plugins/pplx-space/skills/space-validation/references/smoke-testing.md, infra/space/kind/AGENTS.md, space_smoke/AGENTS.md). Those come from commits below this stack (for example ac76e0548, #2631). They are outside the PR's own change and in any case contain only prose and fenced text. The PR does not introduce them. Caveat: the local checkout is detached at the stack head, and the PR's base branch name does not resolve locally. I compared against the stack's own commits instead. This does not change the result, because every commit in the stack above main is Rust-only.

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, out-of-repo path, [patch], [replace]), a container image reference, a downloaded binary or archive, or a Helm chart dependency. Evidence gathered: - The PR head commit 02a811508 ("api: move the admin routes onto postgres-pool's Db and Tx") changes 33 files. All of them are Rust sources under crates/l40_api/api/src/routes/admin/. No Cargo.toml, Cargo.lock, Dockerfile, YAML, Chart, shell script, or CI file is in the commit. - The stacked commits directly below it (67e6c3b75, 99e89cc41) were also checked. Across 67e6c3b75^..HEAD, every changed file is a .rs file. No TOML dependency-source keys were added. - Searches of the added lines for FROM, image:, curl, wget, sha256, checksum, and digest found no container image reference and no download. The one "digest" hit is a Rust function name, lock_releases_of_digest, and not an external source. The primary PR's base branch (ac/api2-AH5-api-area-d-handles) is not present in this checkout. I therefore compared against the parent commits of the stack. The result is the same for either view: no in-scope external code source is added or changed. Limitation: the exact provider-side base diff could not be retrieved. The verdict relies on the local commit history, which contains the PR's own commit at HEAD.

Full details: Public-Safe Content

Explanation

Checked the PR title, the contributor description, and the diff for the sensitive categories listed in the Public-safe content check. - Diff: I fetched the PR head (ac/api2-AH4-api-area-c-handles) and base (ac/api2-AH5-api-area-d-handles) and compared them (33 files). A scan of the added lines found no private keys, AWS account IDs or ARNs, GitHub or AWS tokens, personal absolute paths (/Users/&lt;name&gt;/, /home/&lt;name&gt;/), internal hostnames, or private tracker or chat links. The scan found no URLs at all in added lines. - Credential-like hits: A search of the admin routes tree matched only test fixtures and variable names (for example generate_api_key() and password = Uuid::now_v7() in test code). These are not real credentials. - Description: It names only PRs in the same repository (#2396, #2401, #2402, #2630, #2637). It mentions a local Kind/Firecracker cluster and a "pinned CI Postgres image" without naming any real cluster, host, or environment. It has no absolute paths and no links. - Test counts and statement logs: The differential results are counts and comparisons from a disposable test harness. They are not raw production logs, query output, or production measurements. - Security: The description does not describe an unfixed or undisclosed vulnerability. - AI credit line: The description ends with "AI assistance: Claude Code drafted…". It is not a "Created with …" line and contains no link or internal value, so it does not trigger a failure. No sensitive content was found in the title, description, or diff.

Full details: Description Follows The Pr Template

Explanation

The PR description does not meet the template check. It has one ## heading other than the required ones: ## Stack. It has no ## Summary, no ## Validation, and no ## Severity and risk heading. 1. ## Summary section: missing. The opening paragraph describes the change, but it has no ## Summary heading. 2. ## Validation section: missing. The validation content exists. It appears under plain-text lead-ins such as "At this head:", "Statement-log differential", and "The area's own tests", with no ## Validation heading. The check requires the section. 3. ## Severity and risk section: missing. The text "Severity: does not apply." and "Risk: low." appears as plain-text paragraphs under no heading. 4. AI assistance: line: present. The line reads "AI assistance: Claude Code drafted the code changes, the disposable differential harness and this description." This item passes. The check judges presence only. Three of the four required items are not present as sections. The check fails.

Resolution

Edit the PR description so it has these headings, each with its content under it: - ## Summary: state what merging the change does. Move the opening paragraph under this heading. - ## Validation: name each run and its result, or write "CI on this head". Move the "At this head", statement-log differential, and test-run text under this heading. - ## Severity and risk: state a severity (or "does not apply") and a risk. Move the "Severity: does not apply." and "Risk: low." lines under this heading. Keep the existing AI assistance: line.

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.

This pull request is a draft

Merging is unavailable until it is marked ready for review.