Skip to content

: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.

fix(previews): fence stale hogbox teardown (#71052)

Julian Bez90ad2cee55f0
diff --git a/tools/hogbox-preview/hogbox_preview/hogland_backend.py b/tools/hogbox-preview/hogbox_preview/hogland_backend.py
index d9fa837e640e..60b07eaae8a4 100644
--- a/tools/hogbox-preview/hogbox_preview/hogland_backend.py
+++ b/tools/hogbox-preview/hogbox_preview/hogland_backend.py
@@ -35,9 +35,10 @@ import pathlib
import tempfile
import subprocess
import urllib.request
-from urllib.parse import urlsplit
+from urllib.parse import quote, urlsplit
from hogland import AccessType, AuthenticationError, BoxSpec, ConflictError, Hogland, NotFoundError, ServerError
+from hogland._http import raise_for_status
from . import timing
from .backend import ExecResult, PreviewBackend
@@ -137,9 +138,8 @@ class HoglandBackend(PreviewBackend):
timing.stage("box exec ready")
return
# 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.
+ # per-attempt unique name so a failed placement cannot block a retry. The
+ # pen outlives the box across pushes.
timing.stage("pen resolve/create")
self._ensure_pen()
timing.stage("box restore start")
@@ -166,11 +166,6 @@ 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
@@ -332,34 +327,62 @@ class HoglandBackend(PreviewBackend):
return self._pen.id if (self._pen is not None and self._pen.id) else None
def destroy(self) -> None:
- # 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 — 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.
+ # An explicit box id is owned by this invocation. When its pen was
+ # already removed, still release that requested box rather than leaving
+ # it until its TTL.
+ if self._box_id:
+ try:
+ self._delete_pen_if_current_box(self._box_id)
+ return
+ except ConflictError:
+ self._delete_explicit_box()
+ return
+ except NotFoundError:
+ self._delete_explicit_box()
+ return
+
+ # Name-only cleanup is an authoritative teardown for a closed or
+ # opted-out preview, so it intentionally removes the pen's current box.
try:
- box = self._resolve_box()
- if box is not None:
- box.delete()
+ pen = self._client.get_pen(self.name)
+ except NotFoundError:
+ return
+ if not pen.current_box_id:
+ try:
+ self._delete_pen()
+ except NotFoundError:
+ pass
+ except Exception as e:
+ timing.stage(f"warn: couldn't delete empty pen during teardown: {e}")
+ return
+ try:
+ self._delete_pen_if_current_box(pen.current_box_id)
+ except ConflictError:
+ timing.stage("teardown skipped: preview was replaced by a newer run")
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()
+
+ def _delete_pen_if_current_box(self, expected_box_id: str) -> None:
+ # The workflow currently installs an SDK version that predates the
+ # public expected_current_box_id argument. Keep the request explicit so
+ # the safety fence works before that dependency is bumped.
+ response = self._client._http.delete(
+ f"/v1/pens/{quote(self.name, safe='')}",
+ params={"expected_current_box_id": expected_box_id},
+ )
+ raise_for_status(response)
+
+ def _delete_pen(self) -> None:
+ response = self._client._http.delete(f"/v1/pens/{quote(self.name, safe='')}")
+ raise_for_status(response)
+
+ def _delete_explicit_box(self) -> None:
try:
- self._client.delete_pen(self.name)
+ self._client.get(self._box_id).delete()
except NotFoundError:
pass
+ except Exception as e:
+ timing.stage(f"warn: couldn't delete explicit box during teardown: {e}")
# --- pen: the stable identity over the box lifecycle ---------------------
def _ensure_pen(self) -> None:
@@ -489,30 +512,6 @@ class HoglandBackend(PreviewBackend):
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 scan over live boxes matching
diff --git a/tools/hogbox-preview/tests/test_hogland_backend.py b/tools/hogbox-preview/tests/test_hogland_backend.py
index 20b834e33661..fb5911871f2d 100644
--- a/tools/hogbox-preview/tests/test_hogland_backend.py
+++ b/tools/hogbox-preview/tests/test_hogland_backend.py
@@ -156,188 +156,42 @@ class BoxNameIsUniquePerAttemptTest(unittest.TestCase):
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()
-
-
@unittest.skipUnless(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):
+ def test_explicit_box_is_deleted_when_pen_is_missing(self):
from hogland import NotFoundError
- def boom(_box_id):
- raise NotFoundError("box gone", status_code=404)
-
- client = _FakeClient(get=boom, get_pen=_FakePen(current_box_id="box-reaped"))
+ box = _FakeBox(box_id="box-explicit")
+ client = _FakeClient(get=box)
backend = _make_backend(client)
- backend._box_id = "box-reaped" # forces _resolve_box down the direct get() path
-
- backend.destroy()
-
- self.assertEqual(client.deleted_pens, ["preview-pr-999"])
-
- def test_pen_released_when_box_delete_404s(self):
- from hogland import NotFoundError
-
- box = _FakeBox(delete_raises=NotFoundError("box gone", status_code=404))
- client = _FakeClient()
- backend = _make_backend(client)
- backend._box = box # _resolve_box short-circuits to the live handle
-
- backend.destroy()
-
- self.assertEqual(client.deleted_pens, ["preview-pr-999"])
-
- def test_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 = _make_backend(client)
- backend._box = box
+ backend._box_id = box.id
+ backend._delete_pen_if_current_box = unittest.mock.Mock(side_effect=NotFoundError("no pen", status_code=404))
backend.destroy()
self.assertTrue(box.deleted)
- self.assertEqual(client.deleted_pens, ["preview-pr-999"])
+ backend._delete_pen_if_current_box.assert_called_once_with(box.id)
- 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)")
+ def test_explicit_box_is_deleted_when_pen_was_replaced(self):
+ from hogland import ConflictError
- box = _FakeBox()
- backend = _make_backend(_ListBoom())
- backend._box = box # _resolve_box short-circuits, only the reap lists
+ box = _FakeBox(box_id="box-explicit")
+ backend = _make_backend(_FakeClient(get=box))
+ backend._box_id = box.id
+ backend._delete_pen_if_current_box = unittest.mock.Mock(side_effect=ConflictError("pen moved", status_code=409))
backend.destroy()
self.assertTrue(box.deleted)
- self.assertEqual(backend._client.deleted_pens, ["preview-pr-999"])
-
- 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
-
- 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
- ]
+ backend._delete_pen_if_current_box.assert_called_once_with(box.id)
- def get_pen(_name):
- raise NotFoundError("no pen", status_code=404)
-
- def get(box_id):
- h = _FakeBox(box_id=box_id)
- deleted_handles[box_id] = h
- return h
-
- client = _FakeClient(get=get, get_pen=get_pen, boxes=boxes)
- backend = _make_backend(client)
+ def test_name_only_teardown_deletes_empty_pen(self):
+ backend = _make_backend(_FakeClient(get_pen=_FakePen(current_box_id=None)))
+ backend._delete_pen = unittest.mock.Mock()
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"])
+ backend._delete_pen.assert_called_once_with()
@unittest.skipUnless(HAVE_SDK, "posthog-hogland SDK not installed")