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(devex): restore personhog env in preview override and gate ready on an authed health check (#70093)

Julian Bez73ba2b2f26f8
diff --git a/tools/hogbox-preview/hogbox_preview/__main__.py b/tools/hogbox-preview/hogbox_preview/__main__.py
index 3eca772ef402..001eef95f1df 100644
--- a/tools/hogbox-preview/hogbox_preview/__main__.py
+++ b/tools/hogbox-preview/hogbox_preview/__main__.py
@@ -109,6 +109,11 @@ def cmd_health(args: argparse.Namespace) -> int:
backend = build_backend(args)
backend.provision()
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
+ # (genuinely unseeded box); it no longer skips the probe outright.
+ build_stack(backend, args).deep_health()
print(f"healthy: {backend.web_url}")
return 0
@@ -229,9 +234,10 @@ def main(argv: list[str] | None = None) -> int:
sd.add_argument("--box-id", required=True)
sd.set_defaults(func=cmd_seed, no_seed=False)
- he = sub.add_parser("health", help="wait for /_health on an existing box")
+ he = sub.add_parser("health", help="wait for /_health, then run the authed deep-health probe")
he.add_argument("--box-id", required=True)
he.add_argument("--timeout", type=int, default=600)
+ he.add_argument("--no-seed", action="store_true", help="skip the authed deep-health probe (no demo user seeded)")
he.set_defaults(func=cmd_health)
de = sub.add_parser("destroy", help="tear a box down")
diff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.py
index 956c03b62c61..a3008372271d 100644
--- a/tools/hogbox-preview/hogbox_preview/stack.py
+++ b/tools/hogbox-preview/hogbox_preview/stack.py
@@ -39,14 +39,28 @@ import secrets
from . import timing
from .backend import PreviewBackend
-# The tool's web override must reproduce the golden's baked preview env (hogland
-# scripts/posthog-preview-setup.sh) — constant across previews so web's config
-# never drifts per-box. JS_URL="" makes the SPA load assets relative to the
-# request origin; the wildcard CSRF origin trusts every box's edge host for the
-# login POST. One recipe then serves any box at its own edge URL.
+# The tool's web override MUST stay in sync with the golden bake script (hogland
+# scripts/posthog-preview-setup.sh): both write docker-compose.preview.yml, and
+# regenerating it here CLOBBERS the golden's baked copy — so anything the bake
+# adds (env, services) must be mirrored here or a per-PR override drops it. That
+# drift is exactly what broke previews fleet-wide from 2026-07-06 to 2026-07-10
+# (missing PERSONHOG_ADDR -> "personhog client not configured" 500s); see
+# write_override for the full post-mortem. JS_URL="" makes the SPA load assets
+# relative to the request origin; the wildcard CSRF origin trusts every box's
+# edge host for the login POST. One recipe then serves any box at its own edge
+# URL.
# Built as a single comma-separated string (Django's get_list() splits on commas)
# — a join, not a tuple, so there's no ambiguity about what reaches the env.
_CSRF_TRUSTED_ORIGINS = ",".join(f"https://*.boxes.hogland.{env}.posthog.dev" for env in ("dev", "prod-us", "prod-eu"))
+# The seeded demo login. These are the defaults of posthog's
+# `manage.py generate_demo_data` (--email / --password, see
+# posthog/management/commands/generate_demo_data.py), which generate_demo_data()
+# runs unchanged. Not importable here — the tool runs in an SDK-only env with no
+# posthog Django on the path — so they're duplicated with that source named. If
+# the seed defaults ever change, change these too.
+_DEMO_EMAIL = "[email protected]"
+_DEMO_PASSWORD = "12345678"
+
# PostHog's prod settings refuse to boot on the default SECRET_KEY, so the
# override must supply one (the migrate `run --rm web` one-off needs it too).
#
@@ -68,7 +82,22 @@ class PostHogPreviewStack:
COMPOSE = "docker-compose.dev-full.yml"
OVERRIDE = "docker-compose.preview.yml"
# Dependency services (published images, pulled by `up`).
- DEPS = ["db", "redis7", "clickhouse", "zookeeper", "kafka", "objectstorage"]
+ # personhog-replica/router are defined in the OVERRIDE (not dev-full.yml) —
+ # compose merges both files, so starting them here works. They must be in
+ # this list: nothing else starts them (up_web brings up only `web`, no
+ # depends_on edges), so a cold/reset box would otherwise boot web with
+ # PERSONHOG_ADDR pointing at a service that was never started. On the warm
+ # golden they're already running and `up` is a no-op.
+ DEPS = [
+ "db",
+ "redis7",
+ "clickhouse",
+ "zookeeper",
+ "kafka",
+ "objectstorage",
+ "personhog-replica",
+ "personhog-router",
+ ]
# App services built from the checkout (build escape hatch only). web shares
# its image with the other build: . services, so building web warms them all.
BUILD_SERVICES = ["web"]
@@ -145,6 +174,7 @@ class PostHogPreviewStack:
self.swap_frontend()
self.up_web()
self.wait_for_health()
+ self.deep_health()
return url
def swap_frontend_only(self) -> str:
@@ -218,16 +248,25 @@ class PostHogPreviewStack:
)
def write_override(self) -> None:
- # Reproduce the golden's baked web env (hogland
- # scripts/posthog-preview-setup.sh) so this block carries no per-box
- # value and never drifts between previews. A web recreate still happens
- # in up_web — but only to bind-mount the PR's backend source over the
- # image's /code (you can't add a mount to a running container). On the
- # warm golden that's a ~18s warm import (1 Unit worker + preloaded
- # config), not the old ~120s cold rebuild; #315's win is making that
- # recreate warm and serving the frontend relative (JS_URL=""), not
- # removing it. Keeping the env constant means web only ever recreates
- # for the mount, never for config drift.
+ # This override MUST stay in sync with hogland's
+ # scripts/posthog-preview-setup.sh (the golden bake script). Both write
+ # the same docker-compose.preview.yml; the bake bakes it into the golden,
+ # this regenerates it per PR — and regenerating it CLOBBERS the baked one.
+ # When the two drifted, previews broke fleet-wide: the bake added
+ # PERSONHOG_ADDR + the personhog services on 2026-07-06 (master's Django
+ # hard-requires the personhog service for group-type lookups since #65968
+ # — require_personhog_client() raises "personhog client not configured"
+ # without it), this file didn't, and every preview 500'd on
+ # /api/projects/@current/ (and environment/@current, team create, some
+ # HogQL paths) from 2026-07-06 to 2026-07-10 until this was fixed.
+ #
+ # A web recreate still happens in up_web — but only to bind-mount the PR's
+ # backend source over the image's /code (you can't add a mount to a
+ # running container). On the warm golden that's a ~18s warm import (1 Unit
+ # worker + preloaded config), not the old ~120s cold rebuild; #315's win
+ # is making that recreate warm and serving the frontend relative
+ # (JS_URL=""), not removing it. Keeping the env constant means web only
+ # ever recreates for the mount, never for config drift.
timing.stage("write compose override (backend mount)")
lines = ["# Generated by tools/hogbox-preview.", "services:", " web:"]
if self.image:
@@ -268,6 +307,34 @@ class PostHogPreviewStack:
# /_health; one worker + a preloaded config is ~15-20s.
" - NGINX_UNIT_APP_PROCESSES=1",
" - NGINX_UNIT_PRELOAD_CONFIG=true",
+ # master's Django hard-requires the personhog service for group-type
+ # lookups (require_personhog_client() raises "personhog client not
+ # configured" without it — #65968). Same addr the dev/hobby composes
+ # use; the router service is defined below. See write_override's note.
+ " - PERSONHOG_ADDR=personhog-router:50052",
+ ]
+ # Mirror the bake script's personhog service definitions (hogland
+ # scripts/posthog-preview-setup.sh): dev-full.yml carries NO personhog
+ # services (dev runs them via hogli), so define them here the way HOBBY
+ # does — extend the base definitions and point the replica at the MAIN
+ # posthog DB (persons live there for single-node deployments). The
+ # golden's warm containers keep running regardless, but a cold/reset
+ # path that `up`s the full project would lose them if they weren't here.
+ # Tag matches the bake: the part of self.image after the last ':'.
+ personhog_tag = self.image.rsplit(":", 1)[-1] if self.image else "master"
+ lines += [
+ " personhog-replica:",
+ " extends:",
+ " file: docker-compose.base.yml",
+ " service: personhog-replica",
+ f" image: ghcr.io/posthog/posthog/personhog-replica:{personhog_tag}",
+ " environment:",
+ " PRIMARY_DATABASE_URL: postgres://posthog:posthog@db:5432/posthog",
+ " personhog-router:",
+ " extends:",
+ " file: docker-compose.base.yml",
+ " service: personhog-router",
+ f" image: ghcr.io/posthog/posthog/personhog-router:{personhog_tag}",
]
self.backend.write_file(f"{self.repo_dir}/{self.OVERRIDE}", "\n".join(lines) + "\n")
@@ -393,6 +460,82 @@ class PostHogPreviewStack:
self.backend.wait_http_ok("/_health", expect=200, timeout=900)
timing.stage("health poll pass")
+ def deep_health(self) -> None:
+ # /_health is UNAUTHENTICATED — it passed the whole time previews were
+ # 500ing on /api/projects/@current/ (the personhog drift), so "healthy"
+ # meant "process is up", not "app is usable". This gate logs into the
+ # seeded demo user and hits the endpoints that actually broke, so a
+ # regression like that fails the bring-up instead of shipping a dead box.
+ #
+ # ALWAYS attempt the probe — including on --no-seed. The CI preview
+ # workflow calls `up --no-seed` because the golden is pre-seeded, so the
+ # demo user exists even when this run skipped the seed step; keying the
+ # whole gate off seed_demo_data would disable it in exactly the
+ # production path it was built for. The only concession to --no-seed is
+ # 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()
+
+ def _run_authed_probe(self) -> None:
+ # Everything runs INSIDE the box (curl against localhost:8000), so it's
+ # independent of external networking — same posture as wait_http_ok. One
+ # bash script does the whole login+probe flow with a shared cookie jar:
+ # 1. GET /login -> seed the CSRF cookie
+ # 2. POST /api/login/ -> authenticate the demo user
+ # 3. GET /api/projects/@current/ expect 200
+ # 4. POST /api/environments/@current/query/ expect 200 (HogQL)
+ # It prints "STEP <name> <http_code>" per step and the body of the first
+ # non-2xx, so the Python side can raise with the exact failure.
+ base = f"http://localhost:{self.backend.web_port}"
+ script = f"""
+set -u
+jar=$(mktemp)
+probe() {{ # name method path [json]
+ name=$1; method=$2; path=$3; data=${{4:-}}
+ if [ -n "$data" ]; then
+ csrf=$(awk '/csrftoken/ {{print $7}}' "$jar" | tail -n1)
+ code=$(curl -s -o /tmp/dh_body -w '%{{http_code}}' -m 30 -b "$jar" -c "$jar" \
+ -X "$method" -H 'Content-Type: application/json' -H "X-CSRFToken: $csrf" \
+ -H 'Referer: {base}/' -d "$data" "{base}$path")
+ else
+ code=$(curl -s -o /tmp/dh_body -w '%{{http_code}}' -m 30 -b "$jar" -c "$jar" "{base}$path")
+ fi
+ echo "STEP $name $code"
+ case "$code" in 2*) ;; *) echo "BODY_START"; head -c 300 /tmp/dh_body; echo; echo "BODY_END"; return 1;; esac
+}}
+probe login GET /login || exit 1
+probe api_login POST /api/login/ '{{"email":"{_DEMO_EMAIL}","password":"{_DEMO_PASSWORD}"}}' || exit 1
+probe projects GET /api/projects/@current/ || exit 1
+probe hogql POST /api/environments/@current/query/ '{{"query":{{"kind":"HogQLQuery","query":"select 1"}}}}' || exit 1
+echo "DEEP_HEALTH_OK"
+"""
+ r = self.backend.exec(script, timeout=180)
+ if "DEEP_HEALTH_OK" in r.stdout:
+ timing.stage("deep health pass")
+ return
+ # Login failed on a run that skipped seeding: the box may genuinely have
+ # no demo user (e.g. `up --no-seed` on a non-golden image), which isn't
+ # an app-health failure. Everything past a successful login stays fatal.
+ failed_step = ([ln.split()[1] for ln in r.stdout.splitlines() if ln.startswith("STEP ")] or ["?"])[-1]
+ if not self.seed_demo_data and failed_step == "api_login":
+ sys.stderr.write(
+ "[hogbox-preview] deep health: demo login failed on a --no-seed run — "
+ "assuming an unseeded box and skipping the authed probes\n"
+ )
+ timing.stage("deep health skipped (unseeded box)")
+ return
+ # Failed: surface the step + status + body, and the web log tail. The
+ # missing traceback is what cost hours on 2026-07-06 — dump it here so
+ # CI shows the Django error directly instead of just "not 200".
+ logs = self.backend.exec("docker logs --tail 40 posthog-web-1 2>&1", timeout=60)
+ raise RuntimeError(
+ "deep health (authed api) failed — the app is up but not usable:\n"
+ f"{r.stdout.strip()}\n{r.stderr.strip()}\n"
+ f"--- docker logs --tail 40 posthog-web-1 ---\n{logs.stdout.strip()}"
+ )
+
# --- internal ------------------------------------------------------------
def _compose(self, args: str) -> str:
return f"cd {self.repo_dir} && docker compose -f {self.COMPOSE} -f {self.OVERRIDE} {args}"
diff --git a/tools/hogbox-preview/tests/test_deep_health.py b/tools/hogbox-preview/tests/test_deep_health.py
new file mode 100644
index 000000000000..66fa929c8e22
--- /dev/null
+++ b/tools/hogbox-preview/tests/test_deep_health.py
@@ -0,0 +1,162 @@
+"""Unit tests for the personhog override parity + the authed deep-health gate.
+
+Self-contained: no network, no live box. Two seams are covered:
+
+ - ``write_override`` must mirror hogland's scripts/posthog-preview-setup.sh —
+ the PERSONHOG_ADDR web env plus the personhog-replica/router services. When
+ those drifted, previews 500'd fleet-wide with "personhog client not
+ configured" (2026-07-06 -> 07-10).
+ - ``deep_health`` — after /_health, log into the seeded demo user and hit the
+ endpoints that actually broke. Passes on 200s, raises with the failing
+ step's body + a docker-logs tail on a 500, and is skipped on --no-seed.
+
+Guarded on the SDK import (pulled per-run via ``uv run --with``), same as the
+sibling tests.
+
+ cd tools/hogbox-preview && python -m unittest discover tests
+"""
+
+from __future__ import annotations
+
+import unittest
+
+try:
+ from hogbox_preview.backend import ExecResult
+ from hogbox_preview.stack import PostHogPreviewStack
+
+ HAVE_SDK = True
+except ImportError:
+ HAVE_SDK = False
+
+
+class _RecordingBackend:
+ """Duck-typed PreviewBackend. ``exec`` returns a scripted result keyed off
+ the command so we can drive the probe down a pass or a fail path without a
+ real box."""
+
+ def __init__(self, *, probe_result: ExecResult | None = None):
+ self.web_port = 8000
+ self.files: dict[str, str] = {}
+ self.execs: list[str] = []
+ self._probe_result = probe_result
+
+ def write_file(self, remote_path, content) -> None:
+ self.files[remote_path] = content if isinstance(content, str) else content.decode()
+
+ def exec(self, command, *, timeout: int = 120) -> ExecResult:
+ self.execs.append(command)
+ # The authed probe script is the one that logs in + hits /api endpoints.
+ if "DEEP_HEALTH_OK" in command:
+ return self._probe_result or ExecResult(0, "", "")
+ # The failure path also greps docker logs; hand back a fake traceback.
+ if "docker logs" in command:
+ return ExecResult(
+ 0, "Traceback (most recent call last):\n RuntimeError: personhog client not configured", ""
+ )
+ return ExecResult(0, "", "")
+
+
[email protected](HAVE_SDK, "posthog-hogland SDK not installed")
+class OverridePersonhogParityTest(unittest.TestCase):
+ def _override(self, **kwargs) -> str:
+ backend = _RecordingBackend()
+ stack = PostHogPreviewStack(backend, **kwargs)
+ stack.write_override()
+ return backend.files[f"{stack.repo_dir}/{stack.OVERRIDE}"]
+
+ def test_web_env_has_personhog_addr(self):
+ self.assertIn("PERSONHOG_ADDR=personhog-router:50052", self._override())
+
+ def test_personhog_services_defined(self):
+ override = self._override()
+ self.assertIn("personhog-replica:", override)
+ self.assertIn("personhog-router:", override)
+ # extends the shared base compose (HOBBY-style), not a standalone def.
+ self.assertIn("file: docker-compose.base.yml", override)
+ # replica points at the MAIN posthog DB (persons live there single-node).
+ self.assertIn("PRIMARY_DATABASE_URL: postgres://posthog:posthog@db:5432/posthog", override)
+
+ def test_image_tag_flows_into_personhog_images(self):
+ # The personhog tag is the part of self.image after the last ':'.
+ override = self._override(image="ghcr.io/posthog/posthog:abc123")
+ self.assertIn("ghcr.io/posthog/posthog/personhog-replica:abc123", override)
+ self.assertIn("ghcr.io/posthog/posthog/personhog-router:abc123", override)
+
+
[email protected](HAVE_SDK, "posthog-hogland SDK not installed")
+class DeepHealthTest(unittest.TestCase):
+ def test_passes_when_probe_reports_ok(self):
+ backend = _RecordingBackend(probe_result=ExecResult(0, "STEP projects 200\nDEEP_HEALTH_OK\n", ""))
+ PostHogPreviewStack(backend).deep_health()
+ # Ran the probe; didn't need to dump logs.
+ self.assertTrue(any("DEEP_HEALTH_OK" in c for c in backend.execs))
+ self.assertFalse(any("docker logs" in c for c in backend.execs))
+
+ def test_probe_script_hits_the_endpoints_that_broke(self):
+ backend = _RecordingBackend(probe_result=ExecResult(0, "DEEP_HEALTH_OK\n", ""))
+ PostHogPreviewStack(backend).deep_health()
+ script = next(c for c in backend.execs if "DEEP_HEALTH_OK" in c)
+ self.assertIn("/login", script)
+ self.assertIn("/api/login/", script)
+ self.assertIn("/api/projects/@current/", script)
+ self.assertIn("/api/environments/@current/query/", script)
+ self.assertIn("HogQLQuery", script)
+ self.assertIn("[email protected]", script)
+
+ def test_raises_with_body_and_logs_on_500(self):
+ # Probe fails at the projects step with a 500 + body.
+ failing = ExecResult(
+ 0,
+ "STEP login 200\nSTEP api_login 200\nSTEP projects 500\nBODY_START\npersonhog client not configured\nBODY_END\n",
+ "",
+ )
+ backend = _RecordingBackend(probe_result=failing)
+ with self.assertRaises(RuntimeError) as ctx:
+ PostHogPreviewStack(backend).deep_health()
+ msg = str(ctx.exception)
+ # The failing step + body are surfaced...
+ self.assertIn("STEP projects 500", msg)
+ self.assertIn("personhog client not configured", msg)
+ # ...and so is the web-log tail (the traceback that cost hours).
+ self.assertIn("docker logs --tail 40 posthog-web-1", msg)
+ self.assertIn("Traceback", msg)
+ # It actually fetched the logs.
+ self.assertTrue(any("docker logs" in c for c in backend.execs))
+
+ def test_no_seed_still_probes_the_preseeded_golden(self):
+ # The CI workflow calls `up --no-seed` (the golden is pre-seeded), so the
+ # probe must RUN on no-seed runs — keying the gate off seed_demo_data
+ # disabled it in exactly the production path (Codex review catch).
+ backend = _RecordingBackend(probe_result=ExecResult(0, "DEEP_HEALTH_OK", ""))
+ PostHogPreviewStack(backend, seed_demo_data=False).deep_health()
+ self.assertTrue(any("DEEP_HEALTH_OK" in c for c in backend.execs))
+
+ def test_no_seed_tolerates_failed_login_only(self):
+ # A genuinely unseeded box has no demo user: a failed api_login on a
+ # no-seed run soft-skips instead of raising...
+ login_fail = ExecResult(1, "STEP login 200\nSTEP api_login 401\nBODY_START\n{}\nBODY_END", "")
+ backend = _RecordingBackend(probe_result=login_fail)
+ PostHogPreviewStack(backend, seed_demo_data=False).deep_health() # no raise
+ # ...but a post-login failure raises even on no-seed (app is unusable).
+ later_fail = ExecResult(
+ 1, "STEP login 200\nSTEP api_login 200\nSTEP projects 500\nBODY_START\n{}\nBODY_END", ""
+ )
+ backend = _RecordingBackend(probe_result=later_fail)
+ with self.assertRaises(RuntimeError):
+ PostHogPreviewStack(backend, seed_demo_data=False).deep_health()
+
+ def test_seeded_run_fails_hard_on_login_failure(self):
+ login_fail = ExecResult(1, "STEP login 200\nSTEP api_login 401\nBODY_START\n{}\nBODY_END", "")
+ backend = _RecordingBackend(probe_result=login_fail)
+ with self.assertRaises(RuntimeError):
+ PostHogPreviewStack(backend, seed_demo_data=True).deep_health()
+
+ def test_personhog_services_started_with_deps(self):
+ # Nothing else starts them (up_web brings up only web) — a cold/reset box
+ # must not boot web pointing at a router that never started.
+ self.assertIn("personhog-replica", PostHogPreviewStack.DEPS)
+ self.assertIn("personhog-router", PostHogPreviewStack.DEPS)
+
+
+if __name__ == "__main__":
+ unittest.main()