Skip to content

Reuse unchanged container images in staging and production deploys - #2770

Merged
simple-agent-manager[bot] merged 10 commits into
mainfrom
sam/staging-production-deploys-stop-cad8ke
Nov 16, 2026
Merged

simple-agent-manager[bot] merged 10 commits into
mainfrom
sam/staging-production-deploys-stop-cad8ke

Conversation

@simple-agent-manager

@simple-agent-manager simple-agent-manager Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Staging and production deploys stop rebuilding, pushing and rolling out the two Instant container images (apps/api/Dockerfile.sandbox, apps/api/Dockerfile.vm-agent-container) when nothing that goes into them has changed. Task 01M7G55K6BSR1RPMZK14CAD8KE; ideas 01M7FYGMEESYH3AJZJ0CT3NKCZ and 01M0QED2G61RWM8Z3TPFCHEQXS (item S1).

Measured on staging, same day:

Deploy Resolve images Deploy API Worker Rollout wait Deploy job What happened
Baseline 43725591242 (main) n/a 376 s 347 s ~1260 s Wrangler rebuilt and pushed both images
Run 1 43748378393 (new key) 415 s 18 s 409 s 1214 s both images built, pushed under inputs-<key>, rolled out
Run 2 43749548337 (inputs unchanged) 11 s 12 s 1 s 371 s both reused; Wrangler: "No changes to be made" for both applications
Run 3 43751675486 (sandbox Dockerfile edited) 114 s 16 s 144 s 602 s sandbox built + rolled out; VM agent reused

Production baseline: 43749474483 took 21.1 min (Deploy API Worker 408 s, rollout wait 304 s). With unchanged images a production deploy should take about 8 min.

How it works

The new Resolve container images step in deploy-reusable.yml runs after the VM-agent artifact is prepared and before the first wrangler deploy. It runs scripts/deploy/container-image-reuse.ts:

  1. analyzeDockerfile() (container-image-inputs.ts) reads every input from the Dockerfile:
    • digest-pinned base images;
    • copied files;
    • apt suites: the base image's own sources (from a reviewed table keyed by base digest) plus any deb lines written in RUN;
    • fetched URLs;
    • exact npm install -g specs;
    • pinned uv tool install specs;
    • executed build scripts.
  2. fingerprintInputs() (container-image-fingerprints.ts) fingerprints each floating input, so the key changes whenever upstream can change the image:
    • apt: the InRelease SHA256 lines for each component's amd64 Packages index. Re-signing alone does not change it.
    • fetched URLs: sha256 of the bytes.
    • npm: one isolated npm install --package-lock-only per global package, because global installs do not dedupe across packages.
    • PyPI: uv pip compile --no-build --no-config per tool.
    • copied files: sha256 plus file mode.
  3. composeImageKey() hashes all of it together with the Dockerfile bytes and Wrangler's build flags. A missing fingerprint throws, so a partial set never produces a key.
  4. The registry tag inputs-<key> lives in the repository Wrangler already uses (<worker>-<class>-<env>) and records an image built from those inputs.
    • Tag present: the deploy uses that image's digest. The lookup uses a pull-only credential.
    • Tag absent: the step runs docker build with Wrangler's flags, pushes under the tag, and deploys the new digest.
  5. The digest-pinned reference goes into the generated [env.<env>].containers image. This is the existing SAM_CONTAINER_IMAGE_OVERRIDES path; the value is also exported to GITHUB_ENV so the first-install tail re-sync keeps it.

Any doubt leads to a rebuild, never to reuse. In every case below the Dockerfile is left for Wrangler to build, exactly as before:

  • a Dockerfile instruction the analysis does not recognise;
  • a RUN command outside ALLOWED_COMMANDS;
  • a fetched URL outside REVIEWED_FETCH_URLS;
  • an npm install script outside REVIEWED_NPM_INSTALL_SCRIPTS;
  • an edited build script (reviewed by sha256);
  • an unpinned base image;
  • a failed fingerprint, a registry lookup error or a push error.

A failed docker build fails the deploy, as Wrangler's would. If the application's latest rollout failed, was cancelled, or cannot be read, the image is rebuilt to a fresh digest, so a redeploy starts a new rollout instead of re-pointing at the failed one.

Why not a Docker layer cache (requirement 2)

Measured, and read from the Wrangler 4.149 source (pushImageIfChanged, apply):

  • Wrangler always pushes from a fresh runner. It skips a push only when the local daemon already holds a RepoDigest for the image, which a fresh runner never does. Even a perfect layer cache would still push and still produce a rollout.
  • A layer cache freezes unpinned installs. BuildKit keys a RUN layer on its instruction text, so it would freeze the unpinned apt, gh, transitive npm and PyPI installs. That is the stale-image risk, and busting those layers would need the same fingerprints anyway.
  • GitHub Actions caches are branch-scoped, and staging deploys run from feature branches. The account registry is shared by every branch that deploys to an environment, and it is not a new service.
  • Cost of the check and of a miss. Fingerprinting takes about 7 s per image. On a miss, pushing dominates: run 1 spent 104 s (sandbox) and 202 s (VM agent) of its 415 s pushing, and 33 s and 58 s building. A layer cache would shorten misses only if it kept the big RUN layers byte-identical. That is noted on the idea as a follow-up; the common case doesn't need it.

