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(tasks): org-routed default VM images + prebaked dev-stack bake (#73478)

Alessandro Pogliaghi14cff7493d93
diff --git a/AGENTS.md b/AGENTS.md
index c42b9b08a7e9..1626806b59c5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,6 +25,8 @@
- Build:
- Frontend: `pnpm --filter=@posthog/frontend build`
- Start dev: `./bin/start` or `hogli start` (interactive TUI). Detached mode: `hogli up -d` paired with `hogli wait` / `hogli down`
+ - Cloud task VMs (prebaked dev-stack image): run `bootstrap-dev-stack` first (restores compose host aliases, starts dockerd), then `uv sync`, `source .venv/bin/activate`, `hogli start -y -d`, and `hogli wait` (the detached start returns while the stack is still booting; `hogli wait` blocks until every process is ready) — always detached: the sandbox has no TTY, and phrocs under a pseudo-TTY balloons in memory until OOM-killed
+ - Cloud task VMs, frontend work: `pnpm install --frozen-lockfile --prefer-offline` links from the prebaked pnpm store, and Playwright Chromium is preinstalled; product/Storybook builds still run from source
- OpenAPI/types: `hogli build:openapi` (regenerate after changing serializers/viewsets)
- New product: `bin/hogli product:bootstrap <name>`
- LSP: Pyright is configured against the flox venv. Prefer LSP (`goToDefinition`, `findReferences`, `hover`) over grep when navigating or refactoring Python code.
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 8832ebaeeff6..a63540b6fd52 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -264,7 +264,7 @@ Agents should stage changes with `git add`, then use the `git_signed_commit` too
### Runtime selection (gVisor vs Modal VM)
Production sandboxes run on one of two Modal runtimes,
-chosen per run in `get_task_processing_context` (`_is_modal_vm_sandbox_enabled`)
+chosen per run in `get_task_processing_context` (`_resolve_modal_vm_sandbox`)
and forked in `provision_sandbox`:
- **gVisor** (`SandboxTemplate.DEFAULT_BASE`) — the historical default: a gVisor kernel-sandboxed container.
@@ -273,13 +273,62 @@ and forked in `provision_sandbox`:
Custom base images layer on this base, and it is what image-builder runs execute on.
Selection is driven by the `tasks-modal-vm-sandbox` flag's JSON payload,
-which carries two origin allowlists:
+which carries two origin allowlists and an optional default image:
- `origin_products` — origins allowed on the VM runtime when a custom image is resolved for the run
(custom images cannot run under gVisor).
- `default_base_origin_products` — origins that default to the bare VM base image **even without a custom image**.
This is the knob for making the VM runtime the default for standard cloud runs;
we widen it origin-by-origin (and, later, the flag's release condition) as the rollout expands.
+- `default_custom_image` — a Modal image name that VM runs fall back to when no custom image was picked.
+ Because the flag's payload variants are org-targeted, this routes _which default VM image an org gets_:
+ PostHog's own org points at the prebaked dev-stack image (below), everyone else keeps the plain VM base.
+ A user- or environment-selected custom image always wins over this default,
+ and provisioning falls back to the plain VM base if the named image is missing.
+
+#### The prebaked dev-stack image
+
+`hogli start` on a fresh VM pays for multi-gigabyte docker pulls and the full Django + persons +
+ClickHouse migration history — and dead-ends anyway, because the lean VM base lacks the dev
+toolchain flox provides on dev machines (brotli, phrocs, Go, Rust). For runs on the PostHog
+monorepo we bake all of that ahead of time:
+the `bake-dev-stack-image` Temporal workflow boots a plain VM-base sandbox,
+runs `bake-posthog-dev-stack.sh` inside it (install the dev toolchain, pre-pull the dev compose
+images, bring the stack up, run the Django and Rust-driven migrations, shut down cleanly),
+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.
+`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
+that landed since the last bake. The pnpm store and Playwright's Chromium are prewarmed too:
+`pnpm install --frozen-lockfile --prefer-offline` is a fast linking pass and browser installs
+are no-ops. Build outputs (node_modules, Storybook dist, Vite/Turbo caches) are deliberately
+not baked — the bake's checkout is deleted before the snapshot — so frontend builds always run
+from the task's own source. The bake must run on the real VM runtime —
+dockerd cannot run inside Modal's gVisor image builder — which is why it is a sandbox filesystem
+snapshot rather than a spec-built image.
+
+At task time the restored image is not self-starting: the sandbox runtime rewrites `/etc/hosts`
+at boot and dockerd does not autostart. Run the baked `bootstrap-dev-stack` helper first
+(restores the compose host aliases and starts dockerd — the bake manifest at
+`/opt/posthog/dev-stack-bake.json` names it under `bootstrap`), then from the checkout run
+`uv sync`, `source .venv/bin/activate`, `hogli start -y -d`, and `hogli wait`. Detached mode is
+required — the sandbox has no TTY, and running phrocs under a pseudo-TTY makes it balloon in
+memory until it is OOM-killed — and the detached start returns while the stack is still booting,
+so `hogli wait` is what blocks until every process reports ready.
+
+Provisioning also fires that helper detached as soon as the sandbox is up (best-effort, only on
+runs that booted the PostHog-published `posthog-dev-stack` image itself — never a user-authored
+custom image, and never a filesystem-snapshot restore, whose filesystem a prior run could have
+altered; directory-snapshot resumes only mount the workspace, so they keep the warmup), so
+the dockerd warmup overlaps the repo clone and the environment is usually
+ready by the agent's first command. Running `bootstrap-dev-stack` again is still the right first
+step — it is the synchronization point, blocking until the warmup completes.
Runs with a restricted-egress `SandboxEnvironment` (a custom domain allowlist) always stay on gVisor —
Modal's outbound domain allowlist is a gVisor-only feature.
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index a77cb77fc9dd..cc0726290faa 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -107,7 +107,9 @@ from products.streamlit_apps.backend.facade.api import (
stop_idle_streamlit_sandboxes,
)
from products.tasks.backend.facade.tasks import (
+ bake_dev_stack_image_task,
reconcile_loop_trigger_schedules_task,
+ refresh_dev_stack_image_task,
refresh_stale_sandbox_custom_images_task,
sweep_loop_task_retention_task,
)
@@ -282,6 +284,26 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
expires_seconds=10 * 60,
)
+ # Rebake the prebaked dev-stack VM image nightly so the baked migration state
+ # stays close to master. No-ops unless the tasks-dev-stack-image-bake flag
+ # enables this deployment's region.
+ sender.add_periodic_task(
+ crontab(hour="6", minute="45"),
+ bake_dev_stack_image_task.s(),
+ name="bake prebaked dev-stack VM image",
+ )
+
+ # Fast lane mirroring the custom-image refresh above: rebake the prebaked
+ # dev-stack image when the VM base image digest changes (e.g. a new
+ # agent-server release), at most once per new digest.
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/10"),
+ refresh_dev_stack_image_task.s(),
+ name="refresh prebaked dev-stack VM image on base change",
+ expires_seconds=10 * 60,
+ )
+
# Re-enqueue signals PR refunds whose billing credit sync hasn't landed - hourly at minute 25
sender.add_periodic_task(
crontab(hour="*", minute="25"),
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index ff2ccdaf5af4..70c4aa061b43 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -6,6 +6,8 @@ import posthoganalytics
SANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"
AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG = "tasks-agent-proxy-keep-stream-open"
MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"
+# Gates the nightly prebaked dev-stack image bake (see logic/services/dev_stack_image.py).
+DEV_STACK_IMAGE_BAKE_FEATURE_FLAG = "tasks-dev-stack-image-bake"
MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG = "tasks-modal-network-allowlist"
AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG = "tasks-agent-run-otel-telemetry"
PI_CLOUD_RUNTIME_FEATURE_FLAG = "pi-harness"
@@ -14,13 +16,19 @@ PI_CLOUD_RUNTIME_FEATURE_FLAG = "pi-harness"
AGENT_OTEL_TELEMETRY_STATE_KEY = "agent_otel_telemetry_enabled"
-def vm_sandbox_allowed_origin_products(payload: object) -> set[str]:
- """Origin products allowed on the Modal VM runtime, parsed from the flag's payload."""
+def _decode_vm_sandbox_payload(payload: object) -> object:
+ """Flag payloads may arrive JSON-encoded; decode strings, mapping bad JSON to None."""
if isinstance(payload, str):
try:
- payload = json.loads(payload)
+ return json.loads(payload)
except (ValueError, TypeError):
- payload = None
+ return None
+ return payload
+
+
+def vm_sandbox_allowed_origin_products(payload: object) -> set[str]:
+ """Origin products allowed on the Modal VM runtime, parsed from the flag's payload."""
+ payload = _decode_vm_sandbox_payload(payload)
value = payload.get("origin_products") if isinstance(payload, dict) else payload
if isinstance(value, list) and all(isinstance(item, str) for item in value):
return {item for item in value if isinstance(item, str)}
@@ -35,17 +43,35 @@ def vm_sandbox_default_base_origin_products(payload: object) -> set[str]:
default base, without requiring the user to pick a custom image. Read only from the
explicit dict key — unlike `origin_products`, a bare-list payload keeps its legacy
`origin_products` meaning and never opts an origin into the default base."""
- if isinstance(payload, str):
- try:
- payload = json.loads(payload)
- except (ValueError, TypeError):
- payload = None
+ payload = _decode_vm_sandbox_payload(payload)
value = payload.get("default_base_origin_products") if isinstance(payload, dict) else None
if isinstance(value, list) and all(isinstance(item, str) for item in value):
return {item for item in value if isinstance(item, str)}
return set()
+# Published Modal image name of the prebaked PostHog dev-stack VM image. Unlike
+# spec-built custom images, this one is a sandbox *filesystem snapshot* publish
+# (see logic/services/dev_stack_image.py), which Modal cannot layer build steps on.
+DEV_STACK_IMAGE_NAME = "posthog-dev-stack"
+
+
+def vm_sandbox_default_custom_image(payload: object) -> str | None:
+ """Modal image name that VM runs fall back to when no custom image was picked.
+
+ This is how the *default* VM image is routed per organization: the flag's payload
+ variants are org-targeted, so e.g. PostHog's own org can point its standard VM runs
+ at the prebaked posthog dev-stack image (see
+ `products/tasks/backend/logic/services/dev_stack_image.py`) while every other org
+ keeps the plain VM base. A user- or environment-picked custom image always wins over
+ this default. Read only from the explicit dict key."""
+ payload = _decode_vm_sandbox_payload(payload)
+ value = payload.get("default_custom_image") if isinstance(payload, dict) else None
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return None
+
+
def get_vm_sandbox_flag_payload(*, distinct_id: str, organization_id: str) -> object:
"""Raw payload of the Modal VM-sandbox flag; resolves to None when the flag is off."""
return posthoganalytics.get_feature_flag_payload(
diff --git a/products/tasks/backend/facade/tasks.py b/products/tasks/backend/facade/tasks.py
index dd6a81001c48..0d026773738c 100644
--- a/products/tasks/backend/facade/tasks.py
+++ b/products/tasks/backend/facade/tasks.py
@@ -4,6 +4,8 @@ Celery-task wiring for the tasks product.
Re-exports the beat-scheduled loop sweeps that core's scheduler registers.
"""
+import logging
+
from celery import shared_task
from products.tasks.backend.loop_reconciliation import reconcile_loop_trigger_schedules_task
@@ -11,6 +13,8 @@ from products.tasks.backend.loop_retention import sweep_loop_task_retention_task
__all__ = ["reconcile_loop_trigger_schedules_task", "sweep_loop_task_retention_task"]
+logger = logging.getLogger(__name__)
+
@shared_task(ignore_result=True)
def dispatch_loop_run_terminal_notification_task(loop_id: str, team_id: int, event: str, payload: dict) -> None:
@@ -28,3 +32,40 @@ def refresh_stale_sandbox_custom_images_task() -> None:
)
refresh_stale_sandbox_custom_images()
+
+
+@shared_task(ignore_result=True)
+def bake_dev_stack_image_task() -> None:
+ """Dispatch the nightly rebake of the prebaked PostHog dev-stack VM image."""
+ from products.tasks.backend.feature_flags import (
+ is_dev_stack_image_bake_enabled, # noqa: PLC0415 — keeps posthoganalytics off the import path
+ )
+
+ if not is_dev_stack_image_bake_enabled():
+ return
+
+ from products.tasks.backend.metrics import (
+ observe_dev_stack_image_bake, # noqa: PLC0415 — keeps prometheus off the celery import path
+ )
+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keeps the Temporal client off the import path
+ execute_bake_dev_stack_image_workflow,
+ )
+
+ try:
+ execute_bake_dev_stack_image_workflow()
+ 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")
+ raise
+
+
+@shared_task(ignore_result=True)
+def refresh_dev_stack_image_task() -> None:
+ """Rebake the prebaked dev-stack image when the VM base image digest changes."""
+ from products.tasks.backend.logic.services.dev_stack_image import ( # noqa: PLC0415 — keeps the service deps off the import path
+ refresh_dev_stack_image_if_base_changed,
+ )
+
+ refresh_dev_stack_image_if_base_changed()
diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.py
index 894d8f0a3c0f..2647d2900bc9 100644
--- a/products/tasks/backend/feature_flags.py
+++ b/products/tasks/backend/feature_flags.py
@@ -4,13 +4,50 @@ from django.conf import settings
import posthoganalytics
-from products.tasks.backend.constants import AGENT_OTEL_TELEMETRY_STATE_KEY, AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG
+from posthog.utils import get_instance_region
+
+from products.tasks.backend.constants import (
+ AGENT_OTEL_TELEMETRY_STATE_KEY,
+ AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG,
+ DEV_STACK_IMAGE_BAKE_FEATURE_FLAG,
+)
logger = logging.getLogger(__name__)
NATIVE_STEERING_SIGNALS_FEATURE_FLAG = "tasks-native-steering-signals"
NATIVE_STEERING_SIGNALS_DISTINCT_ID = "tasks-native-steering-signals"
+DEV_STACK_IMAGE_BAKE_DISTINCT_ID = "tasks-dev-stack-image-bake"
+
+
+def is_dev_stack_image_bake_enabled() -> bool:
+ """Gates the nightly prebaked dev-stack image bake (a paid Modal VM run per tick).
+
+ The bake publishes into the region's own Modal workspace, so the flag is evaluated
+ with the deployment region as a person property — release conditions can enable one
+ region at a time (`region = US` first). Fail-closed: a flag-service error must not
+ start a bake, and local dev is excluded outright — use `manage.py
+ bake_dev_stack_image` to bake manually."""
+ # Explicit rather than inherited from SDK state: self-capture re-enables
+ # posthoganalytics in local dev, so without this guard a locally seeded flag could
+ # start paid Modal bakes from a laptop.
+ if settings.DEBUG:
+ return False
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ DEV_STACK_IMAGE_BAKE_FEATURE_FLAG,
+ distinct_id=DEV_STACK_IMAGE_BAKE_DISTINCT_ID,
+ # Same region vocabulary as other region-conditioned flags: US / EU / DEV.
+ person_properties={"region": get_instance_region() or "DEV"},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("dev_stack_image_bake_flag_check_failed")
+ return False
+
def is_native_steering_signals_enabled() -> bool:
if settings.DEBUG:
diff --git a/products/tasks/backend/logic/services/dev_stack_image.py b/products/tasks/backend/logic/services/dev_stack_image.py
new file mode 100644
index 000000000000..88e1aa28d168
--- /dev/null
+++ b/products/tasks/backend/logic/services/dev_stack_image.py
@@ -0,0 +1,223 @@
+"""Bakes the prebaked PostHog dev-stack VM image.
+
+Boots a plain VM-base sandbox, runs `bake-posthog-dev-stack.sh` inside it (install the
+dev toolchain the VM base lacks, pre-pull the dev compose images, bring the stack up,
+run the Django/persons/ClickHouse and Rust-driven migrations, shut everything down
+cleanly), then publishes the sandbox's filesystem snapshot as a named Modal image.
+
+Orgs are routed onto the published image through the `tasks-modal-vm-sandbox` flag
+payload: a payload variant with `"default_custom_image": "posthog-dev-stack"` makes it
+the default base for that org's VM runs (see `vm_sandbox_default_custom_image` in
+`products/tasks/backend/constants.py`). `hogli start` on those runs then skips the
+multi-gigabyte docker pulls and only applies migrations that landed after the bake.
+
+The bake must run on the real VM runtime — dockerd cannot run inside Modal's gVisor
+image builder — which is why this is a sandbox snapshot rather than a spec-built image.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections import deque
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from django.conf import settings
+
+if TYPE_CHECKING:
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
+
+from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME
+from products.tasks.backend.exceptions import SnapshotTimeoutError
+from products.tasks.backend.feature_flags import is_dev_stack_image_bake_enabled
+from products.tasks.backend.logic.services.sandbox import SandboxConfig, SandboxTemplate, get_sandbox_class
+from products.tasks.backend.metrics import observe_dev_stack_image_bake
+from products.tasks.backend.redis import get_tasks_cache
+
+logger = logging.getLogger(__name__)
+
+BAKE_SCRIPT_LOCAL_PATH = Path("products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh")
+BAKE_SCRIPT_SANDBOX_PATH = "/tmp/bake-posthog-dev-stack.sh"
+
+# Cold bake budget: multi-GB image pulls plus the full migration history from scratch.
+BAKE_EXECUTION_TIMEOUT_SECONDS = 90 * 60
+BAKE_SANDBOX_TTL_SECONDS = 3 * 60 * 60
+BAKE_SANDBOX_CPU_CORES = 8.0
+BAKE_SANDBOX_MEMORY_GB = 32.0
+
+# Transient snapshot failures are retried in place on the still-running sandbox: a retry
+# costs only the snapshot, whereas failing the activity re-runs the whole 15-25 minute bake.
+PUBLISH_SNAPSHOT_MAX_ATTEMPTS = 3
+
+# Tail of bake output retained for error reporting.
+MAX_BAKE_LOG_CHARS = 20_000
+
+# VM base image reference the last successful bake layered on, so the refresh sweep can
+# tell whether the published image is stale (mirrors SandboxCustomImage.base_image_reference).
+BAKED_BASE_REFERENCE_CACHE_KEY = "tasks:dev-stack-image:baked-base-reference:{publish_name}"
+BAKED_BASE_REFERENCE_TTL_SECONDS = 30 * 24 * 60 * 60
+# Per-digest dispatch claim: a refresh is attempted at most once per new base reference
+# (mirrors SandboxCustomImage.base_image_refresh_reference); a failed attempt is retried
+# by the nightly bake, never by the next sweep tick.
+REFRESH_CLAIM_CACHE_KEY = "tasks:dev-stack-image:refresh-claim:{publish_name}:{base_reference}"
+REFRESH_CLAIM_TTL_SECONDS = 7 * 24 * 60 * 60
+
+
+class DevStackImageBakeError(Exception):
+ pass
+
+
+def _publish_snapshot_with_retries(sandbox: ModalSandbox, publish_name: str) -> str:
+ """Publish the sandbox's filesystem snapshot, retrying transient snapshot failures in place.
+
+ The sandbox keeps running between attempts, so a retry costs only the snapshot —
+ failing the activity instead would re-run the whole 15-25 minute bake.
+ """
+ for attempt in range(1, PUBLISH_SNAPSHOT_MAX_ATTEMPTS):
+ try:
+ return sandbox.publish_filesystem_image(publish_name)
+ except SnapshotTimeoutError as e:
+ logger.warning(
+ "dev_stack_image_publish_retry",
+ extra={"publish_name": publish_name, "sandbox_id": sandbox.id, "attempt": attempt, "error": str(e)},
+ )
+ return sandbox.publish_filesystem_image(publish_name)
+
+
+def _resolve_current_base_reference() -> str | None:
+ """Best-effort resolve of the VM base digest; losing it only costs one redundant
+ rebake on the next sweep."""
+ from products.tasks.backend.logic.services.modal_sandbox import ( # noqa: PLC0415 — keeps the Modal SDK off the import path
+ resolve_template_base_image_reference,
+ )
+
+ try:
+ return resolve_template_base_image_reference(SandboxTemplate.VM_BASE)
+ except Exception:
+ logger.exception("dev_stack_image_base_reference_resolve_failed")
+ return None
+
+
+def _record_baked_base_reference(publish_name: str, base_reference: str | None) -> None:
+ """Best-effort stamp of the base digest a successful bake layered on."""
+ if base_reference is None:
+ return
+ try:
+ get_tasks_cache().set(
+ BAKED_BASE_REFERENCE_CACHE_KEY.format(publish_name=publish_name),
+ base_reference,
+ timeout=BAKED_BASE_REFERENCE_TTL_SECONDS,
+ )
+ except Exception:
+ logger.exception("dev_stack_image_baked_reference_record_failed", extra={"publish_name": publish_name})
+
+
+def refresh_dev_stack_image_if_base_changed(publish_name: str = DEV_STACK_IMAGE_NAME) -> bool:
+ """Rebake when the VM base image digest has moved since the last successful bake.
+
+ The nightly bake keeps the heavy state (migrations, docker pulls) fresh; this is the
+ fast lane mirroring the custom-image refresh fanout, so a new VM base publish (e.g. an
+ agent-server release) reaches the prebaked image within a sweep tick instead of
+ overnight. Also converges a region with no recorded bake (first enable, cache flush)
+ by dispatching one. Returns whether a bake was dispatched.
+ """
+ if not is_dev_stack_image_bake_enabled():
+ return False
+
+ from products.tasks.backend.logic.services.modal_sandbox import ( # noqa: PLC0415 — keeps the Modal SDK off the import path
+ resolve_template_base_image_reference,
+ )
+
+ base_reference = resolve_template_base_image_reference(SandboxTemplate.VM_BASE)
+ if base_reference is None:
+ return False
+
+ cache = get_tasks_cache()
+ baked_reference = cache.get(BAKED_BASE_REFERENCE_CACHE_KEY.format(publish_name=publish_name))
+ if baked_reference == base_reference:
+ return False
+
+ claim_key = REFRESH_CLAIM_CACHE_KEY.format(publish_name=publish_name, base_reference=base_reference)
+ if not cache.add(claim_key, True, timeout=REFRESH_CLAIM_TTL_SECONDS):
+ return False
+
+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — breaks the temporal.client -> dev_stack_image import cycle
+ execute_bake_dev_stack_image_workflow,
+ )
+
+ logger.info(
+ "dev_stack_image_refresh_dispatched",
+ extra={"publish_name": publish_name, "base_reference": base_reference, "baked_reference": baked_reference},
+ )
+ try:
+ execute_bake_dev_stack_image_workflow(publish_name)
+ 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")
+ raise
+ return True
+
+
+def bake_dev_stack_image(publish_name: str = DEV_STACK_IMAGE_NAME) -> str:
+ """Run the bake in a fresh VM sandbox and publish the result; returns the image object id."""
+ from products.tasks.backend.logic.services.modal_sandbox import ( # noqa: PLC0415 — keeps the Modal SDK off the import path
+ ModalSandbox,
+ )
+
+ sandbox_cls = get_sandbox_class()
+ if not issubclass(sandbox_cls, ModalSandbox):
+ raise DevStackImageBakeError("Dev-stack image bakes require the Modal sandbox provider")
+
+ script = (Path(settings.BASE_DIR) / BAKE_SCRIPT_LOCAL_PATH).read_text()
+
+ # Capture the base digest BEFORE creating the sandbox: the digest can move during the
+ # long bake (e.g. an agent-server release), and recording the post-bake value would
+ # make the refresh sweep believe the stale publish already sits on the new base. The
+ # digest cache's TTL means this same value is what the create below resolves to.
+ base_reference = _resolve_current_base_reference()
+
+ sandbox = sandbox_cls.create(
+ SandboxConfig(
+ name="dev-stack-image-bake",
+ template=SandboxTemplate.VM_BASE,
+ vm_runtime=True,
+ cpu_cores=BAKE_SANDBOX_CPU_CORES,
+ memory_gb=BAKE_SANDBOX_MEMORY_GB,
+ ttl_seconds=BAKE_SANDBOX_TTL_SECONDS,
+ default_execution_timeout_seconds=BAKE_EXECUTION_TIMEOUT_SECONDS,
+ metadata={"purpose": "dev_stack_image_bake"},
+ )
+ )
+ try:
+ sandbox.write_file(BAKE_SCRIPT_SANDBOX_PATH, script.encode())
+
+ log_tail: deque[str] = deque()
+ tail_len = 0
+ stream = sandbox.execute_stream(f"bash {BAKE_SCRIPT_SANDBOX_PATH} 2>&1")
+ for line in stream.iter_stdout():
+ logger.info("dev_stack_image_bake_output", extra={"sandbox_id": sandbox.id, "line": line.rstrip()})
+ log_tail.append(line)
+ tail_len += len(line)
+ while tail_len > MAX_BAKE_LOG_CHARS and len(log_tail) > 1:
+ tail_len -= len(log_tail.popleft())
+ result = stream.wait()
+ if result.exit_code != 0:
+ raise DevStackImageBakeError(
+ f"Bake script exited with {result.exit_code}; output tail:\n{''.join(log_tail)[-MAX_BAKE_LOG_CHARS:]}"
+ )
+
+ image_id = _publish_snapshot_with_retries(sandbox, publish_name)
+ _record_baked_base_reference(publish_name, base_reference)
+ logger.info(
+ "dev_stack_image_published",
+ extra={"publish_name": publish_name, "image_id": image_id, "sandbox_id": sandbox.id},
+ )
+ return image_id
+ finally:
+ try:
+ sandbox.destroy()
+ except Exception:
+ logger.exception("dev_stack_image_bake_sandbox_cleanup_failed", extra={"sandbox_id": sandbox.id})
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 0a91d4451daa..df108a9c879d 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -1128,7 +1128,8 @@ class DockerSandbox(SandboxBase):
def read_agent_server_session_init_ms(self) -> int | None:
return self._read_health_session_init_ms(AGENT_SERVER_PORT)
- def create_snapshot(self) -> str:
+ def create_snapshot(self, *, timeout_seconds: int | None = None) -> str:
+ # timeout_seconds bounds Modal's snapshot RPC; docker commits have no equivalent knob.
if not self.is_running():
raise SandboxExecutionError(
"Sandbox not in running state.",
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index e2a6e3076928..3f3e07e7a01c 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -10,6 +10,7 @@ import logging
import tempfile
import threading
from collections.abc import Iterable
+from dataclasses import dataclass
from functools import lru_cache
from io import StringIO
from pathlib import Path
@@ -36,6 +37,7 @@ from posthog.settings import CLOUD_DEPLOYMENT
from products.tasks.backend.constants import (
ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,
+ DEV_STACK_IMAGE_NAME,
POSTHOG_EXEC_PERMISSION_REGEX,
SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS,
SNAPSHOT_KIND_DIRECTORY,
@@ -130,6 +132,16 @@ TRANSIENT_SNAPSHOT_ERRORS: tuple[type[BaseException], ...] = (
DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS = 240
+# Modal's snapshot_filesystem default timeout is 55s, which multi-GB sandbox filesystems
+# routinely exceed. The default fits the standalone snapshot activity's 10-minute budget;
+# resume snapshots run under a 5-minute activity budget and pass a tighter per-call
+# timeout (see create_resume_snapshot) so Modal's classified timeout fires before
+# Temporal kills the attempt. Published-image snapshots (the prebaked dev-stack bake,
+# with gigabytes of docker state) get a far larger budget bounded only by the bake
+# activity timeout.
+FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS = 8 * 60
+PUBLISHED_IMAGE_SNAPSHOT_TIMEOUT_SECONDS = 30 * 60
+
SESSION_INIT_PROBE_HOSTS = (
"gateway.us.posthog.com",
"gateway.eu.posthog.com",
@@ -302,6 +314,19 @@ def _get_sandbox_image_reference(image: str = SANDBOX_IMAGE) -> str:
AGENT_SERVER_TEMPLATES = frozenset({SandboxTemplate.DEFAULT_BASE, SandboxTemplate.VM_BASE})
+@dataclass(frozen=True)
+class ImageCandidate:
+ """One entry of the ordered image-downgrade chain a sandbox is created from."""
+
+ image: modal.Image
+ label: str
+ restored_from_snapshot: bool = False
+ # The image is a Modal sandbox filesystem snapshot (a resume snapshot or the
+ # published dev-stack image), so a boot from it needs the post-create health probe —
+ # snapshot restores can come up dead with every RPC succeeding.
+ snapshot_derived: bool = False
+
+
def _merge_runtime_dependency_specs(name: str, existing: str, candidate: str) -> str:
if existing == candidate:
return existing
@@ -342,7 +367,9 @@ def _local_package_bin_link_commands(packages: tuple[LocalPackage, ...]) -> list
return commands
-def _attach_local_package_mounts(image: modal.Image, template: SandboxTemplate) -> modal.Image:
+def _attach_local_package_mounts(
+ image: modal.Image, template: SandboxTemplate, *, install_dependencies: bool = True
+) -> modal.Image:
"""Overlay each local package's built `dist/` dir onto the installed package
via add_local_dir(copy=False). No-op unless `template` bundles the agent-server
and local packages are available.
@@ -350,6 +377,14 @@ def _attach_local_package_mounts(image: modal.Image, template: SandboxTemplate)
Install external runtime dependencies that are missing from the published image
before mounting the compiled output. The published package can lag behind a local
branch, but running npm inside it would also process unpublished workspace packages.
+
+ ``install_dependencies=False`` skips that npm-install build layer and attaches the
+ mounts only. Sandbox filesystem snapshots (resume/repo snapshots, the published
+ dev-stack image) cannot take Modal build steps — the image build fails and the
+ sandbox loses the snapshot entirely — while the mounts are attached at create time
+ without a build. Runtime dependencies a local branch added over the published
+ package are then missing; that dev-only gap surfaces as an agent-server import
+ error rather than silently forfeiting the snapshot.
"""
if template not in AGENT_SERVER_TEMPLATES:
return image
@@ -358,7 +393,12 @@ def _attach_local_package_mounts(image: modal.Image, template: SandboxTemplate)
return image
dependencies = get_local_package_runtime_dependencies(packages)
- if dependencies:
+ if dependencies and not install_dependencies:
+ logger.info(
+ "Skipping local package dependency install on snapshot-derived image; attaching dist mounts only",
+ extra={"packages": sorted(dependencies)},
+ )
+ elif dependencies:
if any("@openai/codex" in package_dependencies for package_dependencies in dependencies.values()):
image = image.apt_install("musl")
@@ -571,19 +611,23 @@ class ModalSandbox(SandboxBase):
modal.enable_output()
app = cls._get_app_for_template(config.template)
base_image = _get_template_image(config.template)
- image = base_image
+ custom_image_bare: modal.Image | None = None
custom_image: modal.Image | None = None
if config.custom_image_name:
try:
+ custom_image_bare = modal.Image.from_name(config.custom_image_name)
+ # The prebaked dev-stack image is a published sandbox filesystem snapshot,
+ # which Modal cannot layer build steps on — mount-only overlay for it.
custom_image = _attach_local_package_mounts(
- modal.Image.from_name(config.custom_image_name), config.template
+ custom_image_bare,
+ config.template,
+ install_dependencies=config.custom_image_name != DEV_STACK_IMAGE_NAME,
)
- image = custom_image
except Exception as e:
logger.warning(f"Failed to load custom image {config.custom_image_name}: {e}")
capture_exception(e)
- used_custom_image = custom_image is not None
config.snapshot_restored = False
+ config.image_fallback = None
snapshot_external_id: str | None = None
snapshot_kind = _normalize_snapshot_kind(config.snapshot_kind)
# No default-fill: a directory snapshot must arrive with an explicit allowed mount
@@ -591,15 +635,11 @@ class ModalSandbox(SandboxBase):
# snapshot that upstream validation invalidated (mount path stripped).
snapshot_mount_path: str | None = config.snapshot_mount_path
snapshot_image: modal.Image | None = None
- used_snapshot_image = False
if config.snapshot_external_id:
snapshot_external_id = config.snapshot_external_id
try:
snapshot_image = modal.Image.from_id(config.snapshot_external_id)
- if snapshot_kind == SNAPSHOT_KIND_FILESYSTEM:
- image = _attach_local_package_mounts(snapshot_image, config.template)
- used_snapshot_image = True
except Exception as e:
logger.warning(f"Failed to load resume snapshot image {config.snapshot_external_id}: {e}")
capture_exception(e)
@@ -613,12 +653,59 @@ class ModalSandbox(SandboxBase):
snapshot_mount_path = metadata_mount_path
try:
snapshot_image = modal.Image.from_id(snapshot.external_id)
- if snapshot_kind == SNAPSHOT_KIND_FILESYSTEM:
- image = _attach_local_package_mounts(snapshot_image, config.template)
- used_snapshot_image = True
except Exception as e:
logger.warning(f"Failed to load snapshot image {snapshot.external_id}: {e}")
capture_exception(e)
+ # Keep the config's kind authoritative for downstream trust decisions — the
+ # dev-stack bootstrap gate distinguishes directory from filesystem restores.
+ config.snapshot_kind = snapshot_kind
+
+ # Creation candidates, best first. Each later entry is a downgrade attempted only
+ # when creating from the previous image fails (e.g. its overlay image build errors),
+ # so a broken overlay costs the local packages, never the snapshot or custom image.
+ candidates: list[ImageCandidate] = []
+ if snapshot_image is not None and snapshot_kind == SNAPSHOT_KIND_FILESYSTEM:
+ overlaid_snapshot = _attach_local_package_mounts(
+ snapshot_image, config.template, install_dependencies=False
+ )
+ if overlaid_snapshot is not snapshot_image:
+ candidates.append(
+ ImageCandidate(
+ overlaid_snapshot,
+ f"snapshot image {snapshot_external_id} with local package overlay",
+ restored_from_snapshot=True,
+ snapshot_derived=True,
+ )
+ )
+ candidates.append(
+ ImageCandidate(
+ snapshot_image,
+ f"snapshot image {snapshot_external_id}",
+ restored_from_snapshot=True,
+ snapshot_derived=True,
+ )
+ )
+ if custom_image is not None and custom_image_bare is not None:
+ # The published dev-stack image is itself a sandbox filesystem snapshot
+ # (dockerd cannot run in the gVisor image builder), so booting it is the
+ # same restore the health probe guards; user custom images are spec-built.
+ custom_is_snapshot = config.custom_image_name == DEV_STACK_IMAGE_NAME
+ if custom_image is not custom_image_bare:
+ candidates.append(
+ ImageCandidate(
+ custom_image,
+ f"custom image {config.custom_image_name} with local package overlay",
+ snapshot_derived=custom_is_snapshot,
+ )
+ )
+ candidates.append(
+ ImageCandidate(
+ custom_image_bare,
+ f"custom image {config.custom_image_name}",
+ snapshot_derived=custom_is_snapshot,
+ )
+ )
+ candidates.append(ImageCandidate(base_image, "base image"))
secrets = []
if config.environment_variables:
@@ -633,7 +720,6 @@ class ModalSandbox(SandboxBase):
create_kwargs: dict[str, object] = {
"app": app,
"name": sandbox_name,
- "image": image,
"timeout": config.ttl_seconds,
**_resource_create_kwargs(config),
"region": region,
@@ -649,36 +735,7 @@ class ModalSandbox(SandboxBase):
if secrets:
create_kwargs["secrets"] = secrets
- try:
- modal_output: StringIO | None
- with capture_modal_output_if_debug() as modal_output:
- sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]
- config.snapshot_restored = used_snapshot_image
- except Exception as e:
- if not used_snapshot_image and not used_custom_image:
- raise
- fallback_image = custom_image if used_snapshot_image and custom_image is not None else base_image
- logger.warning(
- f"Failed to create sandbox with {'snapshot' if used_snapshot_image else 'custom'} image, "
- f"falling back to {'custom' if fallback_image is custom_image else 'base'} image: {e}"
- )
- capture_exception(e)
- create_kwargs["image"] = fallback_image
- try:
- with capture_modal_output_if_debug() as modal_output:
- sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]
- config.snapshot_restored = False
- except Exception as fallback_error:
- if fallback_image is base_image:
- raise
- logger.warning(
- f"Failed to create sandbox with custom image, falling back to base image: {fallback_error}"
- )
- capture_exception(fallback_error)
- create_kwargs["image"] = base_image
- with capture_modal_output_if_debug() as modal_output:
- sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]
- config.snapshot_restored = False
+ sb, modal_output, winner = cls._create_from_image_candidates(create_kwargs, candidates, config)
if snapshot_kind == SNAPSHOT_KIND_DIRECTORY and snapshot_image is not None:
# The mount REPLACES the target directory in the running sandbox — over a live
@@ -711,12 +768,18 @@ class ModalSandbox(SandboxBase):
)
capture_exception(e)
- # A restored sandbox can come up dead with every RPC succeeding; probe before use.
- if config.snapshot_restored and not cls._is_healthy_after_restore(sb):
+ # A sandbox whose filesystem came out of a Modal snapshot restore can come up
+ # dead with every RPC succeeding — probe before use. That covers resume
+ # snapshots (image or directory mount) and the published dev-stack image,
+ # which is itself a sandbox filesystem snapshot; spec-built images boot
+ # normally and skip the probe. Loops because a recovery can land on another
+ # snapshot-derived tier (resume snapshot -> dev-stack image -> base).
+ while (config.snapshot_restored or winner.snapshot_derived) and not cls._is_healthy_after_restore(sb):
logger.warning(
- "Snapshot-restored sandbox is not executing processes; recreating from base image",
+ "Snapshot-restored sandbox is not executing processes; recreating from the remaining image candidates",
extra={
"sandbox_id": sb.object_id,
+ "winner_label": winner.label,
"snapshot_external_id": snapshot_external_id,
"snapshot_kind": snapshot_kind,
"snapshot_mount_path": snapshot_mount_path,
@@ -726,10 +789,23 @@ class ModalSandbox(SandboxBase):
sb.terminate()
except Exception as e:
logger.warning(f"Failed to terminate wedged sandbox {sb.object_id}: {e}")
- create_kwargs["image"] = base_image
- with capture_modal_output_if_debug() as modal_output:
- sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]
- config.snapshot_restored = False
+ if config.snapshot_restored and not winner.restored_from_snapshot:
+ # The directory resume mount (not the image) wedged the sandbox:
+ # recreate on the same chain and leave the mount off. The run loses
+ # its resume state — exactly what the fallback message must say,
+ # rather than implying an image downgrade that never happened.
+ wedged = (
+ f"directory resume snapshot {snapshot_external_id} "
+ "(sandbox unresponsive after mount; resume state dropped)"
+ )
+ remaining = [c for c in candidates if not c.restored_from_snapshot]
+ else:
+ # The winning image itself restored wedged: drop it and every tier
+ # above it, along with any resume-snapshot candidates.
+ wedged = f"{winner.label} (unresponsive after restore)"
+ remaining = [c for c in candidates[candidates.index(winner) + 1 :] if not c.restored_from_snapshot]
+ sb, modal_output, winner = cls._create_from_image_candidates(create_kwargs, remaining, config)
+ config.image_fallback = f"{wedged} -> {winner.label}"
if config.metadata:
sb.set_tags(config.metadata)
@@ -748,6 +824,44 @@ class ModalSandbox(SandboxBase):
"Failed to create sandbox", {"config_name": config.name, "error": str(e)}, cause=e
)
+ @staticmethod
+ def _create_from_image_candidates(
+ create_kwargs: dict[str, object],
+ candidates: list[ImageCandidate],
+ config: SandboxConfig,
+ ) -> tuple[modal.Sandbox, StringIO | None, ImageCandidate]:
+ """Create the sandbox from the best image candidate that works, downgrading in order.
+
+ A downgrade is recorded on ``config.image_fallback`` so callers can surface it in
+ run-visible logs instead of the run silently landing on a lesser image. The last
+ candidate's failure propagates. Returns the winning candidate so callers that
+ re-enter this chain (the wedged-restore recovery) can describe what they landed on.
+ """
+ for index, candidate in enumerate(candidates):
+ create_kwargs["image"] = candidate.image
+ try:
+ modal_output: StringIO | None
+ with capture_modal_output_if_debug() as modal_output:
+ sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]
+ except Exception as e:
+ if index == len(candidates) - 1:
+ raise
+ logger.warning(
+ f"Failed to create sandbox with {candidate.label}, "
+ f"falling back to {candidates[index + 1].label}: {e}"
+ )
+ capture_exception(e)
+ continue
+ config.snapshot_restored = candidate.restored_from_snapshot
+ if index > 0:
+ config.image_fallback = f"{candidates[0].label} -> {candidate.label}"
+ return sb, modal_output, candidate
+ raise SandboxProvisionError(
+ "No sandbox image candidates to create from",
+ {"config_name": config.name},
+ cause=RuntimeError("empty image candidate list"),
+ )
+
@staticmethod
def _is_healthy_after_restore(sb: modal.Sandbox) -> bool:
"""Whether the sandbox executes processes after a snapshot restore (image or mount)."""
@@ -1343,25 +1457,32 @@ class ModalSandbox(SandboxBase):
timeout_seconds=15,
)
- def create_snapshot(self) -> str:
+ def _snapshot_filesystem_image(
+ self, publish_name: str | None = None, *, timeout_seconds: int = FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS
+ ) -> str:
+ """Guarded filesystem snapshot, optionally published under a Modal image name.
+
+ Returns the snapshot image's object id.
+ """
if not self.is_running():
raise SandboxNotRunningError(
- f"Sandbox not in running state.",
+ "Sandbox not in running state.",
{"sandbox_id": self.id},
cause=RuntimeError(f"Sandbox {self.id} is not running"),
)
+ error_context = {"sandbox_id": self.id, **({"publish_name": publish_name} if publish_name else {})}
try:
# Modal can report the sandbox as running before filesystem snapshotting is ready.
self._sandbox.exec("true", timeout=30).wait()
# ttl=None keeps indefinite retention; modal 1.5.0 otherwise defaults snapshots to a 30-day TTL.
- image = self._sandbox.snapshot_filesystem(ttl=None)
-
- snapshot_id = image.object_id
-
- logger.info(f"Created snapshot for sandbox {self.id}, snapshot ID: {snapshot_id}")
-
- return snapshot_id
+ image = self._sandbox.snapshot_filesystem(timeout=timeout_seconds, ttl=None)
+ if publish_name is not None:
+ image.publish(publish_name)
+ logger.info(f"Published filesystem image {publish_name} ({image.object_id}) from sandbox {self.id}")
+ else:
+ logger.info(f"Created snapshot for sandbox {self.id}, snapshot ID: {image.object_id}")
+ return image.object_id
except TRANSIENT_SNAPSHOT_ERRORS as e:
# Transient Modal infra timeout — Temporal retries the activity, so log at warning and
@@ -1369,16 +1490,19 @@ class ModalSandbox(SandboxBase):
logger.warning(f"Transient error creating snapshot for sandbox {self.id}, will retry: {e}")
raise SnapshotTimeoutError(
f"Transient error creating snapshot: {e}",
- {"sandbox_id": self.id, "error": str(e)},
+ {**error_context, "error": str(e)},
cause=e,
capture=False,
)
except Exception as e:
logger.exception(f"Failed to create snapshot: {e}")
- raise SnapshotCreationError(
- f"Failed to create snapshot: {e}", {"sandbox_id": self.id, "error": str(e)}, cause=e
- )
+ raise SnapshotCreationError(f"Failed to create snapshot: {e}", {**error_context, "error": str(e)}, cause=e)
+
+ def create_snapshot(self, *, timeout_seconds: int | None = None) -> str:
+ return self._snapshot_filesystem_image(
+ timeout_seconds=timeout_seconds if timeout_seconds is not None else FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS
+ )
def create_directory_snapshot(self, path: str) -> str:
if not self.is_running():
@@ -1423,6 +1547,15 @@ class ModalSandbox(SandboxBase):
cause=e,
)
+ def publish_filesystem_image(self, publish_name: str) -> str:
+ """Snapshot the filesystem and publish it as a named Modal image.
+
+ Republishing an existing name moves it to the new snapshot, so a fixed name
+ (e.g. the prebaked dev-stack image) can be refreshed without touching its
+ consumers. Returns the snapshot image's object id.
+ """
+ return self._snapshot_filesystem_image(publish_name, timeout_seconds=PUBLISHED_IMAGE_SNAPSHOT_TIMEOUT_SECONDS)
+
@staticmethod
def delete_snapshot(external_id: str) -> None:
logger.info(f"Deleting snapshot {external_id}")
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index db46d7464bcb..fa101f05f9a4 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -27,7 +27,13 @@ from django.conf import settings
import structlog
from pydantic import BaseModel, model_validator
-from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_FILESYSTEM, SnapshotKind
+from products.tasks.backend.constants import (
+ DEFAULT_SANDBOX_WORKING_DIR,
+ DEV_STACK_IMAGE_NAME,
+ SNAPSHOT_KIND_DIRECTORY,
+ SNAPSHOT_KIND_FILESYSTEM,
+ SnapshotKind,
+)
from products.tasks.backend.logic.services.sandbox_config import (
BURSTABLE_REQUEST_CPU_CORES,
BURSTABLE_REQUEST_MEMORY_MB,
@@ -115,6 +121,10 @@ class SandboxConfig(BaseModel):
outbound_domain_allowlist: list[str] | None = None
# VM runtime only — custom images layer on the VM base; snapshot restores take precedence.
custom_image_name: str | None = None
+ # Set by the provider when the sandbox could not be created from the intended image and a
+ # downgraded one was used instead (e.g. published custom image -> plain base). Human-readable,
+ # surfaced in the run log so image downgrades are never silent.
+ image_fallback: str | None = None
@model_validator(mode="before")
@classmethod
@@ -256,6 +266,76 @@ class SandboxBase(ABC):
timeout_seconds=45,
)
+ def launch_dev_stack_bootstrap(self) -> bool:
+ """Fire-and-forget the baked dev-stack bootstrap helper when this image carries it.
+
+ The prebaked dev-stack image ships /usr/local/bin/bootstrap-dev-stack (see
+ bake-posthog-dev-stack.sh): it restores the compose /etc/hosts aliases the sandbox
+ boot wiped and starts dockerd. Launching it detached at provision time overlaps
+ that warmup with the repo clone and agent-server boot, so a task-time `hogli start`
+ finds dockerd already up. The helper is idempotent — an agent running it again per
+ AGENTS.md just blocks until the warmup completes.
+
+ Best-effort by design: returns whether the helper was found and launched, and never
+ raises. A missed warmup only costs the overlap; the agent-side bootstrap still works.
+ """
+ # Only a sandbox that actually booted the PostHog-published dev-stack image gets
+ # its bootstrap run by the backend. This hook runs after credentials land in the
+ # sandbox env, so executing a script from any less-trusted filesystem would hand
+ # its author code execution with another member's secrets. Two checks:
+ # - the reserved name (user images always publish as posthog-sandbox-custom-*),
+ # with the absolute path below avoiding PATH shadowing;
+ # - not a filesystem-snapshot restore: such a resume boots a mutable snapshot
+ # of a prior run — one that processed untrusted repo content and could have
+ # replaced the helper file itself. Directory restores only mount the workspace
+ # dir (ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS), leaving the helper the
+ # vetted image's own binary, so the warmup stays on for them — but the
+ # workspace is still attacker-controlled, so the launcher below scrubs the
+ # environment (fixed PATH, no credentials) rather than trusting it. Anything
+ # not explicitly a directory restore is treated as filesystem — fail closed.
+ restored_untrusted_filesystem = (
+ self.config.snapshot_restored and self.config.snapshot_kind != SNAPSHOT_KIND_DIRECTORY
+ )
+ if (
+ not self.config.is_vm
+ or self.config.custom_image_name != DEV_STACK_IMAGE_NAME
+ or restored_untrusted_filesystem
+ ):
+ return False
+ try:
+ # Exit 3 = helper not present (downgraded to the plain VM base, or a pre-helper
+ # image) — an expected skip, not a failure. setsid + redirects detach the helper
+ # from this exec, which the sandbox runtime reaps as soon as the command returns.
+ #
+ # Run the helper through `/usr/bin/env -i` (absolute — a user PATH cannot shadow
+ # the launcher) with a fixed system PATH and no other environment. This is what
+ # makes the directory-restore case above safe: a directory resume mounts the
+ # untrusted workspace at /tmp/workspace, and PATH is a settable sandbox env var,
+ # so without scrubbing the helper's `start-dockerd`/`docker` lookups could resolve
+ # an attacker binary from the workspace — and would run it with the injected
+ # POSTHOG_PERSONAL_API_KEY / GITHUB_TOKEN. `env -i` drops those credentials and the
+ # user PATH; the fixed PATH resolves only real system binaries (start-dockerd lives
+ # in /usr/local/bin). HOME=/root covers tooling that needs it (dockerd runs as root).
+ result = self.execute(
+ "[ -x /usr/local/bin/bootstrap-dev-stack ] || exit 3; "
+ "/usr/bin/env -i HOME=/root PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin "
+ "setsid /usr/local/bin/bootstrap-dev-stack >/var/log/bootstrap-dev-stack.log 2>&1 </dev/null &",
+ timeout_seconds=30,
+ )
+ except Exception as e:
+ _logger.warning("dev_stack_bootstrap_launch_failed", sandbox_id=self.id, error=str(e))
+ return False
+ if result.exit_code == 0:
+ return True
+ if result.exit_code != 3:
+ _logger.warning(
+ "dev_stack_bootstrap_launch_failed",
+ sandbox_id=self.id,
+ exit_code=result.exit_code,
+ stderr=result.stderr,
+ )
+ return False
+
def agent_server_supports_auto_publish(self) -> bool:
"""Sandboxes restored from old snapshots can carry an agent-server that rejects unknown
CLI options, so probe the installed binary before passing --autoPublish; unsupported
@@ -382,7 +462,7 @@ class SandboxBase(ABC):
def mark_repo_ready(self, repo_ready_file: str) -> None: ...
@abstractmethod
- def create_snapshot(self) -> str: ...
+ def create_snapshot(self, *, timeout_seconds: int | None = None) -> str: ...
@abstractmethod
def create_directory_snapshot(self, path: str) -> str: ...
diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index c4f07c841a52..00fdbbbf13c3 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -17,6 +17,7 @@ from modal.exception import (
)
from requests.exceptions import ConnectionError, Timeout
+from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY
from products.tasks.backend.exceptions import (
SandboxExecutionError,
SandboxProvisionError,
@@ -33,6 +34,8 @@ from products.tasks.backend.logic.services.modal_sandbox import (
AGENT_SERVER_PORT,
DEFAULT_MODAL_REGION,
DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS,
+ FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS,
+ PUBLISHED_IMAGE_SNAPSHOT_TIMEOUT_SECONDS,
SANDBOX_IMAGE,
ModalSandbox,
_attach_local_package_mounts,
@@ -375,6 +378,41 @@ class TestAttachLocalPackageMounts:
)
assert result is final_image
+ def test_mount_only_overlay_adds_no_build_layers(self, tmp_path: Path) -> None:
+ # Sandbox filesystem snapshots (resume snapshots, the published dev-stack image)
+ # cannot take Modal build steps — a run_commands/apt_install layer fails the image
+ # build at sandbox create and forfeits the snapshot. Mount-only must stay build-free
+ # even when the local packages declare registry dependencies.
+ source_path = tmp_path / "agent"
+ build_output_path = source_path / "dist"
+ build_output_path.mkdir(parents=True)
+ (source_path / "package.json").write_text(
+ json.dumps({"dependencies": {"@openai/codex": "0.140.0", "zod": "^4.2.0"}})
+ )
+ package = LocalPackage(
+ name="agent",
+ source_path=source_path,
+ sandbox_install_path="/scripts/node_modules/@posthog/agent",
+ )
+ snapshot_image = MagicMock()
+ mounted_image = MagicMock()
+ snapshot_image.add_local_dir.return_value = mounted_image
+
+ with patch(
+ "products.tasks.backend.logic.services.modal_sandbox.get_local_posthog_code_packages",
+ return_value=(package,),
+ ):
+ result = _attach_local_package_mounts(snapshot_image, SandboxTemplate.VM_BASE, install_dependencies=False)
+
+ snapshot_image.apt_install.assert_not_called()
+ snapshot_image.run_commands.assert_not_called()
+ snapshot_image.add_local_dir.assert_called_once_with(
+ str(build_output_path),
+ "/scripts/node_modules/@posthog/agent/dist",
+ copy=False,
+ )
+ assert result is mounted_image
+
class TestModalSandboxAgentServer:
@pytest.fixture
@@ -767,7 +805,7 @@ class TestModalSandboxAgentServer:
image = MagicMock()
image.object_id = "snapshot-123"
- def snapshot_filesystem(ttl: Any = None) -> Any:
+ def snapshot_filesystem(timeout: int = 55, ttl: Any = None) -> Any:
events.append("snapshot")
return image
@@ -779,9 +817,23 @@ class TestModalSandboxAgentServer:
assert result == "snapshot-123"
mock_sandbox._sandbox.exec.assert_called_once_with("true", timeout=30)
exec_process.wait.assert_called_once_with()
- mock_sandbox._sandbox.snapshot_filesystem.assert_called_once_with(ttl=None)
+ mock_sandbox._sandbox.snapshot_filesystem.assert_called_once_with(
+ timeout=FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS, ttl=None
+ )
assert events == ["wait", "snapshot"]
+ def test_create_snapshot_per_call_timeout_reaches_modal(self, mock_sandbox: Any) -> None:
+ # The resume path passes a timeout tighter than its 5-minute activity budget —
+ # dropping the threading would revert it to the 8-minute default, which Temporal
+ # kills before Modal's classified timeout can fire.
+ mock_sandbox._sandbox.exec.return_value = MagicMock()
+ mock_sandbox._sandbox.snapshot_filesystem.return_value = MagicMock(object_id="snapshot-456")
+
+ result = mock_sandbox.create_snapshot(timeout_seconds=240)
+
+ assert result == "snapshot-456"
+ mock_sandbox._sandbox.snapshot_filesystem.assert_called_once_with(timeout=240, ttl=None)
+
class TestModalSandboxProvisionDiagnostics:
@pytest.mark.parametrize(
@@ -1079,6 +1131,327 @@ class TestModalSandboxCreateAllowlist:
assert mock_create.call_args.kwargs["experimental_options"] == {"vm_runtime": True}
+class TestModalSandboxCreateImageFallback:
+ """A failed create with an overlaid image must downgrade one step at a time (bare
+ snapshot / bare custom image) instead of jumping to the clean base image — jumping
+ straight to base silently forfeits the prebaked stack the run was routed onto."""
+
+ def _create_failing_on(self, config: SandboxConfig, *, failing_image: Any, loaded_image: Any) -> tuple[Any, list]:
+ mock_sb = MagicMock()
+ mock_sb.object_id = "sb-created"
+ # A snapshot-restored sandbox is health-probed after create; make the probe pass.
+ mock_sb.exec.return_value.poll.return_value = 0
+ images_tried: list[Any] = []
+
+ def sandbox_create(**kwargs: Any) -> Any:
+ images_tried.append(kwargs["image"])
+ if kwargs["image"] is failing_image:
+ raise RuntimeError("image build failed")
+ return mock_sb
+
+ with (
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),
+ patch.object(ModalSandbox, "_get_app_for_template", return_value=MagicMock()),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._get_template_image",
+ return_value=MagicMock(name="base"),
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name",
+ return_value=loaded_image,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_id",
+ return_value=loaded_image,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",
+ return_value=failing_image,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", side_effect=sandbox_create
+ ),
+ patch("products.tasks.backend.logic.services.modal_sandbox.capture_exception"),
+ ):
+ sandbox = ModalSandbox.create(config)
+ return sandbox, images_tried
+
+ def test_custom_image_overlay_failure_falls_back_to_bare_custom_image(self):
+ # The verified failure mode: the local package overlay on the published dev-stack
+ # image failed to build and the run silently landed on the clean VM base.
+ config = SandboxConfig(name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-dev-stack")
+ bare_custom = MagicMock(name="bare_custom")
+ overlaid_custom = MagicMock(name="overlaid_custom")
+
+ sandbox, images_tried = self._create_failing_on(config, failing_image=overlaid_custom, loaded_image=bare_custom)
+
+ assert images_tried == [overlaid_custom, bare_custom]
+ assert sandbox.config.image_fallback is not None
+ assert "custom image posthog-dev-stack" in sandbox.config.image_fallback
+
+ def test_snapshot_overlay_failure_falls_back_to_bare_snapshot(self):
+ config = SandboxConfig(name="t", snapshot_external_id="im-snap-1")
+ bare_snapshot = MagicMock(name="bare_snapshot")
+ overlaid_snapshot = MagicMock(name="overlaid_snapshot")
+
+ sandbox, images_tried = self._create_failing_on(
+ config, failing_image=overlaid_snapshot, loaded_image=bare_snapshot
+ )
+
+ assert images_tried == [overlaid_snapshot, bare_snapshot]
+ # The run still restored from the snapshot — the downgrade only cost the overlay.
+ assert sandbox.config.snapshot_restored is True
+ assert sandbox.config.image_fallback is not None
+
+ def _create_with_probe(
+ self,
+ config: SandboxConfig,
+ *,
+ probe: Any,
+ snapshot_image: Any,
+ custom_image: Any,
+ ) -> tuple[Any, list]:
+ images_tried: list[Any] = []
+
+ def sandbox_create(**kwargs: Any) -> Any:
+ images_tried.append(kwargs["image"])
+ sb = MagicMock()
+ sb.object_id = f"sb-{len(images_tried)}"
+ return sb
+
+ with (
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),
+ patch.object(ModalSandbox, "_get_app_for_template", return_value=MagicMock()),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._get_template_image",
+ return_value=MagicMock(name="base"),
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name",
+ return_value=custom_image,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_id",
+ return_value=snapshot_image,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",
+ side_effect=lambda image, template, **kwargs: image,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", side_effect=sandbox_create
+ ),
+ probe,
+ ):
+ sandbox = ModalSandbox.create(config)
+ return sandbox, images_tried
+
+ def test_wedged_snapshot_restore_recovers_through_custom_image_and_records_fallback(self):
+ # A snapshot restore that comes up unresponsive must not jump to the plain base:
+ # an internal run routed onto the prebaked dev-stack image should still land on
+ # it, and the downgrade must show up on image_fallback, not happen silently.
+ config = SandboxConfig(
+ name="t",
+ template=SandboxTemplate.VM_BASE,
+ custom_image_name="posthog-dev-stack",
+ snapshot_external_id="im-snap-1",
+ )
+ snapshot_image = MagicMock(name="snapshot_image")
+ custom_image = MagicMock(name="custom_image")
+
+ sandbox, images_tried = self._create_with_probe(
+ config,
+ # Snapshot restore wedged; the recovered dev-stack boot probes healthy.
+ probe=patch.object(ModalSandbox, "_is_healthy_after_restore", side_effect=[False, True]),
+ snapshot_image=snapshot_image,
+ custom_image=custom_image,
+ )
+
+ assert images_tried == [snapshot_image, custom_image]
+ assert sandbox.config.snapshot_restored is False
+ assert sandbox.config.image_fallback is not None
+ assert "snapshot image im-snap-1 (unresponsive after restore)" in sandbox.config.image_fallback
+ assert "custom image posthog-dev-stack" in sandbox.config.image_fallback
+
+ def test_wedged_dev_stack_boot_is_probed_and_falls_back_to_base(self):
+ # The published dev-stack image is itself a filesystem snapshot, so its boot can
+ # wedge exactly like a resume restore. Without the probe on this tier, every
+ # internal run booting it would be handed a dead sandbox with no detection.
+ config = SandboxConfig(name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-dev-stack")
+ custom_image = MagicMock(name="custom_image")
+
+ sandbox, images_tried = self._create_with_probe(
+ config,
+ probe=patch.object(ModalSandbox, "_is_healthy_after_restore", side_effect=[False]),
+ snapshot_image=MagicMock(name="unused_snapshot"),
+ custom_image=custom_image,
+ )
+
+ assert len(images_tried) == 2 # dev-stack image, then base
+ assert images_tried[0] is custom_image
+ assert sandbox.config.image_fallback is not None
+ assert "custom image posthog-dev-stack (unresponsive after restore)" in sandbox.config.image_fallback
+ assert "base image" in sandbox.config.image_fallback
+
+ def test_spec_built_custom_images_are_not_probed(self):
+ # User custom images are spec-built, not snapshot restores — probing them would
+ # add a health-check roundtrip (and its flake surface) to every custom-image run.
+ config = SandboxConfig(
+ name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-sandbox-custom-2-abc:latest"
+ )
+ probe_mock = MagicMock()
+
+ _, images_tried = self._create_with_probe(
+ config,
+ probe=patch.object(ModalSandbox, "_is_healthy_after_restore", probe_mock),
+ snapshot_image=MagicMock(name="unused_snapshot"),
+ custom_image=MagicMock(name="custom_image"),
+ )
+
+ assert len(images_tried) == 1
+ probe_mock.assert_not_called()
+
+ def test_wedged_directory_mount_recovers_on_same_image_and_names_the_mount(self):
+ # A directory resume that wedges the sandbox never changed the boot image — the
+ # fallback must say the mount (and the resume state) was dropped, not claim a
+ # "snapshot image" downgrade that never happened.
+ config = SandboxConfig(
+ name="t",
+ template=SandboxTemplate.VM_BASE,
+ custom_image_name="posthog-dev-stack",
+ snapshot_external_id="im-snap-1",
+ snapshot_kind=SNAPSHOT_KIND_DIRECTORY,
+ snapshot_mount_path=DEFAULT_SANDBOX_WORKING_DIR,
+ )
+ custom_image = MagicMock(name="custom_image")
+
+ sandbox, images_tried = self._create_with_probe(
+ config,
+ # Mounted sandbox wedged; the recreated (mount-free) one probes healthy.
+ probe=patch.object(ModalSandbox, "_is_healthy_after_restore", side_effect=[False, True]),
+ snapshot_image=MagicMock(name="snapshot_image"),
+ custom_image=custom_image,
+ )
+
+ assert images_tried == [custom_image, custom_image] # same image, mount dropped
+ assert sandbox.config.snapshot_restored is False
+ assert sandbox.config.image_fallback is not None
+ assert "directory resume snapshot im-snap-1" in sandbox.config.image_fallback
+ assert "resume state dropped" in sandbox.config.image_fallback
+ assert not sandbox.config.image_fallback.startswith("snapshot image")
+
+
+class TestLaunchDevStackBootstrap:
+ def _sandbox(
+ self,
+ *,
+ vm: bool = True,
+ custom_image_name: str | None = "posthog-dev-stack",
+ snapshot_restored: bool = False,
+ snapshot_kind: Any = None,
+ ) -> Any:
+ mock_modal_sandbox = MagicMock()
+ mock_modal_sandbox.object_id = "sb-boot"
+ config = SandboxConfig(
+ name="t",
+ vm_runtime=vm,
+ custom_image_name=custom_image_name,
+ snapshot_restored=snapshot_restored,
+ **({"snapshot_kind": snapshot_kind} if snapshot_kind is not None else {}),
+ )
+ with patch.object(ModalSandbox, "_get_app_for_template", return_value=MagicMock()):
+ return ModalSandbox(sandbox=mock_modal_sandbox, config=config)
+
+ @pytest.mark.parametrize(
+ "exit_code,expected",
+ [
+ (0, True), # helper present, launched detached
+ (3, False), # helper absent (downgraded to VM base, pre-helper image) — expected skip
+ (1, False), # genuine launch failure — logged, never surfaced
+ ],
+ )
+ def test_maps_exec_exit_code_to_launch_outcome(self, exit_code: int, expected: bool):
+ sandbox = self._sandbox()
+ result = ExecutionResult(stdout="", stderr="", exit_code=exit_code, error=None)
+
+ with patch.object(ModalSandbox, "execute", return_value=result) as mock_execute:
+ assert sandbox.launch_dev_stack_bootstrap() is expected
+
+ # Absolute path, not a PATH probe — PATH could be shadowed inside the image.
+ assert "/usr/local/bin/bootstrap-dev-stack" in mock_execute.call_args.args[0]
+
+ def test_never_raises_when_exec_fails(self):
+ # A warmup hiccup must never fail provisioning — without the overlap, the
+ # agent-side bootstrap flow still works.
+ sandbox = self._sandbox()
+
+ with patch.object(ModalSandbox, "execute", side_effect=RuntimeError("exec transport lost")):
+ assert sandbox.launch_dev_stack_bootstrap() is False
+
+ def test_skips_non_vm_sandboxes_without_exec(self):
+ # gVisor sandboxes can never carry the baked helper; probing them would add an
+ # exec roundtrip to every default-base provisioning.
+ sandbox = self._sandbox(vm=False)
+
+ with patch.object(ModalSandbox, "execute") as mock_execute:
+ assert sandbox.launch_dev_stack_bootstrap() is False
+
+ mock_execute.assert_not_called()
+
+ @pytest.mark.parametrize("custom_image_name", [None, "posthog-sandbox-custom-2-abc123:latest"])
+ def test_skips_images_other_than_the_dev_stack_image_without_exec(self, custom_image_name: str | None):
+ # The backend must never execute a bootstrap script out of a user-authored custom
+ # image: this hook runs after credentials land in the sandbox env, so a planted
+ # same-named script would hand the image author another member's secrets.
+ sandbox = self._sandbox(custom_image_name=custom_image_name)
+
+ with patch.object(ModalSandbox, "execute") as mock_execute:
+ assert sandbox.launch_dev_stack_bootstrap() is False
+
+ mock_execute.assert_not_called()
+
+ def test_skips_filesystem_restored_sandboxes_without_exec(self):
+ # A filesystem resume boots a mutable snapshot of a prior run's filesystem — a
+ # run that processed untrusted repo content and could have replaced the helper —
+ # not the vetted image the configured name refers to. The backend must not
+ # execute it.
+ sandbox = self._sandbox(snapshot_restored=True)
+
+ with patch.object(ModalSandbox, "execute") as mock_execute:
+ assert sandbox.launch_dev_stack_bootstrap() is False
+
+ mock_execute.assert_not_called()
+
+ def test_directory_restored_sandboxes_still_get_the_warmup(self):
+ # Directory resumes only mount the workspace dir, so /usr/local/bin's helper is
+ # still the vetted image's own binary — the warmup must not be lost on the
+ # primary resume path.
+ sandbox = self._sandbox(snapshot_restored=True, snapshot_kind=SNAPSHOT_KIND_DIRECTORY)
+ result = ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
+
+ with patch.object(ModalSandbox, "execute", return_value=result):
+ assert sandbox.launch_dev_stack_bootstrap() is True
+
+ def test_launch_scrubs_environment_so_a_poisoned_workspace_path_cannot_run_with_credentials(self):
+ # The exact directory-restore attack: a mounted /tmp/workspace holds an attacker
+ # `start-dockerd`, and PATH is a settable sandbox env var pointed at it. The
+ # launcher must strip the environment (no injected credentials) and pin PATH to
+ # system dirs via an absolute /usr/bin/env, so the helper can never resolve or
+ # run the workspace binary with the run's POSTHOG_PERSONAL_API_KEY / GITHUB_TOKEN.
+ sandbox = self._sandbox(snapshot_restored=True, snapshot_kind=SNAPSHOT_KIND_DIRECTORY)
+ result = ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
+
+ with patch.object(ModalSandbox, "execute", return_value=result) as mock_execute:
+ assert sandbox.launch_dev_stack_bootstrap() is True
+
+ command = mock_execute.call_args.args[0]
+ assert "/usr/bin/env -i " in command # absolute launcher, empty environment
+ assert "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" in command
+ assert "/tmp/workspace" not in command
+ # env -i means no credential is ever named in (or inherited by) the helper's env.
+ assert "TOKEN" not in command and "API_KEY" not in command
+
+
class TestResourceCreateKwargs:
def test_flat_scalars_when_not_burstable(self):
config = SandboxConfig(name="t", cpu_cores=4, memory_gb=16)
@@ -1219,6 +1592,19 @@ class TestModalSandboxCreateSnapshot:
"/tmp/workspace", timeout=DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS, ttl=None
)
+ def test_publish_filesystem_image_uses_published_image_snapshot_timeout(self, mock_sandbox: Any):
+ # The dev-stack bake snapshots multiple GB of docker state; Modal's 55s default
+ # (and the regular snapshot budget) time out under it and fail the whole bake.
+ image = MagicMock(object_id="im-123")
+ mock_sandbox._sandbox.snapshot_filesystem.return_value = image
+
+ assert mock_sandbox.publish_filesystem_image("posthog-dev-stack") == "im-123"
+
+ mock_sandbox._sandbox.snapshot_filesystem.assert_called_once_with(
+ timeout=PUBLISHED_IMAGE_SNAPSHOT_TIMEOUT_SECONDS, ttl=None
+ )
+ image.publish.assert_called_once_with("posthog-dev-stack")
+
class TestSessionInitProbeHosts:
@override_settings(
diff --git a/products/tasks/backend/management/commands/bake_dev_stack_image.py b/products/tasks/backend/management/commands/bake_dev_stack_image.py
new file mode 100644
index 000000000000..a4fe6ab2393c
--- /dev/null
+++ b/products/tasks/backend/management/commands/bake_dev_stack_image.py
@@ -0,0 +1,38 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+from products.tasks.backend.logic.services.dev_stack_image import DEV_STACK_IMAGE_NAME, bake_dev_stack_image
+
+
+class Command(BaseCommand):
+ help = (
+ "Bake the prebaked PostHog dev-stack VM image (warm docker state + migrated databases) "
+ "and publish it as a named Modal image. Dispatches the Temporal workflow by default; "
+ "use --inline to run the bake in this process."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument(
+ "--publish-name",
+ default=DEV_STACK_IMAGE_NAME,
+ help=f"Modal image name to publish under (default: {DEV_STACK_IMAGE_NAME})",
+ )
+ parser.add_argument(
+ "--inline",
+ action="store_true",
+ help="Run the bake synchronously in this process instead of dispatching the Temporal workflow",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ publish_name: str = options["publish_name"]
+ if options["inline"]:
+ image_id = bake_dev_stack_image(publish_name)
+ self.stdout.write(self.style.SUCCESS(f"Published {publish_name} ({image_id})"))
+ else:
+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keeps the Temporal client off command discovery
+ execute_bake_dev_stack_image_workflow,
+ )
+
+ execute_bake_dev_stack_image_workflow(publish_name)
+ self.stdout.write(self.style.SUCCESS(f"Dispatched bake-dev-stack-image-{publish_name}"))
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 39a82319a3fe..2e28cbe666ae 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -11,6 +11,7 @@ if TYPE_CHECKING:
TaskWorkflowStartOutcome = Literal["attempted", "blocked", "failed", "started"]
CustomImageBuildOutcome = Literal["started", "succeeded", "failed", "scan_rejected"]
+DevStackImageBakeOutcome = Literal["succeeded", "bake_failed", "failed", "dispatch_failed"]
# Outcome of an SSE task-run stream connection when it closes.
# completed — stream reached its completion sentinel
# stream_error — Redis/stream error sentinel ended the connection
@@ -105,6 +106,12 @@ CUSTOM_IMAGE_BUILD_TOTAL = Counter(
labelnames=["outcome"],
)
+DEV_STACK_IMAGE_BAKE_TOTAL = Counter(
+ "posthog_tasks_dev_stack_image_bake_total",
+ "Prebaked dev-stack VM image bake lifecycle events",
+ labelnames=["outcome"],
+)
+
# Connection lifetimes range from a few seconds (cold reconnect) to the
# per-connection cap. The 120s bucket isolates connections cut at the
@@ -285,6 +292,13 @@ 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:
+ try:
+ DEV_STACK_IMAGE_BAKE_TOTAL.labels(outcome=outcome).inc()
+ except Exception:
+ logger.exception("dev_stack_image_bake_metric_failed", outcome=outcome)
+
+
def origin_product_label(task_run: "TaskRun | None") -> str:
"""Bounded origin_product metric label resolved from the task run's task."""
if task_run is None:
diff --git a/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
new file mode 100644
index 000000000000..fabd4d3b0288
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
@@ -0,0 +1,312 @@
+#!/usr/bin/env bash
+# Bakes a warm PostHog dev stack into a VM sandbox so its filesystem snapshot can be
+# published as the default base image for PostHog-internal cloud task runs (see
+# products/tasks/backend/logic/services/dev_stack_image.py).
+#
+# What ends up in the image:
+# - every default-profile docker-compose.dev.yml service image pre-pulled into
+# /var/lib/docker (profile-gated services are not warmed: the default task intent
+# activates no compose profiles, so task runs never pull them)
+# - Postgres (main + persons + product DBs, including the Rust-migrated cyclotron /
+# behavioral-cohorts / flags-read-store databases) and ClickHouse fully migrated,
+# with the data living in the compose project's volumes/containers under
+# /var/lib/docker
+# - the dev toolchain `hogli start` needs but the VM base image lacks: brotli
+# (bin/download-mmdb), phrocs (the process manager bin/start requires), Go and the
+# Rust toolchain — with rustfmt/clippy (hogli format:rust, CI-parity cargo clippy)
+# and sqlx-cli (bin/start-go-service / bin/start-rust-service and the rust/bin
+# migrators) — plus warm cargo-registry and Go-module caches for the workspaces
+# - a warm uv cache, so the task-time `uv sync` is a fast linking pass
+# - a warm pnpm content-addressed store, so the task-time `pnpm install` is a fast
+# linking pass, plus Playwright's Chromium (and its system libraries) for
+# Storybook builds and screenshot runs
+# - /usr/local/bin/bootstrap-dev-stack, the one-shot task-time bootstrap (restores
+# the compose /etc/hosts aliases the sandbox boot wiped, starts dockerd)
+#
+# Build outputs are deliberately NOT baked: the checkout — node_modules, Storybook
+# dist, Vite/Turbo caches — is deleted before the snapshot, so frontend builds always
+# run from the task's own source instead of silently reflecting the baked commit.
+#
+# `hogli start` on a task VM then skips the multi-gigabyte image pulls and runs only
+# the migrations that landed after the bake, instead of the full history from scratch.
+#
+# The toolchain lives here rather than in Dockerfile.sandbox-vm on purpose: the plain
+# VM base serves every org's VM runs and stays lean; only the PostHog-internal prebaked
+# image needs a full dev toolchain.
+#
+# Runs as root inside a Modal VM sandbox created from SandboxTemplate.VM_BASE.
+set -euo pipefail
+
+BAKE_ROOT=/tmp/posthog-dev-stack-bake
+REPO_DIR="$BAKE_ROOT/posthog"
+BAKE_MANIFEST=/opt/posthog/dev-stack-bake.json
+
+# Toolchain pins — versions in sync with .flox/env/manifest.toml, which is what dev
+# machines (and therefore `hogli start`) are built against. The sha256 pins come from
+# the vendors' published manifests (go.dev/dl, static.rust-lang.org/rustup/archive) and
+# guard the privileged downloads below: a tampered artifact fails the bake instead of
+# being published into the shared internal image. Bump them together with the versions.
+GO_VERSION=1.25.5
+GO_SHA256_AMD64=9e9b755d63b36acf30c12a9a3fc379243714c1c6d3dd72861da637f336ebb35b
+GO_SHA256_ARM64=b00b694903d126c588c378e72d3545549935d3982635ba3f7a964c9fa23fe3b9
+RUSTUP_VERSION=1.29.0
+RUSTUP_SHA256_AMD64=4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10
+RUSTUP_SHA256_ARM64=9732d6c5e2a098d3521fca8145d826ae0aaa067ef2385ead08e6feac88fa5792
+RUST_TOOLCHAIN=1.91.1
+SQLX_CLI_VERSION=0.8.3
+
+export RUSTUP_HOME=/opt/rust/rustup
+export CARGO_HOME=/opt/rust/cargo
+
+log() { echo "[bake] $(date -u +%H:%M:%S) $*"; }
+
+# Compose hostnames (db, clickhouse, ...) that resolve to 127.0.0.1 on dev machines via
+# /etc/hosts. Needed twice: during the bake itself, and again at task time — the sandbox
+# runtime rewrites /etc/hosts at boot, so the baked bootstrap-dev-stack helper (installed
+# below) restores them for the run.
+COMPOSE_HOSTS=(db redis7 kafka clickhouse clickhouse-coordinator objectstorage seaweedfs temporal)
+for host in "${COMPOSE_HOSTS[@]}"; do
+ grep -qE "127\.0\.0\.1[[:space:]].*\b${host}\b" /etc/hosts || echo "127.0.0.1 ${host}" >> /etc/hosts
+done
+
+log "starting dockerd"
+# The first invocation's exec can be reaped while dockerd brings up its bridge
+# (see Dockerfile.sandbox-vm) — the helper is idempotent, so just run it again.
+start-dockerd || start-dockerd
+docker info > /dev/null
+
+log "cloning posthog/posthog"
+rm -rf "$BAKE_ROOT"
+mkdir -p "$BAKE_ROOT"
+# The directory basename must be "posthog": docker compose derives the project name
+# (and therefore volume/container names) from it, and it has to match the project name
+# task-time runs get from their /tmp/workspace/repos/posthog/posthog checkout.
+git clone --depth 1 https://github.com/posthog/posthog.git "$REPO_DIR"
+cd "$REPO_DIR"
+BAKED_SHA=$(git rev-parse HEAD)
+export COMPOSE_PROJECT_NAME=posthog
+
+log "installing dev toolchain (brotli, phrocs, go, rust)"
+# On dev machines flox provides these; the sandbox has no flox, so `hogli start`
+# dead-ends without them: bin/start fails at bin/download-mmdb (brotli) and then at
+# process-manager resolution (phrocs), and the Go/Rust procs and rust/bin migrators
+# need their toolchains.
+apt-get update
+apt-get install -y --no-install-recommends brotli make
+rm -rf /var/lib/apt/lists/*
+
+case "$(uname -m)" in
+ x86_64)
+ GO_ARCH=amd64
+ GO_SHA256="$GO_SHA256_AMD64"
+ RUSTUP_TARGET=x86_64-unknown-linux-gnu
+ RUSTUP_SHA256="$RUSTUP_SHA256_AMD64"
+ ;;
+ aarch64)
+ GO_ARCH=arm64
+ GO_SHA256="$GO_SHA256_ARM64"
+ RUSTUP_TARGET=aarch64-unknown-linux-gnu
+ RUSTUP_SHA256="$RUSTUP_SHA256_ARM64"
+ ;;
+ *)
+ echo "unsupported architecture: $(uname -m)" >&2
+ exit 1
+ ;;
+esac
+curl -fsSL -o /tmp/go.tar.gz "https://go.dev/dl/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
+echo "${GO_SHA256} /tmp/go.tar.gz" | sha256sum -c -
+tar -xzf /tmp/go.tar.gz -C /usr/local
+rm /tmp/go.tar.gz
+ln -sf /usr/local/go/bin/go /usr/local/go/bin/gofmt /usr/local/bin/
+
+# phrocs is built from this checkout rather than downloaded via tools/phrocs/install.sh:
+# the phrocs-latest release that installer trusts is mutable and ships checksums.txt
+# next to its binaries, so verifying one against the other proves nothing an attacker
+# altering the release could not fake. The source build (with go.sum-pinned deps)
+# derives from the same HTTPS-cloned commit the rest of the bake already executes as
+# root — and is what bin/start treats as canonical anyway; task-time checkouts have no
+# flox-built dist binary and resolve phrocs from PATH.
+make -C tools/phrocs build
+install -m 0755 tools/phrocs/dist/phrocs /usr/local/bin/phrocs
+phrocs --version
+
+# Rust under /opt/rust, exposed through env-setting shims so any task-time process
+# finds the toolchain regardless of $HOME or login-shell profile handling. A pinned,
+# checksum-verified rustup-init binary instead of piping sh.rustup.rs into sh; rustup
+# itself then verifies the toolchain components against the channel manifest.
+curl -fsSL -o /tmp/rustup-init "https://static.rust-lang.org/rustup/archive/${RUSTUP_VERSION}/${RUSTUP_TARGET}/rustup-init"
+echo "${RUSTUP_SHA256} /tmp/rustup-init" | sha256sum -c -
+chmod +x /tmp/rustup-init
+# minimal profile plus the two components the repo's standard Rust workflows need on
+# top of it: hogli format:rust runs rustfmt directly, and reproducing ci-rust locally
+# runs cargo clippy — both are in .flox/env/manifest.toml for dev machines too.
+/tmp/rustup-init -y --no-modify-path --profile minimal --component rustfmt --component clippy \
+ --default-toolchain "$RUST_TOOLCHAIN"
+rm /tmp/rustup-init
+for tool in cargo rustc rustup rustfmt cargo-fmt cargo-clippy clippy-driver; do
+ printf '%s\n' \
+ '#!/bin/sh' \
+ 'export RUSTUP_HOME="${RUSTUP_HOME:-/opt/rust/rustup}" CARGO_HOME="${CARGO_HOME:-/opt/rust/cargo}"' \
+ "exec /opt/rust/cargo/bin/$tool \"\$@\"" > "/usr/local/bin/$tool"
+ chmod +x "/usr/local/bin/$tool"
+done
+
+log "installing sqlx-cli (rust/bin migrators)"
+cargo install sqlx-cli --version "$SQLX_CLI_VERSION" --locked --no-default-features --features native-tls,postgres
+ln -sf /opt/rust/cargo/bin/sqlx /usr/local/bin/sqlx
+
+log "warming cargo registry for the rust workspace"
+# Download-only: task-time `cargo run` in bin/start-rust-service still compiles, but
+# skips fetching the whole dependency graph. The compiled target/ dir lives inside the
+# checkout and is discarded with it, so it cannot be warmed here.
+(cd rust && cargo fetch)
+
+log "warming go module cache (livestream)"
+# Mirrors the cargo fetch above: GOMODCACHE defaults to /root/go/pkg/mod, outside the
+# checkout, so a task-time bin/start-go-service skips the cold module download.
+(cd livestream && go mod download)
+
+log "warming python environment (uv sync)"
+# The checkout's .venv is discarded with the checkout; the uv cache persists in the
+# image and makes the task-time `uv sync` a fast linking pass.
+uv sync --frozen
+
+log "warming pnpm store"
+# pnpm fetch downloads every package in pnpm-lock.yaml into the content-addressed
+# store (under ~/.local/share/pnpm), which lives outside the checkout and survives the
+# cleanup below — the task-time `pnpm install` becomes mostly a linking pass. Bake and
+# task time run the same image's pnpm, so the store layout always matches.
+pnpm fetch --frozen-lockfile
+# Link a full node_modules once: it backfills anything fetch skipped (git/tarball
+# resolutions) and provides the workspace-pinned playwright CLI for the browser
+# install below. --ignore-scripts keeps third-party postinstall hooks from failing
+# the bake — the deliberate cost is that native-addon builds (node-rdkafka's node-gyp
+# compile, chiefly) are not warmed and still compile during the task-time install,
+# which runs scripts as usual. node_modules itself is discarded with the checkout.
+pnpm install --prefer-offline --frozen-lockfile --ignore-scripts
+
+log "installing playwright chromium (+ system deps)"
+# Storybook builds and screenshot runs drive Playwright's Chromium. Browsers land in
+# ~/.cache/ms-playwright, outside the checkout; --with-deps apt-installs the shared
+# libraries Chromium needs. The version follows the workspace's @playwright/test pin —
+# if a task's checkout bumps the pin, playwright just downloads the newer build then.
+node_modules/.bin/playwright install --with-deps chromium
+rm -rf /var/lib/apt/lists/*
+
+log "pulling dev stack images"
+# Warm every service image a default-intent `hogli start` would pull (profile-gated
+# services are deliberately left cold — see the header). --ignore-pull-failures: services
+# whose image tag is momentarily unpublished fall back to task-time pull/build instead
+# of failing the whole bake.
+docker compose -f docker-compose.dev.yml pull --quiet --ignore-pull-failures
+# --ignore-pull-failures exits 0 no matter how many pulls failed, and a silently-cold
+# image costs every task run the multi-gigabyte pull this bake exists to remove — so
+# name anything missing from the warm set where bake logs are read.
+while read -r image; do
+ docker image inspect "$image" > /dev/null 2>&1 || log "WARNING: image not warmed (pull failed): ${image}"
+done < <(docker compose -f docker-compose.dev.yml config --images | sort -u)
+
+log "starting datastores"
+# Only what migrations need. --no-build so a service whose pull failed above can never
+# trigger a from-source image build during the bake; everything else starts at task time.
+docker compose -f docker-compose.dev.yml up -d --no-build db redis7 zookeeper kafka clickhouse objectstorage
+bin/wait-for-docker
+
+log "running migrations"
+# Mirror the env bin/start assembles for the migrate-* units: committed defaults from
+# the checked-in env files (loaded with the same skip-if-set, skip-comments semantics),
+# plus the derived persons URL. DEBUG=1 from .env.development keeps Django's insecure
+# dev SECRET_KEY default acceptable.
+load_env_defaults() {
+ while IFS='=' read -r name value; do
+ [[ -z "$name" || "$name" == \#* ]] && continue
+ # op:// refs only resolve under `op run` (see bin/start); exporting the literal
+ # would bake a garbage value into the image.
+ [[ "$value" == *op://* ]] && continue
+ if [[ -z "${!name:-}" ]]; then
+ export "$name=$value"
+ fi
+ done < "$1"
+}
+load_env_defaults .env.development
+load_env_defaults .env.services
+export PERSONS_DB_WRITER_URL="${PERSONS_DB_WRITER_URL:-postgres://posthog:posthog@db:5432/posthog_persons}"
+
+# shellcheck disable=SC1091
+source .venv/bin/activate
+# ClickHouse runs strictly after Postgres: bin/migrate parallelizes the two scopes when
+# both are requested, but on a fresh database migrate_clickhouse crashes until Postgres
+# migrations have created posthog_instancesetting (the same race bin/mprocs.yaml gates
+# with wait-for-postgres-tables).
+bin/migrate --scope=postgres --scope=persons
+bin/migrate --scope=clickhouse
+
+log "running rust-driven migrations"
+# Same connection URLs bin/start derives for these scopes; the rust/bin migrators
+# otherwise default to localhost with per-store host/user envs.
+export CYCLOTRON_DATABASE_URL="${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@db:5432/cyclotron}"
+export CYCLOTRON_NODE_DATABASE_URL="${CYCLOTRON_NODE_DATABASE_URL:-postgres://posthog:posthog@db:5432/cyclotron_node}"
+export BEHAVIORAL_COHORTS_DATABASE_URL="${BEHAVIORAL_COHORTS_DATABASE_URL:-postgres://posthog:posthog@db:5432/behavioral_cohorts}"
+export FLAGS_READ_STORE_DATABASE_URL="${FLAGS_READ_STORE_DATABASE_URL:-postgres://posthog:posthog@db:5432/flags_read_store}"
+bin/migrate --scope=cyclotron --scope=behavioral-cohorts --scope=flags-read-store
+
+log "stopping dev stack"
+# stop (not down): the stopped containers keep their anonymous volumes — ClickHouse
+# keeps its data in one — and `docker compose up` at task time reuses them as long as
+# the compose config still matches.
+docker compose -f docker-compose.dev.yml stop --timeout 120
+
+log "stopping dockerd"
+if [[ -f /var/run/docker.pid ]]; then
+ kill "$(cat /var/run/docker.pid)" 2> /dev/null || true
+ for _ in $(seq 1 120); do
+ docker info > /dev/null 2>&1 || break
+ sleep 1
+ done
+fi
+# Fail closed rather than snapshot with a live daemon: the loop above swallows the
+# did-it-exit signal, and this image is shared fleet-wide — a bake with a wedged
+# dockerd is not a state worth publishing.
+if docker info > /dev/null 2>&1; then
+ echo "dockerd still running after 120s; refusing to snapshot" >&2
+ exit 1
+fi
+# Leftover runtime files would confuse the task-time start-dockerd.
+rm -f /var/run/docker.pid /var/run/docker.sock
+
+log "cleaning up"
+# The checkout goes away — node_modules, Storybook dist, Vite/Turbo caches included.
+# Deliberate: baked build output would reflect the baked commit, not the task's
+# checkout, so e.g. Storybook screenshots would silently miss the agent's edits.
+# The warmed stores above keep the task-time installs that precede a rebuild cheap.
+cd /
+rm -rf "$BAKE_ROOT"
+
+log "installing task-time bootstrap helper"
+# A restored sandbox is not self-starting: the sandbox runtime rewrites /etc/hosts at
+# boot and dockerd does not autostart. This one-shot, idempotent helper restores both
+# so a task-time `hogli start` finds the baked docker state. It lives in the image (not
+# the checkout) because it configures the VM itself, independent of any clone.
+cat > /usr/local/bin/bootstrap-dev-stack << EOF
+#!/usr/bin/env bash
+# Task-time bootstrap for the prebaked PostHog dev stack (written by
+# bake-posthog-dev-stack.sh). Idempotent — safe to re-run.
+set -euo pipefail
+# Pin PATH to system dirs: a directory resume can mount an untrusted workspace and a
+# poisoned PATH could otherwise resolve start-dockerd/docker/grep to attacker binaries.
+# The provisioning-side launcher already scrubs the environment, but harden the helper
+# itself so it is safe however it is invoked. start-dockerd lives in /usr/local/bin.
+export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+for host in ${COMPOSE_HOSTS[*]}; do
+ grep -qE "127\\.0\\.0\\.1[[:space:]].*\\b\${host}\\b" /etc/hosts || echo "127.0.0.1 \${host}" >> /etc/hosts
+done
+/usr/local/bin/start-dockerd || /usr/local/bin/start-dockerd
+docker info > /dev/null
+echo "dev stack ready — from the posthog checkout: uv sync && source .venv/bin/activate && hogli start -y -d && hogli wait"
+EOF
+chmod +x /usr/local/bin/bootstrap-dev-stack
+
+mkdir -p "$(dirname "$BAKE_MANIFEST")"
+printf '{"baked_at": "%s", "posthog_sha": "%s", "bootstrap": "bootstrap-dev-stack"}\n' \
+ "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$BAKED_SHA" > "$BAKE_MANIFEST"
+log "bake complete at $BAKED_SHA"
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index 4f62417f7f64..b88ae1ccbce1 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -1,4 +1,6 @@
from .automation import RunTaskAutomationWorkflow, run_task_automation_activity
+from .bake_dev_stack_image.activities import bake_and_publish_dev_stack_image
+from .bake_dev_stack_image.workflow import BakeDevStackImageWorkflow
from .build_image.activities import build_and_publish_image, mark_image_build_failed, scan_image_spec
from .build_image.workflow import BuildSandboxImageWorkflow
from .create_snapshot.activities import (
@@ -63,6 +65,7 @@ WORKFLOWS = [
RunTaskAutomationWorkflow,
RunLoopWorkflow,
BuildSandboxImageWorkflow,
+ BakeDevStackImageWorkflow,
]
ACTIVITIES = [
@@ -117,4 +120,6 @@ ACTIVITIES = [
scan_image_spec,
build_and_publish_image,
mark_image_build_failed,
+ # bake_dev_stack_image activities
+ bake_and_publish_dev_stack_image,
]
diff --git a/products/tasks/backend/temporal/bake_dev_stack_image/activities.py b/products/tasks/backend/temporal/bake_dev_stack_image/activities.py
new file mode 100644
index 000000000000..3302d1167a19
--- /dev/null
+++ b/products/tasks/backend/temporal/bake_dev_stack_image/activities.py
@@ -0,0 +1,68 @@
+import logging
+import threading
+import contextvars
+from dataclasses import dataclass
+from typing import Any
+
+from temporalio import activity
+
+from posthog.temporal.common.utils import asyncify
+
+from products.tasks.backend.logic.services.dev_stack_image import (
+ DEV_STACK_IMAGE_NAME,
+ DevStackImageBakeError,
+ bake_dev_stack_image,
+)
+from products.tasks.backend.metrics import observe_dev_stack_image_bake
+from products.tasks.backend.temporal.observability import log_activity_execution
+
+logger = logging.getLogger(__name__)
+
+BAKE_HEARTBEAT_INTERVAL_SECONDS = 30
+
+
+@dataclass
+class BakeDevStackImageInput:
+ publish_name: str = DEV_STACK_IMAGE_NAME
+
+ def to_log_context(self) -> dict[str, Any]:
+ return {"publish_name": self.publish_name}
+
+
+@asyncify
+def bake_and_publish_dev_stack_image(input: BakeDevStackImageInput) -> str:
+ """Run the bake and publish the snapshot under the input's Modal image name.
+
+ Heartbeats from a side thread while the sync bake blocks (15-90 minutes), so a
+ worker crash or redeploy mid-bake is detected within the workflow's heartbeat
+ timeout and retried promptly, instead of burning the full 3-hour start_to_close
+ (mirrors send_followup_to_sandbox).
+ """
+ stop_heartbeat = threading.Event()
+ heartbeat_ctx = contextvars.copy_context()
+
+ def _heartbeat_loop() -> None:
+ while not stop_heartbeat.wait(BAKE_HEARTBEAT_INTERVAL_SECONDS):
+ try:
+ activity.heartbeat()
+ except Exception:
+ return
+
+ heartbeat_thread = threading.Thread(target=lambda: heartbeat_ctx.run(_heartbeat_loop), daemon=True)
+ heartbeat_thread.start()
+ try:
+ with log_activity_execution("bake_and_publish_dev_stack_image", **input.to_log_context()):
+ try:
+ image_id = bake_dev_stack_image(input.publish_name)
+ except DevStackImageBakeError:
+ observe_dev_stack_image_bake("bake_failed")
+ raise
+ except Exception:
+ observe_dev_stack_image_bake("failed")
+ raise
+ observe_dev_stack_image_bake("succeeded")
+ return image_id
+ finally:
+ stop_heartbeat.set()
+ heartbeat_thread.join(timeout=2)
diff --git a/products/tasks/backend/temporal/bake_dev_stack_image/test_activities.py b/products/tasks/backend/temporal/bake_dev_stack_image/test_activities.py
new file mode 100644
index 000000000000..ac2bb910627f
--- /dev/null
+++ b/products/tasks/backend/temporal/bake_dev_stack_image/test_activities.py
@@ -0,0 +1,38 @@
+import time
+
+import pytest
+from unittest.mock import patch
+
+from temporalio.testing import ActivityEnvironment
+
+from products.tasks.backend.temporal.bake_dev_stack_image.activities import (
+ BakeDevStackImageInput,
+ bake_and_publish_dev_stack_image,
+)
+
+
+async def test_bake_activity_heartbeats_while_the_sync_bake_blocks() -> None:
+ # Without heartbeats, a worker crash mid-bake goes undetected until the 3-hour
+ # start_to_close (~6h across both attempts) instead of the heartbeat timeout.
+ env = ActivityEnvironment()
+ heartbeats: list[tuple] = []
+ env.on_heartbeat = lambda *details: heartbeats.append(details)
+
+ def slow_bake(publish_name: str) -> str:
+ time.sleep(0.3)
+ return "im-1"
+
+ with (
+ patch("products.tasks.backend.temporal.bake_dev_stack_image.activities.BAKE_HEARTBEAT_INTERVAL_SECONDS", 0.01),
+ patch(
+ "products.tasks.backend.temporal.bake_dev_stack_image.activities.bake_dev_stack_image",
+ side_effect=slow_bake,
+ ),
+ ):
+ result = await env.run(
+ bake_and_publish_dev_stack_image, BakeDevStackImageInput(publish_name="posthog-dev-stack")
+ )
+
+ assert result == "im-1"
+ assert heartbeats
diff --git a/products/tasks/backend/temporal/bake_dev_stack_image/workflow.py b/products/tasks/backend/temporal/bake_dev_stack_image/workflow.py
new file mode 100644
index 000000000000..90b256373fa4
--- /dev/null
+++ b/products/tasks/backend/temporal/bake_dev_stack_image/workflow.py
@@ -0,0 +1,43 @@
+import json
+from datetime import timedelta
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from .activities import BakeDevStackImageInput, bake_and_publish_dev_stack_image
+
+# Matches the bake sandbox's TTL: the 90-minute bake execution budget plus the
+# published-image snapshot attempts (each up to 30 minutes, retried in place).
+BAKE_ACTIVITY_TIMEOUT = timedelta(hours=3)
+
+
[email protected](name="bake-dev-stack-image")
+class BakeDevStackImageWorkflow(PostHogWorkflow):
+ """Bakes and republishes the prebaked PostHog dev-stack VM image.
+
+ Dispatched nightly (see `bake_dev_stack_image_task` in the tasks facade) so the
+ baked migration state stays close to master and task-time `hogli start` only
+ applies a day's worth of migrations.
+ """
+
+ @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"})
+
+ @workflow.run
+ async def run(self, input: BakeDevStackImageInput) -> str:
+ return await workflow.execute_activity(
+ bake_and_publish_dev_stack_image,
+ input,
+ start_to_close_timeout=BAKE_ACTIVITY_TIMEOUT,
+ # The activity heartbeats while the sync bake blocks, so a worker crash or
+ # redeploy mid-bake is detected here instead of at the 3-hour start_to_close.
+ heartbeat_timeout=timedelta(minutes=3),
+ # At most one automated re-bake: each attempt is a full 15-25 minute stack build.
+ # The workflow itself is started with maximum_attempts=1 (see temporal/client.py)
+ # so these attempts never multiply; the nightly schedule is the outer retry loop.
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 2eefc31a9724..d43d404c79b9 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -18,8 +18,10 @@ from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.constants import AGENT_OTEL_TELEMETRY_STATE_KEY, SANDBOX_EVENT_INGEST_FEATURE_FLAG
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.feature_flags import is_agent_otel_telemetry_enabled, is_native_steering_signals_enabled
+from products.tasks.backend.logic.services.dev_stack_image import DEV_STACK_IMAGE_NAME
from products.tasks.backend.metrics import AGENT_OTEL_TELEMETRY_STAMPED_TOTAL, observe_task_run_workflow_start
from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.temporal.bake_dev_stack_image.workflow import BakeDevStackImageInput
from products.tasks.backend.temporal.build_image.workflow import BuildSandboxImageInput
from products.tasks.backend.temporal.constants import (
SEND_STEER_SIGNAL,
@@ -514,6 +516,29 @@ 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:
+ """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
+ fresh one instead of blocking it.
+ """
+ client = sync_connect()
+ asyncio.run(
+ client.start_workflow(
+ "bake-dev-stack-image",
+ BakeDevStackImageInput(publish_name=publish_name),
+ id=f"bake-dev-stack-image-{publish_name}",
+ id_reuse_policy=WorkflowIDReusePolicy.TERMINATE_IF_RUNNING,
+ task_queue=settings.TASKS_TASK_QUEUE,
+ # A single workflow attempt: each bake is a full 15-25 minute stack build, the
+ # activity inside already retries once, and the nightly schedule plus the
+ # base-digest sweep are the outer retry loop. Workflow-level retries would
+ # multiply with the activity's into up to four consecutive bakes.
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ )
+
+
def execute_build_sandbox_image_workflow(image_id: str, team_id: int, *, refresh: bool = False) -> None:
"""Start (or restart) the scan → build → publish workflow for a custom sandbox image."""
client = sync_connect()
diff --git a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
index 404ff217aac3..edf586c4eec7 100644
--- a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
@@ -19,6 +19,12 @@ from products.tasks.backend.temporal.metrics import increment_snapshot_create, r
logger = structlog.get_logger(__name__)
+# Both callers (process_task and execute_sandbox workflows) give this activity a
+# 5-minute start_to_close budget; the Modal-side snapshot timeout must be tighter so
+# a slow snapshot surfaces as the classified SnapshotTimeoutError instead of Temporal
+# killing the attempt first.
+RESUME_SNAPSHOT_TIMEOUT_SECONDS = 4 * 60
+
PENDING_USER_STATE_KEYS = [
"pending_user_message",
"pending_user_artifact_ids",
@@ -81,7 +87,7 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap
if snapshot_kind == SNAPSHOT_KIND_DIRECTORY:
external_id = sandbox.create_directory_snapshot(snapshot_mount_path)
else:
- external_id = sandbox.create_snapshot()
+ external_id = sandbox.create_snapshot(timeout_seconds=RESUME_SNAPSHOT_TIMEOUT_SECONDS)
except SnapshotTimeoutError as e:
outcome = "transient_error"
logger.warning("create_resume_snapshot_transient_error", sandbox_id=input.sandbox_id, error=str(e))
diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
index 1f7b2c3ea9d0..31307f8c9eaa 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
@@ -317,6 +317,12 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
sandbox_created_at = timezone.now()
used_snapshot = bool((resume_snapshot_ext_id or snapshot) and sandbox.config.snapshot_restored)
sandbox_creation_timer.set_used_snapshot(used_snapshot)
+ if sandbox.config.image_fallback:
+ emit_agent_log(ctx.run_id, "warn", f"Sandbox image downgraded: {sandbox.config.image_fallback}")
+ if sandbox.launch_dev_stack_bootstrap():
+ emit_agent_log(
+ ctx.run_id, "debug", "Warming the prebaked dev stack in the background (compose host aliases + dockerd)"
+ )
snapshot_outcome = "used" if used_snapshot else "fresh" if snapshot_source == "none" else "fallback"
metrics_snapshot_kind = snapshot_kind if snapshot_source != "none" else "none"
increment_snapshot_usage(used_snapshot, snapshot_source=snapshot_source, snapshot_kind=metrics_snapshot_kind)
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 54722de3aace..386ae0b3caa5 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -22,6 +22,7 @@ from products.tasks.backend.constants import (
get_vm_sandbox_flag_payload,
vm_sandbox_allowed_origin_products,
vm_sandbox_default_base_origin_products,
+ vm_sandbox_default_custom_image,
)
from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError
from products.tasks.backend.facade.api import ensure_task_run_session
@@ -417,7 +418,17 @@ def _is_agent_otel_telemetry_enabled(
return enabled
-def _is_modal_vm_sandbox_enabled(
+@dataclass(frozen=True)
+class VmSandboxDecision:
+ use_vm_sandbox: bool
+ # Modal image name from the flag payload that VM runs fall back to when no custom
+ # image was picked. None whenever the payload was not consulted (state override,
+ # flag error, restricted egress) or defines no default — image-builder runs must
+ # keep layering on the plain VM base, never on a prebaked default.
+ default_custom_image: str | None = None
+
+
+def _resolve_modal_vm_sandbox(
*,
distinct_id: str,
organization_id: str,
@@ -426,36 +437,40 @@ def _is_modal_vm_sandbox_enabled(
allowed_domains: list[str] | None,
custom_image_available: bool = False,
state: dict | None = None,
-) -> bool:
+) -> VmSandboxDecision:
if allowed_domains is not None:
log_with_activity_context(
"modal_vm_sandbox_skipped_restricted_egress",
run_id=run_id,
use_modal_vm_sandbox=False,
)
- return False
+ return VmSandboxDecision(use_vm_sandbox=False)
# A trusted, server-set per-run override (image builders) forces the runtime
# decision without consulting the flag; any non-bool value is ignored.
raw_state_override = (state or {}).get("use_modal_vm_sandbox")
state_override: bool | None = raw_state_override if isinstance(raw_state_override, bool) else None
- # Resolve the flag payload once and derive both allowlists from it, skipping the
+ # Resolve the flag payload once and derive the routing config from it, skipping the
# fetch entirely when a bool state override is present (so image-builder runs never
# depend on the flag service):
# - allowed_origins: origins permitted on the VM runtime (custom images are VM-only).
# - default_base_origins: origins that may run on the bare VM *base* image even
# without a custom image — makes the VM runtime the default for standard runs.
+ # - default_custom_image: image VM runs default to when the user picked none, so
+ # org-targeted payload variants decide which default VM image an org gets.
allowed_origins: set[str] = set()
default_base_origins: set[str] = set()
+ default_custom_image: str | None = None
if state_override is None:
try:
payload = get_vm_sandbox_flag_payload(distinct_id=distinct_id, organization_id=organization_id)
except Exception as e:
log_with_activity_context("modal_vm_sandbox_flag_check_failed", run_id=run_id, error=str(e))
- return False
+ return VmSandboxDecision(use_vm_sandbox=False)
allowed_origins = vm_sandbox_allowed_origin_products(payload)
default_base_origins = vm_sandbox_default_base_origin_products(payload)
+ default_custom_image = vm_sandbox_default_custom_image(payload)
origin_allows_default_base = origin_product in default_base_origins
@@ -472,7 +487,7 @@ def _is_modal_vm_sandbox_enabled(
run_id=run_id,
use_modal_vm_sandbox=False,
)
- return False
+ return VmSandboxDecision(use_vm_sandbox=False)
if state_override is not None:
log_with_activity_context(
@@ -480,7 +495,7 @@ def _is_modal_vm_sandbox_enabled(
run_id=run_id,
use_modal_vm_sandbox=state_override,
)
- return state_override
+ return VmSandboxDecision(use_vm_sandbox=state_override)
result = origin_product in allowed_origins or origin_allows_default_base
log_with_activity_context(
@@ -490,10 +505,14 @@ def _is_modal_vm_sandbox_enabled(
origin_product=origin_product,
allowed_origin_products=sorted(allowed_origins),
default_base_origin_products=sorted(default_base_origins),
+ default_custom_image=default_custom_image,
custom_image_available=custom_image_available,
use_modal_vm_sandbox=result,
)
- return result
+ return VmSandboxDecision(
+ use_vm_sandbox=result,
+ default_custom_image=default_custom_image if result else None,
+ )
def _is_burstable_sandbox_resources_enabled(
@@ -829,7 +848,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
run_id=run_id,
state=state,
)
- use_modal_vm_sandbox = _is_modal_vm_sandbox_enabled(
+ vm_sandbox_decision = _resolve_modal_vm_sandbox(
distinct_id=distinct_id,
organization_id=organization_id,
run_id=run_id,
@@ -838,6 +857,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
custom_image_available=environment_custom_image_name is not None,
state=state,
)
+ use_modal_vm_sandbox = vm_sandbox_decision.use_vm_sandbox
emit_agent_log(
run_id,
"debug",
@@ -855,6 +875,12 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
"This environment's custom image requires the VM runtime, which is not enabled for this run; "
"using the default base image",
)
+ elif vm_sandbox_decision.default_custom_image:
+ # Org-level default from the flag payload, only ever set when the run resolved to
+ # the VM runtime — provisioning falls back to the plain VM base automatically if
+ # this image is missing or unloadable.
+ custom_image_name = vm_sandbox_decision.default_custom_image
+ emit_agent_log(run_id, "debug", f"Using the organization's default custom base image: {custom_image_name}")
use_modal_network_allowlist = _is_modal_network_allowlist_enabled(
distinct_id=distinct_id,
organization_id=organization_id,
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 306d7b8f466d..4c2860f5b1b8 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -602,6 +602,18 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cre
(prepared.snapshot_external_id or prepared.snapshot_id) and sandbox.config.snapshot_restored
)
sandbox_creation_timer.set_used_snapshot(actual_used_snapshot)
+ if sandbox.config.image_fallback:
+ emit_agent_log(
+ ctx.run_id,
+ "warn",
+ f"Sandbox image downgraded: {sandbox.config.image_fallback}",
+ )
+ if sandbox.launch_dev_stack_bootstrap():
+ emit_agent_log(
+ ctx.run_id,
+ "debug",
+ "Warming the prebaked dev stack in the background (compose host aliases + dockerd)",
+ )
create_ms = sandbox_creation_timer.elapsed_ms
snapshot_outcome = (
"used" if actual_used_snapshot else "fresh" if prepared.snapshot_source == "none" else "fallback"
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index 9f496e803a20..4c61a8eaf622 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -18,19 +18,21 @@ from products.tasks.backend.constants import (
SANDBOX_EVENT_INGEST_FEATURE_FLAG,
vm_sandbox_allowed_origin_products,
vm_sandbox_default_base_origin_products,
+ vm_sandbox_default_custom_image,
)
from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError
from products.tasks.backend.models import SandboxEnvironment, Task
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (
GetTaskProcessingContextInput,
TaskProcessingContext,
+ VmSandboxDecision,
_is_agent_otel_telemetry_enabled,
_is_agent_proxy_keep_stream_open_enabled,
_is_burstable_sandbox_resources_enabled,
_is_continue_as_new_enabled,
- _is_modal_vm_sandbox_enabled,
_is_rtk_enabled,
_is_sandbox_event_ingest_enabled,
+ _resolve_modal_vm_sandbox,
get_task_processing_context,
)
from products.tasks.backend.temporal.process_task.utils import get_actor_distinct_id
@@ -762,14 +764,14 @@ class TestGetTaskProcessingContextActivity:
return_value=payload,
) as payload_mock:
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
origin_product="user_created",
allowed_domains=None,
custom_image_available=True,
- )
+ ).use_vm_sandbox
is expected
)
@@ -788,13 +790,13 @@ class TestGetTaskProcessingContextActivity:
side_effect=RuntimeError("flag service failed"),
):
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
origin_product="user_created",
allowed_domains=None,
- )
+ ).use_vm_sandbox
is False
)
@@ -812,7 +814,7 @@ class TestGetTaskProcessingContextActivity:
return_value=None,
) as payload_mock:
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
@@ -820,7 +822,7 @@ class TestGetTaskProcessingContextActivity:
allowed_domains=None,
custom_image_available=custom_image_available,
state={"use_modal_vm_sandbox": True},
- )
+ ).use_vm_sandbox
is expected
)
@@ -832,13 +834,13 @@ class TestGetTaskProcessingContextActivity:
return_value='{"origin_products": ["user_created"]}',
) as payload_mock:
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
origin_product="user_created",
allowed_domains=["github.com"],
- )
+ ).use_vm_sandbox
is False
)
@@ -850,14 +852,14 @@ class TestGetTaskProcessingContextActivity:
return_value='{"origin_products": ["user_created"]}',
) as payload_mock:
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
origin_product="user_created",
allowed_domains=["github.com"],
state={"use_modal_vm_sandbox": True},
- )
+ ).use_vm_sandbox
is False
)
@@ -872,13 +874,13 @@ class TestGetTaskProcessingContextActivity:
return_value='{"default_base_origin_products": ["user_created"]}',
) as payload_mock:
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
origin_product="user_created",
allowed_domains=["github.com"],
- )
+ ).use_vm_sandbox
is False
)
@@ -892,7 +894,7 @@ class TestGetTaskProcessingContextActivity:
return_value='{"default_base_origin_products": ["user_created"]}',
) as payload_mock:
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
@@ -900,7 +902,7 @@ class TestGetTaskProcessingContextActivity:
allowed_domains=None,
custom_image_available=True,
state={"use_modal_vm_sandbox": False},
- )
+ ).use_vm_sandbox
is False
)
@@ -945,14 +947,14 @@ class TestGetTaskProcessingContextActivity:
return_value=payload,
):
assert (
- _is_modal_vm_sandbox_enabled(
+ _resolve_modal_vm_sandbox(
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
origin_product=origin_product,
allowed_domains=None,
custom_image_available=custom_image_available,
- )
+ ).use_vm_sandbox
is expected
)
@@ -988,6 +990,73 @@ class TestGetTaskProcessingContextActivity:
def test_vm_sandbox_default_base_origin_products_parsing(self, payload, expected):
assert vm_sandbox_default_base_origin_products(payload) == expected
+ @pytest.mark.parametrize(
+ "payload, expected",
+ [
+ (None, None),
+ ({"default_custom_image": "posthog-dev-stack"}, "posthog-dev-stack"),
+ ('{"default_custom_image": "posthog-dev-stack"}', "posthog-dev-stack"),
+ ({"default_custom_image": " padded "}, "padded"),
+ # Empty/whitespace/non-string values and payloads without the key must resolve
+ # to "no default", never crash routing — the payload is human-edited flag JSON.
+ ({"default_custom_image": ""}, None),
+ ({"default_custom_image": " "}, None),
+ ({"default_custom_image": 3}, None),
+ ({"origin_products": ["user_created"]}, None),
+ (["posthog-dev-stack"], None),
+ ("not-json", None),
+ ],
+ )
+ def test_vm_sandbox_default_custom_image_parsing(self, payload, expected):
+ assert vm_sandbox_default_custom_image(payload) == expected
+
+ @pytest.mark.parametrize(
+ "origin_product, expected",
+ [
+ # Default-base origin resolves to VM and picks up the org's default image.
+ (
+ "user_created",
+ VmSandboxDecision(use_vm_sandbox=True, default_custom_image="posthog-dev-stack"),
+ ),
+ # An origin that stays on gVisor must not leak the (VM-only) default image out.
+ ("signals_scout", VmSandboxDecision(use_vm_sandbox=False)),
+ ],
+ )
+ def test_modal_vm_sandbox_default_custom_image_resolution(self, origin_product, expected):
+ with patch(
+ VM_FLAG_PAYLOAD_TARGET,
+ return_value='{"default_base_origin_products": ["user_created"], "default_custom_image": "posthog-dev-stack"}',
+ ):
+ assert (
+ _resolve_modal_vm_sandbox(
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ origin_product=origin_product,
+ allowed_domains=None,
+ )
+ == expected
+ )
+
+ def test_modal_vm_sandbox_state_override_never_gets_default_custom_image(self):
+ # Image-builder runs (trusted state override) must keep layering on the plain VM
+ # base: the flag is never consulted, so the org default image cannot apply.
+ with patch(
+ VM_FLAG_PAYLOAD_TARGET,
+ return_value='{"default_base_origin_products": ["image_builder"], "default_custom_image": "posthog-dev-stack"}',
+ ) as payload_mock:
+ decision = _resolve_modal_vm_sandbox(
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ origin_product="image_builder",
+ allowed_domains=None,
+ state={"use_modal_vm_sandbox": True},
+ )
+
+ assert decision == VmSandboxDecision(use_vm_sandbox=True, default_custom_image=None)
+ payload_mock.assert_not_called()
+
@pytest.mark.parametrize(
"state,expected",
[
@@ -1055,6 +1124,22 @@ class TestGetTaskProcessingContextActivity:
assert result.use_modal_resume_snapshots is expected_resume_snapshots
assert result.use_modal_directory_resume_snapshots is directory_resume_snapshots
+ @pytest.mark.django_db(transaction=True)
+ def test_get_task_processing_context_applies_org_default_custom_image(self, activity_environment, test_task):
+ # Wiring guard for the elif chain in the activity body: a VM run with no
+ # user/environment image must land the payload's default in custom_image_name.
+ task_run = test_task.create_run()
+ input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))
+
+ with patch(
+ VM_FLAG_PAYLOAD_TARGET,
+ return_value='{"default_base_origin_products": ["user_created"], "default_custom_image": "posthog-dev-stack"}',
+ ):
+ result = async_to_sync(activity_environment.run)(get_task_processing_context, input_data)
+
+ assert result.use_modal_vm_sandbox is True
+ assert result.custom_image_name == "posthog-dev-stack"
+
@pytest.mark.django_db(transaction=True)
def test_get_task_processing_context_exposes_ci_prompt(self, activity_environment, test_task):
custom_prompt = "Re-run the failed mypy checks and push a fix."
diff --git a/products/tasks/backend/tests/test_dev_stack_image.py b/products/tasks/backend/tests/test_dev_stack_image.py
new file mode 100644
index 000000000000..232f835f15ca
--- /dev/null
+++ b/products/tasks/backend/tests/test_dev_stack_image.py
@@ -0,0 +1,274 @@
+import uuid
+
+import pytest
+from unittest.mock import patch
+
+from products.tasks.backend.exceptions import SnapshotTimeoutError
+from products.tasks.backend.logic.services.dev_stack_image import (
+ PUBLISH_SNAPSHOT_MAX_ATTEMPTS,
+ DevStackImageBakeError,
+ bake_dev_stack_image,
+ refresh_dev_stack_image_if_base_changed,
+)
+from products.tasks.backend.logic.services.sandbox import ExecutionResult
+
+BASE_REFERENCE = "ghcr.io/posthog/posthog-sandbox-vm@sha256:current"
+
+
+def _unique_publish_name() -> str:
+ # The baked-reference and claim stamps live in a shared cache; a unique image name
+ # per test keeps tests order-independent.
+ return f"posthog-dev-stack-test-{uuid.uuid4().hex[:8]}"
+
+
+class _FakeStream:
+ def __init__(self, exit_code: int):
+ self._exit_code = exit_code
+
+ def iter_stdout(self):
+ yield "[bake] starting dockerd\n"
+ yield "[bake] running migrations\n"
+
+ def wait(self) -> ExecutionResult:
+ return ExecutionResult(stdout="", stderr="", exit_code=self._exit_code, error=None)
+
+
+def _make_fake_sandbox_cls(exit_code: int, publish_failures: int = 0):
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
+
+ class FakeSandbox(ModalSandbox):
+ instances: list["FakeSandbox"] = []
+
+ def __init__(self): # skip ModalSandbox.__init__ — no real Modal objects in tests
+ self.id = "sb-fake"
+ self.destroyed = False
+ self.published_name: str | None = None
+ self.publish_attempts = 0
+ self.written_files: dict[str, bytes] = {}
+ FakeSandbox.instances.append(self)
+
+ @classmethod
+ def create(cls, config):
+ return cls()
+
+ def write_file(self, path: str, payload: bytes) -> ExecutionResult:
+ self.written_files[path] = payload
+ return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
+
+ def execute_stream(self, command: str, timeout_seconds: int | None = None) -> _FakeStream:
+ return _FakeStream(exit_code)
+
+ def publish_filesystem_image(self, publish_name: str) -> str:
+ self.publish_attempts += 1
+ if self.publish_attempts <= publish_failures:
+ raise SnapshotTimeoutError(
+ "Transient error creating snapshot",
+ {"sandbox_id": self.id},
+ cause=RuntimeError("Deadline exceeded"),
+ capture=False,
+ )
+ self.published_name = publish_name
+ return "im-fake-123"
+
+ def destroy(self) -> None:
+ self.destroyed = True
+
+ return FakeSandbox
+
+
+class TestBakeDevStackImage:
+ def test_successful_bake_publishes_destroys_sandbox_and_settles_refresh(self):
+ publish_name = _unique_publish_name()
+ fake_cls = _make_fake_sandbox_cls(exit_code=0)
+ with (
+ patch("products.tasks.backend.logic.services.dev_stack_image.get_sandbox_class", return_value=fake_cls),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ return_value=BASE_REFERENCE,
+ ),
+ ):
+ image_id = bake_dev_stack_image(publish_name)
+
+ assert image_id == "im-fake-123"
+ (sandbox,) = fake_cls.instances
+ assert sandbox.published_name == publish_name
+ assert sandbox.destroyed is True
+ # The bake script actually reaches the sandbox.
+ assert any(b"bin/migrate" in payload for payload in sandbox.written_files.values())
+
+ # A successful bake records the base reference it used, so the refresh sweep
+ # stops dispatching until the base digest actually moves.
+ with (
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image.is_dev_stack_image_bake_enabled",
+ return_value=True,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ return_value=BASE_REFERENCE,
+ ),
+ 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 False
+ dispatch_mock.assert_not_called()
+
+ def test_failed_bake_never_publishes_but_still_destroys_sandbox(self):
+ # Publishing after a failed bake would overwrite the last good image with a broken
+ # one under the same name — every internal VM run would then boot from it.
+ fake_cls = _make_fake_sandbox_cls(exit_code=1)
+ with patch("products.tasks.backend.logic.services.dev_stack_image.get_sandbox_class", return_value=fake_cls):
+ with pytest.raises(DevStackImageBakeError):
+ bake_dev_stack_image(_unique_publish_name())
+
+ (sandbox,) = fake_cls.instances
+ assert sandbox.published_name is None
+ assert sandbox.destroyed is True
+
+ def test_transient_snapshot_failure_retries_publish_without_rebaking(self):
+ # A snapshot timeout after a completed bake must retry on the still-running
+ # sandbox — failing the activity instead re-runs the whole 15-25 minute bake.
+ publish_name = _unique_publish_name()
+ fake_cls = _make_fake_sandbox_cls(exit_code=0, publish_failures=PUBLISH_SNAPSHOT_MAX_ATTEMPTS - 1)
+ with (
+ patch("products.tasks.backend.logic.services.dev_stack_image.get_sandbox_class", return_value=fake_cls),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ return_value=BASE_REFERENCE,
+ ),
+ ):
+ image_id = bake_dev_stack_image(publish_name)
+
+ assert image_id == "im-fake-123"
+ (sandbox,) = fake_cls.instances # a single sandbox: the bake itself never re-ran
+ assert sandbox.publish_attempts == PUBLISH_SNAPSHOT_MAX_ATTEMPTS
+ assert sandbox.published_name == publish_name
+
+ def test_records_base_reference_from_bake_start_when_digest_moves_mid_bake(self):
+ # The VM base can be republished during the long bake. The sweep must compare
+ # against the digest the bake actually layered on — recording the post-bake
+ # digest would make the stale publish look current and never rebake it.
+ publish_name = _unique_publish_name()
+ current = {"ref": "ghcr.io/posthog/posthog-sandbox-vm@sha256:at-bake-start"}
+ fake_cls = _make_fake_sandbox_cls(exit_code=0)
+
+ class MovingBaseSandbox(fake_cls): # type: ignore[valid-type, misc]
+ def publish_filesystem_image(self, publish_name: str) -> str:
+ current["ref"] = "ghcr.io/posthog/posthog-sandbox-vm@sha256:moved-mid-bake"
+ return super().publish_filesystem_image(publish_name)
+
+ with (
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image.get_sandbox_class",
+ return_value=MovingBaseSandbox,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ side_effect=lambda template: current["ref"],
+ ),
+ ):
+ bake_dev_stack_image(publish_name)
+
+ with (
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image.is_dev_stack_image_bake_enabled",
+ return_value=True,
+ ),
+ 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)
+
+ 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)
+ with patch("products.tasks.backend.logic.services.dev_stack_image.get_sandbox_class", return_value=fake_cls):
+ with pytest.raises(SnapshotTimeoutError):
+ bake_dev_stack_image(_unique_publish_name())
+
+ (sandbox,) = fake_cls.instances
+ assert sandbox.published_name is None
+ assert sandbox.destroyed is True
+
+
+class TestRefreshDevStackImageIfBaseChanged:
+ def _refresh(self, publish_name: str, *, flag_enabled: bool = True, base_reference: str | None = BASE_REFERENCE):
+ with (
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image.is_dev_stack_image_bake_enabled",
+ return_value=flag_enabled,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ return_value=base_reference,
+ ),
+ patch("products.tasks.backend.temporal.client.execute_bake_dev_stack_image_workflow") as dispatch_mock,
+ ):
+ dispatched = refresh_dev_stack_image_if_base_changed(publish_name)
+ return dispatched, dispatch_mock
+
+ def test_dispatches_at_most_once_per_new_base_digest(self):
+ # The 10-minute sweep must not redispatch while a rebake for the same digest is
+ # in flight or has failed — that would start a paid Modal bake on every tick.
+ publish_name = _unique_publish_name()
+
+ dispatched, dispatch_mock = self._refresh(publish_name)
+ assert dispatched is True
+ dispatch_mock.assert_called_once_with(publish_name)
+
+ dispatched, dispatch_mock = self._refresh(publish_name)
+ assert dispatched is False
+ dispatch_mock.assert_not_called()
+
+ @pytest.mark.parametrize("flag_enabled, base_reference", [(False, BASE_REFERENCE), (True, None)])
+ def test_skips_when_flag_off_or_no_registry_reference(self, flag_enabled, base_reference):
+ dispatched, dispatch_mock = self._refresh(
+ _unique_publish_name(), flag_enabled=flag_enabled, base_reference=base_reference
+ )
+ assert dispatched is False
+ dispatch_mock.assert_not_called()
+
+ def test_releases_claim_when_dispatch_fails_so_next_sweep_retries(self):
+ # A transient Temporal error must not consume the per-digest claim — that would
+ # silently block the fast refresh lane for the claim's whole 7-day TTL.
+ publish_name = _unique_publish_name()
+ with (
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image.is_dev_stack_image_bake_enabled",
+ return_value=True,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ return_value=BASE_REFERENCE,
+ ),
+ patch(
+ "products.tasks.backend.temporal.client.execute_bake_dev_stack_image_workflow",
+ side_effect=RuntimeError("temporal unavailable"),
+ ),
+ patch("products.tasks.backend.logic.services.dev_stack_image.observe_dev_stack_image_bake") as observe_mock,
+ ):
+ with pytest.raises(RuntimeError):
+ refresh_dev_stack_image_if_base_changed(publish_name)
+
+ observe_mock.assert_called_once_with("dispatch_failed")
+ dispatched, dispatch_mock = self._refresh(publish_name)
+ assert dispatched is True
+ dispatch_mock.assert_called_once_with(publish_name)
+
+
+class TestBakeDevStackImageTask:
+ def test_dispatch_failure_is_counted_and_reraised(self):
+ # A Temporal-unreachable night must be distinguishable from the flag being off
+ # in the bake metric, while the Celery task still records the failure.
+ from products.tasks.backend.facade.tasks import bake_dev_stack_image_task
+
+ with (
+ patch("products.tasks.backend.feature_flags.is_dev_stack_image_bake_enabled", return_value=True),
+ patch(
+ "products.tasks.backend.temporal.client.execute_bake_dev_stack_image_workflow",
+ side_effect=RuntimeError("temporal unavailable"),
+ ),
+ patch("products.tasks.backend.metrics.observe_dev_stack_image_bake") as observe_mock,
+ ):
+ with pytest.raises(RuntimeError):
+ bake_dev_stack_image_task()
+
+ observe_mock.assert_called_once_with("dispatch_failed")
diff --git a/products/tasks/backend/tests/test_feature_flags.py b/products/tasks/backend/tests/test_feature_flags.py
new file mode 100644
index 000000000000..6fab3f356de1
--- /dev/null
+++ b/products/tasks/backend/tests/test_feature_flags.py
@@ -0,0 +1,49 @@
+import pytest
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from products.tasks.backend.feature_flags import is_dev_stack_image_bake_enabled
+
+
+class TestIsDevStackImageBakeEnabled:
+ @pytest.mark.parametrize("flag_value, expected", [(True, True), (False, False), (None, False)])
+ def test_reflects_flag_and_scopes_by_region(self, flag_value, expected):
+ with (
+ override_settings(DEBUG=False),
+ patch("products.tasks.backend.feature_flags.get_instance_region", return_value="US"),
+ patch(
+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
+ return_value=flag_value,
+ ) as feature_enabled_mock,
+ ):
+ assert is_dev_stack_image_bake_enabled() is expected
+
+ # The region person property is the flag's release-condition input: dropping it
+ # would make a region-scoped condition never match and silently stop all bakes.
+ assert feature_enabled_mock.call_args.kwargs["person_properties"] == {"region": "US"}
+
+ def test_fails_closed_on_flag_service_error(self):
+ # A flag-service outage must not start a paid Modal bake.
+ with (
+ override_settings(DEBUG=False),
+ patch(
+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
+ side_effect=RuntimeError("flag service failed"),
+ ),
+ ):
+ assert is_dev_stack_image_bake_enabled() is False
+
+ def test_debug_short_circuits_false_without_consulting_the_flag(self):
+ # Self-capture re-enables posthoganalytics in local dev, so the DEBUG guard is
+ # the only thing keeping a locally seeded flag from starting paid Modal bakes.
+ with (
+ override_settings(DEBUG=True),
+ patch(
+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
+ return_value=True,
+ ) as feature_enabled_mock,
+ ):
+ assert is_dev_stack_image_bake_enabled() is False
+
+ feature_enabled_mock.assert_not_called()