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): restrict modal VMs to custom images (#70656)

Alessandro Pogliaghi50c6137d1f8d
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 8b1d6e88d389..caef391b1a1f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1295,6 +1295,9 @@ def build_sandbox_custom_image(
parse_image_spec_yaml,
validate_spec_buildable,
)
+ from products.tasks.backend.metrics import (
+ observe_custom_image_build, # noqa: PLC0415 — keep prometheus deps off the api import path
+ )
from products.tasks.backend.temporal.client import execute_build_sandbox_image_workflow # noqa: PLC0415
image = _accessible_custom_images(team_id, user_id).filter(id=image_id).first()
@@ -1320,6 +1323,7 @@ def build_sandbox_custom_image(
image.error = ""
image.save(update_fields=["spec", "status", "error", "updated_at"])
+ observe_custom_image_build("started")
execute_build_sandbox_image_workflow(str(image.id), team_id)
return _reload_image_dto(image.pk)
@@ -1521,6 +1525,8 @@ def _sync_automation_schedule(automation: TaskAutomation) -> None:
# provision an oversized or long-lived sandbox beyond what they're entitled to.
# - use_modal_directory_resume_snapshots is the server-side directory snapshot rollout decision;
# a caller could otherwise force directory snapshot creation while the feature flag is off.
+# - use_modal_vm_sandbox is reserved for trusted server-created runs such as image builders;
+# a caller could otherwise force the VM runtime while the feature flag or custom-image gate is off.
# - snapshot_external_id / snapshot_kind / snapshot_mount_path control which Modal image is
# restored on resume and where directory snapshots are mounted.
# - workflow_id is the run's Temporal workflow address (``TaskRun.workflow_id`` prefers it over
@@ -1539,6 +1545,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"wizard_config",
"wizard_head_branch",
"use_modal_directory_resume_snapshots",
+ "use_modal_vm_sandbox",
"snapshot_external_id",
"snapshot_kind",
"snapshot_mount_path",
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index e2c55865f045..a7bfdde6559e 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -10,6 +10,7 @@ if TYPE_CHECKING:
TaskWorkflowStartOutcome = Literal["attempted", "blocked", "failed", "started"]
+CustomImageBuildOutcome = Literal["started", "succeeded", "failed", "scan_rejected"]
# 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
@@ -79,6 +80,12 @@ TASK_RUN_FAILED_TOTAL = Counter(
],
)
+CUSTOM_IMAGE_BUILD_TOTAL = Counter(
+ "posthog_tasks_custom_image_build_total",
+ "Custom sandbox image build 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
@@ -228,6 +235,13 @@ def observe_prewarmed_activated(task_run: "TaskRun") -> None:
PREWARMED_ACTIVATED_TOTAL.labels(origin_product=origin_product_label(task_run)).inc()
+def observe_custom_image_build(outcome: CustomImageBuildOutcome) -> None:
+ try:
+ CUSTOM_IMAGE_BUILD_TOTAL.labels(outcome=outcome).inc()
+ except Exception:
+ logger.exception("custom_image_build_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/temporal/build_image/activities.py b/products/tasks/backend/temporal/build_image/activities.py
index e1e570908395..1196d4dad718 100644
--- a/products/tasks/backend/temporal/build_image/activities.py
+++ b/products/tasks/backend/temporal/build_image/activities.py
@@ -19,6 +19,7 @@ from products.tasks.backend.logic.services.image_spec import (
validate_image_repository,
validate_spec_buildable,
)
+from products.tasks.backend.metrics import observe_custom_image_build
from products.tasks.backend.models import SandboxCustomImage
from products.tasks.backend.temporal.observability import log_activity_execution
@@ -136,6 +137,7 @@ def scan_image_spec(input: ImageBuildActivityInput) -> ScanImageSpecOutput:
image.status = SandboxCustomImage.Status.SCAN_FAILED
image.error = "Security scan failed: " + ("; ".join(filter(None, high_findings)) or "unsafe spec")
image.save(update_fields=["scan_result", "status", "error", "updated_at"])
+ observe_custom_image_build("scan_rejected")
return result
@@ -322,6 +324,7 @@ def build_and_publish_image(input: ImageBuildActivityInput) -> str:
image.status = SandboxCustomImage.Status.READY
image.error = ""
image.save(update_fields=["version", "modal_image_name", "status", "error", "updated_at"])
+ observe_custom_image_build("succeeded")
logger.info(
"custom_image_published",
@@ -352,3 +355,4 @@ def mark_image_build_failed(input: MarkImageBuildFailedInput) -> None:
image.status = SandboxCustomImage.Status.BUILD_FAILED
image.error = input.error[:2000]
image.save(update_fields=["status", "error", "updated_at"])
+ observe_custom_image_build("failed")
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 8856eff0298b..0a2ca70feb85 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
@@ -352,6 +352,7 @@ def _is_modal_vm_sandbox_enabled(
run_id: str,
origin_product: str | None,
allowed_domains: list[str] | None,
+ custom_image_available: bool = False,
state: dict | None = None,
) -> bool:
if allowed_domains is not None:
@@ -362,6 +363,14 @@ def _is_modal_vm_sandbox_enabled(
)
return False
+ if origin_product != Task.OriginProduct.IMAGE_BUILDER and not custom_image_available:
+ log_with_activity_context(
+ "modal_vm_sandbox_skipped_without_custom_image",
+ run_id=run_id,
+ use_modal_vm_sandbox=False,
+ )
+ return False
+
state_override = (state or {}).get("use_modal_vm_sandbox")
if isinstance(state_override, bool):
log_with_activity_context(
@@ -377,13 +386,15 @@ def _is_modal_vm_sandbox_enabled(
log_with_activity_context("modal_vm_sandbox_flag_check_failed", run_id=run_id, error=str(e))
return False
- result = origin_product in allowed_origins
+ origin_allowed = origin_product in allowed_origins
+ result = origin_allowed
log_with_activity_context(
"modal_vm_sandbox_flag_checked",
run_id=run_id,
flag_enabled=bool(allowed_origins),
origin_product=origin_product,
allowed_origin_products=sorted(allowed_origins),
+ custom_image_available=custom_image_available,
use_modal_vm_sandbox=result,
)
return result
@@ -670,6 +681,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
run_id=run_id,
origin_product=task.origin_product,
allowed_domains=allowed_domains,
+ custom_image_available=environment_custom_image_name is not None,
state=state,
)
emit_agent_log(
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 cf26b0167972..c15c8ae9520e 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
@@ -614,6 +614,7 @@ class TestGetTaskProcessingContextActivity:
run_id="run-id",
origin_product="user_created",
allowed_domains=None,
+ custom_image_available=True,
)
is expected
)
@@ -643,7 +644,15 @@ class TestGetTaskProcessingContextActivity:
is False
)
- def test_modal_vm_sandbox_state_override_skips_flag_check(self):
+ @pytest.mark.parametrize(
+ "origin_product, custom_image_available, expected",
+ [
+ ("image_builder", False, True),
+ ("user_created", False, False),
+ ("user_created", True, True),
+ ],
+ )
+ def test_modal_vm_sandbox_state_override_skips_flag_check(self, origin_product, custom_image_available, expected):
with patch(
VM_FLAG_PAYLOAD_TARGET,
return_value=None,
@@ -653,11 +662,12 @@ class TestGetTaskProcessingContextActivity:
distinct_id="distinct-id",
organization_id="organization-id",
run_id="run-id",
- origin_product="user_created",
+ origin_product=origin_product,
allowed_domains=None,
+ custom_image_available=custom_image_available,
state={"use_modal_vm_sandbox": True},
)
- is True
+ is expected
)
payload_mock.assert_not_called()
@@ -700,17 +710,20 @@ class TestGetTaskProcessingContextActivity:
payload_mock.assert_not_called()
@pytest.mark.parametrize(
- "origin_product, payload, expected",
+ "origin_product, payload, custom_image_available, expected",
[
- ("user_created", None, False),
- ("signals_scout", None, False),
- ("signals_scout", {"origin_products": ["signals_scout"]}, True),
- ("signals_scout", ["signals_scout", "user_created"], True),
- ("user_created", {"origin_products": ["signals_scout"]}, False),
- ("user_created", '{"origin_products": ["user_created"]}', True),
+ ("user_created", None, True, False),
+ ("signals_scout", None, False, False),
+ ("signals_scout", {"origin_products": ["signals_scout"]}, False, False),
+ ("signals_scout", ["signals_scout", "user_created"], False, False),
+ ("signals_scout", {"origin_products": ["signals_scout"]}, True, True),
+ ("image_builder", {"origin_products": ["image_builder"]}, False, True),
+ ("user_created", {"origin_products": ["signals_scout"]}, True, False),
+ ("user_created", '{"origin_products": ["user_created"]}', False, False),
+ ("user_created", '{"origin_products": ["user_created"]}', True, True),
],
)
- def test_modal_vm_sandbox_origin_product_gating(self, origin_product, payload, expected):
+ def test_modal_vm_sandbox_origin_product_gating(self, origin_product, payload, custom_image_available, expected):
with patch(
VM_FLAG_PAYLOAD_TARGET,
return_value=payload,
@@ -722,6 +735,7 @@ class TestGetTaskProcessingContextActivity:
run_id="run-id",
origin_product=origin_product,
allowed_domains=None,
+ custom_image_available=custom_image_available,
)
is expected
)
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 2651f9207e49..02f00b5fc4e7 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -3731,6 +3731,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"sandbox_ttl_seconds": 1800,
"inactivity_timeout_seconds": 600,
"use_modal_directory_resume_snapshots": True,
+ "use_modal_vm_sandbox": False,
"snapshot_external_id": "im-real",
"snapshot_kind": "directory",
"snapshot_mount_path": "/tmp",
@@ -3759,6 +3760,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"inactivity_timeout_seconds": 86400,
"wizard_config": {},
"use_modal_directory_resume_snapshots": False,
+ "use_modal_vm_sandbox": True,
"snapshot_external_id": "im-attacker",
"snapshot_kind": "directory",
"snapshot_mount_path": "/tmp/workspace",
@@ -3780,6 +3782,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["inactivity_timeout_seconds"] == 600
assert "wizard_config" not in run.state # caller cannot mark a run as a wizard run
assert run.state["use_modal_directory_resume_snapshots"] is True
+ assert run.state["use_modal_vm_sandbox"] is False
assert run.state["snapshot_external_id"] == "im-real"
assert run.state["snapshot_kind"] == "directory"
assert run.state["snapshot_mount_path"] == "/tmp"
@@ -3796,6 +3799,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"github_credential_source",
"sandbox_id",
"use_modal_directory_resume_snapshots",
+ "use_modal_vm_sandbox",
"snapshot_external_id",
"snapshot_kind",
"snapshot_mount_path",
@@ -3811,6 +3815,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["github_credential_source"] == "caller_token" # protected key survives removal
assert run.state["sandbox_id"] == "sb-real" # protected key survives removal
assert run.state["use_modal_directory_resume_snapshots"] is True # protected key survives removal
+ assert run.state["use_modal_vm_sandbox"] is False # protected key survives removal
assert run.state["snapshot_external_id"] == "im-real" # protected key survives removal
assert run.state["snapshot_kind"] == "directory" # protected key survives removal
assert run.state["snapshot_mount_path"] == "/tmp" # protected key survives removal
diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.py
index bb7e0f4b1984..a07c07a7da22 100644
--- a/products/tasks/backend/tests/test_task_run_metrics.py
+++ b/products/tasks/backend/tests/test_task_run_metrics.py
@@ -7,6 +7,7 @@ from prometheus_client import REGISTRY
from posthog.models import Organization, Team, User
+from products.tasks.backend.metrics import CustomImageBuildOutcome, observe_custom_image_build
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.client import execute_task_processing_workflow
from products.tasks.backend.temporal.process_task.activities.track_workflow_event import (
@@ -19,6 +20,21 @@ def _sample_value(name: str, labels: dict[str, str]) -> float:
return REGISTRY.get_sample_value(name, labels) or 0.0
+class TestCustomImageBuildMetrics:
+ @parameterized.expand(["started", "succeeded", "failed", "scan_rejected"])
+ def test_counter_tracks_lifecycle_outcomes(self, outcome: CustomImageBuildOutcome) -> None:
+ labels: dict[str, str] = {"outcome": outcome}
+ before = _sample_value("posthog_tasks_custom_image_build_total", labels)
+
+ observe_custom_image_build(outcome)
+
+ assert _sample_value("posthog_tasks_custom_image_build_total", labels) == before + 1
+
+ @patch("products.tasks.backend.metrics.CUSTOM_IMAGE_BUILD_TOTAL.labels", side_effect=RuntimeError("boom"))
+ def test_counter_failure_does_not_escape(self, _mock_labels: MagicMock) -> None:
+ observe_custom_image_build("succeeded")
+
+
class TestTaskRunMetrics(TestCase):
def setUp(self) -> None:
self.organization = Organization.objects.create(name="Test Org")