Image inputs (requirement 3)

Image Input Treatment
both base image pinned by digest (unchanged)
both copied files: apps/api/scripts/*.mjs; container-artifacts/* (content-keyed reproducible vm-agent binary, version json, checksum-verified codex runtime); entrypoints sha256 + file mode
sandbox Ubuntu 22.04 apt (ca-certificates jq wget), gh from cli.github.com apt index fingerprints (4 Ubuntu suites + gh repo)
VM agent Debian 12 apt (both stages), gh apt index fingerprints (3 Debian suites + gh repo)
both gh keyring URL sha256 of fetched bytes (reviewed URL)
sandbox @anthropic-ai/claude-code, @openai/codex (--ignore-scripts) isolated npm lock fingerprint
VM agent 6 exact top-level npm CLIs with floating transitive deps (e.g. codex-acp → @openai/codex ^0.159.1) isolated npm lock fingerprint each; install scripts that run must come from reviewed packages (claude-code, amp, keytar, node-pty)
VM agent uv installer was unpinned latest, now pinned to 0.13.8 (its version also selects the managed Python); URL bytes hashed
VM agent mistral-vibe (96 floating transitive PyPI deps), acp-amp uv pip compile fingerprint
VM agent opencode installer, codex runtime installer, acp-amp patch reviewed by sha256 (digest-pinned or local only)

The deploy also builds only the Linux VM-agent binaries now. Nothing uploads or serves darwin builds (publish-vm-agent-artifacts.sh), and Build VM Agent went from 62 s to 21-25 s. The CLI build stays where it is: moving it off the serial path needs a parallel job, which is not a small change.

Validation

  • pnpm lint (pnpm check:fast EXIT 0 before the main merge; ESLint on all changed files after)
  • pnpm typecheck (tsc -p scripts/deploy/tsconfig.json after the latest main merge, 326372c)
  • pnpm test, relevant suites after the latest main merge:
    • 199 tests (11 files) with the deploy vitest config, including 77 in scripts/deploy/container-image-*.test.ts;
    • 175 tests (4 files) in the deploy workflow quality suites, including deploy-reusable-workflow.test.ts.
  • SonarCloud quality gate passes. The uv installer in Dockerfile.vm-agent-container is now downloaded over https-only redirects, checked against its sha256 and then run (no curl | sh); the sort comparator is an explicit code-unit compare.
  • Additional validation: I reverted each new guard once, confirmed its tests went red, and restored it:
    • key ignoring npm;
    • accepting a ranged npm spec;
    • treating a lookup error as a miss;
    • dropping the apt component check;
    • resolving npm packages together;
    • the rollout-failed guard;
    • the command allowlist;
    • the URL allowlist;
    • the npm install-script review.
  • Control-loop candidate selection: N/A, no sweep/cron/alarm change

Staging Verification (REQUIRED for all code changes — merge-blocking)

  • Staging deployment green: runs 43748378393, 43749548337 and 43751675486 (staging) and 43804232117 (staging2) all succeeded, each with the Playwright smoke tests.
  • Live app verified via Playwright: the workflow's staging smoke suite logged in to app.sammy.party and passed on all three runs.
  • Existing workflows confirmed working: the smoke suite (dashboard, projects, settings) was green on each run.
  • New feature/fix verified on staging: see the evidence below.
  • Infrastructure verification completed: one Instant (cf-container) session and one VM session on staging2, deployed from head 0d7b5ad; both agents replied, and both were cleaned up (see below).
  • Mobile and desktop verification notes added for UI changes: N/A, no UI changes.

Staging Verification Evidence

  • Run 1 (first deploy with this code):
    • | SandboxDO | built | ... | 145s | and | VmAgentContainer | built | ... | 269s |.
    • Wrangler applied EDIT to sha256:d50031c6... and sha256:5641a3b1... without building anything itself.
    • The rollout gate waited 409 s.
  • Run 2 (merge of main, no image input changed):
    • | SandboxDO | reused | inputs unchanged | 5s | and | VmAgentContainer | reused | inputs unchanged | 5s |.
    • Wrangler logged no changes sam-api-staging-sandboxdo-staging, No changes to be made for both applications.
    • The gate saw status=completed version=1939 target=1939 on its first poll and returned in 1 s.
  • Run 3 (comment added to Dockerfile.sandbox):
    • Sandbox built under new key be5335006db9203b; VM agent reused.
    • Wrangler applied EDIT to the sandbox only.
    • The gate polled the sandbox rollout progressing 13 times, then saw it complete (144 s).
  • Instant session after run 3 (staging): task 01M7GB4YR9CQK4TKQ63EBZ38YM on the reused VM-agent image (sha256:5641a3b1) finished its turn; container node deleted at 19:40:54Z. The reply text was not captured, so the check was repeated on staging2.
  • staging2, run 43804232117 (first deploy of this code there; primary staging was blocked for main-based branches by open PR feat: run deployment builds in Cloudflare Containers (phase 3) #2721's DO migration tag v23):
    • both images built (352 s resolve), rollout gate 346 s, deploy job 1088 s;
    • the sandbox key be5335006db9203b was identical to staging's run 3, so the key reproduces across installations.
  • VM session (staging2): claude-code, lightweight; the agent replied with the expected marker. Its node 01M7HBJHTKVSJYAE9R4G7CCQT8 heartbeated healthy on agent build 7bea824b (built from the linux-only VM agent targets). Workspace and node cleaned up, verified in D1.
  • Instant session (staging2): the agent replied with the expected marker 54 s after submit; cleaned up, verified in D1.
    • A first Instant attempt, started ~5 s after creating a fresh Artifacts project, failed its clone (could not read Username). The same flow 90 s after project creation succeeded, and a VM session on the first project cloned fine. This is a pre-existing race unrelated to the images; filed as tasks/backlog/2026-11-16-instant-artifacts-new-project-clone-race.md.
  • staging2 lease released at 05:14:16Z (run 43808654059).

End-to-End Verification (Required for multi-component changes)

  • Data flow traced from user input to final outcome with code path citations
  • Capability test exercises the complete happy path across system boundaries
  • All spec/doc assumptions about existing behavior verified against code
  • Gaps documented below

Data Flow Trace

  1. deploy-reusable.yml runs "Resolve container images".
  2. container-image-reuse.ts:main() reads the top-level containers in apps/api/wrangler.toml and the names from containerApplicationNames().
  3. For each class, resolveContainerImage() runs analyzeDockerfile(), then fingerprintInputs(), then composeImageKey(), then latestRolloutFailed() (createRolloutApi).
  4. It then calls RegistryIo.lookup() (docker manifest inspect) or buildAndPush() (container-image-registry.ts).
  5. applyImageOverrides() writes [env.<env>].containers[].image. GITHUB_ENV gets SAM_CONTAINER_IMAGE_OVERRIDES, which sync-wrangler-config.ts:generateContainerBindings() reads again on the tail re-sync.
  6. In wrangler deploy, apply() compares image references: an unchanged reference means no rollout.
  7. wait-container-rollout.ts runs the gate.

Untested Gaps

  • The Docker/registry process boundary (container-image-registry.ts) is exercised by the staging runs, not by unit tests. Each of its failure modes falls back to a Wrangler build.
  • A clean install (no repository yet) has not been run live. A missing repository is treated as "no image" (name unknown), and any other lookup error falls back to Wrangler; both paths build.

Post-Mortem (Required for bug fix PRs)

N/A: not a bug fix (deploy speed).

Specialist Review Evidence (Required for agent-authored PRs)

  • All local reviewers completed and findings addressed before merge
  • If any reviewer did NOT complete: needs-human-review label added and merge deferred to human: all completed
Reviewer Status Outcome
cloudflare-specialist ADDRESSED No CRITICAL/HIGH. MEDIUM: a failed rollout plus unchanged inputs would never roll out again; now a latest rollout that failed, was cancelled or is unreadable rebuilds a fresh digest (efa4cac). MEDIUM: "same reference gives no rollout" was untested live; run 2 verified it. LOWs accepted (safe fallbacks).
security-auditor ADDRESSED No CRITICAL/HIGH. M2: PyPI resolution could run sdist builds next to the deploy token; now --no-build --no-config, and resolvers run without the deploy secrets. M3: denylist replaced by ALLOWED_COMMANDS, REVIEWED_FETCH_URLS and reviewed npm install scripts. M1: registry tag as trust anchor; lookup is now pull-only and the threat model is documented (registry write access is already deploy access). L4: uv installer checksum on the runner. L6: summary newline collapse, credential lifetime cap (efa4cac).
constitution-validator PASS No violations; 2 LOW doc wording fixes applied.
task-completion-validator ADDRESSED WARN, no CRITICAL/HIGH: checklist ticked; backlog task for the installer's imageContextKey (tasks/backlog/2026-11-15-installer-prebuilt-image-key-floating-inputs.md); sandbox decision test added; measurement recorded above.

CodeRabbit Review Evidence (Required for agent-authored PRs)

  • CodeRabbit requested when the PR was marked ready for review
  • Waited about 15 minutes (or until a skip, rate-limit or quota reply), or up to about 45 minutes in total while a review CodeRabbit had started was still in progress
  • Either CodeRabbit reviewed and no CodeRabbit feedback is unresolved, or it did not review and the observed outcome is recorded below

CodeRabbit Notes

Requested at 22:18Z when the PR opened ready: coderabbit-review label added, and the trusted bridge workflow (run 43768548404) posted @coderabbitai review. CodeRabbit replied within seconds with "Review limit reached: You've used all free OSS reviews for now" (comment 6902289643) and "Review rate limited" (comment 6902295917), so the wait ended at once per rule 25. No review arrived; not re-triggered.

Exceptions (If any)

  • Scope: none
  • Rationale:
  • Expiration:

Agent Preflight (Required)

  • Preflight completed before code changes

Classification

  • external-api-change
  • cross-component-change
  • business-logic-change
  • public-surface-change
  • docs-sync-change
  • security-sensitive-change
  • ui-change
  • infra-change

External References

Codebase Impact Analysis

  • .github/workflows/deploy-reusable.yml: two new steps; Linux-only VM-agent build.
  • New scripts/deploy/container-image-{inputs,fingerprints,reviewed-inputs,registry,reuse}.ts and their tests.
  • scripts/deploy/installer-engine.vitest.config.ts and scripts/quality/deploy-reusable-workflow.test.ts.
  • apps/api/Dockerfile.vm-agent-container (uv pin, comment) and apps/api/Dockerfile.sandbox (comment).
  • Reuses sync-wrangler-config.ts overrides and container-rollout.ts; neither changed.
  • Compatible with the staging2 installation (worker and env names come from steps.deploy_resources).
  • No Worker runtime code.

Documentation & Specs

apps/www/src/content/docs/docs/guides/self-hosting.mdx, new "Container image reuse" section: behaviour, threat model, CONTAINER_IMAGE_REUSE_ENABLED, CONTAINER_IMAGE_FINGERPRINT_TIMEOUT_MS, CONTAINER_REGISTRY_CREDENTIAL_MINUTES.

Constitution & Risk Check

  • Principle XI: the timeouts and the credential lifetime have DEFAULT_* constants with GitHub Environment overrides. The registry host and build flags mirror Wrangler.
  • Rule 74: the signal (the content key) is derived from the condition's own content, and every degraded input fails closed to a rebuild.
  • Risks:
    • A fingerprint gap would freeze an input. Mitigated by the allowlists and reviewed lists, which disable reuse for anything unknown.
    • Registry write access can replace the image behind a tag. Documented; it is the same privilege the deploy token already has.
  • Kill switch: CONTAINER_IMAGE_REUSE_ENABLED=false.

🤖 Generated with Claude Code

raphaeltm and others added 7 commits November 15, 2026 18:22
Key each Instant container image by its Dockerfile, copied files and a
fingerprint of every network-installed input (apt indexes, fetched URLs,
isolated npm resolutions, uv PyPI resolutions). A registry tag
inputs-<key> records a built image; an unchanged key deploys that digest
with no build, push or rollout. Any doubt leaves the Dockerfile for
Wrangler to build as before. Pin the uv installer. Build only the linux
VM-agent binaries the deploy publishes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…m review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- rebuild a fresh digest when the latest container rollout failed, was
  cancelled or cannot be read, so redeploying retries the rollout
- allowlist RUN commands and fetched URLs; npm install scripts that run
  must belong to reviewed packages
- resolve PyPI with --no-build --no-config, run resolvers without the
  deploy secrets, look up the registry with pull-only credentials
- verify the uv installer checksum on the runner; cap credential lifetime
- split the Docker/registry boundary into container-image-registry.ts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@simple-agent-manager simple-agent-manager Bot added the coderabbit-review Trigger CodeRabbit review for opt-in PRs label Nov 15, 2026
@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

- Dockerfile.vm-agent-container downloads the pinned uv installer over
  HTTPS-only redirects, checks its sha256, then runs it (Sonar S8482,
  S6506); the image analysis allows running a file a RUN downloaded
  from a reviewed URL, and sha256sum
- enforce HTTPS redirects for the runner-side uv installer
- explicit code-unit sort comparator (never localeCompare: keys must not
  depend on the host locale); URL literals stop at shell separators
- small readability fixes Sonar flagged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
raphaeltm and others added 2 commits November 16, 2026 05:15
…e; file Artifacts Instant clone race

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@simple-agent-manager
simple-agent-manager Bot merged commit b83d697 into main Nov 16, 2026
34 checks passed
@simple-agent-manager
simple-agent-manager Bot deleted the sam/staging-production-deploys-stop-cad8ke branch November 16, 2026 05:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coderabbit-review Trigger CodeRabbit review for opt-in PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant