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.

chore(tasks): attribute dev-stack image bakes (#78891)

Alessandro Pogliaghi40cbafd6c942
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index a63540b6fd52..44804c76789b 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -299,9 +299,9 @@ snapshots the filesystem, and publishes it under the fixed
Modal image name `posthog-dev-stack` (see `products/tasks/backend/logic/services/dev_stack_image.py`).
It is dispatched on two cadences, both gated per region on the `tasks-dev-stack-image-bake` flag
via a `region` person property: a nightly full rebake that keeps the heavy state (migrations,
-docker pulls) close to master, and — mirroring the custom-image refresh fanout — a ten-minute
-sweep that rebakes as soon as the VM base image digest moves (e.g. an agent-server release),
-at most once per new digest.
+docker pulls) close to master, and a two-minute sweep that rebakes as soon as the VM base image
+digest moves (e.g. an agent-server release), at most once per new digest. User-authored custom
+images retain their separate ten-minute, batched refresh fanout.
`python manage.py bake_dev_stack_image` triggers a bake manually and bypasses the flag.
Pointing an org's `default_custom_image` payload key at that name gives its VM runs warm docker
state and already-migrated databases, so a task-time `hogli start` only applies the migrations
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 668fd19a0f65..51b4833f039c 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -304,10 +304,10 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
# agent-server release), at most once per new digest.
add_periodic_task_with_expiry(
sender,
- crontab(minute="*/10"),
+ crontab(minute="*/2"),
refresh_dev_stack_image_task.s(),
name="refresh prebaked dev-stack VM image on base change",
- expires_seconds=10 * 60,
+ expires_seconds=2 * 60,
)
# Re-enqueue signals PR refunds whose billing credit sync hasn't landed - hourly at minute 25
diff --git a/products/tasks/backend/facade/tasks.py b/products/tasks/backend/facade/tasks.py
index 0d026773738c..ea0589364f4d 100644
--- a/products/tasks/backend/facade/tasks.py
+++ b/products/tasks/backend/facade/tasks.py
@@ -52,12 +52,12 @@ def bake_dev_stack_image_task() -> None:
)
try:
- execute_bake_dev_stack_image_workflow()
+ execute_bake_dev_stack_image_workflow(trigger="nightly")
except Exception:
# Without these, a Temporal-unreachable night is indistinguishable from the flag
# being off in the bake metric. Re-raise so Celery still records the task failure.
logger.exception("dev_stack_image_bake_dispatch_failed")
- observe_dev_stack_image_bake("dispatch_failed")
+ observe_dev_stack_image_bake("dispatch_failed", trigger="nightly")
raise
diff --git a/products/tasks/backend/logic/services/dev_stack_image.py b/products/tasks/backend/logic/services/dev_stack_image.py
index 88e1aa28d168..c0df09828ed7 100644
--- a/products/tasks/backend/logic/services/dev_stack_image.py
+++ b/products/tasks/backend/logic/services/dev_stack_image.py
@@ -150,13 +150,13 @@ def refresh_dev_stack_image_if_base_changed(publish_name: str = DEV_STACK_IMAGE_
extra={"publish_name": publish_name, "base_reference": base_reference, "baked_reference": baked_reference},
)
try:
- execute_bake_dev_stack_image_workflow(publish_name)
+ execute_bake_dev_stack_image_workflow(publish_name, trigger="base_changed")
except Exception:
# Release the claim so the next sweep tick retries this digest — otherwise a
# transient Temporal error blocks the fast lane for the claim's whole TTL
# (mirrors the rollback in custom_image_refresh).
cache.delete(claim_key)
- observe_dev_stack_image_bake("dispatch_failed")
+ observe_dev_stack_image_bake("dispatch_failed", trigger="base_changed")
raise
return True
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 2e28cbe666ae..3778cc0e1a6b 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -109,7 +109,7 @@ CUSTOM_IMAGE_BUILD_TOTAL = Counter(
DEV_STACK_IMAGE_BAKE_TOTAL = Counter(
"posthog_tasks_dev_stack_image_bake_total",
"Prebaked dev-stack VM image bake lifecycle events",
- labelnames=["outcome"],
+ labelnames=["outcome", "region", "trigger"],
)
@@ -292,11 +292,17 @@ def observe_custom_image_build(outcome: CustomImageBuildOutcome) -> None:
logger.exception("custom_image_build_metric_failed", outcome=outcome)
-def observe_dev_stack_image_bake(outcome: DevStackImageBakeOutcome) -> None:
+def observe_dev_stack_image_bake(outcome: DevStackImageBakeOutcome, *, trigger: str) -> None:
try:
- DEV_STACK_IMAGE_BAKE_TOTAL.labels(outcome=outcome).inc()
+ from posthog.utils import get_instance_region # noqa: PLC0415
+
+ DEV_STACK_IMAGE_BAKE_TOTAL.labels(
+ outcome=outcome,
+ region=get_instance_region() or "unknown",
+ trigger=trigger,
+ ).inc()
except Exception:
- logger.exception("dev_stack_image_bake_metric_failed", outcome=outcome)
+ logger.exception("dev_stack_image_bake_metric_failed", outcome=outcome, trigger=trigger)
def origin_product_label(task_run: "TaskRun | None") -> str:
diff --git a/products/tasks/backend/temporal/bake_dev_stack_image/activities.py b/products/tasks/backend/temporal/bake_dev_stack_image/activities.py
index 3302d1167a19..66191f0ca537 100644
--- a/products/tasks/backend/temporal/bake_dev_stack_image/activities.py
+++ b/products/tasks/backend/temporal/bake_dev_stack_image/activities.py
@@ -2,7 +2,7 @@ import logging
import threading
import contextvars
from dataclasses import dataclass
-from typing import Any
+from typing import Any, Literal
from temporalio import activity
@@ -24,9 +24,10 @@ BAKE_HEARTBEAT_INTERVAL_SECONDS = 30
@dataclass
class BakeDevStackImageInput:
publish_name: str = DEV_STACK_IMAGE_NAME
+ trigger: Literal["nightly", "base_changed", "manual"] = "manual"
def to_log_context(self) -> dict[str, Any]:
- return {"publish_name": self.publish_name}
+ return {"publish_name": self.publish_name, "trigger": self.trigger}
@activity.defn
@@ -56,12 +57,12 @@ def bake_and_publish_dev_stack_image(input: BakeDevStackImageInput) -> str:
try:
image_id = bake_dev_stack_image(input.publish_name)
except DevStackImageBakeError:
- observe_dev_stack_image_bake("bake_failed")
+ observe_dev_stack_image_bake("bake_failed", trigger=input.trigger)
raise
except Exception:
- observe_dev_stack_image_bake("failed")
+ observe_dev_stack_image_bake("failed", trigger=input.trigger)
raise
- observe_dev_stack_image_bake("succeeded")
+ observe_dev_stack_image_bake("succeeded", trigger=input.trigger)
return image_id
finally:
stop_heartbeat.set()
diff --git a/products/tasks/backend/temporal/bake_dev_stack_image/workflow.py b/products/tasks/backend/temporal/bake_dev_stack_image/workflow.py
index 90b256373fa4..a5ad544a7677 100644
--- a/products/tasks/backend/temporal/bake_dev_stack_image/workflow.py
+++ b/products/tasks/backend/temporal/bake_dev_stack_image/workflow.py
@@ -25,7 +25,7 @@ class BakeDevStackImageWorkflow(PostHogWorkflow):
@staticmethod
def parse_inputs(inputs: list[str]) -> BakeDevStackImageInput:
loaded = json.loads(inputs[0])
- return BakeDevStackImageInput(**{k: v for k, v in loaded.items() if k == "publish_name"})
+ return BakeDevStackImageInput(**{k: v for k, v in loaded.items() if k in ("publish_name", "trigger")})
@workflow.run
async def run(self, input: BakeDevStackImageInput) -> str:
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index d43d404c79b9..d46138de94e8 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -1,7 +1,7 @@
import uuid
import asyncio
import logging
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Literal, Optional
from django.conf import settings
from django.db import transaction
@@ -516,7 +516,9 @@ def resume_task_in_cloud_workflow(run_id: str, workflow_id: str) -> None:
)
-def execute_bake_dev_stack_image_workflow(publish_name: str = DEV_STACK_IMAGE_NAME) -> None:
+def execute_bake_dev_stack_image_workflow(
+ publish_name: str = DEV_STACK_IMAGE_NAME, *, trigger: Literal["nightly", "base_changed", "manual"] = "manual"
+) -> None:
"""Start (or restart) the bake of the prebaked PostHog dev-stack VM image.
TERMINATE_IF_RUNNING: a bake stuck from the previous night gets replaced by the
@@ -526,7 +528,7 @@ def execute_bake_dev_stack_image_workflow(publish_name: str = DEV_STACK_IMAGE_NA
asyncio.run(
client.start_workflow(
"bake-dev-stack-image",
- BakeDevStackImageInput(publish_name=publish_name),
+ BakeDevStackImageInput(publish_name=publish_name, trigger=trigger),
id=f"bake-dev-stack-image-{publish_name}",
id_reuse_policy=WorkflowIDReusePolicy.TERMINATE_IF_RUNNING,
task_queue=settings.TASKS_TASK_QUEUE,
diff --git a/products/tasks/backend/tests/test_dev_stack_image.py b/products/tasks/backend/tests/test_dev_stack_image.py
index 232f835f15ca..52e600d7a182 100644
--- a/products/tasks/backend/tests/test_dev_stack_image.py
+++ b/products/tasks/backend/tests/test_dev_stack_image.py
@@ -176,7 +176,7 @@ class TestBakeDevStackImage:
patch("products.tasks.backend.temporal.client.execute_bake_dev_stack_image_workflow") as dispatch_mock,
):
assert refresh_dev_stack_image_if_base_changed(publish_name) is True
- dispatch_mock.assert_called_once_with(publish_name)
+ dispatch_mock.assert_called_once_with(publish_name, trigger="base_changed")
def test_publish_gives_up_after_exhausting_snapshot_attempts(self):
fake_cls = _make_fake_sandbox_cls(exit_code=0, publish_failures=PUBLISH_SNAPSHOT_MAX_ATTEMPTS)
@@ -212,7 +212,7 @@ class TestRefreshDevStackImageIfBaseChanged:
dispatched, dispatch_mock = self._refresh(publish_name)
assert dispatched is True
- dispatch_mock.assert_called_once_with(publish_name)
+ dispatch_mock.assert_called_once_with(publish_name, trigger="base_changed")
dispatched, dispatch_mock = self._refresh(publish_name)
assert dispatched is False
@@ -248,10 +248,10 @@ class TestRefreshDevStackImageIfBaseChanged:
with pytest.raises(RuntimeError):
refresh_dev_stack_image_if_base_changed(publish_name)
- observe_mock.assert_called_once_with("dispatch_failed")
+ observe_mock.assert_called_once_with("dispatch_failed", trigger="base_changed")
dispatched, dispatch_mock = self._refresh(publish_name)
assert dispatched is True
- dispatch_mock.assert_called_once_with(publish_name)
+ dispatch_mock.assert_called_once_with(publish_name, trigger="base_changed")
class TestBakeDevStackImageTask:
@@ -271,4 +271,4 @@ class TestBakeDevStackImageTask:
with pytest.raises(RuntimeError):
bake_dev_stack_image_task()
- observe_mock.assert_called_once_with("dispatch_failed")
+ observe_mock.assert_called_once_with("dispatch_failed", trigger="nightly")