Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): activate verified immutable dev-stack images (#115464)

Alessandro Pogliaghib1be3368dc0e
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index ed0c9dbf4100..e202241bf9f8 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -415,9 +415,29 @@ Each sandbox is created from a template that determines its base image and capab
### Protected dev-stack activation
-The two infrastructure models are instance-global: they describe the shared image, not a tenant's sandbox or custom image. They persist targets, attempts, leases, deadlines and active image provenance in Postgres. Explicit rebuild requests are recorded before observing inputs, so a newer routine observation can carry a pending request forward.
+Dev-stack bakes can use a durable, regional activation pointer instead of publishing over a shared Modal image name. The two infrastructure models are instance-global: they describe the shared image, not a tenant's sandbox or custom image. Explicit rebuild requests are recorded before observing inputs, so a newer routine observation can carry a pending request forward.
-Activation locks the target and checks its generation, attempt owner, lease and deadline. A superseded bake can finish its snapshot but cannot change the active pointer. The state layer does not schedule bakes or change the image used by task readers.
+```text
+VM digest + repository SHA + bake recipe
+ -> generation -> immutable snapshot -> boot verification
+ -> atomic activation -> new task sandboxes
+```
+
+Activation locks the target and checks its generation, attempt owner, lease and deadline. A superseded bake can finish its snapshot but cannot change the active pointer. Candidate verification boots the exact snapshot, restores the manifest's repository revision for retained container bind mounts, and checks its manifest, agent version, Postgres, Redis and ClickHouse. The previous active image remains available if verification fails. Failed verification commands log bounded output tails with the stage and attempt, image and sandbox IDs. Cleanup retries cannot replace the original verification failure.
+
+The two-minute sweep reconciles durable state using a fresh registry digest rather than the task-provisioning cache. A changed bake recipe requests a new generation even when the VM digest is unchanged. Dispatch retries reuse an attempt's Temporal workflow ID, and a lost activation acknowledgment reads the committed result. Workers renew two-minute leases every 30 seconds, with a separate three-hour deadline. Failed bakes retry after 2, 5 and then 15 minutes with up to 29 seconds of jitter. Each region allows three full bakes per rolling six hours across generations; snapshot verification does not consume that budget. Provider boot failures retry the checkpointed snapshot; confirmed candidate defects require a corrected target or a new manual request.
+
+Roll out one region at a time:
+
+1. Apply the additive migration and deploy the new workers and task readers. With no target row, the existing named-image behavior remains in place.
+2. Disable the legacy `tasks-dev-stack-image-bake` flag and drain legacy bake executions and old task workers. All task readers must understand protected activation before initialization.
+3. Run `python manage.py bake_dev_stack_image --initialize --seed-image-id <immutable-image-id>` using a known existing snapshot. This boots and checks the baseline before recording its ID and a verified attempt for rollback. Save the printed attempt UUID; its base provenance remains unknown. Omitting the seed deliberately leaves tasks on the plain VM base until the first verified activation.
+4. Run `python manage.py bake_dev_stack_image --enable`. The durable enablement setting now controls scheduling in this region; the legacy flag no longer controls protected bakes. GitHub App Contents read access is needed to pin the repository revision. The next sweep requests a generation from the current VM digest.
+5. Verify a successful candidate and a new task's image selection before enabling another region. Existing sandboxes are unchanged.
+
+Use `python manage.py bake_dev_stack_image --request-key <request-id>` for a manual refresh. Protected bakes reject `--inline`. `--disable` stops scheduling and activation while preserving the active image. A database read failure or missing active pointer falls back to the plain VM base with a recorded image-fallback reason, never to the mutable named image.
+
+To roll back, use `python manage.py bake_dev_stack_image --rollback-attempt <verified-attempt-uuid>`, including the seed's UUID. This creates a new generation and reverifies that attempt's immutable candidate. Automatic target updates remain paused until `--enable` resumes them. Initialization, enablement, disablement, and rollback must be separate commands. Do not delete the target row or redeploy alias-only readers as a rollback strategy. Candidate snapshots are retained; this change does not add automatic image deletion.
### Optional: local repository mounts (Docker only)
diff --git a/products/tasks/backend/facade/tasks.py b/products/tasks/backend/facade/tasks.py
index f873b3723eae..a3a708cdfeb9 100644
--- a/products/tasks/backend/facade/tasks.py
+++ b/products/tasks/backend/facade/tasks.py
@@ -8,6 +8,7 @@ import logging
from celery import shared_task
+from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
from products.tasks.backend.loop_reconciliation import reconcile_loop_trigger_schedules_task
from products.tasks.backend.loop_retention import sweep_loop_task_retention_task
from products.tasks.backend.task_auto_archive import sweep_inactive_tasks_task
@@ -42,7 +43,7 @@ def bake_dev_stack_image_task() -> None:
is_dev_stack_image_bake_enabled, # noqa: PLC0415 — keeps posthoganalytics off the import path
)
- if not is_dev_stack_image_bake_enabled():
+ if DevStackImageState.target() is None and not is_dev_stack_image_bake_enabled():
return
from products.tasks.backend.metrics import (
diff --git a/products/tasks/backend/logic/services/dev_stack_image.py b/products/tasks/backend/logic/services/dev_stack_image.py
index ebb736593e48..455087fe66c9 100644
--- a/products/tasks/backend/logic/services/dev_stack_image.py
+++ b/products/tasks/backend/logic/services/dev_stack_image.py
@@ -17,19 +17,26 @@ image builder — which is why this is a sandbox snapshot rather than a spec-bui
from __future__ import annotations
+import shlex
+import hashlib
import logging
from collections import deque
+from functools import partial
from pathlib import Path
+from threading import Event
from typing import TYPE_CHECKING
from django.conf import settings
if TYPE_CHECKING:
+ from products.tasks.backend.dev_stack_image_models import DevStackImageAttempt
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.dev_stack_image_refresh import reconcile_dev_stack_image
+from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
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
@@ -67,21 +74,21 @@ 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.
- """
+def _snapshot_with_retries(sandbox: ModalSandbox, publish_name: str | None) -> str:
+ snapshot = (
+ partial(sandbox.publish_filesystem_image, publish_name)
+ if publish_name
+ else partial(sandbox.create_snapshot, timeout_seconds=30 * 60)
+ )
for attempt in range(1, PUBLISH_SNAPSHOT_MAX_ATTEMPTS):
try:
- return sandbox.publish_filesystem_image(publish_name)
+ return snapshot()
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)
+ return snapshot()
def _resolve_current_base_reference() -> str | None:
@@ -121,6 +128,10 @@ def refresh_dev_stack_image_if_base_changed(publish_name: str = DEV_STACK_IMAGE_
overnight. Also converges a region with no recorded bake (first enable, cache flush)
by dispatching one. Returns whether a bake was dispatched.
"""
+ target = DevStackImageState.target(publish_name)
+ if target is not None:
+ return reconcile_dev_stack_image(target, trigger="base_changed")
+
if not is_dev_stack_image_bake_enabled():
return False
@@ -161,7 +172,12 @@ def refresh_dev_stack_image_if_base_changed(publish_name: str = DEV_STACK_IMAGE_
return True
-def bake_dev_stack_image(publish_name: str = DEV_STACK_IMAGE_NAME) -> str:
+def bake_dev_stack_image(
+ publish_name: str = DEV_STACK_IMAGE_NAME,
+ *,
+ candidate: DevStackImageAttempt | None = None,
+ cancelled: Event | None = None,
+) -> 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,
@@ -173,15 +189,16 @@ def bake_dev_stack_image(publish_name: str = DEV_STACK_IMAGE_NAME) -> str:
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()
+ base_reference = candidate.base_reference if candidate else _resolve_current_base_reference()
+ if candidate and hashlib.sha256(script.encode()).hexdigest() != candidate.recipe_sha:
+ raise DevStackImageBakeError("Bake recipe changed; request a new generation")
+ if candidate is None and DevStackImageState.target(publish_name) is not None:
+ raise DevStackImageBakeError("Protected dev-stack images must use the activation workflow")
sandbox = sandbox_cls.create(
SandboxConfig(
name="dev-stack-image-bake",
+ base_image_reference=base_reference,
template=SandboxTemplate.VM_BASE,
vm_runtime=True,
cpu_cores=BAKE_SANDBOX_CPU_CORES,
@@ -196,8 +213,17 @@ def bake_dev_stack_image(publish_name: str = DEV_STACK_IMAGE_NAME) -> str:
log_tail: deque[bytes] = deque()
tail_len = 0
- stream = sandbox.execute_stream(f"bash {BAKE_SCRIPT_SANDBOX_PATH} 2>&1")
+ environment = (
+ f"DEV_STACK_REPOSITORY_SHA={shlex.quote(candidate.repository_sha)} "
+ f"DEV_STACK_BASE_REFERENCE={shlex.quote(candidate.base_reference)} "
+ f"DEV_STACK_RECIPE_SHA={shlex.quote(candidate.recipe_sha)} "
+ if candidate
+ else ""
+ )
+ stream = sandbox.execute_stream(f"{environment}bash {BAKE_SCRIPT_SANDBOX_PATH} 2>&1")
for line in stream.iter_stdout():
+ if cancelled is not None and cancelled.is_set():
+ raise DevStackImageBakeError("Bake ownership ended")
logger.info("dev_stack_image_bake_output", extra={"sandbox_id": sandbox.id, "line": line.rstrip()})
encoded_line = line.encode("utf-8")[-MAX_BAKE_LOG_BYTES:]
log_tail.append(encoded_line)
@@ -209,8 +235,13 @@ def bake_dev_stack_image(publish_name: str = DEV_STACK_IMAGE_NAME) -> str:
output_tail = b"".join(log_tail)[-MAX_BAKE_LOG_BYTES:].decode("utf-8", errors="ignore")
raise DevStackImageBakeError(f"Bake script exited with {result.exit_code}; output tail:\n{output_tail}")
- image_id = _publish_snapshot_with_retries(sandbox, publish_name)
- _record_baked_base_reference(publish_name, base_reference)
+ if candidate:
+ if cancelled is not None and cancelled.is_set():
+ raise DevStackImageBakeError("Bake ownership ended")
+ image_id = _snapshot_with_retries(sandbox, None)
+ else:
+ image_id = _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},
diff --git a/products/tasks/backend/logic/services/dev_stack_image_refresh.py b/products/tasks/backend/logic/services/dev_stack_image_refresh.py
new file mode 100644
index 000000000000..0cfc0a4c3eb1
--- /dev/null
+++ b/products/tasks/backend/logic/services/dev_stack_image_refresh.py
@@ -0,0 +1,110 @@
+import re
+import uuid
+import asyncio
+import hashlib
+import logging
+from pathlib import Path
+from typing import Literal
+
+from django.conf import settings
+from django.utils import timezone
+
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.temporal.common.client import sync_connect
+
+from products.tasks.backend.dev_stack_image_models import DevStackImageTarget
+from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
+from products.tasks.backend.logic.services.sandbox import SandboxTemplate
+
+logger = logging.getLogger(__name__)
+
+
+def resolve_repository_sha() -> str:
+ installation = GitHubIntegrationBase.app_request("repos/PostHog/posthog/installation", timeout=5)
+ installation.raise_for_status()
+ installation_id = str(installation.json()["id"])
+ token = GitHubIntegrationBase.client_request(
+ f"installations/{installation_id}/access_tokens",
+ method="POST",
+ timeout=5,
+ json_body={"repositories": ["posthog"], "permissions": {"contents": "read"}},
+ )
+ token.raise_for_status()
+ response = github_request(
+ "GET",
+ "https://api.github.com/repos/PostHog/posthog/commits/master",
+ source="tasks_dev_stack_image",
+ priority=Priority.BATCH,
+ installation_id=installation_id,
+ headers={"Authorization": f"Bearer {token.json()['token']}"},
+ timeout=5,
+ )
+ response.raise_for_status()
+ sha = response.json()["sha"]
+ if not isinstance(sha, str) or re.fullmatch(r"[0-9a-f]{40}", sha) is None:
+ raise ValueError("Invalid repository revision")
+ return sha
+
+
+def reconcile_dev_stack_image(
+ target: DevStackImageTarget, *, trigger: Literal["nightly", "base_changed", "manual"], request_key: str = ""
+) -> bool:
+ from products.tasks.backend.logic.services.modal_sandbox import resolve_template_base_image_reference
+
+ if not target.enabled:
+ return False
+ state = DevStackImageState(target.pk)
+ if target.auto_refresh:
+ if trigger == "nightly":
+ request_key = f"nightly:{timezone.now().date().isoformat()}"
+ elif trigger == "manual":
+ request_key = request_key or f"manual:{uuid.uuid4()}"
+ revision = state.begin_observation(request_key)
+ try:
+ base = resolve_template_base_image_reference(SandboxTemplate.VM_BASE, use_cache=False)
+ if not base or re.fullmatch(r"ghcr.io/posthog/posthog-sandbox-vm@sha256:[0-9a-f]{64}", base) is None:
+ raise ValueError("The VM base must resolve to an immutable registry digest")
+ target.refresh_from_db(using="default")
+ recipe_sha = hashlib.sha256(
+ (
+ Path(settings.BASE_DIR) / "products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh"
+ ).read_bytes()
+ ).hexdigest()
+ needs_inputs = (
+ target.base_reference != base or target.recipe_sha != recipe_sha or bool(target.pending_request_key)
+ )
+ repository_sha = resolve_repository_sha() if needs_inputs else target.repository_sha
+ state.observe(revision, base, repository_sha, recipe_sha)
+ except Exception:
+ DevStackImageTarget.objects.using("default").filter(pk=target.pk, observation_revision=revision).update(
+ observation_error="Target refresh failed. Retrying the last known target; inspect the server logs."
+ )
+ logger.exception("dev_stack_image_target_observation_failed")
+ if trigger != "base_changed":
+ raise
+ attempt = state.reconcile()
+ if attempt is None:
+ return False
+ client = sync_connect()
+ try:
+ handle = asyncio.run(
+ client.start_workflow(
+ "activate-dev-stack-image",
+ str(attempt.id),
+ id=f"activate-dev-stack-image-{attempt.id}",
+ id_reuse_policy=WorkflowIDReusePolicy.REJECT_DUPLICATE,
+ task_queue=settings.TASKS_TASK_QUEUE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ )
+ type(attempt).objects.filter(pk=attempt.id, workflow_run_id="").update(
+ workflow_run_id=handle.first_execution_run_id or ""
+ )
+ except WorkflowAlreadyStartedError:
+ pass
+ return True
diff --git a/products/tasks/backend/logic/services/dev_stack_image_verification.py b/products/tasks/backend/logic/services/dev_stack_image_verification.py
new file mode 100644
index 000000000000..5b8b2fe9e34b
--- /dev/null
+++ b/products/tasks/backend/logic/services/dev_stack_image_verification.py
@@ -0,0 +1,127 @@
+import re
+import json
+import time
+import logging
+
+from products.tasks.backend.dev_stack_image_models import DevStackImageAttempt
+from products.tasks.backend.logic.services.sandbox import (
+ ExecutionResult,
+ SandboxConfig,
+ SandboxTemplate,
+ get_sandbox_class,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _log_command_failure(
+ result: ExecutionResult, stage: str, attempt: DevStackImageAttempt | None, image_id: str, sandbox_id: str
+) -> None:
+ logger.error(
+ "dev_stack_image_verification_command_failed",
+ extra={
+ "stage": stage,
+ "exit_code": result.exit_code,
+ "attempt_id": str(attempt.id) if attempt else None,
+ "image_id": image_id,
+ "sandbox_id": sandbox_id,
+ "stdout_tail": result.stdout.encode()[-4_000:].decode(errors="ignore"),
+ "stderr_tail": result.stderr.encode()[-4_000:].decode(errors="ignore"),
+ },
+ )
+
+
+class DevStackImageVerificationError(Exception):
+ pass
+
+
+def verify_dev_stack_image(attempt: DevStackImageAttempt | None, image_id: str) -> str:
+ config = SandboxConfig(
+ name="dev-stack-image-verification",
+ template=SandboxTemplate.VM_BASE,
+ base_image_reference=(attempt.base_reference or None) if attempt else None,
+ snapshot_external_id=image_id,
+ require_snapshot=True,
+ vm_runtime=True,
+ ttl_seconds=15 * 60,
+ default_execution_timeout_seconds=5 * 60,
+ memory_gb=32,
+ cpu_cores=8,
+ )
+ sandbox = get_sandbox_class().create(config)
+ try:
+ if not config.snapshot_restored:
+ raise RuntimeError("Candidate snapshot could not be restored")
+ manifest = sandbox.execute("cat /opt/posthog/dev-stack-bake.json")
+ if manifest.exit_code != 0:
+ _log_command_failure(manifest, "manifest", attempt, image_id, sandbox.id)
+ raise DevStackImageVerificationError("Bake manifest is missing")
+ try:
+ observed = json.loads(manifest.stdout)
+ except ValueError as error:
+ raise DevStackImageVerificationError("Invalid bake manifest") from error
+ if not isinstance(observed, dict):
+ raise DevStackImageVerificationError("Invalid bake manifest")
+ if attempt and any(
+ expected and observed.get(key) != expected
+ for key, expected in (
+ ("base_reference", attempt.base_reference),
+ ("posthog_sha", attempt.repository_sha),
+ ("recipe_sha", attempt.recipe_sha),
+ )
+ ):
+ raise DevStackImageVerificationError("Candidate inputs do not match the requested generation")
+ agent = sandbox.execute("node -p \"require('/scripts/node_modules/@posthog/agent/package.json').version\"")
+ version = agent.stdout.strip()
+ if (
+ agent.exit_code != 0
+ or not version
+ or (attempt and attempt.recipe_sha and observed.get("agent_version") != version)
+ ):
+ _log_command_failure(agent, "agent", attempt, image_id, sandbox.id)
+ raise DevStackImageVerificationError("Candidate agent version does not match its manifest")
+ repository_sha = observed.get("posthog_sha")
+ if not isinstance(repository_sha, str) or re.fullmatch(r"[0-9a-f]{40}", repository_sha) is None:
+ raise DevStackImageVerificationError("Invalid bake repository revision")
+ restored = sandbox.execute(
+ "set -e; repo=/tmp/workspace/repos/posthog/posthog; "
+ 'git init "$repo"; '
+ f'git -C "$repo" fetch --depth 1 https://github.com/PostHog/posthog.git {repository_sha}; '
+ 'git -C "$repo" checkout --force --detach FETCH_HEAD; '
+ f'test "$(git -C "$repo" rev-parse HEAD)" = {repository_sha}',
+ timeout_seconds=5 * 60,
+ )
+ if restored.exit_code != 0:
+ _log_command_failure(restored, "checkout", attempt, image_id, sandbox.id)
+ raise RuntimeError("Verification checkout could not be restored")
+ result = sandbox.execute(
+ "set -e; /usr/local/bin/bootstrap-dev-stack; "
+ "docker start posthog-db-1 posthog-redis7-1 posthog-clickhouse-1; "
+ "for attempt in $(seq 1 60); do "
+ "if docker exec posthog-db-1 pg_isready -U posthog && "
+ "docker exec posthog-redis7-1 redis-cli ping | grep -qx PONG && "
+ "docker exec posthog-clickhouse-1 clickhouse-client --query 'SELECT 1'; "
+ "then exit 0; fi; sleep 3; done; exit 1",
+ timeout_seconds=5 * 60,
+ )
+ if result.exit_code != 0:
+ _log_command_failure(result, "datastores", attempt, image_id, sandbox.id)
+ raise DevStackImageVerificationError("Candidate datastores did not become ready")
+ return version
+ finally:
+ for cleanup_attempt in range(3):
+ try:
+ sandbox.destroy()
+ break
+ except Exception:
+ if cleanup_attempt < 2:
+ time.sleep(2**cleanup_attempt)
+ else:
+ logger.exception(
+ "dev_stack_image_verification_cleanup_failed",
+ extra={
+ "attempt_id": str(attempt.id) if attempt else None,
+ "image_id": image_id,
+ "sandbox_id": sandbox.id,
+ },
+ )
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index b1ef851634be..4e623ea39a56 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -36,6 +36,7 @@ from semantic_version import NpmSpec
from posthog.exceptions_capture import capture_exception
from posthog.settings import CLOUD_DEPLOYMENT
+from posthog.utils import get_instance_region
from products.tasks.backend.constants import (
ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,
@@ -90,7 +91,7 @@ from products.tasks.backend.logic.services.modal_provision_diagnostics import (
summarize_modal_output,
)
from products.tasks.backend.logic.services.sandbox import redact_sandbox_command
-from products.tasks.backend.models import SandboxSnapshot
+from products.tasks.backend.models import DevStackImageTarget, SandboxSnapshot
from .agent_server_launcher import (
AGENT_SERVER_PORT as AGENT_SERVER_PORT,
@@ -417,18 +418,7 @@ def _resolve_image_digest_once(image: str) -> str:
return f"{image}@{digest}"
-@cached(cache=_image_ref_cache, lock=_image_ref_lock)
-def _get_sandbox_image_reference(image: str = SANDBOX_IMAGE) -> str:
- """Resolve the sandbox image to an immutable digest pin.
-
- Modal caches sandbox images by reference indefinitely, so a mutable
- ``:master`` tag would let Modal keep serving a stale or broken image. We
- therefore retry transient GHCR failures with exponential backoff and, if
- resolution still fails, fail closed by raising ``SandboxProvisionError``
- (transient — the provisioning activity retries) rather than ever returning
- the floating tag. Successful resolutions are cached for ~5 minutes;
- failures are not cached and re-resolve on the next call.
- """
+def _resolve_sandbox_image_reference(image: str) -> str:
last_error: Exception | None = None
for attempt in range(1, _GHCR_RESOLVE_MAX_ATTEMPTS + 1):
try:
@@ -453,6 +443,21 @@ def _get_sandbox_image_reference(image: str = SANDBOX_IMAGE) -> str:
)
+@cached(cache=_image_ref_cache, lock=_image_ref_lock)
+def _get_sandbox_image_reference(image: str = SANDBOX_IMAGE) -> str:
+ """Resolve the sandbox image to an immutable digest pin.
+
+ Modal caches sandbox images by reference indefinitely, so a mutable
+ ``:master`` tag would let Modal keep serving a stale or broken image. We
+ therefore retry transient GHCR failures with exponential backoff and, if
+ resolution still fails, fail closed by raising ``SandboxProvisionError``
+ (transient — the provisioning activity retries) rather than ever returning
+ the floating tag. Successful resolutions are cached for ~5 minutes;
+ failures are not cached and re-resolve on the next call.
+ """
+ return _resolve_sandbox_image_reference(image)
+
+
# Templates whose image bundles the agent-server at /scripts and can therefore
# take a live local dist overlay in DEBUG. Add new agent-server-bearing templates here.
AGENT_SERVER_TEMPLATES = frozenset(
@@ -698,7 +703,7 @@ def resolve_template_base_image(template: SandboxTemplate) -> modal.Image:
return get_template_base_image(template)
-def resolve_template_base_image_reference(template: SandboxTemplate) -> str | None:
+def resolve_template_base_image_reference(template: SandboxTemplate, *, use_cache: bool = True) -> str | None:
if settings.DEBUG:
return None
@@ -711,7 +716,9 @@ def resolve_template_base_image_reference(template: SandboxTemplate) -> str | No
}.get(template)
if registry_image is None:
raise ValueError(f"Template does not use a registry image: {template}")
- return _get_sandbox_image_reference(registry_image)
+ return (
+ _get_sandbox_image_reference(registry_image) if use_cache else _resolve_sandbox_image_reference(registry_image)
+ )
@lru_cache(maxsize=3)
@@ -931,12 +938,30 @@ class ModalSandbox(AgentServerLaunchMixin):
except Exception as e:
_raise_if_proxy_failure(e, None, "lookup")
raise
- base_image = _get_template_image(config.template)
+ base_image = (
+ modal.Image.from_registry(config.base_image_reference)
+ if config.base_image_reference
+ else _get_template_image(config.template)
+ )
custom_image_bare: modal.Image | None = None
custom_image: modal.Image | None = None
+ custom_image_failure: str | None = None
if config.custom_image_name:
try:
- custom_image_bare = modal.Image.from_name(config.custom_image_name)
+ if config.custom_image_name == DEV_STACK_IMAGE_NAME:
+ target = (
+ DevStackImageTarget.objects.using("default")
+ .filter(region=get_instance_region() or "DEV", name=DEV_STACK_IMAGE_NAME)
+ .first()
+ )
+ if target is not None:
+ if not target.active_image_id:
+ raise RuntimeError("No verified dev-stack image is active")
+ custom_image_bare = modal.Image.from_id(target.active_image_id)
+ else:
+ custom_image_bare = modal.Image.from_name(config.custom_image_name)
+ else:
+ 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(
@@ -945,6 +970,7 @@ class ModalSandbox(AgentServerLaunchMixin):
install_dependencies=config.custom_image_name != DEV_STACK_IMAGE_NAME,
)
except Exception as e:
+ custom_image_failure = f"custom image {config.custom_image_name} unavailable"
logger.warning(f"Failed to load custom image {config.custom_image_name}: {e}")
capture_exception(e)
config.snapshot_restored = False
@@ -1024,6 +1050,14 @@ class ModalSandbox(AgentServerLaunchMixin):
)
)
candidates.append(ImageCandidate(base_image, "base image"))
+ if config.require_snapshot:
+ if snapshot_image is None or snapshot_kind != SNAPSHOT_KIND_FILESYSTEM:
+ raise RuntimeError("The required filesystem snapshot could not be loaded")
+ candidates = [
+ ImageCandidate(
+ snapshot_image, f"snapshot image {snapshot_external_id}", restored_from_snapshot=True
+ )
+ ]
secrets = []
if config.environment_variables:
@@ -1058,6 +1092,8 @@ class ModalSandbox(AgentServerLaunchMixin):
create_kwargs["secrets"] = secrets
sb, modal_output, winner = cls._create_from_image_candidates(create_kwargs, candidates, config)
+ if custom_image_failure and winner.label == "base image":
+ config.image_fallback = f"{custom_image_failure} -> base image"
directory_mount_applied = False
if snapshot_kind == SNAPSHOT_KIND_DIRECTORY and snapshot_image is not None:
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index f1b31f41c953..d8ba10dde0ce 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -206,6 +206,8 @@ class SandboxResources:
class SandboxConfig(BaseModel):
+ base_image_reference: str | None = None
+ require_snapshot: bool = False
name: str
template: SandboxTemplate = SandboxTemplate.DEFAULT_BASE
# Decides which Modal app owns the box, and with it how its cost is attributed. Changes
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 d16eeb295605..3802051ecf27 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -28,7 +28,10 @@ from requests.exceptions import (
Timeout,
)
+from posthog.utils import get_instance_region
+
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY
+from products.tasks.backend.dev_stack_image_models import DevStackImageTarget
from products.tasks.backend.exceptions import (
ProcessTaskFatalError,
SandboxControlPlaneError,
@@ -1763,6 +1766,7 @@ class TestModalSandboxCreateAllowlist:
mock_create.return_value.wait_until_ready.assert_called_once_with(timeout=READINESS_PROBE_TIMEOUT_SECONDS)
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
@@ -1819,6 +1823,42 @@ class TestModalSandboxCreateImageFallback:
assert sandbox.config.image_fallback is not None
assert "custom image posthog-dev-stack" in sandbox.config.image_fallback
+ @pytest.mark.parametrize("image_id", ["im-verified", ""])
+ def test_protected_dev_stack_never_reads_the_mutable_name(self, image_id: str) -> None:
+
+ DevStackImageTarget.objects.create(
+ region=get_instance_region() or "DEV",
+ name="posthog-dev-stack",
+ active_image_id=image_id,
+ )
+ config = SandboxConfig(name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-dev-stack")
+ custom = MagicMock(name="active")
+ with (
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),
+ patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),
+ patch("products.tasks.backend.logic.services.modal_sandbox._get_template_image") as base,
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",
+ side_effect=lambda image, *args, **kwargs: image,
+ ),
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name") as from_name,
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_id", return_value=custom
+ ) as from_id,
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create") as create,
+ patch("products.tasks.backend.logic.services.modal_sandbox.capture_exception"),
+ ):
+ sandbox = ModalSandbox.create(config)
+ from_name.assert_not_called()
+ if image_id:
+ from_id.assert_called_once_with(image_id)
+ assert create.call_args.kwargs["image"] is custom
+ assert sandbox.config.is_dev_stack_image
+ else:
+ assert create.call_args.kwargs["image"] is base.return_value
+ assert not sandbox.config.is_dev_stack_image
+ assert sandbox.config.image_fallback
+
def test_falling_back_to_the_base_image_drops_the_dev_stack_cpu_floor(self) -> None:
config = SandboxConfig(
name="t",
@@ -1879,6 +1919,40 @@ class TestModalSandboxCreateImageFallback:
assert sandbox.config.snapshot_restored is True
assert sandbox.config.image_fallback is not None
+ @pytest.mark.parametrize("failure", ["lookup", "create", "readiness"])
+ def test_required_snapshot_failure_never_falls_back_to_base(self, failure: str) -> None:
+ config = SandboxConfig(name="verification", snapshot_external_id="im-candidate", require_snapshot=True)
+ snapshot = MagicMock(name="candidate")
+ sandbox = MagicMock(object_id="sb-candidate")
+ with (
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),
+ patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),
+ patch("products.tasks.backend.logic.services.modal_sandbox._get_template_image"),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",
+ side_effect=lambda image, *args, **kwargs: image,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_id",
+ return_value=snapshot,
+ side_effect=RuntimeError("lookup unavailable") if failure == "lookup" else None,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create",
+ return_value=sandbox,
+ side_effect=RuntimeError("create unavailable") if failure == "create" else None,
+ ) as create,
+ patch.object(ModalSandbox, "_wait_until_ready", return_value=False),
+ patch("products.tasks.backend.logic.services.modal_sandbox.capture_exception"),
+ ):
+ with pytest.raises(SandboxProvisionError):
+ ModalSandbox.create(config)
+ assert create.call_count == (0 if failure == "lookup" else 1)
+ if create.called:
+ assert create.call_args.kwargs["image"] is snapshot
+ if failure == "readiness":
+ sandbox.terminate.assert_called_once()
+
def test_unrelated_invalid_error_preserves_vm_network_policy_on_fallback(self):
config = SandboxConfig(
name="t",
diff --git a/products/tasks/backend/management/commands/bake_dev_stack_image.py b/products/tasks/backend/management/commands/bake_dev_stack_image.py
index a4fe6ab2393c..06e0a162bfa0 100644
--- a/products/tasks/backend/management/commands/bake_dev_stack_image.py
+++ b/products/tasks/backend/management/commands/bake_dev_stack_image.py
@@ -1,18 +1,34 @@
from typing import Any
+from uuid import UUID
-from django.core.management.base import BaseCommand
+from django.core.management.base import BaseCommand, CommandError
+from django.db import transaction
+from django.utils import timezone
+from posthog.utils import get_instance_region
+
+from products.tasks.backend.dev_stack_image_models import DevStackImageAttempt, DevStackImageTarget
from products.tasks.backend.logic.services.dev_stack_image import DEV_STACK_IMAGE_NAME, bake_dev_stack_image
+from products.tasks.backend.logic.services.dev_stack_image_refresh import reconcile_dev_stack_image
+from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
+from products.tasks.backend.logic.services.dev_stack_image_verification import verify_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."
+ "Bake the PostHog dev-stack image through Temporal. Initialize protected activation "
+ "after deploying all readers and workers, then enable regional reconciliation. "
+ "Inline bakes are available only before protected activation is initialized."
)
def add_arguments(self, parser: Any) -> None:
+ lifecycle = parser.add_mutually_exclusive_group()
+ lifecycle.add_argument("--initialize", action="store_true")
+ lifecycle.add_argument("--enable", action="store_true")
+ lifecycle.add_argument("--disable", action="store_true")
+ lifecycle.add_argument("--rollback-attempt", type=UUID)
+ parser.add_argument("--request-key", default="")
+ parser.add_argument("--seed-image-id")
parser.add_argument(
"--publish-name",
default=DEV_STACK_IMAGE_NAME,
@@ -26,6 +42,73 @@ class Command(BaseCommand):
def handle(self, *args: Any, **options: Any) -> None:
publish_name: str = options["publish_name"]
+ if sum(bool(options[key]) for key in ("initialize", "enable", "disable", "rollback_attempt")) > 1:
+ raise CommandError("Choose only one of --initialize, --enable, --disable, or --rollback-attempt")
+ if options["seed_image_id"] and not options["initialize"]:
+ raise CommandError("--seed-image-id requires --initialize")
+ if len(options["request_key"]) > 128:
+ raise CommandError("Request IDs must be at most 128 characters")
+ if options["initialize"]:
+ if publish_name != DEV_STACK_IMAGE_NAME:
+ raise CommandError("Protected activation supports the default dev-stack image only")
+ if DevStackImageState.target(publish_name) is not None:
+ raise CommandError("This region already uses protected reads")
+ image_id = options["seed_image_id"] or ""
+ version = verify_dev_stack_image(None, image_id) if image_id else ""
+ with transaction.atomic():
+ initialized, created = DevStackImageTarget.objects.using("default").get_or_create(
+ region=get_instance_region() or "DEV",
+ name=publish_name,
+ defaults={
+ "active_image_id": image_id,
+ "active_agent_version": version,
+ "activated_at": timezone.now() if image_id else None,
+ },
+ )
+ if not created:
+ raise CommandError("This region already uses protected reads")
+ if image_id:
+ seed = DevStackImageAttempt.objects.using("default").create(
+ target=initialized,
+ generation=0,
+ base_reference="",
+ repository_sha="",
+ recipe_sha="",
+ status=DevStackImageAttempt.Status.ACTIVE,
+ candidate_image_id=image_id,
+ verified_at=initialized.activated_at,
+ finished_at=initialized.activated_at,
+ )
+ self.stdout.write(f"Verified seed retained for rollback: {seed.id} (provenance unknown).")
+ self.stdout.write("Protected image reads initialized. Baking remains disabled until --enable.")
+ return
+ target = DevStackImageState.target(publish_name)
+ if options["rollback_attempt"] and target is None:
+ raise CommandError("Rollback requires protected activation")
+ if options["enable"] or options["disable"]:
+ if target is None:
+ raise CommandError("Initialize first and choose either --enable or --disable")
+ target.enabled = options["enable"]
+ if target.enabled:
+ target.auto_refresh = True
+ target.save(update_fields=["enabled", "auto_refresh"])
+ self.stdout.write(
+ "Bake scheduling enabled." if target.enabled else "Bake scheduling disabled. Active image retained."
+ )
+ return
+ if target is not None:
+ if options["inline"]:
+ raise CommandError("Protected images require Temporal; omit --inline")
+ if options["rollback_attempt"]:
+ if not target.enabled:
+ raise CommandError("Enable scheduling before requesting a rollback")
+ DevStackImageState(target.pk).rollback(options["rollback_attempt"])
+ target.refresh_from_db(using="default")
+ dispatched = reconcile_dev_stack_image(target, trigger="manual", request_key=options["request_key"])
+ self.stdout.write(
+ "Bake scheduled." if dispatched else "No bake dispatched. Check enablement and retry state."
+ )
+ return
if options["inline"]:
image_id = bake_dev_stack_image(publish_name)
self.stdout.write(self.style.SUCCESS(f"Published {publish_name} ({image_id})"))
diff --git a/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
index fc3342869e39..2a2b8bd435f2 100644
--- a/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
+++ b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
@@ -92,6 +92,11 @@ mkdir -p "$BAKE_ROOT" "$(dirname "$REPO_DIR")"
# Rust target dir only counts as warm for a checkout at this same path.
git clone --depth 1 https://github.com/posthog/posthog.git "$REPO_DIR"
cd "$REPO_DIR"
+if [[ -n "${DEV_STACK_REPOSITORY_SHA:-}" ]]; then
+ git fetch --depth 1 origin "$DEV_STACK_REPOSITORY_SHA"
+ git checkout --detach FETCH_HEAD
+ [[ "$(git rev-parse HEAD)" == "$DEV_STACK_REPOSITORY_SHA" ]]
+fi
BAKED_SHA=$(git rev-parse HEAD)
export COMPOSE_PROJECT_NAME=posthog
@@ -343,6 +348,7 @@ 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"
+BAKED_AGENT_VERSION=$(node -p "require('/scripts/node_modules/@posthog/agent/package.json').version")
+export BAKED_SHA BAKE_MANIFEST BAKED_AGENT_VERSION
+python3 -c 'import json, os; from datetime import datetime, timezone; json.dump({"baked_at": datetime.now(timezone.utc).isoformat(), "posthog_sha": os.environ["BAKED_SHA"], "agent_version": os.environ["BAKED_AGENT_VERSION"], "base_reference": os.environ.get("DEV_STACK_BASE_REFERENCE"), "recipe_sha": os.environ.get("DEV_STACK_RECIPE_SHA"), "bootstrap": "bootstrap-dev-stack"}, open(os.environ["BAKE_MANIFEST"], "w"))'
log "bake complete at $BAKED_SHA"
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index 8341c8dc69e3..1f5d1cc0e483 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -1,3 +1,4 @@
+from .bake_dev_stack_image.activation import ActivateDevStackImageWorkflow, activate_dev_stack_image
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
@@ -76,6 +77,7 @@ WORKFLOWS = [
RunLoopWorkflow,
BuildSandboxImageWorkflow,
BakeDevStackImageWorkflow,
+ ActivateDevStackImageWorkflow,
]
ACTIVITIES = [
@@ -142,4 +144,5 @@ ACTIVITIES = [
mark_image_build_failed,
# bake_dev_stack_image activities
bake_and_publish_dev_stack_image,
+ activate_dev_stack_image,
]
diff --git a/products/tasks/backend/temporal/bake_dev_stack_image/activation.py b/products/tasks/backend/temporal/bake_dev_stack_image/activation.py
new file mode 100644
index 000000000000..671d065e7a5c
--- /dev/null
+++ b/products/tasks/backend/temporal/bake_dev_stack_image/activation.py
@@ -0,0 +1,96 @@
+import uuid
+import asyncio
+from datetime import timedelta
+from threading import Event
+
+from asgiref.sync import sync_to_async
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.utils import close_db_connections, retry_on_db_connection_drop
+
+from products.tasks.backend.dev_stack_image_models import DevStackImageAttempt
+from products.tasks.backend.logic.services.dev_stack_image import bake_dev_stack_image
+from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
+from products.tasks.backend.logic.services.dev_stack_image_verification import (
+ DevStackImageVerificationError,
+ verify_dev_stack_image,
+)
+from products.tasks.backend.metrics import observe_dev_stack_image_bake
+
+
+async def renew_lease(state: DevStackImageState, attempt_id: uuid.UUID, owner: uuid.UUID) -> None:
+ while True:
+ activity.heartbeat()
+ await asyncio.sleep(30)
+ if not await sync_to_async(retry_on_db_connection_drop)(lambda: state.renew(attempt_id, owner)):
+ raise RuntimeError("Dev-stack bake no longer owns its generation")
+
+
+async def build_and_activate(
+ state: DevStackImageState, attempt: DevStackImageAttempt, owner: uuid.UUID, cancelled: Event
+) -> str:
+ image_id = attempt.candidate_image_id or await sync_to_async(bake_dev_stack_image, thread_sensitive=False)(
+ candidate=attempt, cancelled=cancelled
+ )
+ if not await sync_to_async(retry_on_db_connection_drop)(lambda: state.checkpoint(attempt.id, owner, image_id)):
+ return "superseded"
+ version = await sync_to_async(verify_dev_stack_image, thread_sensitive=False)(attempt, image_id)
+ if not await sync_to_async(retry_on_db_connection_drop)(
+ lambda: state.activate(attempt.id, owner, image_id, version)
+ ):
+ return "superseded"
+ observe_dev_stack_image_bake("succeeded", trigger="protected")
+ return image_id
+
+
+@close_db_connections
+async def activate_dev_stack_image(attempt_id: str) -> str:
+ attempt = await sync_to_async(retry_on_db_connection_drop)(
+ lambda: DevStackImageAttempt.objects.using("default").get(pk=attempt_id)
+ )
+ state = DevStackImageState(attempt.target_id)
+ owner = uuid.uuid4()
+ run_id = activity.info().workflow_run_id or ""
+ claimed = await sync_to_async(retry_on_db_connection_drop)(lambda: state.claim(attempt.id, owner, run_id))
+ if claimed is None:
+ return "not_claimed"
+ lease = asyncio.create_task(renew_lease(state, attempt.id, owner))
+ cancelled = Event()
+ build = asyncio.create_task(build_and_activate(state, claimed, owner, cancelled))
+ try:
+ done, _ = await asyncio.wait([lease, build], return_when=asyncio.FIRST_COMPLETED)
+ if lease in done:
+ await lease
+ return await build
+ except BaseException as error:
+ observe_dev_stack_image_bake("failed", trigger="protected")
+ invalid = isinstance(error, DevStackImageVerificationError)
+ await asyncio.shield(
+ sync_to_async(retry_on_db_connection_drop)(lambda: state.fail(attempt.id, owner, invalid=invalid))
+ )
+ raise
+ finally:
+ cancelled.set()
+ for task in (lease, build):
+ task.cancel()
+ await asyncio.gather(lease, build, return_exceptions=True)
+
+
[email protected](name="activate-dev-stack-image")
+class ActivateDevStackImageWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> str:
+ return str(uuid.UUID(inputs[0]))
+
+ @workflow.run
+ async def run(self, attempt_id: str) -> str:
+ return await workflow.execute_activity(
+ activate_dev_stack_image,
+ attempt_id,
+ start_to_close_timeout=timedelta(hours=3),
+ heartbeat_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 9029f67f19ce..640010f5caeb 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -27,6 +27,8 @@ from products.tasks.backend.constants import (
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.logic.services.dev_stack_image_refresh import reconcile_dev_stack_image
+from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
from products.tasks.backend.logic.services.run_actor import get_actor_distinct_id, get_task_run_credential_user
from products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_for_run
from products.tasks.backend.metrics import AGENT_OTEL_TELEMETRY_STAMPED_TOTAL, observe_task_run_workflow_start
@@ -582,6 +584,10 @@ def execute_bake_dev_stack_image_workflow(
TERMINATE_IF_RUNNING: a bake stuck from the previous night gets replaced by the
fresh one instead of blocking it.
"""
+ target = DevStackImageState.target(publish_name)
+ if target is not None:
+ reconcile_dev_stack_image(target, trigger=trigger)
+ return
client = sync_connect()
asyncio.run(
client.start_workflow(
diff --git a/products/tasks/backend/tests/test_dev_stack_image.py b/products/tasks/backend/tests/test_dev_stack_image.py
index be9c36b9faf1..ae0b1a2149c8 100644
--- a/products/tasks/backend/tests/test_dev_stack_image.py
+++ b/products/tasks/backend/tests/test_dev_stack_image.py
@@ -1,8 +1,13 @@
import uuid
+import hashlib
+from pathlib import Path
import pytest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
+from django.conf import settings
+
+from products.tasks.backend.dev_stack_image_models import DevStackImageAttempt
from products.tasks.backend.exceptions import SnapshotTimeoutError
from products.tasks.backend.logic.services.dev_stack_image import (
PUBLISH_SNAPSHOT_MAX_ATTEMPTS,
@@ -13,6 +18,7 @@ from products.tasks.backend.logic.services.dev_stack_image import (
from products.tasks.backend.logic.services.sandbox import ExecutionResult
BASE_REFERENCE = "ghcr.io/posthog/posthog-sandbox-vm@sha256:current"
+pytestmark = pytest.mark.django_db
def _unique_publish_name() -> str:
@@ -49,7 +55,9 @@ def _make_fake_sandbox_cls(exit_code: int, publish_failures: int = 0):
@classmethod
def create(cls, config):
- return cls()
+ sandbox = cls()
+ sandbox.config = config
+ return sandbox
def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult:
self.written_files[path] = payload
@@ -77,6 +85,31 @@ def _make_fake_sandbox_cls(exit_code: int, publish_failures: int = 0):
class TestBakeDevStackImage:
+ def test_candidate_bake_uses_pinned_base_and_never_publishes_a_name(self) -> None:
+ fake_cls = _make_fake_sandbox_cls(exit_code=0)
+ snapshot = Mock(return_value="im-candidate")
+ candidate = DevStackImageAttempt(
+ base_reference=BASE_REFERENCE,
+ repository_sha="a" * 40,
+ recipe_sha=hashlib.sha256(
+ (
+ Path(settings.BASE_DIR) / "products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh"
+ ).read_bytes()
+ ).hexdigest(),
+ )
+ with (
+ patch("products.tasks.backend.logic.services.dev_stack_image.get_sandbox_class", return_value=fake_cls),
+ patch.object(fake_cls, "create_snapshot", snapshot),
+ patch("products.tasks.backend.logic.services.dev_stack_image._record_baked_base_reference") as record,
+ ):
+ assert bake_dev_stack_image(candidate=candidate) == "im-candidate"
+ sandbox = fake_cls.instances[0]
+ assert sandbox.config.base_image_reference == BASE_REFERENCE
+ assert sandbox.published_name is None
+ assert sandbox.destroyed
+ snapshot.assert_called_once()
+ record.assert_not_called()
+
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)
diff --git a/products/tasks/backend/tests/test_dev_stack_image_activation.py b/products/tasks/backend/tests/test_dev_stack_image_activation.py
index 834d84e25c0a..8626945ea9a8 100644
--- a/products/tasks/backend/tests/test_dev_stack_image_activation.py
+++ b/products/tasks/backend/tests/test_dev_stack_image_activation.py
@@ -1,16 +1,34 @@
+import json
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
+from io import StringIO
+from itertools import combinations
from threading import Barrier
import pytest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, Mock, patch
-from django.db import connections
+from django.core.management import call_command
+from django.core.management.base import CommandError
+from django.db import OperationalError, connections
+from django.test import override_settings
from django.utils import timezone
+from asgiref.sync import sync_to_async
+from temporalio.testing import ActivityEnvironment
+
from products.tasks.backend.dev_stack_image_models import DevStackImageAttempt, DevStackImageTarget
+from products.tasks.backend.exceptions import SandboxCleanupError
+from products.tasks.backend.logic.services.dev_stack_image_refresh import reconcile_dev_stack_image
from products.tasks.backend.logic.services.dev_stack_image_state import BUILD_BUDGET, DevStackImageState
+from products.tasks.backend.logic.services.dev_stack_image_verification import (
+ DevStackImageVerificationError,
+ verify_dev_stack_image,
+)
+from products.tasks.backend.logic.services.modal_sandbox import _image_ref_cache, resolve_template_base_image_reference
+from products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig, SandboxTemplate
+from products.tasks.backend.temporal.bake_dev_stack_image.activation import activate_dev_stack_image
@pytest.fixture
@@ -34,6 +52,145 @@ def claim(state: DevStackImageState) -> tuple[DevStackImageAttempt, uuid.UUID]:
@pytest.mark.django_db
class TestDevStackImageActivation:
+ @override_settings(DEBUG=False)
+ def test_sweeps_do_not_restore_a_cached_base(self, state: DevStackImageState) -> None:
+ token = Mock(status_code=200)
+ token.json.return_value = {"token": "example-token"}
+
+ def manifest(digest: str) -> Mock:
+ return Mock(status_code=200, headers={"Docker-Content-Digest": f"sha256:{digest * 64}"})
+
+ target = DevStackImageTarget.objects.get(pk=state.target_id)
+ try:
+ with (
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
+ side_effect=[
+ token,
+ manifest("a"),
+ TimeoutError(),
+ token,
+ manifest("b"),
+ token,
+ manifest("c"),
+ token,
+ manifest("b"),
+ ],
+ ),
+ patch("products.tasks.backend.logic.services.modal_sandbox.time.sleep"),
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image_refresh.resolve_repository_sha",
+ return_value="b" * 40,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image_refresh.sync_connect",
+ return_value=Mock(
+ start_workflow=AsyncMock(return_value=Mock(first_execution_run_id="example-run"))
+ ),
+ ),
+ ):
+ for index, cached in enumerate(("a", "c")):
+ _image_ref_cache.clear()
+ reference = resolve_template_base_image_reference(SandboxTemplate.VM_BASE)
+ assert reference and reference.endswith(f"sha256:{cached * 64}")
+ assert reconcile_dev_stack_image(target, trigger="base_changed") is (index == 0)
+ if index == 0:
+ claim(state)
+ target.refresh_from_db()
+ assert target.base_reference.endswith(f"sha256:{'b' * 64}")
+ assert target.generation == 1
+ assert DevStackImageAttempt.objects.get().status == "building"
+ finally:
+ _image_ref_cache.clear()
+
+ def test_recipe_deployment_supersedes_pending_bake_without_a_base_change(self, state: DevStackImageState) -> None:
+ target = DevStackImageTarget.objects.get(pk=state.target_id)
+ with (
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ return_value="ghcr.io/posthog/posthog-sandbox-vm@sha256:" + "a" * 64,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image_refresh.resolve_repository_sha",
+ return_value="b" * 40,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image_refresh.Path.read_bytes",
+ side_effect=[b"recipe one", b"recipe two"],
+ ),
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image_refresh.sync_connect",
+ return_value=Mock(start_workflow=AsyncMock(return_value=Mock(first_execution_run_id="example-run"))),
+ ),
+ ):
+ assert reconcile_dev_stack_image(target, trigger="base_changed")
+ previous, owner = claim(state)
+ assert reconcile_dev_stack_image(target, trigger="base_changed")
+ target.refresh_from_db()
+ previous.refresh_from_db()
+ assert target.generation == 2
+ assert previous.status == "superseded"
+ assert not state.renew(previous.id, owner)
+ assert target.recipe_sha != previous.recipe_sha
+ assert target.attempt_id != previous.id
+
+ def test_initialized_seed_remains_a_verified_rollback_source(self) -> None:
+ with patch(
+ "products.tasks.backend.management.commands.bake_dev_stack_image.verify_dev_stack_image",
+ return_value="1.0.0",
+ ):
+ call_command("bake_dev_stack_image", initialize=True, seed_image_id="im-seed", stdout=StringIO())
+ target = DevStackImageState.target()
+ assert target is not None
+ seed = target.attempts.get(candidate_image_id="im-seed")
+ assert seed.verified_at is not None
+ assert (seed.base_reference, seed.repository_sha, seed.recipe_sha) == ("", "", "")
+ call_command("bake_dev_stack_image", enable=True, stdout=StringIO())
+ state = DevStackImageState(target.pk)
+ observe(state)
+ first, owner = claim(state)
+ assert state.checkpoint(first.id, owner, "im-first")
+ assert state.activate(first.id, owner, "im-first", "1.0.1")
+ with patch(
+ "products.tasks.backend.management.commands.bake_dev_stack_image.reconcile_dev_stack_image",
+ return_value=True,
+ ):
+ call_command("bake_dev_stack_image", rollback_attempt=seed.id, stdout=StringIO())
+ rollback, owner = claim(state)
+ target.refresh_from_db()
+ assert target.active_image_id == "im-first"
+ assert not target.auto_refresh
+ assert rollback.candidate_image_id == "im-seed"
+ assert rollback.status == "verifying"
+ assert state.activate(rollback.id, owner, "im-seed", "1.0.0")
+ target.refresh_from_db()
+ assert target.active_image_id == "im-seed"
+ assert target.active_base_reference == ""
+
+ def test_lost_dispatch_acknowledgement_reuses_the_durable_attempt(self, state: DevStackImageState) -> None:
+ target = DevStackImageTarget.objects.get(pk=state.target_id)
+ client = Mock(
+ start_workflow=AsyncMock(side_effect=[TimeoutError(), Mock(first_execution_run_id="example-run")])
+ )
+ with (
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.resolve_template_base_image_reference",
+ return_value="ghcr.io/posthog/posthog-sandbox-vm@sha256:" + "a" * 64,
+ ),
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image_refresh.resolve_repository_sha",
+ return_value="b" * 40,
+ ),
+ patch("products.tasks.backend.logic.services.dev_stack_image_refresh.sync_connect", return_value=client),
+ ):
+ with pytest.raises(TimeoutError):
+ reconcile_dev_stack_image(target, trigger="base_changed")
+ assert reconcile_dev_stack_image(target, trigger="base_changed")
+ assert (
+ client.start_workflow.call_args_list[0].kwargs["id"] == client.start_workflow.call_args_list[1].kwargs["id"]
+ )
+ assert DevStackImageAttempt.objects.count() == 1
+
def test_rollback_reverifies_known_candidate_and_pauses_automatic_updates(self, state: DevStackImageState) -> None:
observe(state)
good, owner = claim(state)
@@ -173,6 +330,95 @@ class TestDevStackImageActivation:
assert target.blocked_reason == "Candidate verification failed"
+ "failure,cleanup_failures",
+ [(failure, 0) for failure in (None, "seed", "boot", "manifest", "agent", "health", "checkout", "invalid_json")]
+ + [(None, 1), (None, 3), ("health", 3)],
+)
+def test_candidate_must_boot_and_match_manifest_before_activation(
+ failure: str | None, cleanup_failures: int, caplog: pytest.LogCaptureFixture
+) -> None:
+ attempt = DevStackImageAttempt(base_reference="sha256:example", repository_sha="a" * 40, recipe_sha="b" * 64)
+ manifest = {
+ "base_reference": attempt.base_reference,
+ "posthog_sha": attempt.repository_sha,
+ "recipe_sha": attempt.recipe_sha,
+ "agent_version": "1.0.0",
+ }
+ if failure == "manifest":
+ manifest["base_reference"] = "sha256:other"
+ if failure == "seed":
+ attempt.base_reference = attempt.repository_sha = attempt.recipe_sha = ""
+ sandbox = Mock(id="sb-verification")
+ sandbox.destroy.side_effect = [
+ SandboxCleanupError("cleanup failed", {}, RuntimeError("provider cleanup failed"), capture=False)
+ ] * cleanup_failures + [None]
+ output = "x" * 5_000 + "diagnostic tail"
+ sandbox.execute.side_effect = [
+ ExecutionResult(
+ stdout="invalid" if failure == "invalid_json" else json.dumps(manifest), stderr="", exit_code=0
+ ),
+ ExecutionResult(stdout="0.9.0" if failure == "agent" else "1.0.0", stderr="", exit_code=0),
+ ExecutionResult(stdout=output, stderr=output, exit_code=1 if failure == "checkout" else 0),
+ ExecutionResult(stdout=output, stderr=output, exit_code=1 if failure == "health" else 0),
+ ]
+
+ def create(config: SandboxConfig) -> Mock:
+ assert config.base_image_reference == (attempt.base_reference or None)
+ assert config.snapshot_external_id == "im-candidate"
+ assert config.require_snapshot
+ config.snapshot_restored = failure != "boot"
+ return sandbox
+
+ with (
+ patch(
+ "products.tasks.backend.logic.services.dev_stack_image_verification.get_sandbox_class",
+ return_value=Mock(create=create),
+ ),
+ patch("products.tasks.backend.logic.services.dev_stack_image_verification.time.sleep"),
+ ):
+ if failure not in (None, "seed"):
+ with pytest.raises(RuntimeError if failure in ("boot", "checkout") else DevStackImageVerificationError):
+ verify_dev_stack_image(attempt, "im-candidate")
+ else:
+ assert verify_dev_stack_image(attempt, "im-candidate") == "1.0.0"
+ assert sandbox.destroy.call_count == min(cleanup_failures + 1, 3)
+ if failure in ("checkout", "health"):
+ record = next(
+ record for record in caplog.records if record.message == "dev_stack_image_verification_command_failed"
+ )
+ assert (
+ record.__dict__.items()
+ >= {
+ "stage": "checkout" if failure == "checkout" else "datastores",
+ "exit_code": 1,
+ "attempt_id": str(attempt.id),
+ "image_id": "im-candidate",
+ "sandbox_id": sandbox.id,
+ "stdout_tail": output[-4_000:],
+ "stderr_tail": output[-4_000:],
+ }.items()
+ )
+ if cleanup_failures == 3:
+ record = next(
+ record for record in caplog.records if record.message == "dev_stack_image_verification_cleanup_failed"
+ )
+ assert record.__dict__["sandbox_id"] == sandbox.id
+
+
[email protected]("actions", list(combinations(("initialize", "enable", "disable", "rollback_attempt"), 2)))
+def test_conflicting_lifecycle_actions_do_not_change_state(actions: tuple[str, str]) -> None:
+ options = {key: uuid.uuid4() if key == "rollback_attempt" else True for key in actions}
+ args = [
+ f"--{key.replace('_', '-')}{'=' + str(value) if key == 'rollback_attempt' else ''}"
+ for key, value in options.items()
+ ]
+ with pytest.raises(CommandError, match="not allowed with argument"):
+ call_command("bake_dev_stack_image", *args)
+ with pytest.raises(CommandError, match="Choose only one"):
+ call_command("bake_dev_stack_image", **options)
+
+
@pytest.mark.django_db(transaction=True)
def test_concurrent_sweeps_reserve_one_attempt(state: DevStackImageState) -> None:
observe(state)
@@ -191,3 +437,69 @@ def test_concurrent_sweeps_reserve_one_attempt(state: DevStackImageState) -> Non
futures = [pool.submit(reconcile) for _ in range(2)]
assert futures[0].result(timeout=10) == futures[1].result(timeout=10)
assert DevStackImageAttempt.objects.count() == 1
+
+
[email protected]_db(transaction=True)
[email protected]("failure", [None, "invalid", "provider", "connection"])
+async def test_activation_activity_preserves_active_image_until_verification(failure: str | None) -> None:
+ target = await DevStackImageTarget.objects.acreate(
+ region="DEV",
+ name="posthog-dev-stack",
+ enabled=True,
+ generation=1,
+ base_reference="sha256:example",
+ repository_sha="a" * 40,
+ recipe_sha="b" * 64,
+ active_image_id="im-existing",
+ )
+ state = DevStackImageState(target.pk)
+ attempt = await sync_to_async(state.reconcile)()
+ assert attempt is not None
+ error = (
+ DevStackImageVerificationError("invalid")
+ if failure == "invalid"
+ else RuntimeError("provider unavailable")
+ if failure == "provider"
+ else None
+ )
+ original_checkpoint = DevStackImageState.checkpoint
+ checkpoint_calls = 0
+
+ def checkpoint(state: DevStackImageState, attempt_id: uuid.UUID, owner: uuid.UUID, image_id: str) -> bool:
+ nonlocal checkpoint_calls
+ checkpoint_calls += 1
+ if failure == "connection" and checkpoint_calls == 1:
+ raise OperationalError("connection closed")
+ return original_checkpoint(state, attempt_id, owner, image_id)
+
+ with (
+ patch.object(DevStackImageState, "checkpoint", checkpoint),
+ patch(
+ "products.tasks.backend.temporal.bake_dev_stack_image.activation.bake_dev_stack_image",
+ return_value="im-candidate",
+ ),
+ patch(
+ "products.tasks.backend.temporal.bake_dev_stack_image.activation.verify_dev_stack_image",
+ return_value="1.0.0",
+ side_effect=error,
+ ),
+ ):
+ if error:
+ with pytest.raises(type(error)):
+ await ActivityEnvironment().run(activate_dev_stack_image, str(attempt.id))
+ else:
+ assert await ActivityEnvironment().run(activate_dev_stack_image, str(attempt.id)) == "im-candidate"
+ await target.arefresh_from_db()
+ assert target.active_image_id == ("im-existing" if error else "im-candidate")
+ if failure == "provider":
+ assert target.blocked_reason == ""
+ assert target.next_retry_at is not None
+ with patch(
+ "products.tasks.backend.logic.services.dev_stack_image_state.timezone.now",
+ return_value=target.next_retry_at,
+ ):
+ retry = await sync_to_async(state.reconcile)()
+ assert retry is not None and retry.candidate_image_id == "im-candidate"
+ if failure == "connection":
+ assert checkpoint_calls == 2