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): sync alert templates in hogbox (#85339)

Hugues Pouillotab4cbfee1d4f
diff --git a/tools/hogbox-preview/README.md b/tools/hogbox-preview/README.md
index a9432f7ca713..30dbcb763c87 100644
--- a/tools/hogbox-preview/README.md
+++ b/tools/hogbox-preview/README.md
@@ -47,7 +47,9 @@ print(url) # https://pen-….boxes.hogland.prod-us.posthog.dev/ (stable across
under the longer bring-up instead of serializing before it.
4. **Delta-migrate** — only the PR's _unapplied_ migrations on top of the seeded
DB (`--reset-db` if the PR's migrations are incompatible with the baseline).
-5. **Serve + report** — the box is HTTP-exposed; the URL is posted to the PR.
+5. **Sync HogFunction templates** - start the CDP service and load destination
+ templates into the restored database before the preview becomes available.
+6. **Serve + report** — the box is HTTP-exposed; the URL is posted to the PR.
Driven entirely by the **`posthog-hogland` Python SDK** over hogplane's HTTP API
— **keyless** (GitHub OIDC → hogplane token over the tailnet), no `hogland` CLI
diff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.py
index 13be48dd2e30..72720a183300 100644
--- a/tools/hogbox-preview/hogbox_preview/stack.py
+++ b/tools/hogbox-preview/hogbox_preview/stack.py
@@ -78,6 +78,7 @@ class PostHogPreviewStack:
# Default: run the ready-made published image and mount PR source over it.
# Pass image=None to fall back to the build-from-checkout escape hatch.
IMAGE = "ghcr.io/posthog/posthog:master"
+ CDP_IMAGE = "ghcr.io/posthog/posthog-node:master"
REPO_DIR = "/home/hog/posthog"
COMPOSE = "docker-compose.dev-full.yml"
OVERRIDE = "docker-compose.preview.yml"
@@ -98,6 +99,7 @@ class PostHogPreviewStack:
DEPS = [
"db",
"redis7",
+ "valkey",
"clickhouse",
"zookeeper",
"kafka",
@@ -166,11 +168,13 @@ class PostHogPreviewStack:
self.build_app() # native path: build the checkout (PR code)
if self.reset_db:
self.reset_database()
- # Migrate (and seed) BEFORE web serves: web can't be restarted to pick up
- # a PR's delta migrations (the Unit-listener gotcha), so the schema must
- # be ready before the serving container boots.
+ # Prepare the database and service-backed templates BEFORE web serves:
+ # web can't be restarted to pick up a PR's delta migrations (the
+ # Unit-listener gotcha), so all setup must finish before it boots.
self.up_deps()
self.migrate()
+ self.start_cdp_service()
+ self.sync_hog_function_templates()
if self.seed_demo_data:
# Best-effort: a transient build/model issue shouldn't sink an
# otherwise-good preview — it just opens empty.
@@ -339,6 +343,20 @@ class PostHogPreviewStack:
# inert no-op on an image that predates it.
" - USE_LOCAL_SETUP=1",
]
+ lines += [
+ " plugins:",
+ f" image: {self.CDP_IMAGE}",
+ # The checkout mount from dev-full masks the compiled code in the published image.
+ " volumes: !override []",
+ " environment:",
+ " - CYCLOTRON_NODE_DATABASE_URL=postgres://posthog:posthog@db:5432/cyclotron_node",
+ " - CDP_REDIS_HOST=redis7",
+ " - CDP_VALKEY_HOST=valkey",
+ " - CDP_VALKEY_PORT=6379",
+ " - ENCRYPTION_SALT_KEYS=00beef0000beef0000beef0000beef00",
+ " - PERSONHOG_ADDR=personhog-router:50052",
+ " - PERSONHOG_ENABLED=true",
+ ]
# 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
@@ -471,18 +489,21 @@ class PostHogPreviewStack:
self.backend.run_long(self._compose(f"build {services}"), name="build", timeout=2700)
def pull_image(self, *, attempts: int = 3) -> None:
- # The default path: fetch the ready-made image. Fast/no-op if a golden
- # already baked it in; otherwise pulls. ghcr pulls flake (TLS
- # handshake timeouts mid-layer); retry — docker resumes from pulled
- # layers, so a retry is cheap.
- last: Exception | None = None
- for _ in range(attempts):
- try:
- self.backend.run_long(f"docker pull {self.image}", name="pull", timeout=1800)
- return
- except RuntimeError as e:
- last = e
- raise RuntimeError(f"docker pull {self.image} failed after {attempts} attempts: {last}")
+ # The default path: fetch the ready-made images. Fast/no-op if a golden
+ # already baked them in; otherwise pulls. ghcr pulls flake (TLS
+ # handshake timeouts mid-layer); retry because docker resumes from
+ # pulled layers, so a retry is cheap.
+ assert self.image is not None
+ for image in (self.image, self.CDP_IMAGE):
+ last: Exception | None = None
+ for _ in range(attempts):
+ try:
+ self.backend.run_long(f"docker pull {image}", name="pull", timeout=1800)
+ break
+ except RuntimeError as e:
+ last = e
+ else:
+ raise RuntimeError(f"docker pull {image} failed after {attempts} attempts: {last}")
def reset_database(self) -> None:
# Drop the snapshot's pre-migrated DB so migrate() rebuilds it fresh and
@@ -575,6 +596,25 @@ class PostHogPreviewStack:
)
timing.stage("migrate done")
+ def start_cdp_service(self) -> None:
+ timing.stage("start CDP service")
+ ready_probe = self._compose("exec -T plugins curl -fsS http://localhost:6738/_ready")
+ script = (
+ f"set -e; {self._compose('up -d --no-build plugins')}; "
+ "ready=0; for _ in $(seq 1 60); do "
+ f"{ready_probe} >/dev/null 2>&1 && {{ ready=1; break; }}; sleep 4; done; "
+ '[ "$ready" = 1 ] || { echo "CDP service never became ready" >&2; exit 1; }'
+ )
+ self.backend.run_long(script, name="up-cdp", timeout=900)
+
+ def sync_hog_function_templates(self) -> None:
+ timing.stage("sync HogFunction templates")
+ self.backend.run_long(
+ self._compose("run --rm -T web python manage.py sync_hog_function_templates"),
+ name="sync-templates",
+ timeout=900,
+ )
+
def generate_demo_data(self) -> None:
# Same command hobby-ci uses (bin/hobby-ci.py). Seeds a demo org + the
# [email protected] / 12345678 login so the preview opens populated.
@@ -675,6 +715,7 @@ probe() {{ # name method path [json]
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 template GET /api/projects/@current/hog_function_templates/template-slack/ || exit 1
probe hogql POST /api/environments/@current/query/ '{{"query":{{"kind":"HogQLQuery","query":"select 1"}}}}' || exit 1
echo "DEEP_HEALTH_OK"
"""
diff --git a/tools/hogbox-preview/tests/test_deep_health.py b/tools/hogbox-preview/tests/test_deep_health.py
index 1a4ff6eb4a5a..5d1c91a3a13f 100644
--- a/tools/hogbox-preview/tests/test_deep_health.py
+++ b/tools/hogbox-preview/tests/test_deep_health.py
@@ -20,7 +20,10 @@ sibling tests.
from __future__ import annotations
+from contextlib import ExitStack
+
import unittest
+from unittest.mock import MagicMock, call, patch
try:
from hogbox_preview.backend import ExecResult
@@ -197,6 +200,107 @@ class OverrideTemporalParityTest(unittest.TestCase):
self.assertIn("rm -f db clickhouse web temporal temporal-django-worker", script)
[email protected](HAVE_SDK, "posthog-hogland SDK not installed")
+class ImagePullTest(unittest.TestCase):
+ def test_retries_each_image_independently(self):
+ backend = MagicMock()
+ backend.run_long.side_effect = [RuntimeError("app TLS timeout"), None, RuntimeError("CDP TLS timeout"), None]
+ image = "ghcr.io/posthog/posthog:test"
+ stack = PostHogPreviewStack(backend, image=image)
+
+ stack.pull_image(attempts=3)
+
+ backend.run_long.assert_has_calls(
+ [
+ call(f"docker pull {image}", name="pull", timeout=1800),
+ call(f"docker pull {image}", name="pull", timeout=1800),
+ call(f"docker pull {stack.CDP_IMAGE}", name="pull", timeout=1800),
+ call(f"docker pull {stack.CDP_IMAGE}", name="pull", timeout=1800),
+ ]
+ )
+ self.assertEqual(backend.run_long.call_count, 4)
+
+ def test_stops_before_cdp_image_when_app_image_exhausts_retries(self):
+ backend = MagicMock()
+ backend.run_long.side_effect = RuntimeError("TLS timeout")
+ image = "ghcr.io/posthog/posthog:test"
+ stack = PostHogPreviewStack(backend, image=image)
+
+ with self.assertRaisesRegex(RuntimeError, f"docker pull {image} failed after 2 attempts: TLS timeout"):
+ stack.pull_image(attempts=2)
+
+ self.assertEqual(
+ backend.run_long.call_args_list,
+ [
+ call(f"docker pull {image}", name="pull", timeout=1800),
+ call(f"docker pull {image}", name="pull", timeout=1800),
+ ],
+ )
+
+
[email protected](HAVE_SDK, "posthog-hogland SDK not installed")
+class TemplateSyncTest(unittest.TestCase):
+ def test_no_seed_bring_up_still_syncs_templates(self):
+ backend = MagicMock()
+ backend.web_url = "https://preview.example.com"
+ preview = PostHogPreviewStack(backend, seed_demo_data=False)
+ events: list[str] = []
+ methods = (
+ "start_runtime",
+ "write_override",
+ "pull_image",
+ "up_deps",
+ "migrate",
+ "start_cdp_service",
+ "sync_hog_function_templates",
+ "up_web",
+ "wait_for_health",
+ "deep_health",
+ )
+
+ with ExitStack() as patches:
+ for method in methods:
+ patches.enter_context(
+ patch.object(preview, method, side_effect=lambda name=method: events.append(name))
+ )
+ preview.bring_up()
+
+ self.assertLess(events.index("migrate"), events.index("start_cdp_service"))
+ self.assertLess(events.index("start_cdp_service"), events.index("sync_hog_function_templates"))
+ self.assertLess(events.index("sync_hog_function_templates"), events.index("up_web"))
+
+ def test_cdp_service_uses_the_published_image_configuration(self):
+ backend = _RecordingBackend()
+ stack = PostHogPreviewStack(backend)
+ stack.write_override()
+ override = backend.files[f"{stack.repo_dir}/{stack.OVERRIDE}"]
+ plugins_block = override.split(" plugins:", 1)[1].split(" personhog-replica:", 1)[0]
+
+ self.assertIn(f"image: {stack.CDP_IMAGE}", plugins_block)
+ self.assertIn("volumes: !override []", plugins_block)
+ self.assertIn("CYCLOTRON_NODE_DATABASE_URL=postgres://posthog:posthog@db:5432/cyclotron_node", plugins_block)
+ self.assertIn("CDP_REDIS_HOST=redis7", plugins_block)
+ self.assertIn("CDP_VALKEY_HOST=valkey", plugins_block)
+ self.assertIn("ENCRYPTION_SALT_KEYS=00beef0000beef0000beef0000beef00", plugins_block)
+ self.assertIn("PERSONHOG_ADDR=personhog-router:50052", plugins_block)
+
+ def test_starts_cdp_service_and_waits_until_ready(self):
+ backend = _RecordingBackend()
+ stack = PostHogPreviewStack(backend)
+ stack.start_cdp_service()
+
+ script = backend.long_runs[-1]
+ self.assertIn("up -d --no-build plugins", script)
+ self.assertIn("http://localhost:6738/_ready", script)
+
+ def test_syncs_hog_function_templates(self):
+ backend = _RecordingBackend()
+ stack = PostHogPreviewStack(backend)
+ stack.sync_hog_function_templates()
+
+ self.assertIn("python manage.py sync_hog_function_templates", backend.long_runs[-1])
+
+
@unittest.skipUnless(HAVE_SDK, "posthog-hogland SDK not installed")
class DeepHealthTest(unittest.TestCase):
def test_passes_when_probe_reports_ok(self):
@@ -214,6 +318,7 @@ class DeepHealthTest(unittest.TestCase):
self.assertIn("/api/login/", script)
self.assertIn("/api/projects/@current/", script)
self.assertIn("/api/environments/@current/query/", script)
+ self.assertIn("/api/projects/@current/hog_function_templates/template-slack/", script)
self.assertIn("HogQLQuery", script)
self.assertIn("[email protected]", script)