: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): launch the agent shadow observer (#89114)
Alessandro Pogliaghi2d31e6e9461d
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 3ce3a5f41a88..36fc250856ed 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@@ -180,15 +180,15 @@ def _launch_agent_shadow(ctx: TaskProcessingContext, sandbox: SandboxBase) -> boreturn Falseif sandbox.config.snapshot_restored and sandbox.config.snapshot_kind != SNAPSHOT_KIND_DIRECTORY:return False- process = f"[a]gent-shadow --boot-id {ctx.run_id}"+ quoted_run_id = shlex.quote(ctx.run_id)command = (- f"if pgrep -f -- {shlex.quote(process)} >/dev/null; then "- f"printf %s {shlex.quote(ctx.run_id)} > /tmp/agent-shadow-launched; "- f"elif test -x /usr/local/bin/agent-shadow; then nohup /usr/bin/env -i /usr/local/bin/agent-shadow "- f"--boot-id {shlex.quote(ctx.run_id)} --health-url {shlex.quote(sandbox.agent_server_health_url())} "+ f'if test "$(cat /tmp/agent-shadow-launched 2>/dev/null)" = {quoted_run_id}; then exit 0; fi; '+ "test -x /usr/local/bin/agent-shadow || exit 1; "+ "/usr/bin/env -i /usr/bin/setsid /usr/local/bin/agent-shadow "+ f"--boot-id {quoted_run_id} --health-url {shlex.quote(sandbox.agent_server_health_url())} ""--timeout 6m ""> /tmp/agent-shadow.json 2> /tmp/agent-shadow.log < /dev/null & "- f"printf %s {shlex.quote(ctx.run_id)} > /tmp/agent-shadow-launched; else exit 1; fi"+ f"printf %s {quoted_run_id} > /tmp/agent-shadow-launched")try:result = sandbox.execute(command, timeout_seconds=10)@@ -216,8 +216,9 @@ def _read_agent_shadow_result(sandbox: SandboxBase, run_id: str) -> dict[str, stf'if test "$marker" = {quoted_run_id}; then 'f'i=0; while pgrep -f -- {shlex.quote(process)} >/dev/null && test "$i" -lt 20; do '"sleep 0.1; i=$((i + 1)); done; "- f"if pgrep -f -- {shlex.quote(process)} >/dev/null; then printf 'timed_out\\n'; fi; "- "tail -c 65536 /tmp/agent-shadow.json 2>/dev/null || true; fi",+ f"if pgrep -f -- {shlex.quote(process)} >/dev/null; then printf 'timed_out\\n'; "+ "elif test -s /tmp/agent-shadow.json; then tail -c 65536 /tmp/agent-shadow.json; "+ "else printf 'no_output\\n'; tail -c 2048 /tmp/agent-shadow.log 2>/dev/null || true; fi; fi",timeout_seconds=5,)except Exception:@@ -233,6 +234,15 @@ def _read_agent_shadow_result(sandbox: SandboxBase, run_id: str) -> dict[str, stobservation["timed_out"] = Trueif len(lines) == 2:return observation+ elif lines[1] == "no_output":+ observation["failure_class"] = "no_output"+ logger.warning(+ "agent_shadow_no_output",+ run_id=run_id,+ sandbox_id=sandbox.id,+ stderr_tail="\n".join(lines[2:])[:2048],+ )+ return observationtry:payload = json.loads(lines[-1])except (TypeError, json.JSONDecodeError):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 2f60db1ad054..7f206b90595f 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@@ -479,13 +479,42 @@ def test_agent_shadow_launches_without_credentials(mocker) -> None:assert _launch_agent_shadow(_context(), sandbox) is Truecommand = sandbox.execute.call_args.args[0]assert "/usr/local/bin/agent-shadow" in command- assert "[a]gent-shadow --boot-id run-id" in command- assert "/usr/bin/env -i /usr/local/bin/agent-shadow" in command+ assert "/usr/bin/env -i /usr/bin/setsid /usr/local/bin/agent-shadow" in commandassert "--boot-id run-id" in commandassert "--timeout 6m" in commandassert "POSTHOG" not in command+def test_agent_shadow_launch_guards_on_marker_not_its_own_command_line(mocker) -> None:+ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",+ return_value=True,+ )+ sandbox = mocker.Mock(id="sandbox-id")+ sandbox.config.snapshot_restored = False+ sandbox.agent_server_health_url.return_value = "http://127.0.0.1:8080/health"+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)++ assert _launch_agent_shadow(_context(), sandbox) is True+ command = sandbox.execute.call_args.args[0]+ assert "pgrep" not in command+ assert "/tmp/agent-shadow-launched" in command++[email protected]("exit_code,launched", [(0, True), (1, False)])+def test_agent_shadow_launch_fails_closed_on_nonzero_exit(mocker, exit_code, launched) -> None:+ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",+ return_value=True,+ )+ sandbox = mocker.Mock(id="sandbox-id")+ sandbox.config.snapshot_restored = False+ sandbox.agent_server_health_url.return_value = "http://127.0.0.1:8080/health"+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=exit_code)++ assert _launch_agent_shadow(_context(), sandbox) is launched++def test_agent_shadow_skips_filesystem_snapshot(mocker) -> None:mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",@@ -533,15 +562,22 @@ def test_agent_shadow_result_rejects_another_boot(mocker) -> None:assert _read_agent_shadow_result(sandbox, "run-id") == {"launched": True}-def test_agent_shadow_result_reports_read_timeout(mocker) -> None:+ "stdout,expected",+ [+ ("run-id\ntimed_out\n", {"launched": True, "timed_out": True}),+ ("run-id\nno_output\n", {"launched": True, "failure_class": "no_output"}),+ (+ "run-id\nno_output\n/usr/local/bin/agent-shadow: Exec format error\n",+ {"launched": True, "failure_class": "no_output"},+ ),+ ],+)+def test_agent_shadow_result_reports_sentinel_outcomes(mocker, stdout, expected) -> None:sandbox = mocker.Mock(id="sandbox-id")- sandbox.execute.return_value = ExecutionResult(- stdout="run-id\ntimed_out\n",- stderr="",- exit_code=0,- )+ sandbox.execute.return_value = ExecutionResult(stdout=stdout, stderr="", exit_code=0)- assert _read_agent_shadow_result(sandbox, "run-id") == {"launched": True, "timed_out": True}+ assert _read_agent_shadow_result(sandbox, "run-id") == expected@pytest.mark.parametrize("payload", ["null", "true", "1", "[]", '"value"'])