: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): stop hogbox preview creates 409ing against their own failed attempts (#70349)
Julian Bezcce761568585
diff --git a/tools/hogbox-preview/README.md b/tools/hogbox-preview/README.mdindex 01073d423448..d5ff068224dd 100644--- a/tools/hogbox-preview/README.md+++ b/tools/hogbox-preview/README.md@@ -63,6 +63,13 @@ box-http edge resolves to whatever box currently backs the pen — so **areviewer's link survives every re-push** (the box swaps underneath). Requireshogland's pen-id edge routing (shipped in hogland #319).+Only the _pen_ name is deterministic. Each box gets a unique name — a fresh+`preview-pr-<n>-<6hex>` per create _attempt_, including 5xx retries — because+hogland enforces per-owner name uniqueness across all box statuses (a failed+placement holds its name for up to an hour), so any reused box name would make+a placement retry 409 against its own corpse. Leftover boxes are reaped after+the new box comes up and on teardown.+## Auto-previews & opt-outFrontend PRs get a preview **automatically** — no label needed. A cheap,diff --git a/tools/hogbox-preview/hogbox_preview/__main__.py b/tools/hogbox-preview/hogbox_preview/__main__.pyindex 2d853e2a1107..19b81bb17e3a 100644--- a/tools/hogbox-preview/hogbox_preview/__main__.py+++ b/tools/hogbox-preview/hogbox_preview/__main__.py@@ -181,7 +181,9 @@ def main(argv: list[str] | None = None) -> int: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)"+ "--name",+ default="posthog-preview",+ help="pen name / preview identity (e.g. preview-pr-123); boxes get a unique suffix",)# Sizing MUST match the golden snapshot being restored ("omit to inherit" is# broken server-side). Defaults match the preview golden (snap-753bb8b3eeef,diff --git a/tools/hogbox-preview/hogbox_preview/hogland_backend.py b/tools/hogbox-preview/hogbox_preview/hogland_backend.pyindex 522db7c13819..d9fa837e640e 100644--- a/tools/hogbox-preview/hogbox_preview/hogland_backend.py+++ b/tools/hogbox-preview/hogbox_preview/hogland_backend.py@@ -26,8 +26,10 @@ un-exposed ``--box-id`` box.from __future__ import annotationsimport os+import reimport jsonimport time+import uuidimport shleximport pathlibimport tempfile@@ -108,8 +110,13 @@ class HoglandBackend(PreviewBackend):self.memory_mib = memory_mibself.disk_gib = disk_gibself.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.+ # `name` is the deterministic PEN name (e.g. preview-pr-123) — the stable+ # identity, conflict-free by design. The box name is NOT this: hogland+ # enforces per-owner name uniqueness across ALL box statuses (failed+ # included), and a failed placement holds its name for up to an hour, so a+ # deterministic box name makes a retry 409 against its own corpse. Each+ # created box gets `<name>-<6hex>` instead (see _create_kwargs), unique per+ # attempt. 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).@@ -129,10 +136,10 @@ class HoglandBackend(PreviewBackend):self._wait_exec_ready()timing.stage("box exec ready")return- # Stable identity first, then a fresh box from the golden. _restore_fresh- # reaps a stale same-named box (a leaked prior run) via its ConflictError- # path, so at most one box holds the name at a time; we then point the pen- # at the new box. The pen outlives the box across pushes.+ # Stable identity first, then a fresh box from the golden. Each box gets a+ # per-attempt unique name (so a failed placement can't block a retry), and+ # we reap the leftovers once the new box is exec-ready. The pen outlives+ # the box across pushes.timing.stage("pen resolve/create")self._ensure_pen()timing.stage("box restore start")@@ -159,6 +166,19 @@ class HoglandBackend(PreviewBackend):on_idle="hibernate",wake="on-request",)+ # Now that the pen points at the new box, sweep the leftovers: prior+ # attempts of THIS run (each restore attempt uses a fresh unique name, and+ # a failed one leaves a corpse holding it for up to an hour) plus corpses+ # from failed runs of the old deterministic-name code. Best-effort.+ self._reap_leftovers()++ def _box_name(self) -> str:+ # A per-attempt unique box name: `<pen-name>-<6hex>`. hogland's name+ # uniqueness spans failed boxes and a failed placement holds its name for+ # up to an hour, so reusing a name (deterministic, or even per-instance)+ # would make the 5xx retry 409 against its own corpse. Regenerate for+ # every create attempt so retries never self-conflict.+ return f"{self.name}-{uuid.uuid4().hex[:6]}"def _create_kwargs(self) -> dict:# The golden is pinned to this sizing; restore must MATCH it exactly.@@ -170,7 +190,7 @@ class HoglandBackend(PreviewBackend):"disk_class": self.disk_class,"access_type": AccessType.ssh_public,"ssh_public_key": _ephemeral_ssh_pubkey(),- "name": self.name,+ "name": self._box_name(),"kind": self.kind,"ttl_seconds": self.ttl_seconds,# HTTP-expose the web port so the box gets its own box-front hostname@@ -183,12 +203,11 @@ class HoglandBackend(PreviewBackend):Placement can fail on a node death mid-restore (OOM / drain) and comesback 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."""+ real client error (bad spec) that a retry won't fix, so it propagates+ immediately. Each attempt draws a fresh unique box name via+ _create_kwargs, so a 5xx-failed attempt — which leaves a failed box+ holding its name for up to an hour — can't make the retry 409 against its+ own corpse."""for attempt in range(_CREATE_5XX_ATTEMPTS):try:return self._client.create(**self._create_kwargs())@@ -200,43 +219,12 @@ class HoglandBackend(PreviewBackend):raise RuntimeError("unreachable")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._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.- 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._create()- except ConflictError:- time.sleep(3)+ """Restore the golden into a new box.++ Box names are per-attempt unique (`<pen-name>-<6hex>`), so a create can no+ longer 409 against a corpse left by a prior run or a prior 5xx attempt —+ which killed the old resolve-stale/delete/retry dance this used to need.+ Leftover corpses are swept in provision() after the pen is repointed."""return self._create()def attach(self) -> None:@@ -344,22 +332,30 @@ class HoglandBackend(PreviewBackend):return self._pen.id if (self._pen is not None and self._pen.id) else Nonedef 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.+ # PR-close teardown: drop every box this preview left behind, then release+ # the stable identity. delete_pen does NOT cascade, so the boxes 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.+ # deleting it can raise NotFoundError — and a transient 5xx here is just+ # as fatal to teardown. Swallow everything so we always reach delete_pen —+ # otherwise the pen leaks forever, which is the exact thing this method+ # exists to prevent. A box left behind is the smaller loss: its 24h TTL+ # reaps it.try:box = self._resolve_box()if box is not None:box.delete()except NotFoundError:pass+ except Exception as e: # noqa: BLE001 — TTL reaper is the backstop+ timing.stage(f"warn: couldn't delete current box during teardown: {e}")+ # Sweep any other name-matched boxes too (a push that failed after create+ # but before repoint leaves a corpse the pen never pointed at).+ self._reap_leftovers()try:self._client.delete_pen(self.name)except NotFoundError:@@ -481,9 +477,48 @@ class HoglandBackend(PreviewBackend):raise RuntimeError("provision() must run before the box is usable")return self._box+ def _name_matches(self, box_name: str | None) -> bool:+ # A box belongs to this preview if its name is exactly the pen name+ # (a legacy box from before per-box names) or the pen name plus exactly+ # the 6-hex attempt tag _box_name() mints. Anchoring on the full suffix+ # shape (not a bare prefix) keeps pen names that nest — "foo" vs+ # "foo-bar" — from cross-matching each other's boxes.+ if not box_name:+ return False+ if box_name == self.name:+ return True+ return re.fullmatch(re.escape(self.name) + r"-[0-9a-f]{6}", box_name) is not None++ def _reap_leftovers(self) -> None:+ """Best-effort delete every OTHER box owned by this preview — corpses from+ failed attempts of this run (each restore attempt uses a fresh unique+ name) and from failed runs of the old deterministic-name code. Never+ touches the just-created box (self._box_id). ALL errors are swallowed —+ including the list call itself failing — because a reap hiccup must not+ fail a working preview (provision calls this after the pen is repointed)+ nor block pen deletion (destroy calls this before delete_pen). The box's+ own 24h idle TTL is the backstop."""+ try:+ leftovers = [+ v.id+ for v in self._client.iter_boxes()+ if v.id != self._box_id and self._name_matches(getattr(v.spec, "name", None))+ ]+ except Exception as e: # noqa: BLE001 — TTL reaper is the backstop+ timing.stage(f"warn: couldn't list boxes to reap leftovers: {e}")+ return+ for box_id in leftovers:+ try:+ self._client.get(box_id).delete()+ except Exception as e: # noqa: BLE001 — TTL reaper is the backstop+ timing.stage(f"warn: couldn't reap leftover box {box_id}: {e}")+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."""+ current pointer, or — last resort — a name scan over live boxes matching+ this preview's name (exact or `<name>-` prefix), preferring a running box.+ Used by attach() (swap-frontend) and destroy() when the pen pointer is+ missing or dangling."""if self._box is not None:return self._boxif self._box_id:@@ -497,9 +532,18 @@ class HoglandBackend(PreviewBackend):return self._client.get(pen.current_box_id)except NotFoundError:pass # no pen, or its box was already reaped — fall through+ # iter_boxes returns newest-first; take the first name match, but+ # prefer a running one over a corpse if the list view carries status.+ fallback_id = Nonefor v in self._client.iter_boxes():- if getattr(v.spec, "name", None) == self.name:+ if not self._name_matches(getattr(v.spec, "name", None)):+ continue+ if getattr(v, "status", None) == "running":return self._client.get(v.id)+ if fallback_id is None:+ fallback_id = v.id+ if fallback_id is not None:+ return self._client.get(fallback_id)return Nonedef _wait_exec_ready(self, *, timeout: int = 300, interval: int = 5) -> None:diff --git a/tools/hogbox-preview/tests/test_hogland_backend.py b/tools/hogbox-preview/tests/test_hogland_backend.pyindex 407adf0daf39..20b834e33661 100644--- a/tools/hogbox-preview/tests/test_hogland_backend.py+++ b/tools/hogbox-preview/tests/test_hogland_backend.py@@ -27,8 +27,23 @@ class _FakePen:self.id = "pen-deadbeef"+class _FakeSpec:+ def __init__(self, name: str | None):+ self.name = name+++class _FakeBoxView:+ """What iter_boxes() yields: an id + a spec carrying the box name (+ status)."""++ def __init__(self, box_id: str, name: str | None, status: str = "running"):+ self.id = box_id+ self.spec = _FakeSpec(name)+ self.status = status++class _FakeBox:- def __init__(self, *, delete_raises: Exception | None = None):+ def __init__(self, *, box_id: str = "box-new", delete_raises: Exception | None = None):+ self.id = box_idself._delete_raises = delete_raisesself.deleted = False@@ -40,7 +55,8 @@ class _FakeBox: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."""+ test; every call is recorded so we can assert teardown reached delete_pen and+ reaping deleted the right boxes."""def __init__(self, *, get=None, get_pen=None, boxes=None, create=None, update_pen=None):self._get = get@@ -50,6 +66,7 @@ class _FakeClient:self._update_pen = update_penself.deleted_pens: list[str] = []self.update_pen_calls: list[dict] = []+ self.deleted_box_ids: list[str] = []def get(self, box_id):if callable(self._get):@@ -79,27 +96,161 @@ class _FakeClient:return self._update_pen+def _make_backend(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++@unittest.skipUnless(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."""+class BoxNameIsUniquePerAttemptTest(unittest.TestCase):+ """Box names must NOT equal the pen name: hogland enforces per-owner name+ uniqueness across ALL statuses (failed included), and a failed placement+ holds its name for up to an hour — so a deterministic name makes the 5xx+ retry 409 against its own corpse. Each create attempt gets a fresh unique+ suffix so a failed attempt can't block the retry."""++ def _stub_ssh(self):+ from hogbox_preview import hogland_backend- def _backend(self, client):- from hogbox_preview.hogland_backend import HoglandBackend+ return unittest.mock.patch.object(+ hogland_backend, "_ephemeral_ssh_pubkey", return_value="ssh-ed25519 AAAA fake"+ )++ def test_create_name_has_unique_suffix(self):+ client = _FakeClient()+ backend = _make_backend(client)+ with self._stub_ssh():+ kwargs = backend._create_kwargs()+ self.assertRegex(kwargs["name"], r"^preview-pr-999-[0-9a-f]{6}$")++ def test_two_attempts_use_different_suffixes(self):+ # A 5xx-failed attempt leaves a failed box holding its unique name; the+ # retry must NOT reuse that exact name, so the suffix is regenerated per+ # create attempt.+ from hogbox_preview import hogland_backend+ from hogland import ServerError++ seen_names: list[str] = []+ attempts = {"n": 0}+ created = _FakeBox()- backend = HoglandBackend(host="https://example.invalid", name="preview-pr-999", token="test-token")- backend._client = client+ def create(**kwargs):+ seen_names.append(kwargs["name"])+ attempts["n"] += 1+ if attempts["n"] == 1:+ raise ServerError("placement failed: place: EOF", status_code=500)+ return created++ client = _FakeClient(create=create)+ backend = _make_backend(client)+ with self._stub_ssh(), unittest.mock.patch.object(hogland_backend.time, "sleep"):+ result = backend._restore_fresh()++ self.assertIs(result, created)+ self.assertEqual(len(seen_names), 2)+ self.assertNotEqual(seen_names[0], seen_names[1])+ for name in seen_names:+ self.assertRegex(name, r"^preview-pr-999-[0-9a-f]{6}$")++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class ProvisionReapsLeftoversTest(unittest.TestCase):+ """After the pen is repointed at the new box, best-effort reap every OTHER+ box whose name equals the pen name (legacy corpses) or starts with the pen+ name + '-' (this-tool corpses from failed runs) — never the just-created+ box."""++ def _backend_ready_to_reap(self, client, new_box):+ backend = _make_backend(client)+ # Pretend provision() already restored + repointed; drive reaping directly.+ backend._box = new_box+ backend._box_id = new_box.id+ backend._pen = _FakePen(current_box_id=new_box.id)return backend+ def test_reaps_exact_and_prefix_named_boxes(self):+ new_box = _FakeBox(box_id="box-new")+ deleted_handles: dict[str, _FakeBox] = {}++ boxes = [+ _FakeBoxView("box-new", "preview-pr-999-aaaaaa"), # the just-created box — keep+ _FakeBoxView("box-legacy", "preview-pr-999"), # legacy exact-name corpse+ _FakeBoxView("box-corpse", "preview-pr-999-bbbbbb"), # failed-run corpse+ _FakeBoxView("box-other", "preview-pr-1000-cccccc"), # different pen — keep+ ]++ def get(box_id):+ h = _FakeBox(box_id=box_id)+ deleted_handles[box_id] = h+ return h++ client = _FakeClient(get=get, boxes=boxes)+ backend = self._backend_ready_to_reap(client, new_box)++ backend._reap_leftovers()++ deleted = {bid for bid, h in deleted_handles.items() if h.deleted}+ self.assertEqual(deleted, {"box-legacy", "box-corpse"})+ self.assertFalse(new_box.deleted)++ def test_never_matches_other_previews_boxes(self):+ # Nested names must not cross-match: preview-pr-99 owns neither+ # preview-pr-999's boxes nor anything without the exact 6-hex tag.+ from hogbox_preview.hogland_backend import HoglandBackend++ backend = HoglandBackend(host="https://example.invalid", name="preview-pr-99", token="test-token")+ self.assertTrue(backend._name_matches("preview-pr-99"))+ self.assertTrue(backend._name_matches("preview-pr-99-abc123"))+ self.assertFalse(backend._name_matches("preview-pr-999-abc123")) # other preview's box+ self.assertFalse(backend._name_matches("preview-pr-99-abc123-extra")) # not our tag shape+ self.assertFalse(backend._name_matches("preview-pr-99-ABC123")) # tag is lowercase hex++ def test_reap_failure_does_not_raise(self):+ from hogland import NotFoundError++ new_box = _FakeBox(box_id="box-new")+ boxes = [_FakeBoxView("box-corpse", "preview-pr-999-bbbbbb")]++ def get(_box_id):+ raise NotFoundError("box gone", status_code=404)++ client = _FakeClient(get=get, boxes=boxes)+ backend = self._backend_ready_to_reap(client, new_box)++ # Must not raise even though the per-box delete path blows up.+ backend._reap_leftovers()++ def test_list_failure_does_not_raise(self):+ # The list call itself failing (transient 5xx while enumerating boxes)+ # must be swallowed too — provision() reaps after the preview is already+ # working, so a reap hiccup must not fail the run.+ class _ListBoom(_FakeClient):+ def iter_boxes(self):+ raise RuntimeError("hogland API error (HTTP 502)")++ new_box = _FakeBox(box_id="box-new")+ backend = self._backend_ready_to_reap(_ListBoom(), new_box)++ backend._reap_leftovers()++[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class DestroyReleasesPenTest(unittest.TestCase):+ """destroy() must delete the pen's box AND all name-matched boxes, then always+ reach delete_pen — a box already TTL-reaped counts as 'already gone', it must+ not abort teardown and leak the pen."""+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 NotFoundErrordef 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 = _make_backend(client)backend._box_id = "box-reaped" # forces _resolve_box down the direct get() pathbackend.destroy()@@ -107,22 +258,34 @@ class DestroyReleasesPenTest(unittest.TestCase):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 NotFoundErrorbox = _FakeBox(delete_raises=NotFoundError("box gone", status_code=404))client = _FakeClient()- backend = self._backend(client)+ backend = _make_backend(client)backend._box = box # _resolve_box short-circuits to the live handlebackend.destroy()self.assertEqual(client.deleted_pens, ["preview-pr-999"])+ def test_pen_released_when_box_delete_5xxs(self):+ # Teardown is best-effort all the way: a transient server error deleting+ # the box must not abort before delete_pen (the box has a TTL, the pen+ # doesn't).+ box = _FakeBox(delete_raises=RuntimeError("hogland API error (HTTP 502)"))+ client = _FakeClient()+ backend = _make_backend(client)+ backend._box = box++ 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 = _make_backend(client)backend._box = boxbackend.destroy()@@ -130,92 +293,101 @@ class DestroyReleasesPenTest(unittest.TestCase):self.assertTrue(box.deleted)self.assertEqual(client.deleted_pens, ["preview-pr-999"])+ def test_pen_released_when_leftover_listing_fails(self):+ # A transient 5xx while listing boxes for the leftover sweep must not+ # abort teardown before delete_pen — that would leak the pen forever+ # (teardown only runs on PR close).+ class _ListBoom(_FakeClient):+ def iter_boxes(self):+ raise RuntimeError("hogland API error (HTTP 502)")[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."""+ box = _FakeBox()+ backend = _make_backend(_ListBoom())+ backend._box = box # _resolve_box short-circuits, only the reap lists- def _backend(self, client):- from hogbox_preview.hogland_backend import HoglandBackend+ backend.destroy()- backend = HoglandBackend(host="https://example.invalid", name="preview-pr-999", token="test-token")- backend._client = client- return backend+ self.assertTrue(box.deleted)+ self.assertEqual(backend._client.deleted_pens, ["preview-pr-999"])- def test_retries_create_when_stale_box_already_gone(self):- from hogland import ConflictError, NotFoundError+ def test_deletes_all_name_matched_boxes(self):+ # No live handle / pen pointer: destroy() should still sweep every box+ # whose name exact- or prefix-matches, then delete the pen.+ from hogland import NotFoundError- stale_box = _FakeBox(delete_raises=NotFoundError("box gone", status_code=404))- created = object()- attempts = {"n": 0}+ deleted_handles: dict[str, _FakeBox] = {}+ boxes = [+ _FakeBoxView("box-a", "preview-pr-999-aaaaaa"),+ _FakeBoxView("box-legacy", "preview-pr-999"),+ _FakeBoxView("box-other", "preview-pr-1000-cccccc"), # different pen — keep+ ]- def create(**_kwargs):- attempts["n"] += 1- if attempts["n"] == 1:- raise ConflictError("name taken", status_code=409)- return created+ def get_pen(_name):+ raise NotFoundError("no pen", status_code=404)- client = _FakeClient(create=create)- backend = self._backend(client)- backend._box = stale_box # _resolve_box short-circuits to the live handle+ def get(box_id):+ h = _FakeBox(box_id=box_id)+ deleted_handles[box_id] = h+ return h- result = backend._restore_fresh()+ client = _FakeClient(get=get, get_pen=get_pen, boxes=boxes)+ backend = _make_backend(client)- self.assertIs(result, created)+ backend.destroy()++ deleted = {bid for bid, h in deleted_handles.items() if h.deleted}+ self.assertEqual(deleted, {"box-a", "box-legacy"})+ self.assertEqual(client.deleted_pens, ["preview-pr-999"])- 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}[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class ResolveBoxNameScanTest(unittest.TestCase):+ """The last-resort name scan (used by attach() and destroy() when the pen+ pointer is missing/dangling) matches the exact pen name OR the pen-name '-'+ prefix, preferring a running box."""- def create(**_kwargs):- attempts["n"] += 1- if attempts["n"] == 1:- raise ConflictError("name taken", status_code=409)- return created+ def test_prefix_match_fallback(self):+ from hogland import NotFoundError- client = _FakeClient(create=create)- backend = self._backend(client)- backend._box = stale_box+ def get_pen(_name):+ raise NotFoundError("no pen", status_code=404)- result = backend._restore_fresh()+ target = _FakeBox(box_id="box-corpse")+ boxes = [+ _FakeBoxView("box-other", "preview-pr-1000-cccccc"),+ _FakeBoxView("box-corpse", "preview-pr-999-bbbbbb"),+ ]- self.assertIs(result, created)- self.assertTrue(stale_box.deleted)- self.assertEqual(client.update_pen_calls, [{"name": "preview-pr-999", "current_box_id": ""}])+ def get(box_id):+ self.assertEqual(box_id, "box-corpse")+ return target- 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+ client = _FakeClient(get=get, get_pen=get_pen, boxes=boxes)+ backend = _make_backend(client)- stale_box = _FakeBox()- created = object()- attempts = {"n": 0}+ self.assertIs(backend._resolve_box(), target)- def create(**_kwargs):- attempts["n"] += 1- if attempts["n"] == 1:- raise ConflictError("name taken", status_code=409)- return created+ def test_prefers_running_box(self):+ from hogland import NotFoundError- def update_pen(_name, **_kwargs):- raise NotFoundError("no pen yet", status_code=404)+ def get_pen(_name):+ raise NotFoundError("no pen", status_code=404)- client = _FakeClient(create=create, update_pen=update_pen)- backend = self._backend(client)- backend._box = stale_box+ boxes = [+ _FakeBoxView("box-failed", "preview-pr-999-aaaaaa", status="failed"),+ _FakeBoxView("box-running", "preview-pr-999-bbbbbb", status="running"),+ ]- result = backend._restore_fresh()+ target = _FakeBox(box_id="box-running")- self.assertIs(result, created)+ def get(box_id):+ self.assertEqual(box_id, "box-running")+ return target++ client = _FakeClient(get=get, get_pen=get_pen, boxes=boxes)+ backend = _make_backend(client)++ self.assertIs(backend._resolve_box(), target)@unittest.skipUnless(HAVE_SDK, "posthog-hogland SDK not installed")@@ -223,12 +395,12 @@ class CreateRetriesTransient5xxTest(unittest.TestCase):"""A transient placement 5xx (a node dying mid-restore) must be retried ontoa 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+ def _stub_ssh(self):+ from hogbox_preview import hogland_backend- backend = HoglandBackend(host="https://example.invalid", name="preview-pr-999", token="test-token")- backend._client = client- return backend+ return unittest.mock.patch.object(+ hogland_backend, "_ephemeral_ssh_pubkey", return_value="ssh-ed25519 AAAA fake"+ )def test_first_create_500s_second_succeeds(self):from hogbox_preview import hogland_backend@@ -244,10 +416,10 @@ class CreateRetriesTransient5xxTest(unittest.TestCase):return createdclient = _FakeClient(create=create)- backend = self._backend(client)+ backend = _make_backend(client)# Don't actually sleep the backoff in the test.- with unittest.mock.patch.object(hogland_backend.time, "sleep"):+ with self._stub_ssh(), unittest.mock.patch.object(hogland_backend.time, "sleep"):result = backend._restore_fresh()self.assertIs(result, created)@@ -264,13 +436,12 @@ class CreateRetriesTransient5xxTest(unittest.TestCase):raise ServerError("placement failed", status_code=500)client = _FakeClient(create=create)- backend = self._backend(client)+ backend = _make_backend(client)- with unittest.mock.patch.object(hogland_backend.time, "sleep"):+ with self._stub_ssh(), 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):@@ -283,10 +454,11 @@ class CreateRetriesTransient5xxTest(unittest.TestCase):raise ValidationError("bad spec", status_code=422)client = _FakeClient(create=create)- backend = self._backend(client)+ backend = _make_backend(client)- with self.assertRaises(ValidationError):- backend._restore_fresh()+ with self._stub_ssh():+ with self.assertRaises(ValidationError):+ backend._restore_fresh()self.assertEqual(attempts["n"], 1)