: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): burstable sandbox cpu/memory behind a feature flag (#63899)
Georgiy Tarasov3f39c04c08d9
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 4e63cb776168..eb38d0b4ffa7 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -3,6 +3,7 @@ from typing import Literal, get_argsSANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG = "tasks-modal-network-allowlist"+BURSTABLE_SANDBOX_RESOURCES_FEATURE_FLAG = "tasks-burstable-sandbox-resources"ClaudePermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissions", "auto"]CodexPermissionMode = Literal["auto", "read-only", "full-access"]diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 1146351adb85..a0c3464cf325 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -220,6 +220,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):event=event,properties=all_properties,groups=groups(team=self.team),+ send_feature_flags=True,)except Exception as e:logger.warning("task.capture_event_failed", analytics_event=event, error=str(e))@@ -922,6 +923,7 @@ class TaskRun(models.Model):"event": event,"properties": all_properties,"groups": groups(team=self.team),+ "send_feature_flags": True,}if event_uuid:capture_kwargs["uuid"] = event_uuiddiff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.pyindex 142b1bc2b720..02c9f1c214d1 100644--- a/products/tasks/backend/services/modal_sandbox.py+++ b/products/tasks/backend/services/modal_sandbox.py@@ -97,6 +97,27 @@ def _get_modal_region() -> str:return MODAL_REGION_BY_DEPLOYMENT.get(CLOUD_DEPLOYMENT, DEFAULT_MODAL_REGION)+def _resource_create_kwargs(config: SandboxConfig) -> dict[str, object]:+ """Build the `cpu`/`memory` kwargs for ``modal.Sandbox.create``.++ `cpu_cores` / `memory_gb` are the limit (max). When the config is burstable, emit Modal's+ ``(request, limit)`` tuple form so the box is billed at ``max(request, actual)`` and can burst+ up to the limit; otherwise emit the flat scalar, which makes request == limit (fixed size).++ The burstable request floor comes from ``cpu_request_cores`` / ``memory_request_mb`` (defaulting+ to the small floor in ``sandbox_config``). The request is clamped to the limit so it never+ exceeds it when the configured size is at or below the requested floor.+ """+ cpu_limit = float(config.cpu_cores)+ memory_limit_mb = int(config.memory_gb * 1024)+ if not config.burstable_resources:+ return {"cpu": cpu_limit, "memory": memory_limit_mb}+ return {+ "cpu": (min(float(config.cpu_request_cores), cpu_limit), cpu_limit),+ "memory": (min(int(config.memory_request_mb), memory_limit_mb), memory_limit_mb),+ }++LOCAL_MODAL_DOCKERFILES = {SandboxTemplate.DEFAULT_BASE: Path("products/tasks/backend/sandbox/images/Dockerfile.sandbox-base"),SandboxTemplate.NOTEBOOK_BASE: Path("products/tasks/backend/sandbox/images/Dockerfile.sandbox-notebook"),@@ -372,8 +393,7 @@ class ModalSandbox(SandboxBase):"name": sandbox_name,"image": image,"timeout": config.ttl_seconds,- "cpu": float(config.cpu_cores),- "memory": int(config.memory_gb * 1024),+ **_resource_create_kwargs(config),"region": region,"verbose": True,}diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.pyindex 87987a32e71e..3a3f0f4038cb 100644--- a/products/tasks/backend/services/sandbox.py+++ b/products/tasks/backend/services/sandbox.py@@ -26,7 +26,11 @@ from django.conf import settingsimport structlogfrom pydantic import BaseModel-from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS+from products.tasks.backend.services.sandbox_config import (+ BURSTABLE_REQUEST_CPU_CORES,+ BURSTABLE_REQUEST_MEMORY_MB,+ SANDBOX_TTL_SECONDS,+)if TYPE_CHECKING:from products.tasks.backend.temporal.process_task.utils import McpServerConfig@@ -79,6 +83,13 @@ class SandboxConfig(BaseModel):memory_gb: float = 16cpu_cores: float = 4disk_size_gb: float = 64+ # When True, request a small floor and let the box burst up to `cpu_cores` / `memory_gb`+ # (the limit); Modal bills max(request, actual). When False, request == limit (fixed size).+ burstable_resources: bool = False+ # Request floor used when `burstable_resources` is True: the box reserves this much and bursts+ # up to `cpu_cores` / `memory_gb`. Clamped to the limit at create time so it never exceeds it.+ cpu_request_cores: float = BURSTABLE_REQUEST_CPU_CORES+ memory_request_mb: int = BURSTABLE_REQUEST_MEMORY_MBvm_runtime: bool = False# gVisor only — Modal rejects this under vm_runtime.outbound_domain_allowlist: list[str] | None = Nonediff --git a/products/tasks/backend/services/sandbox_config.py b/products/tasks/backend/services/sandbox_config.pyindex d332f23262c7..a135efee7663 100644--- a/products/tasks/backend/services/sandbox_config.py+++ b/products/tasks/backend/services/sandbox_config.py@@ -4,3 +4,9 @@ from django.conf import settings# Tests: 15 min so any sandbox orphaned by a crashed test auto-destroys quickly# instead of burning Modal capacity for hours.SANDBOX_TTL_SECONDS = 15 * 60 if settings.TEST else 6 * 60 * 60++# Default request floor for burstable sandboxes (used when SandboxConfig.burstable_resources is+# True): the box reserves only this much and bursts up to its configured cpu_cores / memory_gb.+# Modal bills max(request, actual), so an idle burstable box costs the floor, not the full size.+BURSTABLE_REQUEST_CPU_CORES = 0.5+BURSTABLE_REQUEST_MEMORY_MB = 1024diff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/services/tests/test_modal_sandbox.pyindex 647b570b0acc..72116c94ede3 100644--- a/products/tasks/backend/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/services/tests/test_modal_sandbox.py@@ -19,6 +19,7 @@ from products.tasks.backend.services.modal_sandbox import (_get_modal_region,_get_sandbox_image_reference,_image_ref_cache,+ _resource_create_kwargs,)from products.tasks.backend.services.sandbox import AgentServerResult, ExecutionResult, SandboxConfig@@ -738,3 +739,60 @@ class TestModalSandboxAgentServerStartupHelpers:command = sandbox.execute.call_args_list[0][0][0]assert "pkill -TERM -f agent-server" in commandassert "pkill -KILL -f agent-server" in command+++class TestResourceCreateKwargs:+ def test_flat_scalars_when_not_burstable(self):+ config = SandboxConfig(name="t", cpu_cores=4, memory_gb=16)++ kwargs = _resource_create_kwargs(config)++ # Not burstable -> fixed-size box: request == limit, emitted as flat scalars.+ assert kwargs == {"cpu": 4.0, "memory": 16384}++ def test_tuple_request_and_limit_when_burstable(self):+ config = SandboxConfig(name="t", cpu_cores=4, memory_gb=16, burstable_resources=True)++ kwargs = _resource_create_kwargs(config)++ # Request the 0.5 CPU / 1024 MiB floor, burst up to the configured size (the limit).+ assert kwargs == {"cpu": (0.5, 4.0), "memory": (1024, 16384)}++ def test_floor_is_clamped_to_limit_when_config_is_below_floor(self):+ # A 1 GB / 1-core box whose configured size is at/under the floor still emits a valid+ # (request, limit) pair — the request is clamped so it never exceeds the limit.+ config = SandboxConfig(name="t", cpu_cores=1, memory_gb=1, burstable_resources=True)++ kwargs = _resource_create_kwargs(config)++ assert kwargs == {"cpu": (0.5, 1.0), "memory": (1024, 1024)}++ def test_explicit_request_floor_is_honored_when_burstable(self):+ config = SandboxConfig(+ name="t",+ cpu_cores=8,+ memory_gb=16,+ burstable_resources=True,+ cpu_request_cores=2,+ memory_request_mb=4096,+ )++ kwargs = _resource_create_kwargs(config)++ # Reserve the explicitly requested floor, burst up to the configured limit.+ assert kwargs == {"cpu": (2.0, 8.0), "memory": (4096, 16384)}++ def test_explicit_request_floor_is_clamped_to_limit(self):+ # A request floor above the configured limit is clamped down to the limit.+ config = SandboxConfig(+ name="t",+ cpu_cores=1,+ memory_gb=2,+ burstable_resources=True,+ cpu_request_cores=4,+ memory_request_mb=8192,+ )++ kwargs = _resource_create_kwargs(config)++ assert kwargs == {"cpu": (1.0, 1.0), "memory": (2048, 2048)}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 8d9c2c588e58..2e0e637cd745 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@@ -10,6 +10,7 @@ from posthog.models import Teamfrom posthog.temporal.common.utils import asyncify, close_db_connectionsfrom products.tasks.backend.constants import (+ BURSTABLE_SANDBOX_RESOURCES_FEATURE_FLAG,MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,MODAL_VM_SANDBOX_FEATURE_FLAG,SANDBOX_EVENT_INGEST_FEATURE_FLAG,@@ -65,6 +66,9 @@ class TaskProcessingContext:sandbox_event_ingest_enabled: bool = Falseuse_modal_vm_sandbox: bool = Falseuse_modal_network_allowlist: bool = False+ # Captured at workflow start so the provisioned box's resource request is stable across+ # activity retries (a mid-run flag flip can't change a live sandbox's resources anyway).+ burstable_sandbox_resources_enabled: bool = False@propertydef mode(self) -> str:@@ -225,6 +229,45 @@ def _is_modal_vm_sandbox_enabled(return enabled+def _is_burstable_sandbox_resources_enabled(+ *,+ distinct_id: str,+ organization_id: str,+ run_id: str,+ state: dict | None = None,+) -> bool:+ state_override = (state or {}).get("burstable_sandbox_resources_enabled")+ if isinstance(state_override, bool):+ log_with_activity_context(+ "burstable_sandbox_resources_state_override",+ run_id=run_id,+ burstable_sandbox_resources_enabled=state_override,+ )+ return state_override++ try:+ enabled = bool(+ posthoganalytics.feature_enabled(+ BURSTABLE_SANDBOX_RESOURCES_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,+ )+ )+ except Exception as e:+ log_with_activity_context("burstable_sandbox_resources_flag_check_failed", run_id=run_id, error=str(e))+ return False++ log_with_activity_context(+ "burstable_sandbox_resources_flag_checked",+ run_id=run_id,+ burstable_sandbox_resources_enabled=enabled,+ )+ return enabled++def _is_modal_network_allowlist_enabled(*,distinct_id: str,@@ -386,6 +429,17 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro"debug",f"use_modal_network_allowlist: {use_modal_network_allowlist} for this task run",)+ burstable_sandbox_resources_enabled = _is_burstable_sandbox_resources_enabled(+ distinct_id=distinct_id,+ organization_id=organization_id,+ run_id=run_id,+ state=state,+ )+ emit_agent_log(+ run_id,+ "debug",+ f"burstable_sandbox_resources_enabled: {burstable_sandbox_resources_enabled} for this task run",+ )user_github_integration_id = str(task.github_user_integration_id) if task.github_user_integration_id else Noneif user_github_integration_id is None and get_pr_authorship_mode(task, state).value == "user":user_github_integration = resolve_user_github_integration_for_task(task, allow_refresh=False)@@ -417,4 +471,5 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProsandbox_event_ingest_enabled=sandbox_event_ingest_enabled,use_modal_vm_sandbox=use_modal_vm_sandbox,use_modal_network_allowlist=use_modal_network_allowlist,+ burstable_sandbox_resources_enabled=burstable_sandbox_resources_enabled,)diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 522eb5cdf13c..fbf2feb33374 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -379,6 +379,18 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Crevm_runtime=use_vm_sandbox,)+ # Request a small slice and let the box burst up to the configured size. The decision is+ # captured once in the context at workflow start, so it's stable across activity retries.+ if ctx.burstable_sandbox_resources_enabled:+ config.burstable_resources = True+ emit_agent_log(+ ctx.run_id,+ "debug",+ f"Burstable resources enabled: requesting {config.cpu_request_cores} CPU / "+ f"{config.memory_request_mb} MiB, bursting up to {config.cpu_cores} CPU / "+ f"{int(config.memory_gb * 1024)} MiB",+ )+# gVisor only — Modal's domain allowlist breaks vm_runtime.if ctx.use_modal_network_allowlist and not use_vm_sandbox and ctx.allowed_domains is not None:config.outbound_domain_allowlist = _to_modal_domain_allowlist(ctx.allowed_domains)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 a6919994a2de..f5473ab55229 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@@ -8,12 +8,17 @@ from asgiref.sync import async_to_syncfrom posthog.models import OrganizationMembership, Userfrom posthog.models.user_integration import UserIntegration-from products.tasks.backend.constants import MODAL_VM_SANDBOX_FEATURE_FLAG, SANDBOX_EVENT_INGEST_FEATURE_FLAG+from products.tasks.backend.constants import (+ BURSTABLE_SANDBOX_RESOURCES_FEATURE_FLAG,+ MODAL_VM_SANDBOX_FEATURE_FLAG,+ SANDBOX_EVENT_INGEST_FEATURE_FLAG,+)from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundErrorfrom products.tasks.backend.models import SandboxEnvironment, Taskfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (GetTaskProcessingContextInput,TaskProcessingContext,+ _is_burstable_sandbox_resources_enabled,_is_modal_vm_sandbox_enabled,_is_sandbox_event_ingest_enabled,get_task_processing_context,@@ -387,6 +392,68 @@ class TestGetTaskProcessingContextActivity:feature_enabled_mock.assert_not_called()+ @pytest.mark.parametrize(+ "flag_value,expected",+ [+ (True, True),+ (False, False),+ (None, False),+ ],+ )+ def test_burstable_sandbox_resources_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:+ assert (+ _is_burstable_sandbox_resources_enabled(+ distinct_id="distinct-id",+ organization_id="organization-id",+ run_id="run-id",+ )+ is expected+ )++ feature_enabled_mock.assert_called_once_with(+ BURSTABLE_SANDBOX_RESOURCES_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,+ )++ def test_burstable_sandbox_resources_flag_fails_closed(self):+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flag service failed"),+ ):+ assert (+ _is_burstable_sandbox_resources_enabled(+ distinct_id="distinct-id",+ organization_id="organization-id",+ run_id="run-id",+ )+ is False+ )++ def test_burstable_sandbox_resources_state_override_skips_flag_check(self):+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ return_value=True,+ ) as feature_enabled_mock:+ assert (+ _is_burstable_sandbox_resources_enabled(+ distinct_id="distinct-id",+ organization_id="organization-id",+ run_id="run-id",+ state={"burstable_sandbox_resources_enabled": False},+ )+ is False+ )++ feature_enabled_mock.assert_not_called()+@pytest.mark.django_db(transaction=True)def test_get_task_processing_context_uses_sandbox_event_ingest_state_override(self, activity_environment, test_taskdiff --git a/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py b/products/tasks/backend/temporal/process_task/activities/track_workflow_event.pyindex 81e67539a463..c1058197d7bc 100644--- a/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py+++ b/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py@@ -31,6 +31,7 @@ def track_workflow_event(input: TrackWorkflowEventInput) -> None:event=input.event_name,properties=input.properties,groups=input.groups or {},+ send_feature_flags=True,)except Exception:logger.exception(