: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): provision task sandboxes from custom images (#68622)
Alessandro Pogliaghic5121e15d648
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.mdindex d9902d89edfb..d0cd3318a078 100644--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md@@ -305,6 +305,34 @@ the agent cannot bypass them through proxy settings or DNS tricks.Environments can also be managed via the REST API (`SandboxEnvironmentViewSet`)or the PostHog Code settings UI.+### Custom base images++Teams can bake their own tools and dependencies into a custom base image (`SandboxCustomImage`)+and select it as a cloud environment's base via `SandboxEnvironment.custom_image`.+Custom images always layer on top of the published VM sandbox base —+agent tooling, git guard, and the VM runtime are always present —+and the whole mechanism is gated on the Modal VM runtime being available:+the `sandbox_custom_images` API returns 403 (and the PostHog Code UI hides the feature)+unless the `tasks-modal-vm-sandbox` flag is enabled for the org+with `user_created` in its `origin_products` payload allowlist,+since custom-image sandboxes cannot run under gVisor.++The flow, driven from the PostHog Code Environments → Cloud tab:++1. Creating an image spawns an interactive **image-builder agent task**+ (`custom_image_builder_id` in the run state, VM runtime forced)+ that iterates inside the real VM base and maintains a declarative spec+ (`SandboxImageSpec`: `apt_packages`, `run_commands`, `env`) at `/tmp/workspace/image-spec.yaml`.+2. "Save & build" reads the spec from the builder sandbox (or accepts it inline via+ `POST /api/projects/:id/sandbox_custom_images/:id/build/`), then the+ `build-sandbox-image` Temporal workflow runs an LLM security scan of the spec,+ builds it layered on the VM base, and publishes it as a Modal named image+ (`Image.publish()` / `Image.from_name()`).+3. Runs using an environment with a ready custom image provision their sandbox+ from the published image (`SandboxConfig.custom_image_name`),+ falling back to the standard base if the image can't be loaded.+ Repo-setup snapshots are skipped for custom-image runs; resume snapshots still apply.+## Local developmentTo set up sandboxed agents for local development:diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 017d9aca01b0..cc9c04b7ccce 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -298,7 +298,8 @@ _template_image_lock = threading.Lock()@cached(cache=_template_image_cache, lock=_template_image_lock)-def _get_template_image(template: SandboxTemplate) -> modal.Image:+def get_template_base_image(template: SandboxTemplate) -> modal.Image:+ """The template's base image without local dev mounts — safe to extend with further layers."""registry_image = {SandboxTemplate.DEFAULT_BASE: SANDBOX_BASE_IMAGE,SandboxTemplate.NOTEBOOK_BASE: SANDBOX_NOTEBOOK_IMAGE,@@ -310,11 +311,18 @@ def _get_template_image(template: SandboxTemplate) -> modal.Image:if settings.DEBUG:dockerfile_path, context_dir = _prepare_local_modal_build_context(template)- image = modal.Image.from_dockerfile(dockerfile_path, context_dir=context_dir, ignore=[])- else:- image = modal.Image.from_registry(_get_sandbox_image_reference(registry_image))+ return modal.Image.from_dockerfile(dockerfile_path, context_dir=context_dir, ignore=[])+ return modal.Image.from_registry(_get_sandbox_image_reference(registry_image))+++def _get_template_image(template: SandboxTemplate) -> modal.Image:+ return _attach_local_package_mounts(get_template_base_image(template), template)+- return _attach_local_package_mounts(image, template)+def resolve_template_base_image(template: SandboxTemplate) -> modal.Image:+ # Undecorated import surface: the @cached wrapper on get_template_base_image trips+ # mypy's cross-module attribute resolution intermittently, so external callers import this.+ return get_template_base_image(template)@lru_cache(maxsize=3)@@ -409,6 +417,17 @@ class ModalSandbox(SandboxBase):app = cls._get_app_for_template(config.template)base_image = _get_template_image(config.template)image = base_image+ custom_image: modal.Image | None = None+ if config.custom_image_name:+ try:+ custom_image = _attach_local_package_mounts(+ modal.Image.from_name(config.custom_image_name), config.template+ )+ 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 Noneconfig.snapshot_restored = Falsesnapshot_external_id: str | None = Nonesnapshot_kind = _normalize_snapshot_kind(config.snapshot_kind)@@ -481,14 +500,30 @@ class ModalSandbox(SandboxBase):sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]config.snapshot_restored = used_snapshot_imageexcept Exception as e:- if not used_snapshot_image:+ if not used_snapshot_image and not used_custom_image:raise- logger.warning(f"Failed to create sandbox with snapshot image, falling back to base image: {e}")+ 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"] = 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+ 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 = Falseif snapshot_kind == SNAPSHOT_KIND_DIRECTORY and snapshot_image is not None:# The mount REPLACES the target directory in the running sandbox — over a livediff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 7412f48adf1d..a45214e87552 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -25,13 +25,14 @@ from typing import TYPE_CHECKING, Protocol, Selffrom django.conf import settingsimport structlog-from pydantic import BaseModel+from pydantic import BaseModel, model_validatorfrom products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_FILESYSTEM, SnapshotKindfrom products.tasks.backend.logic.services.sandbox_config import (BURSTABLE_REQUEST_CPU_CORES,BURSTABLE_REQUEST_MEMORY_MB,SANDBOX_TTL_SECONDS,+ VM_SANDBOX_CPU_CORES,)if TYPE_CHECKING:@@ -108,6 +109,22 @@ class SandboxConfig(BaseModel):vm_runtime: bool = False# gVisor only — Modal rejects this under vm_runtime.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++ @model_validator(mode="before")+ @classmethod+ def _default_vm_cpu(cls, data: object) -> object:+ if (+ isinstance(data, dict)+ and "cpu_cores" not in data+ and (+ data.get("vm_runtime")+ or data.get("template") in (SandboxTemplate.VM_BASE, SandboxTemplate.VM_BASE.value)+ )+ ):+ return {**data, "cpu_cores": VM_SANDBOX_CPU_CORES}+ return data@propertydef is_vm(self) -> bool:diff --git a/products/tasks/backend/logic/services/sandbox_config.py b/products/tasks/backend/logic/services/sandbox_config.pyindex 782e3821a434..42c5a9e54c68 100644--- a/products/tasks/backend/logic/services/sandbox_config.py+++ b/products/tasks/backend/logic/services/sandbox_config.py@@ -11,6 +11,8 @@ SANDBOX_TTL_SECONDS = 15 * 60 if settings.TEST else 6 * 60 * 60BURSTABLE_REQUEST_CPU_CORES = 0.5BURSTABLE_REQUEST_MEMORY_MB = 1024+VM_SANDBOX_CPU_CORES = 8.0+# Upper bounds for per-task sandbox resource overrides. Override values are clamped# to these so a bad or hostile value can't provision an oversized/long-lived sandbox.MAX_SANDBOX_CPU_CORES = 16diff --git a/products/tasks/backend/temporal/build_image/activities.py b/products/tasks/backend/temporal/build_image/activities.pyindex a7186df039a7..e1e570908395 100644--- a/products/tasks/backend/temporal/build_image/activities.py+++ b/products/tasks/backend/temporal/build_image/activities.py@@ -203,9 +203,9 @@ def _attach_repo_warm_layer(image: "modal.Image", spec: SandboxImageSpec):def _compose_modal_image(spec: SandboxImageSpec, *, repository: str, team_id: int) -> "tuple[modal.Image, modal.App]":- from products.tasks.backend.logic.services.modal_sandbox import ( # type: ignore[attr-defined] # noqa: PLC0415+ from products.tasks.backend.logic.services.modal_sandbox import ( # noqa: PLC0415ModalSandbox,- get_template_base_image,+ resolve_template_base_image,)from products.tasks.backend.logic.services.sandbox import SandboxTemplate, get_sandbox_class # noqa: PLC0415@@ -214,7 +214,7 @@ def _compose_modal_image(spec: SandboxImageSpec, *, repository: str, team_id: inraise RuntimeError("Custom image builds require the Modal sandbox provider")app = sandbox_cls._get_app_for_template(SandboxTemplate.VM_BASE)- image = get_template_base_image(SandboxTemplate.VM_BASE)+ image = resolve_template_base_image(SandboxTemplate.VM_BASE)# Clone the linked repo with the token FIRST, on the trusted base, before any spec-authored# layer can tamper with git to capture it. The warm step runs later, token-free.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.pyindex d0c25a466e72..6b028b7e21bf 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@@ -1,4 +1,3 @@-import jsonfrom dataclasses import dataclassfrom datetime import timedelta@@ -15,9 +14,9 @@ from products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG,MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,- MODAL_VM_SANDBOX_FEATURE_FLAG,OVERLAP_CLONE_BOOT_FEATURE_FLAG,SANDBOX_EVENT_INGEST_FEATURE_FLAG,+ vm_sandbox_allowed_origins,)from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyErrorfrom products.tasks.backend.logic.services.sandbox_config import (@@ -25,7 +24,7 @@ from products.tasks.backend.logic.services.sandbox_config import (MAX_SANDBOX_MEMORY_GB,MAX_SANDBOX_TTL_SECONDS,)-from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun+from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.temporal.constants import resolve_inactivity_timeoutfrom products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_contextfrom products.tasks.backend.temporal.process_task.utils import (@@ -84,6 +83,8 @@ class TaskProcessingContext:overlap_clone_boot_enabled: bool = False# Captured at workflow start so the agent-proxy stream lifetime stays deterministic across retries.agent_proxy_keep_stream_open: bool = False+ # Set only when the run resolved to the VM runtime — custom images layer on the VM base.+ custom_image_name: str | None = None@propertydef mode(self) -> str:@@ -139,25 +140,16 @@ class TaskProcessingContext:return value if isinstance(value, dict) else Nonedef inactivity_timeout(self) -> timedelta:- """How long the run may sit idle before the workflow times it out.-- Longer for user-driven runs (explicitly user-created, or with no origin- product) than for automated/background runs. A global env override or a- per-task override set at creation time both take precedence.- """- is_user_origin = not self.origin_product or self.origin_product == Task.OriginProduct.USER_CREATED.value+ """Idle time before the workflow times the run out; longer for user-driven runs."""+ is_user_origin = not self.origin_product or self.origin_product in (+ Task.OriginProduct.USER_CREATED.value,+ Task.OriginProduct.IMAGE_BUILDER.value,+ )return resolve_inactivity_timeout(is_user_origin=is_user_origin, state=self.state)def sandbox_resource_overrides(self) -> dict[str, float | int]:- """SandboxConfig field overrides requested at task creation (compute + TTL).-- Empty when the task requested none — callers spread it into SandboxConfig so- unset fields keep their defaults. `bool` is excluded explicitly since it's an- `int` subclass and would otherwise slip through as 0/1. Values are clamped to- server-owned bounds (and non-positive values ignored) as defense-in-depth, so- even if an override reaches here via an unexpected path it can't provision an- oversized sandbox.- """+ """Per-task SandboxConfig overrides (compute + TTL), clamped to server-owned bounds.+ `bool` is excluded explicitly — it's an `int` subclass and would slip through as 0/1."""overrides: dict[str, float | int] = {}state = self.state or {}for state_key, config_key, max_value in (@@ -290,18 +282,6 @@ def _is_sandbox_event_ingest_enabled(return enabled-def _vm_sandbox_allowed_origin_products(payload: object) -> set[str]:- if isinstance(payload, str):- try:- payload = json.loads(payload)- except (ValueError, TypeError):- payload = None- 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)}- return set()--def _is_modal_vm_sandbox_enabled(*,distinct_id: str,@@ -329,35 +309,16 @@ def _is_modal_vm_sandbox_enabled(return state_overridetry:- enabled = bool(- posthoganalytics.feature_enabled(- MODAL_VM_SANDBOX_FEATURE_FLAG,- distinct_id=distinct_id,- groups={"organization": organization_id},- group_properties={"organization": {"id": organization_id}},- only_evaluate_locally=False,- send_feature_flag_events=False,- )- )- allowed_origins: set[str] = set()- if enabled:- payload = posthoganalytics.get_feature_flag_payload(- MODAL_VM_SANDBOX_FEATURE_FLAG,- distinct_id=distinct_id,- groups={"organization": organization_id},- group_properties={"organization": {"id": organization_id}},- only_evaluate_locally=False,- )- allowed_origins = _vm_sandbox_allowed_origin_products(payload)+ allowed_origins = vm_sandbox_allowed_origins(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- result = enabled and origin_product in allowed_origins+ result = origin_product in allowed_originslog_with_activity_context("modal_vm_sandbox_flag_checked",run_id=run_id,- flag_enabled=enabled,+ flag_enabled=bool(allowed_origins),origin_product=origin_product,allowed_origin_products=sorted(allowed_origins),use_modal_vm_sandbox=result,@@ -528,6 +489,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProsandbox_environment_id = state.get("sandbox_environment_id")sandbox_environment_name: str | None = Noneallowed_domains: list[str] | None = None+ environment_custom_image_name: str | None = Noneif sandbox_environment_id:sandbox_environment = task_run.get_sandbox_environment()@@ -541,6 +503,23 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro)else:sandbox_environment_name = sandbox_environment.name+ custom_image = sandbox_environment.custom_image+ if custom_image is not None:+ if not custom_image.is_accessible_to_user(task.created_by_id):+ emit_agent_log(+ run_id,+ "warn",+ f"Custom image '{custom_image.name}' is private to its creator; using the default base image",+ )+ elif custom_image.is_ready:+ environment_custom_image_name = custom_image.modal_image_name+ else:+ emit_agent_log(+ run_id,+ "warn",+ f"Custom image '{custom_image.name}' is not ready (status: {custom_image.status}); "+ "using the default base image",+ )if sandbox_environment.network_access_level == SandboxEnvironment.NetworkAccessLevel.FULL:allowed_domains = Noneelse:@@ -559,6 +538,22 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProf"Resolved sandbox environment '{sandbox_environment.name}' with full network access",)+ # A per-run image (picked at task start) wins over the environment's image.+ state_custom_image_id = state.get("custom_image_id")+ if state_custom_image_id:+ state_custom_image = SandboxCustomImage.get_accessible_for_task(+ image_id=state_custom_image_id, team_id=task.team_id, task_created_by_id=task.created_by_id+ )+ if state_custom_image is not None and state_custom_image.is_ready:+ environment_custom_image_name = state_custom_image.modal_image_name+ else:+ emit_agent_log(+ run_id,+ "warn",+ f"Requested custom image {state_custom_image_id} is missing, not accessible, or not ready; "+ "falling back to the environment or default base image",+ )+log_with_activity_context("Task processing context created",task_id=str(task.id),@@ -610,6 +605,18 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro"debug",f"use_modal_vm_sandbox: {use_modal_vm_sandbox} for this task run",)+ custom_image_name: str | None = None+ if environment_custom_image_name:+ if use_modal_vm_sandbox:+ custom_image_name = environment_custom_image_name+ emit_agent_log(run_id, "debug", f"Using custom base image: {custom_image_name}")+ else:+ emit_agent_log(+ run_id,+ "warn",+ "This environment's custom image requires the VM runtime, which is not enabled for this run; "+ "using the default base image",+ )use_modal_network_allowlist = _is_modal_network_allowlist_enabled(distinct_id=distinct_id,organization_id=organization_id,@@ -697,4 +704,5 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProburstable_sandbox_resources_enabled=burstable_sandbox_resources_enabled,overlap_clone_boot_enabled=overlap_clone_boot_enabled,agent_proxy_keep_stream_open=agent_proxy_keep_stream_open,+ custom_image_name=custom_image_name,)diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 7a81f0a3ee37..0b825ae5acd4 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -183,6 +183,7 @@ def _get_image_source_label(provider: str | None,resume_snapshot_external_id: str | None,snapshot: SandboxSnapshot | None,+ custom_image_name: str | None = None,) -> tuple[str, str]:if resume_snapshot_external_id:return "resume_snapshot", f"resume snapshot {resume_snapshot_external_id}"@@ -191,6 +192,9 @@ def _get_image_source_label(external_id = snapshot.external_id or str(snapshot.id)return "repository_snapshot", f"repository snapshot {external_id}"+ if custom_image_name:+ return "custom_image", f"custom base image {custom_image_name}"+if provider == "docker":return "docker_base_image", "local Docker sandbox image"@@ -315,7 +319,9 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Psnapshot_source = "none"snapshot_kind = SNAPSHOT_KIND_FILESYSTEMsnapshot_mount_path: str | None = None- if has_repo and ctx.github_integration_id is not None:+ # Repo-setup snapshots come from default-base sandboxes; restoring one would silently+ # drop the custom base image. Resume snapshots were taken from this task's own sandbox.+ if has_repo and ctx.github_integration_id is not None and not ctx.custom_image_name:assert repository is not Nonewith StepTimer("snapshot_lookup") as snapshot_lookup_timer:snapshot = SandboxSnapshot.get_latest_snapshot_with_repos(ctx.github_integration_id, [repository])@@ -420,6 +426,7 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Pprovider=provider,resume_snapshot_external_id=resume_snapshot_external_id,snapshot=snapshot if not resume_snapshot_external_id else None,+ custom_image_name=ctx.custom_image_name if ctx.use_modal_vm_sandbox else None,)return PrepareSandboxForRepositoryOutput(@@ -465,6 +472,7 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Creconfig = SandboxConfig(name=prepared.sandbox_name,template=SandboxTemplate.VM_BASE if use_vm_sandbox else SandboxTemplate.DEFAULT_BASE,+ custom_image_name=ctx.custom_image_name if use_vm_sandbox else None,environment_variables=prepared.environment_variables,snapshot_id=prepared.snapshot_id,snapshot_external_id=prepared.snapshot_external_id,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.pyindex fc539c45ddb5..a828d92dfbda 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@@ -14,6 +14,7 @@ from products.tasks.backend.constants import (MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG,MODAL_VM_SANDBOX_FEATURE_FLAG,SANDBOX_EVENT_INGEST_FEATURE_FLAG,+ vm_sandbox_allowed_origin_products,)from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyErrorfrom products.tasks.backend.models import SandboxEnvironment, Task@@ -24,10 +25,11 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processing_is_burstable_sandbox_resources_enabled,_is_modal_vm_sandbox_enabled,_is_sandbox_event_ingest_enabled,- _vm_sandbox_allowed_origin_products,get_task_processing_context,)+VM_FLAG_PAYLOAD_TARGET = "products.tasks.backend.constants.posthoganalytics.get_feature_flag_payload"+@pytest.mark.requires_secretsclass TestGetTaskProcessingContextActivity:@@ -425,24 +427,17 @@ class TestGetTaskProcessingContextActivity:feature_enabled_mock.assert_not_called()@pytest.mark.parametrize(- "flag_value, expected",+ "payload, expected",[- (True, True),- (False, False),+ ('{"origin_products": ["user_created"]}', True),(None, False),],)- def test_modal_vm_sandbox_flag_uses_organization_rollout(self, flag_value, expected):- with (- patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",- return_value=flag_value,- ) as feature_enabled_mock,- patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.get_feature_flag_payload",- return_value=["user_created"],- ),- ):+ def test_modal_vm_sandbox_flag_uses_organization_rollout(self, payload, expected):+ with patch(+ VM_FLAG_PAYLOAD_TARGET,+ return_value=payload,+ ) as payload_mock:assert (_is_modal_vm_sandbox_enabled(distinct_id="distinct-id",@@ -454,7 +449,7 @@ class TestGetTaskProcessingContextActivity:is expected)- feature_enabled_mock.assert_called_once_with(+ payload_mock.assert_called_once_with(MODAL_VM_SANDBOX_FEATURE_FLAG,distinct_id="distinct-id",groups={"organization": "organization-id"},@@ -465,7 +460,7 @@ class TestGetTaskProcessingContextActivity:def test_modal_vm_sandbox_flag_fails_closed(self):with patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ VM_FLAG_PAYLOAD_TARGET,side_effect=RuntimeError("flag service failed"),):assert (@@ -481,9 +476,9 @@ class TestGetTaskProcessingContextActivity:def test_modal_vm_sandbox_state_override_skips_flag_check(self):with patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",- return_value=False,- ) as feature_enabled_mock:+ VM_FLAG_PAYLOAD_TARGET,+ return_value=None,+ ) as payload_mock:assert (_is_modal_vm_sandbox_enabled(distinct_id="distinct-id",@@ -496,13 +491,13 @@ class TestGetTaskProcessingContextActivity:is True)- feature_enabled_mock.assert_not_called()+ payload_mock.assert_not_called()def test_modal_vm_sandbox_restricted_egress_forces_gvisor(self):with patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",- return_value=True,- ) as feature_enabled_mock:+ VM_FLAG_PAYLOAD_TARGET,+ return_value='{"origin_products": ["user_created"]}',+ ) as payload_mock:assert (_is_modal_vm_sandbox_enabled(distinct_id="distinct-id",@@ -514,13 +509,13 @@ class TestGetTaskProcessingContextActivity:is False)- feature_enabled_mock.assert_not_called()+ payload_mock.assert_not_called()def test_modal_vm_sandbox_restricted_egress_overrides_state_override(self):with patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",- return_value=True,- ) as feature_enabled_mock:+ VM_FLAG_PAYLOAD_TARGET,+ return_value='{"origin_products": ["user_created"]}',+ ) as payload_mock:assert (_is_modal_vm_sandbox_enabled(distinct_id="distinct-id",@@ -533,7 +528,7 @@ class TestGetTaskProcessingContextActivity:is False)- feature_enabled_mock.assert_not_called()+ payload_mock.assert_not_called()@pytest.mark.parametrize("origin_product, payload, expected",@@ -547,15 +542,9 @@ class TestGetTaskProcessingContextActivity:],)def test_modal_vm_sandbox_origin_product_gating(self, origin_product, payload, expected):- with (- patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",- return_value=True,- ),- patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.get_feature_flag_payload",- return_value=payload,- ),+ with patch(+ VM_FLAG_PAYLOAD_TARGET,+ return_value=payload,):assert (_is_modal_vm_sandbox_enabled(@@ -581,7 +570,7 @@ class TestGetTaskProcessingContextActivity:],)def test_vm_sandbox_allowed_origin_products_parsing(self, payload, expected):- assert _vm_sandbox_allowed_origin_products(payload) == expected+ assert vm_sandbox_allowed_origin_products(payload) == expected@pytest.mark.parametrize("state,expected",