: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): preserve startup timing and metric context (#118385)
Alessandro Pogliaghi9eb2aacb843f
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 45ed7a41b9cc..2fcd2d3f23ba 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -41,7 +41,12 @@ from posthog.storage import object_storagefrom posthog.temporal.oauth import PosthogMcpScopesfrom posthog.uuidt import uuid7-from products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINS, GITHUB_PR_URL_PREFIX, PR_LOOP_ENABLED_STATE_KEY+from products.tasks.backend.constants import (+ DEFAULT_TRUSTED_DOMAINS,+ GITHUB_PR_URL_PREFIX,+ PR_LOOP_ENABLED_STATE_KEY,+ is_same_run_resume_state,+)from products.tasks.backend.dev_stack_image_models import (DevStackImageAttempt as DevStackImageAttempt,DevStackImageTarget as DevStackImageTarget,@@ -2931,6 +2936,13 @@ class TaskRun(models.Model):)return props+ @property+ def startup_requested_at(self) -> str | None:+ if is_same_run_resume_state(self.state):+ return self.queued_at.isoformat() if self.queued_at else None+ value = (self.state or {}).get("startup_requested_at")+ return value if isinstance(value, str) else None+def analytics_properties(self) -> dict:"""Run context shared by run events and GitHub PR attribution."""return {@@ -2949,7 +2961,7 @@ class TaskRun(models.Model):# client's deployment-region super-property, so ship the run's# local/cloud value under an unclobbered name too."run_environment": self.environment,- "startup_requested_at": (self.state or {}).get("startup_requested_at"),+ "startup_requested_at": self.startup_requested_at,"mode": self.mode,"slack_session_id": self._slack_session_id(),**self._analytics_usage_properties(),diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.pyindex f78c0027fda9..d04dfd69282f 100644--- a/products/tasks/backend/temporal/metrics.py+++ b/products/tasks/backend/temporal/metrics.py@@ -752,21 +752,24 @@ class StepTimer(ContextDecorator):self._span = Nonedelta = dt.timedelta(milliseconds=delta_ms)+ context = posthoganalytics.get_tags()+ used_snapshot = self.used_snapshot if self.used_snapshot is not None else context.get("used_snapshot")attributes: Attributes = {"step": self.step,- "used_snapshot": _bool_label(self.used_snapshot),+ "used_snapshot": _bool_label(used_snapshot if isinstance(used_snapshot, bool) else None),"status": "FAILED" if exc_value is not None else "COMPLETED",}if self.status_tag is not None and exc_value is None:- attributes["status"] = str(posthoganalytics.get_tags().get(self.status_tag, "FAILED"))- if self.boot_path is not None:- attributes["boot_path"] = self.boot_path- if self.origin_product is not None:- attributes["origin_product"] = self.origin_product- if self.runtime is not None:- attributes["runtime"] = self.runtime- if self.sandbox_backend is not None:- attributes["sandbox_backend"] = self.sandbox_backend+ attributes["status"] = str(context.get(self.status_tag, "FAILED"))+ for key, explicit in (+ ("boot_path", self.boot_path),+ ("origin_product", self.origin_product),+ ("runtime", self.runtime),+ ("sandbox_backend", self.sandbox_backend),+ ):+ value = explicit if explicit is not None else context.get(key)+ if isinstance(value, str):+ attributes[key] = valuetry:_metric_meter(attributes).create_histogram_timedelta(diff --git a/products/tasks/backend/temporal/observability.py b/products/tasks/backend/temporal/observability.pyindex 2b5ce30dc40c..328938acfff7 100644--- a/products/tasks/backend/temporal/observability.py+++ b/products/tasks/backend/temporal/observability.py@@ -128,6 +128,10 @@ def log_activity_execution("run_source","runtime_adapter","provider",+ "runtime",+ "sandbox_backend",+ "boot_path",+ "used_snapshot",):if key in context:posthoganalytics.tag("run_environment" if key == "environment" else key, context[key])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 fbc6d0534e79..ab4d20838edb 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@@ -77,7 +77,7 @@ from products.tasks.backend.logic.services.sandbox_config import (from products.tasks.backend.logic.services.store_skills import resolve_store_skillsfrom products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.temporal.constants import resolve_inactivity_timeout, resolve_max_run_duration-from products.tasks.backend.temporal.metrics import StepTimer+from products.tasks.backend.temporal.metrics import StepTimer, sandbox_runtime_labelfrom products.tasks.backend.temporal.oauth import is_interactive_signals_runfrom products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_contextfrom products.tasks.backend.temporal.process_task.utils import (@@ -114,6 +114,7 @@ class TaskProcessingContext:repository: str | Nonedistinct_id: strorigin_product: str | None = None+ startup_requested_at: str | None = Nonetask_runtime: str = Task.Runtime.ACPenvironment: str | None = Nonegithub_user_integration_id: str | None = None@@ -372,6 +373,8 @@ class TaskProcessingContext:"team_id": self.team_id,"repository": self.repository,"origin_product": self.origin_product,+ "runtime": sandbox_runtime_label(self.use_modal_vm_sandbox),+ "sandbox_backend": self.sandbox_backend,"environment": self.environment,"distinct_id": self.distinct_id,"mode": self.mode,@@ -1705,6 +1708,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProreturn TaskProcessingContext(task_id=str(task.id),run_id=run_id,+ startup_requested_at=task_run.startup_requested_at,team_id=task.team_id,team_uuid=str(task.team.uuid),organization_id=str(task.team.organization_id),diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 5371538a5be3..4b045dfd107f 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -789,7 +789,13 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:ctx = input.contextwith (- log_activity_execution("start_agent_server", sandbox_id=input.sandbox_id, **ctx.to_log_context()),+ log_activity_execution(+ "start_agent_server",+ sandbox_id=input.sandbox_id,+ boot_path=input.boot_path,+ used_snapshot=input.used_snapshot,+ **ctx.to_log_context(),+ ),launch_preparation_metric_context(boot_path=input.boot_path,runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),@@ -920,7 +926,13 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:ctx = input.contextwith (- log_activity_execution("launch_agent_server", sandbox_id=input.sandbox_id, **ctx.to_log_context()),+ log_activity_execution(+ "launch_agent_server",+ sandbox_id=input.sandbox_id,+ boot_path=input.boot_path,+ used_snapshot=input.used_snapshot,+ **ctx.to_log_context(),+ ),launch_preparation_metric_context(boot_path=input.boot_path,runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),@@ -994,7 +1006,13 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOuctx = input.contextwith (- log_activity_execution("await_agent_server_ready", sandbox_id=input.sandbox_id, **ctx.to_log_context()),+ log_activity_execution(+ "await_agent_server_ready",+ sandbox_id=input.sandbox_id,+ boot_path=input.boot_path,+ used_snapshot=input.used_snapshot,+ **ctx.to_log_context(),+ ),launch_preparation_metric_context(boot_path=input.boot_path,runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),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 93901a9911fa..5168e3ed4b72 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@@ -265,8 +265,11 @@ class TestGetTaskProcessingContextActivity:task.soft_delete()@pytest.mark.django_db(transaction=True)- @pytest.mark.parametrize("subscription,is_trial", [(False, False), (True, False), (False, True)])- def test_get_task_processing_context_success(self, activity_environment, test_task, subscription, is_trial):+ @pytest.mark.parametrize(+ "subscription,is_trial,resume",+ [(False, False, False), (True, False, False), (False, True, False), (False, False, True)],+ )+ def test_get_task_processing_context_success(self, activity_environment, test_task, subscription, is_trial, resume):owner = User.objects.create_user(email="[email protected]", password=None, first_name="Owner", distinct_id="subscription-owner")@@ -277,6 +280,8 @@ class TestGetTaskProcessingContextActivity:test_task.origin_key = "scout-trial:11111111-1111-1111-1111-111111111111"test_task.save(update_fields=["origin_product", "origin_key"])task_run = test_task.create_run(acting_user_id=owner.id, extra_state=extra_state)+ if resume:+ task_run.prepare_for_cloud_resume()input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))with (@@ -301,6 +306,9 @@ class TestGetTaskProcessingContextActivity:assert isinstance(result, TaskProcessingContext)assert result.task_id == str(test_task.id)assert result.run_id == str(task_run.id)+ assert result.startup_requested_at == (+ task_run.queued_at.isoformat() if resume else task_run.state["startup_requested_at"]+ )assert result.team_id == test_task.team_idassert result.github_integration_id == test_task.github_integration_idassert result.repository == "posthog/posthog-js"diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.pyindex e9b94495ba87..e3ddcae00896 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py@@ -604,6 +604,7 @@ def test_clone_failure_records_failed_latency_and_captures_command_result(mocker"used_snapshot": "false","status": "FAILED","runtime": "gvisor",+ "sandbox_backend": "modal",}]assert str(capture_exception.call_args.args[0]) == "clone output"diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 9c4452ebc26b..a4d82c92b7fd 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -1519,9 +1519,13 @@ async def test_boot_milestone_contains_only_timing_and_runtime_dimensions(@pytest.mark.parametrize("timing_enabled", [False, True])[email protected]("same_run_resume", [False, True])+ ("same_run_resume", "requested_at"),+ [(False, None), (True, None), (True, "2026-01-01T00:00:00.500000+00:00")],+)[email protected]("continued", [False, True])async def test_shared_startup_boundaries_are_present_only_for_new_workflows(- monkeypatch, timing_enabled, same_run_resume+ monkeypatch, timing_enabled, same_run_resume, requested_at, continued):instance = ProcessTaskWorkflow()instance._context = _build_context(github_integration_id=123)@@ -1529,18 +1533,26 @@ async def test_shared_startup_boundaries_are_present_only_for_new_workflows("startup_requested_at": "2026-01-01T00:00:00+00:00","same_run_resume": same_run_resume,}+ instance._context.startup_requested_at = requested_atinstance._startup_worker_started_at = datetime(2026, 1, 1, 0, 0, 2, tzinfo=UTC) if timing_enabled else Noneinstance._startup_context_loaded_at = datetime(2026, 1, 1, 0, 0, 3, tzinfo=UTC) if timing_enabled else Nonenow = datetime(2026, 1, 1, 0, 0, 10, tzinfo=UTC)- instance._chain_started_at = now+ instance._chain_started_at = datetime(2026, 1, 1, 0, 0, 1, tzinfo=UTC)instance._agent_ready_at = now+ if continued:+ resumed = instance._build_resumed_input(ProcessTaskInput(run_id="run-id"), sandbox_id="sb-1")+ restored = ProcessTaskWorkflow()+ restored._context = instance._context+ assert resumed.resumed_sandbox is not None+ restored._restore_resumed_state(resumed.resumed_sandbox)+ instance = restoredtrack = AsyncMock()monkeypatch.setattr(instance, "_track_boot_milestone", track)monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=now))monkeypatch.setattr(process_task_workflow_module.workflow,"info",- Mock(return_value=SimpleNamespace(start_time=datetime(2026, 1, 1, 0, 0, 1, tzinfo=UTC))),+ Mock(return_value=SimpleNamespace(start_time=now if continued else instance._chain_started_at)),)monkeypatch.setattr(process_task_workflow_module, "record_agent_boot_milestone_ms", Mock())@@ -1549,17 +1561,17 @@ async def test_shared_startup_boundaries_are_present_only_for_new_workflows(properties = track.call_args.args[1]if timing_enabled:- assert properties["startup_requested_at"] == "2026-01-01T00:00:00+00:00"+ assert properties["startup_requested_at"] == (requested_at if same_run_resume else "2026-01-01T00:00:00+00:00")assert properties["workflow_accepted_at"] == "2026-01-01T00:00:01+00:00"assert properties["worker_started_at"] == "2026-01-01T00:00:02+00:00"assert properties["context_loaded_at"] == "2026-01-01T00:00:03+00:00"assert properties["observed_at"] == now.isoformat()- if same_run_resume:+ if same_run_resume and requested_at is None:assert "since_startup_requested_ms" not in propertiesassert "handoff_ms" not in propertieselse:- assert properties["since_startup_requested_ms"] == 10000- assert properties["handoff_ms"] == 1000+ assert properties["since_startup_requested_ms"] == (9500 if same_run_resume else 10000)+ assert properties["handoff_ms"] == (500 if same_run_resume else 1000)assert properties["worker_wait_ms"] == 1000assert properties["task_setup_ms"] == 1000else:diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 3c1835939c5b..77c390f84dd9 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -229,6 +229,8 @@ class ResumedSandboxState:image_source: str | None = Noneagent_ready_at: str | None = Noneagent_boot_interaction_telemetry_enabled: bool | None = None+ startup_worker_started_at: str | None = None+ startup_context_loaded_at: str | None = Nonesandbox_backend: str | None = None@@ -2090,6 +2092,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):image_source=self._image_source,agent_ready_at=self._agent_ready_at.isoformat() if self._agent_ready_at else None,agent_boot_interaction_telemetry_enabled=self._agent_boot_interaction_telemetry_enabled,+ startup_worker_started_at=(+ self._startup_worker_started_at.isoformat() if self._startup_worker_started_at else None+ ),+ startup_context_loaded_at=(+ self._startup_context_loaded_at.isoformat() if self._startup_context_loaded_at else None+ ),sandbox_backend=self.context.sandbox_backend,),)@@ -2135,6 +2143,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._image_source = resumed.image_sourceself._agent_ready_at = datetime.fromisoformat(resumed.agent_ready_at) if resumed.agent_ready_at else Noneself._agent_boot_interaction_telemetry_enabled = resumed.agent_boot_interaction_telemetry_enabled is True+ self._startup_worker_started_at = (+ datetime.fromisoformat(resumed.startup_worker_started_at) if resumed.startup_worker_started_at else None+ )+ self._startup_context_loaded_at = (+ datetime.fromisoformat(resumed.startup_context_loaded_at) if resumed.startup_context_loaded_at else None+ )async def _get_task_processing_context(self, input: ProcessTaskInput) -> TaskProcessingContext:context = await workflow.execute_activity(@@ -2808,32 +2822,33 @@ class ProcessTaskWorkflow(PostHogWorkflow):"prewarmed": self._prewarmed,}if self._startup_worker_started_at is not None:+ accepted_at = self._chain_start_time()+ requested_at = self.context.startup_requested_at+ if requested_at is None and not is_same_run_resume_state(self.context.state or {}):+ requested_at = (self.context.state or {}).get("startup_requested_at")properties.update({"observed_at": now.isoformat(),- "workflow_accepted_at": workflow.info().start_time.isoformat(),+ "workflow_accepted_at": accepted_at.isoformat(),"worker_started_at": self._startup_worker_started_at.isoformat(),"context_loaded_at": self._startup_context_loaded_at.isoformat()if self._startup_context_loaded_atelse None,- "startup_requested_at": (self.context.state or {}).get("startup_requested_at"),+ "startup_requested_at": requested_at,"run_environment": self.context.environment,"agent_ready_at": self._agent_ready_at.isoformat() if self._agent_ready_at else None,})- requested_at = properties["startup_requested_at"]- if isinstance(requested_at, str) and not is_same_run_resume_state(self.context.state or {}):+ if isinstance(requested_at, str):try:requested = datetime.fromisoformat(requested_at)if requested.tzinfo is not None and requested <= now:properties["since_startup_requested_ms"] = int((now - requested).total_seconds() * 1000)- properties["handoff_ms"] = max(- 0, int((workflow.info().start_time - requested).total_seconds() * 1000)- )+ properties["handoff_ms"] = max(0, int((accepted_at - requested).total_seconds() * 1000))except ValueError:passproperties["worker_wait_ms"] = max(- 0, int((self._startup_worker_started_at - workflow.info().start_time).total_seconds() * 1000)+ 0, int((self._startup_worker_started_at - accepted_at).total_seconds() * 1000))if self._startup_context_loaded_at is not None:properties["task_setup_ms"] = max(diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 89d794baf34a..054dcbc0e8fb 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -1271,6 +1271,7 @@ class TestTaskRun(TestCase):@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")def test_prepare_for_cloud_resume_clears_stale_sandbox_routing(self, _publish):+ requested_at = django_timezone.now() - timedelta(days=1)run = TaskRun.objects.create(task=self.task,team=self.team,@@ -1285,10 +1286,16 @@ class TestTaskRun(TestCase):"pending_user_message": "Review the attachment","pending_user_artifact_ids": ["artifact-1"],"failure_error_type": "poll_timeout",+ "startup_requested_at": requested_at.isoformat(),},)run.prepare_for_cloud_resume()+ run.refresh_from_db()++ self.assertEqual(run.state["startup_requested_at"], requested_at.isoformat())+ assert run.queued_at is not None+ self.assertEqual(run.analytics_properties()["startup_requested_at"], run.queued_at.isoformat())self.assertNotIn("failure_error_type", run.state)self.assertNotIn("sandbox_id", run.state)diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.pyindex 758a13481df6..eb12a9b8b2f8 100644--- a/products/tasks/backend/tests/test_task_run_metrics.py+++ b/products/tasks/backend/tests/test_task_run_metrics.py@@ -109,14 +109,31 @@ class TestStartupStepMetrics:assert all(call.kwargs["send_feature_flags"] is False for call in capture.call_args_list)@pytest.mark.parametrize("capture_fails", [False, True])- def test_step_events_use_scoped_run_context_without_affecting_work(self, capture_fails: bool) -> None:- with patch("products.tasks.backend.temporal.metrics.posthoganalytics.capture") as capture:+ @pytest.mark.parametrize("override", [False, True])+ def test_step_events_use_scoped_run_context_without_affecting_work(+ self, capture_fails: bool, override: bool+ ) -> None:+ with (+ patch("products.tasks.backend.temporal.metrics.posthoganalytics.capture") as capture,+ patch("products.tasks.backend.temporal.metrics._metric_meter") as metric_meter,+ ):capture.side_effect = RuntimeError("queue unavailable") if capture_fails else Nonefor run_id, origin in [("first-run", "slack"), ("second-run", "review_hog")]:with (posthoganalytics.new_context(fresh=True, capture_exceptions=False),- log_activity_execution("startup", run_id=run_id, origin_product=origin, environment="cloud"),- StepTimer("setup"),+ log_activity_execution(+ "startup",+ run_id=run_id,+ origin_product=origin,+ environment="cloud",+ runtime="vm",+ sandbox_backend="modal",+ boot_path="overlap",+ used_snapshot=True,+ ),+ StepTimer(+ "setup", runtime="gvisor" if override else None, used_snapshot=False if override else None+ ),):passwith StepTimer("unrelated"):@@ -129,6 +146,20 @@ class TestStartupStepMetrics:("second-run", "review_hog"),]assert all(event["run_environment"] == "cloud" for event in properties)+ for event, sample in zip(properties, metric_meter.call_args_list[:2]):+ for key, expected in {+ "origin_product": event["origin_product"],+ "runtime": "gvisor" if override else "vm",+ "sandbox_backend": "modal",+ "boot_path": "overlap",+ "used_snapshot": "false" if override else "true",+ }.items():+ assert event[key] == sample.args[0][key] == expected+ assert metric_meter.call_args.args[0] == {+ "step": "unrelated",+ "used_snapshot": "unknown",+ "status": "COMPLETED",+ }class TestTaskRunMetrics(TestCase):