: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
fix(devex): harden hogbox preview CI against transient failures (#69893)
Julian Bezeab61b36f192
diff --git a/.github/workflows/hogbox-preview-cleanup.yml b/.github/workflows/hogbox-preview-cleanup.ymlindex 9b41ad1e5bf3..b57cff0ffbb4 100644--- a/.github/workflows/hogbox-preview-cleanup.yml+++ b/.github/workflows/hogbox-preview-cleanup.yml@@ -50,9 +50,20 @@ jobs: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=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \- "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value')+ 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, --withdiff --git a/.github/workflows/hogbox-preview-env.yml b/.github/workflows/hogbox-preview-env.ymlindex cf81769eee7c..a834a8b91bf7 100644--- a/.github/workflows/hogbox-preview-env.yml+++ b/.github/workflows/hogbox-preview-env.yml@@ -440,10 +440,21 @@ jobs:tags: tag:hogland-ci- name: Mint hogland OIDC token+ # 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=$(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; }+ 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"@@ -658,10 +669,21 @@ jobs:audience: ${{ vars.TS_HOGLAND_CI_AUDIENCE }}tags: tag:hogland-ci- name: Mint hogland OIDC token+ # 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=$(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"+ 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: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0with:version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limitdiff --git a/.github/workflows/pr-closed.yml b/.github/workflows/pr-closed.ymlindex c23dd6ffc929..95443c8fb8b2 100644--- a/.github/workflows/pr-closed.yml+++ b/.github/workflows/pr-closed.yml@@ -81,9 +81,22 @@ jobs:tags: tag:hogland-ci- name: Mint hogland OIDC tokenif: steps.gate.outputs.had_preview == 'true'+ # A transient OIDC outage (2026-07-09 ~12:58–13:10 UTC) used to slip+ # an EMPTY token through here: `curl | jq` takes jq's exit code, jq+ # succeeds on empty input, the step passed, and the downstream+ # destroy failed with "no API token provided" — leaking two preview+ # pens (runs 29019106966, 29019621216). Retry the mint to ride out+ # the blip, and keep the empty-token guard as the hard backstop.run: |- token=$(curl -sf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \- "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${HOG_OIDC_AUDIENCE}" | jq -r '.value')+ 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@@ -143,7 +156,14 @@ jobs:pr_age=$((($(date '+%s') - $(date -d "$PR_CREATED_AT" '+%s'))))echo "pr_age=$pr_age" >> $GITHUB_ENV- first_commit_message_in_pr=$(curl -s "$PR_HREF" | jq '.[0].commit.message')+ # The commits endpoint returns an ARRAY on success, but an error+ # OBJECT (rate limit, or a 404 after a force-push-and-close) on+ # failure — and `.[0]` on an object makes jq exit 5, which used+ # to fail the whole run and mask real cleanup failures on the+ # dashboard (4x on 2026-07-09, e.g. run 29040552494). Guard on the+ # type: degrade to an empty message instead of crashing.+ first_commit_message_in_pr=$(curl -s "$PR_HREF" \+ | jq 'if type == "array" and length > 0 then .[0].commit.message else "" end')echo "first_commit_message_in_pr<<EOF" >> $GITHUB_ENVecho "$first_commit_message_in_pr" >> $GITHUB_ENVecho "EOF" >> $GITHUB_ENVdiff --git a/tools/hogbox-preview/hogbox_preview/hogland_backend.py b/tools/hogbox-preview/hogbox_preview/hogland_backend.pyindex 73af21588dd1..4b5b75462ad1 100644--- a/tools/hogbox-preview/hogbox_preview/hogland_backend.py+++ b/tools/hogbox-preview/hogbox_preview/hogland_backend.py@@ -35,7 +35,7 @@ import subprocessimport urllib.requestfrom urllib.parse import urlsplit-from hogland import AccessType, AuthenticationError, BoxSpec, ConflictError, Hogland, NotFoundError+from hogland import AccessType, AuthenticationError, BoxSpec, ConflictError, Hogland, NotFoundError, ServerErrorfrom . import timingfrom .backend import ExecResult, PreviewBackend@@ -46,6 +46,13 @@ from .backend import ExecResult, PreviewBackend_WRITE_FILE_CAP = 64 * 1024 * 1024_WRITE_CHUNK = 48 * 1024 * 1024+# Placement is best-effort server-side: a hogd node can die mid-restore (an OOM,+# a drain) and hogland surfaces it as a 5xx (e.g. `placement failed: ... EOF`).+# The next attempt lands on a healthy node, so retry create/restore on transient+# 5xx only — never on a 4xx, which is a real client error that a retry won't fix.+_CREATE_5XX_ATTEMPTS = 3+_CREATE_5XX_BACKOFF_SECONDS = (5, 15) # slept BEFORE attempts 2 and 3+def _ephemeral_ssh_pubkey() -> str:"""A throwaway ed25519 public key.@@ -171,18 +178,54 @@ class HoglandBackend(PreviewBackend):"web_port": self.web_port,}+ def _create(self):+ """Create/restore the box, retrying transient 5xx ServerErrors only.++ Placement can fail on a node death mid-restore (OOM / drain) and comes+ back as a 5xx; a retry seconds later lands on a healthy node. A 4xx is a+ real client error (bad spec, name conflict) that a retry won't fix, so it+ propagates immediately — ConflictError in particular flows up to+ _restore_fresh's own reap-and-retry loop untouched. That keeps the two+ retry mechanisms from multiplying: a persistent 5xx exhausts these few+ attempts and raises (breaking the ConflictError loop, which never catches+ ServerError), and a ConflictError never triggers this backoff."""+ for attempt in range(_CREATE_5XX_ATTEMPTS):+ try:+ return self._client.create(**self._create_kwargs())+ except ServerError:+ if attempt == _CREATE_5XX_ATTEMPTS - 1:+ raise # out of retries — surface the 5xx+ time.sleep(_CREATE_5XX_BACKOFF_SECONDS[attempt])+ # Unreachable: the loop either returns or raises on the last attempt.+ raise RuntimeError("unreachable")+def _restore_fresh(self):"""Restore the golden into a new box. If our name is already taken, aprior run left a box behind — teardown only fires on PR *close*, so afailed/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())+ return self._create()except ConflictError:try:stale = self._resolve_box()if stale is not None:stale.delete()+ # Close the delete-then-repoint window: stale.delete() just+ # destroyed the box the pen still points at, but the pen is+ # only repointed at the NEW box much later in provision()+ # (after exec-ready). If the run dies in between, the pen+ # dangles at a deleted box. Clear the pointer now, best-effort+ # — the pen may not exist on a first-ever run (NotFoundError),+ # and hogland's reconciler sweep heals a dangling pointer+ # within ~30s regardless, so a failure here must not fail the+ # run (PostHog/hogland#373).+ try:+ self._client.update_pen(self.name, current_box_id="")+ except NotFoundError:+ pass # no pen yet (first-ever run) — nothing to dangle+ except Exception as e: # noqa: BLE001 — the server sweep is the backstop+ timing.stage(f"warn: couldn't clear pen pointer after stale delete: {e}")except NotFoundError:# TTL cleanup or a racing teardown already removed it — the# name is free either way, so fall through to the retry loop.@@ -191,10 +234,10 @@ class HoglandBackend(PreviewBackend):# guard so a lingering ConflictError surfaces instead of being swallowed.for _ in range(10):try:- return self._client.create(**self._create_kwargs())+ return self._create()except ConflictError:time.sleep(3)- return self._client.create(**self._create_kwargs())+ return self._create()def attach(self) -> None:"""Bind to the EXISTING preview box for this pen/name without restoring —diff --git a/tools/hogbox-preview/tests/test_hogland_backend.py b/tools/hogbox-preview/tests/test_hogland_backend.pyindex 8f69ed1af434..407adf0daf39 100644--- a/tools/hogbox-preview/tests/test_hogland_backend.py+++ b/tools/hogbox-preview/tests/test_hogland_backend.py@@ -11,6 +11,7 @@ the SDK import so the monorepo's Django pytest collection can't hard-fail herefrom __future__ import annotationsimport unittest+import unittest.mocktry:import hogland # noqa: F401@@ -41,12 +42,14 @@ class _FakeClient:"""Minimal stand-in for the SDK client. Each method's behaviour is set by thetest; every call is recorded so we can assert teardown reached delete_pen."""- def __init__(self, *, get=None, get_pen=None, boxes=None, create=None):+ def __init__(self, *, get=None, get_pen=None, boxes=None, create=None, update_pen=None):self._get = getself._get_pen = get_penself._boxes = boxes or []self._create = create+ self._update_pen = update_penself.deleted_pens: list[str] = []+ self.update_pen_calls: list[dict] = []def get(self, box_id):if callable(self._get):@@ -69,6 +72,12 @@ class _FakeClient:return self._create(**kwargs)return self._create+ def update_pen(self, name, **kwargs):+ self.update_pen_calls.append({"name": name, **kwargs})+ if callable(self._update_pen):+ return self._update_pen(name, **kwargs)+ return self._update_pen+@unittest.skipUnless(HAVE_SDK, "posthog-hogland SDK not installed")class DestroyReleasesPenTest(unittest.TestCase):@@ -156,6 +165,131 @@ class RestoreFreshHandlesStaleConflictTest(unittest.TestCase):self.assertIs(result, created)+ def test_clears_pen_pointer_after_stale_delete(self):+ # After reaping the stale box, the pen pointer must be cleared right away+ # so the run dying before provision() repoints it doesn't leave the pen+ # dangling at a deleted box.+ from hogland import ConflictError++ stale_box = _FakeBox()+ 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++ result = backend._restore_fresh()++ self.assertIs(result, created)+ self.assertTrue(stale_box.deleted)+ self.assertEqual(client.update_pen_calls, [{"name": "preview-pr-999", "current_box_id": ""}])++ def test_clear_pen_pointer_failure_does_not_abort_run(self):+ # Clearing the pointer is best-effort: the server reconciler sweep is the+ # real backstop, so a failure to clear must not fail the run.+ from hogland import ConflictError, NotFoundError++ stale_box = _FakeBox()+ created = object()+ attempts = {"n": 0}++ def create(**_kwargs):+ attempts["n"] += 1+ if attempts["n"] == 1:+ raise ConflictError("name taken", status_code=409)+ return created++ def update_pen(_name, **_kwargs):+ raise NotFoundError("no pen yet", status_code=404)++ client = _FakeClient(create=create, update_pen=update_pen)+ backend = self._backend(client)+ backend._box = stale_box++ result = backend._restore_fresh()++ self.assertIs(result, created)++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class CreateRetriesTransient5xxTest(unittest.TestCase):+ """A transient placement 5xx (a node dying mid-restore) must be retried onto+ a healthy node, but a 4xx is a real client error and must surface at once."""++ 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_first_create_500s_second_succeeds(self):+ from hogbox_preview import hogland_backend+ from hogland import ServerError++ created = object()+ attempts = {"n": 0}++ def create(**_kwargs):+ attempts["n"] += 1+ if attempts["n"] == 1:+ raise ServerError("placement failed: place: EOF", status_code=500)+ return created++ client = _FakeClient(create=create)+ backend = self._backend(client)++ # Don't actually sleep the backoff in the test.+ with unittest.mock.patch.object(hogland_backend.time, "sleep"):+ result = backend._restore_fresh()++ self.assertIs(result, created)+ self.assertEqual(attempts["n"], 2)++ def test_persistent_500_exhausts_and_raises(self):+ from hogbox_preview import hogland_backend+ from hogland import ServerError++ attempts = {"n": 0}++ def create(**_kwargs):+ attempts["n"] += 1+ raise ServerError("placement failed", status_code=500)++ client = _FakeClient(create=create)+ backend = self._backend(client)++ with unittest.mock.patch.object(hogland_backend.time, "sleep"):+ with self.assertRaises(ServerError):+ backend._restore_fresh()++ # Bounded: exactly _CREATE_5XX_ATTEMPTS, not multiplied by the conflict loop.+ self.assertEqual(attempts["n"], hogland_backend._CREATE_5XX_ATTEMPTS)++ def test_4xx_not_retried(self):+ from hogland import ValidationError++ attempts = {"n": 0}++ def create(**_kwargs):+ attempts["n"] += 1+ raise ValidationError("bad spec", status_code=422)++ client = _FakeClient(create=create)+ backend = self._backend(client)++ with self.assertRaises(ValidationError):+ backend._restore_fresh()++ self.assertEqual(attempts["n"], 1)+if __name__ == "__main__":unittest.main()