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.

feat(devex): time every preview stage, not just some of them (#82537)

Julian Bez80118a80d524
diff --git a/.github/workflows/hogbox-preview-env.yml b/.github/workflows/hogbox-preview-env.yml
index c03f536fc6e8..44f9aa987c6f 100644
--- a/.github/workflows/hogbox-preview-env.yml
+++ b/.github/workflows/hogbox-preview-env.yml
@@ -456,6 +456,15 @@ jobs:
`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.
diff --git a/tools/hogbox-preview/hogbox_preview/__main__.py b/tools/hogbox-preview/hogbox_preview/__main__.py
index 19b81bb17e3a..80c5ec88bdb2 100644
--- a/tools/hogbox-preview/hogbox_preview/__main__.py
+++ b/tools/hogbox-preview/hogbox_preview/__main__.py
@@ -25,6 +25,7 @@ import urllib.request
from hogland import APIError, Hogland
+from . import timing
from .hogland_backend import HoglandBackend
from .stack import PostHogPreviewStack
@@ -111,7 +112,11 @@ def cmd_seed(args: argparse.Namespace) -> int:
def cmd_health(args: argparse.Namespace) -> int:
backend = build_backend(args)
backend.provision()
- backend.wait_http_ok("/_health", expect=200, timeout=args.timeout)
+ # Spanned like the bring-up's own poll so `health --box-id` reports a
+ # summary too; without it this subcommand records no spans at all and
+ # write_summary has nothing to print.
+ with timing.span("health-poll"):
+ backend.wait_http_ok("/_health", expect=200, timeout=args.timeout)
# /_health only proves the process is up. Run the authed deep-health probe
# too so this subcommand catches an unusable app (the personhog-drift 500s
# slipped past /_health). --no-seed only tolerates a failed demo login
@@ -266,6 +271,11 @@ def main(argv: list[str] | None = None) -> int:
if getattr(e, "body", None):
sys.stderr.write(f"[hogbox-preview] details: {json.dumps(e.body, indent=2, default=str)}\n")
raise
+ finally:
+ # Both paths. A failed run's partial timings are precisely how you tell a
+ # restore timeout from a migrate failure without opening the log, and
+ # that's the case where the log is least pleasant to read.
+ timing.write_summary()
if __name__ == "__main__":
diff --git a/tools/hogbox-preview/hogbox_preview/backend.py b/tools/hogbox-preview/hogbox_preview/backend.py
index 31513e6421d8..f79f9bae7f58 100644
--- a/tools/hogbox-preview/hogbox_preview/backend.py
+++ b/tools/hogbox-preview/hogbox_preview/backend.py
@@ -26,6 +26,8 @@ import shlex
import subprocess
import dataclasses
+from . import timing
+
@dataclasses.dataclass
class ExecResult:
@@ -107,6 +109,10 @@ class PreviewBackend(abc.ABC):
a visible chunk of pure waiting across them. Each probe is one cheap
exec round-trip, so 3s is comfortably affordable.
"""
+ with timing.span(name):
+ return self._run_long(script, name=name, timeout=timeout, interval=interval)
+
+ def _run_long(self, script: str, *, name: str, timeout: int, interval: int) -> ExecResult:
base = f"/tmp/hogbox-{name}"
log, done, fail = f"{base}.log", f"{base}.done", f"{base}.fail"
self.write_file(f"{base}.sh", script + "\n")
diff --git a/tools/hogbox-preview/hogbox_preview/hogland_backend.py b/tools/hogbox-preview/hogbox_preview/hogland_backend.py
index 8bec5ff78fca..bbe5e9f5a3bf 100644
--- a/tools/hogbox-preview/hogbox_preview/hogland_backend.py
+++ b/tools/hogbox-preview/hogbox_preview/hogland_backend.py
@@ -161,15 +161,21 @@ class HoglandBackend(PreviewBackend):
# Stable identity first, then a fresh box from the golden. Each box gets a
# 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")
- self._box = self._restore_fresh()
- self._box_id = self._box.id
+ with timing.span("pen-resolve"):
+ self._ensure_pen()
+ with timing.span("box-restore"):
+ self._box = self._restore_fresh()
+ self._box_id = self._box.id
# `running` means the VM resumed, not that hogpanion's HTTP API answers
# yet — a restored box needs a beat before the first exec.
- self._wait_exec_ready()
- timing.stage("box restored (exec ready)")
+ #
+ # Timed separately from the restore on purpose. hogland's own
+ # create->running metric stops at `running`, so the guest-boot tail was
+ # invisible to both sides: sampled builds spent 30s and 171s between
+ # those two points with no way to tell whether a slow bring-up was the
+ # VM or hogpanion.
+ with timing.span("box-exec-ready"):
+ self._wait_exec_ready()
# Point the pen at the new box, re-send the spec so it carries the current
# shape, and RE-ASSERT the hibernate/wake policies. The spec re-send heals
# a pen left by an older SDK whose nested expose:{http_port} the server
@@ -180,13 +186,14 @@ class HoglandBackend(PreviewBackend):
# unaffordable — so even a pen that somehow lost the policy (older create,
# manual PATCH) is healed back to hibernate-on-idle here, not just at
# create. Idempotent for a freshly-created pen.
- self._client.update_pen(
- self.name,
- current_box_id=self._box_id,
- spec=self._pen_spec(),
- on_idle="hibernate",
- wake="on-request",
- )
+ with timing.span("pen-repoint"):
+ self._client.update_pen(
+ self.name,
+ current_box_id=self._box_id,
+ spec=self._pen_spec(),
+ on_idle="hibernate",
+ wake="on-request",
+ )
def _box_name(self) -> str:
# A per-attempt unique box name: `<pen-name>-<6hex>`. hogland's name
diff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.py
index 13dd49483942..11083acd0618 100644
--- a/tools/hogbox-preview/hogbox_preview/stack.py
+++ b/tools/hogbox-preview/hogbox_preview/stack.py
@@ -598,9 +598,13 @@ class PostHogPreviewStack:
# so settings import is fine; collectstatic itself needs no live DB.
import pathlib
- timing.stage("frontend swap start (upload dist)")
- tar = pathlib.Path(self.frontend_dist_tar).read_bytes()
- self.backend.write_file(f"{self.repo_dir}/frontend/dist.tgz", tar)
+ # Upload and collectstatic are separately timed: together they're ~260s,
+ # a third of the whole wait, and they were one opaque block — the dist
+ # is chunked over the exec API, so "slow upload" and "slow collectstatic"
+ # need very different fixes.
+ with timing.span("frontend-dist-upload"):
+ tar = pathlib.Path(self.frontend_dist_tar).read_bytes()
+ self.backend.write_file(f"{self.repo_dir}/frontend/dist.tgz", tar)
compose = f"docker compose -f {self.COMPOSE} -f {self.OVERRIDE}"
# CI tars the dist with `-C frontend dist`, so its members are rooted at
# `dist/`; strip that leading level on extract or the SPA double-nests to
@@ -621,9 +625,8 @@ class PostHogPreviewStack:
# a restart skips it and leaves `listeners: {}`, so nothing serves.
# up_services already brought web up cleanly — just wait for it to serve.
# Django is a heavy import; first health can take ~7 min.
- timing.stage("health poll start")
- self.backend.wait_http_ok("/_health", expect=200, timeout=900)
- timing.stage("health poll pass")
+ with timing.span("health-poll"):
+ self.backend.wait_http_ok("/_health", expect=200, timeout=900)
def deep_health(self) -> None:
# /_health is UNAUTHENTICATED — it passed the whole time previews were
@@ -640,8 +643,8 @@ class PostHogPreviewStack:
# a failed LOGIN (a genuinely unseeded box has no demo user): that
# soft-skips with a note instead of failing. Any failure past login —
# and a failed login on a seeded run — is fatal.
- timing.stage("deep health (authed api)")
- self._run_authed_probe()
+ with timing.span("deep-health"):
+ self._run_authed_probe()
def _run_authed_probe(self) -> None:
# Everything runs INSIDE the box (curl against localhost:8000), so it's
diff --git a/tools/hogbox-preview/hogbox_preview/timing.py b/tools/hogbox-preview/hogbox_preview/timing.py
index 2f9e42edfcc7..8848813b74f4 100644
--- a/tools/hogbox-preview/hogbox_preview/timing.py
+++ b/tools/hogbox-preview/hogbox_preview/timing.py
@@ -12,16 +12,50 @@ stdout contract stays untouched.
Elapsed is whole seconds since the tool started, measured with
``time.monotonic()`` so it's immune to wall-clock jumps and needs no formatting
library.
+
+Two things beyond the breadcrumbs, both because reading a duration off the log
+meant subtracting adjacent ``+NNNs`` lines by hand:
+
+``span()`` times a block and records it. Breadcrumbs mark a *point*, so a stage
+with no successor marker (or one that runs inside another) had no measurable
+duration at all — ``docker pull`` and ``reset-db`` were ~2 minutes of the
+bring-up and emitted nothing. Every ``run_long`` step is wrapped in one, so new
+stages get timed without anyone remembering to add a marker.
+
+``write_summary()`` puts the recorded spans in the job summary and emits one
+machine-readable line. The breadcrumbs live only in a log that ages out in 90
+days, which is why "is the preview getting slower?" has never been answerable
+without scraping. The JSON line is deliberately the same shape a
+``hogbox preview announced`` event would carry.
"""
from __future__ import annotations
+import os
import sys
+import json
import time
+import pathlib
+import contextlib
+from collections.abc import Iterator
# Captured at import (process start) so every stage line is relative to the same
# t0 across both the backend (pen/restore) and the stack (checkout/migrate/...).
-_START = time.monotonic()
+#
+# The bring-up and the deferred frontend swap are two separate processes, so
+# their breadcrumbs used to restart from +0s and couldn't be read as one
+# timeline. HOGBOX_PREVIEW_T0 (unix seconds, exported once by the workflow)
+# gives both an origin far enough back to cover the whole job; without it we
+# fall back to process start and behave exactly as before.
+_T0_ENV = os.environ.get("HOGBOX_PREVIEW_T0")
+if _T0_ENV and _T0_ENV.strip().isdigit():
+ _START = time.monotonic() - max(0.0, time.time() - int(_T0_ENV))
+else:
+ _START = time.monotonic()
+
+# (name, seconds), in completion order. Spans nest, so a parent's duration
+# includes its children — the summary shows both rather than trying to subtract.
+_SPANS: list[tuple[str, float]] = []
def stage(message: str) -> None:
@@ -29,3 +63,59 @@ def stage(message: str) -> None:
elapsed = int(time.monotonic() - _START)
sys.stderr.write(f"[hogbox-preview +{elapsed}s] {message}\n")
sys.stderr.flush()
+
+
+def span(name: str) -> Iterator[None]:
+ """Time a block, record it, and breadcrumb both edges.
+
+ The duration is recorded even when the block raises, so a failed run still
+ reports which stage it died in and how long it burned first — today a
+ restore timeout and a migrate failure look identical from outside the log.
+ """
+ started = time.monotonic()
+ stage(f"{name} start")
+ try:
+ yield
+ finally:
+ elapsed = time.monotonic() - started
+ _SPANS.append((name, elapsed))
+ stage(f"{name} done in {elapsed:.1f}s")
+
+
+def spans() -> list[tuple[str, float]]:
+ """Recorded spans, in completion order."""
+ return list(_SPANS)
+
+
+def write_summary(*, title: str = "preview timings") -> None:
+ """Append the recorded spans to the GH job summary and emit one JSON line.
+
+ Safe to call on the failure path: partial spans are more useful than none.
+ Never raises — timing must not be the thing that fails a preview.
+ """
+ if not _SPANS:
+ return
+
+ total = time.monotonic() - _START
+ # Sum repeats instead of letting a dict keep only the last one: pull_image
+ # retries run_long(name="pull") on a flaky ghcr handshake, so "pull" can be
+ # recorded more than once. Keeping the last attempt would report the 5s
+ # success while total_s still carried the two failed minutes. The table
+ # below still lists every attempt on its own row; this line is the per-stage
+ # total, which is the number you want when asking where the time went.
+ stage_totals: dict[str, float] = {}
+ for name, secs in _SPANS:
+ stage_totals[name] = stage_totals.get(name, 0.0) + secs
+ payload = {"total_s": round(total, 1), "stages": {name: round(secs, 1) for name, secs in stage_totals.items()}}
+ sys.stderr.write(f"[hogbox-preview timings] {json.dumps(payload, sort_keys=True)}\n")
+ sys.stderr.flush()
+
+ summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
+ if not summary_path:
+ return
+ rows = "\n".join(f"| {name} | {secs:.1f} |" for name, secs in _SPANS)
+ block = f"\n### {title}\n\n| stage | seconds |\n| --- | ---: |\n{rows}\n| **total** | **{total:.1f}** |\n"
+ with contextlib.suppress(OSError):
+ with pathlib.Path(summary_path).open("a", encoding="utf-8") as fh:
+ fh.write(block)