: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): per-task sandbox resources/timeout + lower inactivity timeout (#63846)
Joshua Snyder6a850c479fc5
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.pyindex c203e0dcb920..3d704c3e3e93 100644--- a/products/tasks/backend/api.py+++ b/products/tasks/backend/api.py@@ -245,8 +245,21 @@ def _github_credential_source_extra_state(# task creator's server-side token injected into their sandbox.# - sandbox_id is the credential-propagation target; a caller could otherwise repoint a visible# run at a sandbox they control and capture the run owner's token on the next rotation.-# All three are written only server-side (run creation + the temporal workflow), never via PATCH.-_PROTECTED_RUN_STATE_KEYS = frozenset({"github_credential_source", "pr_authorship_mode", "sandbox_id"})+# - sandbox_cpu_cores / sandbox_memory_gb / sandbox_ttl_seconds / inactivity_timeout_seconds set+# the run's compute and lifetime at creation; a caller could otherwise PATCH a queued run to+# provision an oversized or long-lived sandbox beyond what they're entitled to.+# All are written only server-side (run creation + the temporal workflow), never via PATCH.+_PROTECTED_RUN_STATE_KEYS = frozenset(+ {+ "github_credential_source",+ "pr_authorship_mode",+ "sandbox_id",+ "sandbox_cpu_cores",+ "sandbox_memory_gb",+ "sandbox_ttl_seconds",+ "inactivity_timeout_seconds",+ }+)TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex a0c3464cf325..6dc6a976bf2f 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -15,6 +15,7 @@ from pydantic import BaseModelif TYPE_CHECKING:from products.slack_app.backend.slack_thread import SlackThreadContext+ from products.tasks.backend.services.sandbox import SandboxResourcesfrom django.conf import settingsfrom django.contrib.postgres.fields import ArrayField@@ -337,6 +338,9 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):interaction_origin: str | None = None,model: str | None = None,initial_permission_mode: str | None = None,+ sandbox_resources: "SandboxResources | None" = None,+ sandbox_timeout_seconds: int | None = None,+ inactivity_timeout_seconds: int | None = None,) -> "Task":from products.tasks.backend.temporal.client import execute_task_processing_workflow@@ -413,7 +417,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):**({"signal_report_id": signal_report_id} if signal_report_id else {}),)- extra_state: dict[str, str] = {}+ extra_state: dict[str, Any] = {}if slack_thread_url:extra_state["slack_thread_url"] = slack_thread_urlif interaction_origin:@@ -440,6 +444,23 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):if initial_permission_mode:extra_state["initial_permission_mode"] = initial_permission_mode+ # Optional per-task sandbox compute/timeout overrides. Read back into+ # SandboxConfig at provision time (see TaskProcessingContext); unset+ # fields keep the SandboxConfig defaults.+ if sandbox_resources is not None:+ if sandbox_resources.cpu_cores is not None:+ extra_state["sandbox_cpu_cores"] = sandbox_resources.cpu_cores+ if sandbox_resources.memory_gb is not None:+ extra_state["sandbox_memory_gb"] = sandbox_resources.memory_gb+ if sandbox_timeout_seconds is not None:+ extra_state["sandbox_ttl_seconds"] = sandbox_timeout_seconds++ # Optional per-task inactivity timeout override (seconds). Read back via+ # TaskProcessingContext.inactivity_timeout(); unset falls back to the+ # origin-aware default.+ if inactivity_timeout_seconds is not None:+ extra_state["inactivity_timeout_seconds"] = inactivity_timeout_seconds+task_run = task.create_run(mode=mode, extra_state=extra_state or None, branch=branch)if start_workflow:diff --git a/products/tasks/backend/repo_selection/agent.py b/products/tasks/backend/repo_selection/agent.pyindex ac9227aa7741..877016694d06 100644--- a/products/tasks/backend/repo_selection/agent.py+++ b/products/tasks/backend/repo_selection/agent.py@@ -17,6 +17,7 @@ from posthog.sync import database_sync_to_asyncfrom products.tasks.backend.models import Taskfrom products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContextfrom products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession+from products.tasks.backend.services.sandbox import SandboxResourcesif TYPE_CHECKING:from products.tasks.backend.services.custom_prompt_internals import OutputFn@@ -364,6 +365,7 @@ async def select_repository(sandbox_environment_id=sandbox_environment_id,# Read-only PostHog scopes so the agent can call `execute-sql` against `system.integration_repository_cache`.posthog_mcp_scopes="read_only",+ sandbox_resources=SandboxResources(cpu_cores=2, memory_gb=8),)session, result = await MultiTurnSession.start(diff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/services/custom_prompt_internals.pyindex dfeae49a6d48..b441452e9f99 100644--- a/products/tasks/backend/services/custom_prompt_internals.py+++ b/products/tasks/backend/services/custom_prompt_internals.py@@ -20,6 +20,8 @@ from products.tasks.backend.models import Task, TaskRunif TYPE_CHECKING:from temporalio.client import WorkflowHandle+ from products.tasks.backend.services.sandbox import SandboxResources+logger = logging.getLogger(__name__)# Type for an optional output callback (e.g. management command's self.stdout.write)@@ -90,6 +92,11 @@ class CustomPromptSandboxContext:"""Override the agent model (e.g. ``"claude-opus-4-8"``). Falls back to theagent server's default when ``None``. Used by evals to pin a specificmodel so cross-run comparisons are stable."""+ sandbox_resources: SandboxResources | None = None+ """Override the sandbox's compute (CPU / memory). Unset fields keep the+ SandboxConfig defaults (4 cores / 16 GB)."""+ sandbox_timeout_seconds: int | None = None+ """Override the sandbox's max lifetime (Modal TTL). Falls back to SANDBOX_TTL_SECONDS."""class EmptyAgentTurnError(RuntimeError):@@ -132,6 +139,8 @@ async def create_task_and_trigger(sandbox_environment_id=context.sandbox_environment_id,model=context.model,internal=internal,+ sandbox_resources=context.sandbox_resources,+ sandbox_timeout_seconds=context.sandbox_timeout_seconds,)# lambda wrap: task.latest_run is a lazy ORM property; sync_to_async needs a callabletask_run = await sync_to_async(lambda: task.latest_run)()diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.pyindex 3a3f0f4038cb..0f5afeb96cb1 100644--- a/products/tasks/backend/services/sandbox.py+++ b/products/tasks/backend/services/sandbox.py@@ -71,6 +71,15 @@ class ExecutionStream(Protocol):def wait(self) -> ExecutionResult: ...+@dataclass(frozen=True)+class SandboxResources:+ """Optional compute overrides for a task's sandbox. Unset fields keep the+ `SandboxConfig` defaults — callers pass only what they want to change."""++ cpu_cores: float | None = None+ memory_gb: float | None = None++class SandboxConfig(BaseModel):name: strtemplate: SandboxTemplate = SandboxTemplate.DEFAULT_BASEdiff --git a/products/tasks/backend/services/sandbox_config.py b/products/tasks/backend/services/sandbox_config.pyindex a135efee7663..782e3821a434 100644--- a/products/tasks/backend/services/sandbox_config.py+++ b/products/tasks/backend/services/sandbox_config.py@@ -10,3 +10,9 @@ SANDBOX_TTL_SECONDS = 15 * 60 if settings.TEST else 6 * 60 * 60# Modal bills max(request, actual), so an idle burstable box costs the floor, not the full size.BURSTABLE_REQUEST_CPU_CORES = 0.5BURSTABLE_REQUEST_MEMORY_MB = 1024++# 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 = 16+MAX_SANDBOX_MEMORY_GB = 64+MAX_SANDBOX_TTL_SECONDS = SANDBOX_TTL_SECONDSdiff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.pyindex b1f3d32f8105..b0b48f551ea5 100644--- a/products/tasks/backend/temporal/constants.py+++ b/products/tasks/backend/temporal/constants.py@@ -11,11 +11,43 @@ from datetime import timedeltafrom django.conf import settings-# Default 2 hours in production. Override via TASKS_INACTIVITY_TIMEOUT_SECONDS-# for local testing (e.g. `TASKS_INACTIVITY_TIMEOUT_SECONDS=30` to force a fast-# shutdown for resume-flow testing). The CI follow-up timing lives in-# `task_management`, which now owns the loop.-INACTIVITY_TIMEOUT = timedelta(seconds=settings.TASKS_INACTIVITY_TIMEOUT_SECONDS or 2 * 60 * 60)+# Per-task inactivity timeout defaults (production). User-driven runs — explicitly+# user-created, or with no origin product — get a longer idle grace window since a+# human may still be in the loop; automated/background runs reclaim the sandbox+# worker sooner. Under test we drop to 2 minutes so orphaned runs don't pin a+# worker for long.+INACTIVITY_TIMEOUT_USER_SECONDS = 60 * 60 # 1 hour+INACTIVITY_TIMEOUT_DEFAULT_SECONDS = 30 * 60 # 30 minutes+INACTIVITY_TIMEOUT_TEST_SECONDS = 2 * 60 # 2 minutes+# Upper bound for a per-task inactivity override, so a bad or hostile value can't+# keep a sandbox alive far past the intended idle window.+MAX_INACTIVITY_TIMEOUT_SECONDS = 2 * 60 * 60 # 2 hours+++def resolve_inactivity_timeout(*, is_user_origin: bool = False, state: dict | None = None) -> timedelta:+ """Effective inactivity timeout for a task run, in priority order.++ 1. A per-task override stored at creation time (`inactivity_timeout_seconds`),+ clamped to `MAX_INACTIVITY_TIMEOUT_SECONDS`. An explicit per-task value is the+ most specific signal, so it wins even over the global env override.+ 2. The `TASKS_INACTIVITY_TIMEOUT_SECONDS` env var (global fallback, e.g.+ `=30` to force a fast shutdown for local resume-flow testing).+ 3. The test default (short, so orphaned runs don't pin a worker).+ 4. The origin-aware production default (longer for user-driven runs).+ """+ per_task = (state or {}).get("inactivity_timeout_seconds")+ if isinstance(per_task, int | float) and not isinstance(per_task, bool) and per_task > 0:+ return timedelta(seconds=int(min(per_task, MAX_INACTIVITY_TIMEOUT_SECONDS)))+ if settings.TASKS_INACTIVITY_TIMEOUT_SECONDS:+ return timedelta(seconds=settings.TASKS_INACTIVITY_TIMEOUT_SECONDS)+ if settings.TEST:+ return timedelta(seconds=INACTIVITY_TIMEOUT_TEST_SECONDS)+ return timedelta(seconds=INACTIVITY_TIMEOUT_USER_SECONDS if is_user_origin else INACTIVITY_TIMEOUT_DEFAULT_SECONDS)+++# Module-level default (non-user origin, no per-task override) for callers that+# don't have task context. The CI follow-up timing lives in `task_management`.+INACTIVITY_TIMEOUT = resolve_inactivity_timeout()# CI follow-up cadence after the agent has been idle.CI_FOLLOW_UP_DELAY = timedelta(minutes=15)diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex 09081ff522ba..5687947074b9 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -26,7 +26,6 @@ from posthog.temporal.oauth import PosthogMcpScopesfrom products.tasks.backend.services.sandbox import is_public_sandbox_repofrom products.tasks.backend.temporal.constants import (- INACTIVITY_TIMEOUT,OUTBOUND_RETRY_BACKOFF,PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,@@ -328,7 +327,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):return SandboxEvent.SIGNAL_RECEIVEDasync def _wait_for_inactivity(self) -> SandboxEvent:- await workflow.sleep(INACTIVITY_TIMEOUT.total_seconds())+ await workflow.sleep(self.context.inactivity_timeout().total_seconds())return SandboxEvent.TIMEOUT_REACHEDasync def _wait_for_event(self) -> SandboxEvent:diff --git a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.pyindex 2e498a4ec6c3..d7e3f7dfad7c 100644--- a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py@@ -120,6 +120,7 @@ def create_sandbox_from_snapshot(input: CreateSandboxFromSnapshotInput) -> Createnvironment_variables=environment_variables,snapshot_id=str(snapshot.id),metadata={"task_id": ctx.task_id},+ **ctx.sandbox_resource_overrides(),)sandbox = Sandbox.create(config)diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.pyindex 8f5cbfb79685..1a5085073cff 100644--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py@@ -254,6 +254,7 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbosnapshot_external_id=resume_snapshot_ext_id,snapshot_id=str(snapshot.id) if snapshot and not resume_snapshot_ext_id else None,metadata={"task_id": ctx.task_id},+ **ctx.sandbox_resource_overrides(),)emit_agent_log(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 2e0e637cd745..be9c95f80bc6 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,5 @@from dataclasses import dataclass+from datetime import timedeltafrom django.conf import settingsfrom django.core.exceptions import ObjectDoesNotExist@@ -17,6 +18,12 @@ from products.tasks.backend.constants import ()from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundErrorfrom products.tasks.backend.models import SandboxEnvironment, Task, TaskRun+from products.tasks.backend.services.sandbox_config import (+ MAX_SANDBOX_CPU_CORES,+ MAX_SANDBOX_MEMORY_GB,+ MAX_SANDBOX_TTL_SECONDS,+)+from 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 (format_allowed_domains_for_log,@@ -112,6 +119,40 @@ class TaskProcessingContext:value = (self.state or {}).get("run_source")return value if isinstance(value, str) else None+ def 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+ 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.+ """+ overrides: dict[str, float | int] = {}+ state = self.state or {}+ for state_key, config_key, max_value in (+ ("sandbox_cpu_cores", "cpu_cores", MAX_SANDBOX_CPU_CORES),+ ("sandbox_memory_gb", "memory_gb", MAX_SANDBOX_MEMORY_GB),+ ):+ value = state.get(state_key)+ if isinstance(value, int | float) and not isinstance(value, bool) and value > 0:+ overrides[config_key] = float(min(value, max_value))+ ttl = state.get("sandbox_ttl_seconds")+ if isinstance(ttl, int | float) and not isinstance(ttl, bool) and ttl > 0:+ overrides["ttl_seconds"] = int(min(ttl, MAX_SANDBOX_TTL_SECONDS))+ return overrides+def get_sandbox_environment(self):"""Resolve the SandboxEnvironment, team-scoped and respecting privacy."""sandbox_environment_id = self.sandbox_environment_iddiff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex fbf2feb33374..3d33392ebf21 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -377,6 +377,7 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cresnapshot_external_id=prepared.snapshot_external_id,metadata={"task_id": ctx.task_id},vm_runtime=use_vm_sandbox,+ **ctx.sandbox_resource_overrides(),)# Request a small slice and let the box burst up to the configured size. The decision isdiff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex f63c2b30eefb..fcd8d9fc6ae5 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -13,12 +13,15 @@ from temporalio import activityfrom posthog.temporal.common.utils import close_db_connections-from products.tasks.backend.models import TaskRun as TaskRunModel+from products.tasks.backend.models import (+ Task as TaskModel,+ TaskRun as TaskRunModel,+)from products.tasks.backend.redis import run_uses_dedicated_streamfrom products.tasks.backend.services.agent_command import validate_sandbox_urlfrom products.tasks.backend.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key-from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT+from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDS, resolve_inactivity_timeoutfrom ee.hogai.sandbox import is_turn_complete@@ -62,6 +65,14 @@ async def relay_sandbox_events(input: RelaySandboxEventsInput) -> None:task_run = await TaskRunModel.objects.select_related("task__created_by").aget(id=input.run_id)+ # Match the freshness window to the workflow's inactivity timeout for this run+ # so the heartbeat suppression below never resets a timer it shouldn't.+ origin_product = task_run.task.origin_product+ is_user_origin = not origin_product or origin_product == TaskModel.OriginProduct.USER_CREATED.value+ inactivity_timeout_seconds = resolve_inactivity_timeout(+ is_user_origin=is_user_origin, state=task_run.state+ ).total_seconds()+stream_key = get_task_run_stream_key(input.run_id)redis_stream = TaskRunRedisStream(stream_key, run_uses_dedicated_stream(task_run.state))await redis_stream.initialize()@@ -106,6 +117,7 @@ async def relay_sandbox_events(input: RelaySandboxEventsInput) -> None:sandbox_id=input.sandbox_id,background_logs_enabled=background_logs_enabled,task_run=task_run,+ inactivity_timeout_seconds=inactivity_timeout_seconds,)except asyncio.CancelledError:logger.info("relay_sandbox_events_cancelled", run_id=input.run_id)@@ -182,6 +194,7 @@ async def _background_heartbeat(last_event_time: list[float] | None = None,last_workflow_signal: list[float] | None = None,agent_active: list[bool] | None = None,+ inactivity_timeout_seconds: float = INACTIVITY_TIMEOUT_DEFAULT_SECONDS,) -> None:"""Heartbeat to Temporal periodically, independent of event flow.@@ -200,7 +213,7 @@ async def _background_heartbeat(workflow_handle is not Noneand last_event_time is not Noneand last_event_time[0] > 0- and (now - last_event_time[0]) < INACTIVITY_TIMEOUT.total_seconds()+ and (now - last_event_time[0]) < inactivity_timeout_secondsand (last_workflow_signal is None or (now - last_workflow_signal[0]) >= HEARTBEAT_INTERVAL_SECONDS)and (agent_active is None or agent_active[0])):@@ -225,6 +238,7 @@ async def _relay_loop(sandbox_id: str | None = None,background_logs_enabled: bool = False,task_run: TaskRunModel | None = None,+ inactivity_timeout_seconds: float = INACTIVITY_TIMEOUT_DEFAULT_SECONDS,) -> None:"""Connect to sandbox SSE and relay events to Redis. Reconnects on transient failures."""reconnect_count = 0@@ -250,7 +264,14 @@ async def _relay_loop(stop_heartbeat = asyncio.Event()heartbeat_task = asyncio.create_task(- _background_heartbeat(stop_heartbeat, workflow_handle, last_event_time, last_workflow_signal, agent_active)+ _background_heartbeat(+ stop_heartbeat,+ workflow_handle,+ last_event_time,+ last_workflow_signal,+ agent_active,+ inactivity_timeout_seconds=inactivity_timeout_seconds,+ ))try:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex 58ab0c5908c1..bf6180b961b8 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -213,7 +213,9 @@ class TestRelaySandboxEventsCancellation:return selfasync def aget(self, id: str) -> SimpleNamespace:- return SimpleNamespace(task=SimpleNamespace(created_by=SimpleNamespace(id=123)), state={})+ return SimpleNamespace(+ task=SimpleNamespace(created_by=SimpleNamespace(id=123), origin_product=None), state={}+ )async def fake_relay_loop(**_kwargs: object) -> None:raise asyncio.CancelledError@@ -527,7 +529,9 @@ class TestRelaySandboxEventsErrorHandling:return selfasync def aget(self, id: str) -> SimpleNamespace:- return SimpleNamespace(task=SimpleNamespace(created_by=SimpleNamespace(id=123)), state={})+ return SimpleNamespace(+ task=SimpleNamespace(created_by=SimpleNamespace(id=123), origin_product=None), state={}+ )async def fake_relay_loop(**_kwargs: object) -> None:raise RuntimeError("relay error")diff --git a/products/tasks/backend/temporal/process_task/tests/test_followup.py b/products/tasks/backend/temporal/process_task/tests/test_followup.pyindex 969311c5aa39..59c478b50193 100644--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py@@ -119,7 +119,7 @@ class TestFollowupDeliveryFailure:async def test_failed_followup_marks_run_as_failed_promptly(self):"""The workflow must exit its main loop and mark the run as failedwithin seconds when a followup delivery fails — not after the- 2-hour inactivity timeout."""+ full inactivity timeout."""_status_updates.clear()async with await WorkflowEnvironment.start_time_skipping() as env:diff --git a/products/tasks/backend/temporal/process_task/tests/test_inactivity_timeout.py b/products/tasks/backend/temporal/process_task/tests/test_inactivity_timeout.pynew file mode 100644index 000000000000..62e41c5268f1--- /dev/null+++ b/products/tasks/backend/temporal/process_task/tests/test_inactivity_timeout.py@@ -0,0 +1,69 @@+from datetime import timedelta++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from products.tasks.backend.temporal.constants import (+ INACTIVITY_TIMEOUT_DEFAULT_SECONDS,+ INACTIVITY_TIMEOUT_TEST_SECONDS,+ INACTIVITY_TIMEOUT_USER_SECONDS,+ MAX_INACTIVITY_TIMEOUT_SECONDS,+ resolve_inactivity_timeout,+)+++class TestResolveInactivityTimeout(SimpleTestCase):+ @parameterized.expand(+ [+ ("user_origin", True, INACTIVITY_TIMEOUT_USER_SECONDS),+ ("non_user_origin", False, INACTIVITY_TIMEOUT_DEFAULT_SECONDS),+ ]+ )+ @override_settings(TEST=False, TASKS_INACTIVITY_TIMEOUT_SECONDS=0)+ def test_production_default_depends_on_origin(self, _name, is_user_origin, expected_seconds):+ result = resolve_inactivity_timeout(is_user_origin=is_user_origin)+ self.assertEqual(result, timedelta(seconds=expected_seconds))++ @override_settings(TEST=True, TASKS_INACTIVITY_TIMEOUT_SECONDS=0)+ def test_test_default_is_short_regardless_of_origin(self):+ for is_user_origin in (True, False):+ result = resolve_inactivity_timeout(is_user_origin=is_user_origin)+ self.assertEqual(result, timedelta(seconds=INACTIVITY_TIMEOUT_TEST_SECONDS))++ @override_settings(TEST=False, TASKS_INACTIVITY_TIMEOUT_SECONDS=42)+ def test_per_task_override_wins_over_env_override(self):+ result = resolve_inactivity_timeout(is_user_origin=True, state={"inactivity_timeout_seconds": 999})+ self.assertEqual(result, timedelta(seconds=999))++ @override_settings(TEST=False, TASKS_INACTIVITY_TIMEOUT_SECONDS=42)+ def test_env_override_applies_when_state_has_no_per_task_override(self):+ result = resolve_inactivity_timeout(is_user_origin=True, state={})+ self.assertEqual(result, timedelta(seconds=42))++ @override_settings(TEST=True, TASKS_INACTIVITY_TIMEOUT_SECONDS=0)+ def test_per_task_override_wins_over_test_default(self):+ result = resolve_inactivity_timeout(is_user_origin=False, state={"inactivity_timeout_seconds": 1234})+ self.assertEqual(result, timedelta(seconds=1234))++ @override_settings(TEST=False, TASKS_INACTIVITY_TIMEOUT_SECONDS=0)+ def test_per_task_override_is_clamped_to_max(self):+ result = resolve_inactivity_timeout(+ is_user_origin=True, state={"inactivity_timeout_seconds": MAX_INACTIVITY_TIMEOUT_SECONDS * 10}+ )+ self.assertEqual(result, timedelta(seconds=MAX_INACTIVITY_TIMEOUT_SECONDS))++ @parameterized.expand(+ [+ ("bool_true", True),+ ("zero", 0),+ ("negative", -5),+ ("non_numeric", "nope"),+ ("missing", None),+ ]+ )+ @override_settings(TEST=False, TASKS_INACTIVITY_TIMEOUT_SECONDS=0)+ def test_invalid_per_task_override_falls_back_to_origin_default(self, _name, value):+ state = {"inactivity_timeout_seconds": value} if value is not None else {}+ result = resolve_inactivity_timeout(is_user_origin=True, state=state)+ self.assertEqual(result, timedelta(seconds=INACTIVITY_TIMEOUT_USER_SECONDS))diff --git a/products/tasks/backend/temporal/process_task/tests/test_sandbox_resource_overrides.py b/products/tasks/backend/temporal/process_task/tests/test_sandbox_resource_overrides.pynew file mode 100644index 000000000000..75d0319013ae--- /dev/null+++ b/products/tasks/backend/temporal/process_task/tests/test_sandbox_resource_overrides.py@@ -0,0 +1,49 @@+import pytest++from products.tasks.backend.services.sandbox_config import (+ MAX_SANDBOX_CPU_CORES,+ MAX_SANDBOX_MEMORY_GB,+ MAX_SANDBOX_TTL_SECONDS,+)+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext+++def _context(state: dict | None) -> TaskProcessingContext:+ return TaskProcessingContext(+ task_id="task-id",+ run_id="run-id",+ team_id=1,+ team_uuid="team-uuid",+ organization_id="org-id",+ github_integration_id=123,+ repository="explore-science/paper-wizard-frontend",+ distinct_id="distinct",+ state=state,+ )+++class TestSandboxResourceOverrides:+ def test_no_state_returns_empty(self):+ assert _context(None).sandbox_resource_overrides() == {}++ def test_valid_values_pass_through(self):+ # ttl stays under MAX_SANDBOX_TTL_SECONDS (== the default TTL, 15min under test).+ overrides = _context(+ {"sandbox_cpu_cores": 2, "sandbox_memory_gb": 8, "sandbox_ttl_seconds": 600}+ ).sandbox_resource_overrides()+ assert overrides == {"cpu_cores": 2.0, "memory_gb": 8.0, "ttl_seconds": 600}++ def test_values_are_clamped_to_max(self):+ overrides = _context(+ {"sandbox_cpu_cores": 999, "sandbox_memory_gb": 9999, "sandbox_ttl_seconds": MAX_SANDBOX_TTL_SECONDS * 10}+ ).sandbox_resource_overrides()+ assert overrides == {+ "cpu_cores": float(MAX_SANDBOX_CPU_CORES),+ "memory_gb": float(MAX_SANDBOX_MEMORY_GB),+ "ttl_seconds": MAX_SANDBOX_TTL_SECONDS,+ }++ @pytest.mark.parametrize("value", [0, -1, True, False, "nope", None])+ def test_invalid_values_are_ignored(self, value):+ state = {"sandbox_cpu_cores": value, "sandbox_memory_gb": value, "sandbox_ttl_seconds": value}+ assert _context(state).sandbox_resource_overrides() == {}diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 9b19dae85cd8..a4fa7f3b820b 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -246,14 +246,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):# CI_FOLLOW_UP_DELAY. The testing-only `TASKS_INACTIVITY_TIMEOUT_SECONDS`# env var bypasses the floor, but only when explicitly set AND short —# so a misconfigured large value still respects the CI floor.+ base_timeout = self.context.inactivity_timeout()ci_follow_up_floor = CI_FOLLOW_UP_DELAY + timedelta(minutes=1)testing_override_active = bool(settings.TASKS_INACTIVITY_TIMEOUT_SECONDS) and (- INACTIVITY_TIMEOUT < ci_follow_up_floor+ base_timeout < ci_follow_up_floor)inactivity_timeout = (- max(INACTIVITY_TIMEOUT, ci_follow_up_floor)+ max(base_timeout, ci_follow_up_floor)if ci_follow_up_scheduled and not testing_override_active- else INACTIVITY_TIMEOUT+ else base_timeout)possible_events: list[asyncio.Task[TaskEvent]] = [asyncio.create_task(self._wait_for_task_external_event()),diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 46128649b029..8a2045fd3ffa 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -3113,11 +3113,16 @@ class TestTaskRunAPI(BaseTaskAPITest):"github_credential_source": "caller_token","pr_authorship_mode": "user","sandbox_id": "sb-real",+ "sandbox_cpu_cores": 2,+ "sandbox_memory_gb": 8,+ "sandbox_ttl_seconds": 1800,+ "inactivity_timeout_seconds": 600,},)- # A caller cannot escalate to the creator's integration, flip authorship, or repoint the- # credential-propagation target at a sandbox they control. Non-protected keys still merge.+ # A caller cannot escalate to the creator's integration, flip authorship, repoint the+ # credential-propagation target at a sandbox they control, or inflate the run's compute /+ # lifetime to provision an oversized, long-lived sandbox. Non-protected keys still merge.response = self.client.patch(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",{@@ -3125,6 +3130,10 @@ class TestTaskRunAPI(BaseTaskAPITest):"github_credential_source": "server_integration","pr_authorship_mode": "bot","sandbox_id": "sb-attacker",+ "sandbox_cpu_cores": 128,+ "sandbox_memory_gb": 512,+ "sandbox_ttl_seconds": 86400,+ "inactivity_timeout_seconds": 86400,"scratch": "ok",}},@@ -3135,6 +3144,10 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["github_credential_source"] == "caller_token"assert run.state["pr_authorship_mode"] == "user"assert run.state["sandbox_id"] == "sb-real"+ assert run.state["sandbox_cpu_cores"] == 2+ assert run.state["sandbox_memory_gb"] == 8+ assert run.state["sandbox_ttl_seconds"] == 1800+ assert run.state["inactivity_timeout_seconds"] == 600assert run.state["scratch"] == "ok" # non-protected keys still merge# Nor can a caller remove a protected key to force a fallback or unguarded path.