: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(aio): reclaim PostHog AI sandboxes after 10 minutes idle (#82701)
Georgiy Tarasovf943c9f1dd86
diff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.pyindex 02aebe6738b4..89d9333fcda1 100644--- a/products/tasks/backend/temporal/constants.py+++ b/products/tasks/backend/temporal/constants.py@@ -39,8 +39,23 @@ LOOP_RUN_IDLE_TIMEOUT_SECONDS = 2 * 60 # 2 minutes# cap is never mistaken for a zombie.LOOP_RUN_STALE_SECONDS = MAX_INACTIVITY_TIMEOUT_SECONDS + 30 * 60 # 2.5 hours--def resolve_inactivity_timeout(*, is_user_origin: bool = False, state: dict | None = None) -> timedelta:+# PostHog AI runs are chat-shaped: a human sends a message, reads the reply, and either+# follows up within a couple of minutes or walks away. Holding the sandbox for the full+# background window bills idle compute for the walk-away case, and a follow-up that lands+# after the window is cheap now that a fresh sandbox rebuilds the prior session from the+# run log (`@posthog/agent` hydrates it and resumes natively) rather than replaying a+# summary of the conversation.+POSTHOG_AI_IDLE_TIMEOUT_SECONDS = 10 * 60 # 10 minutes++# `Task.OriginProduct.POSTHOG_AI.value`, inlined: this module is imported at module scope by+# the Temporal workflow definitions, which must not pull in Django models. Kept honest by+# `test_posthog_ai_origin_constant_matches_model_enum`.+POSTHOG_AI_ORIGIN_PRODUCT = "posthog_ai"+++def resolve_inactivity_timeout(+ *, is_user_origin: bool = False, origin_product: str | None = None, 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`),@@ -49,7 +64,11 @@ def resolve_inactivity_timeout(*, is_user_origin: bool = False, state: dict | No2. 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).+ 4. The origin-aware production default (longer for user-driven runs, shorter for+ PostHog AI's chat-shaped ones).++ `origin_product` narrows step 4 only. It stays a plain string so callers can pass+ `task.origin_product` straight through without this module importing Django models."""per_task = (state or {}).get("inactivity_timeout_seconds")if isinstance(per_task, int | float) and not isinstance(per_task, bool) and per_task > 0:@@ -58,6 +77,8 @@ def resolve_inactivity_timeout(*, is_user_origin: bool = False, state: dict | Noreturn timedelta(seconds=settings.TASKS_INACTIVITY_TIMEOUT_SECONDS)if settings.TEST:return timedelta(seconds=INACTIVITY_TIMEOUT_TEST_SECONDS)+ if origin_product == POSTHOG_AI_ORIGIN_PRODUCT:+ return timedelta(seconds=POSTHOG_AI_IDLE_TIMEOUT_SECONDS)return timedelta(seconds=INACTIVITY_TIMEOUT_USER_SECONDS if is_user_origin else INACTIVITY_TIMEOUT_DEFAULT_SECONDS)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 9513a4b40674..c9873e134278 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@@ -209,7 +209,9 @@ class TaskProcessingContext:def inactivity_timeout(self) -> timedelta:"""Idle time before the workflow times the run out; longer for user-driven runs."""- return resolve_inactivity_timeout(is_user_origin=self._is_user_origin(), state=self.state)+ return resolve_inactivity_timeout(+ is_user_origin=self._is_user_origin(), origin_product=self.origin_product, state=self.state+ )def _is_user_origin(self) -> bool:return not self.origin_product or self.origin_product in (diff --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 204667786a04..f6a37b03cfd0 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@@ -124,7 +124,7 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_streorigin_product = task_run.task.origin_productis_user_origin = not origin_product or origin_product == TaskModel.OriginProduct.USER_CREATED.valueinactivity_timeout_seconds = resolve_inactivity_timeout(- is_user_origin=is_user_origin, state=task_run.state+ is_user_origin=is_user_origin, origin_product=origin_product, state=task_run.state).total_seconds()stream_key = get_task_run_stream_key(input.run_id)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.pyindex 62e41c5268f1..aed90dc813b4 100644--- a/products/tasks/backend/temporal/process_task/tests/test_inactivity_timeout.py+++ b/products/tasks/backend/temporal/process_task/tests/test_inactivity_timeout.py@@ -4,31 +4,56 @@ from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized+from products.tasks.backend.models import Taskfrom products.tasks.backend.temporal.constants import (INACTIVITY_TIMEOUT_DEFAULT_SECONDS,INACTIVITY_TIMEOUT_TEST_SECONDS,INACTIVITY_TIMEOUT_USER_SECONDS,MAX_INACTIVITY_TIMEOUT_SECONDS,+ POSTHOG_AI_IDLE_TIMEOUT_SECONDS,+ POSTHOG_AI_ORIGIN_PRODUCT,resolve_inactivity_timeout,)+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextclass TestResolveInactivityTimeout(SimpleTestCase):@parameterized.expand([- ("user_origin", True, INACTIVITY_TIMEOUT_USER_SECONDS),- ("non_user_origin", False, INACTIVITY_TIMEOUT_DEFAULT_SECONDS),+ ("user_origin", True, None, INACTIVITY_TIMEOUT_USER_SECONDS),+ ("non_user_origin", False, "signals_scout", INACTIVITY_TIMEOUT_DEFAULT_SECONDS),+ ("posthog_ai", False, POSTHOG_AI_ORIGIN_PRODUCT, POSTHOG_AI_IDLE_TIMEOUT_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)+ def test_production_default_depends_on_origin(self, _name, is_user_origin, origin_product, expected_seconds):+ result = resolve_inactivity_timeout(is_user_origin=is_user_origin, origin_product=origin_product)self.assertEqual(result, timedelta(seconds=expected_seconds))+ def test_posthog_ai_origin_constant_matches_model_enum(self):+ self.assertEqual(POSTHOG_AI_ORIGIN_PRODUCT, Task.OriginProduct.POSTHOG_AI.value)++ @override_settings(TEST=False, TASKS_INACTIVITY_TIMEOUT_SECONDS=0)+ def test_context_forwards_its_origin_to_the_resolver(self):+ # Guards the wiring, not the resolver: dropping `origin_product=` at this call site+ # would leave every resolver case green while PostHog AI silently fell back to 30 minutes.+ context = 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",+ origin_product=POSTHOG_AI_ORIGIN_PRODUCT,+ )+ self.assertEqual(context.inactivity_timeout(), timedelta(seconds=POSTHOG_AI_IDLE_TIMEOUT_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)+ for is_user_origin, origin_product in ((True, None), (False, None), (False, POSTHOG_AI_ORIGIN_PRODUCT)):+ result = resolve_inactivity_timeout(is_user_origin=is_user_origin, origin_product=origin_product)self.assertEqual(result, timedelta(seconds=INACTIVITY_TIMEOUT_TEST_SECONDS))@override_settings(TEST=False, TASKS_INACTIVITY_TIMEOUT_SECONDS=42)