:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
ci(hogbox-preview): run frontend build in parallel with box bring-up (#69203)
Julian Bez4217f14edfc3
diff --git a/.github/workflows/hogbox-preview-env.yml b/.github/workflows/hogbox-preview-env.ymlindex ae9ad9a782cd..cf81769eee7c 100644--- a/.github/workflows/hogbox-preview-env.yml+++ b/.github/workflows/hogbox-preview-env.yml@@ -16,9 +16,13 @@# the BACKEND runs the PR code with NO per-PR build or pull, and runs `migrate` —# applying only the PR's *unapplied* migrations on top of the seeded DB. That# keeps each preview off both the cold 20-min build and the heavy full-migrate-# path. The PR's FRONTEND is built in-box from the mounted source and served from-# frontend/dist. If a PR's migrations are incompatible with the baseline, fall-# back to --reset-db.+# path. The PR's FRONTEND is compiled on the runner (the untrusted build-frontend+# job — never in credential scope), shipped in as a dist tarball through+# hogplane's files API (chunked past the 64 MiB write cap), laid over the image's+# baked dist in-box and followed by a collectstatic re-run. Label-only backend+# PRs that don't touch the frontend skip all of that and serve the image's+# :master SPA. If a PR's migrations are incompatible with the baseline, fall back+# to --reset-db.## --- TRIGGER (who gets a preview) -----------------------------------------------# The `decide` job (cheap, credential-free) is the gate. A same-repo, human,@@ -30,9 +34,12 @@## --- LIFECYCLE ------------------------------------------------------------------# - build/update: once `decide` says build, `announce` posts the in-progress-# Deployment + comment, the untrusted `build-frontend` job builds the PR's-# dist (no credentials — see the permissions note below), and the trusted-# `deploy` job brings the box up.+# Deployment + comment, then `build-frontend` (untrusted, no credentials —+# see the permissions note below) and `deploy` (trusted, brings the box up)+# run IN PARALLEL. deploy no longer waits on the dist: it restores + mounts ++# migrates immediately, and only blocks on build-frontend right at the end,+# to swap the finished dist in before it posts "ready". Cuts wall-clock from+# ~9.5 min (serial) to ~6 (the FE build hides under the longer bring-up).# - teardown on PR close + the daily stale-sweep: pr-closed.yml (box + pen) +# hogbox-preview-cleanup.yml's cron. The GitHub Deployment/environment# (preview-pr-<n>) is reaped by pr-cleanup.yml's existing deployment cleanup.@@ -238,7 +245,7 @@ jobs:const marker = '<!-- hogbox-preview-comment -->';const body =`${marker}\n### 🦔 Hogbox preview · 🔧 building…\n\n` +- `Spinning up PostHog for this PR on a hogland hogbox — this comment updates in place when it's ready (usually ~1–2 min).\n\n` ++ `Spinning up PostHog for this PR on a hogland hogbox — this comment updates in place when it's ready (usually a few minutes).\n\n` +`<sub>commit \`${sha.slice(0, 7)}\` · <a href="${runUrl}">build log</a></sub>`;const { data: comments } = await github.rest.issues.listComments({ ...context.repo, issue_number: pr });const ex = comments.find(c => c.body.includes(marker));@@ -252,30 +259,29 @@ jobs:# OIDC token or write anywhere. Its only product is the dist artifact the# trusted `deploy` job consumes as data.#- # Per-PR cancelable group, keyed on PR number ONLY, and set at the JOB- # level (not workflow level). Rapid pushes coalesce — median 4 pushes/PR,- # p90 17, so without this a busy PR could queue 17 sequential ~10-min- # rebuilds; cancel-in-progress keeps just the latest. Because only an- # eligible run (decide.build==true) reaches this job, a filtered-out event- # never enters the group — so an unrelated `unlabeled` can't cancel an- # active build. `deploy` and `teardown` share this group so the latest- # intent wins (a no-preview teardown cancels an in-flight build for the- # same PR, and vice-versa). Dispatch uses the same key so a manual rebuild- # coalesces with a push rebuild for the same PR.+ # DELIBERATELY NOT in the per-PR concurrency group. build-frontend and+ # deploy now run in PARALLEL within one run (deploy waits on it only at the+ # end, to swap the dist in), and GitHub won't run two jobs of the same group+ # at once — so sharing the group would deadlock them (one sits queued behind+ # the other forever). The group therefore lives on `deploy`/`teardown` ONLY.+ # ACCEPTED COST: a superseded push cancels the newer run's deploy (via the+ # group), but this run's build-frontend is NOT cancelable, so it may run to+ # completion wasted (~3.5 min of runner time). No correctness impact — its+ # artifact is namespaced to its own run_id, so a stale build can't leak into+ # the winning run's swap.build-frontend:name: build PR frontendneeds: decideif: needs.decide.outputs.build == 'true'- concurrency:- group: hogbox-preview-${{ github.event.pull_request.number || github.event.inputs.pr_number }}- cancel-in-progress: trueruns-on: ubuntu-24.04timeout-minutes: 30permissions:contents: readpull-requests: read # list changed files (FE detection) + resolve dispatched PR numbers- outputs:- fe_changed: ${{ steps.fe.outputs.changed }}+ # No job-level outputs: deploy no longer `needs` this job (they run in+ # parallel). It discovers whether a dist exists by checking THIS run for+ # the `hogbox-preview-frontend-dist` artifact — present ⇒ swap, absent ⇒+ # the PR didn't touch the frontend, keep :master.steps:# SECURITY GATE — manual dispatch takes a bare pr_number and the tool# later checks out `pull/<n>/head` INSIDE the box and EXECUTES it with@@ -365,13 +371,23 @@ jobs:# teardown job below and pr-closed.yml). The PR's contribution enters only# as data: the dist artifact from build-frontend, and the in-box# `pull/<n>/head` checkout the tool performs on the guest.+ #+ # PARALLEL with build-frontend: deploy deliberately does NOT `need`+ # build-frontend, so it starts bringing the box up the moment `announce`+ # opens the Deployment — restore + backend mount + migrate run WHILE the+ # runner compiles the PR frontend on its own runner. Only once the box is+ # healthy does deploy block on build-frontend (the "Wait for the PR frontend"+ # step polls this run's jobs), then swap the finished dist in BEFORE posting+ # "ready" — a reviewer must never open a green link and get :master's+ # frontend for their frontend PR. The FE build (~3m27s) hides entirely under+ # the longer bring-up (~6m), so the pipeline is bring-up-bound, not their sum.deploy:name: deploy preview- needs: [decide, announce, build-frontend]- # Runs whenever an eligible build was attempted — even if build-frontend- # or announce failed, so the failure reporter below still flips the- # Deployment + sticky comment to failed. Skips only on cancellation- # (a newer push's run took over the concurrency group).+ needs: [decide, announce]+ # Runs whenever an eligible build was attempted — even if announce+ # failed, so the failure reporter below still flips the Deployment ++ # sticky comment to failed. Skips only on cancellation (a newer push's+ # run took over the concurrency group).if: ${{ !cancelled() && needs.decide.outputs.build == 'true' }}concurrency:group: hogbox-preview-${{ github.event.pull_request.number || github.event.inputs.pr_number }}@@ -381,17 +397,34 @@ jobs:permissions:contents: readid-token: write # mint OIDC for the tailnet join AND the hogplane token+ actions: read # poll this run's jobs + artifacts to wait on build-frontendpull-requests: write # sticky preview commentdeployments: write # flip the Deployment to success/failureenv:SHA: ${{ needs.announce.outputs.sha }}DEP: ${{ needs.announce.outputs.deployment_id }}steps:- - name: Fail if the frontend build failed- if: needs.build-frontend.result != 'success'- run: |- echo "::error::build-frontend finished '${{ needs.build-frontend.result }}' — not deploying"- exit 1+ # SECURITY GATE — same fork check as build-frontend, duplicated here+ # because deploy no longer `needs` that job: without its own guard, a+ # dispatched FORK PR number would reach the tailnet join + token mint+ # below (and stand up a box running fork code) before build-frontend's+ # guard eventually failed the wait step. Runs first, before anything+ # sensitive comes online.+ - name: Guard dispatch against fork PRs+ if: github.event_name == 'workflow_dispatch'+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const pr = Number(process.env.PR);+ const { data } = await github.rest.pulls.get({ ...context.repo, pull_number: pr });+ const head = data.head?.repo?.full_name;+ const base = `${context.repo.owner}/${context.repo.repo}`;+ if (head !== base) {+ core.setFailed(+ `Refusing to build a preview for PR #${pr}: its head is ${head || '(deleted fork)'}, ` ++ `not ${base}. Manual dispatch only runs same-repo PRs — fork code must never run ` ++ `with the hogland token in scope.`);+ }# Trusted checkout: the tool code that runs with HOG_TOKEN comes from# the default branch, never the PR.@@ -399,13 +432,6 @@ jobs:with:ref: ${{ github.event.repository.default_branch }}- - name: Download frontend dist- if: needs.build-frontend.outputs.fe_changed == 'true'- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0- with:- name: hogbox-preview-frontend-dist- path: ${{ runner.temp }}/fe-dist-- name: Connect to Tailscale (tag:hogland-ci)uses: tailscale/github-action@306e68a486fd2350f2bfc3b19fcd143891a4a2d8 # v4.1.2with:@@ -431,16 +457,14 @@ jobs:- name: Bring up previewid: build- env:- # Path to the downloaded dist artifact when the PR touched the- # FE; empty otherwise → the tool keeps the golden's :master- # frontend.- FE_DIST: ${{ needs.build-frontend.outputs.fe_changed == 'true' && format('{0}/fe-dist/frontend-dist.tgz', runner.temp) || '' }}run: |# Restore the golden, check out the PR, mount its backend source- # (posthog/ee/products) over the :master image's /code, swap in- # the PR frontend (when built), delta-migrate. No per-PR image.- t0=$(date +%s)+ # (posthog/ee/products) over the :master image's /code,+ # delta-migrate. No per-PR image, and NO frontend dist here — the+ # frontend is swapped in afterwards (once build-frontend finishes,+ # below) so this step runs in parallel with the FE build. The tool+ # streams `[hogbox-preview +NNNs] <stage>` lines to STDERR for+ # per-stage visibility; stdout stays the url=/box_id= contract.out=$(uv run --no-project --with posthog-hogland==0.3.0 --python 3.12 \python -m hogbox_preview \--host "$HOG_HOST" \@@ -448,15 +472,80 @@ jobs:--snapshot "alias:posthog-preview-golden" \--cpus 8 --memory-mib 16384 --disk-gib 100 \--ttl-seconds 1800 \- up --branch "pull/${PR}/head" --no-seed --frontend-dist "$FE_DIST")+ up --branch "pull/${PR}/head" --no-seed)echo "$out"{echo "url=$(echo "$out" | sed -n 's/^url=//p')"echo "box_id=$(echo "$out" | sed -n 's/^box_id=//p')"- echo "secs=$(( $(date +%s) - t0 ))"} >> "$GITHUB_OUTPUT"working-directory: tools/hogbox-preview+ # The box is healthy on the :master SPA. NOW block on build-frontend:+ # poll THIS run's jobs for the `build PR frontend` job until it has a+ # conclusion. failure/cancelled/timed_out → fail (the failure reporter+ # flips the comment + Deployment). success WITH the dist artifact →+ # swap the PR frontend in. success WITHOUT the artifact, or skipped →+ # the PR didn't touch the frontend, keep :master (no swap). By now the+ # FE build has usually long finished, so this returns near-instantly.+ - name: Wait for the PR frontend build+ id: fe+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const jobName = 'build PR frontend';+ // Ceiling must cover build-frontend's own 30m timeout PLUS+ // queue time, minus the ~6m of bring-up already elapsed;+ // 32m keeps us inside deploy's 40m job timeout with margin.+ const deadline = Date.now() + 32 * 60 * 1000;+ let conclusion = null;+ while (Date.now() < deadline) {+ // No pagination: a preview run has a handful of jobs, so+ // one per_page:100 call always sees them all.+ const { data } = await github.rest.actions.listJobsForWorkflowRun(+ { ...context.repo, run_id: context.runId, per_page: 100 });+ const job = data.jobs.find(j => j.name === jobName);+ if (job && job.status === 'completed') { conclusion = job.conclusion; break; }+ await new Promise(r => setTimeout(r, 10000));+ }+ if (conclusion === null) {+ core.setFailed(`Timed out waiting for '${jobName}' to finish`);+ return;+ }+ core.info(`'${jobName}' concluded: ${conclusion}`);+ if (conclusion !== 'success' && conclusion !== 'skipped') {+ // failure / cancelled / timed_out — don't post a green preview.+ core.setFailed(`Frontend build ${conclusion} — failing deploy so the failure reporter runs`);+ return;+ }+ // Only a success can have produced a dist artifact; skipped never does.+ let swap = false;+ if (conclusion === 'success') {+ const { data: artData } = await github.rest.actions.listWorkflowRunArtifacts(+ { ...context.repo, run_id: context.runId, per_page: 100 });+ swap = artData.artifacts.some(a => a.name === 'hogbox-preview-frontend-dist');+ }+ core.info(`frontend swap needed: ${swap}`);+ core.setOutput('swap', swap ? 'true' : 'false');++ - name: Download frontend dist+ if: steps.fe.outputs.swap == 'true'+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0+ with:+ name: hogbox-preview-frontend-dist+ path: ${{ runner.temp }}/fe-dist++ - name: Swap in the PR frontend+ if: steps.fe.outputs.swap == 'true'+ working-directory: tools/hogbox-preview+ run: |+ # Lay the freshly-built dist over the running box + re-collectstatic.+ # Resolves the live box by pen name (preview-pr-<n>) — no restore.+ uv run --no-project --with posthog-hogland==0.3.0 --python 3.12 \+ python -m hogbox_preview \+ --host "$HOG_HOST" \+ --name "preview-pr-${PR}" \+ swap-frontend --frontend-dist "${RUNNER_TEMP}/fe-dist/frontend-dist.tgz"+- name: Report ready (deployment + comment)if: success()uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0@@ -464,30 +553,42 @@ jobs:env:URL: ${{ steps.build.outputs.url }}BOX: ${{ steps.build.outputs.box_id }}- SECS: ${{ steps.build.outputs.secs }}+ SWAP: ${{ steps.fe.outputs.swap }}with:script: |const pr = Number(process.env.PR);const url = process.env.URL;const environment = `preview-pr-${pr}`;const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;+ // Honest wall-clock: run start (≈ the push) → now (usable).+ // The full pipeline time a reviewer actually waited, not just+ // the bring-up seconds — the FE build runs under it in parallel.+ const run = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: context.runId });+ const startedAt = run.data.run_started_at || run.data.created_at;+ const secs = Math.max(0, Math.round((Date.now() - new Date(startedAt).getTime()) / 1000));if (process.env.DEP) {await github.rest.repos.createDeploymentStatus({...context.repo, deployment_id: Number(process.env.DEP), state: 'success',environment, environment_url: url, log_url: runUrl, description: 'Preview ready',});}+ // Only claim the PR's frontend when it was actually swapped+ // in; a backend-only preview serves the :master SPA, and+ // saying otherwise would be a correctness lie to the reviewer.+ const running = process.env.SWAP === 'true'+ ? "this PR's backend **and** frontend, on the PostHog `:master` base"+ : "this PR's backend on the PostHog `:master` base (frontend unchanged by this PR)";const marker = '<!-- hogbox-preview-comment -->';const body =`${marker}\n### 🦔 Hogbox preview · ✅ ready\n\n` +`### [▶ Open the preview](${url})\n\n` +`| | |\n|--|--|\n` +`| 🔑 **Login** | \`[email protected]\` / \`12345678\` (demo data) |\n` +- `| 🧩 **Running** | this PR's backend **and** frontend, on the PostHog \`:master\` base |\n` ++ `| 🧩 **Running** | ${running} |\n` +`| 🔗 **Link** | **stable across rebuilds** — a re-push swaps the box underneath, the URL stays |\n` +`| 🔒 **Access** | tailnet only (PostHog VPN) |\n` +`| 💤 **Idle** | sleeps after ~30 min idle (snapshot to S3, zero node cost) and wakes on your next visit in ~30s, behind a brief "waking up" screen |\n\n` +- `<sub>commit \`${(process.env.SHA || '').slice(0, 7)}\` · box \`${process.env.BOX}\` · up in ${process.env.SECS}s · ` ++ `<sub>commit \`${(process.env.SHA || '').slice(0, 7)}\` · box \`${process.env.BOX}\` · ready in ${secs}s (push → usable) · ` +`<a href="${runUrl}">build log</a> · rebuilds on every push, torn down on close</sub>`;const { data: comments } = await github.rest.issues.listComments({ ...context.repo, issue_number: pr });const ex = comments.find(c => c.body.includes(marker));diff --git a/tools/hogbox-preview/README.md b/tools/hogbox-preview/README.mdindex 502a86f46c52..01073d423448 100644--- a/tools/hogbox-preview/README.md+++ b/tools/hogbox-preview/README.md@@ -36,10 +36,15 @@ print(url) # https://pen-….boxes.hogland.prod-us.posthog.dev/ (stable acrossthe golden (8 vCPU / 16 GiB / 100 GiB).2. **Mount the PR's backend** (`posthog`, `ee`, `products`) over the image's`/code` — so the backend runs the PR code with **no per-PR image build**.-3. **Frontend** (only when the PR touches `frontend/**`): CI builds the PR's- `frontend/dist`, ships it into the box, and `swap_frontend` re-runs- `collectstatic` before the web recreate. Non-FE PRs keep the golden's- `:master` SPA and stay ~1 min.+3. **Frontend** (only when the PR touches `frontend/**`): the untrusted+ `build-frontend` CI job compiles the PR's `frontend/dist` on the runner **in+ parallel** with the bring-up. Once the box is healthy, the `swap-frontend`+ subcommand ships the dist in (chunked past hogplane's 64 MiB write cap),+ re-runs `collectstatic`, and recreates web — so the box comes up on the+ golden's `:master` SPA first, then swaps to the PR frontend before "ready" is+ posted. Non-FE PRs skip the swap and keep the `:master` SPA. Running the swap+ after bring-up (not inside the single `up`) is what lets the FE build hide+ under the longer bring-up instead of serializing before it.4. **Delta-migrate** — only the PR's _unapplied_ migrations on top of the seededDB (`--reset-db` if the PR's migrations are incompatible with the baseline).5. **Serve + report** — the box is HTTP-exposed; the URL is posted to the PR.@@ -123,10 +128,17 @@ Pure stdlib + the SDK; run with `uv run` or plain `python`. Subcommands mirror```bashcd tools/hogbox-preview-# one-shot: provision (pen + box) + bring PostHog up, print the URL+# one-shot: provision (pen + box) + bring PostHog up, print the URL. The CI flow+# omits --frontend-dist and swaps the frontend in afterwards (below) so the FE+# build runs in parallel; the flag stays for a single-shot local build.python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-$PR" up \--branch "pull/$PR/head" [--frontend-dist /path/to/frontend-dist.tgz] [--no-seed]+# deferred frontend swap onto the already-up box (what CI runs once the parallel+# build-frontend job finishes): resolves the live box by pen name, no restore.+python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-$PR" \+ swap-frontend --frontend-dist /path/to/frontend-dist.tgz+# granular / staged (reuse a box):python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-$PR" createpython -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-$PR" healthdiff --git a/tools/hogbox-preview/hogbox_preview/__main__.py b/tools/hogbox-preview/hogbox_preview/__main__.pyindex d74754c0a251..3eca772ef402 100644--- a/tools/hogbox-preview/hogbox_preview/__main__.py+++ b/tools/hogbox-preview/hogbox_preview/__main__.py@@ -70,6 +70,19 @@ def cmd_up(args: argparse.Namespace) -> int:return 0+def cmd_swap_frontend(args: argparse.Namespace) -> int:+ # Deferred frontend swap onto an already-up box (parallel CI flow): `up`+ # brings the box healthy on the :master SPA with no dist, then this lays the+ # PR's freshly-built dist in once the runner finishes building it. Resolves+ # the live box by pen/name — never restores a new one.+ backend = build_backend(args)+ stack = build_stack(backend, args)+ url = stack.swap_frontend_only()+ print(f"box_id={backend.box_id}")+ print(f"url={url}")+ return 0++def cmd_create(args: argparse.Namespace) -> int:backend = build_backend(args)backend.provision()@@ -196,6 +209,15 @@ def main(argv: list[str] | None = None) -> int:)up.set_defaults(func=cmd_up)+ sf = sub.add_parser("swap-frontend", help="swap the PR frontend onto an already-up box (deferred, parallel CI)")+ sf.add_argument("--box-id", default=None, help="attach to this box instead of resolving the pen by --name")+ sf.add_argument(+ "--frontend-dist",+ required=True,+ help="path to a gzipped tar of the prebuilt frontend/dist to serve (built on the CI runner)",+ )+ sf.set_defaults(func=cmd_swap_frontend)+cr = sub.add_parser("create", help="provision the box only")cr.set_defaults(func=cmd_create)diff --git a/tools/hogbox-preview/hogbox_preview/backend.py b/tools/hogbox-preview/hogbox_preview/backend.pyindex 6c78f237f4d1..31513e6421d8 100644--- a/tools/hogbox-preview/hogbox_preview/backend.py+++ b/tools/hogbox-preview/hogbox_preview/backend.py@@ -65,6 +65,15 @@ class PreviewBackend(abc.ABC):def provision(self) -> None:"""Create/restore the box and expose ``web_port``. Idempotent."""+ def attach(self) -> None:+ """Bind to the EXISTING box for this preview WITHOUT restoring a new one —+ the non-creating counterpart to ``provision``. Used by the deferred+ frontend swap, which must act on the box ``bring_up`` already stood up.+ Default: fall back to ``provision`` for layers where that's idempotent+ reuse; the hogland layer overrides it (there ``provision`` restores a+ fresh box, which a swap must never do)."""+ self.provision()+@abc.abstractmethoddef exec(self, command: str, *, timeout: int = 120) -> ExecResult:"""Run a shell command in the box and capture its output."""diff --git a/tools/hogbox-preview/hogbox_preview/hogland_backend.py b/tools/hogbox-preview/hogbox_preview/hogland_backend.pyindex 7c60aab6ca26..73af21588dd1 100644--- a/tools/hogbox-preview/hogbox_preview/hogland_backend.py+++ b/tools/hogbox-preview/hogbox_preview/hogland_backend.py@@ -37,6 +37,7 @@ from urllib.parse import urlsplitfrom hogland import AccessType, AuthenticationError, BoxSpec, ConflictError, Hogland, NotFoundError+from . import timingfrom .backend import ExecResult, PreviewBackend# hogplane caps a single write_file body at 64 MiB (octet-stream PUT). Blobs over@@ -116,19 +117,24 @@ class HoglandBackend(PreviewBackend):if self._box is not None:returnif self._box_id: # explicit reuse (debug / staged CI)+ timing.stage(f"attach to box {self._box_id}")self._box = self._client.get(self._box_id)self._wait_exec_ready()+ timing.stage("box exec ready")return# Stable identity first, then a fresh box from the golden. _restore_fresh# reaps a stale same-named box (a leaked prior run) via its ConflictError# path, so at most one box holds the name at a time; we then point the pen# at the new box. The pen outlives the box across pushes.+ timing.stage("pen resolve/create")self._ensure_pen()+ timing.stage("box restore start")self._box = self._restore_fresh()self._box_id = self._box.id# `running` means the VM resumed, not that hogpanion's HTTP API answers# yet — a restored box needs a beat before the first exec.self._wait_exec_ready()+ timing.stage("box restored (exec ready)")# Point the pen at the new box, re-send the spec so it carries the current# shape, and RE-ASSERT the hibernate/wake policies. The spec re-send heals# a pen left by an older SDK whose nested expose:{http_port} the server@@ -190,6 +196,33 @@ class HoglandBackend(PreviewBackend):time.sleep(3)return self._client.create(**self._create_kwargs())+ def attach(self) -> None:+ """Bind to the EXISTING preview box for this pen/name without restoring —+ the non-creating counterpart to provision(), used by the deferred+ swap-frontend path. Resolves the box bring_up already stood up (explicit+ --box-id, else the pen's current pointer, else a name lookup) and waits+ for its exec API, so exec/write_file/web_url act on the live box.+ """+ if self._box is not None:+ return+ # The bring-up may have burned most of the CI OIDC token's short life+ # before we get here, and the pen/box lookups below aren't wrapped in the+ # 401-retry that exec/write_file are — so mint a fresh token first+ # (best-effort no-op outside CI).+ self._refresh_auth()+ timing.stage("attach: resolve existing box")+ try:+ self._pen = self._client.get_pen(self.name)+ except NotFoundError:+ self._pen = None # no pen (e.g. --box-id debug run) — web_url falls back to the box URL+ box = self._resolve_box()+ if box is None:+ raise RuntimeError(f"no live preview box found for {self.name!r} to swap the frontend into")+ self._box = box+ self._box_id = box.id+ self._wait_exec_ready()+ timing.stage("attach: box exec ready")+def exec(self, command: str, *, timeout: int = 120) -> ExecResult:# The box exec API runs as root but doesn't set HOME; tools like git# (--global config) and docker expect it. Provide root's home.@@ -407,7 +440,9 @@ class HoglandBackend(PreviewBackend):return self._client.get(self._box_id)if self.name:try:- pen = self._client.get_pen(self.name)+ # Reuse an already-loaded pen (attach() fetches it just before+ # calling here) instead of a second GET for the same name.+ pen = self._pen if self._pen is not None else self._client.get_pen(self.name)if pen.current_box_id:return self._client.get(pen.current_box_id)except NotFoundError:diff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.pyindex 6fe41ca7e714..956c03b62c61 100644--- a/tools/hogbox-preview/hogbox_preview/stack.py+++ b/tools/hogbox-preview/hogbox_preview/stack.py@@ -36,6 +36,7 @@ from __future__ import annotationsimport sysimport secrets+from . import timingfrom .backend import PreviewBackend# The tool's web override must reproduce the golden's baked preview env (hogland@@ -146,6 +147,48 @@ class PostHogPreviewStack:self.wait_for_health()return url+ def swap_frontend_only(self) -> str:+ """Lay the PR's frontend onto an ALREADY-up preview box; return its URL.++ The second half of the parallel CI flow: bring_up() first brings the box+ healthy on the golden's :master SPA with NO dist (so it can run the+ moment the box is restored, in parallel with the runner building the PR+ frontend), then — once that build finishes — this swaps the freshly-built+ dist in. It reuses the exact override + collectstatic + web-recreate the+ single-pass bring_up runs after seeding, so there's no second recipe to+ keep in sync. Attaches to the live box by pen/name rather than restoring+ a new one.+ """+ if not self.frontend_dist_tar:+ raise RuntimeError("swap_frontend_only requires a frontend dist (pass --frontend-dist)")+ self.backend.attach()+ # Keep the box's existing SECRET_KEY: recreating web in up_web must NOT+ # rotate the key bring_up already migrated + seeded under, or anything it+ # wrote encrypted becomes undecryptable (and any live session drops).+ self._reuse_existing_secret_key()+ # Rewrite the override so it now carries the frontend/dist + staticfiles+ # mounts (write_override only adds them when a dist is set), lay the dist+ # in + re-run collectstatic into the mounted staticfiles/, then recreate+ # web so the fresh container reads the PR's index + statics.+ self.write_override()+ self.swap_frontend()+ self.up_web()+ self.wait_for_health()+ return self.backend.web_url++ def _reuse_existing_secret_key(self) -> None:+ """Adopt the SECRET_KEY the box already runs with (read from its override)+ so a deferred swap doesn't rotate it. Falls back to the freshly-minted+ key when the override can't be read — shouldn't happen post-bring_up, but+ a random key is a safe default either way."""+ r = self.backend.exec(+ f"sed -n 's/.*SECRET_KEY=//p' {self.repo_dir}/{self.OVERRIDE} 2>/dev/null | head -n1",+ timeout=60,+ )+ key = r.stdout.strip()+ if key:+ self.secret_key = key+# --- steps (each usable standalone, mirroring bin/hobby-ci.py) -----------def start_runtime(self) -> None:# Ensure docker is up before any compose command. The current golden is@@ -166,6 +209,7 @@ class PostHogPreviewStack:# flags "dubious ownership" — scope a safe.directory exception per# command. (The rest of the stack runs as root too, matching how the# golden's setup script built it.)+ timing.stage(f"in-box PR checkout ({branch})")safe = f"git -c safe.directory={self.repo_dir}"self.backend.run_long(f"cd {self.repo_dir} && {safe} fetch --depth 1 origin {branch} && {safe} checkout --force FETCH_HEAD",@@ -184,6 +228,7 @@ class PostHogPreviewStack:# recreate warm and serving the frontend relative (JS_URL=""), not# removing it. Keeping the env constant means web only ever recreates# for the mount, never for config drift.+ timing.stage("write compose override (backend mount)")lines = ["# Generated by tools/hogbox-preview.", "services:", " web:"]if self.image:lines.append(f" image: {self.image}")@@ -264,6 +309,7 @@ class PostHogPreviewStack:# Start the dependency services and wait for postgres to report healthy# before migrating. Idempotent: on a restored golden whose stack is# already running, `up` is a no-op for already-current containers.+ timing.stage("start dependency services")services = " ".join(self.DEPS)script = (f"cd {self.repo_dir} && docker compose -f {self.COMPOSE} -f {self.OVERRIDE} up -d --no-build {services} && "@@ -277,12 +323,14 @@ class PostHogPreviewStack:def up_web(self) -> None:# Clean `up` (never `restart` — Unit-listener gotcha). --no-build reuses# the pulled image; the override mounts PR source over its /code.+ timing.stage("start web container")self.backend.run_long(self._compose("up -d --no-build web"), name="up-web", timeout=900)def migrate(self) -> None:# PostHog needs both: Postgres (schema) and ClickHouse (events DB +# tables). ClickHouse must be migrated before demo-data generation,# which writes events to it.+ timing.stage("migrate start (postgres + clickhouse)")self.backend.run_long(self._compose("run --rm -T web python manage.py migrate --noinput"),name="migrate",@@ -293,11 +341,13 @@ class PostHogPreviewStack:name="migrate-clickhouse",timeout=1800,)+ timing.stage("migrate done")def generate_demo_data(self) -> None:# Same command hobby-ci uses (bin/hobby-ci.py). Seeds a demo org + the# [email protected] / 12345678 login so the preview opens populated.# (`manage.py n` is a dev-only alias, not registered in this image.)+ timing.stage("seed demo data")self.backend.run_long(self._compose("run --rm -T web python manage.py generate_demo_data"),name="seed",@@ -316,6 +366,7 @@ class PostHogPreviewStack:# so settings import is fine; collectstatic itself needs no live DB.import pathlib+ timing.stage("frontend swap start (upload dist)")tar = pathlib.Path(self.frontend_dist_tar).read_bytes()self.backend.write_file(f"{self.repo_dir}/frontend/dist.tgz", tar)compose = f"docker compose -f {self.COMPOSE} -f {self.OVERRIDE}"@@ -330,6 +381,7 @@ class PostHogPreviewStack:"web python manage.py collectstatic --noinput")self.backend.run_long(script, name="frontend", timeout=900)+ timing.stage("frontend swap done (collectstatic done)")def wait_for_health(self) -> None:# Do NOT `restart web` with the pinned image: Nginx Unit binds its :8000@@ -337,7 +389,9 @@ class PostHogPreviewStack:# a restart skips it and leaves `listeners: {}`, so nothing serves.# up_services already brought web up cleanly — just wait for it to serve.# Django is a heavy import; first health can take ~7 min.+ timing.stage("health poll start")self.backend.wait_http_ok("/_health", expect=200, timeout=900)+ timing.stage("health poll pass")# --- internal ------------------------------------------------------------def _compose(self, args: str) -> str:diff --git a/tools/hogbox-preview/hogbox_preview/timing.py b/tools/hogbox-preview/hogbox_preview/timing.pynew file mode 100644index 000000000000..2f9e42edfcc7--- /dev/null+++ b/tools/hogbox-preview/hogbox_preview/timing.py@@ -0,0 +1,31 @@+"""Lightweight stage timing for the preview bring-up.++The bring-up (and the deferred frontend swap) is a single multi-minute tool+invocation whose STDOUT is a strict ``url=``/``box_id=`` contract the workflow+parses — so progress can't go there. Without any output the CI log shows a+~6-minute void between the step start and ``url=``, which makes it impossible to+tell where the time actually goes. These helpers print+``[hogbox-preview +NNNs] <stage>`` breadcrumbs to STDERR at each major phase+boundary instead: per-stage visibility for free, no new dependency, and the+stdout contract stays untouched.++Elapsed is whole seconds since the tool started, measured with+``time.monotonic()`` so it's immune to wall-clock jumps and needs no formatting+library.+"""++from __future__ import annotations++import sys+import time++# Captured at import (process start) so every stage line is relative to the same+# t0 across both the backend (pen/restore) and the stack (checkout/migrate/...).+_START = time.monotonic()+++def stage(message: str) -> None:+ """Emit one ``[hogbox-preview +NNNs] <message>`` line to STDERR."""+ elapsed = int(time.monotonic() - _START)+ sys.stderr.write(f"[hogbox-preview +{elapsed}s] {message}\n")+ sys.stderr.flush()diff --git a/tools/hogbox-preview/tests/test_swap_frontend.py b/tools/hogbox-preview/tests/test_swap_frontend.pynew file mode 100644index 000000000000..d350de032204--- /dev/null+++ b/tools/hogbox-preview/tests/test_swap_frontend.py@@ -0,0 +1,192 @@+"""Unit tests for the deferred frontend swap (parallel CI flow).++Self-contained: no network, no live box. Two seams are covered:++ - ``PostHogPreviewStack.swap_frontend_only`` — the stack half: attach to the+ already-up box, adopt its existing SECRET_KEY (don't rotate), rewrite the+ override WITH the frontend mounts, lay the dist in, recreate web, wait for+ health. A recording fake backend captures every call.+ - ``HoglandBackend.attach`` — the backend half: resolve the EXISTING box via+ the pen's pointer and NEVER call create()/restore.++Guarded on the SDK import (pulled per-run via ``uv run --with``), same as the+sibling tests.++ cd tools/hogbox-preview && python -m unittest discover tests+"""++from __future__ import annotations++import gzip+import pathlib+import tempfile++import unittest++try:+ from hogbox_preview.backend import ExecResult+ from hogbox_preview.stack import PostHogPreviewStack++ HAVE_SDK = True+except ImportError:+ HAVE_SDK = False+++_EXISTING_KEY = "a" * 64 # the SECRET_KEY the box already runs with, from bring_up+++class _RecordingBackend:+ """Duck-typed PreviewBackend for the swap path. Records the calls the stack+ makes so we can assert ordering, the override contents, and the dist upload —+ without a real box."""++ def __init__(self):+ self.files: dict[str, bytes | str] = {}+ self.long_runs: list[str] = []+ self.attached = False+ self.health_waited = False++ def attach(self) -> None:+ self.attached = True++ def exec(self, command, *, timeout: int = 120) -> ExecResult:+ # The only exec the swap path issues is reading the existing SECRET_KEY+ # out of the override — hand back the key the box already uses.+ if "SECRET_KEY=" in command:+ return ExecResult(0, _EXISTING_KEY + "\n", "")+ return ExecResult(0, "", "")++ def write_file(self, remote_path, content) -> None:+ self.files[remote_path] = content++ def run_long(self, script, *, name, timeout: int = 1800, interval: int = 3) -> ExecResult:+ self.long_runs.append(name)+ return ExecResult(0, "", "")++ def wait_http_ok(self, url_path, *, expect=200, timeout=600, interval=3) -> None:+ self.health_waited = True++ @property+ def web_url(self) -> str:+ return "https://pen-deadbeef.boxes.hogland.prod-us.posthog.dev"++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class SwapFrontendOnlyTest(unittest.TestCase):+ def _dist_tar(self) -> str:+ # swap_frontend reads the tar off disk, so hand it a real (tiny) file.+ fd = tempfile.NamedTemporaryFile(suffix=".tgz", delete=False)+ fd.write(gzip.compress(b"not-a-real-tar-but-bytes-are-enough"))+ fd.close()+ self.addCleanup(lambda: pathlib.Path(fd.name).unlink(missing_ok=True))+ return fd.name++ def test_swap_attaches_reuses_key_and_serves_pr_frontend(self):+ backend = _RecordingBackend()+ stack = PostHogPreviewStack(backend, frontend_dist_tar=self._dist_tar())+ # The stack minted a fresh random key at construction; the swap must+ # DROP it in favour of the box's existing one.+ self.assertNotEqual(stack.secret_key, _EXISTING_KEY)++ url = stack.swap_frontend_only()++ # Attached to the live box, never provisioned a fresh one.+ self.assertTrue(backend.attached)+ # Adopted the box's existing SECRET_KEY rather than rotating it.+ self.assertEqual(stack.secret_key, _EXISTING_KEY)++ override = backend.files[f"{stack.repo_dir}/{stack.OVERRIDE}"]+ # The override now carries the frontend mounts (absent on the no-dist up).+ self.assertIn("./frontend/dist:/code/frontend/dist", override)+ self.assertIn("./staticfiles:/code/staticfiles", override)+ # ...and the reused key, so recreating web doesn't invalidate seeded data.+ self.assertIn(f"SECRET_KEY={_EXISTING_KEY}", override)++ # Ran the swap (collectstatic) then recreated web, then waited for health.+ self.assertEqual(backend.long_runs, ["frontend", "up-web"])+ self.assertTrue(backend.health_waited)+ self.assertEqual(url, backend.web_url)++ def test_swap_requires_a_dist(self):+ backend = _RecordingBackend()+ stack = PostHogPreviewStack(backend) # no frontend_dist_tar+ with self.assertRaises(RuntimeError):+ stack.swap_frontend_only()+ self.assertFalse(backend.attached)+++class _FakePen:+ def __init__(self, current_box_id):+ self.current_box_id = current_box_id+ self.id = "pen-deadbeef"+++class _FakeBox:+ def __init__(self, box_id):+ self.id = box_id++ def exec(self, argv, *, timeout_seconds=20, env=None):+ class _R:+ exit_code = 0+ stdout = ""+ stderr = ""++ return _R()+++class _NoCreateClient:+ """SDK stand-in whose create() blows up — attach must never restore."""++ def __init__(self, *, pen, box):+ self._pen = pen+ self._box = box++ def get_pen(self, name):+ return self._pen++ def get(self, box_id):+ return self._box++ def create(self, **kwargs):+ raise AssertionError("attach() must not restore a new box")++ def iter_boxes(self):+ return iter([])++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class AttachResolvesExistingBoxTest(unittest.TestCase):+ def test_attach_binds_pen_pointer_without_restoring(self):+ from hogbox_preview.hogland_backend import HoglandBackend++ box = _FakeBox("box-live")+ client = _NoCreateClient(pen=_FakePen(current_box_id="box-live"), box=box)+ backend = HoglandBackend(host="https://example.invalid", name="preview-pr-42", token="test-token")+ backend._client = client++ backend.attach()++ self.assertIs(backend._box, box)+ self.assertEqual(backend._box_id, "box-live")+ self.assertIsNotNone(backend._pen)++ def test_attach_raises_when_no_box_is_live(self):+ from hogbox_preview.hogland_backend import HoglandBackend+ from hogland import NotFoundError++ class _EmptyClient:+ def get_pen(self, name):+ raise NotFoundError("no pen", status_code=404)++ def iter_boxes(self):+ return iter([])++ backend = HoglandBackend(host="https://example.invalid", name="preview-pr-42", token="test-token")+ backend._client = _EmptyClient()++ with self.assertRaises(RuntimeError):+ backend.attach()+++if __name__ == "__main__":+ unittest.main()