: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): record agent version before server launch (#107730)
Alessandro Pogliaghi3d57f3d18a6f
diff --git a/docs/internal/task-run-api.md b/docs/internal/task-run-api.mdindex 69fe2cfbf30c..04ec05e67da7 100644--- a/docs/internal/task-run-api.md+++ b/docs/internal/task-run-api.md@@ -48,6 +48,8 @@ Cloud runs send live events through event ingest. Clients can replay only eventsPresence-gated runs do not mirror events while no reader is attached.Reload the run's session logs to recover agent output.Refetch the run for its current state because run-state and progress frames are not in those logs.+When available, sandbox provisioning records the installed agent package version in run state for terminal analytics events.+Failures before sandbox creation have no agent version.When event ingest is enabled, the agent server does not also retain events for a disconnected SSE client.An attached SSE client still receives live events.Runs without event ingest buffer events until an SSE client attaches.diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 090c920f7843..d60bf730e2f2 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -1,3 +1,4 @@+import jsonimport shleximport asyncioimport logging@@ -832,6 +833,27 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P)+def _persist_sandbox_agent_version(run_id: str, sandbox: SandboxBase) -> None:+ version: str | None = None+ try:+ result = sandbox.execute("cat /scripts/node_modules/@posthog/agent/package.json", timeout_seconds=10)+ if result.exit_code == 0:+ manifest = json.loads(result.stdout)+ candidate = manifest.get("version") if isinstance(manifest, dict) else None+ if isinstance(candidate, str) and candidate:+ version = candidate+ except Exception:+ logger.warning("Failed to read sandbox agent version", extra={"run_id": run_id}, exc_info=True)++ try:+ if version is None:+ TaskRun.update_state_atomic(run_id, remove_keys=["agent_version"])+ else:+ TaskRun.update_state_atomic(run_id, updates={"agent_version": version})+ except Exception:+ logger.warning("Failed to persist sandbox agent version", extra={"run_id": run_id}, exc_info=True)++@asyncifydef _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> CreateSandboxForRepositoryOutput:ctx = input.context@@ -954,6 +976,7 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr"sandbox_creation_with_policy_request", runtime, "modal_requested", "failure")raise+ _persist_sandbox_agent_version(ctx.run_id, sandbox)try:if config.outbound_domain_allowlist is not None:emit_agent_log(ctx.run_id, "debug", "Modal sandbox created with network policy requested")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 7a2d107347d6..3b3e6878c5cf 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@@ -659,6 +659,7 @@ def test_a_failure_after_create_destroys_the_fresh_sandbox(mocker, failing_step:sandbox.config.snapshot_restored = Falsesandbox.launch_dev_stack_bootstrap.return_value = Falsesandbox.start_cpu_billing_sampler.return_value = True+ sandbox.execute.return_value = ExecutionResult(stdout='{"version": "1.2.3"}', stderr="", exit_code=0)getattr(sandbox, failing_step).side_effect = SandboxRateLimitedError("Sandbox control plane is rate limited", {"sandbox_id": "sandbox-id", "operation": "create_connect_token"})@@ -687,9 +688,64 @@ def test_a_failure_after_create_destroys_the_fresh_sandbox(mocker, failing_step:)sandbox.destroy.assert_called_once_with()+ task_run.update_state_atomic.assert_called_once_with("run-id", updates={"agent_version": "1.2.3"})task_run.clear_sandbox_connection_state_atomic.assert_called_once_with("run-id", "sandbox-id")+ ("manifest_result", "version"),+ [+ (ExecutionResult(stdout='{"version": "1.2.3"}', stderr="", exit_code=0), "1.2.3"),+ (ExecutionResult(stdout="{}", stderr="", exit_code=0), None),+ (ExecutionResult(stdout="not json", stderr="", exit_code=0), None),+ (ExecutionResult(stdout="", stderr="not found", exit_code=1), None),+ (RuntimeError("manifest read failed"), None),+ ],+)+def test_create_sandbox_records_installed_agent_version(+ mocker, manifest_result: ExecutionResult | Exception, version: str | None+) -> None:+ context = _context_for_desktop_bootstrap()+ context.state = {"await_user_message": True}+ sandbox = mocker.Mock(id="sandbox-id")+ sandbox.config.image_fallback = None+ sandbox.config.snapshot_restored = False+ sandbox.config.ttl_seconds = 60+ sandbox.start_cpu_billing_sampler.return_value = True+ sandbox.launch_dev_stack_bootstrap.return_value = False+ if isinstance(manifest_result, Exception):+ sandbox.execute.side_effect = manifest_result+ else:+ sandbox.execute.return_value = manifest_result+ mocker.patch.object(+ provision_sandbox_module,+ "get_sandbox_class_for_run_backend",+ return_value=mocker.Mock(create=mocker.Mock(return_value=sandbox)),+ )+ for name in (+ "emit_agent_log",+ "_emit_image_source_log",+ "_apply_modal_network_policy",+ "record_sandbox_created",+ "increment_snapshot_usage",+ "increment_snapshot_restore",+ "persist_sandbox_connection",+ ):+ mocker.patch.object(provision_sandbox_module, name)+ mocker.patch.object(provision_sandbox_module, "_build_sandbox_tags", return_value={})+ update_state = mocker.patch.object(provision_sandbox_module.TaskRun, "update_state_atomic")++ result = async_to_sync(provision_sandbox_module._create_sandbox_for_repository)(+ CreateSandboxForRepositoryInput(context=context, prepared=_prepared_for_create())+ )++ assert result.sandbox_id == "sandbox-id"+ if version:+ update_state.assert_called_once_with("run-id", updates={"agent_version": version})+ else:+ update_state.assert_called_once_with("run-id", remove_keys=["agent_version"])++def test_create_reads_the_sandbox_template_from_the_run_context(mocker):# The prepare output carries no template on purpose: a prepare activity claimed by an# older worker during a rolling deploy returns the old shape.