: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
fix(tasks): reserve a cpu floor for dev-stack image sandboxes (#90855)
Alessandro Pogliaghib9a10c564ab6
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.mdindex dc3909684829..b1d4dcacc85b 100644--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md@@ -343,8 +343,10 @@ the agent up. The in-sandbox script (`start-dev-stack-preview.sh`) runs `pnpm in`failed` in `/tmp/posthog-preview/status.json`, which the wait activity polls. A crashed or unreadydev-stack process fails the preview instead of publishing a half-working one, and each click on thelink re-probes Django and Vite inside the sandbox before redirecting. Startup peaks around 19 GB, so-these runs default to 32 GB rather than the standard VM memory size; cores stay at the VM default,-and a per-task `sandbox_resources` override still wins. The launcher starts with a scrubbed+these runs default to 32 GB rather than the standard VM memory size; the core limit stays at the+VM default, but a box that actually boots the dev-stack image reserves 4 cores instead of the+burstable 0.5 floor (a fallback to the plain base image keeps the plain floor), and a per-task+`sandbox_resources` override still wins. The launcher starts with a scrubbedenvironment (`env -i`, fixed PATH), so the stack and its containers never inherit the run'sGitHub token or personal API key. Relaunching is safe: the script takes an `flock` and reports`ready` straight away when the stack is already serving.diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 8b8a0f3a1234..0a72130b7042 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -346,6 +346,7 @@ class ImageCandidate:image: modal.Imagelabel: strrestored_from_snapshot: bool = False+ has_dev_stack: bool = False# The image is a Modal sandbox filesystem snapshot (a resume snapshot or the# published dev-stack image), so a boot from it needs the post-create health probe —# snapshot restores can come up dead with every RPC succeeding.@@ -743,6 +744,7 @@ class ModalSandbox(AgentServerLaunchMixin):# when creating from the previous image fails (e.g. its overlay image build errors),# so a broken overlay costs the local packages, never the snapshot or custom image.candidates: list[ImageCandidate] = []+ requested_dev_stack = config.is_dev_stack_imageif snapshot_image is not None and snapshot_kind == SNAPSHOT_KIND_FILESYSTEM:overlaid_snapshot = _attach_local_package_mounts(snapshot_image, config.template, install_dependencies=False@@ -754,6 +756,7 @@ class ModalSandbox(AgentServerLaunchMixin):f"snapshot image {snapshot_external_id} with local package overlay",restored_from_snapshot=True,snapshot_derived=True,+ has_dev_stack=requested_dev_stack,))candidates.append(@@ -762,6 +765,7 @@ class ModalSandbox(AgentServerLaunchMixin):f"snapshot image {snapshot_external_id}",restored_from_snapshot=True,snapshot_derived=True,+ has_dev_stack=requested_dev_stack,))if custom_image is not None and custom_image_bare is not None:@@ -775,6 +779,7 @@ class ModalSandbox(AgentServerLaunchMixin):custom_image,f"custom image {config.custom_image_name} with local package overlay",snapshot_derived=custom_is_snapshot,+ has_dev_stack=requested_dev_stack,))candidates.append(@@ -782,6 +787,7 @@ class ModalSandbox(AgentServerLaunchMixin):custom_image_bare,f"custom image {config.custom_image_name}",snapshot_derived=custom_is_snapshot,+ has_dev_stack=requested_dev_stack,))candidates.append(ImageCandidate(base_image, "base image"))@@ -925,7 +931,8 @@ class ModalSandbox(AgentServerLaunchMixin):re-enter this chain (the wedged-restore recovery) can describe what they landed on."""for index, candidate in enumerate(candidates):- attempt_kwargs = {**create_kwargs, "image": candidate.image}+ config.dev_stack_present = candidate.has_dev_stack+ attempt_kwargs = {**create_kwargs, "image": candidate.image, **_resource_create_kwargs(config)}try:modal_output: StringIO | Nonewith capture_modal_output_if_debug() as modal_output:diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex beb1a1d6c638..36e822f0cc41 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -41,6 +41,7 @@ from products.tasks.backend.constants import (from products.tasks.backend.logic.services.sandbox_config import (BURSTABLE_REQUEST_CPU_CORES,BURSTABLE_REQUEST_MEMORY_MB,+ DEV_STACK_CPU_REQUEST_CORES,SANDBOX_TTL_SECONDS,VM_SANDBOX_CPU_CORES,)@@ -174,6 +175,7 @@ class SandboxConfig(BaseModel):# downgraded one was used instead (e.g. published custom image -> plain base). Human-readable,# surfaced in the run log so image downgrades are never silent.image_fallback: str | None = None+ dev_stack_present: bool | None = None@model_validator(mode="before")@classmethod@@ -193,11 +195,22 @@ class SandboxConfig(BaseModel):def is_vm(self) -> bool:return self.vm_runtime or self.template == SandboxTemplate.VM_BASE+ @property+ def is_dev_stack_image(self) -> bool:+ if not self.is_vm:+ return False+ if self.dev_stack_present is not None:+ return self.dev_stack_present+ return self.custom_image_name == DEV_STACK_IMAGE_NAME+@propertydef effective_cpu_request_cores(self) -> float:"""CPU floor the provider actually reserves when burstable: the configured request,- clamped to the limit."""- return min(float(self.cpu_request_cores), float(self.cpu_cores))+ raised to the dev-stack image floor, clamped to the limit."""+ floor = float(self.cpu_request_cores)+ if self.is_dev_stack_image:+ floor = max(floor, DEV_STACK_CPU_REQUEST_CORES)+ return min(floor, float(self.cpu_cores))@propertydef effective_memory_request_mb(self) -> int:diff --git a/products/tasks/backend/logic/services/sandbox_config.py b/products/tasks/backend/logic/services/sandbox_config.pyindex f20158259b08..f9c859785fb7 100644--- a/products/tasks/backend/logic/services/sandbox_config.py+++ b/products/tasks/backend/logic/services/sandbox_config.py@@ -20,3 +20,4 @@ MAX_SANDBOX_MEMORY_GB = 64MAX_SANDBOX_TTL_SECONDS = SANDBOX_TTL_SECONDSDEV_STACK_PREVIEW_MEMORY_GB = 32.0+DEV_STACK_CPU_REQUEST_CORES = 4.0diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex d121af6d481c..545ab9a7ff23 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -1365,6 +1365,53 @@ class TestModalSandboxCreateImageFallback:assert sandbox.config.image_fallback is not Noneassert "custom image posthog-dev-stack" in sandbox.config.image_fallback+ def test_falling_back_to_the_base_image_drops_the_dev_stack_cpu_floor(self) -> None:+ config = SandboxConfig(+ name="t",+ template=SandboxTemplate.VM_BASE,+ custom_image_name="posthog-dev-stack",+ cpu_cores=8,+ memory_gb=16,+ burstable_resources=True,+ )+ bare_custom = MagicMock(name="bare_custom")+ cpu_requests: list[Any] = []+ original_create = MagicMock()++ def sandbox_create(**kwargs: Any) -> Any:+ cpu_requests.append(kwargs["cpu"])+ if kwargs["image"] is bare_custom:+ raise RuntimeError("image build failed")+ return original_create(**kwargs)++ original_create.return_value.object_id = "sb-created"+ original_create.return_value.exec.return_value.poll.return_value = 0+ 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",+ return_value=MagicMock(name="base"),+ ),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name",+ return_value=bare_custom,+ ),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",+ return_value=bare_custom,+ ),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", side_effect=sandbox_create+ ),+ patch("products.tasks.backend.logic.services.modal_sandbox.capture_exception"),+ ):+ sandbox = ModalSandbox.create(config)++ assert cpu_requests == [(4.0, 8.0), (0.5, 8.0)]+ assert sandbox.config.image_fallback is not None+ assert sandbox.config.effective_cpu_request_cores == 0.5+def test_snapshot_overlay_failure_falls_back_to_bare_snapshot(self):config = SandboxConfig(name="t", snapshot_external_id="im-snap-1")bare_snapshot = MagicMock(name="bare_snapshot")@@ -1760,6 +1807,26 @@ class TestResourceCreateKwargs:# Reserve the explicitly requested floor, burst up to the configured limit.assert kwargs == {"cpu": (2.0, 8.0), "memory": (4096, 16384)}+ @pytest.mark.parametrize(+ "config_kwargs, expected_cpu",+ [+ ({"vm_runtime": True, "custom_image_name": "posthog-dev-stack"}, (4.0, 8.0)),+ ({"vm_runtime": True, "custom_image_name": "posthog-dev-stack", "cpu_request_cores": 6}, (6.0, 8.0)),+ (+ {"vm_runtime": True, "custom_image_name": "posthog-dev-stack", "cpu_request_cores": 6, "cpu_cores": 4},+ (4.0, 4.0),+ ),+ ({"vm_runtime": True, "custom_image_name": "posthog-sandbox-custom-other"}, (0.5, 8.0)),+ ({"custom_image_name": "posthog-dev-stack"}, (0.5, 8.0)),+ ],+ )+ def test_dev_stack_image_raises_the_cpu_request_floor(+ self, config_kwargs: dict[str, Any], expected_cpu: tuple[float, float]+ ) -> None:+ config = SandboxConfig(name="t", memory_gb=16, burstable_resources=True, **{"cpu_cores": 8, **config_kwargs})++ assert _resource_create_kwargs(config)["cpu"] == expected_cpu+def test_vm_runtime_uses_equal_memory_request_and_limit(self):config = SandboxConfig(name="t", cpu_cores=4, memory_gb=16, burstable_resources=True, vm_runtime=True)