Repository navigation
feat: run deployment builds in Cloudflare Containers (phase 3) - #2721
Conversation
|
Important Review skippedWe couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting You can disable this status message by setting the Use the checkbox below for a quick retry:
Walkthrough
Merge Risk:
|
Merging this PR will not alter performance
Comparing Footnotes
|
|
@coderabbitai review |
Action not completed
|
…-run-3xj273 # Conflicts: # apps/api/src/scheduled/handler.ts
|
@coderabbitai review |
Action not completed
|
|
…2753) (#2772) * Fix security finding acf_1c430965be49bdf046a1933ae3b533a0 * fix(api): race-safe first-superadmin election without demoting anyone Corrects the bot election from #2753: - Election (services/first-superadmin.ts): promote the signing-in user in one guarded UPDATE only while they are the ONLY real (status != 'system') account, are not suspended, and the election marker is absent; then record the oldest real superadmin as the marker in the same D1 batch. A later sign-up never wins against an existing account (suspended or non-admin), and two sign-ups whose rows both exist fail closed rather than electing by timing. - Report installs with more than one superadmin via a structured first-superadmin.multiple_superadmins warning on sign-in, folded into the existing single read. No user row is changed. - session.create.before: catch election failures, log auth.first_superadmin_election.failed and continue without promotion, so a D1 error never blocks login. - Migration renumbered 0242 -> 0243 (open PR #2721 already uses 0242). It now only inserts the marker for installs that already have a non-system superadmin and never updates or deletes users; the oldest-superadmin demotion is removed. - Tests: real-SQL election/migration tests on drizzle-built tables (attack cases paired with owner controls), the auth.test fixture regression, and workers tests that drive BetterAuth's createSession against real D1 (happy path, existing-account refusal, D1 outage, owner-email skip, and the BOOTSTRAP_OWNER_EMAIL recovery path). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: first-superadmin election, duplicate superadmins and admin recovery Describe the one-time ordinary election (only-real-account guard, durable setup.firstSuperadminEstablished marker, login never blocked), how to review and resolve more than one superadmin, and the recovery paths when no account can administer the instance: the BOOTSTRAP_OWNER_EMAIL Worker secret (bootstrapSessionAllowed) or a direct D1 update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(api): keep first-superadmin migration at 0242 and locate it by name Coordinator decision: main ends at 0241 and the builder branch also uses 0242; whichever merges second renumbers, so do not renumber speculatively. Tests now find the migration by its `_first_superadmin_election.sql` suffix, and the code comments and docs name it without a number, so a renumber is a file rename only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: correct first-superadmin recovery details after review - wrangler secret put needs --name (no checked-in env sections) - owner-email recovery does not apply to an installer-bound instance whose owner was already established; use the D1 update there - the duplicate-superadmin warning is logged only without BOOTSTRAP_OWNER_EMAIL - admin-settings and .env.example no longer claim nobody is ever promoted again - rule 40 notes where the promotion lives now Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: parameterize duplicated first-superadmin attack and self-heal cases Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(api): number the first-superadmin migration 0243 0242 is taken by the Cloudflare build executor migration (PR #2721), which is already applied on staging. Migration-ordering CI rejects duplicate prefixes; the migration is replay-safe and tests locate it by name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(api): renumber the first-superadmin migration to 0246 after main's 0245 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Raphaël Titsworth-Morin <raphael@raphaeltm.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
@coderabbitai review |
Action not completed
|
|
For the owner of this PR (task 01M7C1SRMAWR3PYFWKF03XJ273), from task 01M7HK7TY9GA8DTV3BGS4QYNM8: two staging changes merged today.
Since this PR merged, main has v23 and primary staging is consistent again; nothing needs repairing. For future migration branches: verify on staging2. If the branch has not merged when you're done, tear staging2 down (Teardown → |



Summary
Instant
build_and_publishuploads a verified portable Compose context and runs the build in a dedicated Cloudflare DinD microVM. VM sessions default to the node executor and can select Cloudflare in Admin Settings. The Go builder reusesinternal/publishand existing publish callbacks; old agents fail explicitly rather than silently moving the build back to the source.A conditional D1 UPDATE enforces two reservations per project and six platform-wide, clamped to class capacity. Cron drains eligible projects fairly; capacity errors back off. Reservation epochs fence late startup outcomes and retries. An independent durable deadline destroys the guest; terminal stop skips inactive guests and clears obsolete schedules and the native alarm. A durable quiescent marker suppresses SDK reconstruction renewal and stale alarm delivery until a fresh admission. A database trigger retains reservations through deletion cascades until confirmed shutdown or the bounded deadline-plus-grace escape.
Raphaël approved unrestricted build egress November15, superseding the initial host-allowlist proposal. Arbitrary root RUN code executes with host networking inside the microVM and receives only one job's callback/object authority. No platform credentials or runtime secrets are supplied. Bootstrap closes before build execution. Two exact Sonar HTTP findings are narrowly documented private-workerd-port false positives; this adds no public plaintext transport.
Merged and production verified. PR2721 merged08:11:32UTC as
a96b6e847f557c5b4693a78efcb3e21b3298a3e2after coordinator approval of exact headab0d2363107ca12ac749a0f41db3a7cc9c3a29f3, PR Evidence green, ready CI success and a production-idle check. The merge used--match-head-commit; no main-only update or additional code change was needed. Staging cleanup and lease release were completed before merge.Ready-state CI43823981787 attempt1 passed PR Evidence and all seven DO shards but API3 hit an unchanged capacity-pool-edit-query-plan.test.ts five-second timeout (idea01M7HNXQ1EE0W8NKV23PPHDA1M). Local focused2/2 passed; exactly one failed-jobs-only retry succeeded (attempt2). No approved-head changes.
Final coordinator correction
Diff from previously reviewed
7c17f185: merge main60e899730 via b741106 (only adjacent scheduled-handler imports conflicted; retained both and sorted), then bounded reservation retention. Applied0242 and guard0244 remain unchanged; no new migration or duplicate prefix, builder DOv23 remains after mainv22.Cron now force-releases reservations after the immutable builder deadline plus
deployments.builderReservationGraceMs(named default300000). The atomic update fences attempt, epoch, instance and deadline and changes unfinished jobs tounknown, revoking late callback authority. Existing terminal verdicts remain. A structured error and dedicated alert-level job event explicitly report unconfirmed physical shutdown; failed telemetry does not undo release or block later jobs. Temporary undercounting and occupied Cloudflare capacity are accepted instead of permanent admission/deletion failure.Deletion audit: owner node DELETE preflights before provider destruction and again before D1 removal; a racing admission can retain the tombstone after provider deletion, with strict termination evidence supporting retry. Cron teardown and warm-pool handoff update/tombstone nodes, so do not fire the DELETE trigger. A small adjacent fix guards fallible per-node failure diagnosis so later nodes still progress (idea01M7HHXGHRBG8T97K1M357ESMN). Self-service account deletion is disabled in BetterAuth; direct user deletion remains atomically blocked by held reservations until confirmed/forced release.
Correction validation: 48 focused tests pass, including actual shipped SQLite/FKs proving inside-grace rejection, past-grace cascading deletion, preserved terminal verdicts, revoked late callbacks, stale reservation fences and per-item mutation/alert-failure isolation. API typecheck, package build/lint, affected API lint, docs build291pages, source-contract/runtime-tunable/migration-ordering/DO-safety checks pass. Independent security/correctness and config/docs/constitution reviews PASS. No Go executable changes. Current-head full CI43820100864 PASSED on the first attempt, including all seven Durable Object shards. Trusted incremental CodeRabbit43820106498 requested06:55:19; comment6909642429 at06:55:36 says Incremental review skipped, so wait ended immediately with no retrigger. The prior draft PR Evidence failure reflected the review-hold label; coordinator approval now authorizes removing it and rerunning the PR gate on this unchanged SHA.
Production verification — November16
COMPOSE_BUILDER/ComposeBuilderContainernamespacec6ac62e463504374bc7a8d049ad7c30f. Worker version6e1809dd-88b7-4696-9dfd-0fa9fe77aca1is at100%.a03b08bd-8cfc-4a24-b259-c2c2a5b1d9e3was directly created atv1; it has no gradual rollout. Builder image digestsha256:9cdeefd8ca4435b5bda7a3e7d4b1e147b686a12f6d40695772cb29b3127f4d63.01M7HDK9DV8G2JPBK1KTVNY6JNand deferred VM-proof01M7H8GCR5FFDEXA70DNMEF8BWhave both been posted UNBLOCKED. VM proof is still unproven and VM default remainsnode. No follow-up implementation or staging trial started here.Validation
Previous reviewed head7c17: CI43813866700 SUCCESS on the first attempt, including all three Durable Object shards.
git diff -U0 018a56f1..HEAD -- '*.go'filtered to changed lines finds two comment additions and zero executable changes. Only runner.go, the deployments guide and the active task differ; independent qualification review passed. Runtime CI43805600123 attempt2 SUCCESS.API callback authentication/actual byte bounds, job/attempt/source handoff fencing and profile guard:126 focused tests passed during the correction unit; subsequent real-setting/legacy callback fixtures also passed.
Reservation epochs/fair drain/deadline:94 focused cases passed, including23 DO lifecycle cases. Controlled stale outcomes, capped backlog, deferred SDK startup, diagnostic blockage and inactive terminal wake cases failed before their fixes.
Deletion correction:89 related cases across8 files passed. Independent security reran22 deletion/route cases; actual shipped SQLite FK migrations prove direct/node/project/environment/user cascades, terminal-held versus released reservations and both delete/admission orderings. Workspace-only deletion retains the job because workspace_id has no FK.
Go builder/publish race suites and real daemon-free Compose5.7.1 path regression passed. Archive directory modes are restored after successful extraction; runtime placeholders remain separate from build interpolation.
Package build, API typecheck, affected lint, docs build and migration ordering/safety passed. Applied D10242 is unchanged; the new unapplied deletion guard is0244 after a fresh open-PR collision audit. DO migration remainsv23 (mainv22).
Prior candidate full manual CI: 43792773359 SUCCESS on83febdf0ac, including all three Durable Object shards. Prior76f3 run43791408547 exposed four stale fixture contracts; these are corrected in tests only, with48 related cases across6files, API typecheck/lint and source-contract check passing. Production code and e1ed binary inputs are unchanged. The superseded12372 run43790800522 (now canceled) found the source-contract checker rejecting a direct migration SQL read; the test now executes the same SQL via the existing applySqliteMigration helper, and13 migration cases plus the source-contract check pass locally. Historical c577 run43776771299 attempt2 passed after exactly one unchanged unrelated archive-shard retry; this is not final-head evidence. Known archive flake remains out of scope.
Native-alarm correction:33 focused cases across3files pass, including9 real installed-SDK/SQLite scenarios (original baseline6RED/1PASS). Removing only the production native-alarm deletion reproduces the explicit-stop failure; restored code is GREEN. API typecheck/lint/format pass; independent Cloudflare/lifecycle and security reviews pass. Delayed SDK sync and old-stop/readmission races are controlled. Current fullCI: 43805600123.
Staging Verification
Runtime was tested at
018a56f1acb78755a959ea053f18e5dad3338f64, with agent/buildere1ed097d8d345f241d1205dd47a4168cbfc1e5f4. Full CI 43805600123 attempt 2 passed after exactly one unchanged runtime-secret overlap-test retry (idea01M7HB8YEFM9YTZWFH31PQ0DX0). Deployment 43807052699 and smoke passed. Worker served the exact commit at 100%; both actual Container rollouts completed 100% before trials; D1 0244 was applied.01M7HDZ456E5C8BJ91ZW4NDW07succeeded at 05:43:39 UTC. Exact source instance was inactive at 05:42:23 while the job was still building at 05:42:34. No manual sleep or cancellation was needed.01M7HE3RQ41M15X3MC5870XKCCapplied; unauthenticated GET at 05:49:32 returned 200 with the exact fixture marker and no redirects. The single target VM was cx23, 2 CPU/4 GB, and reported the deployed e1ed binary.01M7HCZC8WS4E7VJ88ST2FTA3Zfailed in an invalid generated Python fixture (idea01M7HDH4BFZ77B0XKREE33JNTT). Its builder likewise stayed inactive beyond its original deadline+2; final unsampled telemetry had 3/3 events after 309 seconds ingestion wait. This failed job does not count as served-release proof. The coordinator explicitly approved exactly one corrected replacement in the same lease.7f5276c169260cf0d917de67664497c8b01b0fb1a0adf054fdb656ff2ada9dde; image 22,585,856 bytes / SHA25610481734d6bd0698c365775827c2970a1b00a9a8a13a30300acdac38795334d4. The earlier successful Instant trial on 83feb supplied the required >100 MiB proof: context 125,833,194 bytes / SHA256d3053459ce85a46969333d4101d5b6601432a50022c8f0152eb4faf532fc4a9d; image 147,402,752 bytes / SHA256c2164dbbbbb33b945137a3d29abb7b8ef768b71b91a1e5487c9fffacb9fd2644.The previous 83feb trial exposed the stale native-alarm recurrence (idea
01M7GYR3VCTK0G72HBHJJ000G5); the real-SDK regression tests and the focused success/failed-terminal trials above validate its correction. Prior trial cleanup and lease release completed before this trial began.VM Cloudflare capability remains unverified and explicitly deferred to idea
01M7H8GCR5FFDEXA70DNMEF8BWby the coordinator. No VM-source publish task/job was submitted. Baseline counters alone do not establish zero delta. VM sessions retain unconfigureddeployments.buildExecutor=node; keep that default until the follow-up proves a served release and same-process zero source build/save delta.Build diagnostics follow-up: Cloudflare currently discards Docker failure detail preserved by node builds. High-priority idea
01M7HDK9DV8G2JPBK1KTVNY6JNis the first follow-up after merge. The coordinator accepted this deferral with a code TODO and an explicit deployments-guide limitation. The final diff from runtime-tested 018a contains only Go comments, documentation and task evidence; executable Go is unchanged, although the comment rotates the release identity.Cleanup: both tasks/workspaces, environment, profile and project deleted normally; all three owned node records are deleted with runtime termination confirmed (target VM at 05:51:19). Deadline setting restored to original absence at revision 86. Logout returned a null session and removed the private cache. Immediate audit at 05:52:59 is clear; late audit at 05:58:08 is clear. Normal release workflow43813679472 succeeded; authoritative PRIMARY lease record7816727391 is RELEASED at05:59:18.866. Exact source/builder instances are inactive; public DNS and release rows are gone. Exact R2 objects remain under the approved >=48-hour retention exception. Aggregate estimate USD 0.914512, reserve USD 0.95, below the USD 1 ceiling; this is not a billing assertion.
Specialist Review Evidence
CodeRabbit Review Evidence
Trusted main workflow43780966380 requested review November16 00:32UTC; CodeRabbit review5913874558 returned9 inline and1 outside finding. All9 inline findings are fixed, explained in replies and resolved. The valid outside deletion/accounting finding is fixed by0244 plus authorized preflights; the proposed permanent-R2-orphan issue does not apply because existing cleanup LISTs retained prefixes independently of job rows. One incremental trusted request43790805717 was made at02:13:14UTC after the production fixes; CodeRabbit check133049508279 ended neutral with Review rate limited (all analysis steps skipped). The wait ended immediately under policy; no retrigger. The subsequent76f3 change only routes the behavioral migration test through the shared helper; production code is unchanged. The new native-alarm unit received one trusted incremental request43805627532 at04:41UTC; check133096137886 ended neutral RATE LIMITED with all analysis skipped; wait ended immediately. No retrigger loop. Every arriving finding remains binding. Final bounded-reservation unit: trusted workflow43820106498 requested06:55:19UTC; CodeRabbit comment6909642429 at06:55:36 says Incremental review skipped. Wait ended immediately under policy; no retrigger.
Agent Preflight
Classification
External References
Read the entire November 6 implementation section of idea
01KZ6V37D1QGDR3WN12PSDB0QD, linked phase-0 spike and PR #2605 contracts before implementation. Official documentation: outbound traffic, Container API, DinD guide. Installed Containers SDK 0.3.7 source/types checked. November 15 egress approval is recorded in knowledgeCloudflareDeploymentBuilds.Codebase Impact Analysis
Business logic remains in
packages/app-deployment/, with thin adapters underapps/api/, schema inpackages/worker-core/, source collector and Go builder inpackages/vm-agent/, and image/deploy/cache wiring underscripts/deploy/. Existing deployment apply remains the target. Cron terminal cleanup and reserved-start recovery inspect at most classMax candidates; queue drain is bounded by builderDrainLimit.Documentation & Specs
Deployments/Instant guides, security architecture, configuration reference, self-hosting note, API contracts and active task match the approved one-job microVM trust boundary and open egress.
Constitution & Risk Check
Operational budgets and sizing are configurable. Root DinD with host build networking is required by measured spike evidence. The microVM is the isolation boundary; arbitrary root code is assumed to possess one job's callback and short-lived object authority. No broad credentials are delivered. Cleanup and cross-project/attempt fences remain mandatory.