: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
feat(devex): per-PR PostHog preview environments on hogland hogboxes (#62672)
Julian Bez4f43b2061268
diff --git a/.github/workflows/hogbox-preview-cleanup.yml b/.github/workflows/hogbox-preview-cleanup.ymlnew file mode 100644index 000000000000..9b41ad1e5bf3--- /dev/null+++ b/.github/workflows/hogbox-preview-cleanup.yml@@ -0,0 +1,69 @@+name: Hogbox Preview Cleanup++# Daily backstop sweep: destroy hogbox previews (box + pen) whose PR has closed+# but whose fast-path teardown didn't fire or failed — that fast path is+# pr-closed.yml (on close) and the label-removal job in hogbox-preview-env.yml.+#+# Why its own file and not a job in pr-cleanup.yml (where hobby's stale-sweep+# lives): pr-cleanup.yml is a *reusable* workflow — pr-closed.yml calls it with+# only `deployments: write`. A job that mints a hogland OIDC token needs+# `id-token: write`, which exceeds that capped call and fails the caller's run at+# startup. So the hogbox sweep lives here, on its own triggers, where it can hold+# the permission it needs.++on:+ schedule:+ # Daily at 03:15 UTC (staggered just after pr-cleanup.yml's 03:00 sweep).+ - cron: '15 3 * * *'+ workflow_dispatch:+ inputs:+ dry_run:+ description: 'Dry run (list closed-PR previews, destroy nothing)'+ type: boolean+ default: true++permissions:+ contents: read+ id-token: write # OIDC for the tailnet join + hogplane token++env:+ HOG_HOST: https://hogland.hedgehog-kitefin.ts.net+ HOG_OIDC_AUDIENCE: hogland.prod-us.posthog.dev++jobs:+ cleanup-hogbox-preview:+ name: Reap stale hogbox previews+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ steps:+ # Pin to the default branch: the sweep runs the tool with the hogland+ # token, and a workflow_dispatch from a non-master ref would otherwise+ # run that ref's tool code in credential scope — same rule as every+ # other credentialed job in this family.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.event.repository.default_branch }}+ - name: Connect to Tailscale (tag:hogland-ci)+ uses: tailscale/github-action@306e68a486fd2350f2bfc3b19fcd143891a4a2d8 # v4.1.2+ with:+ oauth-client-id: ${{ vars.TS_HOGLAND_CI_CLIENT_ID }}+ audience: ${{ vars.TS_HOGLAND_CI_AUDIENCE }}+ tags: tag:hogland-ci+ - name: Mint hogland OIDC token+ run: |+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value')+ echo "::add-mask::$token"+ echo "HOG_TOKEN=$token" >> "$GITHUB_ENV"+ # uv (repo convention): --no-project skips the monorepo sync, --with+ # pins the first-party SDK (exempted from the 7-day soak in [tool.uv]).+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit+ - name: Reap previews for closed PRs+ working-directory: tools/hogbox-preview+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ GITHUB_REPOSITORY: ${{ github.repository }}+ DRY_RUN: ${{ inputs.dry_run || 'false' }}+ run: uv run --no-project --with posthog-hogland==0.3.0 --python 3.12 python -m hogbox_preview --host "$HOG_HOST" cleanup-stalediff --git a/.github/workflows/hogbox-preview-env.yml b/.github/workflows/hogbox-preview-env.ymlnew file mode 100644index 000000000000..ae9ad9a782cd--- /dev/null+++ b/.github/workflows/hogbox-preview-env.yml@@ -0,0 +1,599 @@+# Hogbox Preview Environment (per-PR PostHog on a hogland hogbox)+#+# Restores the pre-baked "preview golden" snapshot (PostHog already migrated ++# seeded on the :master image), mounts the PR's backend source over the image's+# /code, builds the PR's frontend, runs the delta migrations, and posts the+# reachable URL on the PR (sticky comment + a GitHub Deployment).+#+# This drives tools/hogbox-preview — the layer (hogland) is swappable; the stack+# recipe is not. See tools/hogbox-preview/README.md.+#+# --- WHY MOUNT (not build / not a per-PR image) ---------------------------------+# The golden is baked ONCE (a hogland-side setup script: docker pull+# ghcr.io/posthog/posthog:master, migrate pg+CH, seed demo data), so its DB is+# already migrated AND seeded on the master image. A per-PR run restores that,+# bind-mounts the PR's checkout (posthog/ee/products) over the image's /code so+# 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.+#+# --- TRIGGER (who gets a preview) -----------------------------------------------+# The `decide` job (cheap, credential-free) is the gate. A same-repo, human,+# ready (non-draft) PR gets a preview when it carries the `hogbox-preview` label+# (manual opt-in, ANY paths) OR its diff touches the frontend (frontend/**,+# products/*/frontend/**, common/esbuilder/**). The `no-preview` label opts out.+# Auto-previews for frontend PRs are org-visible default behavior; the opt-out ++# hibernation (below) keep them cheap. See the trigger notes on `on.pull_request`.+#+# --- 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.+# - 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.+# - teardown fast path: the `teardown` job below fires when `hogbox-preview` is+# removed OR `no-preview` is added (the cron is the backstop); it also marks+# the Deployment inactive and flips the sticky comment.+#+# --- PREREQS (tracked out of band) ----------------------------------------------+# - vars.TS_HOGLAND_CI_CLIENT_ID / TS_HOGLAND_CI_AUDIENCE (tailnet join)+# - the golden is referenced by its global alias `posthog-preview-golden`+# - target hogland deploy has HOG_GITHUB_OIDC_AUDIENCE + a github_oidc+# TrustMapping for PostHog/posthog on prod-us+# - frontend PRs auto-preview; `hogbox-preview` forces it for any paths,+# `no-preview` opts out (see the TRIGGER section above)+# The box is driven entirely by the posthog-hogland SDK (pip-installable, keyless+# over hogplane's HTTP API) — no `hogland` CLI binary and no box SSH key needed.++name: Hogbox Preview Environment++on:+ pull_request:+ # Broad on purpose — the eligibility decision CANNOT live in an+ # `on.pull_request.paths` filter: that would kill the label-only path for+ # backend PRs (a labeled PR gets a preview for ANY paths). So the trigger+ # fires for every PR event of these types and the `decide` job below is the+ # real gate (see 2a in README). `ready_for_review` is included so a+ # draft→ready flip creates the preview; `labeled`/`unlabeled` drive both+ # the manual `hogbox-preview` opt-in and the `no-preview` opt-out.+ types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]+ workflow_dispatch:+ inputs:+ pr_number:+ description: PR number to (re)build a preview for+ required: true++# NOTE: there is deliberately NO workflow-level `concurrency` here. The workflow+# fires on `unlabeled` (a no-op teardown-irrelevant label removal still starts a+# run), and a workflow-level `cancel-in-progress` would let such an unrelated run+# cancel an in-flight preview BUILD for the same PR. Instead the cancelable+# concurrency lives on the `preview`/`teardown` jobs (keyed on PR number), which+# only run once eligibility is decided — so a no-op run never enters the group+# and never cancels anything. See 2b in README.++# Least privilege at the workflow level; each job asks for exactly what it+# needs. Crucially `id-token: write` lives ONLY on jobs that never execute+# PR-controlled code (deploy/teardown, which check out the DEFAULT branch) —+# with it on a job, $ACTIONS_ID_TOKEN_REQUEST_TOKEN is ambient in EVERY step,+# so a job that runs the PR's pnpm lifecycle/build scripts could mint a+# hogland-audience token no matter how late our own mint step runs.+permissions:+ contents: read++env:+ # prod-us: the golden lives here and the box edge is live here.+ HOG_HOST: https://hogland.hedgehog-kitefin.ts.net+ HOG_OIDC_AUDIENCE: hogland.prod-us.posthog.dev+ PR: ${{ github.event.pull_request.number || github.event.inputs.pr_number }}++jobs:+ # ----------------------------------------------------------------------------+ # Cheap, credential-free gate. Runs on EVERY event (github-script only, no+ # checkout, no tailnet, no token) and decides — from the PR's labels, author,+ # draft state and diff — whether to build a preview, tear one down, or do+ # nothing. Keeping it separate + non-cancelable is what dodges the+ # unlabeled-cancel trap: a no-op event runs only this job, never touches the+ # `preview`/`teardown` concurrency group, so it can't cancel an active build.+ decide:+ name: decide eligibility+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ permissions:+ contents: read+ pull-requests: read # read labels + list changed files; no write, no token+ outputs:+ build: ${{ steps.decide.outputs.build }}+ teardown: ${{ steps.decide.outputs.teardown }}+ steps:+ - name: Decide build vs teardown vs skip+ id: decide+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const base = `${context.repo.owner}/${context.repo.repo}`;+ const event = context.eventName;+ const action = context.payload.action;+ const decide = (build, teardown, why) => {+ core.info(why);+ core.setOutput('build', build ? 'true' : 'false');+ core.setOutput('teardown', teardown ? 'true' : 'false');+ };++ // Manual dispatch is an explicit act by someone with Actions+ // write — always attempt a build. The preview job's fork guard+ // is the security gate for a dispatched fork number.+ if (event === 'workflow_dispatch') {+ return decide(true, false, 'workflow_dispatch → build');+ }++ const pr = context.payload.pull_request;+ const label = context.payload.label && context.payload.label.name;++ // Teardown fast paths (idempotent — a no-op if nothing is up):+ // removing `hogbox-preview` keeps its existing teardown+ // semantics; adding the `no-preview` opt-out tears a live+ // preview down the same way.+ if (action === 'unlabeled' && label === 'hogbox-preview') {+ return decide(false, true, 'hogbox-preview removed → tear down');+ }+ if (action === 'labeled' && label === 'no-preview') {+ return decide(false, true, 'no-preview opt-out added → tear down');+ }++ // Most label toggles don't change build intent — only two do:+ // `hogbox-preview` ADDED (manual opt-in) and `no-preview`+ // REMOVED (opt-out lifted). Any other labeled/unlabeled is a+ // no-op, skipped WITHOUT an API call so a busy PR's unrelated+ // label churn never queues a ~10-min rebuild. Code pushes+ // (synchronize) are what rebuild on change.+ const buildRelevantLabel =+ (action === 'labeled' && label === 'hogbox-preview') ||+ (action === 'unlabeled' && label === 'no-preview');+ if ((action === 'labeled' || action === 'unlabeled') && !buildRelevantLabel) {+ return decide(false, false, `label ${action} '${label}' — not preview-relevant → skip`);+ }++ // Build eligibility: same-repo AND human AND ready AND not+ // opted-out AND (labeled OR frontend-touching).+ const labels = (pr.labels || []).map(l => l.name);+ const hasPreviewLabel = labels.includes('hogbox-preview');+ const optedOut = labels.includes('no-preview');+ const sameRepo = (pr.head && pr.head.repo && pr.head.repo.full_name) === base;+ const login = (pr.user && pr.user.login) || '';+ const isBot = (pr.user && pr.user.type) === 'Bot'+ || /\[bot\]$/i.test(login)+ || /^(dependabot|renovate|github-actions|snyk-bot|posthog-bot|mendral-app|greptileai|coderabbitai|sentry-io)\b/i.test(login);+ const ready = pr.draft === false;++ if (!sameRepo) return decide(false, false, `fork PR (${pr.head && pr.head.repo && pr.head.repo.full_name}) → skip`);+ if (isBot) return decide(false, false, `bot author (${login}) → skip`);+ if (!ready) return decide(false, false, 'draft PR → skip');+ if (optedOut) return decide(false, false, 'no-preview label present → skip');++ // The manual label opts a PR in for ANY paths; without it we+ // require a frontend-touching diff. Only pay for the files+ // list when there's no label (short-circuit the API call).+ let frontend = false;+ if (!hasPreviewLabel) {+ const files = await github.paginate(github.rest.pulls.listFiles,+ { ...context.repo, pull_number: pr.number, per_page: 100 });+ const fe = /^frontend\/|^products\/[^/]+\/frontend\/|^common\/esbuilder\//;+ frontend = files.some(f => fe.test(f.filename));+ core.info(`frontend-touching: ${frontend}`);+ }+ const build = hasPreviewLabel || frontend;+ return decide(build, false, build+ ? `eligible (label=${hasPreviewLabel}, frontend=${frontend}) → build`+ : 'no hogbox-preview label and no frontend changes → skip');++ # ----------------------------------------------------------------------------+ # Trusted, tiny, no-checkout: open a GitHub Deployment (in_progress) and the+ # sticky "building…" comment immediately, so the PR shows activity before the+ # multi-minute build + bring-up finishes. Runs github-script only — no PR+ # code — which is why it may hold write perms. Deliberately OUTSIDE the+ # per-PR concurrency group: announcing must never cancel an in-flight+ # deploy; build-frontend/deploy below do the coalescing.+ announce:+ name: announce build+ needs: decide+ if: needs.decide.outputs.build == 'true'+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ permissions:+ contents: read+ pull-requests: write # sticky preview comment+ deployments: write # GitHub Deployment for the PR's Environments UI+ outputs:+ sha: ${{ steps.start.outputs.sha }}+ deployment_id: ${{ steps.start.outputs.deployment_id }}+ steps:+ - name: Announce (deployment + building comment)+ id: start+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const pr = Number(process.env.PR);+ let sha = context.payload.pull_request?.head?.sha;+ if (!sha) {+ const { data } = await github.rest.pulls.get({ ...context.repo, pull_number: pr });+ sha = data.head.sha;+ }+ core.setOutput('sha', sha);+ const environment = `preview-pr-${pr}`;+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;+ const dep = await github.rest.repos.createDeployment({+ ...context.repo, ref: sha, environment, auto_merge: false,+ required_contexts: [], transient_environment: true, description: 'Hogbox preview',+ });+ core.setOutput('deployment_id', String(dep.data.id));+ await github.rest.repos.createDeploymentStatus({+ ...context.repo, deployment_id: dep.data.id, state: 'in_progress',+ environment, log_url: runUrl, description: 'Building preview…',+ });+ 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` ++ `<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));+ if (ex) await github.rest.issues.updateComment({ ...context.repo, comment_id: ex.id, body });+ else await github.rest.issues.createComment({ ...context.repo, issue_number: pr, body });++ # ----------------------------------------------------------------------------+ # UNTRUSTED build: checks out the PR and runs its pnpm lifecycle + turbo+ # build scripts. Deliberately powerless — read-only GITHUB_TOKEN, NO+ # id-token, no tailnet — so PR-controlled code can't mint a hogland-audience+ # 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.+ build-frontend:+ name: build PR frontend+ needs: decide+ if: needs.decide.outputs.build == 'true'+ concurrency:+ group: hogbox-preview-${{ github.event.pull_request.number || github.event.inputs.pr_number }}+ cancel-in-progress: true+ runs-on: ubuntu-24.04+ timeout-minutes: 30+ permissions:+ contents: read+ pull-requests: read # list changed files (FE detection) + resolve dispatched PR numbers+ outputs:+ fe_changed: ${{ steps.fe.outputs.changed }}+ 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+ # the tailnet + a minted hogland token in scope. The `pull_request`+ # path is same-repo-gated in the `decide` job, but a dispatched number+ # is not — dispatching a FORK PR's number would run fork code against+ # real credentials. So resolve the PR via the API and hard-fail unless+ # its head lives in this repo (never a fork). Runs first, before any+ # checkout / credential mint, so a fork number dies 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.`);+ }++ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2++ # --- Frontend: only build it when the PR actually touches it --------+ # The golden serves the :master SPA; mounting the backend doesn't+ # change the frontend. So for FE-touching PRs, build the PR's+ # frontend here (the canonical Dockerfile build) and hand the dist to+ # the tool, which lays it in + re-runs collectstatic in-box. Non-FE+ # PRs skip all of this and keep the ~1-min preview.+ - name: Detect frontend changes+ id: fe+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const pr = Number(process.env.PR);+ const files = await github.paginate(github.rest.pulls.listFiles, { ...context.repo, pull_number: pr, per_page: 100 });+ // Rebuild the FE for anything that feeds the frontend build:+ // app code, shared workspace packages (common/*, packages/*),+ // and the root manifests/lockfile that pin the build graph.+ const changed = files.some(f =>+ f.filename.startsWith('frontend/') ||+ f.filename.includes('/frontend/') ||+ f.filename.startsWith('common/') ||+ f.filename.startsWith('packages/') ||+ f.filename === 'package.json' ||+ f.filename === 'pnpm-lock.yaml' ||+ f.filename === 'pnpm-workspace.yaml');+ core.info(`frontend changed in PR #${pr}: ${changed}`);+ core.setOutput('changed', changed ? 'true' : 'false');++ # The repo's composite handles pnpm + Node (.nvmrc) + cache, and keeps+ # the cache keyed to the default branch (the lint-workflows rule bans a+ # raw setup-node `cache: pnpm` here).+ - name: Install frontend deps+ if: steps.fe.outputs.changed == 'true'+ uses: ./.github/actions/pnpm-install+ with:+ install-command: pnpm --filter=@posthog/frontend... install --frozen-lockfile+ - name: Build the PR frontend+ if: steps.fe.outputs.changed == 'true'+ env:+ NODE_OPTIONS: --max-old-space-size=6144+ run: |+ bin/turbo --filter=@posthog/frontend build+ pnpm build:products+ tar czf "$RUNNER_TEMP/frontend-dist.tgz" -C frontend dist++ # The artifact is the ONLY thing that crosses the trust boundary into+ # the deploy job — a tarball of built assets, consumed as data.+ - name: Upload frontend dist+ if: steps.fe.outputs.changed == 'true'+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0+ with:+ name: hogbox-preview-frontend-dist+ path: ${{ runner.temp }}/frontend-dist.tgz+ retention-days: 1++ # ----------------------------------------------------------------------------+ # TRUSTED deploy: the only job that holds hogland credentials (id-token →+ # tailnet + HOG_TOKEN). It checks out the DEFAULT branch — never the PR — so+ # no PR-controlled code executes in credential scope (same reasoning as the+ # 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.+ 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).+ if: ${{ !cancelled() && needs.decide.outputs.build == 'true' }}+ concurrency:+ group: hogbox-preview-${{ github.event.pull_request.number || github.event.inputs.pr_number }}+ cancel-in-progress: true+ runs-on: ubuntu-24.04+ timeout-minutes: 40+ permissions:+ contents: read+ id-token: write # mint OIDC for the tailnet join AND the hogplane token+ pull-requests: write # sticky preview comment+ deployments: write # flip the Deployment to success/failure+ env:+ 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++ # Trusted checkout: the tool code that runs with HOG_TOKEN comes from+ # the default branch, never the PR.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ 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.2+ with:+ oauth-client-id: ${{ vars.TS_HOGLAND_CI_CLIENT_ID }}+ audience: ${{ vars.TS_HOGLAND_CI_AUDIENCE }}+ tags: tag:hogland-ci++ - name: Mint hogland OIDC token+ run: |+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value')+ [ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::OIDC mint failed"; exit 1; }+ echo "::add-mask::$token"+ echo "HOG_TOKEN=$token" >> "$GITHUB_ENV"++ # uv (repo convention) instead of pip — no separate install step.+ # --no-project skips the posthog monorepo (don't sync it); --with pins+ # the SDK into an ephemeral env. posthog-hogland is first-party and+ # exempted from the 7-day soak in [tool.uv].+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit++ - name: Bring up preview+ id: 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)+ out=$(uv run --no-project --with posthog-hogland==0.3.0 --python 3.12 \+ python -m hogbox_preview \+ --host "$HOG_HOST" \+ --name "preview-pr-${PR}" \+ --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")+ 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++ - name: Report ready (deployment + comment)+ if: success()+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ # SHA + DEP come from the job env (announce job outputs).+ env:+ URL: ${{ steps.build.outputs.url }}+ BOX: ${{ steps.build.outputs.box_id }}+ SECS: ${{ steps.build.outputs.secs }}+ 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}`;+ 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',+ });+ }+ 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` ++ `| 🔗 **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 · ` ++ `<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));+ if (ex) await github.rest.issues.updateComment({ ...context.repo, comment_id: ex.id, body });+ else await github.rest.issues.createComment({ ...context.repo, issue_number: pr, body });++ - name: Report failure (deployment + comment)+ if: failure()+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const pr = Number(process.env.PR);+ const environment = `preview-pr-${pr}`;+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;+ if (process.env.DEP) {+ await github.rest.repos.createDeploymentStatus({+ ...context.repo, deployment_id: Number(process.env.DEP), state: 'failure',+ environment, log_url: runUrl, description: 'Preview build failed',+ });+ }+ const marker = '<!-- hogbox-preview-comment -->';+ const body =+ `${marker}\n### 🦔 Hogbox preview · ❌ build failed\n\n` ++ `The preview didn't come up for commit \`${(process.env.SHA || '').slice(0, 7)}\`. ` ++ `See the **[build log](${runUrl})** for the failing step. It'll retry on the next push.`;+ const { data: comments } = await github.rest.issues.listComments({ ...context.repo, issue_number: pr });+ const ex = comments.find(c => c.body.includes(marker));+ if (ex) await github.rest.issues.updateComment({ ...context.repo, comment_id: ex.id, body });+ else await github.rest.issues.createComment({ ...context.repo, issue_number: pr, body });++ # ----------------------------------------------------------------------------+ # Fast-path teardown, decided by the `decide` job: either the `hogbox-preview`+ # label was removed (existing semantics) or the `no-preview` opt-out was added+ # to a PR with a live preview. Both destroy box + pen (idempotent — a no-op if+ # nothing is up). The daily stale-sweep in hogbox-preview-cleanup.yml is the+ # backstop; PR *close* teardown lives in pr-closed.yml.+ teardown:+ name: tear down preview+ needs: decide+ if: needs.decide.outputs.teardown == 'true'+ # Share the preview job's per-PR group so the latest intent wins: a+ # teardown cancels an in-flight build for the same PR (and vice-versa),+ # instead of a build finishing and re-posting a preview the user just+ # opted out of.+ concurrency:+ group: hogbox-preview-${{ github.event.pull_request.number || github.event.inputs.pr_number }}+ cancel-in-progress: true+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ permissions:+ contents: read+ id-token: write # tailnet join + hogland token — no PR code in this job+ pull-requests: write # flip the sticky comment to torn-down+ deployments: write # mark the preview Deployment inactive+ steps:+ # Teardown runs the tool with the hogland token, so check it out from+ # the trusted default branch, not the PR's (possibly modified) code —+ # same reasoning as pr-closed.yml's cleanup. Only a destroy call is+ # needed, so master's copy is correct.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.event.repository.default_branch }}+ - name: Connect to Tailscale (tag:hogland-ci)+ uses: tailscale/github-action@306e68a486fd2350f2bfc3b19fcd143891a4a2d8 # v4.1.2+ with:+ oauth-client-id: ${{ vars.TS_HOGLAND_CI_CLIENT_ID }}+ audience: ${{ vars.TS_HOGLAND_CI_AUDIENCE }}+ tags: tag:hogland-ci+ - name: Mint hogland OIDC token+ run: |+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value')+ echo "::add-mask::$token"; echo "HOG_TOKEN=$token" >> "$GITHUB_ENV"+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit+ - name: Destroy preview box + pen+ working-directory: tools/hogbox-preview+ run: uv run --no-project --with posthog-hogland==0.3.0 --python 3.12 python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-${PR}" destroy++ # Don't leave a green "ready" Deployment + comment pointing at a box+ # that no longer exists: mark every deployment of this PR's+ # environment inactive and flip the sticky comment. (The close path+ # gets the same treatment from pr-cleanup.yml's deployment reaper.)+ - name: Deactivate deployment + update comment+ if: always()+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const pr = Number(process.env.PR);+ const environment = `preview-pr-${pr}`;+ const deployments = await github.paginate(github.rest.repos.listDeployments,+ { ...context.repo, environment, per_page: 100 });+ for (const d of deployments) {+ await github.rest.repos.createDeploymentStatus({+ ...context.repo, deployment_id: d.id, state: 'inactive',+ environment, description: 'Preview torn down',+ });+ }+ const marker = '<!-- hogbox-preview-comment -->';+ const { data: comments } = await github.rest.issues.listComments({ ...context.repo, issue_number: pr });+ const ex = comments.find(c => c.body.includes(marker));+ if (ex) {+ const body =+ `${marker}\n### 🦔 Hogbox preview · 💤 torn down\n\n` ++ `The preview for this PR was torn down (label removed or \`no-preview\` added). ` ++ `Re-add the \`hogbox-preview\` label to bring it back.`;+ await github.rest.issues.updateComment({ ...context.repo, comment_id: ex.id, body });+ }diff --git a/.github/workflows/pr-closed.yml b/.github/workflows/pr-closed.ymlindex a96736c51d58..c23dd6ffc929 100644--- a/.github/workflows/pr-closed.yml+++ b/.github/workflows/pr-closed.yml@@ -24,6 +24,79 @@ jobs:CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}+ cleanup-hogbox-preview:+ name: Cleanup hogbox preview+ # Tear down the per-PR hogbox (box + pen) on close. The daily stale-sweep+ # in pr-cleanup.yml is the backstop; the GitHub Deployment/environment is+ # reaped there too. Idempotent — a no-op if nothing is up.+ #+ # Frontend PRs auto-preview WITHOUT the `hogbox-preview` label, so a+ # label-only gate here would leak their boxes until the daily sweep. The+ # job `if:` only prunes PRs that can't have had a preview at all (forks,+ # bots); the real gate is the credential-free deployment check below —+ # a preview always leaves a `preview-pr-<n>` GitHub Deployment behind.+ if: >-+ contains(github.event.pull_request.labels.*.name, 'hogbox-preview')+ || (github.event.pull_request.head.repo.full_name == github.repository+ && github.event.pull_request.user.type != 'Bot')+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ permissions:+ contents: read+ deployments: read # the had-a-preview gate lists the PR's deployments+ id-token: write # OIDC for the tailnet join + hogplane token+ env:+ HOG_HOST: https://hogland.hedgehog-kitefin.ts.net+ HOG_OIDC_AUDIENCE: hogland.prod-us.posthog.dev+ PR: ${{ github.event.pull_request.number }}+ steps:+ # Credential-free gate: only PRs that actually had a preview (labeled+ # or auto) proceed to the tailnet join + token mint below.+ - name: Check whether this PR had a preview+ id: gate+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0+ with:+ script: |+ const pr = Number(process.env.PR);+ const { data } = await github.rest.repos.listDeployments({+ ...context.repo, environment: `preview-pr-${pr}`, per_page: 1 });+ const had = data.length > 0;+ core.info(`preview deployment for PR #${pr}: ${had}`);+ core.setOutput('had_preview', had ? 'true' : 'false');+ # Run the teardown tool from the trusted default branch, never the PR's+ # code. On a `closed` event the default checkout can resolve to the PR+ # merge ref, which would execute PR-modified tools/hogbox-preview with+ # the hogland token below. Cleanup only needs the SDK + a destroy call,+ # so master's copy is correct and removes that exec vector.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ if: steps.gate.outputs.had_preview == 'true'+ with:+ ref: ${{ github.event.repository.default_branch }}+ - name: Connect to Tailscale (tag:hogland-ci)+ if: steps.gate.outputs.had_preview == 'true'+ uses: tailscale/github-action@306e68a486fd2350f2bfc3b19fcd143891a4a2d8 # v4.1.2+ with:+ oauth-client-id: ${{ vars.TS_HOGLAND_CI_CLIENT_ID }}+ audience: ${{ vars.TS_HOGLAND_CI_AUDIENCE }}+ tags: tag:hogland-ci+ - name: Mint hogland OIDC token+ if: steps.gate.outputs.had_preview == 'true'+ run: |+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value')+ echo "::add-mask::$token"+ echo "HOG_TOKEN=$token" >> "$GITHUB_ENV"+ # uv (repo convention): --no-project skips the monorepo sync, --with+ # pins the first-party SDK (exempted from the 7-day soak in [tool.uv]).+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ if: steps.gate.outputs.had_preview == 'true'+ with:+ version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit+ - name: Destroy preview box + pen+ if: steps.gate.outputs.had_preview == 'true'+ working-directory: tools/hogbox-preview+ run: uv run --no-project --with posthog-hogland==0.3.0 --python 3.12 python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-${PR}" destroy+disable-canary-flags:name: Disable feature flags canaryif: contains(github.event.pull_request.labels.*.name, 'canary-flags')diff --git a/pyproject.toml b/pyproject.tomlindex 442915d7f48c..8ef002a72187 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -290,7 +290,7 @@ hogql-parser-parity = [required-version = ">=0.10.2"add-bounds = "major"exclude-newer = "7 days"-exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, posthoganalytics = false, pixelhog = false, django = false, modal = false }+exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, posthoganalytics = false, pixelhog = false, django = false, modal = false, posthog-hogland = false }[tool.uv.workspace]members = ["tools/hogli"]diff --git a/tools/hogbox-preview/README.md b/tools/hogbox-preview/README.mdnew file mode 100644index 000000000000..502a86f46c52--- /dev/null+++ b/tools/hogbox-preview/README.md@@ -0,0 +1,149 @@+# hogbox-preview++Per-PR PostHog preview environments, the layer-agnostic way.++Spins PostHog up inside a disposable box and serves it at a **stable URL** that+survives the box being recreated. Today the box is a+[hogland](https://github.com/PostHog/hogland) hogbox (Firecracker microVM,+reachable over the tailnet). It used to be a DigitalOcean droplet+(`bin/hobby-ci.py`), and it may be something else next.++## The one idea: layer vs stack++The thing that changes when we swap providers is small and isolated:++- **Layer** (`backend.py`, `*_backend.py`) — _which box_: how to provision it,+ how to run commands / write files in it, what its URL is, how to destroy it.+ Swapping providers = one new `PreviewBackend`.+- **Stack** (`stack.py`) — _what runs in the box_: the PostHog docker-compose+ recipe (image, override, frontend, migrate, seed, health). It talks to the box+ only through the backend interface and **never changes when the layer changes**.++```python+from hogbox_preview import HoglandBackend, PostHogPreviewStack++backend = HoglandBackend(host="https://hogland.hedgehog-kitefin.ts.net", name="preview-pr-123")+url = PostHogPreviewStack(backend, branch="pull/123/head").bring_up()+print(url) # https://pen-….boxes.hogland.prod-us.posthog.dev/ (stable across rebuilds)+```++## How it actually works++1. **Restore a warm golden** (`alias:posthog-preview-golden`) — a Firecracker+ snapshot of PostHog already running on the `ghcr.io/posthog/posthog:master`+ image, pg + ClickHouse migrated, demo-data seeded. A warm restore resumes a+ live, serving PostHog in ~30s (no cold boot, no rebuild). Sizing must match+ the 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.+4. **Delta-migrate** — only the PR's _unapplied_ migrations on top of the seeded+ DB (`--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.++Driven entirely by the **`posthog-hogland` Python SDK** over hogplane's HTTP API+— **keyless** (GitHub OIDC → hogplane token over the tailnet), no `hogland` CLI+binary and no box SSH key.++## Pens: the stable URL++The box behind a preview rotates (a fresh restore per push), so the tool keys a+**pen** (hogland's stable identity, `docs/PENS.md` there) on the deterministic+name `preview-pr-<n>`: get-or-create the pen, restore a fresh box, PATCH+`current_box_id`. The posted URL is `https://<pen-id>.<edge>/`, which hogland's+box-http edge resolves to whatever box currently backs the pen — so **a+reviewer's link survives every re-push** (the box swaps underneath). Requires+hogland's pen-id edge routing (shipped in hogland #319).++## Auto-previews & opt-out++Frontend PRs get a preview **automatically** — no label needed. A cheap,+credential-free `decide` job in `hogbox-preview-env.yml` gates every PR event and+builds a preview when **all** hold:++- the PR is **same-repo** (fork PRs never get one — they'd run fork code with the+ hogland token in scope),+- the author is a **human** (bots — `user.type == 'Bot'`, `…[bot]`, and the usual+ suspects like dependabot/renovate — are skipped),+- the PR is **ready** (not draft; flipping draft→ready builds it),+- it does **not** carry the **`no-preview`** opt-out label, and+- it either carries the **`hogbox-preview`** label (manual opt-in, works for **any**+ paths) **or** its diff touches the frontend (`frontend/**`,+ `products/*/frontend/**`, `common/esbuilder/**`).++Two labels, two escape hatches: **`hogbox-preview`** forces a preview on a PR that+wouldn't auto-qualify (e.g. a backend-only change you want to click through);+**`no-preview`** suppresses one on a PR that would (and tears down a live one).++Why a `decide` job and not an `on.pull_request.paths` filter: a path filter would+kill the label-only path for backend PRs, so the trigger stays broad and+eligibility is decided in a job step. Rapid pushes coalesce via a per-PR+`concurrency` group on the build job (cancel-in-progress) — a busy PR (p90 ~17+pushes) rebuilds once for the latest commit, not 17 times. The group is job-level+and keyed on PR number only, so an unrelated label removal can't cancel an active+build.++## Reporting & lifecycle++- **PR comment** — a sticky comment (`<!-- hogbox-preview-comment -->`) staged+ building → ready → failed, with the URL, login, and what's running.+- **GitHub Deployment** — a `preview-pr-<n>` environment (in_progress → success+ /failure + URL), so the preview shows in the PR's Deployments UI.+- **Teardown** — on PR close (`pr-closed.yml`) + on the fast path in+ `hogbox-preview-env.yml`: removing `hogbox-preview` **or** adding `no-preview`+ destroys box + pen. A daily stale-sweep (`cleanup-stale`) in+ `hogbox-preview-cleanup.yml` reaps previews whose PR closed but slipped+ through — its own workflow because the OIDC mint needs `id-token: write`, which+ can't live in the reusable `pr-cleanup.yml`.++## Hibernation & wake (why autos are affordable)++Every preview pen is created with `on_idle=hibernate` + `wake=on-request` (both+re-asserted on each push). After ~30 min idle (the `--ttl-seconds` window),+hogland's reaper **snapshots the box to S3 and deletes it** — zero node cost while+nobody's looking. The **stable URL stays live**: the next visit hits the box-front+edge, which sees a hibernated wake-on-request pen and serves a brief **"waking+up" interstitial** (a polling page for browser navigations, a retry-503 for+XHR/asset clients) while it restores the box (~30–40s, a warm restore of the ready+stack) and repoints the pen. Actively-viewed previews stay awake — edge traffic+touches the box, so only a genuinely idle one sleeps. This hibernate/wake cycle is+what makes fleet-wide auto-previews (peak ~85–115 concurrently open) affordable+(~7–10× vs always-on). See hogland's `docs/PENS.md`.++Access is **tailnet-only** (PostHog VPN) — internal reviewers, no public URL.++## CLI++Pure stdlib + the SDK; run with `uv run` or plain `python`. Subcommands mirror+`bin/hobby-ci.py` so it drops into the same CI shape.++```bash+cd tools/hogbox-preview++# one-shot: provision (pen + box) + bring PostHog up, print the URL+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]++# granular / staged (reuse a box):+python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-$PR" create+python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-$PR" health+python -m hogbox_preview --host "$HOG_HOST" --name "preview-pr-$PR" destroy # box + pen++# cron backstop: reap previews whose PR is closed (needs GITHUB_REPOSITORY + GH_TOKEN)+python -m hogbox_preview --host "$HOG_HOST" cleanup-stale+```++## The golden (and why it's fast)++The image-pull + full migrate is a one-time cost baked into the golden, not paid+per-PR. The golden is built on the **hogland** side by `scripts/posthog-preview-setup.sh`+via `snapshot-build` (a cold-boot seed — **never** `box snapshot` of a restored+box, which bakes the source TAP name and won't re-restore) and is left **warm**+(stack running) so restores resume a serving PostHog. It bakes `JS_URL=""` ++wildcard CSRF so any box's edge URL serves without a per-box rewrite. The DB+travels with the image it was migrated by — don't reuse a stale golden DB against+a newer image; re-bake instead. Timing details + the warm-vs-cold analysis live+in `STARTUP.md` and hogland's `docs/CHUNKFS_RESTORE_PERFORMANCE.md`.diff --git a/tools/hogbox-preview/STARTUP.md b/tools/hogbox-preview/STARTUP.mdnew file mode 100644index 000000000000..631e2a985543--- /dev/null+++ b/tools/hogbox-preview/STARTUP.md@@ -0,0 +1,172 @@+# Preview bring-up startup profiling++Why a per-PR preview takes a while to come up on a hogland hogbox, where the+time actually goes, and the levers that shrink it. Profiled 2026-06-15 against+prod-us, golden `snap-085a84dd47cd` (8 vCPU / 16 GiB / 100 GiB mirrored).++## Cold baseline: restore → `/_health`=200 ≈ 590s (~10 min)++Ground-truth per-phase wall time (in-box `date` markers, so poll granularity+doesn't distort it):++| phase | cold | what it does |+| -------------------- | -------- | ------------------------------------------------------------------------------------------------ |+| restore (VM resume) | 38s | server blocks until the box is `running` |+| ssh / exec ready | 36s | sshd/hogpanion start accepting after resume |+| `start-docker` | **75s** | `systemctl start docker`; containerd cold-reads its content store |+| `up-deps` | 36s | recreate 6 dep containers (the bake `down`s them), wait pg healthy |+| `migrate` (pg) | **126s** | `run --rm web manage.py migrate` — a **no-op** on the golden (`No planned migration operations`) |+| `migrate_clickhouse` | **147s** | same, 281 CH migrations, all no-ops |+| `up-web` | 2s | create the web container |+| web `/_health` | **117s** | Nginx Unit + workers import `posthog.wsgi`, then serve |++## Root cause: cold page-faulting through S3-backed chunkfs — not Django CPU++The rootfs is xfs on `/dev/vda`, which is chunkfs/NBD-backed. On a restore the+disk is lazily faulted: the **first** read of any byte fetches its chunk from the+S3-backed store. Everything that touches a lot of cold disk for the first time+pays for it:++- `django.setup()` is **~6s warm** (exec into a running container) but the first+ boot on a fresh restore — the `migrate` phase — is **~126s**. The delta is pure+ first-touch faulting of the python runtime + site-packages + posthog code.+ (FYI: the recent 12s→2s `setup()` win on master is real but orthogonal — it+ trims warm CPU; the preview's pain is the cold fault.)+- `start-docker` is 75s because containerd cold-reads its content store on start+ — the baked 8.7 GB posthog image + 6 dep images.+- Measured raw cold read throughput: **~48 MB/s** at the CLI default+ `--disk-mbps 125`, **~88 MB/s** unthrottled. So the **S3 chunk-fetch path+ (~88 MB/s) is the ceiling, not the disk cap** — `shared/types.go` notes NVMe+ "far exceeds 1000". Raising the cap helps a little (start-docker 75→53s,+ migrate 126→108s) but can't beat the backing-store rate.+- 16 GiB RAM also causes page-cache eviction between phases under the running+ stack, so pages warmed by one phase get re-faulted by the next.++> **Trap:** the production tool uses the SDK, which sends `disk_mbps=0`+> (unthrottled). Only the `hogland` **CLI** defaults to `125`. Don't profile via+> the CLI and conclude the disk is the cap.++## Validated levers++- **Web: `NGINX_UNIT_APP_PROCESSES=1` + `NGINX_UNIT_PRELOAD_CONFIG=true` → first+ `/_health` 118s → ~18s.** The biggest cheap win. `bin/docker-server-unit` runs+ **4** Unit workers and, when `PRELOAD_CONFIG` is unset, **double-loads** Django+ per worker (start → apply config → stop → restart) = 8 full imports. A preview+ serves one user; one worker + a preloaded config kills the redundancy. Applied+ in `stack.py` `write_override` and in the golden's own bake+ (hogland `scripts/posthog-preview-setup.sh`).+- **Tighter poll intervals** (`run_long`/`wait_http_ok` 10s → 3s): each completed+ step otherwise sits on up to 10s of dead air before we notice; a handful of+ steps adds up.+- **Don't bother combining migrate + migrate_clickhouse** — measured ~260s+ combined vs ~252s separate. They fault different working sets and CH queries+ hit a cold CH server; combining buys nothing.+- **Skipping migrate on a no-migration PR** just moves the ~90s import-fault to+ the web phase (something has to fault the import set once). Floor with the+ cheap wins ≈ 220s.++## The structural fix: a warm, docker-running golden++The cheap wins bottom out around 220s because, on a cold-on-disk snapshot, three+costs are irreducible: containerd cold-read (~60s), the import working-set fault+(~90s), and restore+ssh (~70s). To beat that, **don't snapshot the golden cold**.++Today the bake ends with `docker compose down` + `systemctl stop docker` so the+restore "cold-starts a clean runtime." That was forced by a corruption bug —+concurrent NBD writes racing chunkfs `WriteAt`'s read-modify-write, which tore+every docker-running snapshot (hogland #302, now **fixed**). With that gone, bake+the golden with the stack **up, healthy, and cache-warm** instead:++- restore **resumes a serving PostHog** — no containerd cold-start, no cold+ import faults. Page cache is guest RAM, restored via UFFD from a node-local+ memory snapshot (fast), not re-fetched from S3 disk chunks.+- delta-migrate for a PR runs via `exec` into the already-warm container (~20s)+ instead of a cold `run --rm` (~126s).++**Validated 2026-06-15** (alias `posthog-preview-golden-warm`, `snap-e82258df6119`,+baked via `snapshot-build`): a warm restore reaches external `/_health`=200 in+**~32s** (21s VM resume + ~11s) with **zero bring-up** — docker resumes `active`,+all 7 containers resume in place, the real SPA at `/` and the seeded `/login`+serve, `/_health` is stable, and **0 containers crash-loop on resume**. vs ~590s+cold. The recipe is now the default in hogland `scripts/posthog-preview-setup.sh`+(bakes warm instead of `down` + stop-docker).++Two hard constraints learned the hard way:++- The golden **must** be built by `snapshot-build` (cold-boot seed). `box snapshot`+ of a _restored_ box bakes in the source's TAP name and fails to re-restore+ (`Open tap device ... kn-box-XXXX`). So there's no "warm a box then snapshot it"+ shortcut — the warm state has to be produced inside the cold-boot bake.+- Cold-boot bakes need real host NVMe (fresh rootfs + 8.7GB image pull). A node+ with a stuck/abandoned box wedges placement with `no space left on device` —+ which fails restores too. Watch node disk; reap abandoned boxes.++What the per-PR tool still pays on a warm golden: it rewrites `SITE_URL` to the+box's edge URL and recreates **only** web (warm import + 1 worker ≈ 18s); `start+docker` / `up deps` are idempotent no-ops on the running stack; delta-migrate (if+the PR touches migrations) runs warm (~20s). So a real preview lands ~60–90s, not+32s — the 32s is the golden's own resume. A follow-on win is making `SITE_URL`+per-box without a web recreate, which would bring real previews toward ~32s too.++## Wake-on-request (shipped): warm restore of a hibernated preview++The same warm-restore physics enable the end goal: hibernate an idle preview+(snapshot the _ready_ box — stack up, PR code current — then destroy it, zero+node cost) and **wake it on the first HTTP request**. Because the snapshot is the+fully-brought-up preview, waking is a warm restore, not a rebuild: **~30–40s to+serving even on a cold node** (UFFD restores the page cache; the serving working+set faults in lazily — see hogland `docs/CHUNKFS_RESTORE_PERFORMANCE.md`), vs the+~250s to rebuild from the golden. **This is now live end-to-end:** hogland #319's+pen resolver + the wake-on-request interstitial at that 503 seam (#325), the+server-side hibernate/wake verbs, the idle-TTL reaper that auto-hibernates an+`on_idle=hibernate` pen (#329), and the pen-delete cascade that reaps the box ++hibernate snapshot on teardown (#328). The former blocker — hibernate snapshots+a _restored_ box, which baked the source TAP name and wouldn't re-restore (C7) —+was fixed by the TAP-remap (#322). So an idle preview now sleeps after its+`ttl_seconds` and wakes on the next visit, with no preview-tool changes needed+(this tool already tags its pens `on_idle=hibernate` / `wake=on-request`).++## Gotchas — baking & restoring the golden++Hard-won in PR #308 (the golden bake) + the warm-golden work. The bake script+encodes them, but they're easy to regress, so they live here too:++- **`compose run` has no `--no-build`.** Only a _present_ image stops it from+ silently starting dev-full's ~20-min `build: .`. Pull the image upfront and+ hard-fail if it's absent — don't discover the build at the migrate step.+- **Never `compose restart web`.** Nginx Unit installs its `*:8000` listener only+ on a fresh container's first boot (`/var/lib/unit` empty); a restart skips it+ and comes up with `listeners: {}` serving nothing. Recreate with a clean `up`+ (`--force-recreate` if web must be replaced).+- **Restore sizing must match the baked spec exactly** — 8 vCPU / 16384 MiB /+ 100 GiB / mirrored. "Omit to inherit" is unreliable server-side; a mismatch is+ rejected. (NB: the SDK sends `disk_mbps=0` = unthrottled; the `hogland` CLI+ defaults to `125` — a trap if you profile via the CLI.)+- **Build via `snapshot-build` (cold-boot seed), never `box snapshot` of a+ restored box** — the latter bakes the source TAP name and won't re-restore+ (`Open tap device ... kn-box-XXXX`).+- **Watch node disk.** Cold-boot bakes need real host NVMe (fresh rootfs + ~8.7GB+ image pull). A stuck/abandoned box wedges placement with `no space left on+device`, which fails restores too. Abandoned _running_ boxes aren't auto-reaped.+- **No-TTY seed box → `DEBIAN_FRONTEND=noninteractive`.** apt's `-y` doesn't+ suppress debconf prompts (tzdata/locale); without it a bake can hang.+- **Hard-fail the postgres wait loop.** A silent timeout falls through to a+ confusing psycopg2 error at migrate instead of a clear "pg never healthy".+- **Don't hardcode container names** (`posthog-db-1`) — exec via the compose+ service (`db`) so it tracks `COMPOSE_PROJECT_NAME`.+- **Shrink + flush before snapshot:** `apt-get clean` + drop `/var/lib/apt/lists`+ (re-fetches in seconds, but costs every restore real chunk I/O if baked in),+ and `sync` so the pause-time flush has the smallest backlog.+- **32 KiB bootstrap-script cap** (MMDS budget) — a guard test covers the setup+ script; keep edits under it or bakes fail at runtime.+- **`--web-port` needs the CLI `Expose`-forwarding fix (#309)** — older CLIs+ silently drop exposure, so the box gets no edge URL.+- **`:master` can ship a model ahead of its migrations** — the defensive+ `last_seen_at` ALTER stays until the image is migration-coherent.++## Reproducing++`~/workspace/startup-profiling/preview/harness.py` — provisions via the `hogland`+CLI (Tailscale identity, no token), drives every phase over SSH-as-`hog`, and+records ground-truth per-phase timing via in-box `date` markers. `restore` /+`bringup` / `fast-bringup` / `bringup-prewarm` / `phase <name>` / `health-fine`.diff --git a/tools/hogbox-preview/hogbox_preview/__init__.py b/tools/hogbox-preview/hogbox_preview/__init__.pynew file mode 100644index 000000000000..9c4476df2e3e--- /dev/null+++ b/tools/hogbox-preview/hogbox_preview/__init__.py@@ -0,0 +1,24 @@+"""Per-PR PostHog preview environments, layer-agnostic.++backend = which box (HoglandBackend today, DigitalOceanBackend before)+stack = what runs in it (PostHogPreviewStack — never changes per layer)++ from hogbox_preview import HoglandBackend, PostHogPreviewStack+ backend = HoglandBackend(host="https://hogland.…ts.net")+ url = PostHogPreviewStack(backend, branch="my-pr").bring_up()+"""++from .backend import ExecResult, PreviewBackend, SSHBackend, SSHTarget+from .digitalocean_backend import DigitalOceanBackend+from .hogland_backend import HoglandBackend+from .stack import PostHogPreviewStack++__all__ = [+ "ExecResult",+ "PreviewBackend",+ "SSHBackend",+ "SSHTarget",+ "HoglandBackend",+ "DigitalOceanBackend",+ "PostHogPreviewStack",+]diff --git a/tools/hogbox-preview/hogbox_preview/__main__.py b/tools/hogbox-preview/hogbox_preview/__main__.pynew file mode 100644index 000000000000..d74754c0a251--- /dev/null+++ b/tools/hogbox-preview/hogbox_preview/__main__.py@@ -0,0 +1,239 @@+"""CLI for hogbox previews. Mirrors bin/hobby-ci.py's subcommand shape so it+slots into the same CI flow.++ # one-shot: provision + bring PostHog up, print the URL+ python -m hogbox_preview up --branch "$BRANCH" --host "$HOG_HOST"++ # granular (debug / staged CI), reusing a box:+ python -m hogbox_preview create --host "$HOG_HOST"+ python -m hogbox_preview seed --box-id box-xxxx --host "$HOG_HOST"+ python -m hogbox_preview health --box-id box-xxxx --host "$HOG_HOST"+ python -m hogbox_preview destroy --box-id box-xxxx --host "$HOG_HOST"++Layer is chosen with --backend (hogland today). The stack is identical across+layers — see stack.py.+"""+# ruff: noqa: T201 — this is a CLI; it prints results for CI to capture.++from __future__ import annotations++import os+import sys+import json+import argparse+import urllib.request++from hogland import APIError, Hogland++from .hogland_backend import HoglandBackend+from .stack import PostHogPreviewStack++DEFAULT_HOST = os.environ.get("HOG_HOST", "https://hogland.hedgehog-kitefin.ts.net")+++def build_backend(args: argparse.Namespace) -> HoglandBackend:+ if args.backend != "hogland":+ raise SystemExit(f"backend {args.backend!r} not wired up yet (see digitalocean_backend.py)")+ return HoglandBackend(+ host=args.host,+ snapshot=args.snapshot,+ web_port=args.web_port,+ box_id=getattr(args, "box_id", None),+ name=args.name,+ cpus=args.cpus,+ memory_mib=args.memory_mib,+ disk_gib=args.disk_gib,+ ttl_seconds=args.ttl_seconds,+ )+++def build_stack(backend: HoglandBackend, args: argparse.Namespace) -> PostHogPreviewStack:+ return PostHogPreviewStack(+ backend,+ branch=getattr(args, "branch", None),+ image=args.image,+ seed_demo_data=not getattr(args, "no_seed", False),+ reset_db=getattr(args, "reset_db", False),+ frontend_dist_tar=getattr(args, "frontend_dist", None),+ )+++def cmd_up(args: argparse.Namespace) -> int:+ backend = build_backend(args)+ stack = build_stack(backend, args)+ url = stack.bring_up()+ print(f"box_id={backend.box_id}")+ print(f"url={url}")+ if args.destroy:+ backend.destroy()+ print(f"destroyed {backend.box_id}")+ return 0+++def cmd_create(args: argparse.Namespace) -> int:+ backend = build_backend(args)+ backend.provision()+ print(f"box_id={backend.box_id}")+ print(f"url={backend.web_url}")+ return 0+++def cmd_migrate(args: argparse.Namespace) -> int:+ backend = build_backend(args)+ backend.provision()+ build_stack(backend, args).migrate()+ return 0+++def cmd_seed(args: argparse.Namespace) -> int:+ backend = build_backend(args)+ backend.provision() # resolves the existing box when --box-id is set+ build_stack(backend, args).generate_demo_data()+ return 0+++def cmd_health(args: argparse.Namespace) -> int:+ backend = build_backend(args)+ backend.provision()+ backend.wait_http_ok("/_health", expect=200, timeout=args.timeout)+ print(f"healthy: {backend.web_url}")+ return 0+++def cmd_destroy(args: argparse.Namespace) -> int:+ backend = build_backend(args)+ backend.destroy()+ print(f"destroyed {args.box_id or args.name}")+ return 0+++def _pr_state(repo: str, pr: str, token: str) -> str | None:+ """The GitHub state ("open"/"closed") of a PR, or None on any error."""+ req = urllib.request.Request(+ f"https://api.github.com/repos/{repo}/pulls/{pr}",+ headers={"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=30) as r: # noqa: S310 — fixed GitHub host # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ return json.load(r).get("state")+ except Exception: # noqa: BLE001 — a flaky check shouldn't reap a live preview+ return None+++def cmd_cleanup_stale(args: argparse.Namespace) -> int:+ """Reap previews whose PR is closed: list the caller's preview-pr-<n> pens,+ check each PR's GitHub state, destroy (box + pen) the closed ones. Backstop+ for a missed PR-close teardown — leaked boxes self-reap at their 24h preview+ TTL, but pens have none, so this clears them. Honours DRY_RUN=true. Needs+ GITHUB_REPOSITORY + GH_TOKEN/GITHUB_TOKEN; without them it can't tell stale+ from live, so it keeps everything."""+ repo = os.environ.get("GITHUB_REPOSITORY", "")+ token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") or ""+ dry = os.environ.get("DRY_RUN", "false").lower() == "true"+ if not (repo and token):+ print("cleanup-stale: GITHUB_REPOSITORY + GH_TOKEN required to check PR state; nothing reaped")+ return 0+ client = Hogland(base_url=args.host, timeout=300)+ reaped = 0+ for pen in client.iter_pens():+ name = getattr(pen, "name", "") or ""+ if not name.startswith("preview-pr-"):+ continue+ pr = name[len("preview-pr-") :]+ state = _pr_state(repo, pr, token)+ if state != "closed":+ print(f"{name}: PR #{pr} {state or 'unknown'} -> keep")+ continue+ print(f"{name}: PR #{pr} closed -> {'WOULD destroy' if dry else 'destroying'}")+ if not dry:+ HoglandBackend(host=args.host, name=name).destroy()+ reaped += 1+ print(f"cleanup-stale: reaped {reaped} closed-PR preview(s)")+ return 0+++def main(argv: list[str] | None = None) -> int:+ p = argparse.ArgumentParser(prog="hogbox_preview", description=__doc__)+ p.add_argument("--backend", default="hogland", help="preview layer (default: hogland)")+ p.add_argument("--host", default=DEFAULT_HOST, help="hogland API host")+ p.add_argument("--snapshot", default="alias:posthog-preview-golden", help="golden snapshot id/alias")+ p.add_argument("--web-port", type=int, default=8000, help="in-guest port PostHog serves on")+ p.add_argument("--image", default=PostHogPreviewStack.IMAGE, help="published posthog image")+ p.add_argument(+ "--name", default="posthog-preview", help="box name (must be unique among live boxes; e.g. preview-pr-123)"+ )+ # Sizing MUST match the golden snapshot being restored ("omit to inherit" is+ # broken server-side). Defaults match the preview golden (snap-753bb8b3eeef,+ # alias posthog-preview-golden) at 8 vCPU / 16 GB / 100 GB.+ p.add_argument("--cpus", type=int, default=8, help="vCPUs (must match the golden's size)")+ p.add_argument("--memory-mib", type=int, default=16384, help="memory MiB (must match the golden's size)")+ p.add_argument("--disk-gib", type=int, default=100, help="rootfs GiB (must match the golden's size)")+ p.add_argument(+ "--ttl-seconds",+ type=int,+ default=1800,+ help="idle TTL in seconds; hogland's reaper hibernates this on_idle=hibernate preview "+ "after it's been idle this long (default 1800 = 30 min). A reviewer's next visit "+ "wakes it in ~30s. Min 60.",+ )++ sub = p.add_subparsers(dest="cmd", required=True)++ up = sub.add_parser("up", help="provision + bring PostHog up (one-shot)")+ up.add_argument("--box-id", default=None, help="reuse an existing box instead of restoring a new one")+ up.add_argument("--branch", default=None, help="posthog branch to check out in the box")+ up.add_argument("--no-seed", action="store_true", help="skip demo-data seeding (generate_demo_data)")+ up.add_argument(+ "--reset-db",+ action="store_true",+ help="wipe pg+clickhouse first, so they migrate fresh & coherent with --image (use when baking a golden)",+ )+ up.add_argument("--destroy", action="store_true", help="tear the box down after (smoke-test mode)")+ up.add_argument(+ "--frontend-dist",+ default=None,+ help="path to a gzipped tar of a prebuilt frontend/dist; serves the PR's own frontend (else the image's :master SPA)",+ )+ up.set_defaults(func=cmd_up)++ cr = sub.add_parser("create", help="provision the box only")+ cr.set_defaults(func=cmd_create)++ mg = sub.add_parser("migrate", help="run postgres + clickhouse migrations on an existing box")+ mg.add_argument("--box-id", required=True)+ mg.set_defaults(func=cmd_migrate)++ sd = sub.add_parser("seed", help="run demo-data seeding on an existing box")+ sd.add_argument("--box-id", required=True)+ sd.set_defaults(func=cmd_seed, no_seed=False)++ he = sub.add_parser("health", help="wait for /_health on an existing box")+ he.add_argument("--box-id", required=True)+ he.add_argument("--timeout", type=int, default=600)+ he.set_defaults(func=cmd_health)++ de = sub.add_parser("destroy", help="tear a box down")+ de.add_argument(+ "--box-id", default=None, help="box to tear down (falls back to --name lookup, e.g. for CI cleanup)"+ )+ de.set_defaults(func=cmd_destroy)++ sub.add_parser("cleanup-stale", help="reap previews whose PR is closed (cron backstop)").set_defaults(+ func=cmd_cleanup_stale+ )++ args = p.parse_args(argv)+ try:+ return args.func(args)+ except APIError as e:+ # Surface the server's RFC 7807 problem-details body. The SDK exception+ # message alone (e.g. "validation failed") hides which field the server+ # rejected, which makes a CI failure undiagnosable from the log.+ sys.stderr.write(f"[hogbox-preview] hogland API error (HTTP {e.status_code}): {e}\n")+ if getattr(e, "body", None):+ sys.stderr.write(f"[hogbox-preview] details: {json.dumps(e.body, indent=2, default=str)}\n")+ raise+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/hogbox-preview/hogbox_preview/backend.py b/tools/hogbox-preview/hogbox_preview/backend.pynew file mode 100644index 000000000000..6c78f237f4d1--- /dev/null+++ b/tools/hogbox-preview/hogbox_preview/backend.py@@ -0,0 +1,186 @@+"""The preview *layer* seam.++A ``PreviewBackend`` is "a box we can run a docker stack inside and reach over+HTTP". Swapping the layer — hogland today, DigitalOcean before that, something+else next — means writing one new backend. Everything about *what* runs in the+box (the PostHog stack: compose, image, migrate, seed) lives in ``stack.py`` and+never changes when the layer changes.++The split, concretely:+ - LAYER (this file + *_backend.py): what box to provision, how to ssh / which+ SDK to call, what its public URL is, how to tear it down.+ - STACK (stack.py): the docker-compose recipe, run through the backend's+ ``exec`` / ``write_file`` / ``run_long`` — blind to which provider it's on.++Most backends reach the box over ssh, so ``SSHBackend`` implements+``exec``/``write_file`` once; a provider subclass only supplies ``provision``,+``ssh_target``, ``web_url`` and ``destroy``. A future SDK-only backend can skip+``SSHBackend`` and implement the abstract methods directly.+"""++from __future__ import annotations++import abc+import time+import shlex+import subprocess+import dataclasses+++class ExecResult:+ returncode: int+ stdout: str+ stderr: str++ @property+ def ok(self) -> bool:+ return self.returncode == 0+++class SSHTarget:+ """How to reach a box over ssh. This — host/port/user/key — is the whole of+ what differs between layers at the data-plane level."""++ host: str+ port: int = 22+ user: str = "root"+ key_path: str | None = None # None -> ssh's default identity+++class PreviewBackend(abc.ABC):+ """A box that can host the PostHog docker stack and serve it over HTTP.++ ``web_port`` is the in-guest port the stack listens on; the backend exposes+ it at ``web_url`` (for hogland, the box-front edge; for a droplet, its+ domain). The stack is told this port and nothing else about the provider.+ """++ def __init__(self, *, web_port: int = 8000):+ self.web_port = web_port++ # --- layer-specific: each provider implements these four -----------------+ @abc.abstractmethod+ def provision(self) -> None:+ """Create/restore the box and expose ``web_port``. Idempotent."""++ @abc.abstractmethod+ def exec(self, command: str, *, timeout: int = 120) -> ExecResult:+ """Run a shell command in the box and capture its output."""++ @abc.abstractmethod+ def write_file(self, remote_path: str, content: bytes | str) -> None:+ """Write ``content`` (text or raw bytes) to ``remote_path`` in the box."""++ @property+ @abc.abstractmethod+ def web_url(self) -> str:+ """Externally reachable, root-served base URL for ``web_port``."""++ @abc.abstractmethod+ def destroy(self) -> None:+ """Tear the box down."""++ # --- provider-agnostic conveniences, built on exec/write_file ------------+ def run_long(self, script: str, *, name: str, timeout: int = 1800, interval: int = 3) -> ExecResult:+ """Run a slow command (image pull, migrate, seed) detached so it+ outlives the control channel, then poll a marker until it finishes.++ The detach matters: a multi-minute command run synchronously trips+ exec deadlines / connection drops. ``setsid`` + a ``.done``/``.fail``+ marker file is the portable way to launch-and-wait through any+ ``exec`` implementation. Returns the tail of the captured log.++ ``interval`` is the marker poll period: each completed step pays up to+ one interval of dead air before we notice it's done, so it's kept tight+ (3s) — the bring-up has a handful of run_long steps and a 10s poll added+ a visible chunk of pure waiting across them. Each probe is one cheap+ exec round-trip, so 3s is comfortably affordable.+ """+ base = f"/tmp/hogbox-{name}"+ log, done, fail = f"{base}.log", f"{base}.done", f"{base}.fail"+ self.write_file(f"{base}.sh", script + "\n")+ inner = f"bash {base}.sh > {log} 2>&1 && touch {done} || touch {fail}"+ launch = f"rm -f {done} {fail}; setsid bash -c {shlex.quote(inner)} </dev/null >/dev/null 2>&1 & echo launched"+ self.exec(launch, timeout=60)++ deadline = time.time() + timeout+ while time.time() < deadline:+ probe = self.exec(+ f"if [ -f {done} ]; then echo DONE; elif [ -f {fail} ]; then echo FAIL; else echo RUN; fi",+ timeout=30,+ )+ state = probe.stdout.strip().splitlines()[-1] if probe.stdout.strip() else "RUN"+ if state == "DONE":+ return self.exec(f"tail -n 80 {log}", timeout=30)+ if state == "FAIL":+ tail = self.exec(f"tail -n 60 {log}", timeout=30).stdout+ raise RuntimeError(f"{name} failed:\n{tail}")+ time.sleep(interval)+ tail = self.exec(f"tail -n 60 {log}", timeout=30).stdout+ raise TimeoutError(f"{name} did not finish within {timeout}s:\n{tail}")++ def wait_http_ok(self, url_path: str, *, expect: int = 200, timeout: int = 600, interval: int = 3) -> None:+ """Poll an in-box HTTP path until it returns ``expect`` (probed from+ inside the box, so it's independent of external networking). 3s poll so+ we don't sit on up to 10s of dead air after web actually starts serving."""+ target = f"http://localhost:{self.web_port}{url_path}"+ deadline = time.time() + timeout+ last = None+ while time.time() < deadline:+ r = self.exec(f"curl -s -o /dev/null -w '%{{http_code}}' -m 15 {target}", timeout=30)+ last = r.stdout.strip()+ if last == str(expect):+ return+ time.sleep(interval)+ raise TimeoutError(f"{target} never returned {expect} (last={last})")+++class SSHBackend(PreviewBackend):+ """A ``PreviewBackend`` reached over ssh. Subclasses supply ``ssh_target``+ plus the four layer methods; ``exec``/``write_file`` are shared here so+ every ssh-based provider gets them for free."""++ # ssh options: non-interactive, don't pollute known_hosts, fail fast.+ # nosemgrep: trailofbits.generic.ssh-disable-host-key-checking.ssh-disable-host-key-checking+ _SSH_OPTS = [+ "-o",+ "StrictHostKeyChecking=no", # ephemeral throwaway boxes with rotating IPs, no stable host key to pin+ "-o",+ "UserKnownHostsFile=/dev/null",+ "-o",+ "LogLevel=ERROR",+ "-o",+ "ConnectTimeout=20",+ "-o",+ "ServerAliveInterval=15",+ ]++ @abc.abstractmethod+ def ssh_target(self) -> SSHTarget: ...++ def _ssh_argv(self, target: SSHTarget) -> list[str]:+ argv = ["ssh", *self._SSH_OPTS, "-p", str(target.port)]+ if target.key_path:+ argv += ["-i", target.key_path, "-o", "IdentitiesOnly=yes"]+ argv.append(f"{target.user}@{target.host}")+ return argv++ def exec(self, command: str, *, timeout: int = 120) -> ExecResult:+ argv = [*self._ssh_argv(self.ssh_target()), command]+ try:+ p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout + 30)+ return ExecResult(p.returncode, p.stdout, p.stderr)+ except subprocess.TimeoutExpired as e:+ return ExecResult(124, e.stdout or "", f"ssh exec timed out after {timeout}s")++ def write_file(self, remote_path: str, content: bytes | str) -> None:+ # Pipe the body over stdin into `cat >` so no quoting/heredoc games. The+ # contract is bytes|str (stack.swap_frontend ships a binary tar), so run+ # in binary mode and encode text — text=True would corrupt raw bytes.+ data = content.encode() if isinstance(content, str) else content+ argv = [*self._ssh_argv(self.ssh_target()), f"cat > {shlex.quote(remote_path)}"]+ p = subprocess.run(argv, input=data, capture_output=True, timeout=60)+ if p.returncode != 0:+ raise RuntimeError(f"write_file({remote_path}) failed: {p.stderr.decode(errors='replace').strip()}")diff --git a/tools/hogbox-preview/hogbox_preview/digitalocean_backend.py b/tools/hogbox-preview/hogbox_preview/digitalocean_backend.pynew file mode 100644index 000000000000..5ead42720247--- /dev/null+++ b/tools/hogbox-preview/hogbox_preview/digitalocean_backend.py@@ -0,0 +1,38 @@+"""The *previous* preview layer, kept as a skeleton to prove the seam.++Before hogland, previews ran on DigitalOcean droplets (see ``bin/hobby-ci.py``+for the full droplet + DNS + cloud-init logic). Porting that here means+filling in ``provision`` / ``destroy`` and pointing ``ssh_target`` / ``web_url``+at the droplet — the PostHog stack recipe in ``stack.py`` runs unchanged. This+stub is intentionally not wired up; it exists so the layer boundary is concrete+and the next swap has an obvious shape to follow.+"""++from __future__ import annotations++from .backend import SSHBackend, SSHTarget+++class DigitalOceanBackend(SSHBackend):+ def __init__(self, *, domain: str, ip: str | None = None, ssh_key: str | None = None, web_port: int = 8000):+ super().__init__(web_port=web_port)+ self.domain = domain+ self._ip = ip+ self.ssh_key = ssh_key++ def provision(self) -> None:+ # Port bin/hobby-ci.py: create the droplet, attach the DNS record,+ # wait for cloud-init, install docker + the repo, expose web_port.+ raise NotImplementedError("DigitalOcean provisioning lives in bin/hobby-ci.py; port it here when needed")++ def ssh_target(self) -> SSHTarget:+ if not self._ip:+ raise RuntimeError("no droplet IP — provision() first")+ return SSHTarget(host=self._ip, port=22, user="root", key_path=self.ssh_key)++ @property+ def web_url(self) -> str:+ return f"https://{self.domain}".rstrip("/")++ def destroy(self) -> None:+ raise NotImplementedError("port droplet teardown from bin/hobby-ci.py")diff --git a/tools/hogbox-preview/hogbox_preview/hogland_backend.py b/tools/hogbox-preview/hogbox_preview/hogland_backend.pynew file mode 100644index 000000000000..7c60aab6ca26--- /dev/null+++ b/tools/hogbox-preview/hogbox_preview/hogland_backend.py@@ -0,0 +1,445 @@+"""Hogland preview layer, driven by the ``posthog-hogland`` SDK.++Restore a warmed golden snapshot into a hogbox (Firecracker microVM), run the+stack inside it, and reach its web over the box's own edge hostname. The box is+fronted by a **pen** — the stable named identity that outlives the box. Boxes+rotate IDs on every restore (a fresh golden restore per push); the pen, keyed on+a deterministic name (``preview-pr-1234``), persists and carries the+``current_box_id`` pointer plus repo/PR attribution. See ``docs/PENS.md`` in the+hogland repo.++Why the SDK and not the ``hogland`` CLI: the SDK is the whole PreviewBackend+surface, keyless, with one dependency (``uv run --with posthog-hogland``).+``client.create(snapshot_id=...)`` restores; ``box.exec`` / ``box.write_file``+run commands and write files over hogplane's HTTP API (no SSH); ``box.delete``+tears down; ``create_pen`` / ``update_pen`` track the stable identity. The CLI+route meant shipping a private-repo binary to the runner plus an SSH-key secret+for exec — neither is needed.++``create(web_port=...)`` opts the box into HTTP exposure, and ``box.web_url()``+returns its own per-box edge hostname (``https://<box>.<box-edge>/``, TLS+terminated at the edge, plain HTTP inside) — the clean URL posted to the PR.+``proxy_url`` (the authenticated path proxy) is only the fallback for a reused,+un-exposed ``--box-id`` box.+"""++from __future__ import annotations++import os+import json+import time+import shlex+import pathlib+import tempfile+import subprocess+import urllib.request+from urllib.parse import urlsplit++from hogland import AccessType, AuthenticationError, BoxSpec, ConflictError, Hogland, NotFoundError++from .backend import ExecResult, PreviewBackend++# hogplane caps a single write_file body at 64 MiB (octet-stream PUT). Blobs over+# that (the PR frontend dist tar) are shipped as sub-cap parts and `cat`'d back+# together in-box; _WRITE_CHUNK keeps headroom under the hard cap.+_WRITE_FILE_CAP = 64 * 1024 * 1024+_WRITE_CHUNK = 48 * 1024 * 1024+++def _ephemeral_ssh_pubkey() -> str:+ """A throwaway ed25519 public key.++ ``access_type=ssh_public`` still requires *a* key at restore time, but+ exec/write_file go over the HTTP API, so this key never reaches the box.+ Keyless (``access_type=none``, shipped for service kinds like ``preview``)+ is the clean follow-up — switching drops this whole helper.+ """+ with tempfile.TemporaryDirectory() as d:+ key = pathlib.Path(d) / "id_ed25519"+ subprocess.run(+ ["ssh-keygen", "-t", "ed25519", "-N", "", "-q", "-C", "hogbox-preview", "-f", str(key)],+ check=True,+ )+ return key.with_suffix(".pub").read_text().strip()+++class HoglandBackend(PreviewBackend):+ def __init__(+ self,+ *,+ host: str | None = None,+ snapshot: str = "alias:posthog-preview-golden",+ cpus: float = 8,+ memory_mib: int = 16384,+ disk_gib: int = 100,+ disk_class: str = "mirrored",+ web_port: int = 8000,+ name: str = "posthog-preview",+ kind: str = "preview",+ ttl_seconds: int | None = None,+ box_id: str | None = None,+ token: str | None = None,+ timeout: float = 300.0,+ oidc_audience: str | None = None,+ ):+ super().__init__(web_port=web_port)+ # Hogland() reads HOG_TOKEN / HOG_HOST from env; --host/--token override.+ # A generous timeout is required: create() blocks server-side until the+ # restore completes (tens of seconds), which trips the SDK's short+ # default and raises httpx.ReadTimeout mid-restore.+ self._host = host+ self._timeout = timeout+ # In CI the bearer is a short-lived GitHub OIDC JWT; the bring-up outlives+ # it (restore alone eats minutes), so exec/write_file re-mint on 401.+ self._oidc_audience = oidc_audience or os.environ.get("HOG_OIDC_AUDIENCE")+ self._client = Hogland(token=token, base_url=host, timeout=timeout)+ self.snapshot = snapshot+ # The golden is pinned to this sizing; restore must MATCH it exactly+ # ("omit to inherit" is unreliable server-side).+ self.cpus = cpus+ self.memory_mib = memory_mib+ self.disk_gib = disk_gib+ self.disk_class = disk_class+ # `name` is the deterministic PEN name (e.g. preview-pr-123) AND the box+ # name. The pen persists across pushes; the box behind it rotates.+ self.name = name+ # kind="preview" gives the box hogland's 24h preview idle-TTL default+ # (sandbox is immortal — a leaked preview would never be reaped).+ self.kind = kind+ self.ttl_seconds = ttl_seconds+ self._box_id = box_id+ self._box = None # hogland.Hogbox once provisioned+ self._pen = None # shared.Pen once ensured (carries the stable id for web_url)++ # --- layer methods -------------------------------------------------------+ def provision(self) -> None:+ if self._box is not None:+ return+ if self._box_id: # explicit reuse (debug / staged CI)+ self._box = self._client.get(self._box_id)+ self._wait_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.+ self._ensure_pen()+ 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()+ # 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+ # dropped: such a pen has wake=on-request but no spec.web_port, and the+ # server rejects any update of it until the flat web_port is present.+ # Re-asserting on_idle/wake makes hibernation mandatory for every push:+ # with auto-previews the fleet is large, and always-on previews would be+ # unaffordable — so even a pen that somehow lost the policy (older create,+ # manual PATCH) is healed back to hibernate-on-idle here, not just at+ # create. Idempotent for a freshly-created pen.+ self._client.update_pen(+ self.name,+ current_box_id=self._box_id,+ spec=self._pen_spec(),+ on_idle="hibernate",+ wake="on-request",+ )++ def _create_kwargs(self) -> dict:+ # The golden is pinned to this sizing; restore must MATCH it exactly.+ return {+ "snapshot_id": self.snapshot,+ "cpus": self.cpus,+ "memory_mib": self.memory_mib,+ "disk_gib": self.disk_gib,+ "disk_class": self.disk_class,+ "access_type": AccessType.ssh_public,+ "ssh_public_key": _ephemeral_ssh_pubkey(),+ "name": self.name,+ "kind": self.kind,+ "ttl_seconds": self.ttl_seconds,+ # HTTP-expose the web port so the box gets its own box-front hostname+ # (https://<box>.<box-edge>/) — that's the URL we post to the PR.+ "web_port": self.web_port,+ }++ def _restore_fresh(self):+ """Restore the golden into a new box. If our name is already taken, a+ prior run left a box behind — teardown only fires on PR *close*, so a+ failed/cancelled run leaks its box. Replace it so each run is idempotent+ (retry the create while the freed name propagates)."""+ try:+ return self._client.create(**self._create_kwargs())+ except ConflictError:+ try:+ stale = self._resolve_box()+ if stale is not None:+ stale.delete()+ except NotFoundError:+ # TTL cleanup or a racing teardown already removed it — the+ # name is free either way, so fall through to the retry loop.+ pass+ # Retry while the freed name propagates; the final attempt is outside the+ # guard so a lingering ConflictError surfaces instead of being swallowed.+ for _ in range(10):+ try:+ return self._client.create(**self._create_kwargs())+ except ConflictError:+ time.sleep(3)+ return self._client.create(**self._create_kwargs())++ 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.+ argv = ["bash", "-lc", command]+ try:+ r = self._require_box().exec(argv, timeout_seconds=timeout, env={"HOME": "/root"})+ except AuthenticationError:+ if not self._refresh_auth():+ raise+ r = self._require_box().exec(argv, timeout_seconds=timeout, env={"HOME": "/root"})+ return ExecResult(r.exit_code, r.stdout, r.stderr)++ def write_file(self, remote_path: str, content: bytes | str) -> None:+ data = content.encode() if isinstance(content, str) else content+ # The frontend dist tar blows past hogplane's 64 MiB per-PUT cap, so big+ # blobs go up as sub-cap parts and get reassembled in-box. Small writes+ # (every other caller) stay a single PUT.+ if len(data) > _WRITE_FILE_CAP:+ self._write_chunked(remote_path, data)+ else:+ self._put_file(remote_path, data)++ def _put_file(self, remote_path: str, data: bytes) -> None:+ # One PUT, re-minting the OIDC bearer once on a 401 — the bring-up+ # outlives a single short-lived CI token.+ try:+ self._require_box().write_file(remote_path, data, mkdir=True)+ except AuthenticationError:+ if not self._refresh_auth():+ raise+ self._require_box().write_file(remote_path, data, mkdir=True)++ def _write_chunked(self, remote_path: str, data: bytes) -> None:+ # Ship the blob as <=_WRITE_CHUNK parts, then `cat` them back in order+ # (listed explicitly, not globbed). The box is fresh each run, so there+ # are no stale parts to collide with.+ parts = []+ for i in range(0, len(data), _WRITE_CHUNK):+ part = f"{remote_path}.part{i // _WRITE_CHUNK:03d}"+ self._put_file(part, data[i : i + _WRITE_CHUNK])+ parts.append(part)+ quoted = " ".join(shlex.quote(p) for p in parts)+ r = self.exec(f"cat {quoted} > {shlex.quote(remote_path)} && rm -f {quoted}", timeout=300)+ if r.returncode != 0:+ raise RuntimeError(f"reassembling {remote_path} from {len(parts)} parts failed: {r.stderr.strip()}")++ @property+ def web_url(self) -> str:+ # The STABLE pen URL: https://<pen-id>.<edge>/. The pen outlives the box,+ # so this URL survives box recreation — hogland's box-http edge resolves+ # <pen-id> to the pen's current box (hogland #319). We derive the edge+ # base from the box's own per-box hostname (same edge, first label swapped+ # to the pen id) so there's no env-specific base to hardcode here.+ # Falls back to the box's own URL (no pen, or no gateway configured), then+ # to the authenticated path-proxy for an un-exposed reused box.+ box = self._require_box()+ box_url = box.web_url()+ if box_url and self._pen is not None and self._pen.id:+ host = urlsplit(box_url).hostname or ""+ base = host.split(".", 1)[1] if "." in host else ""+ if base:+ return f"https://{self._pen.id}.{base}"+ if box_url:+ return box_url.rstrip("/")+ return box.proxy_url(self.web_port).rstrip("/")++ @property+ def box_id(self) -> str | None:+ return self._box_id++ def destroy(self) -> None:+ # PR-close teardown: drop the live box, then release the stable identity.+ # delete_pen does NOT cascade, so the box must go first. Each step is+ # best-effort — a half-torn-down preview shouldn't wedge cleanup.+ #+ # A box that was already TTL-reaped counts as "already gone": the pen can+ # still point at a dead current_box_id (previews outlive their boxes — the+ # box has a 24h idle TTL, the pen has none), so both resolving it and+ # deleting it can raise NotFoundError. Swallow that so teardown still+ # reaches delete_pen — otherwise the pen leaks forever, which is the exact+ # thing this method exists to prevent.+ try:+ box = self._resolve_box()+ if box is not None:+ box.delete()+ except NotFoundError:+ pass+ try:+ self._client.delete_pen(self.name)+ except NotFoundError:+ pass++ # --- pen: the stable identity over the box lifecycle ---------------------+ def _ensure_pen(self) -> None:+ """Get-or-create the pen. Keyed on the deterministic name, it persists+ across pushes while the box rotates, carrying the ``current_box_id``+ pointer + attribution. Idempotent and race-safe: a concurrent CI re-run+ that wins the create is simply found on the retry.++ ``on_idle=hibernate`` / ``wake=on-request`` are now enforced server-side:+ hogland's idle-TTL reaper snapshots-and-sleeps an idle preview to S3+ (zero node cost), and the box-front edge wakes it on the next request+ behind a "waking up" interstitial. ``wake`` requires an exposed spec,+ which ``_pen_spec`` provides; the idle window is the pen's+ ``ttl_seconds``."""+ try:+ self._pen = self._client.get_pen(self.name)+ return+ except NotFoundError:+ pass+ try:+ self._pen = self._client.create_pen(+ self.name,+ source_alias=self._source_alias(),+ spec=self._pen_spec(),+ on_idle="hibernate",+ wake="on-request",+ metadata=self._pen_metadata(),+ )+ except ConflictError:+ # A racing run created it between our get and create — fetch the winner.+ self._pen = self._client.get_pen(self.name)++ def _pen_spec(self) -> BoxSpec:+ """The spec the pen remembers — sizing, the golden it seeds from, and the+ exposed web port (``web_port``, which is what makes ``wake=on-request`` a+ valid policy). Records enough for a wake/EnsureUp to rebuild the box from+ the pen alone. Built as the SDK's BoxSpec so the wire body carries every+ field the server requires (the throughput caps default to 0) — this code+ never re-derives the contract by hand."""+ return BoxSpec(+ snapshot_id=self.snapshot,+ cpus=self.cpus,+ memory_mib=self.memory_mib,+ disk_gib=self.disk_gib,+ disk_class=self.disk_class,+ kind=self.kind,+ web_port=self.web_port,+ ttl_seconds=self.ttl_seconds,+ )++ def _source_alias(self) -> str | None:+ """The seed alias the pen can re-restore from if its snapshots are GC'd.+ ``snapshot`` carries the ``alias:`` resolve hint; the pen stores the bare+ name (None when a concrete snap id was passed)."""+ prefix = "alias:"+ return self.snapshot[len(prefix) :] if self.snapshot.startswith(prefix) else None++ def _pen_metadata(self) -> dict[str, str] | None:+ """Display-only attribution (repo / PR / author / backlink) read from the+ GitHub Actions env, best-effort — it's the "who is this preview for" shown+ in pen listings, never used in a server decision. Empty on local runs ->+ omit the field."""+ env = os.environ+ repo = env.get("GITHUB_REPOSITORY")+ actor = env.get("GITHUB_ACTOR")+ server = env.get("GITHUB_SERVER_URL", "https://github.com")+ pr = env.get("PR") or env.get("PR_NUMBER")+ if not pr and self.name.startswith("preview-pr-"):+ pr = self.name[len("preview-pr-") :]+ md: dict[str, str] = {}+ if repo:+ md["repo"] = repo+ if pr:+ md["pr"] = pr+ if actor:+ md["author"] = actor+ if repo and pr:+ md["url"] = f"{server}/{repo}/pull/{pr}"+ return md or None++ # --- CI token refresh ----------------------------------------------------+ def _mint_oidc(self) -> str | None:+ """Mint a fresh GitHub Actions OIDC token, or None when not in CI.++ GitHub issues short-lived JWTs and the bring-up outlives one (the restore+ alone eats minutes before the first stack step), so exec/write_file+ re-mint on 401. The request URL + token are valid for the whole job, so+ this can be called as often as needed. The audience must match the+ deploy's github_oidc TrustMapping (HOG_OIDC_AUDIENCE)."""+ url = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL")+ rtok = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN")+ if not (url and rtok and self._oidc_audience):+ return None+ req = urllib.request.Request(+ f"{url}&audience={self._oidc_audience}",+ headers={"Authorization": f"bearer {rtok}"},+ )+ with urllib.request.urlopen(req, timeout=30) as r: # noqa: S310 — fixed GitHub host # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ return json.load(r).get("value")++ def _refresh_auth(self) -> bool:+ """Swap in a fresh OIDC token after a 401. Returns False outside CI+ (nothing to re-mint — let the original AuthenticationError propagate)."""+ fresh = self._mint_oidc()+ if not fresh:+ return False+ self._client = Hogland(token=fresh, base_url=self._host, timeout=self._timeout)+ if self._box is not None:+ self._box = self._client.get(self._box_id)+ return True++ # --- internal ------------------------------------------------------------+ def _require_box(self):+ if self._box is None:+ raise RuntimeError("provision() must run before the box is usable")+ return self._box++ def _resolve_box(self):+ """Find the box to act on: the live handle, an explicit id, the pen's+ current pointer, or — last resort — a name lookup over live boxes."""+ if self._box is not None:+ return self._box+ if self._box_id:+ return self._client.get(self._box_id)+ if self.name:+ try:+ pen = self._client.get_pen(self.name)+ if pen.current_box_id:+ return self._client.get(pen.current_box_id)+ except NotFoundError:+ pass # no pen, or its box was already reaped — fall through+ for v in self._client.iter_boxes():+ if getattr(v.spec, "name", None) == self.name:+ return self._client.get(v.id)+ return None++ def _wait_exec_ready(self, *, timeout: int = 300, interval: int = 5) -> None:+ deadline = time.time() + timeout+ last = ""+ while time.time() < deadline:+ try:+ r = self._box.exec(["true"], timeout_seconds=20)+ if r.exit_code == 0:+ return+ last = r.stderr or ""+ except AuthenticationError as e:+ # A multi-minute restore can outlive the CI OIDC bearer, and this+ # poll runs before the first exec()/write_file() that would refresh+ # it — so re-mint here too, or readiness spins to timeout on a+ # token that expired mid-restore. _refresh_auth swaps self._box to+ # the fresh client's handle. Guard it: a transient failure while+ # re-minting (token endpoint / get() blip) must be polled through,+ # not raised out of the loop.+ last = str(e)+ try:+ self._refresh_auth()+ except Exception as refresh_err: # noqa: BLE001 — keep polling+ last = f"{e}; refresh failed: {refresh_err}"+ except Exception as e: # noqa: BLE001 — keep polling through transient API errors+ last = str(e)+ time.sleep(interval)+ raise RuntimeError(f"box {self._box_id} exec API not ready within {timeout}s (last: {last})")diff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.pynew file mode 100644index 000000000000..6fe41ca7e714--- /dev/null+++ b/tools/hogbox-preview/hogbox_preview/stack.py@@ -0,0 +1,344 @@+"""The preview *stack* — provider-agnostic.++``PostHogPreviewStack`` knows how to bring PostHog up inside any+``PreviewBackend``: build from the checkout, migrate, seed demo data, wait for+health. It talks to the box only through ``backend.exec`` / ``write_file`` /+``run_long`` / ``wait_http_ok`` — it never knows or cares whether the box is a+hogbox or a droplet. Swapping the layer changes the backend, not this file.++Recipe (mount-over-image — the default, ~minutes per PR):+ - Run the ready-made published image (``ghcr.io/posthog/posthog:master``) and+ bind-mount the PR's backend source (``posthog``/``ee``/``products``) over the+ image's ``/code``. The image is the prod Dockerfile: it runs from+ ``WORKDIR /code`` via ``./bin/docker-server-unit`` with the frontend baked at+ ``/code/frontend/dist``. Mounting the source swaps the BACKEND code live — no+ per-PR build. (Frontend stays at the image's version; frontend hot-mount is a+ later iteration.) DEBUG=0 is required: the prod image lacks DEBUG-only apps.+ - NEVER ``restart`` the web container. Nginx Unit applies its ``*:8000``+ listener only on a fresh container's first boot (``/var/lib/unit`` empty); a+ ``restart`` finds it non-empty, skips the listener, and the app comes up with+ ``listeners: {}`` — nothing serves on 8000. ``wait_for_health`` just waits on+ the clean ``up`` (use ``--force-recreate`` if web ever needs replacing).+ - DB coherence: the restored golden's DB was migrated + seeded against the same+ image tag, so a restore only needs the PR's *delta* migrations on top+ (``migrate`` + ``migrate_clickhouse``). Reseeding is skipped — the golden is+ already seeded (CI passes ``--no-seed``).+ - ``build`` ESCAPE HATCH: pass ``image=None`` to build ``web`` from the+ checkout instead (``build: .`` — cold ~20 min; used when baking a golden, or+ to pin nothing). ``reset_db`` wipes pg+clickhouse so they migrate fresh+ against the built code. ``compose run`` has no ``--no-build`` flag (that's+ ``up``-only); what prevents a build is the image being present, so always+ pull/pin the image before any ``run``.+"""++from __future__ import annotations++import sys+import secrets++from .backend import PreviewBackend++# The tool's web override must reproduce the golden's baked preview env (hogland+# scripts/posthog-preview-setup.sh) — constant across previews so web's config+# never drifts per-box. JS_URL="" makes the SPA load assets relative to the+# request origin; the wildcard CSRF origin trusts every box's edge host for the+# login POST. One recipe then serves any box at its own edge URL.+# Built as a single comma-separated string (Django's get_list() splits on commas)+# — a join, not a tuple, so there's no ambiguity about what reaches the env.+_CSRF_TRUSTED_ORIGINS = ",".join(f"https://*.boxes.hogland.{env}.posthog.dev" for env in ("dev", "prod-us", "prod-eu"))+# PostHog's prod settings refuse to boot on the default SECRET_KEY, so the+# override must supply one (the migrate `run --rm web` one-off needs it too).+#+# It MUST be random per preview, NOT a shared constant. Previews are served on+# PUBLIC URLs (pen-<id>.boxes.hogland.<env>.posthog.dev) — the old+# "tailnet-only" assumption was stale — so a globally derivable SECRET_KEY lets+# anyone forge session cookies against every preview. We mint one random key per+# provision (see __init__) and pin it in the compose override so ALL of a+# single preview's processes share it, while different previews never do. A+# re-provision of the same PR rotates the key; that's fine — preview logins are+# throwaway demo sessions, so dropping them on re-provision is acceptable.+++class PostHogPreviewStack:+ # Default: run the ready-made published image and mount PR source over it.+ # Pass image=None to fall back to the build-from-checkout escape hatch.+ IMAGE = "ghcr.io/posthog/posthog:master"+ REPO_DIR = "/home/hog/posthog"+ COMPOSE = "docker-compose.dev-full.yml"+ OVERRIDE = "docker-compose.preview.yml"+ # Dependency services (published images, pulled by `up`).+ DEPS = ["db", "redis7", "clickhouse", "zookeeper", "kafka", "objectstorage"]+ # App services built from the checkout (build escape hatch only). web shares+ # its image with the other build: . services, so building web warms them all.+ BUILD_SERVICES = ["web"]+ # PR backend source bind-mounted over the image's /code (backend hot-mount).+ # The frontend stays baked in the image; mounting these swaps backend live.+ MOUNTS = [("posthog", "/code/posthog"), ("ee", "/code/ee"), ("products", "/code/products")]++ def __init__(+ self,+ backend: PreviewBackend,+ *,+ branch: str | None = None,+ image: str | None = None,+ repo_dir: str | None = None,+ seed_demo_data: bool = True,+ reset_db: bool = False,+ mount: bool = True,+ frontend_dist_tar: str | None = None,+ ):+ self.backend = backend+ # One random Django SECRET_KEY per stack (i.e. per provisioned box). Pinned+ # into the compose override so every process of THIS preview shares it, and+ # never shared across previews — see the module-level note above.+ self.secret_key = secrets.token_hex(32)+ self.branch = branch+ # Default (None) -> the ready-made image; "" -> build-from-checkout escape+ # hatch; any tag -> run that published image.+ self.image = self.IMAGE if image is None else image+ # Bind-mount PR source over the image's /code (only meaningful with a+ # pinned image — the build path bakes the code in, so no mount needed).+ self.mount = mount+ self.repo_dir = repo_dir or self.REPO_DIR+ self.seed_demo_data = seed_demo_data+ # reset_db wipes pg + clickhouse before migrating, so the DB is migrated+ # fresh against the built code rather than inheriting a snapshot's+ # drifted DB. Set when baking a golden; a restore-and-delta leaves False.+ self.reset_db = reset_db+ # Optional gzipped tar of a prebuilt frontend/dist (built in CI with the+ # Turbo cache). When set, swap_frontend serves the PR's own frontend+ # instead of the golden image's :master SPA. None => keep :master.+ self.frontend_dist_tar = frontend_dist_tar++ # --- public API ----------------------------------------------------------+ def bring_up(self) -> str:+ """Provision the box and bring PostHog up; return the public URL."""+ self.backend.provision()+ self.start_runtime()+ url = self.backend.web_url+ if self.branch:+ self.checkout_branch(self.branch)+ self.write_override()+ if self.image:+ self.pull_image() # escape hatch: run a published image, skip build+ else:+ self.build_app() # native path: build the checkout (PR code)+ if self.reset_db:+ self.reset_database()+ # Migrate (and seed) BEFORE web serves: web can't be restarted to pick up+ # a PR's delta migrations (the Unit-listener gotcha), so the schema must+ # be ready before the serving container boots.+ self.up_deps()+ self.migrate()+ if self.seed_demo_data:+ # Best-effort: a transient build/model issue shouldn't sink an+ # otherwise-good preview — it just opens empty.+ try:+ self.generate_demo_data()+ except Exception as e: # noqa: BLE001+ sys.stderr.write(f"[hogbox-preview] demo-data seeding skipped (preview still usable): {e}\n")+ if self.frontend_dist_tar:+ # Serve the PR's frontend (else it's the golden's :master SPA). Must+ # run before up_web so the fresh web container reads the new index+ # template + collected statics.+ self.swap_frontend()+ self.up_web()+ self.wait_for_health()+ return url++ # --- 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+ # baked WARM (stack already running — see tools/hogbox-preview/STARTUP.md),+ # so this is a no-op there; it stays as a safety net for a cold/stopped+ # golden or a box whose daemon didn't auto-start. Idempotent either way —+ # returns once `docker info` answers.+ self.backend.run_long(+ "systemctl start docker; "+ "for _ in $(seq 1 30); do docker info >/dev/null 2>&1 && break; sleep 2; done; "+ "docker info >/dev/null 2>&1",+ name="start-docker",+ timeout=180,+ )++ def checkout_branch(self, branch: str) -> None:+ # The box's exec API runs as root while the repo is hog-owned, so git+ # 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.)+ 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",+ name="checkout",+ timeout=600,+ )++ def write_override(self) -> None:+ # Reproduce the golden's baked web env (hogland+ # scripts/posthog-preview-setup.sh) so this block carries no per-box+ # value and never drifts between previews. A web recreate still happens+ # in up_web — but only to bind-mount the PR's backend source over the+ # image's /code (you can't add a mount to a running container). On the+ # warm golden that's a ~18s warm import (1 Unit worker + preloaded+ # config), not the old ~120s cold rebuild; #315's win is making that+ # 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.+ lines = ["# Generated by tools/hogbox-preview.", "services:", " web:"]+ if self.image:+ lines.append(f" image: {self.image}")+ if self.image and self.mount:+ # Bind-mount PR backend source over the image's /code — no rebuild.+ # Compose concatenates volume lists across files, so dev-full's+ # .:/app/posthog stays and these are appended.+ lines.append(" volumes:")+ mounts = list(self.MOUNTS)+ if self.frontend_dist_tar:+ # Serve the PR's frontend too: its built dist (the SPA index+ # template) + the statics collectstatic writes into staticfiles/.+ # Both are mounted so swap_frontend's `run` container and the+ # serving web container share them — static is served by+ # WhiteNoise from staticfiles/, NOT frontend/dist, hence both.+ mounts += [("frontend/dist", "/code/frontend/dist"), ("staticfiles", "/code/staticfiles")]+ lines += [f" - ./{src}:{dst}" for src, dst in mounts]+ lines += [+ " environment:",+ # SITE_URL is a cosmetic placeholder (absolute links in emails etc.);+ # serving is driven by JS_URL="" (relative assets) + the wildcard+ # CSRF origin, so the box's own edge host serves with no per-box env.+ " - SITE_URL=http://localhost:8000",+ " - JS_URL=",+ f" - EXTRA_CSRF_TRUSTED_ORIGINS={_CSRF_TRUSTED_ORIGINS}",+ " - DISABLE_SECURE_SSL_REDIRECT=1",+ " - DEBUG=0",+ # Random per-preview key (see self.secret_key) — PostHog's prod+ # settings refuse to boot on the default, and the migrate one-off+ # (compose run --rm web) needs it too. Not shared across previews, so+ # a public preview URL can't be used to forge sessions on another.+ f" - SECRET_KEY={self.secret_key}",+ # A preview serves one user, so one Unit worker is plenty — and the+ # image's entrypoint otherwise double-loads Django on every boot+ # (start→apply config→stop→restart), once per worker. Measured on a+ # restored golden: the stock 4-worker double-load is ~118s to first+ # /_health; one worker + a preloaded config is ~15-20s.+ " - NGINX_UNIT_APP_PROCESSES=1",+ " - NGINX_UNIT_PRELOAD_CONFIG=true",+ ]+ self.backend.write_file(f"{self.repo_dir}/{self.OVERRIDE}", "\n".join(lines) + "\n")++ def build_app(self) -> None:+ # `build: .` from the checkout — bakes the PR's code (front + back) into+ # the image. Cold this is ~15-25 min; on a restored golden the Docker+ # layer + turbo cache make it incremental.+ services = " ".join(self.BUILD_SERVICES)+ self.backend.run_long(self._compose(f"build {services}"), name="build", timeout=2700)++ def pull_image(self, *, attempts: int = 3) -> None:+ # The default path: fetch the ready-made image. Fast/no-op if a golden+ # already baked it in; otherwise pulls. ghcr pulls flake (TLS+ # handshake timeouts mid-layer); retry — docker resumes from pulled+ # layers, so a retry is cheap.+ last: Exception | None = None+ for _ in range(attempts):+ try:+ self.backend.run_long(f"docker pull {self.image}", name="pull", timeout=1800)+ return+ except RuntimeError as e:+ last = e+ raise RuntimeError(f"docker pull {self.image} failed after {attempts} attempts: {last}")++ def reset_database(self) -> None:+ # Drop the snapshot's pre-migrated DB so migrate() rebuilds it fresh and+ # coherent with the built code. Postgres keeps its data in a named volume+ # that survives container recreation, so the volume must be removed by+ # name; ClickHouse is volume-less, so recreating its container is enough.+ cmd = (+ f"cd {self.repo_dir} && "+ f"docker compose -f {self.COMPOSE} -f {self.OVERRIDE} stop db clickhouse web ; "+ f"docker compose -f {self.COMPOSE} -f {self.OVERRIDE} rm -f db clickhouse web ; "+ "docker volume rm posthog_postgres-15-data || true"+ )+ self.backend.run_long(cmd, name="reset-db", timeout=300)++ def up_deps(self) -> None:+ # 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.+ services = " ".join(self.DEPS)+ script = (+ f"cd {self.repo_dir} && docker compose -f {self.COMPOSE} -f {self.OVERRIDE} up -d --no-build {services} && "+ "healthy=0; for _ in $(seq 1 60); do "+ f"docker compose -f {self.COMPOSE} -f {self.OVERRIDE} ps --format '{{{{.Service}}}} {{{{.Status}}}}' "+ "| grep '^db ' | grep -q healthy && { healthy=1; break; }; sleep 4; done; "+ '[ "$healthy" = 1 ] || { echo "db never became healthy" >&2; exit 1; }'+ )+ self.backend.run_long(script, name="up-deps", timeout=900)++ 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.+ 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.+ self.backend.run_long(+ self._compose("run --rm -T web python manage.py migrate --noinput"),+ name="migrate",+ timeout=1800,+ )+ self.backend.run_long(+ self._compose("run --rm -T web python manage.py migrate_clickhouse"),+ name="migrate-clickhouse",+ timeout=1800,+ )++ 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.)+ self.backend.run_long(+ self._compose("run --rm -T web python manage.py generate_demo_data"),+ name="seed",+ timeout=1800,+ )++ def swap_frontend(self) -> None:+ # Serve the PR's OWN frontend. The dist is built in CI (Depot + Turbo+ # cache) and handed in as a gzipped tar; drop it into the box's+ # frontend/dist (bind-mounted over /code/frontend/dist by write_override)+ # and re-run collectstatic so WhiteNoise serves the PR's hashed chunks+ # from the (also-mounted) staticfiles/. Static is served from+ # staticfiles/, NOT frontend/dist — so collectstatic is mandatory.+ # STATIC_COLLECTION=1 skips the prod SECRET_KEY guard; the version skip+ # mirrors the image's own collectstatic. Deps are already up (up_deps ran)+ # so settings import is fine; collectstatic itself needs no live DB.+ import pathlib++ 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}"+ # CI tars the dist with `-C frontend dist`, so its members are rooted at+ # `dist/`; strip that leading level on extract or the SPA double-nests to+ # frontend/dist/dist/ and collectstatic finds nothing.+ script = (+ f"cd {self.repo_dir} && "+ "rm -rf frontend/dist && mkdir -p frontend/dist staticfiles && "+ "tar xzf frontend/dist.tgz -C frontend/dist --strip-components=1 && "+ f"{compose} run --rm -T -e STATIC_COLLECTION=1 -e SKIP_SERVICE_VERSION_REQUIREMENTS=1 "+ "web python manage.py collectstatic --noinput"+ )+ self.backend.run_long(script, name="frontend", timeout=900)++ def wait_for_health(self) -> None:+ # Do NOT `restart web` with the pinned image: Nginx Unit binds its :8000+ # listener only on a fresh container's first boot (/var/lib/unit empty);+ # 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.+ self.backend.wait_http_ok("/_health", expect=200, timeout=900)++ # --- internal ------------------------------------------------------------+ def _compose(self, args: str) -> str:+ return f"cd {self.repo_dir} && docker compose -f {self.COMPOSE} -f {self.OVERRIDE} {args}"diff --git a/tools/hogbox-preview/tests/test_hogland_backend.py b/tools/hogbox-preview/tests/test_hogland_backend.pynew file mode 100644index 000000000000..8f69ed1af434--- /dev/null+++ b/tools/hogbox-preview/tests/test_hogland_backend.py@@ -0,0 +1,161 @@+"""Unit tests for the hogland preview backend.++Self-contained: no network, no live hogland. Runs against a hand-rolled fake+client that stands in for the ``posthog-hogland`` SDK's ``Hogland``. Guarded on+the SDK import so the monorepo's Django pytest collection can't hard-fail here+(the SDK is pulled per-run via ``uv run --with``, not a repo dependency).++ cd tools/hogbox-preview && python -m unittest discover tests+"""++from __future__ import annotations++import unittest++try:+ import hogland # noqa: F401++ HAVE_SDK = True+except ImportError:+ HAVE_SDK = False+++class _FakePen:+ def __init__(self, current_box_id: str | None = None):+ self.current_box_id = current_box_id+ self.id = "pen-deadbeef"+++class _FakeBox:+ def __init__(self, *, delete_raises: Exception | None = None):+ self._delete_raises = delete_raises+ self.deleted = False++ def delete(self) -> None:+ if self._delete_raises is not None:+ raise self._delete_raises+ self.deleted = True+++class _FakeClient:+ """Minimal stand-in for the SDK client. Each method's behaviour is set by the+ test; every call is recorded so we can assert teardown reached delete_pen."""++ def __init__(self, *, get=None, get_pen=None, boxes=None, create=None):+ self._get = get+ self._get_pen = get_pen+ self._boxes = boxes or []+ self._create = create+ self.deleted_pens: list[str] = []++ def get(self, box_id):+ if callable(self._get):+ return self._get(box_id)+ return self._get++ def get_pen(self, name):+ if callable(self._get_pen):+ return self._get_pen(name)+ return self._get_pen++ def iter_boxes(self):+ return iter(self._boxes)++ def delete_pen(self, name):+ self.deleted_pens.append(name)++ def create(self, **kwargs):+ if callable(self._create):+ return self._create(**kwargs)+ return self._create++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class DestroyReleasesPenTest(unittest.TestCase):+ """destroy() must always reach delete_pen — a box already TTL-reaped counts+ as 'already gone', it must not abort teardown and leak the pen."""++ def _backend(self, client):+ from hogbox_preview.hogland_backend import HoglandBackend++ backend = HoglandBackend(host="https://example.invalid", name="preview-pr-999", token="test-token")+ backend._client = client+ return backend++ def test_pen_released_when_box_lookup_404s(self):+ # The pen still points at a dead box id; resolving it raises NotFoundError.+ from hogland import NotFoundError++ def boom(_box_id):+ raise NotFoundError("box gone", status_code=404)++ client = _FakeClient(get=boom, get_pen=_FakePen(current_box_id="box-reaped"))+ backend = self._backend(client)+ backend._box_id = "box-reaped" # forces _resolve_box down the direct get() path++ backend.destroy()++ self.assertEqual(client.deleted_pens, ["preview-pr-999"])++ def test_pen_released_when_box_delete_404s(self):+ # A stale live handle whose box was reaped between resolve and delete.+ from hogland import NotFoundError++ box = _FakeBox(delete_raises=NotFoundError("box gone", status_code=404))+ client = _FakeClient()+ backend = self._backend(client)+ backend._box = box # _resolve_box short-circuits to the live handle++ backend.destroy()++ self.assertEqual(client.deleted_pens, ["preview-pr-999"])++ def test_happy_path_deletes_box_then_pen(self):+ box = _FakeBox()+ client = _FakeClient()+ backend = self._backend(client)+ backend._box = box++ backend.destroy()++ self.assertTrue(box.deleted)+ self.assertEqual(client.deleted_pens, ["preview-pr-999"])++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class RestoreFreshHandlesStaleConflictTest(unittest.TestCase):+ """A name conflict on create() means a prior run's box is still in the way.+ If that box was already reaped (TTL cleanup or a racing teardown) between+ resolving it and deleting it, the retry must still proceed — not abort."""++ def _backend(self, client):+ from hogbox_preview.hogland_backend import HoglandBackend++ backend = HoglandBackend(host="https://example.invalid", name="preview-pr-999", token="test-token")+ backend._client = client+ return backend++ def test_retries_create_when_stale_box_already_gone(self):+ from hogland import ConflictError, NotFoundError++ stale_box = _FakeBox(delete_raises=NotFoundError("box gone", status_code=404))+ created = object()+ attempts = {"n": 0}++ def create(**_kwargs):+ attempts["n"] += 1+ if attempts["n"] == 1:+ raise ConflictError("name taken", status_code=409)+ return created++ client = _FakeClient(create=create)+ backend = self._backend(client)+ backend._box = stale_box # _resolve_box short-circuits to the live handle++ result = backend._restore_fresh()++ self.assertIs(result, created)+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/hogbox-preview/tests/test_stack_secret_key.py b/tools/hogbox-preview/tests/test_stack_secret_key.pynew file mode 100644index 000000000000..3d15dfb0a01c--- /dev/null+++ b/tools/hogbox-preview/tests/test_stack_secret_key.py@@ -0,0 +1,85 @@+"""Unit tests for the preview SECRET_KEY handling in the stack.++Self-contained: no network, no live box. The stack's ``write_override`` only+touches ``backend.write_file``, so a recording fake backend is enough to assert+the key is random per preview (not a shared, publicly derivable constant) —+previews are served on PUBLIC URLs, so a shared key would let anyone forge+sessions across every preview.++ cd tools/hogbox-preview && python -m unittest discover tests+"""++from __future__ import annotations++import hashlib++import unittest++# Importing the package pulls hogland_backend, which needs the posthog-hogland+# SDK (installed per-run via `uv run --with`, not a repo dependency). Guard the+# import so the monorepo's Django pytest collection can't hard-fail here — the+# key path itself is SDK-free, but the package __init__ isn't.+try:+ from hogbox_preview.stack import PostHogPreviewStack++ HAVE_SDK = True+except ImportError:+ HAVE_SDK = False++# The old, broken approach: a globally derivable constant shared by every box.+_OLD_DERIVABLE_KEY = hashlib.sha256(b"hogbox-preview-ephemeral-tailnet-only").hexdigest()+++class _RecordingBackend:+ """Duck-typed stand-in for a PreviewBackend: write_override only calls+ write_file, so that's all the stack needs from us here."""++ def __init__(self):+ self.files: dict[str, str] = {}++ def write_file(self, remote_path, content) -> None:+ self.files[remote_path] = content if isinstance(content, str) else content.decode()+++def _secret_key_from_override(stack, backend: _RecordingBackend) -> str:+ stack.write_override()+ override = backend.files[f"{stack.repo_dir}/{stack.OVERRIDE}"]+ for line in override.splitlines():+ stripped = line.strip().lstrip("- ")+ if stripped.startswith("SECRET_KEY="):+ return stripped.split("=", 1)[1]+ raise AssertionError(f"no SECRET_KEY in override:\n{override}")++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class PreviewSecretKeyTest(unittest.TestCase):+ def test_key_is_random_hex_not_the_derivable_constant(self):+ backend = _RecordingBackend()+ stack = PostHogPreviewStack(backend)+ key = _secret_key_from_override(stack, backend)++ self.assertNotEqual(key, _OLD_DERIVABLE_KEY)+ # secrets.token_hex(32) -> 64 lowercase hex chars.+ self.assertEqual(len(key), 64)+ self.assertTrue(all(c in "0123456789abcdef" for c in key))++ def test_key_differs_across_previews(self):+ # Two independent previews (e.g. a re-provision) must not share a key.+ b1, b2 = _RecordingBackend(), _RecordingBackend()+ k1 = _secret_key_from_override(PostHogPreviewStack(b1), b1)+ k2 = _secret_key_from_override(PostHogPreviewStack(b2), b2)+ self.assertNotEqual(k1, k2)++ def test_key_is_stable_within_a_single_preview(self):+ # All of one preview's processes must agree: rewriting the override for+ # the same stack yields the same key.+ backend = _RecordingBackend()+ stack = PostHogPreviewStack(backend)+ self.assertEqual(+ _secret_key_from_override(stack, backend),+ _secret_key_from_override(stack, backend),+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/uv.lock b/uv.lockindex 62d9be9b8c9f..8f79faf48bcb 100644--- a/uv.lock+++ b/uv.lock@@ -15,12 +15,13 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included forexclude-newer-span = "P7D"[options.exclude-newer-package]+hogql-parser-rs = falsepixelhog = falsehogql-parser = falseposthoganalytics = falsedjango = false+posthog-hogland = falsemodal = false-hogql-parser-rs = false[manifest]members = [