: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): add gradual VM rollout observability (#78913)
Alessandro Pogliaghi06cc300c712c
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 00eca0154512..2ece4b7b2735 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -1,4 +1,5 @@import json+import hashlibfrom typing import Literal, get_argsimport posthoganalytics@@ -50,6 +51,35 @@ def vm_sandbox_default_base_origin_products(payload: object) -> set[str]:return set()+def vm_sandbox_origin_rollout_percentages(payload: object) -> dict[str, float]:+ payload = _decode_vm_sandbox_payload(payload)+ value = payload.get("origin_product_rollout_percentages") if isinstance(payload, dict) else None+ if not isinstance(value, dict):+ return {}++ return {+ origin: float(percentage)+ for origin, percentage in value.items()+ if isinstance(origin, str)+ and isinstance(percentage, int | float)+ and not isinstance(percentage, bool)+ and 0 <= percentage <= 100+ }+++def vm_sandbox_origin_in_rollout(origin_product: str | None, run_id: str, percentages: dict[str, float]) -> bool:+ origin_key = origin_product or ""+ percentage = percentages.get(origin_key, 0)+ if percentage <= 0:+ return False+ if percentage >= 100:+ return True++ digest = hashlib.sha256(f"{origin_key}:{run_id}".encode()).digest()+ bucket = int.from_bytes(digest[:8], "big") / 2**64 * 100+ return bucket < percentage++# Published Modal image name of the prebaked PostHog dev-stack VM image. Unlike# spec-built custom images, this one is a sandbox *filesystem snapshot* publish# (see logic/services/dev_stack_image.py), which Modal cannot layer build steps on.diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.pyindex c7ac1a6b8778..d59aa1c23376 100644--- a/products/tasks/backend/temporal/metrics.py+++ b/products/tasks/backend/temporal/metrics.py@@ -20,9 +20,14 @@ TASKS_LATENCY_HISTOGRAM_BUCKETS = [1_000.0,5_000.0,10_000.0,+ 15_000.0,+ 20_000.0,30_000.0,+ 45_000.0,60_000.0,+ 90_000.0,120_000.0,+ 180_000.0,300_000.0,600_000.0,1_800_000.0,@@ -74,6 +79,10 @@ def _bool_label(value: bool | None) -> str:_ALLOWED_RUNTIME_ADAPTERS = {"claude", "codex"}+def sandbox_runtime_label(use_vm_sandbox: bool) -> str:+ return "vm" if use_vm_sandbox else "gvisor"++def _runtime_adapter_label(value: str | None) -> str:"""Bounded label: unexpected values collapse to "other" to cap cardinality."""if not value:@@ -223,7 +232,13 @@ def record_sandbox_created(runtime: str, image_kind: str, image_fallback: bool,pass-def record_agent_server_session_init_ms(session_init_ms: int, boot_path: str | None = None) -> None:+def record_agent_server_session_init_ms(+ session_init_ms: int,+ boot_path: str | None = None,+ *,+ origin_product: str | None = None,+ runtime: str | None = None,+) -> None:try:attributes: Attributes = {"step": "agent_server_session_init",@@ -231,6 +246,10 @@ def record_agent_server_session_init_ms(session_init_ms: int, boot_path: str | N}if boot_path is not None:attributes["boot_path"] = boot_path+ if origin_product is not None:+ attributes["origin_product"] = origin_product+ if runtime is not None:+ attributes["runtime"] = runtime_metric_meter(attributes).create_histogram_timedelta("tasks_process_sandbox_step_latency","Latency for get_sandbox_for_repository sub-steps",@@ -247,6 +266,7 @@ def record_boot_total_ms(used_snapshot: bool | None,has_repo: bool,origin_product: str | None,+ runtime: str,) -> None:"""Wall-clock time from workflow start to agent-server ready, the boot headline number.@@ -260,6 +280,7 @@ def record_boot_total_ms("used_snapshot": _bool_label(used_snapshot),"has_repo": _bool_label(has_repo),"origin_product": origin_product or "unknown",+ "runtime": runtime,}_metric_meter(attributes).create_histogram_timedelta("tasks_boot_total_latency",@@ -271,10 +292,20 @@ def record_boot_total_ms(class StepTimer:- def __init__(self, step: str, used_snapshot: bool | None = None, boot_path: str | None = None) -> None:+ def __init__(+ self,+ step: str,+ used_snapshot: bool | None = None,+ boot_path: str | None = None,+ *,+ origin_product: str | None = None,+ runtime: str | None = None,+ ) -> None:self.step = stepself.used_snapshot = used_snapshotself.boot_path = boot_path+ self.origin_product = origin_product+ self.runtime = runtime# Elapsed wall-clock of the step, readable after the context exits so callers# can thread the same number into activity outputs / analytics events.self.elapsed_ms: int | None = None@@ -302,6 +333,10 @@ class StepTimer:}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.runtimetry:_metric_meter(attributes).create_histogram_timedelta(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 31307f8c9eaa..d398443bbc8b 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@@ -30,7 +30,12 @@ from products.tasks.backend.logic.services.sandbox import ()from products.tasks.backend.logic.services.sandbox_usage import open_sandbox_sessionfrom products.tasks.backend.models import SandboxSnapshot, Task, TaskRun-from products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_restore, increment_snapshot_usage+from products.tasks.backend.temporal.metrics import (+ StepTimer,+ increment_snapshot_restore,+ increment_snapshot_usage,+ sandbox_runtime_label,+)from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_runfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom products.tasks.backend.temporal.process_task.utils import (@@ -140,7 +145,11 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo# Repo-setup snapshots come from default-base sandboxes; restoring one would drop the custom image.if has_repo and github_integration_id is not None and not ctx.custom_image_name:assert repository is not None- with StepTimer("snapshot_lookup") as snapshot_lookup_timer:+ with StepTimer(+ "snapshot_lookup",+ origin_product=ctx.origin_product,+ runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),+ ) as snapshot_lookup_timer:snapshot = SandboxSnapshot.get_latest_snapshot_with_repos(github_integration_id, [repository])used_snapshot = snapshot is not Nonesnapshot_lookup_timer.set_used_snapshot(used_snapshot)@@ -310,7 +319,13 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo"debug",f"Provisioning sandbox from {image_source_label} (image build may take a few minutes on first run)",)- with StepTimer("sandbox_creation", used_snapshot=used_snapshot) as sandbox_creation_timer:+ runtime = sandbox_runtime_label(use_vm_sandbox)+ with StepTimer(+ "sandbox_creation",+ used_snapshot=used_snapshot,+ origin_product=ctx.origin_product,+ runtime=runtime,+ ) as sandbox_creation_timer:sandbox = Sandbox.create(config)# The provider's TTL clock starts here — the usage ledger anchors its# kill deadline on this boundary, not on when the row is opened below.@@ -342,7 +357,12 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo)else:emit_agent_log(ctx.run_id, "debug", f"Cloning {repository} into sandbox")- with StepTimer("repository_clone", used_snapshot=used_snapshot):+ with StepTimer(+ "repository_clone",+ used_snapshot=used_snapshot,+ origin_product=ctx.origin_product,+ runtime=runtime,+ ):clone_result = sandbox.clone_repository(repository, github_token=github_token, shallow=shallow)if clone_result.exit_code != 0:sandbox.destroy()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 300f9138eba9..2f6456967e7a 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@@ -23,6 +23,8 @@ from products.tasks.backend.constants import (vm_sandbox_allowed_origin_products,vm_sandbox_default_base_origin_products,vm_sandbox_default_custom_image,+ vm_sandbox_origin_in_rollout,+ vm_sandbox_origin_rollout_percentages,)from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyErrorfrom products.tasks.backend.facade.api import ensure_task_run_session@@ -468,6 +470,7 @@ def _resolve_modal_vm_sandbox(# org-targeted payload variants decide which default VM image an org gets.allowed_origins: set[str] = set()default_base_origins: set[str] = set()+ origin_rollout_percentages: dict[str, float] = {}default_custom_image: str | None = Noneif state_override is None:try:@@ -477,9 +480,11 @@ def _resolve_modal_vm_sandbox(return VmSandboxDecision(use_vm_sandbox=False)allowed_origins = vm_sandbox_allowed_origin_products(payload)default_base_origins = vm_sandbox_default_base_origin_products(payload)+ origin_rollout_percentages = vm_sandbox_origin_rollout_percentages(payload)default_custom_image = vm_sandbox_default_custom_image(payload)- origin_allows_default_base = origin_product in default_base_origins+ origin_in_percentage_rollout = vm_sandbox_origin_in_rollout(origin_product, run_id, origin_rollout_percentages)+ origin_allows_default_base = origin_product in default_base_origins or origin_in_percentage_rollout# Custom images are VM-only, so VM historically required one. image_builder always# runs on VM (it builds images on that base); origins in the default-base allowlist@@ -508,10 +513,12 @@ def _resolve_modal_vm_sandbox(log_with_activity_context("modal_vm_sandbox_flag_checked",run_id=run_id,- flag_enabled=bool(allowed_origins or default_base_origins),+ flag_enabled=bool(allowed_origins or default_base_origins or origin_rollout_percentages),origin_product=origin_product,allowed_origin_products=sorted(allowed_origins),default_base_origin_products=sorted(default_base_origins),+ origin_product_rollout_percentages=origin_rollout_percentages,+ origin_in_percentage_rollout=origin_in_percentage_rollout,default_custom_image=default_custom_image,custom_image_available=custom_image_available,use_modal_vm_sandbox=result,diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 12bd8747056f..c7c5b5900a7f 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -36,6 +36,7 @@ from products.tasks.backend.temporal.metrics import (increment_snapshot_restore,increment_snapshot_usage,record_sandbox_created,+ sandbox_runtime_label,)from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run, create_wizard_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution@@ -443,7 +444,11 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P# Repo-setup snapshots come from default-base sandboxes; restoring one would silently# drop the custom base image. Resume snapshots were taken from this task's own sandbox.if has_repo and ctx.github_integration_id is not None and not ctx.custom_image_name:- with StepTimer("snapshot_lookup") as snapshot_lookup_timer:+ with StepTimer(+ "snapshot_lookup",+ origin_product=ctx.origin_product,+ runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),+ ) as snapshot_lookup_timer:snapshot = SandboxSnapshot.get_latest_snapshot_with_repos(ctx.github_integration_id, ctx.repositories)used_snapshot = snapshot is not Nonesnapshot_lookup_timer.set_used_snapshot(used_snapshot)@@ -609,7 +614,13 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cref"Using Modal outbound_domain_allowlist ({len(config.outbound_domain_allowlist)} domains) instead of agentsh",)- with StepTimer("sandbox_creation", used_snapshot=prepared.used_snapshot) as sandbox_creation_timer:+ runtime = sandbox_runtime_label(use_vm_sandbox)+ with StepTimer(+ "sandbox_creation",+ used_snapshot=prepared.used_snapshot,+ origin_product=ctx.origin_product,+ runtime=runtime,+ ) as sandbox_creation_timer:sandbox = Sandbox.create(config)# The provider's TTL clock starts here — the usage ledger anchors its# kill deadline on this boundary, not on when the row is opened below.@@ -643,7 +654,7 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Creincrement_snapshot_restore(prepared.snapshot_source, metrics_snapshot_kind, snapshot_outcome)record_sandbox_created(- "vm" if use_vm_sandbox else "gvisor",+ runtime,_sandbox_image_kind(prepared.image_source, config.custom_image_name),sandbox.config.image_fallback is not None,create_ms,@@ -702,7 +713,12 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRestate = ctx.state or {}is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))- with StepTimer("repository_clone", used_snapshot=False) as clone_timer:+ with StepTimer(+ "repository_clone",+ used_snapshot=False,+ origin_product=ctx.origin_product,+ runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),+ ) as clone_timer:clone_result = sandbox.clone_repository(input.repository,github_token=input.github_token,@@ -799,7 +815,12 @@ def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> CheckoutB)raise RuntimeError(f"Failed to check whether branch {input.branch} exists")- with StepTimer("branch_checkout", used_snapshot=input.used_snapshot) as checkout_timer:+ with StepTimer(+ "branch_checkout",+ used_snapshot=input.used_snapshot,+ origin_product=ctx.origin_product,+ runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox),+ ) as checkout_timer:result = sandbox.execute(checkout_command, timeout_seconds=5 * 60)if result.exit_code != 0: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 148f3d61104d..21951cd70c00 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@@ -19,7 +19,12 @@ from products.tasks.backend.exceptions import OAuthTokenError, SandboxExecutionEfrom products.tasks.backend.logic.services.connection_token import create_sandbox_event_ingest_tokenfrom products.tasks.backend.logic.services.sandbox import REPO_READY_FILE, Sandbox, SandboxBase, sandbox_repo_pathfrom products.tasks.backend.models import Task, TaskRun-from products.tasks.backend.temporal.metrics import StepTimer, record_agent_server_session_init_ms, record_boot_total_ms+from products.tasks.backend.temporal.metrics import (+ StepTimer,+ record_agent_server_session_init_ms,+ record_boot_total_ms,+ sandbox_runtime_label,+)from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_runfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom products.tasks.backend.temporal.process_task.utils import (@@ -146,6 +151,7 @@ class StartAgentServerInput:# Workflow start time (ISO 8601); when set, the activity that completes boot records# the wall-clock workflow-start → agent-ready total.workflow_start_at: str | None = None+ boot_excluded_ms: int = 0@dataclass@@ -418,7 +424,7 @@ def _record_boot_total(input: StartAgentServerInput) -> int | None:# letting the aware-naive subtraction raise. Metrics must never fail the boot.if started_at.tzinfo is None:started_at = started_at.replace(tzinfo=UTC)- boot_total_ms = max(0, int((datetime.now(UTC) - started_at).total_seconds() * 1000))+ boot_total_ms = max(0, int((datetime.now(UTC) - started_at).total_seconds() * 1000) - input.boot_excluded_ms)except (TypeError, ValueError):logger.warning("boot_total_unparseable_start_time", workflow_start_at=input.workflow_start_at)return None@@ -428,6 +434,7 @@ def _record_boot_total(input: StartAgentServerInput) -> int | None:used_snapshot=input.used_snapshot,has_repo=input.context.repository is not None,origin_product=input.context.origin_product,+ runtime=sandbox_runtime_label(input.context.use_modal_vm_sandbox),)return boot_total_ms@@ -456,7 +463,10 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:_ensure_repository_on_disk(ctx, sandbox)params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)- with StepTimer("agent_server_ready", boot_path=input.boot_path) as ready_timer:+ runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)+ with StepTimer(+ "agent_server_ready", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime+ ) as ready_timer:_invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None, wait_for_health=True)emit_agent_log(ctx.run_id, "debug", f"Agent server started at {input.sandbox_url}")@@ -464,7 +474,9 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:session_init_ms = sandbox.read_agent_server_session_init_ms()if session_init_ms is not None:- record_agent_server_session_init_ms(session_init_ms, boot_path=input.boot_path)+ record_agent_server_session_init_ms(+ session_init_ms, boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime+ )boot_total_ms = _record_boot_total(input)@@ -495,7 +507,10 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)repo_ready_file = REPO_READY_FILE if input.defer_for_clone else None- with StepTimer("agent_server_launch", boot_path=input.boot_path) as launch_timer:+ runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)+ with StepTimer(+ "agent_server_launch", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime+ ) as launch_timer:_invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=repo_ready_file, wait_for_health=False)activity.logger.info(f"Agent server process launched for task {ctx.task_id}")@@ -528,7 +543,10 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOuagentsh_domains = _agentsh_domains_for(ctx)try:- with StepTimer("agent_server_ready", boot_path=input.boot_path) as ready_timer:+ runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)+ with StepTimer(+ "agent_server_ready", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime+ ) as ready_timer:sandbox.wait_for_agent_server_ready(agentsh_domains)except Exception:if agentsh_domains is not None:@@ -541,7 +559,9 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOusession_init_ms = sandbox.read_agent_server_session_init_ms()if session_init_ms is not None:- record_agent_server_session_init_ms(session_init_ms, boot_path=input.boot_path)+ record_agent_server_session_init_ms(+ session_init_ms, boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime+ )boot_total_ms = _record_boot_total(input)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 4c61a8eaf622..bb2099573f18 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@@ -19,6 +19,8 @@ from products.tasks.backend.constants import (vm_sandbox_allowed_origin_products,vm_sandbox_default_base_origin_products,vm_sandbox_default_custom_image,+ vm_sandbox_origin_in_rollout,+ vm_sandbox_origin_rollout_percentages,)from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyErrorfrom products.tasks.backend.models import SandboxEnvironment, Task@@ -932,6 +934,7 @@ class TestGetTaskProcessingContextActivity:("user_created", {"default_base_origin_products": ["user_created"]}, False, True),# the waiver is scoped per origin — an unlisted origin still gets gVisor.("signals_scout", {"default_base_origin_products": ["user_created"]}, False, False),+ ("signals_scout", {"origin_product_rollout_percentages": {"signals_scout": 100}}, False, True),# origin_products membership alone does NOT waive the custom-image requirement.("user_created",@@ -990,6 +993,34 @@ class TestGetTaskProcessingContextActivity:def test_vm_sandbox_default_base_origin_products_parsing(self, payload, expected):assert vm_sandbox_default_base_origin_products(payload) == expected+ @pytest.mark.parametrize(+ "payload,expected",+ [+ ({"origin_product_rollout_percentages": {"signals_scout": 10}}, {"signals_scout": 10.0}),+ ('{"origin_product_rollout_percentages":{"signals_scout":12.5}}', {"signals_scout": 12.5}),+ ({"origin_product_rollout_percentages": {"negative": -1, "large": 101, "bool": True}}, {}),+ ({"origin_product_rollout_percentages": ["signals_scout"]}, {}),+ (None, {}),+ ],+ )+ def test_vm_sandbox_origin_rollout_percentages_parsing(self, payload, expected):+ assert vm_sandbox_origin_rollout_percentages(payload) == expected++ def test_vm_sandbox_origin_percentage_rollout_is_stable_and_distributed(self):+ percentages = {"signals_scout": 10.0}+ decisions = [+ vm_sandbox_origin_in_rollout("signals_scout", f"run-{index}", percentages) for index in range(1000)+ ]++ assert decisions == [+ vm_sandbox_origin_in_rollout("signals_scout", f"run-{index}", percentages) for index in range(1000)+ ]+ assert 70 <= sum(decisions) <= 130+ assert not vm_sandbox_origin_in_rollout("onboarding", "run-1", percentages)+ assert vm_sandbox_origin_in_rollout(None, "run-1", {"": 50}) == vm_sandbox_origin_in_rollout(+ "", "run-1", {"": 50}+ )+@pytest.mark.parametrize("payload, expected",[diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex 4a3d91f9db68..717e9c933649 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -1,4 +1,5 @@import pytest+from freezegun import freeze_timefrom products.tasks.backend.exceptions import SandboxMissingRepositoryErrorfrom products.tasks.backend.logic.services.sandbox import ExecutionResult, sandbox_repo_path@@ -7,11 +8,36 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_serverStartAgentServerInput,_ensure_repository_on_disk,_include_personal_mcp_for_task,+ _record_boot_total,_resolve_protected_base_branch,start_agent_server,)+@freeze_time("2026-08-06T12:01:30Z")+def test_record_boot_total_excludes_wizard_time_and_labels_runtime(mocker) -> None:+ record_metric = mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.record_boot_total_ms"+ )+ input = StartAgentServerInput(+ context=_context(),+ sandbox_id="sandbox-id",+ sandbox_url="https://sandbox.example",+ workflow_start_at="2026-08-06T12:00:00+00:00",+ boot_excluded_ms=60_000,+ )++ assert _record_boot_total(input) == 30_000+ record_metric.assert_called_once_with(+ 30_000,+ boot_path="classic",+ used_snapshot=None,+ has_repo=False,+ origin_product=None,+ runtime="gvisor",+ )++def _context(*,sandbox_event_ingest_enabled: bool = False,diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 4d34c2d290c4..ccdf753116b3 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -244,6 +244,10 @@ _PATCH_ID_FOLLOWUP_QUEUE = "tasks-follow-up-message-queue"# turn, while ordinary follow-ups remain queued behind it._PATCH_ID_CONCURRENT_FOLLOWUP_STEERING = "tasks-concurrent-followup-steering"+# Existing onboarding histories include the setup agent in boot_total_ms, so replay must+# preserve that input while new histories subtract the setup agent's elapsed time.+_PATCH_ID_EXCLUDE_WIZARD_FROM_BOOT_TOTAL = "tasks-exclude-wizard-from-boot-total"+# #60923 dropped the redundant slack post that ran immediately after sandbox# provisioning — between `_get_sandbox_for_repository` and the agent-start# progress emit. Pre-rollout histories scheduled a `post_slack_update` activity@@ -1137,14 +1141,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):# Run the PostHog setup wizard before the agent, when this is a cloud wizard run.# The wizard integrates PostHog and dirties the working tree; the agent then commits# those changes, opens the PR, and keeps it green (it never implements PostHog itself).- await self._run_wizard_if_configured(sandbox_output)+ wizard_ms = await self._run_wizard_if_configured(sandbox_output)# Start agent-server for direct connection from PostHog Desktopif sandbox_output.agent_server_launched:- agent_server_output = await self._await_agent_server_ready(sandbox_output)+ agent_server_output = await self._await_agent_server_ready(sandbox_output, boot_excluded_ms=wizard_ms)else:await self._emit_progress("agent", "in_progress", "Starting agent", "setup")- agent_server_output = await self._start_agent_server(sandbox_output)+ agent_server_output = await self._start_agent_server(sandbox_output, boot_excluded_ms=wizard_ms)await self._emit_progress("agent", "completed", "Started agent", "setup")await self._track_workflow_event(@@ -1467,7 +1471,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):except Exception as e:workflow.logger.warning(f"Failed to read sandbox logs: {e}")- async def _run_wizard_if_configured(self, sandbox_output: GetSandboxForRepositoryOutput) -> None:+ async def _run_wizard_if_configured(self, sandbox_output: GetSandboxForRepositoryOutput) -> int:"""Run the setup wizard in the sandbox before the agent, for cloud wizard runs only.Fails the run on a non-zero wizard exit (maximum_attempts=1, and the wizard is non-idempotent@@ -1476,9 +1480,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):repository = self.context.repository# `is not None` (not truthiness): an empty config dict still means "this is a wizard run".if self.context.wizard_config is None or not repository:- return+ return 0+ exclude_from_boot_total = workflow.patched(_PATCH_ID_EXCLUDE_WIZARD_FROM_BOOT_TOTAL)await self._emit_progress("wizard", "in_progress", "Running PostHog setup wizard", "setup")+ started_at = workflow.now() if exclude_from_boot_total else Noneawait workflow.execute_activity(run_wizard,RunWizardInput(@@ -1491,7 +1497,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):start_to_close_timeout=timedelta(minutes=50),retry_policy=RetryPolicy(maximum_attempts=1),)+ wizard_ms = int((workflow.now() - started_at).total_seconds() * 1000) if started_at is not None else 0await self._emit_progress("wizard", "completed", "Ran PostHog setup wizard", "setup")+ return wizard_ms@staticmethoddef _workflow_start_at_iso() -> str | None:@@ -1501,7 +1509,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):except Exception:return None- async def _start_agent_server(self, sandbox_output: GetSandboxForRepositoryOutput) -> StartAgentServerOutput:+ async def _start_agent_server(+ self, sandbox_output: GetSandboxForRepositoryOutput, *, boot_excluded_ms: int = 0+ ) -> StartAgentServerOutput:return await workflow.execute_activity(start_agent_server,StartAgentServerInput(@@ -1513,6 +1523,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):boot_path=sandbox_output.boot_path,used_snapshot=sandbox_output.used_snapshot,workflow_start_at=self._workflow_start_at_iso(),+ boot_excluded_ms=boot_excluded_ms,),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=3),@@ -1545,7 +1556,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)- async def _await_agent_server_ready(self, sandbox_output: GetSandboxForRepositoryOutput) -> StartAgentServerOutput:+ async def _await_agent_server_ready(+ self, sandbox_output: GetSandboxForRepositoryOutput, *, boot_excluded_ms: int = 0+ ) -> StartAgentServerOutput:return await workflow.execute_activity(await_agent_server_ready,StartAgentServerInput(@@ -1557,6 +1570,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):boot_path=sandbox_output.boot_path,used_snapshot=sandbox_output.used_snapshot,workflow_start_at=self._workflow_start_at_iso(),+ boot_excluded_ms=boot_excluded_ms,),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=3),diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.mdindex b72c94a6d776..3f4e84d91af8 100644--- a/products/tasks/docs/INSTRUMENTATION.md+++ b/products/tasks/docs/INSTRUMENTATION.md@@ -124,14 +124,36 @@ Tracked when the workflow begins execution.Tracked after sandbox and agent server are provisioned.-| Property | Type | Description |-| --------------- | ------ | ------------------------------- |-| `run_id` | `str` | UUID of the run |-| `task_id` | `str` | UUID of the task |-| `sandbox_id` | `str` | Sandbox identifier |-| `sandbox_url` | `str` | URL of the sandbox |-| `used_snapshot` | `bool` | Whether a snapshot was used |-| `repository` | `str` | Repository in `org/repo` format |+| Property | Type | Description |+| ----------------------- | ------ | --------------------------------------------------------- |+| `run_id` | `str` | UUID of the run |+| `task_id` | `str` | UUID of the task |+| `sandbox_id` | `str` | Sandbox identifier |+| `sandbox_url` | `str` | URL of the sandbox |+| `used_snapshot` | `bool` | Whether a snapshot was used |+| `repository` | `str` | Repository in `org/repo` format |+| `boot_path` | `str` | Classic or overlapping clone boot |+| `boot_total_ms` | `int` | Infrastructure boot time, excluding setup agent execution |+| `sandbox_create_ms` | `int` | Sandbox creation time |+| `repo_clone_ms` | `int` | Repository clone time |+| `branch_checkout_ms` | `int` | Branch checkout time |+| `agent_launch_ms` | `int` | Agent server launch time |+| `agent_ready_wait_ms` | `int` | Time spent waiting for the agent server |+| `agent_session_init_ms` | `int` | Agent session initialization time |++### Modal VM rollout payload++The `tasks-modal-vm-sandbox` payload supports gradual rollout by origin product:++```json+{+ "default_base_origin_products": ["user_created"],+ "origin_product_rollout_percentages": { "signals_scout": 10 },+ "default_custom_image": "posthog-dev-stack"+}+```++Each percentage uses a stable hash of the origin product and run ID. The same run keeps its runtime choice across activity retries.### `task_run_cancelled`