: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
chore(ci): restore hogbox pr previews behind a label on dev (#122674)
Georges-Antoine Assiad0e45d4cd66
diff --git a/.github/scripts/post-ci-sections.test.mjs b/.github/scripts/post-ci-sections.test.mjsindex 59c01596060f..21b62c3a1fc1 100644--- a/.github/scripts/post-ci-sections.test.mjs+++ b/.github/scripts/post-ci-sections.test.mjs@@ -3,6 +3,7 @@ import { describe, it } from 'node:test'import { buildDocsPreviewSection } from './post-docs-preview-section.mjs'import { buildHobbySection } from './post-hobby-section.mjs'+import { buildHogboxPreviewSection } from './post-hogbox-preview-section.mjs'import { buildTrunkLaneSection, parseCrossLane, postTrunkLaneSection } from './post-trunk-lane-section.mjs'const commonHobby = {@@ -153,6 +154,36 @@ describe('CI report section builders', () => {assert.match(section.body, /actions\/runs\/42/)})+ for (const testCase of [+ {+ name: 'claims the PR frontend only when it was swapped in',+ frontendSwapped: true,+ expected: /\*\*and\*\* frontend/,+ },+ {+ name: 'says the frontend is unchanged when it was not swapped in',+ frontendSwapped: false,+ expected: /frontend unchanged by this PR/,+ },+ ]) {+ it(testCase.name, () => {+ const section = buildHogboxPreviewSection({+ state: 'ready',+ sha: '1234567890abcdef',+ runUrl: 'https://github.com/PostHog/posthog/actions/runs/42',+ url: 'https://preview.example.com',+ boxId: 'box-1',+ penId: 'None',+ consoleHost: 'console.example.com',+ frontendSwapped: testCase.frontendSwapped,+ })+ assert.equal(section.status, 'ok')+ assert.match(section.summary, /https:\/\/preview\.example\.com/)+ assert.match(section.body, testCase.expected)+ assert.doesNotMatch(section.body, /console\/fleet\/pens/)+ })+ }+it('moves a hobby preview through setup, ready, and failed states', () => {const initial = buildHobbySection({ state: 'initial', ...commonHobby })const ready = buildHobbySection({diff --git a/.github/scripts/post-hogbox-preview-section.mjs b/.github/scripts/post-hogbox-preview-section.mjsnew file mode 100644index 000000000000..ea9eba3d5f51--- /dev/null+++ b/.github/scripts/post-hogbox-preview-section.mjs@@ -0,0 +1,105 @@+#!/usr/bin/env node+import { pathToFileURL } from 'node:url'++import { postSection, updateSectionIfPresent } from '../../frontend/bin/ci-report/update-ci-report.mjs'++const LEGACY_PREFIXES = ['<!-- hogbox-preview-comment -->']++export function buildHogboxPreviewSection({+ state,+ sha = '',+ runUrl,+ url,+ boxId,+ penId,+ consoleHost,+ frontendSwapped,+ readySeconds,+}) {+ const commit = sha.slice(0, 7)++ if (state === 'building') {+ return {+ status: 'info',+ summary: 'building',+ body: [+ "Spinning up PostHog for this PR on a hogland hogbox. This section updates in place when it's ready (usually a few minutes).",+ '',+ `<sub>commit \`${commit}\` · <a href="${runUrl}">build log</a></sub>`,+ ].join('\n'),+ }+ }++ if (state === 'failed') {+ return {+ status: 'fail',+ summary: 'build failed',+ body: [+ `The preview didn't come up for commit \`${commit}\`. See the **[build log](${runUrl})** for the failing step. It'll retry on the next push.`,+ '',+ '<sub>Previews are optional and never block merging. A failure here is often a hogland or tailnet hiccup rather than anything in your PR, so the check stays green and this section is the status.</sub>',+ ].join('\n'),+ }+ }++ if (state === 'torn-down') {+ return {+ status: 'info',+ summary: 'torn down',+ body: 'The preview for this PR was torn down because the `hogbox-preview` label was removed. Add the label again to bring it back.',+ }+ }++ if (state !== 'ready') {+ throw new Error(`Unknown hogbox preview section state: ${state}`)+ }++ // A backend-only preview serves the :master SPA, so only claim the PR's frontend when it was swapped in.+ const running = frontendSwapped+ ? "this PR's backend **and** frontend, on the PostHog `:master` base"+ : "this PR's backend on the PostHog `:master` base (frontend unchanged by this PR)"+ // The CLI parser can surface a missing pen id as the literal string 'None'.+ const adminUrl =+ consoleHost && penId && penId !== 'None' ? `https://${consoleHost}/console/fleet/pens/${penId}` : null+ const readyIn = readySeconds ? ` · ready in ${readySeconds}s (push → usable)` : ''++ return {+ status: 'ok',+ summary: `ready, <a href="${url}">open the preview</a>`,+ body: [+ `### [▶ Open the preview](${url})`,+ '',+ '| | |',+ '|--|--|',+ '| 🔑 **Login** | `[email protected]` / `12345678` (demo data) |',+ `| 🧩 **Running** | ${running} |`,+ '| 🔗 **Link** | **stable across rebuilds**: a re-push swaps the box underneath, the URL stays |',+ '| 🔒 **Access** | tailnet only (PostHog VPN) |',+ ...(adminUrl ? [`| 🛠️ **Admin** | [inspect & debug state in hogland](${adminUrl}) |`] : []),+ '| 💤 **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 |',+ '',+ `<sub>commit \`${commit}\` · box \`${boxId}\`${readyIn} · <a href="${runUrl}">build log</a> · rebuilds on every push, torn down on close</sub>`,+ ].join('\n'),+ }+}++async function main() {+ const [state] = process.argv.slice(2)+ const section = buildHogboxPreviewSection({+ state,+ sha: process.env.SHA,+ runUrl: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`,+ url: process.env.URL,+ boxId: process.env.BOX,+ penId: process.env.PEN,+ consoleHost: process.env.CONSOLE_HOST,+ frontendSwapped: process.env.SWAP === 'true',+ readySeconds: process.env.READY_SECONDS,+ })+ const post = state === 'torn-down' ? updateSectionIfPresent : postSection+ await post({ id: 'hogbox-preview', ...section }, { legacyPrefixes: LEGACY_PREFIXES })+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ await main()+}diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 64338571ef49..6c13f9676b60 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -182,6 +182,9 @@ const DESKTOP = 'desktop'// from services/mcp sources. The same pair STANDALONE_TREES gives cli/ itself.const CLI_ARTIFACTS = 'cli-artifacts'+// The hogbox preview-environment workflows, which read the hogbox tooling.+const HOGBOX_PREVIEW = 'hogbox-preview'+// Bot, report, sync, and canary workflows plus the scripts they run. None of// them is a required check, so a break costs a bot action rather than a merge// gate, and one shared lane keeps a script and the workflow that runs it@@ -319,6 +322,10 @@ const TRIPWIRE_RULES = [// the rust lanes on top of deploy: those PR checks parse it, even though// only the image builds act on what it maps.['.github/rust-images.yml', [RUST, DEPLOY]],+ // The hogbox preview environment gates no check, and its deploys read the+ // hogbox tooling, which owns a lane already.+ ['.github/workflows/hogbox-preview-env.yml', HOGBOX_PREVIEW],+ ['.github/workflows/hogbox-preview-cleanup.yml', HOGBOX_PREVIEW],// CI scripts held to the workflows that run them: the backend test-timing// pair and the IDOR coverage check run only in ci-backend and its timing// workflow, while report_test_timings is read by the backend, frontend,@@ -1728,6 +1735,11 @@ function addHobbyLane(targets) {return true}+function addHogboxPreviewLane(targets) {+ targets.add('tools:hogbox-preview')+ return true+}+function addCliArtifactLanes(targets) {targets.add('cli')targets.add('svc:mcp')@@ -1857,6 +1869,7 @@ const DOMAIN_LANES = new Map([[FULLSTACK, addFullstackLanes],[DEPLOY, addDeployLane],[HOBBY, addHobbyLane],+ [HOGBOX_PREVIEW, addHogboxPreviewLane],[CLI_ARTIFACTS, addCliArtifactLanes],[DESKTOP, addDesktopLanes],[REPO_AUTOMATION, laneOf('repo-automation')],@@ -2979,6 +2992,7 @@ module.exports = {DESKTOP,FULLSTACK,HOBBY,+ HOGBOX_PREVIEW,JAVASCRIPT,NATIVE_BINDING_CONSUMER_LANES,NODE,diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.jsindex a14e884d908a..2d51ae004caa 100644--- a/.github/scripts/trunk-impacted-targets.test.js+++ b/.github/scripts/trunk-impacted-targets.test.js@@ -827,6 +827,12 @@ test('the cli workflow and the reusable release plan share the cli lane', () =>}})+test('the hogbox preview workflows keep the hogbox tooling lane', () => {+ for (const file of ['.github/workflows/hogbox-preview-env.yml', '.github/workflows/hogbox-preview-cleanup.yml']) {+ assert.deepEqual(computeTargets([file], CONTEXT), ['tools:hogbox-preview'], file)+ }+})+test('the mcp ui-apps workflow claims the product-surface readers', () => {assert.deepEqual(computeTargets(['.github/workflows/ci-mcp-ui-apps.yml'], CONTEXT),@@ -1330,6 +1336,7 @@ test('every target the rules can emit appears in the enumerated universe', () =>'.github/workflows/ci-hobby.yml','.github/workflows/ci-oauth-proxy.yml','.github/workflows/ci-agent-skills.yml',+ '.github/workflows/hogbox-preview-env.yml','.github/workflows/ci-cli.yml','bin/hobby-ci.py','Dockerfile.llm-analytics',diff --git a/.github/workflows/hogbox-preview-cleanup.yml b/.github/workflows/hogbox-preview-cleanup.ymlnew file mode 100644index 000000000000..08d87cf0f4bf--- /dev/null+++ b/.github/workflows/hogbox-preview-cleanup.yml@@ -0,0 +1,81 @@+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-dev.hedgehog-kitefin.ts.net+ HOG_OIDC_AUDIENCE: hogland.dev.posthog.dev++jobs:+ cleanup-hogbox-preview:+ name: Reap stale hogbox previews+ if: github.repository == 'PostHog/posthog'+ 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+ # Retry + empty-token guard, matching the other mint sites: `curl |+ # jq` takes jq's exit (which succeeds on empty input), so without the+ # guard a transient OIDC outage would pass an empty token and the+ # sweep would no-op silently instead of reaping stale previews.+ run: |+ token=""+ for attempt in 1 2 3; do+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value') || token=""+ [ -n "$token" ] && [ "$token" != "null" ] && break+ echo "::warning::OIDC mint attempt ${attempt} failed; retrying"+ [ "$attempt" -lt 3 ] && sleep 5+ done+ [ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::OIDC mint failed after 3 attempts"; exit 1; }+ 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: ./.github/actions/setup-uv+ with:+ enable-cache: false+ - 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..e4c26cc6bae4--- /dev/null+++ b/.github/workflows/hogbox-preview-env.yml@@ -0,0 +1,736 @@+# 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 (a CI report section + 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 compiled on the runner (the untrusted build-frontend+# job — never in credential scope), shipped in as a dist tarball through+# hogplane's files API (chunked past the 64 MiB write cap), laid over the image's+# baked dist in-box and followed by a collectstatic re-run. Label-only backend+# PRs that don't touch the frontend skip all of that and serve the image's+# :master SPA. If a PR's migrations are incompatible with the baseline, fall back+# to --reset-db.+#+# --- TRIGGER (who gets a preview) -----------------------------------------------+# Opt-in only. A same-repo PR gets a preview when someone adds the+# `hogbox-preview` label, on a draft or a ready PR and for any paths. While the+# label stays on, every push rebuilds it. Removing the label tears it down.+#+# --- LIFECYCLE ------------------------------------------------------------------+# - build/update: once `decide` says build, `announce` posts the in-progress+# Deployment + CI report section, then `build-frontend` (untrusted, no credentials —+# see the permissions note below) and `deploy` (trusted, brings the box up)+# run IN PARALLEL. deploy no longer waits on the dist: it restores + mounts ++# migrates immediately, and only blocks on build-frontend right at the end,+# to swap the finished dist in before it posts "ready". Cuts wall-clock:+# the FE build hides under the longer bring-up.+# - teardown on PR close + the daily stale-sweep: pr-closed.yml (box + pen) ++# hogbox-preview-cleanup.yml's cron. The GitHub Deployments live in the+# shared `hogbox-preview` environment with task `preview-pr-<n>`.+# - teardown fast path: the `teardown` job below fires when `hogbox-preview` is+# removed (the cron is the backstop); it also marks the Deployment inactive+# and flips the CI report section.+#+# --- 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 dev+# 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.++# --- OPTIONAL BY DESIGN ---------------------------------------------------------+# A preview never gates a PR: all preview infra (tailnet, hogland, GitHub API, the+# reporters) fails open and reports via the Deployment + CI report section. Only+# `build-frontend` (PR code — deploy reads its conclusion) and the fork guards still+# red. There is no "yellow" to use instead, and job-level `continue-on-error` still+# reds the PR, so fail-open means step-level. The name prefix is on the JOBS because+# a check run is named after the job, not the workflow.+name: '[Optional] Hogbox Preview Environment'++on:+ pull_request:+ # `labeled`/`unlabeled` drive the opt-in and the teardown; `synchronize`+ # and `reopened` rebuild a PR that still carries the label. GitHub cannot+ # filter a label trigger by name, so the `decide` job's `if:` drops every+ # other event before a runner starts.+ types: [synchronize, reopened, 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:+ # dev: prod-us no longer serves previews.+ HOG_HOST: https://hogland-dev.hedgehog-kitefin.ts.net+ HOG_OIDC_AUDIENCE: hogland.dev.posthog.dev+ PR: ${{ github.event.pull_request.number || github.event.inputs.pr_number }}+ # One shared GitHub environment for every PR, keyed per PR by the deployment+ # task. GitHub creates an environment for each new deployment name, and a+ # workflow token cannot delete environments, so a per-PR name leaks one each.+ DEPLOY_ENVIRONMENT: hogbox-preview++jobs:+ # ----------------------------------------------------------------------------+ # Cheap, credential-free gate. The job `if:` keeps every PR without the+ # label off a runner, and keeps fork PRs out of credential scope even when+ # someone labels one. The step only maps the event to build or teardown.+ # Keeping it separate + non-cancelable is what dodges the unlabeled-cancel+ # trap: a no-op event never touches the `deploy`/`teardown` concurrency+ # group, so it can't cancel an active build.+ decide:+ # A preview for the queue's branch would outlive it by minutes.+ if: >-+ github.event_name == 'workflow_dispatch'+ || (github.event.pull_request.head.repo.full_name == github.repository+ && !startsWith(github.head_ref, 'trunk-merge/')+ && (github.event.label.name == 'hogbox-preview'+ || (contains(fromJSON('["synchronize", "reopened"]'), github.event.action)+ && contains(github.event.pull_request.labels.*.name, 'hogbox-preview'))))+ name: '[Optional] decide eligibility'+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ permissions: {}+ outputs:+ build: ${{ steps.decide.outputs.build }}+ teardown: ${{ steps.decide.outputs.teardown }}+ steps:+ - name: Decide build vs teardown+ id: decide+ env:+ ACTION: ${{ github.event_name == 'workflow_dispatch' && 'dispatch' || github.event.action }}+ run: |+ if [ "$ACTION" = unlabeled ]; then+ echo "hogbox-preview removed → tear down"+ { echo build=false; echo teardown=true; } >> "$GITHUB_OUTPUT"+ else+ echo "$ACTION with hogbox-preview → build"+ { echo build=true; echo teardown=false; } >> "$GITHUB_OUTPUT"+ fi++ # ----------------------------------------------------------------------------+ # Trusted and tiny: open a GitHub Deployment (in_progress) and the+ # "building…" CI report section immediately, so the PR shows activity before the+ # multi-minute build + bring-up finishes. Runs only default-branch scripts — 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: '[Optional] announce build'+ needs: decide+ if: needs.decide.outputs.build == 'true'+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ permissions:+ contents: read+ pull-requests: write # CI report section+ deployments: write # GitHub Deployment for the PR's Environments UI+ outputs:+ sha: ${{ steps.start.outputs.sha }}+ deployment_id: ${{ steps.start.outputs.deployment_id }}+ steps:+ # Cosmetic: on a blip sha/deployment_id go empty, which deploy already tolerates.+ - name: Announce (deployment)+ id: start+ continue-on-error: true+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.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 = process.env.DEPLOY_ENVIRONMENT;+ 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, task: `preview-pr-${pr}`, 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…',+ });++ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ continue-on-error: true+ with:+ ref: ${{ github.event.repository.default_branch }}+ sparse-checkout: |+ .github/scripts+ frontend/bin/ci-report++ - name: Post building section+ continue-on-error: true+ env:+ GITHUB_TOKEN: ${{ github.token }}+ PR_NUMBER: ${{ env.PR }}+ SHA: ${{ steps.start.outputs.sha }}+ run: node .github/scripts/post-hogbox-preview-section.mjs building++ # ----------------------------------------------------------------------------+ # 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.+ #+ # DELIBERATELY NOT in the per-PR concurrency group. build-frontend and+ # deploy now run in PARALLEL within one run (deploy waits on it only at the+ # end, to swap the dist in), and GitHub won't run two jobs of the same group+ # at once — so sharing the group would deadlock them (one sits queued behind+ # the other forever). The group therefore lives on `deploy`/`teardown` ONLY.+ # ACCEPTED COST: a superseded push cancels the newer run's deploy (via the+ # group), but this run's build-frontend is NOT cancelable, so it may run to+ # completion wasted (runner time only). No correctness impact — its+ # artifact is namespaced to its own run_id, so a stale build can't leak into+ # the winning run's swap.+ # Hard-fails on purpose: it runs PR code, and deploy reads its conclusion to tell+ # a broken FE build from a backend-only PR. deploy matches this `name` literally.+ build-frontend:+ name: '[Optional] build PR frontend'+ needs: decide+ if: needs.decide.outputs.build == 'true'+ runs-on: ubuntu-24.04+ timeout-minutes: 30+ permissions:+ contents: read+ pull-requests: read # list changed files (FE detection) + resolve dispatched PR numbers+ # No job-level outputs: deploy no longer `needs` this job (they run in+ # parallel). It discovers whether a dist exists by checking THIS run for+ # the `hogbox-preview-frontend-dist` artifact — present ⇒ swap, absent ⇒+ # the PR didn't touch the frontend, keep :master.+ steps:+ # SECURITY GATE — manual dispatch takes a bare pr_number and the tool+ # later checks out `pull/<n>/head` INSIDE the box and EXECUTES it with+ # 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@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.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+ with:+ # A dispatched run would otherwise check out master (the dispatch ref)+ # and ship master's SPA as the "PR frontend" — dispatch is the only+ # preview path for bot-authored PRs. The PR head is safe here:+ # the fork guard above has already hard-failed non-same-repo numbers,+ # and this job runs without credentials. pull_request events keep the+ # default merge-ref behavior (empty ref).+ ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/pull/{0}/head', env.PR) || '' }}++ # --- 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 fast preview.+ - name: Detect frontend changes+ id: fe+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.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+ compression-level: 0+ 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.+ #+ # PARALLEL with build-frontend: deploy deliberately does NOT `need`+ # build-frontend, so it starts bringing the box up the moment `announce`+ # opens the Deployment — restore + backend mount + migrate run WHILE the+ # runner compiles the PR frontend on its own runner. Only once the box is+ # healthy does deploy block on build-frontend (the "Wait for the PR frontend"+ # step polls this run's jobs), then swap the finished dist in BEFORE posting+ # "ready" — a reviewer must never open a green link and get :master's+ # frontend for their frontend PR. The FE build hides entirely under the+ # longer bring-up, so the pipeline is bring-up-bound, not their sum.+ #+ # FAIL-OPEN, so infra failures leave this job green: success()/failure() are+ # meaningless here, the `outcome` step is the verdict. The fork guard is exempt —+ # it must hard-stop before the tailnet and token come online.+ deploy:+ name: '[Optional] deploy preview'+ needs: [decide, announce]+ # Runs whenever an eligible build was attempted — even if announce+ # failed, so the failure reporter below still flips the Deployment ++ # CI report section 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+ actions: read # poll this run's jobs + artifacts to wait on build-frontend+ pull-requests: write # CI report section+ deployments: write # flip the Deployment to success/failure+ env:+ SHA: ${{ needs.announce.outputs.sha }}+ DEP: ${{ needs.announce.outputs.deployment_id }}+ steps:+ # SECURITY GATE — same fork check as build-frontend, duplicated here+ # because deploy no longer `needs` that job: without its own guard, a+ # dispatched FORK PR number would reach the tailnet join + token mint+ # below (and stand up a box running fork code) before build-frontend's+ # guard eventually failed the wait step. Runs first, before anything+ # sensitive comes online.+ - name: Guard dispatch against fork PRs+ if: github.event_name == 'workflow_dispatch'+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.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.`);+ }++ # Shared t0 for the stage breadcrumbs. Bring-up and the frontend swap+ # are separate tool processes, so each timed from its own start and+ # their `+NNNs` lines couldn't be read as one timeline. Anchoring both+ # here makes the whole job one clock. Computed in a step rather than+ # a job-level env because no `github` context field is reliably epoch+ # seconds, and a non-numeric value silently falls back to per-process.+ - name: Anchor preview stage timings+ run: echo "HOGBOX_PREVIEW_T0=$(date +%s)" >> "$GITHUB_ENV"++ # Trusted checkout: the tool code that runs with HOG_TOKEN comes from+ # the default branch, never the PR.+ # A blip is infra: bring-up then fails into the failure reporter, not a red X.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ continue-on-error: true+ with:+ ref: ${{ github.event.repository.default_branch }}++ - name: Connect to Tailscale (tag:hogland-ci)+ id: tailnet+ continue-on-error: 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+ id: token+ if: steps.tailnet.outcome == 'success'+ continue-on-error: true+ # Retry the mint across transient GitHub OIDC hiccups (a ~12-min+ # outage on 2026-07-09 leaked two preview pens). curl -sf makes an+ # HTTP error a non-zero exit, but a `curl | jq` pipe takes jq's exit+ # — and jq succeeds on empty input — so the empty-token guard is the+ # load-bearing backstop AFTER the retries, never dropped.+ run: |+ token=""+ for attempt in 1 2 3; do+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value') || token=""+ [ -n "$token" ] && [ "$token" != "null" ] && break+ echo "::warning::OIDC mint attempt ${attempt} failed; retrying"+ [ "$attempt" -lt 3 ] && sleep 5+ done+ [ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::OIDC mint failed after 3 attempts"; 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: ./.github/actions/setup-uv+ with:+ enable-cache: false+ id: uv+ if: steps.token.outcome == 'success'+ continue-on-error: true++ - name: Bring up preview+ id: build+ if: steps.uv.outcome == 'success'+ continue-on-error: true+ run: |+ # Restore the golden, check out the PR, mount its backend source+ # (posthog/ee/products) over the :master image's /code,+ # delta-migrate. No per-PR image, and NO frontend dist here — the+ # frontend is swapped in afterwards (once build-frontend finishes,+ # below) so this step runs in parallel with the FE build. The tool+ # streams `[hogbox-preview +NNNs] <stage>` lines to STDERR for+ # per-stage visibility; stdout stays the url=/box_id=/pen_id= contract.+ 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)+ echo "$out"+ {+ echo "url=$(echo "$out" | sed -n 's/^url=//p')"+ echo "box_id=$(echo "$out" | sed -n 's/^box_id=//p')"+ echo "pen_id=$(echo "$out" | sed -n 's/^pen_id=//p')"+ } >> "$GITHUB_OUTPUT"+ working-directory: tools/hogbox-preview++ # The box is healthy on the :master SPA. NOW block on build-frontend:+ # poll THIS run's jobs for the `build PR frontend` job until it has a+ # conclusion. failure/cancelled/timed_out → fail (the failure reporter+ # flips the CI report section + Deployment). success WITH the dist artifact →+ # swap the PR frontend in. success WITHOUT the artifact, or skipped →+ # the PR didn't touch the frontend, keep :master (no swap). By now the+ # FE build has usually long finished, so this returns near-instantly.+ - name: Wait for the PR frontend build+ id: fe+ if: steps.build.outcome == 'success'+ continue-on-error: true+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0+ with:+ script: |+ // Must match the build-frontend job's `name:` exactly.+ const jobName = '[Optional] build PR frontend';+ // Ceiling must cover build-frontend's own 30m timeout PLUS+ // queue time, minus the ~6m of bring-up already elapsed;+ // 32m keeps us inside deploy's 40m job timeout with margin.+ const deadline = Date.now() + 32 * 60 * 1000;+ let conclusion = null;+ while (Date.now() < deadline) {+ // No pagination: a preview run has a handful of jobs, so+ // one per_page:100 call always sees them all.+ const { data } = await github.rest.actions.listJobsForWorkflowRun(+ { ...context.repo, run_id: context.runId, per_page: 100 });+ const job = data.jobs.find(j => j.name === jobName);+ if (job && job.status === 'completed') { conclusion = job.conclusion; break; }+ await new Promise(r => setTimeout(r, 10000));+ }+ if (conclusion === null) {+ core.setFailed(`Timed out waiting for '${jobName}' to finish`);+ return;+ }+ core.info(`'${jobName}' concluded: ${conclusion}`);+ if (conclusion !== 'success' && conclusion !== 'skipped') {+ // failure / cancelled / timed_out — don't post a green preview.+ core.setFailed(`Frontend build ${conclusion} — failing deploy so the failure reporter runs`);+ return;+ }+ // Only a success can have produced a dist artifact; skipped never does.+ let swap = false;+ if (conclusion === 'success') {+ const { data: artData } = await github.rest.actions.listWorkflowRunArtifacts(+ { ...context.repo, run_id: context.runId, per_page: 100 });+ swap = artData.artifacts.some(a => a.name === 'hogbox-preview-frontend-dist');+ }+ core.info(`frontend swap needed: ${swap}`);+ core.setOutput('swap', swap ? 'true' : 'false');++ - name: Download frontend dist+ id: dist+ if: steps.fe.outputs.swap == 'true'+ continue-on-error: true+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0+ with:+ name: hogbox-preview-frontend-dist+ path: ${{ runner.temp }}/fe-dist++ - name: Swap in the PR frontend+ id: swap+ if: steps.dist.outcome == 'success'+ continue-on-error: true+ working-directory: tools/hogbox-preview+ run: |+ # Lay the freshly-built dist over the running box + re-collectstatic.+ # Resolves the live box by pen name (preview-pr-<n>) — no restore.+ uv run --no-project --with posthog-hogland==0.3.0 --python 3.12 \+ python -m hogbox_preview \+ --host "$HOG_HOST" \+ --name "preview-pr-${PR}" \+ swap-frontend --frontend-dist "${RUNNER_TEMP}/fe-dist/frontend-dist.tgz"++ # dist/swap are 'skipped' on a backend-only PR, which passes; 'failure'+ # would serve :master under a section claiming the PR's frontend.+ - name: Decide preview outcome+ id: outcome+ if: ${{ !cancelled() }}+ env:+ BRING_UP: ${{ steps.build.outcome }}+ FE_WAIT: ${{ steps.fe.outcome }}+ DIST: ${{ steps.dist.outcome }}+ SWAP: ${{ steps.swap.outcome }}+ run: |+ ok=false+ if [ "$BRING_UP" = success ] && [ "$FE_WAIT" = success ] \+ && [ "$DIST" != failure ] && [ "$SWAP" != failure ]; then+ ok=true+ fi+ echo "bring-up=$BRING_UP fe-wait=$FE_WAIT dist=$DIST swap=$SWAP -> ok=$ok"+ echo "ok=$ok" >> "$GITHUB_OUTPUT"++ # Reporting is auxiliary: an API blip must not red a preview that came up.+ - name: Report ready (deployment)+ id: ready+ if: steps.outcome.outputs.ok == 'true'+ continue-on-error: true+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0+ # DEP comes from the job env (announce job outputs).+ env:+ URL: ${{ steps.build.outputs.url }}+ with:+ script: |+ const url = process.env.URL;+ const environment = process.env.DEPLOY_ENVIRONMENT;+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;+ // Honest wall-clock: run start (≈ the push) → now (usable).+ // The full pipeline time a reviewer actually waited, not just+ // the bring-up seconds — the FE build runs under it in parallel.+ const run = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: context.runId });+ const startedAt = run.data.run_started_at || run.data.created_at;+ const secs = Math.max(0, Math.round((Date.now() - new Date(startedAt).getTime()) / 1000));+ core.setOutput('secs', String(secs));+ 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',+ // The environment is shared across PRs, so this status must never inactivate another PR's deployment.+ auto_inactive: false,+ });+ }++ # SHA comes from the job env (announce job outputs).+ - name: Post ready section+ if: steps.outcome.outputs.ok == 'true'+ continue-on-error: true+ env:+ GITHUB_TOKEN: ${{ github.token }}+ PR_NUMBER: ${{ env.PR }}+ URL: ${{ steps.build.outputs.url }}+ BOX: ${{ steps.build.outputs.box_id }}+ PEN: ${{ steps.build.outputs.pen_id }}+ SWAP: ${{ steps.fe.outputs.swap }}+ READY_SECONDS: ${{ steps.ready.outputs.secs }}+ # The hogland admin/console host (same value as the OIDC audience).+ CONSOLE_HOST: ${{ env.HOG_OIDC_AUDIENCE }}+ run: node .github/scripts/post-hogbox-preview-section.mjs ready++ # Load-bearing: runs on the very failures the chain above swallows, so an+ # unguarded API call would hand the red X straight back.+ - name: Report failure (deployment)+ if: steps.outcome.outputs.ok != 'true'+ continue-on-error: true+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0+ with:+ script: |+ const environment = process.env.DEPLOY_ENVIRONMENT;+ 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',+ });+ }++ - name: Post failure section+ if: steps.outcome.outputs.ok != 'true'+ continue-on-error: true+ env:+ GITHUB_TOKEN: ${{ github.token }}+ PR_NUMBER: ${{ env.PR }}+ run: node .github/scripts/post-hogbox-preview-section.mjs failed++ # ----------------------------------------------------------------------------+ # Fast-path teardown, decided by the `decide` job: the `hogbox-preview` label+ # was removed. Destroys 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: '[Optional] 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+ # removed.+ 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 CI report section 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.+ # Fails open throughout: a missed destroy is reaped by the daily sweep in+ # hogbox-preview-cleanup.yml, so hogland being down never reds the PR.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ continue-on-error: true+ with:+ ref: ${{ github.event.repository.default_branch }}+ - name: Connect to Tailscale (tag:hogland-ci)+ continue-on-error: 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+ continue-on-error: true+ # Same retry + empty-token guard as the deploy job: a mint that+ # silently yields an empty token here would make the destroy fail+ # with "no API token provided" and leak the box + pen.+ run: |+ token=""+ for attempt in 1 2 3; do+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value') || token=""+ [ -n "$token" ] && [ "$token" != "null" ] && break+ echo "::warning::OIDC mint attempt ${attempt} failed; retrying"+ [ "$attempt" -lt 3 ] && sleep 5+ done+ [ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::OIDC mint failed after 3 attempts"; exit 1; }+ echo "::add-mask::$token"+ echo "HOG_TOKEN=$token" >> "$GITHUB_ENV"+ - uses: ./.github/actions/setup-uv+ with:+ enable-cache: false+ continue-on-error: true+ - name: Destroy preview box + pen+ continue-on-error: 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++ # Don't leave a green "ready" Deployment + section pointing at a box+ # that no longer exists: mark every deployment of this PR inactive+ # and flip the CI report section.+ - name: Deactivate deployment+ if: always()+ continue-on-error: true+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0+ with:+ script: |+ const pr = Number(process.env.PR);+ const environment = process.env.DEPLOY_ENVIRONMENT;+ const deployments = await github.paginate(github.rest.repos.listDeployments,+ { ...context.repo, environment, task: `preview-pr-${pr}`, 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',+ });+ }++ - name: Post torn-down section+ if: always()+ continue-on-error: true+ env:+ GITHUB_TOKEN: ${{ github.token }}+ PR_NUMBER: ${{ env.PR }}+ run: node .github/scripts/post-hogbox-preview-section.mjs torn-downdiff --git a/.github/workflows/pr-closed.yml b/.github/workflows/pr-closed.ymlindex 9fbf6a961a8f..90fd0316bc56 100644--- a/.github/workflows/pr-closed.yml+++ b/.github/workflows/pr-closed.yml@@ -24,6 +24,76 @@ 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. Previews are+ # label-only, so a PR without the label has nothing to destroy. Removing+ # the label already tore its preview down, and the daily stale-sweep in+ # hogbox-preview-cleanup.yml is the backstop. Idempotent — a no-op if+ # nothing is up.+ if: >-+ contains(github.event.pull_request.labels.*.name, 'hogbox-preview')+ && github.event.pull_request.head.repo.full_name == github.repository+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ permissions:+ contents: read+ id-token: write # OIDC for the tailnet join + hogplane token+ env:+ HOG_HOST: https://hogland-dev.hedgehog-kitefin.ts.net+ HOG_OIDC_AUDIENCE: hogland.dev.posthog.dev+ PR: ${{ github.event.pull_request.number }}+ steps:+ # 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.+ #+ # The teardown imports only tools/hogbox-preview and the external+ # posthog-hogland SDK, so a sparse blobless checkout of that+ # directory replaces a full clone of the monorepo. The checkout+ # also includes .github/actions/setup-uv because a step can only+ # use a local action that exists in the workspace.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.event.repository.default_branch }}+ sparse-checkout: |+ tools/hogbox-preview/+ .github/actions/setup-uv/+ sparse-checkout-cone-mode: false+ filter: blob:none+ - 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+ # `curl | jq` takes jq's exit code, and jq succeeds on empty input,+ # so a transient OIDC outage can yield an empty token. Retry the+ # mint, and keep the empty-token guard as the hard backstop.+ run: |+ token=""+ for attempt in 1 2 3; do+ token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \+ "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value') || token=""+ [ -n "$token" ] && [ "$token" != "null" ] && break+ echo "::warning::OIDC mint attempt ${attempt} failed; retrying"+ [ "$attempt" -lt 3 ] && sleep 5+ done+ [ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::OIDC mint failed after 3 attempts"; exit 1; }+ 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: ./.github/actions/setup-uv+ with:+ enable-cache: false+ - 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+disable-canary-flags:name: Disable feature flags canaryif: contains(github.event.pull_request.labels.*.name, 'canary-flags')diff --git a/tools/hogbox-preview/README.md b/tools/hogbox-preview/README.mdindex b38f5955eb27..1819722771e7 100644--- a/tools/hogbox-preview/README.md+++ b/tools/hogbox-preview/README.md@@ -22,9 +22,9 @@ The thing that changes when we swap providers is small and isolated:```pythonfrom hogbox_preview import HoglandBackend, PostHogPreviewStack-backend = HoglandBackend(host="https://hogland.hedgehog-kitefin.ts.net", name="preview-pr-123")+backend = HoglandBackend(host="https://hogland-dev.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)+print(url) # https://pen-….boxes.hogland.dev.posthog.dev/ (stable across rebuilds)```## How it actually works@@ -82,12 +82,24 @@ placement holds its name for up to an hour), so any reused box name would makea placement retry 409 against its own corpse. Leftover boxes are reaped afterthe new box comes up and on teardown.-## Running a preview+## Getting a preview-No CI workflow builds previews.-Run the tool by hand against a hogland cluster (see [CLI](#cli)), and destroy the box when you are done.+Previews are opt-in and run on the dev hogland cluster.+Add the **`hogbox-preview`** label to a same-repo PR, draft or ready, and `hogbox-preview-env.yml` builds one for any paths.+While the label stays on, every push rebuilds the preview.+Fork PRs never get one, even when labeled, because the build would run fork code with the hogland token in scope.+GitHub cannot filter a label trigger by name, so the workflow dispatches on every `labeled`, `unlabeled`, `synchronize` and `reopened` event, and a job-level `if:` skips every PR without the label before a runner starts.+Rapid pushes coalesce through a per-PR `concurrency` group on the deploy job.-## Hibernation & wake (why autos are affordable)+## Reporting & lifecycle++- **PR comment**: a `Hogbox preview` section in the shared `🤖 CI report` comment (`.github/scripts/post-hogbox-preview-section.mjs`), staged building → ready → failed → torn down, with the URL, login, and what's running.+- **GitHub Deployment**: a `preview-pr-<n>` task in the shared `hogbox-preview` environment (in_progress → success/failure + URL), so the preview shows in the PR's Deployments UI.+- **Teardown**: removing the label destroys box + pen, and so does closing a labeled PR (`pr-closed.yml`).+ A daily stale-sweep (`cleanup-stale`) in `hogbox-preview-cleanup.yml` reaps previews whose PR closed but slipped through.+ It is its own workflow because the OIDC mint needs `id-token: write`, which can't live in the reusable `pr-cleanup.yml`.++## Hibernation & wake (why previews are affordable)Every preview pen is created with `on_idle=hibernate` + `wake=on-request` (bothre-asserted on each push). After ~30 min idle (the `--ttl-seconds` window),@@ -97,9 +109,7 @@ edge, which sees a hibernated wake-on-request pen and serves a brief **"wakingup" interstitial** (a polling page for browser navigations, a retry-503 forXHR/asset clients) while it restores the box (~30–40s, a warm restore of the readystack) 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`.+touches the box, so only a genuinely idle one sleeps. See hogland's `docs/PENS.md`.Access is **tailnet-only** (PostHog VPN) — internal reviewers, no public URL.diff --git a/tools/hogbox-preview/hogbox_preview/__main__.py b/tools/hogbox-preview/hogbox_preview/__main__.pyindex 80c5ec88bdb2..83c274ac0429 100644--- a/tools/hogbox-preview/hogbox_preview/__main__.py+++ b/tools/hogbox-preview/hogbox_preview/__main__.py@@ -29,7 +29,7 @@ from . import timingfrom .hogland_backend import HoglandBackendfrom .stack import PostHogPreviewStack-DEFAULT_HOST = os.environ.get("HOG_HOST", "https://hogland.hedgehog-kitefin.ts.net")+DEFAULT_HOST = os.environ.get("HOG_HOST", "https://hogland-dev.hedgehog-kitefin.ts.net")def build_backend(args: argparse.Namespace) -> HoglandBackend: