From ba244e30cdfab00dd19a4f7ef4356a152790f202 Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 21 Oct 2026 11:10:32 +0300 Subject: [PATCH 1/5] Maintain fork installer and reliable Phoenix transport --- .claude-plugin/marketplace.json | 6 +-- README.md | 23 ++++++-- core/common.py | 41 +++++++++----- install.bat | 6 +-- install.sh | 6 +-- pyproject.toml | 2 +- tests/core/test_otlp_delivery.py | 53 +++++++++++++++++++ tests/core/test_shell_router.py | 2 +- .../claude_code/.claude-plugin/plugin.json | 6 +-- tracing/claude_code/pyproject.toml | 2 +- uv.lock | 2 +- 11 files changed, 116 insertions(+), 33 deletions(-) create mode 100644 tests/core/test_otlp_delivery.py diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 113baa63..d790d14a 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -12,10 +12,10 @@ "name": "claude-code-tracing", "source": "./tracing/claude_code", "description": "Automatic tracing of Claude Code sessions to Arize AX or Phoenix with OpenInference spans", - "version": "1.0.1", + "version": "1.1.0", "homepage": "https://arize.com", - "repository": "https://github.com/Arize-ai/coding-harness-tracing", - "license": "MIT", + "repository": "https://github.com/lifldev/coding-harness-tracing", + "license": "Apache-2.0", "keywords": [ "tracing", "agents", diff --git a/README.md b/README.md index 72f8816f..79b99943 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,20 @@ # Arize Coding Harness Tracing +Maintained fork of [Arize Coding Harness Tracing](https://github.com/Arize-ai/coding-harness-tracing) +for Claude Code and Codex sessions in Phoenix. Upstream attribution and the +Apache-2.0 license are retained. Install and update commands below use this fork. + +Fork maintenance: + +- Keep Claude and Codex response, tool, token and subagent reconstruction covered + by synthetic regression fixtures. Never commit private session transcripts. +- Validate parser changes against saved session records without making model calls. +- Deploy a reviewed commit from a detached worktree and point runtime consumers at + that worktree. Preserve configuration, state, logs and a rollback environment. +- GitHub Actions is disabled on this public fork. Owner-hosted runners must remain + private-only; run tests locally before publishing until an approved CI placement + is configured. Do not enable upstream paid triage automation. + Trace AI coding sessions to [Arize AX](https://arize.com) or [Phoenix](https://github.com/Arize-ai/phoenix) with [OpenInference](https://github.com/Arize-ai/openinference) spans. Each harness integration emits spans for prompts, tool calls, model responses, and session lifecycle events. Claude Code tracing reconstructs each turn as a `CHAIN` containing per-response `LLM` spans, correlated `TOOL` spans, and a foreground subagent `AGENT` subtree when available. See [Claude Code trace structure and current limitations](tracing/claude_code/README.md#trace-structure) for details. @@ -11,7 +26,7 @@ You need Python 3.9+ and the harness you want to trace. The commands below are t ### Claude Code ```bash -curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.sh | bash -s -- claude +curl -sSL https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.sh | bash -s -- claude ``` The installer registers hooks in `~/.claude/settings.json`. Start a session with `claude`, or `claude -p "hello"`. Spans for that session show up in the project you chose. @@ -28,10 +43,10 @@ That path skips the wizard, so set backend credentials in `~/.claude/settings.js ### Codex ```bash -curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.sh | bash -s -- codex +curl -sSL https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.sh | bash -s -- codex ``` -The installer registers hooks in `~/.codex/config.toml`. Codex will not run them until you trust them once: start `codex`, run `/hooks`, and approve each `arize-hook-codex-*` entry. Then run a session, for example: +The installer registers a completion `notify` command in `~/.codex/config.toml`. At the end of each turn, it reconstructs the trace from the local Codex rollout. Then run a session, for example: ```bash codex exec "explain what this file does" path/to/file.py @@ -40,7 +55,7 @@ codex exec "explain what this file does" path/to/file.py ### Cursor ```bash -curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.sh | bash -s -- cursor +curl -sSL https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.sh | bash -s -- cursor ``` The installer registers hooks in `~/.cursor/hooks.json`, which applies to the Cursor IDE and the Cursor CLI for your user. Use either as usual; agent activity produces spans in the project you chose. diff --git a/core/common.py b/core/common.py index 906257b3..6a4ac948 100644 --- a/core/common.py +++ b/core/common.py @@ -644,21 +644,36 @@ def _inject_openinference_project_resource_attr(span_dict: dict, project_name: s def _post_otlp(url: str, body: bytes, headers: dict, label: str) -> bool: - """POST an encoded OTLP payload, logging failures. Returns True on 2xx.""" + """POST one payload with bounded retries for transient transport failures.""" req = urllib.request.Request(url, data=body, headers=headers, method="POST") - try: - with urllib.request.urlopen(req, timeout=10) as resp: - return 200 <= resp.status < 300 - except urllib.error.HTTPError as e: + if not req.has_header("User-agent"): + req.add_header("User-Agent", "LiFl-Coding-Harness-Tracing/1.0") + for attempt in range(3): try: - detail = e.read().decode("utf-8", errors="replace") - except Exception: - detail = "" - error(f"{label} send failed: HTTP {e.code}: {detail or e.reason}") - return False - except Exception as e: - error(f"{label} send failed: {e}") - return False + with urllib.request.urlopen(req, timeout=10) as resp: + return 200 <= resp.status < 300 + except urllib.error.HTTPError as e: + try: + detail = e.read(8192).decode("utf-8", errors="replace") + except Exception: + detail = "" + finally: + e.close() + message = f"HTTP {e.code}: {detail or e.reason}" + retryable = e.code in (429, 502, 503, 504) + except (urllib.error.URLError, TimeoutError, ConnectionError) as e: + message = str(e) + retryable = True + except Exception as e: + message = str(e) + retryable = False + if not retryable or attempt == 2: + error(f"{label} send failed: {message}") + return False + # Reuse the encoded payload and IDs if the collector accepted a request + # whose acknowledgement was lost, so it can deduplicate the retry. + time.sleep(0.25 * (2**attempt)) + return False def _extract_span_name(span_dict: dict) -> str: diff --git a/install.bat b/install.bat index e2a125d0..5a2b1f81 100644 --- a/install.bat +++ b/install.bat @@ -8,10 +8,10 @@ REM install.bat uninstall [harness] REM install.bat update REM --- Constants --- -set "REPO_URL=https://github.com/Arize-ai/coding-harness-tracing.git" +set "REPO_URL=https://github.com/lifldev/coding-harness-tracing.git" if not defined ARIZE_INSTALL_BRANCH set "ARIZE_INSTALL_BRANCH=main" set "INSTALL_BRANCH=%ARIZE_INSTALL_BRANCH%" -set "TARBALL_URL=https://github.com/Arize-ai/coding-harness-tracing/archive/refs/heads/%INSTALL_BRANCH%.tar.gz" +set "TARBALL_URL=https://github.com/lifldev/coding-harness-tracing/archive/refs/heads/%INSTALL_BRANCH%.tar.gz" set "INSTALL_DIR=%USERPROFILE%\.arize\harness" set "VENV_DIR=%INSTALL_DIR%\venv" set "VENV_PYTHON=%VENV_DIR%\Scripts\python.exe" @@ -41,7 +41,7 @@ if /i "%~1"=="--wheel-dir" ( if not exist "%~2\coding_harness_tracing-*.whl" ( echo [arize] No coding_harness_tracing-*.whl in %~2 >&2 & exit /b 1 ) shift & shift & goto :parse_args ) -if /i "%~1"=="--branch" ( set "INSTALL_BRANCH=%~2" & set "TARBALL_URL=https://github.com/Arize-ai/coding-harness-tracing/archive/refs/heads/%~2.tar.gz" & shift & shift & goto :parse_args ) +if /i "%~1"=="--branch" ( set "INSTALL_BRANCH=%~2" & set "TARBALL_URL=https://github.com/lifldev/coding-harness-tracing/archive/refs/heads/%~2.tar.gz" & shift & shift & goto :parse_args ) for %%C in (claude codex copilot cursor gemini kiro antigravity opencode omp devin) do if /i "%~1"=="%%C" ( set "COMMAND=%%C" & shift & goto :parse_args ) if /i "%~1"=="update" ( set "COMMAND=update" & shift & goto :parse_args ) diff --git a/install.sh b/install.sh index 195a9903..126455c3 100755 --- a/install.sh +++ b/install.sh @@ -11,9 +11,9 @@ set -euo pipefail -REPO_URL="https://github.com/Arize-ai/coding-harness-tracing.git" +REPO_URL="https://github.com/lifldev/coding-harness-tracing.git" INSTALL_BRANCH="${ARIZE_INSTALL_BRANCH:-main}" -TARBALL_URL="https://github.com/Arize-ai/coding-harness-tracing/archive/refs/heads/${INSTALL_BRANCH}.tar.gz" +TARBALL_URL="https://github.com/lifldev/coding-harness-tracing/archive/refs/heads/${INSTALL_BRANCH}.tar.gz" INSTALL_DIR="${HOME}/.arize/harness" VENV_DIR="${INSTALL_DIR}/venv" # When set, install from local wheels in this directory instead of fetching the @@ -343,7 +343,7 @@ main() { --branch) i=$((i + 1)) INSTALL_BRANCH="${args[$i]:-main}" - TARBALL_URL="https://github.com/Arize-ai/coding-harness-tracing/archive/refs/heads/${INSTALL_BRANCH}.tar.gz" + TARBALL_URL="https://github.com/lifldev/coding-harness-tracing/archive/refs/heads/${INSTALL_BRANCH}.tar.gz" ;; --wheel-dir) i=$((i + 1)) diff --git a/pyproject.toml b/pyproject.toml index da12ca64..d1a5336c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "coding-harness-tracing" -version = "0.1.0" +version = "0.1.1+lifl.1" requires-python = ">=3.9" # python-dotenv parses the credential file for non-interactive installs. It is # the only runtime dependency; keep it that way. Imported by core/setup alone, diff --git a/tests/core/test_otlp_delivery.py b/tests/core/test_otlp_delivery.py new file mode 100644 index 00000000..2f982545 --- /dev/null +++ b/tests/core/test_otlp_delivery.py @@ -0,0 +1,53 @@ +import io +import urllib.error +from unittest import mock + +import pytest + +from core.common import _post_otlp + + +def _response(): + response = mock.MagicMock() + response.status = 200 + response.__enter__.return_value = response + return response + + +def test_sender_identifies_itself_without_mutating_caller_headers(): + headers = {"Content-Type": "application/x-protobuf"} + with mock.patch("core.common.urllib.request.urlopen", return_value=_response()) as send: + assert _post_otlp("https://collector.example/v1/traces", b"payload", headers, "Phoenix") + assert send.call_args.args[0].get_header("User-agent") == "LiFl-Coding-Harness-Tracing/1.0" + assert headers == {"Content-Type": "application/x-protobuf"} + + +@pytest.mark.parametrize("status", [429, 502, 503, 504]) +def test_transient_rejection_retries_the_same_payload(status): + rejection = urllib.error.HTTPError("https://collector.example", status, "Retry", {}, io.BytesIO(b"busy")) + with mock.patch("core.common.urllib.request.urlopen", side_effect=[rejection, _response()]) as send: + with mock.patch("core.common.time.sleep") as sleep: + assert _post_otlp("https://collector.example/v1/traces", b"payload", {}, "Phoenix") + assert send.call_count == 2 + assert all(call.args[0].data == b"payload" for call in send.call_args_list) + sleep.assert_called_once() + + +def test_auth_rejection_is_not_retried(capsys): + rejection = urllib.error.HTTPError( + "https://collector.example", 403, "Forbidden", {}, io.BytesIO(b"error code: 1010") + ) + with mock.patch("core.common.urllib.request.urlopen", side_effect=rejection) as send: + with mock.patch("core.common.time.sleep") as sleep: + assert not _post_otlp("https://collector.example/v1/traces", b"payload", {}, "Phoenix") + send.assert_called_once() + sleep.assert_not_called() + assert "1010" in capsys.readouterr().err + + +def test_connection_failure_has_bounded_retries(): + with mock.patch("core.common.urllib.request.urlopen", side_effect=urllib.error.URLError("offline")) as send: + with mock.patch("core.common.time.sleep") as sleep: + assert not _post_otlp("https://collector.example/v1/traces", b"payload", {}, "Phoenix") + assert send.call_count == 3 + assert sleep.call_count == 2 diff --git a/tests/core/test_shell_router.py b/tests/core/test_shell_router.py index 8eeb6849..4a879136 100644 --- a/tests/core/test_shell_router.py +++ b/tests/core/test_shell_router.py @@ -421,7 +421,7 @@ def _load(self): self.text = _read_install_sh() def test_repo_url(self): - assert "https://github.com/Arize-ai/coding-harness-tracing.git" in self.text + assert "https://github.com/lifldev/coding-harness-tracing.git" in self.text def test_install_dir(self): assert "${HOME}/.arize/harness" in self.text diff --git a/tracing/claude_code/.claude-plugin/plugin.json b/tracing/claude_code/.claude-plugin/plugin.json index e997ea4c..17bd69a4 100644 --- a/tracing/claude_code/.claude-plugin/plugin.json +++ b/tracing/claude_code/.claude-plugin/plugin.json @@ -1,14 +1,14 @@ { "name": "claude-code-tracing", "description": "Automatic tracing of Claude Code sessions to Arize AX or Phoenix with OpenInference spans.", - "version": "1.0.3", + "version": "1.1.0", "author": { "name": "Arize AI", "email": "support@arize.com", "url": "https://arize.com" }, - "repository": "https://github.com/Arize-ai/coding-harness-tracing", - "license": "MIT", + "repository": "https://github.com/lifldev/coding-harness-tracing", + "license": "Apache-2.0", "keywords": [ "tracing", "agents", diff --git a/tracing/claude_code/pyproject.toml b/tracing/claude_code/pyproject.toml index 67690453..ed33e6d8 100644 --- a/tracing/claude_code/pyproject.toml +++ b/tracing/claude_code/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "claude-code-tracing" -version = "1.0.3" +version = "1.1.0" requires-python = ">=3.9" dependencies = [] diff --git a/uv.lock b/uv.lock index b7d14d00..f93a03ae 100644 --- a/uv.lock +++ b/uv.lock @@ -155,7 +155,7 @@ wheels = [ [[package]] name = "coding-harness-tracing" -version = "0.1.0" +version = "0.1.1+lifl.1" source = { editable = "." } dependencies = [ { name = "python-dotenv", version = "1.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, From 59595a37e77f5dd01dc9285e714d38e8b73fd3f6 Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 21 Oct 2026 11:11:09 +0300 Subject: [PATCH 2/5] Point marketplace installation at maintained fork --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 79b99943..9ea621b3 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ The installer registers hooks in `~/.claude/settings.json`. Start a session with To install from the Claude marketplace instead: ```bash -claude plugin marketplace add Arize-ai/coding-harness-tracing +claude plugin marketplace add lifldev/coding-harness-tracing claude plugin install claude-code-tracing@coding-harness-tracing ``` @@ -63,7 +63,7 @@ The installer registers hooks in `~/.cursor/hooks.json`, which applies to the Cu Cursor 2.5+ can install from the marketplace instead. In a Cursor agent chat, run: ```text -/add-plugin Arize-ai/coding-harness-tracing +/add-plugin lifldev/coding-harness-tracing ``` The plugin skips the wizard. Run the bundled `manage-cursor-tracing` skill once to write credentials. See [Cursor plugin install](tracing/cursor/README.md#plugin-install). From 07ba4668619e50c3a5f3e1e27e1d189e74eab605 Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 21 Oct 2026 11:13:17 +0300 Subject: [PATCH 3/5] Describe supported Codex and Claude trace trees --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9ea621b3..386fbd96 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,9 @@ Fork maintenance: Trace AI coding sessions to [Arize AX](https://arize.com) or [Phoenix](https://github.com/Arize-ai/phoenix) with [OpenInference](https://github.com/Arize-ai/openinference) spans. Each harness integration emits spans for prompts, tool calls, model responses, and session lifecycle events. -Claude Code tracing reconstructs each turn as a `CHAIN` containing per-response `LLM` spans, correlated `TOOL` spans, and a foreground subagent `AGENT` subtree when available. See [Claude Code trace structure and current limitations](tracing/claude_code/README.md#trace-structure) for details. +Claude Code tracing reconstructs each turn as a `CHAIN` with per-response `LLM` spans, correlated `TOOL` spans, and nested foreground or background `AGENT` subtrees when their transcripts are available. See [Claude Code trace structure and limitations](tracing/claude_code/README.md#trace-structure). + +Codex tracing reconstructs saved rollout records as a `CHAIN` with per-response `LLM` spans and `TOOL` spans. Code Mode `exec` containers include structured command executions when Codex persists them; model usage is counted once per response. See [Codex trace structure and limitations](tracing/codex/README.md). ## Quick Start From d31fbf069a79ab15ab6824e30471fea0ae45dda6 Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 21 Oct 2026 11:13:06 +0300 Subject: [PATCH 4/5] fix(claude): preserve nested and background trace fidelity Integrate upstream PR170 at 51fbe03c714b73fe98708386e9c0bce645f1c41f, retaining replay filtering and async launch correlation. Resolve nested agents through explicit tool IDs and transcript metadata, serialize completions, reuse retry span identities, preserve interrupted outcomes, and label inferred timing. Add synthetic lifecycle regressions and document observability limits. --- .../claude/fixtures/async_subagent_main.jsonl | 4 + tests/tracing/claude/test_claude_fixtures.py | 1 + .../claude/test_claude_high_fidelity.py | 134 ++++++ tests/tracing/claude/test_claude_hook.py | 20 +- .../claude/test_claude_hook_subagent_start.py | 10 +- .../claude/test_claude_subagent_lifecycle.py | 287 ++++++++++++ .../tracing/claude/test_claude_transcript.py | 87 ++++ .../claude/test_claude_transcript_encoding.py | 2 +- tracing/claude_code/README.md | 21 +- tracing/claude_code/hooks/handlers.py | 432 +++++++++++++++--- tracing/claude_code/hooks/span_renderer.py | 23 +- tracing/claude_code/hooks/transcript.py | 58 ++- .../manage-claude-code-tracing/SKILL.md | 2 +- 13 files changed, 1008 insertions(+), 73 deletions(-) create mode 100644 tests/tracing/claude/fixtures/async_subagent_main.jsonl create mode 100644 tests/tracing/claude/test_claude_subagent_lifecycle.py diff --git a/tests/tracing/claude/fixtures/async_subagent_main.jsonl b/tests/tracing/claude/fixtures/async_subagent_main.jsonl new file mode 100644 index 00000000..b28a1e3e --- /dev/null +++ b/tests/tracing/claude/fixtures/async_subagent_main.jsonl @@ -0,0 +1,4 @@ +{"parentUuid":null,"isSidechain":false,"promptId":"prompt-async-1","type":"user","message":{"role":"user","content":"Delegate one read-only subagent in the background to inspect hello.py."},"uuid":"user-async-main-1","timestamp":"2026-01-01T13:00:00.000Z","cwd":"/synthetic/project","sessionId":"session-async-1","version":"2.1.301"} +{"parentUuid":"user-async-main-1","isSidechain":false,"message":{"id":"message-async-main-1","type":"message","role":"assistant","model":"qwen3-coder-next","content":[{"type":"tool_use","id":"tool-async-1","name":"Agent","input":{"description":"Inspect hello.py","prompt":"Read hello.py and report the function and returned string.","subagent_type":"synthetic-explorer","run_in_background":true}}],"usage":{"input_tokens":200,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":30},"stop_reason":"tool_use"},"type":"assistant","uuid":"assistant-async-main-1","timestamp":"2026-01-01T13:00:01.000Z","cwd":"/synthetic/project","sessionId":"session-async-1","version":"2.1.301"} +{"parentUuid":"assistant-async-main-1","isSidechain":false,"promptId":"prompt-async-1","type":"user","message":{"role":"user","content":[{"tool_use_id":"tool-async-1","type":"tool_result","content":[{"type":"text","text":"Async agent launched successfully.\nagentId: agent-1"}]}]},"uuid":"result-async-main-1","timestamp":"2026-01-01T13:00:01.500Z","toolUseResult":{"isAsync":true,"status":"async_launched","agentId":"agent-1","description":"Inspect hello.py","resolvedModel":"qwen3-coder-next","prompt":"Read hello.py and report the function and returned string."},"sourceToolAssistantUUID":"assistant-async-main-1","cwd":"/synthetic/project","sessionId":"session-async-1","version":"2.1.301"} +{"parentUuid":"result-async-main-1","isSidechain":false,"message":{"id":"message-async-main-2","type":"message","role":"assistant","model":"qwen3-coder-next","content":[{"type":"text","text":"LAUNCHED_IN_BACKGROUND"}],"usage":{"input_tokens":220,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":5},"stop_reason":"end_turn"},"type":"assistant","uuid":"assistant-async-main-2","timestamp":"2026-01-01T13:00:02.000Z","cwd":"/synthetic/project","sessionId":"session-async-1","version":"2.1.301"} diff --git a/tests/tracing/claude/test_claude_fixtures.py b/tests/tracing/claude/test_claude_fixtures.py index 944319ab..a836ad4f 100644 --- a/tests/tracing/claude/test_claude_fixtures.py +++ b/tests/tracing/claude/test_claude_fixtures.py @@ -20,6 +20,7 @@ def test_fixture_set_is_present(): assert {path.name for path in FIXTURES} == { + "async_subagent_main.jsonl", "main_tool_cycle.jsonl", "subagent_agent.jsonl", "subagent_main.jsonl", diff --git a/tests/tracing/claude/test_claude_high_fidelity.py b/tests/tracing/claude/test_claude_high_fidelity.py index 9ba9cf21..a01370d4 100644 --- a/tests/tracing/claude/test_claude_high_fidelity.py +++ b/tests/tracing/claude/test_claude_high_fidelity.py @@ -26,6 +26,7 @@ FIXTURE = Path(__file__).parent / "fixtures" / "main_tool_cycle.jsonl" SUBAGENT_MAIN_FIXTURE = Path(__file__).parent / "fixtures" / "subagent_main.jsonl" SUBAGENT_AGENT_FIXTURE = Path(__file__).parent / "fixtures" / "subagent_agent.jsonl" +ASYNC_MAIN_FIXTURE = Path(__file__).parent / "fixtures" / "async_subagent_main.jsonl" def _spans(payload): @@ -459,6 +460,139 @@ def send_with_retry(payload): assert state.get("subagent_agent-1_start_time") is None +def test_background_subagent_is_exported_under_its_launching_agent_span(tmp_path: Path): + state = StateManager(tmp_path, state_file=tmp_path / "state.json", lock_path=tmp_path / "state.lock") + state.init_state() + for key, value in { + "session_id": "session-async-1", + "current_trace_id": "e" * 32, + "current_trace_span_id": "f" * 16, + "current_trace_start_time": "1767272400000", + "current_trace_prompt": "Delegate one read-only subagent in the background.", + "trace_count": "1", + "trace_start_line": "0", + "project_name": "synthetic-project", + "user_id": "dev@example.com", + }.items(): + state.set(key, value) + + sent = [] + clock = iter(range(1767272401000, 1767272500000, 1000)) + + def send(payload): + sent.append(payload) + return True + + with ( + mock.patch("tracing.claude_code.hooks.handlers.resolve_session", return_value=state), + mock.patch("tracing.claude_code.hooks.handlers.resolve_transcript_path", return_value=ASYNC_MAIN_FIXTURE), + mock.patch("tracing.claude_code.hooks.handlers.get_timestamp_ms", side_effect=lambda: next(clock)), + mock.patch("tracing.claude_code.hooks.handlers.send_span", side_effect=send), + ): + _handle_subagent_start( + { + "session_id": "session-async-1", + "transcript_path": str(ASYNC_MAIN_FIXTURE), + "agent_id": "agent-1", + "agent_type": "synthetic-explorer", + } + ) + # The launching turn ends while the subagent is still running. + _handle_stop( + { + "session_id": "session-async-1", + "transcript_path": str(ASYNC_MAIN_FIXTURE), + "last_assistant_message": "LAUNCHED_IN_BACKGROUND", + } + ) + assert len(sent) == 1 + turn_spans = _spans(sent[0]) + assert [span["name"] for span in turn_spans] == [ + "Turn 1", + "LLM call 1: qwen3-coder-next", + "Agent", + "LLM call 2: qwen3-coder-next", + ] + assert state.get("current_trace_id") is None + assert state.get("async_subagents") is not None + + # It stops later, with no turn open. + _handle_subagent_stop( + { + "session_id": "session-async-1", + "transcript_path": str(ASYNC_MAIN_FIXTURE), + "agent_transcript_path": str(SUBAGENT_AGENT_FIXTURE), + "agent_id": "agent-1", + "agent_type": "synthetic-explorer", + "last_assistant_message": "Function: greeting; return: SYNTHETIC_TOOL_OK", + } + ) + + assert len(sent) == 2 + agent_span = turn_spans[2] + spans = _spans(sent[1]) + assert [span["name"] for span in spans] == [ + "Subagent: synthetic-explorer", + "LLM call 1: qwen3-coder-next", + "Read", + "LLM call 2: qwen3-coder-next", + ] + assert {span["traceId"] for span in spans} == {"e" * 32} + assert spans[0]["parentSpanId"] == agent_span["spanId"] + assert spans[1]["parentSpanId"] == spans[0]["spanId"] + assert spans[2]["parentSpanId"] == spans[1]["spanId"] + assert spans[3]["parentSpanId"] == spans[0]["spanId"] + subagent = _attrs(spans[0]) + assert subagent["openinference.span.kind"] == "AGENT" + assert subagent["subagent.id"] == "agent-1" + assert subagent["user.id"] == "dev@example.com" + # Real duration: from SubagentStart to SubagentStop, not the launch call. + assert int(spans[0]["endTimeUnixNano"]) > int(spans[0]["startTimeUnixNano"]) + assert int(spans[0]["startTimeUnixNano"]) == 1767272401000 * 1_000_000 + assert _attrs(spans[2])["subagent.id"] == "agent-1" + assert state.get("async_subagents") is None + assert state.get("subagent_agent-1_start_time") is None + + +def test_background_subagent_that_stops_inside_its_turn_keeps_the_foreground_path(tmp_path: Path): + state = StateManager(tmp_path, state_file=tmp_path / "state.json", lock_path=tmp_path / "state.lock") + state.init_state() + for key, value in { + "session_id": "session-async-1", + "current_trace_id": "e" * 32, + "current_trace_span_id": "f" * 16, + "current_trace_start_time": "1767272400000", + "trace_count": "1", + "trace_start_line": "0", + }.items(): + state.set(key, value) + + sent = [] + clock = iter(range(1767272401000, 1767272500000, 1000)) + with ( + mock.patch("tracing.claude_code.hooks.handlers.resolve_session", return_value=state), + mock.patch("tracing.claude_code.hooks.handlers.resolve_transcript_path", return_value=ASYNC_MAIN_FIXTURE), + mock.patch("tracing.claude_code.hooks.handlers.get_timestamp_ms", side_effect=lambda: next(clock)), + mock.patch("tracing.claude_code.hooks.handlers.send_span", side_effect=lambda p: sent.append(p) or True), + ): + _handle_subagent_stop( + { + "session_id": "session-async-1", + "transcript_path": str(ASYNC_MAIN_FIXTURE), + "agent_transcript_path": str(SUBAGENT_AGENT_FIXTURE), + "agent_id": "agent-1", + "agent_type": "synthetic-explorer", + } + ) + _handle_stop({"session_id": "session-async-1", "transcript_path": str(ASYNC_MAIN_FIXTURE)}) + + assert len(sent) == 1 + names = [span["name"] for span in _spans(sent[0])] + assert names.index("Subagent: synthetic-explorer") == names.index("Agent") + 1 + assert state.get("async_subagents") is None + assert state.get("pending_subagents") is None + + def test_failed_tool_hook_is_correlated_and_marks_tool_span_error(tmp_path: Path): state = StateManager(tmp_path, state_file=tmp_path / "state.json", lock_path=tmp_path / "state.lock") state.init_state() diff --git a/tests/tracing/claude/test_claude_hook.py b/tests/tracing/claude/test_claude_hook.py index a2ed9bb9..6ea46f5b 100644 --- a/tests/tracing/claude/test_claude_hook.py +++ b/tests/tracing/claude/test_claude_hook.py @@ -993,6 +993,7 @@ def test_uses_file_creation_time(self, mock_resolve, state, captured_spans, tran state.set("current_trace_id", "t" * 32) state.set("current_trace_span_id", "s" * 16) + original_stat = Path.stat real_stat = Path(transcript_file).stat() mock_stat = mock.MagicMock(wraps=real_stat) mock_stat.st_birthtime = 1700000.0 # seconds → 1700000000 ms @@ -1001,7 +1002,14 @@ def test_uses_file_creation_time(self, mock_resolve, state, captured_spans, tran with mock.patch( "tracing.claude_code.hooks.handlers.resolve_transcript_path", return_value=Path(transcript_file) ): - with mock.patch.object(Path, "stat", return_value=mock_stat): + with mock.patch.object( + Path, + "stat", + autospec=True, + side_effect=lambda path, *args, **kwargs: ( + mock_stat if path == Path(transcript_file) else original_stat(path, *args, **kwargs) + ), + ): _handle_subagent_stop( { "agent_type": "explorer", @@ -1018,6 +1026,7 @@ def test_falls_back_to_ctime(self, mock_resolve, state, captured_spans, transcri state.set("current_trace_id", "t" * 32) state.set("current_trace_span_id", "s" * 16) + original_stat = Path.stat real_stat = Path(transcript_file).stat() class FakeStat: @@ -1030,7 +1039,14 @@ class FakeStat: with mock.patch( "tracing.claude_code.hooks.handlers.resolve_transcript_path", return_value=Path(transcript_file) ): - with mock.patch.object(Path, "stat", return_value=FakeStat()): + with mock.patch.object( + Path, + "stat", + autospec=True, + side_effect=lambda path, *args, **kwargs: ( + FakeStat() if path == Path(transcript_file) else original_stat(path, *args, **kwargs) + ), + ): _handle_subagent_stop( { "agent_type": "explorer", diff --git a/tests/tracing/claude/test_claude_hook_subagent_start.py b/tests/tracing/claude/test_claude_hook_subagent_start.py index 0e0723b3..c4891de2 100644 --- a/tests/tracing/claude/test_claude_hook_subagent_start.py +++ b/tests/tracing/claude/test_claude_hook_subagent_start.py @@ -117,6 +117,7 @@ def test_subagent_stop_falls_back_when_state_missing(self, mock_resolve, state, state.set("current_trace_id", "t" * 32) state.set("current_trace_span_id", "s" * 16) + original_stat = Path.stat real_stat = Path(transcript_file).stat() mock_stat = mock.MagicMock(wraps=real_stat) mock_stat.st_birthtime = 1700000.0 @@ -125,7 +126,14 @@ def test_subagent_stop_falls_back_when_state_missing(self, mock_resolve, state, with mock.patch( "tracing.claude_code.hooks.handlers.resolve_transcript_path", return_value=Path(transcript_file) ): - with mock.patch.object(Path, "stat", return_value=mock_stat): + with mock.patch.object( + Path, + "stat", + autospec=True, + side_effect=lambda path, *args, **kwargs: ( + mock_stat if path == Path(transcript_file) else original_stat(path, *args, **kwargs) + ), + ): _handle_subagent_stop( {"agent_type": "explorer", "agent_id": "a2", "agent_transcript_path": transcript_file} ) diff --git a/tests/tracing/claude/test_claude_subagent_lifecycle.py b/tests/tracing/claude/test_claude_subagent_lifecycle.py new file mode 100644 index 00000000..bea2db1d --- /dev/null +++ b/tests/tracing/claude/test_claude_subagent_lifecycle.py @@ -0,0 +1,287 @@ +"""Synthetic regressions for out-of-order and interrupted Claude agent lifecycles.""" + +import json +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager +from threading import Event +from unittest.mock import patch + +import pytest + +from core.common import StateManager +from core.event_model import EventStatus, ModelCallEvent, ToolEvent, TurnEvent +from tracing.claude_code.hooks import handlers +from tracing.claude_code.hooks.span_renderer import render_event_graph +from tracing.claude_code.hooks.transcript import parse_claude_transcript + + +def assistant(key, content, **extra): + return { + "type": "assistant", + "uuid": key, + "timestamp": 2000, + "message": { + "role": "assistant", + "id": key, + "model": "synthetic-model", + "content": content, + "usage": {"input_tokens": 2, "output_tokens": 3}, + **extra, + }, + } + + +def launch(agent, call, *, result=True): + rows = [ + assistant( + f"model-{call}", [{"type": "tool_use", "id": call, "name": "Agent", "input": {"prompt": "synthetic"}}] + ) + ] + if result: + rows.append( + { + "type": "user", + "timestamp": 2100, + "toolUseResult": {"isAsync": True, "status": "async_launched", "agentId": agent}, + "message": { + "role": "user", + "content": [{"type": "tool_result", "tool_use_id": call, "content": "launched"}], + }, + } + ) + return rows + + +def transcript(tmp_path, name, rows, *, parent_call=None): + path = tmp_path / f"{name}.jsonl" + path.write_text("\n".join(json.dumps(row) for row in rows) + "\n") + if parent_call: + path.with_suffix(".meta.json").write_text(json.dumps({"toolUseId": parent_call, "requestShape": "background"})) + return path + + +def spans(payload): + return payload["resourceSpans"][0]["scopeSpans"][0]["spans"] + + +def attrs(span): + return {item["key"]: next(iter(item["value"].values())) for item in span["attributes"]} + + +@contextmanager +def session(tmp_path, main, send=None): + state = StateManager(tmp_path, tmp_path / "state.json", tmp_path / "state.lock") + state.init_state() + for key, value in { + "session_id": "synthetic", + "current_trace_id": "a" * 32, + "current_trace_span_id": "b" * 16, + "current_trace_start_time": "1000", + "trace_count": "1", + "trace_start_line": "0", + }.items(): + state.set(key, value) + sent = [] + + def capture(payload): + sent.append(payload) + return send(payload) if send else True + + with ( + patch.object(handlers, "resolve_session", return_value=state), + patch.object(handlers, "resolve_transcript_path", return_value=main), + patch.object(handlers, "get_timestamp_ms", return_value=3000), + patch.object(handlers, "send_span", side_effect=capture), + ): + yield state, sent + + +def stop_agent(main, agent, path, **extra): + handlers._handle_subagent_stop( + { + "transcript_path": str(main), + "agent_id": agent, + "agent_transcript_path": str(path), + "agent_type": "synthetic", + **extra, + } + ) + + +def test_nested_agents_match_metadata_even_without_launch_results_and_in_reverse_order(tmp_path): + main = transcript(tmp_path, "main", launch("outer", "call-outer", result=False)) + outer = transcript(tmp_path, "agent-outer", launch("inner", "call-inner", result=False), parent_call="call-outer") + inner = transcript( + tmp_path, + "agent-inner", + [assistant("inner-model", [{"type": "text", "text": "done"}])], + parent_call="call-inner", + ) + with session(tmp_path, main) as (state, sent): + stop_agent(main, "inner", inner) + stop_agent(main, "outer", outer) + handlers._handle_stop({"transcript_path": str(main)}) + tree = spans(sent[0]) + tools = {attrs(s).get("tool.call.id"): s for s in tree if attrs(s).get("tool.call.id")} + agents = {attrs(s).get("subagent.id"): s for s in tree if attrs(s).get("openinference.span.kind") == "AGENT"} + assert set(agents) == {"outer", "inner"} + assert agents["outer"]["parentSpanId"] == tools["call-outer"]["spanId"] + assert agents["inner"]["parentSpanId"] == tools["call-inner"]["spanId"] + assert state.get("pending_subagents") is None + + +def test_nested_background_child_can_stop_before_parent_after_launch_turn(tmp_path): + main = transcript(tmp_path, "main", launch("outer", "call-outer")) + outer = transcript(tmp_path, "agent-outer", launch("inner", "call-inner")) + inner = transcript(tmp_path, "agent-inner", [assistant("inner-model", [])]) + with session(tmp_path, main) as (state, sent): + handlers._handle_stop({"transcript_path": str(main)}) + stop_agent(main, "inner", inner) + stop_agent(main, "outer", outer) + assert state.get("pending_subagents") is None + assert state.get("async_subagents") is None + tree = [s for p in sent for s in spans(p)] + tools = {attrs(s).get("tool.call.id"): s for s in tree if attrs(s).get("tool.call.id")} + agents = {attrs(s).get("subagent.id"): s for s in tree if attrs(s).get("openinference.span.kind") == "AGENT"} + assert set(agents) == {"outer", "inner"} + assert agents["inner"]["parentSpanId"] == tools["call-inner"]["spanId"] + assert {s["traceId"] for s in tree} == {"a" * 32} + + +def test_async_retry_reuses_all_span_ids_and_repeated_stop_does_not_attach_to_new_turn(tmp_path): + main = transcript(tmp_path, "main", launch("outer", "call-outer")) + outer = transcript(tmp_path, "agent-outer", [assistant("outer-model", [])]) + attempts = iter([True, False, True]) + with session(tmp_path, main, lambda _: next(attempts)) as (state, sent): + handlers._handle_stop({"transcript_path": str(main)}) + stop_agent(main, "outer", outer) + stop_agent(main, "outer", outer) + state.set("current_trace_id", "c" * 32) + stop_agent(main, "outer", outer) + assert state.get("pending_subagents") is None + assert len(sent) == 3 + assert [s["spanId"] for s in spans(sent[1])] == [s["spanId"] for s in spans(sent[2])] + + +def test_concurrent_duplicate_stops_export_one_turn(tmp_path): + main = transcript(tmp_path, "main", [assistant("main-model", [])]) + entered, release = Event(), Event() + + def send(_): + entered.set() + assert release.wait(3) + return True + + with session(tmp_path, main, send) as (_, sent), ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(handlers._handle_stop, {"transcript_path": str(main)}) + assert entered.wait(3) + second = pool.submit(handlers._handle_stop, {"transcript_path": str(main)}) + release.set() + first.result() + second.result() + assert len(sent) == 1 + + +@pytest.mark.parametrize("outcome", ["cancelled", "failed"]) +def test_subagent_outcome_is_preserved(tmp_path, outcome): + main = transcript(tmp_path, "main", launch("outer", "call-outer")) + outer = transcript( + tmp_path, + "agent-outer", + [assistant("outer-model", [{"type": "tool_use", "id": "pending", "name": "Read", "input": {}}])], + ) + with session(tmp_path, main) as (_, sent): + handlers._handle_stop({"transcript_path": str(main)}) + stop_agent(main, "outer", outer, status=outcome, error="synthetic interruption") + agent, _, tool = spans(sent[1]) + assert attrs(agent)["event.status"] == outcome + assert agent["status"]["code"] != 1 + assert tool["status"]["code"] != 1 + + +def test_stop_failure_keeps_chain_and_recorded_children(tmp_path): + main = transcript( + tmp_path, + "main", + [assistant("main-model", [{"type": "tool_use", "id": "pending", "name": "Read", "input": {}}])], + ) + with session(tmp_path, main) as (_, sent): + handlers._handle_stop_failure( + {"transcript_path": str(main), "error": "interrupted", "error_details": "synthetic"} + ) + tree = spans(sent[0]) + assert [attrs(s)["openinference.span.kind"] for s in tree] == ["CHAIN", "LLM", "TOOL"] + assert tree[0]["status"]["code"] == 2 + + +def test_model_timing_provenance_and_final_cache_snapshot(tmp_path): + first = assistant("model", [], usage={"input_tokens": 2, "output_tokens": 3, "cache_read_input_tokens": 40}) + last = assistant("model", [], usage={"input_tokens": 2, "output_tokens": 3, "cache_read_input_tokens": 50}) + last["uuid"] = "continuation" + main = transcript(tmp_path, "main", [first, last]) + root = TurnEvent("turn", "session", "1", 0, 1000, 3000, EventStatus.COMPLETED) + graph = parse_claude_transcript(main, root) + model = next(e for e in graph.events if isinstance(e, ModelCallEvent)) + assert model.usage.cache_read_tokens == 50 + payload = render_event_graph(graph, trace_id="a" * 32) + details = attrs(spans(payload)[1]) + assert details["llm.timing.start_source"] == "inferred_previous_conversation_record" + assert details["llm.timing.end_source"] == "observed_assistant_record" + + +def test_api_error_and_cancelled_tool_result_are_not_successful(tmp_path): + error = assistant("api-error", [{"type": "text", "text": "synthetic failure"}]) + error.update(isApiErrorMessage=True, error="overloaded_error") + result = { + "type": "user", + "timestamp": 2500, + "toolUseResult": {"status": "cancelled"}, + "message": { + "role": "user", + "content": [{"type": "tool_result", "tool_use_id": "call", "content": "cancelled"}], + }, + } + main = transcript(tmp_path, "main", launch("unused", "call", result=False) + [result, error]) + root = TurnEvent("turn", "session", "1", 0, 1000, 3000, EventStatus.COMPLETED) + graph = parse_claude_transcript(main, root) + assert next(e for e in graph.events if isinstance(e, ToolEvent)).status is EventStatus.CANCELLED + assert next(e for e in graph.events if e.event_id == "api-error").status is EventStatus.FAILED + + +def test_late_metadata_only_agent_keeps_launch_parent_across_session_end(tmp_path): + main = transcript(tmp_path, "main", launch("outer", "call-outer", result=False)) + outer = transcript(tmp_path, "agent-outer", [assistant("outer-model", [])], parent_call="call-outer") + with session(tmp_path, main) as (state, sent), patch.object(handlers, "gc_stale_state_files"): + handlers._handle_stop({"transcript_path": str(main)}) + handlers._handle_session_end({}) + assert state.state_file.is_file() + stop_agent(main, "outer", outer) + assert len(sent) == 2 + assert spans(sent[1])[0]["parentSpanId"] == spans(sent[0])[2]["spanId"] + + +def test_missing_async_transcript_does_not_fall_back_to_unrelated_turn(tmp_path): + main = transcript(tmp_path, "main", launch("outer", "call-outer")) + with session(tmp_path, main) as (state, sent): + handlers._handle_stop({"transcript_path": str(main)}) + state.set("current_trace_id", "c" * 32) + state.set("current_trace_span_id", "d" * 16) + stop_agent(main, "outer", tmp_path / "absent.jsonl") + assert state.get("async_subagents") is not None + assert len(sent) == 1 + + +def test_concurrent_agents_and_duplicate_completion_keep_individual_parents(tmp_path): + main = transcript(tmp_path, "main", launch("one", "call-one") + launch("two", "call-two")) + children = { + name: transcript(tmp_path, f"agent-{name}", [assistant(f"model-{name}", [])]) for name in ("one", "two") + } + with session(tmp_path, main) as (_, sent): + handlers._handle_stop({"transcript_path": str(main)}) + with ThreadPoolExecutor(max_workers=4) as pool: + list(pool.map(lambda name: stop_agent(main, name, children[name]), ["two", "one", "two", "one"])) + assert len(sent) == 3 + tools = {attrs(s)["tool.call.id"]: s for s in spans(sent[0]) if "tool.call.id" in attrs(s)} + for payload in sent[1:]: + agent = spans(payload)[0] + assert agent["parentSpanId"] == tools[f"call-{attrs(agent)['subagent.id']}"]["spanId"] diff --git a/tests/tracing/claude/test_claude_transcript.py b/tests/tracing/claude/test_claude_transcript.py index aa1039cf..2ef647c0 100644 --- a/tests/tracing/claude/test_claude_transcript.py +++ b/tests/tracing/claude/test_claude_transcript.py @@ -370,3 +370,90 @@ def test_duplicate_tool_call_id_keeps_first_use_for_result_correlation(tmp_path: assert tools[1].status is EventStatus.PENDING assert tools[0].event_id != tools[1].event_id assert any(item.code == "duplicate_tool_call_id" for item in graph.diagnostics) + + +def test_replayed_request_blobs_are_not_events(tmp_path: Path): + # Claude Code 2.1.3xx records the request it replays to the model, with + # copies of the earlier tool_use and tool_result blocks. + transcript = tmp_path / "replayed-request.jsonl" + tool_use = {"type": "tool_use", "id": "call-1", "name": "Read", "input": {"file_path": "hello.py"}} + tool_result = {"type": "tool_result", "tool_use_id": "call-1", "content": "SYNTHETIC_TOOL_OK"} + rows = [ + { + "type": "assistant", + "uuid": "assistant-1", + "timestamp": "2026-01-01T12:00:01.000Z", + "message": {"id": "message-1", "role": "assistant", "content": [tool_use]}, + }, + { + "type": "user", + "uuid": "result-1", + "timestamp": "2026-01-01T12:00:02.000Z", + "message": {"role": "user", "content": [tool_result]}, + }, + {"type": "api-request-blob", "message": {"role": "assistant", "content": [tool_use]}}, + {"type": "api-request-blob", "message": {"role": "user", "content": [tool_result]}}, + { + "type": "assistant", + "uuid": "assistant-2", + "timestamp": "2026-01-01T12:00:03.000Z", + "message": {"id": "message-2", "role": "assistant", "content": [{"type": "text", "text": "done"}]}, + }, + ] + transcript.write_text("\n".join(json.dumps(row) for row in rows) + "\n") + + graph = parse_claude_transcript(transcript, _turn()) + + tools = _typed(graph.events, ToolEvent) + assert [tool.tool_call_id for tool in tools] == ["call-1"] + assert tools[0].status == EventStatus.COMPLETED + assert [model.source_id for model in _typed(graph.events, ModelCallEvent)] == ["message-1", "message-2"] + assert not [d for d in graph.diagnostics if d.code in {"duplicate_tool_call_id", "missing_source_id"}] + + +def test_model_call_start_estimates_the_preceding_conversation_boundary(tmp_path: Path): + # Responses have recorded arrival times. The prompt/last tool result is a + # useful start estimate, but does not record actual request dispatch. + transcript = tmp_path / "model-call-timing.jsonl" + rows = [ + { + "type": "user", + "uuid": "prompt-1", + "timestamp": "2026-01-01T12:00:00.000Z", + "message": {"role": "user", "content": "read hello.py"}, + }, + { + "type": "assistant", + "uuid": "assistant-1", + "timestamp": "2026-01-01T12:00:02.000Z", + "message": { + "id": "message-1", + "role": "assistant", + "content": [{"type": "tool_use", "id": "call-1", "name": "Read", "input": {}}], + }, + }, + { + "type": "user", + "uuid": "result-1", + "timestamp": "2026-01-01T12:00:03.000Z", + "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call-1", "content": "ok"}]}, + }, + { + "type": "assistant", + "uuid": "assistant-2", + "timestamp": "2026-01-01T12:00:05.000Z", + "message": {"id": "message-2", "role": "assistant", "content": [{"type": "text", "text": "done"}]}, + }, + ] + transcript.write_text("\n".join(json.dumps(row) for row in rows) + "\n") + + graph = parse_claude_transcript(transcript, _turn()) + + t0 = 1_767_268_800_000 + calls = _typed(graph.events, ModelCallEvent) + assert [(call.started_at_ms, call.ended_at_ms) for call in calls] == [ + (t0, t0 + 2_000), + (t0 + 3_000, t0 + 5_000), + ] + tool = _typed(graph.events, ToolEvent)[0] + assert (tool.started_at_ms, tool.ended_at_ms) == (t0 + 2_000, t0 + 3_000) diff --git a/tests/tracing/claude/test_claude_transcript_encoding.py b/tests/tracing/claude/test_claude_transcript_encoding.py index 25495707..a785fec6 100644 --- a/tests/tracing/claude/test_claude_transcript_encoding.py +++ b/tests/tracing/claude/test_claude_transcript_encoding.py @@ -123,7 +123,7 @@ def test_parse_claude_transcript_under_non_utf8_locale(transcript: Path): with _non_utf8_locale(): graph = parse_claude_transcript(transcript, root) - assert not graph.diagnostics + assert not [item for item in graph.diagnostics if item.severity != "info"] models = [e for e in graph.events if isinstance(e, ModelCallEvent)] assert len(models) == 1 assert models[0].output == NON_ASCII_TEXT diff --git a/tracing/claude_code/README.md b/tracing/claude_code/README.md index 9a68eaa0..9c7461ee 100644 --- a/tracing/claude_code/README.md +++ b/tracing/claude_code/README.md @@ -4,7 +4,7 @@ Automatic [OpenInference](https://github.com/Arize-ai/openinference) tracing for ## Trace structure -Each user turn is represented as a `CHAIN` with a separate `LLM` span for every model response. Tool calls are correlated by Claude's `tool_use_id` and parented to the model response that requested them. A foreground subagent is represented as an `AGENT` below its invoking tool, with its own model and tool spans. +Each user turn is represented as a `CHAIN` with a separate `LLM` span for every model response. Tool calls are correlated by Claude's `tool_use_id` and parented to the model response that requested them. Subagents are represented as `AGENT` spans below their invoking tools, with their own model and tool spans. Background agents retain the launching turn's trace and parent tool even when they finish after that turn; nested and concurrent agents use explicit agent IDs or adjacent transcript metadata's `toolUseId` to resolve their parents. ```text Turn 1 (CHAIN) @@ -24,7 +24,10 @@ Transcript parsing and hook observations are fail-soft. Unknown or malformed rec ### Current limitations -- One foreground subagent is correlated into the main turn. Nested, background, cancelled, and concurrently running subagents are not yet reconstructed as complete subtrees. +- Subagent reconstruction requires a readable child transcript and an unambiguous invoking tool, identified by the structured launch result's `agentId`, an explicit parent tool ID, or the child transcript's adjacent `.meta.json` `toolUseId`. Unmatched descriptors are retained; parent relationships are never guessed from timing, prompt text, or launch order. +- A subagent that never emits `SubagentStop`, or disappears without a recorded failure/cancellation signal, cannot be reconstructed as a completed subtree. Explicit failed/cancelled/interrupted outcomes and transcript API errors are preserved; missing tool results remain incomplete. A successful stop hook alone does not reveal an unrecorded earlier interruption. +- Claude transcript timestamps record response arrival, not model request dispatch. Model starts estimated from the preceding conversation boundary include possible local processing; `llm.timing.start_source` marks this inference, and `llm.timing.end_source` identifies the observed response record. Subagent timestamps use start/stop hooks when available; a launch-tool fallback is marked by `subagent.timing.start_source`. +- Export snapshots are serialized per session. Retries reuse persisted span IDs, and repeated completion hooks are acknowledged once while session state exists. A process crash between remote acceptance and local acknowledgment is not an exactly-once delivery guarantee; exporter/backend retry semantics still apply. Pending state survives `SessionEnd`, but missing completion hooks are not retried by a background scheduler. - High-fidelity model/tool parenting depends on a readable Claude transcript. The no-transcript fallback remains intentionally less detailed. - Unknown future Claude transcript schemas are handled fail-soft, but may produce partial graphs until fixtures and parser support are updated. @@ -55,7 +58,7 @@ For Phoenix, swap the Arize keys for `PHOENIX_ENDPOINT` (and optional `PHOENIX_A Install: ```bash -claude plugin marketplace add Arize-ai/coding-harness-tracing +claude plugin marketplace add lifldev/coding-harness-tracing claude plugin install claude-code-tracing@coding-harness-tracing ``` @@ -63,7 +66,7 @@ Uninstall: ```bash claude plugin uninstall claude-code-tracing@coding-harness-tracing -claude plugin marketplace remove Arize-ai/coding-harness-tracing +claude plugin marketplace remove lifldev/coding-harness-tracing ``` ### Remote setup @@ -73,13 +76,13 @@ claude plugin marketplace remove Arize-ai/coding-harness-tracing Install: ```bash -curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.sh | bash -s -- claude +curl -sSL https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.sh | bash -s -- claude ``` Uninstall: ```bash -curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.sh | bash -s -- uninstall claude +curl -sSL https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.sh | bash -s -- uninstall claude ``` #### Windows (PowerShell) @@ -87,21 +90,21 @@ curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main Install: ```powershell -iwr -useb https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.bat -OutFile $env:TEMP\install.bat +iwr -useb https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.bat -OutFile $env:TEMP\install.bat & $env:TEMP\install.bat claude ``` Uninstall: ```powershell -iwr -useb https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.bat -OutFile $env:TEMP\install.bat +iwr -useb https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.bat -OutFile $env:TEMP\install.bat & $env:TEMP\install.bat uninstall claude ``` ### Local setup ```bash -git clone https://github.com/Arize-ai/coding-harness-tracing.git +git clone https://github.com/lifldev/coding-harness-tracing.git cd coding-harness-tracing ``` diff --git a/tracing/claude_code/hooks/handlers.py b/tracing/claude_code/hooks/handlers.py index 22459e07..f3c3b2fb 100644 --- a/tracing/claude_code/hooks/handlers.py +++ b/tracing/claude_code/hooks/handlers.py @@ -8,10 +8,12 @@ import json import math import sys +from contextlib import nullcontext from dataclasses import dataclass from pathlib import Path from core.common import ( + FileLock, build_span, env, error, @@ -475,6 +477,8 @@ def _scan_transcript_for_usage( entry = json.loads(line) except json.JSONDecodeError: continue + if not isinstance(entry, dict) or entry.get("type") not in (None, "assistant", "user"): + continue msg = entry.get("message") if not isinstance(msg, dict) or msg.get("role") != "assistant": continue @@ -603,9 +607,14 @@ def _transcript_has_stable_assistant_uuid(path_value: object) -> bool: record = json.loads(raw_line) except (json.JSONDecodeError, TypeError, ValueError): continue - if record.get("type") == "assistant" and isinstance(record.get("uuid"), str) and record["uuid"]: + if ( + isinstance(record, dict) + and record.get("type") == "assistant" + and isinstance(record.get("uuid"), str) + and record["uuid"] + ): return True - except OSError: + except (OSError, UnicodeError): return False return False @@ -614,7 +623,10 @@ def _buffer_subagent(state, input_json: dict, ended_at_ms: int) -> bool: agent_id = input_json.get("agent_id") transcript_path = input_json.get("agent_transcript_path") main_transcript_path = input_json.get("transcript_path") - if main_transcript_path == transcript_path or not _transcript_has_stable_assistant_uuid(main_transcript_path): + if not ( + _transcript_has_stable_assistant_uuid(main_transcript_path) + or _transcript_has_stable_assistant_uuid(transcript_path) + ): return False if not isinstance(agent_id, str) or not agent_id: return False @@ -633,6 +645,9 @@ def _buffer_subagent(state, input_json: dict, ended_at_ms: int) -> bool: "started_at_ms": None, "ended_at_ms": ended_at_ms, "output": input_json.get("last_assistant_message") or "", + "parent_tool_use_id": _parent_tool_use_id(input_json), + "status": _subagent_status(input_json).value, + "error": input_json.get("error_details") or input_json.get("error") or None, } if state.state_file is None: return False @@ -642,7 +657,8 @@ def _buffer_subagent(state, input_json: dict, ended_at_ms: int) -> bool: descriptors = _decode_pending_subagents(data.get("pending_subagents", "")) stored_start = str(data.get(f"subagent_{agent_id}_start_time", "")) descriptor["started_at_ms"] = int(stored_start) if stored_start.isdigit() else None - descriptors[agent_id] = descriptor + # Duplicate Stop hooks retain the first observed completion boundary. + descriptors.setdefault(agent_id, descriptor) data["pending_subagents"] = json.dumps(descriptors, sort_keys=True) state._write(data) except Exception as exc: @@ -651,6 +667,51 @@ def _buffer_subagent(state, input_json: dict, ended_at_ms: int) -> bool: return True +def _parent_tool_use_id(input_json: dict) -> str: + """Read an explicit hook or adjacent transcript-metadata relationship.""" + call_id = input_json.get("parent_tool_use_id") + if isinstance(call_id, str) and call_id: + return call_id + path = input_json.get("agent_transcript_path") + if isinstance(path, str) and path: + try: + metadata = json.loads(Path(path).with_suffix(".meta.json").read_text(encoding="utf-8")) + call_id = metadata.get("toolUseId") if isinstance(metadata, dict) else None + if isinstance(call_id, str): + return call_id + except (OSError, UnicodeError, ValueError): + pass + return "" + + +def _subagent_status(payload: dict) -> EventStatus: + status = payload.get("status") + if status in {"cancelled", "canceled", "interrupted"} or payload.get("interrupted") is True: + return EventStatus.CANCELLED + if status in {"failed", "error"} or payload.get("error") or payload.get("error_details"): + return EventStatus.FAILED + return EventStatus.COMPLETED + + +def _export_lock(state): + # Keep export snapshots and acknowledgment serial without blocking tool + # observations on the state lock. Never break a live export lock on timeout. + if state.state_file is None: + return nullcontext() + return FileLock(state.state_file.with_suffix(".export.lock"), timeout=3, break_on_timeout=False) + + +def _exported_subagents(state) -> dict[str, dict]: + return _decode_pending_subagents(state.get("exported_subagents") or "") + + +def _mark_exported_subagents(data: dict, agent_ids) -> None: + exported = _decode_pending_subagents(data.get("exported_subagents", "")) + exported.update({agent_id: {} for agent_id in agent_ids}) + if exported: + data["exported_subagents"] = json.dumps(exported, sort_keys=True) + + def _agent_id_from_tool(event: ToolEvent) -> str: if not isinstance(event.output, dict): return "" @@ -661,59 +722,287 @@ def _agent_id_from_tool(event: ToolEvent) -> str: return agent_id if isinstance(agent_id, str) else "" +# Background (async) subagents: the Agent tool returns ``async_launched`` at +# once and the subagent stops after the launching turn was exported, often +# while no turn is open. The launching turn records where its Agent span went; +# SubagentStop then exports the subagent tree under that span directly. +ASYNC_SUBAGENTS_KEY = "async_subagents" + + +def _async_launched_agent_id(event) -> str: + if not isinstance(event, ToolEvent) or not isinstance(event.output, dict): + return "" + result = event.output.get("toolUseResult") + if not isinstance(result, dict): + return "" + if result.get("isAsync") is not True and result.get("status") != "async_launched": + return "" + agent_id = result.get("agentId") + return agent_id if isinstance(agent_id, str) else "" + + +def _async_subagents(state) -> dict[str, dict]: + return _decode_pending_subagents(state.get(ASYNC_SUBAGENTS_KEY) or "") + + +def _remember_async_subagents( + state, + graph, + span_ids: dict[str, str], + trace_id: str, + matched: dict[str, dict], +) -> None: + """Record the exported Agent span of every async launch still running.""" + launches: dict[str, dict] = {} + for event in graph.events: + if not isinstance(event, ToolEvent) or event.tool_name not in {"Agent", "Task"}: + continue + agent_id = _async_launched_agent_id(event) + if not agent_id and not _agent_id_from_tool(event) and event.status is EventStatus.PENDING: + agent_id = f"tool:{event.tool_call_id}" + if ( + not agent_id + or agent_id in matched + or any( + graph_event.parent_event_id == event.event_id and isinstance(graph_event, AgentEvent) + for graph_event in graph.events + ) + ): + continue + span_id = span_ids.get(event.event_id) + if not span_id: + continue + prompt = event.input.get("prompt") if isinstance(event.input, dict) else None + launches[agent_id] = { + "trace_id": trace_id, + "parent_span_id": span_id, + "turn_id": event.turn_id, + "launched_at_ms": event.started_at_ms, + "prompt": prompt if isinstance(prompt, str) else None, + "parent_tool_use_id": event.tool_call_id, + } + if not launches or state.state_file is None: + return + try: + with state._lock(): + data = state._read_safe() + current = _decode_pending_subagents(data.get(ASYNC_SUBAGENTS_KEY, "")) + current.update(launches) + data[ASYNC_SUBAGENTS_KEY] = json.dumps(current, sort_keys=True) + state._write(data) + except Exception as exc: + error(f"Failed to record async subagent launches: {exc}") + + +def _forget_async_subagent(state, agent_id: str) -> None: + if state.state_file is None: + return + try: + with state._lock(): + data = state._read_safe() + current = _decode_pending_subagents(data.get(ASYNC_SUBAGENTS_KEY, "")) + current.pop(agent_id, None) + if current: + data[ASYNC_SUBAGENTS_KEY] = json.dumps(current, sort_keys=True) + else: + data.pop(ASYNC_SUBAGENTS_KEY, None) + data.pop(f"subagent_{agent_id}_start_time", None) + data.pop(f"subagent_{agent_id}_prompt", None) + _mark_exported_subagents(data, [agent_id]) + state._write(data) + except Exception as exc: + error(f"Failed to clean up async subagent {agent_id}: {exc}") + + +def _export_async_subagent(state, input_json: dict) -> bool: + """Export a background subagent under its launching Agent span. + + Returns True when the subagent belongs to a recorded async launch, whether + or not the export succeeded, so the caller does not buffer it for a turn + that will never contain its Agent tool. + """ + agent_id = input_json.get("agent_id") + if not isinstance(agent_id, str) or not agent_id: + return False + launches = _async_subagents(state) + launch_key = agent_id + launch = launches.get(agent_id) + if launch is None: + call_id = _parent_tool_use_id(input_json) + candidates = [ + (key, value) for key, value in launches.items() if call_id and value.get("parent_tool_use_id") == call_id + ] + if len(candidates) == 1: + launch_key, launch = candidates[0] + if launch is None: + return False + trace_id = launch.get("trace_id") + parent_span_id = launch.get("parent_span_id") + transcript_path = input_json.get("agent_transcript_path") + if not isinstance(trace_id, str) or not isinstance(parent_span_id, str): + error(f"Invalid persisted launch relationship for subagent {agent_id}; retaining state") + return True + if not isinstance(transcript_path, str) or not Path(transcript_path).is_file(): + return True + + pending = _pending_subagents(state).get(agent_id, {}) + ended_at_ms = pending.get("ended_at_ms") or get_timestamp_ms() + stored_start = str(state.get(f"subagent_{agent_id}_start_time") or "") + launched_at = launch.get("launched_at_ms") + started_at_ms = int(stored_start) if stored_start.isdigit() else launched_at + agent_event = AgentEvent( + event_id=f"agent:{agent_id}", + session_id=state.get("session_id") or input_json.get("session_id") or "", + turn_id=str(launch.get("turn_id") or ""), + sequence=0, + started_at_ms=started_at_ms if isinstance(started_at_ms, int) else None, + ended_at_ms=ended_at_ms, + status=EventStatus(pending["status"]) if pending.get("status") else _subagent_status(input_json), + input=launch.get("prompt") or state.get(f"subagent_{agent_id}_prompt") or None, + output=input_json.get("last_assistant_message") or "", + agent_id=agent_id, + source_id=input_json.get("agent_type") or "unknown", + error=pending.get("error") or input_json.get("error_details") or input_json.get("error") or None, + ) + graph = parse_claude_transcript(Path(transcript_path), agent_event) + if any(item.code == "transcript_read_error" for item in graph.diagnostics): + return True + _apply_agent_outcome(graph, agent_event) + matched_subagents = _merge_pending_subagents(graph, _pending_subagents(state)) + matched_observations = _merge_tool_observations(graph, ToolBuffer(state).all()) + graph.validate() + if not stored_start.isdigit() and started_at_ms is not None: + graph.diagnostics.append( + GraphDiagnostic( + code="inferred_agent_start", + message="Start estimated from invoking tool observation", + event_id=agent_event.event_id, + severity="info", + ) + ) + + user_id = state.get("user_id") or "" + extra = {agent_event.event_id: {"user.id": user_id}} if user_id else None + span_ids = launch.get("span_ids") or {} + for event in graph.events: + span_ids.setdefault(event.event_id, generate_span_id()) + launch["span_ids"] = span_ids + launch.setdefault("stopped_at_ms", ended_at_ms) + agent_event.ended_at_ms = launch["stopped_at_ms"] + # Persist identities before sending so transport retries update the same spans. + with state._lock(): + data = state._read_safe() + current = _decode_pending_subagents(data.get(ASYNC_SUBAGENTS_KEY, "")) + current[launch_key] = launch + data[ASYNC_SUBAGENTS_KEY] = json.dumps(current, sort_keys=True) + state._write(data) + payload = render_event_graph( + graph, + trace_id=trace_id, + service_name=SERVICE_NAME, + scope_name=SCOPE_NAME, + extra_attributes=extra, + span_id_overrides=span_ids, + ) + for scope in payload.get("resourceSpans", [{}])[0].get("scopeSpans", []): + for span in scope.get("spans", []): + if not span.get("parentSpanId"): + span["parentSpanId"] = parent_span_id + if send_span(payload) is False: + error(f"Failed to export async subagent {agent_id}") + return True + _remember_async_subagents(state, graph, span_ids, trace_id, matched_subagents) + ToolBuffer(state).remove_many(matched_observations) + _cleanup_pending_subagents(state, {**matched_subagents, **({agent_id: pending} if pending else {})}) + _forget_async_subagent(state, launch_key) + if launch_key != agent_id: + with state._lock(): + data = state._read_safe() + _mark_exported_subagents(data, [agent_id]) + data.pop(f"subagent_{agent_id}_start_time", None) + data.pop(f"subagent_{agent_id}_prompt", None) + state._write(data) + return True + + def _merge_pending_subagents(graph, descriptors: dict[str, dict]) -> dict[str, dict]: - """Insert correlated foreground agent graphs and return exported descriptors.""" + """Resolve exact tool relationships until no additional subtree is reachable.""" matched: dict[str, dict] = {} - if not descriptors or not graph.events: + if not graph.events: return matched root = graph.events[0] - for agent_id, descriptor in descriptors.items(): - parent_tool = next( - ( + remaining = dict(descriptors) + while remaining: + progressed = False + for agent_id, descriptor in list(remaining.items()): + call_id = descriptor.get("parent_tool_use_id") + candidates = [ event for event in graph.events - if isinstance(event, ToolEvent) and _agent_id_from_tool(event) == agent_id - ), - None, - ) - if parent_tool is None: - graph.diagnostics.append( - GraphDiagnostic( - code="unmatched_subagent", - message="Subagent descriptor had no correlated Agent tool", - event_id=f"agent:{agent_id}", - ) + if isinstance(event, ToolEvent) + and event.tool_name in {"Agent", "Task"} + and (event.tool_call_id == call_id if call_id else _agent_id_from_tool(event) == agent_id) + and _agent_id_from_tool(event) in {"", agent_id} + and event.agent_id != agent_id + ] + if len(candidates) != 1 or any(event.event_id == f"agent:{agent_id}" for event in graph.events): + continue + parent_tool = candidates[0] + agent_event = AgentEvent( + event_id=f"agent:{agent_id}", + parent_event_id=parent_tool.event_id, + session_id=root.session_id, + turn_id=root.turn_id, + sequence=parent_tool.sequence + 1, + started_at_ms=descriptor.get("started_at_ms"), + ended_at_ms=descriptor.get("ended_at_ms"), + status=EventStatus(descriptor.get("status", "completed")), + input=parent_tool.input.get("prompt") if isinstance(parent_tool.input, dict) else None, + output=descriptor.get("output"), + error=descriptor.get("error"), + agent_id=agent_id, + source_id=str(descriptor.get("agent_type") or "unknown"), + ) + subgraph = parse_claude_transcript(Path(str(descriptor.get("transcript_path") or "")), agent_event) + if any(item.code == "transcript_read_error" for item in subgraph.diagnostics): + graph.diagnostics.extend(subgraph.diagnostics) + continue + _apply_agent_outcome(subgraph, agent_event) + insertion_index = graph.events.index(parent_tool) + 1 + graph.events[insertion_index:insertion_index] = subgraph.events + graph.diagnostics.extend(subgraph.diagnostics) + matched[agent_id] = descriptor + remaining.pop(agent_id) + progressed = True + if not progressed: + break + for agent_id in remaining: + graph.diagnostics.append( + GraphDiagnostic( + code="unmatched_subagent", + message="Subagent has no unambiguous invoking Agent tool", + event_id=f"agent:{agent_id}", + severity="warning", ) - continue - parent_event_id = parent_tool.event_id - agent_type = str(descriptor.get("agent_type") or "unknown") - agent_input = None - if parent_tool is not None and isinstance(parent_tool.input, dict): - agent_input = parent_tool.input.get("prompt") - agent_event = AgentEvent( - event_id=f"agent:{agent_id}", - parent_event_id=parent_event_id, - session_id=root.session_id, - turn_id=root.turn_id, - sequence=(parent_tool.sequence + 1) if parent_tool is not None else len(graph.events), - started_at_ms=descriptor.get("started_at_ms"), - ended_at_ms=descriptor.get("ended_at_ms"), - status=EventStatus.COMPLETED, - input=agent_input, - output=descriptor.get("output"), - agent_id=agent_id, - source_id=agent_type, ) - transcript_path = Path(str(descriptor.get("transcript_path") or "")) - subgraph = parse_claude_transcript(transcript_path, agent_event) - insertion_index = graph.events.index(parent_tool) + 1 if parent_tool is not None else len(graph.events) - graph.events[insertion_index:insertion_index] = subgraph.events - graph.diagnostics.extend(subgraph.diagnostics) - matched[agent_id] = descriptor graph.validate() return matched +def _apply_agent_outcome(graph, agent_event) -> None: + if agent_event.status is EventStatus.COMPLETED and any( + isinstance(event, ModelCallEvent) and event.status is EventStatus.FAILED for event in graph.events + ): + agent_event.status = EventStatus.FAILED + agent_event.error = "Subagent transcript records a model request failure" + if agent_event.status in {EventStatus.CANCELLED, EventStatus.FAILED}: + for event in graph.events: + if isinstance(event, ToolEvent) and event.status in {EventStatus.PENDING, EventStatus.RUNNING}: + event.status = ( + EventStatus.CANCELLED if agent_event.status is EventStatus.CANCELLED else EventStatus.UNKNOWN + ) + + def _cleanup_pending_subagents(state, exported: dict[str, dict]) -> set[str]: """Acknowledge only descriptors unchanged since the export snapshot.""" if state.state_file is None: @@ -734,6 +1023,7 @@ def _cleanup_pending_subagents(state, exported: dict[str, dict]) -> set[str]: data["pending_subagents"] = json.dumps(current, sort_keys=True) else: data.pop("pending_subagents", None) + _mark_exported_subagents(data, removed) state._write(data) except Exception as exc: error(f"Failed to clean up exported subagents: {exc}") @@ -772,6 +1062,7 @@ def _acknowledge_exported_turn( data["pending_subagents"] = json.dumps(current_subagents, sort_keys=True) else: data.pop("pending_subagents", None) + _mark_exported_subagents(data, subagents) for key in ( "current_trace_id", @@ -802,9 +1093,14 @@ def _periodic_gc(trace_count: str) -> None: gc_stale_state_files() -def _handle_stop(input_json: dict) -> None: - """Handle Stop: send the LLM span for the completed turn and clean up trace state.""" +def _handle_stop(input_json: dict, *, _failed: bool = False) -> None: + """Serialize export and acknowledgment across concurrent Stop hooks.""" state = resolve_session(input_json) + with _export_lock(state): + _stop_turn(state, input_json, failed=_failed) + + +def _stop_turn(state, input_json: dict, *, failed: bool = False) -> None: session_id = state.get("session_id") trace_id = state.get("current_trace_id") if session_id is None or trace_id is None: @@ -844,7 +1140,8 @@ def _handle_stop(input_json: dict) -> None: sequence=0, started_at_ms=int(trace_start_time) if trace_start_time.isdigit() else None, ended_at_ms=get_timestamp_ms(), - status=EventStatus.COMPLETED, + status=EventStatus.FAILED if failed else EventStatus.COMPLETED, + error=str(input_json.get("error_details") or input_json.get("error") or "Turn failed") if failed else None, input=user_prompt, output=output, ) @@ -859,6 +1156,14 @@ def _handle_stop(input_json: dict) -> None: pending_subagents = _pending_subagents(state) matched_observations = _merge_tool_observations(graph, observations) matched_subagents = _merge_pending_subagents(graph, pending_subagents) + matched_ids = {item.tool_use_id for item in matched_observations} + matched_observations.extend( + _merge_tool_observations(graph, [item for item in observations if item.tool_use_id not in matched_ids]) + ) + if failed: + for event in graph.events: + if isinstance(event, ToolEvent) and event.status in {EventStatus.PENDING, EventStatus.RUNNING}: + event.status = EventStatus.UNKNOWN graph.validate() timestamp_candidates = [ int(event.ended_at_ms) @@ -920,6 +1225,7 @@ def _handle_stop(input_json: dict) -> None: ) if send_span(payload) is False: return + _remember_async_subagents(state, graph, span_id_overrides, trace_id, matched_subagents) _acknowledge_exported_turn(state, trace_id, matched_observations, matched_subagents) _periodic_gc(trace_count) return @@ -991,12 +1297,20 @@ def _handle_subagent_start(input_json: dict) -> None: def _handle_subagent_stop(input_json: dict) -> None: - """Handle subagent_stop: parse subagent transcript and send CHAIN span.""" + """Serialize subagent completion with the launching turn's export.""" state = resolve_session(input_json) - trace_id = state.get("current_trace_id") - if trace_id is None: - return + with _export_lock(state): + _stop_subagent(state, input_json) + +def _stop_subagent(state, input_json: dict) -> None: + agent_id = input_json.get("agent_id", "") + if agent_id in _exported_subagents(state): + return + # A background subagent outlives the turn that launched it: export it under + # that turn's Agent span, even if no turn is open now. + if _export_async_subagent(state, input_json): + return session_id = state.get("session_id") agent_id = input_json.get("agent_id", "") agent_type = input_json.get("agent_type", "") @@ -1008,6 +1322,10 @@ def _handle_subagent_stop(input_json: dict) -> None: if _buffer_subagent(state, input_json, int(end_time)): return + trace_id = state.get("current_trace_id") + if trace_id is None: + return + if not agent_type or agent_type in ("unknown", "null"): return @@ -1087,6 +1405,10 @@ def _handle_subagent_stop(input_json: dict) -> None: def _handle_stop_failure(input_json: dict) -> None: """Handle StopFailure: emit a span describing the failed turn so it doesn't disappear silently.""" state = resolve_session(input_json) + transcript = resolve_transcript_path(input_json, state.get("session_id") or "") + if transcript is not None and _transcript_has_stable_assistant_uuid(str(transcript)): + _handle_stop(input_json, _failed=True) + return session_id = state.get("session_id") trace_id = state.get("current_trace_id") if session_id is None or trace_id is None: @@ -1276,6 +1598,12 @@ def _handle_session_end(input_json: dict) -> None: error(f"Session complete: {trace_count} traces, {tool_count} tools") error(f"View in Arize/Phoenix: session.id = {session_id}") + # Background descendants can finish after their launching session exits. + # Keep their authoritative span links and any failed export for retry. + if _async_subagents(state) or _pending_subagents(state) or state.get("current_trace_id"): + log("Retaining session state for unfinished exports/subagents") + return + # Clean up state file and lock if state.state_file is not None: state.state_file.unlink(missing_ok=True) diff --git a/tracing/claude_code/hooks/span_renderer.py b/tracing/claude_code/hooks/span_renderer.py index bbd1ae24..220d17ed 100644 --- a/tracing/claude_code/hooks/span_renderer.py +++ b/tracing/claude_code/hooks/span_renderer.py @@ -49,11 +49,31 @@ def render_event_graph( payloads: list[dict] = [] graph_start = _first_timestamp(graph.events, "started_at_ms") graph_end = _last_timestamp(graph.events, "ended_at_ms") or graph_start + inferred_starts = {item.event_id for item in graph.diagnostics if item.code == "inferred_model_start"} + inferred_agent_starts = {item.event_id for item in graph.diagnostics if item.code == "inferred_agent_start"} for index, event in enumerate(graph.events): if isinstance(event, ModelCallEvent): model_call_number += 1 name, kind, attrs = _span_fields(event, model_call_number) + if isinstance(event, ModelCallEvent): + attrs["llm.timing.start_source"] = ( + "inferred_previous_conversation_record" + if event.event_id in inferred_starts + else "observed_assistant_record" if event.started_at_ms is not None else "unavailable" + ) + attrs["llm.timing.end_source"] = ( + "observed_assistant_record" if event.ended_at_ms is not None else "unavailable" + ) + if isinstance(event, AgentEvent): + attrs["subagent.timing.start_source"] = ( + "inferred_launch_tool" + if event.event_id in inferred_agent_starts + else "observed_subagent_start" if event.started_at_ms is not None else "unavailable" + ) + attrs["subagent.timing.end_source"] = ( + "observed_subagent_stop" if event.ended_at_ms is not None else "unavailable" + ) attrs.update(extras.get(event.event_id, {})) parent_span_id = first_span_by_event_id.get(safe_parent_ids[index] or "", "") start_ms = _safe_timestamp(event.started_at_ms, graph_start) @@ -85,6 +105,7 @@ def _span_fields(event: BaseEvent, model_call_number: int) -> tuple[str, str, di attrs: dict[str, Any] = { "session.id": event.session_id, "turn.id": event.turn_id, + "event.status": event.status.value, } if isinstance(event, TurnEvent): @@ -196,7 +217,7 @@ def _status(event: BaseEvent) -> tuple[int, str]: message = redact_content(allowed, event.error) if event.error else "" if event.status is EventStatus.FAILED: return 2, message or "Event failed" - if event.status in {EventStatus.PENDING, EventStatus.RUNNING, EventStatus.UNKNOWN}: + if event.status in {EventStatus.PENDING, EventStatus.RUNNING, EventStatus.UNKNOWN, EventStatus.CANCELLED}: return 0, message return 1, message diff --git a/tracing/claude_code/hooks/transcript.py b/tracing/claude_code/hooks/transcript.py index 6e9953d0..706dc569 100644 --- a/tracing/claude_code/hooks/transcript.py +++ b/tracing/claude_code/hooks/transcript.py @@ -39,6 +39,10 @@ def parse_claude_transcript( models_by_message_id: dict[str, ModelCallEvent] = {} agent_id = root_event.agent_id if isinstance(root_event, AgentEvent) else None sequence = root_event.sequence + 1 + # Claude records response arrival, not request dispatch. The preceding + # conversation boundary is an estimate that can include local processing. + request_ms = _valid_ms(root_event.started_at_ms) + seen_record_ids: set[str] = set() try: lines = transcript.read_text(encoding="utf-8").splitlines() @@ -69,6 +73,17 @@ def parse_claude_transcript( continue if not isinstance(entry, dict): continue + # Claude Code 2.1.3xx also records the request it replays to the model + # ("api-request-blob"), with copies of earlier tool_use and tool_result + # blocks. Only conversation records are events; the replay would + # duplicate every tool as a pending span under an empty model call. + if entry.get("type") not in (None, "assistant", "user"): + continue + record_id = _string(entry.get("uuid")) + if record_id and record_id in seen_record_ids: + continue + if record_id: + seen_record_ids.add(record_id) message = entry.get("message") if not isinstance(message, dict): @@ -109,13 +124,24 @@ def parse_claude_transcript( # stay one-event-per-record (also preserves assistant-line-* ids). model_event = models_by_message_id.get(message_id) if message_id else None if model_event is None: + started_at_ms = timestamp_ms + if timestamp_ms is not None and request_ms is not None and request_ms <= timestamp_ms: + started_at_ms = request_ms + parser_diagnostics.append( + GraphDiagnostic( + code="inferred_model_start", + message="Start estimated from preceding conversation boundary, not recorded request dispatch", + event_id=event_id, + severity="info", + ) + ) model_event = ModelCallEvent( event_id=event_id, parent_event_id=root_event.event_id, session_id=_string(entry.get("sessionId")) or root_event.session_id, turn_id=root_event.turn_id, sequence=sequence, - started_at_ms=timestamp_ms, + started_at_ms=started_at_ms, ended_at_ms=timestamp_ms, status=EventStatus.COMPLETED, input=None, @@ -141,10 +167,15 @@ def parse_claude_transcript( model_event.ended_at_ms = timestamp_ms if not model_event.model: model_event.model = _string(message.get("model")) or None - record_usage = _usage(message.get("usage")) - existing_total = model_event.usage.total_tokens if model_event.usage else -1 - if record_usage.total_tokens > existing_total: - model_event.usage = record_usage + # The final reported snapshot is authoritative, including cache + # corrections that leave uncached input/output totals unchanged. + if isinstance(message.get("usage"), dict) and message["usage"]: + model_event.usage = _usage(message["usage"]) + if entry.get("isApiErrorMessage") is True or message.get("stop_reason") == "error": + model_event.status = EventStatus.FAILED + model_event.error = _string(entry.get("error")) or _assistant_text(content) or "Model request failed" + if timestamp_ms is not None: + request_ms = timestamp_ms for block in _content_blocks(content): if block.get("type") != "tool_use": @@ -184,6 +215,8 @@ def parse_claude_transcript( elif role == "user": result_timestamp_ms = _timestamp_ms(entry.get("timestamp")) + if result_timestamp_ms is not None: + request_ms = result_timestamp_ms for block in _content_blocks(message.get("content")): if block.get("type") != "tool_result": continue @@ -224,7 +257,14 @@ def parse_claude_transcript( content = block.get("content") correlated_tool.output = _tool_output(entry, content) correlated_tool.ended_at_ms = result_timestamp_ms - correlated_tool.status = EventStatus.FAILED if failed else EventStatus.COMPLETED + result = entry.get("toolUseResult") + cancelled = isinstance(result, dict) and ( + result.get("status") in {"cancelled", "canceled", "interrupted"} + or result.get("interrupted") is True + ) + correlated_tool.status = ( + EventStatus.CANCELLED if cancelled else EventStatus.FAILED if failed else EventStatus.COMPLETED + ) if "timestamp" in entry and result_timestamp_ms is None: parser_diagnostics.append( GraphDiagnostic( @@ -306,6 +346,12 @@ def _optional_nonnegative_int(value: Any) -> int | None: return _nonnegative_int(value) +def _valid_ms(value: Any) -> int | None: + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0: + return None + return int(value) + + def _timestamp_ms(value: Any) -> int | None: if isinstance(value, (int, float)) and not isinstance(value, bool): return int(value) if math.isfinite(value) and value >= 0 else None diff --git a/tracing/claude_code/skills/manage-claude-code-tracing/SKILL.md b/tracing/claude_code/skills/manage-claude-code-tracing/SKILL.md index 196f9cfc..bb4230ff 100644 --- a/tracing/claude_code/skills/manage-claude-code-tracing/SKILL.md +++ b/tracing/claude_code/skills/manage-claude-code-tracing/SKILL.md @@ -212,7 +212,7 @@ Ask the user: **"Have you already installed this plugin via the Claude Code CLI? **If no:** Tell them to clone the repo into their project: ```bash -git clone https://github.com/Arize-ai/coding-harness-tracing.git +git clone https://github.com/lifldev/coding-harness-tracing.git ``` The plugin path will be `./coding-harness-tracing/tracing/claude_code`. From 7f4fa5a174fe2a5e73caa724e8ced9360810cfde Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 21 Oct 2026 11:15:00 +0300 Subject: [PATCH 5/5] fix(codex): reconstruct response usage and observed tool execution --- tests/tracing/codex/test_codex_hook.py | 38 +- tests/tracing/codex/test_fidelity.py | 431 ++++++++++++++ tracing/codex/README.md | 195 +++---- tracing/codex/hooks/delivery.py | 55 ++ tracing/codex/hooks/graph.py | 327 +++++++++++ tracing/codex/hooks/handlers.py | 530 +++-------------- tracing/codex/hooks/lineage.py | 98 ++++ tracing/codex/hooks/transcript.py | 542 ++++++++++++++++++ .../skills/manage-codex-tracing/SKILL.md | 374 ++---------- 9 files changed, 1697 insertions(+), 893 deletions(-) create mode 100644 tests/tracing/codex/test_fidelity.py create mode 100644 tracing/codex/hooks/delivery.py create mode 100644 tracing/codex/hooks/graph.py create mode 100644 tracing/codex/hooks/lineage.py create mode 100644 tracing/codex/hooks/transcript.py diff --git a/tests/tracing/codex/test_codex_hook.py b/tests/tracing/codex/test_codex_hook.py index 167e39aa..3fb1f90c 100644 --- a/tests/tracing/codex/test_codex_hook.py +++ b/tests/tracing/codex/test_codex_hook.py @@ -37,6 +37,8 @@ def _isolate_sessions_root(tmp_path, monkeypatch): import tracing.codex.hooks.handlers as h monkeypatch.setattr(h, "_CODEX_SESSIONS_ROOT", tmp_path / "sessions") + monkeypatch.delenv("CODEX_HOME", raising=False) + monkeypatch.setattr("tracing.codex.hooks.delivery._STATE_DIR", tmp_path / "delivery") return tmp_path @@ -503,7 +505,8 @@ def test_web_search_call_pairs_with_preceding_end(self, tmp_path): assert len(turn["tool_calls"]) == 1 tc = turn["tool_calls"][0] assert tc["tool"] == "web_search" - assert tc["call_id"] == "ws_1" + # An end event without a shared durable ID cannot establish a parent/call link. + assert tc["call_id"] == "" assert tc["args"] == "weather" assert tc["output"] == "completed" @@ -652,28 +655,30 @@ def test_multi_span_with_one_tool(self, monkeypatch): assert len(sent) == 1 spans = sent[0]["resourceSpans"][0]["scopeSpans"][0]["spans"] - assert len(spans) == 2 # parent + 1 child + assert len(spans) == 3 # turn + response + tool parent_attrs = _attrs_of_span(spans[0]) assert parent_attrs["input.value"]["stringValue"] == "hi" assert parent_attrs["output.value"]["stringValue"] == "hello" - assert parent_attrs["llm.model_name"]["stringValue"] == "gpt-5.5" + response_attrs = _attrs_of_span(spans[1]) + assert response_attrs["llm.model_name"]["stringValue"] == "gpt-5.5" assert parent_attrs["llm.system"]["stringValue"] == "openai" assert parent_attrs["llm.provider"]["stringValue"] == "openai" assert parent_attrs["codex.approval_mode"]["stringValue"] == "on-request" assert parent_attrs["codex.sandbox_mode"]["stringValue"] == "workspace-write" assert parent_attrs["codex.cwd"]["stringValue"] == "/x/workspace" assert parent_attrs["codex.workspace"]["stringValue"] == "workspace" - assert parent_attrs["llm.token_count.total"]["intValue"] == 15 - assert parent_attrs["llm.token_count.prompt_details.cache_read"]["intValue"] == 8 - assert parent_attrs["llm.token_count.prompt_details.cache_write"]["intValue"] == 2 - assert parent_attrs["llm.token_count.completion_details.reasoning"]["intValue"] == 1 + assert "llm.token_count.total" not in parent_attrs + assert response_attrs["llm.token_count.total"]["intValue"] == 15 + assert response_attrs["llm.token_count.prompt_details.cache_read"]["intValue"] == 8 + assert response_attrs["llm.token_count.prompt_details.cache_write"]["intValue"] == 2 + assert response_attrs["llm.token_count.completion_details.reasoning"]["intValue"] == 1 assert parent_attrs["llm.input_messages.0.message.role"]["stringValue"] == "user" assert parent_attrs["llm.input_messages.0.message.content"]["stringValue"] == "hi" assert parent_attrs["llm.output_messages.0.message.role"]["stringValue"] == "assistant" assert parent_attrs["llm.output_messages.0.message.content"]["stringValue"] == "hello" - child_attrs = _attrs_of_span(spans[1]) + child_attrs = _attrs_of_span(spans[2]) assert child_attrs["tool.name"]["stringValue"] == "exec_command" assert child_attrs["tool.id"]["stringValue"] == "c1" assert child_attrs["codex.tool.call_id"]["stringValue"] == "c1" @@ -687,7 +692,7 @@ def test_spawn_agent_becomes_one_tool_span(self): not a nested AGENT trace. tool.id is the call_id; input.value is the raw argument string, including the nested model field. - TODO: monitor how #114 affects this""" + Native lineage additionally requires authoritative child metadata.""" spawn_args = '{"model": "gpt-5.4", "prompt": "investigate the bug"}' turn = { "trace_count": 1, @@ -718,8 +723,8 @@ def test_spawn_agent_becomes_one_tool_span(self): _build_and_send_spans("sess-1", "turn-1", turn) spans = sent[0]["resourceSpans"][0]["scopeSpans"][0]["spans"] - assert len(spans) == 2 # parent + 1 child - child = spans[1] + assert len(spans) == 3 # turn + response + tool + child = spans[2] assert child["name"] == "spawn_agent" child_attrs = _attrs_of_span(child) assert child_attrs["openinference.span.kind"]["stringValue"] == "TOOL" @@ -767,7 +772,7 @@ def test_no_response_when_assistant_output_empty(self): with patcher: _build_and_send_spans("sess-1", "turn-1", turn) parent_attrs = _attrs_of_span(sent[0]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]) - assert parent_attrs["output.value"]["stringValue"] == "(No response)" + assert parent_attrs["output.value"]["stringValue"] == "" def test_zero_token_counts_kept_unobserved_fields_absent(self): """Observed zero prompt/completion/total survive as intValue 0; a @@ -794,7 +799,7 @@ def test_zero_token_counts_kept_unobserved_fields_absent(self): sent, patcher = self._send_capture() with patcher: _build_and_send_spans("sess-1", "turn-1", turn) - parent_attrs = _attrs_of_span(sent[0]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]) + parent_attrs = _attrs_of_span(sent[0]["resourceSpans"][0]["scopeSpans"][0]["spans"][1]) assert parent_attrs["llm.token_count.prompt"]["intValue"] == 0 assert parent_attrs["llm.token_count.completion"]["intValue"] == 0 assert parent_attrs["llm.token_count.total"]["intValue"] == 0 @@ -1062,12 +1067,13 @@ def test_extracts_from_rollout_and_ships_multi_span(self, _isolate_sessions_root assert len(sent) == 1 spans = sent[0]["resourceSpans"][0]["scopeSpans"][0]["spans"] - assert len(spans) == 2 # parent + 1 tool child + assert len(spans) == 3 # turn + response + tool parent_attrs = _attrs_of_span(spans[0]) assert parent_attrs["input.value"]["stringValue"] == "do something" assert parent_attrs["output.value"]["stringValue"] == "done" - assert parent_attrs["llm.token_count.total"]["intValue"] == 6 - child_attrs = _attrs_of_span(spans[1]) + assert "llm.token_count.total" not in parent_attrs + assert _attrs_of_span(spans[1])["llm.token_count.total"]["intValue"] == 6 + child_attrs = _attrs_of_span(spans[2]) assert child_attrs["tool.name"]["stringValue"] == "exec_command" diff --git a/tests/tracing/codex/test_fidelity.py b/tests/tracing/codex/test_fidelity.py new file mode 100644 index 00000000..abb5a229 --- /dev/null +++ b/tests/tracing/codex/test_fidelity.py @@ -0,0 +1,431 @@ +"""Synthetic rollout regressions; no captured user content or backend calls.""" + +import json +from unittest.mock import patch + +from tracing.codex.hooks.handlers import _build_and_send_spans, _extract_turn_from_rollout + + +def record(kind, payload, second=0, **extra): + return {"type": kind, "timestamp": f"2026-10-21T00:00:{second:02d}Z", "payload": payload, **extra} + + +def write(tmp_path, records, session="s"): + path = tmp_path / f"rollout-test-{session}.jsonl" + path.write_text("\n".join(json.dumps(row) for row in records) + "\n") + return path + + +def attrs(span): + return {a["key"]: next(iter(a["value"].values())) for a in span["attributes"]} + + +def spans(turn): + sent = [] + with patch("tracing.codex.hooks.handlers.send_span_to_backend", side_effect=lambda p: sent.append(p) or True): + _build_and_send_spans("s", "t", turn) + return sent[0]["resourceSpans"][0]["scopeSpans"][0]["spans"] + + +def modern_records(): + usage = { + "input_tokens": 100, + "cached_input_tokens": 80, + "output_tokens": 5, + "reasoning_output_tokens": 2, + "cache_write_input_tokens": 0, + "total_tokens": 105, + } + return [ + record("session_meta", {"id": "s", "model_provider": "openai"}), + record("event_msg", {"type": "task_started", "turn_id": "t"}), + record("event_msg", {"type": "user_message", "message": "inspect a file"}), + record("response_item", {"type": "custom_tool_call", "name": "exec", "call_id": "c", "input": "tool code"}, 1), + record("token_usage_record", {"turn_id": "t", "response_id": "r1", "usage": usage}, 2), + record( + "event_msg", + { + "type": "item_completed", + "turn_id": "t", + "started_at_ms": 1792540803100, + "completed_at_ms": 1792540803200, + "item": { + "type": "CommandExecution", + "id": "exec-1", + "command": "cat missing", + "cwd": "/workspace", + "parsed_cmd": [], + "aggregated_output": "missing file", + "status": "completed", + "exit_code": 1, + "duration": {"secs": 0, "nanos": 100000000}, + }, + }, + 4, + ), + record( + "response_item", + {"type": "custom_tool_call_output", "call_id": "c", "output": [{"type": "text", "text": "result"}]}, + 4, + ), + record( + "event_msg", {"type": "token_count", "info": {"last_token_usage": usage, "total_token_usage": usage}}, 4 + ), + record("token_usage_record", {"turn_id": "t", "response_id": "r1", "usage": usage}, 4), + record( + "response_item", + {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "done"}]}, + 5, + ), + record("token_usage_record", {"turn_id": "t", "response_id": "r2", "usage": usage}, 6), + record("event_msg", {"type": "task_complete", "turn_id": "t", "last_agent_message": "done"}, 7), + ] + + +def test_response_usage_is_exact_and_not_duplicated(tmp_path): + turn = _extract_turn_from_rollout(write(tmp_path, modern_records()), "t") + assert len(turn["llm_calls"]) == 2 + assert turn["token_usage"]["total_tokens"] == 210 + output = spans(turn) + assert attrs(output[0])["openinference.span.kind"] == "CHAIN" + assert "llm.token_count.total" not in attrs(output[0]) + llms = [s for s in output if attrs(s)["openinference.span.kind"] == "LLM"] + assert [attrs(s)["llm.token_count.total"] for s in llms] == [105, 105] + assert attrs(llms[0])["llm.token_count.prompt_details.cache_read"] == 80 + assert attrs(llms[0])["llm.token_count.completion_details.reasoning"] == 2 + assert output == spans(turn) + + +def test_structured_commands_are_observed_tools(tmp_path, monkeypatch): + monkeypatch.setenv("ARIZE_LOG_TOOL_DETAILS", "true") + monkeypatch.setenv("ARIZE_LOG_TOOL_CONTENT", "true") + turn = _extract_turn_from_rollout(write(tmp_path, modern_records()), "t") + command = next(e for e in turn["tool_calls"] if e["call_id"] == "exec-1") + assert command["start_ts"] == 1792540803100 + assert command["end_ts"] == 1792540803200 + assert command["exit_code"] == 1 + output = spans(turn) + command_span = next(s for s in output if attrs(s).get("tool.id") == "exec-1") + wrapper = next(s for s in output if attrs(s).get("tool.id") == "c") + assert command_span["parentSpanId"] == wrapper["spanId"] + assert command_span["status"]["code"] == 2 + assert attrs(command_span)["tool.command"] == "cat missing" + assert attrs(command_span)["output.value"] == "missing file" + assert json.loads(attrs(wrapper)["output.value"]) == [{"text": "result", "type": "text"}] + + +def test_mismatched_completion_is_not_success(tmp_path): + rows = modern_records()[:4] + [record("event_msg", {"type": "task_complete", "turn_id": "other"}, 7)] + turn = _extract_turn_from_rollout(write(tmp_path, rows), "t") + assert turn["status"] == "unknown" + assert "missing_completion" in turn["diagnostics"] + assert spans(turn)[0]["status"]["code"] == 0 + + +def test_privacy_applies_to_tool_results_in_following_response(tmp_path, monkeypatch): + monkeypatch.setenv("ARIZE_LOG_PROMPTS", "true") + monkeypatch.setenv("ARIZE_LOG_TOOL_DETAILS", "false") + monkeypatch.setenv("ARIZE_LOG_TOOL_CONTENT", "false") + turn = _extract_turn_from_rollout(write(tmp_path, modern_records()), "t") + emitted = json.dumps(spans(turn)) + assert "inspect a file" in emitted + assert "cat missing" not in emitted + assert "tool code" not in emitted + assert "missing file" not in emitted + assert '"text": "result"' not in emitted + assert "= {"malformed_record", "invalid_response_usage", "malformed_item"} + assert spans(turn)[0]["status"]["code"] == 2 + + +def test_standalone_command_has_no_invented_response_parent(tmp_path): + rows = [modern_records()[1], modern_records()[5], modern_records()[-1]] + turn = _extract_turn_from_rollout(write(tmp_path, rows), "t") + assert turn["llm_calls"] == [] + from tracing.codex.hooks.graph import build_graph + + graph, _ = build_graph("s", "t", turn) + # A command alone cannot establish an LLM response. + assert len(graph.events) == 2 + assert graph.events[1].parent_event_id == graph.events[0].event_id + assert "command_parent_unobserved" in turn["diagnostics"] + + +def native_rows(session, turn, parent=None, parent_turn=None, spawn=None): + meta = {"id": session, "model_provider": "openai"} + attr = {} + if parent: + meta.update( + source={"subagent": {"thread_spawn": {"parent_thread_id": parent}}}, + forked_from_id=parent, + subagent_history_start_ordinal=10, + ) + attr["parent_turn_id"] = parent_turn + rows = [record("session_meta", meta)] + if parent: + # This copied parent turn must never become a child trace. + rows += [ + record("session_meta", {"id": parent}), + record("event_msg", {"type": "task_started", "turn_id": "inherited"}, ordinal=1), + record("event_msg", {"type": "task_complete", "turn_id": "inherited"}, ordinal=2), + ] + rows.append(record("event_msg", {"type": "task_started", "turn_id": turn, "turn_attribution": attr}, ordinal=10)) + if spawn: + rows += [ + record( + "response_item", + {"type": "function_call", "name": "spawn_agent", "call_id": "spawn", "arguments": "{}"}, + 1, + ordinal=11, + ), + record( + "response_item", + {"type": "function_call_output", "call_id": "spawn", "output": {"agent_id": spawn}}, + 2, + ordinal=12, + ), + ] + rows += [ + record( + "response_item", + {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "complete"}]}, + 3, + ordinal=13, + ), + record( + "token_usage_record", + { + "turn_id": turn, + "response_id": f"r-{turn}", + "usage": {"input_tokens": 4, "output_tokens": 1, "total_tokens": 5}, + }, + 4, + ordinal=14, + ), + record("event_msg", {"type": "task_complete", "turn_id": turn}, 5, ordinal=15), + ] + return rows + + +def test_nested_child_lineage_and_duplicate_notify(tmp_path, monkeypatch): + from tracing.codex.hooks import handlers + from tracing.codex.hooks.graph import stable_id + from tracing.codex.hooks.lineage import child_turns + + monkeypatch.setattr("tracing.codex.hooks.delivery._STATE_DIR", tmp_path / "receipts") + parent_path = write(tmp_path, native_rows("parent", "pt", spawn="child"), "parent") + child_path = write(tmp_path, native_rows("child", "ct", "parent", "pt", spawn="grandchild"), "child") + grand_path = write(tmp_path, native_rows("grandchild", "gt", "child", "ct"), "grandchild") + paths = {"parent": parent_path, "child": child_path, "grandchild": grand_path} + monkeypatch.setattr(handlers, "_find_rollout_file", paths.get) + assert _extract_turn_from_rollout(child_path, "inherited") is None + assert child_turns(child_path, "parent", "pt") == ["ct"] + sent = [] + monkeypatch.setattr(handlers, "send_span_to_backend", lambda payload: sent.append(payload) or True) + handlers._handle_notify({"type": "agent-turn-complete", "thread-id": "parent", "turn-id": "pt"}) + assert len(sent) == 3 + all_spans = [s for p in sent for s in p["resourceSpans"][0]["scopeSpans"][0]["spans"]] + assert len({s["traceId"] for s in all_spans}) == 1 + by_id = {s["spanId"]: s for s in all_spans} + child_turn = by_id[stable_id("turn:child:ct")] + child_agent = by_id[child_turn["parentSpanId"]] + assert attrs(child_agent)["openinference.span.kind"] == "AGENT" + assert child_agent["parentSpanId"] == stable_id("turn:parent:pt") + grand_turn = by_id[stable_id("turn:grandchild:gt")] + assert by_id[grand_turn["parentSpanId"]]["parentSpanId"] == child_turn["spanId"] + assert sum(attrs(s).get("llm.token_count.total", 0) for s in all_spans) == 15 + handlers._handle_notify({"type": "agent-turn-complete", "thread-id": "child", "turn-id": "ct"}) + handlers._handle_notify({"type": "agent-turn-complete", "thread-id": "parent", "turn-id": "pt"}) + assert len(sent) == 3 + + +def test_parent_missing_is_diagnostic_and_never_invented(tmp_path): + from tracing.codex.hooks.lineage import context + + turn = _extract_turn_from_rollout(write(tmp_path, native_rows("child", "ct", "absent", "pt")), "ct") + _, agents = context("child", "ct", turn, lambda _: None) + assert not agents + assert "parent_span_id" not in turn + assert "parent_turn_unavailable" in turn["diagnostics"] + + +def test_background_child_can_finish_after_parent(tmp_path, monkeypatch): + from tracing.codex.hooks import handlers + + monkeypatch.setattr("tracing.codex.hooks.delivery._STATE_DIR", tmp_path / "receipts") + p = write(tmp_path, native_rows("parent", "pt", spawn="child"), "parent") + child_rows = native_rows("child", "ct", "parent", "pt") + c = write(tmp_path, child_rows[:-1], "child") + monkeypatch.setattr(handlers, "_find_rollout_file", {"parent": p, "child": c}.get) + sent = [] + monkeypatch.setattr(handlers, "send_span_to_backend", lambda payload: sent.append(payload) or True) + handlers._handle_notify({"type": "agent-turn-complete", "thread-id": "parent", "turn-id": "pt"}) + before = sent[-1]["resourceSpans"][0]["scopeSpans"][0]["spans"] + write(tmp_path, child_rows, "child") + handlers._handle_notify({"type": "agent-turn-complete", "thread-id": "child", "turn-id": "ct"}) + after = sent[-1]["resourceSpans"][0]["scopeSpans"][0]["spans"] + assert len(sent) == 3 + before_root = next(s for s in before if attrs(s).get("openinference.span.kind") == "CHAIN") + after_root = next(s for s in after if attrs(s).get("openinference.span.kind") == "CHAIN") + assert before_root["spanId"] == after_root["spanId"] + assert before_root["status"]["code"] == 0 + assert after_root["status"]["code"] == 1 + + +def test_reader_rejects_symlinks_and_enforces_limits(tmp_path, monkeypatch): + import pytest + + from tracing.codex.hooks import transcript + + target = write(tmp_path, modern_records()) + alias = tmp_path / "alias.jsonl" + alias.symlink_to(target) + with pytest.raises(OSError): + with transcript._open_regular_text(alias) as handle: + list(handle) + monkeypatch.setattr(transcript, "_MAX_ROLLOUT_BYTES", 10) + with pytest.raises(OSError): + with transcript._open_regular_text(target) as handle: + list(handle) + monkeypatch.setattr(transcript, "_MAX_ROLLOUT_BYTES", 1 << 20) + monkeypatch.setattr(transcript, "_MAX_ROLLOUT_LINE_BYTES", 10) + with pytest.raises(OSError): + with transcript._open_regular_text(target) as handle: + list(handle) + + +def test_direct_command_observations_do_not_duplicate_tool(tmp_path): + rows = modern_records() + rows[3]["payload"] = { + "type": "function_call", + "name": "exec_command", + "call_id": "c", + "arguments": '{"cmd":"cat missing"}', + } + rows[6]["payload"] = { + "type": "function_call_output", + "call_id": "c", + "output": "Process exited with code 1\nmissing file", + } + turn = _extract_turn_from_rollout(write(tmp_path, rows), "t") + assert len(turn["tool_calls"]) == 1 + assert turn["tool_calls"][0]["status"] == "failed" + assert turn["tool_calls"][0]["start_ts"] == 1792540803100 diff --git a/tracing/codex/README.md b/tracing/codex/README.md index e5536693..9bfd3c18 100644 --- a/tracing/codex/README.md +++ b/tracing/codex/README.md @@ -1,122 +1,107 @@ -# Codex CLI Tracing +# Codex CLI tracing -Automatic [OpenInference](https://github.com/Arize-ai/openinference) tracing for the OpenAI Codex CLI. Spans are exported to [Arize AX](https://arize.com) or [Phoenix](https://github.com/Arize-ai/phoenix). +OpenInference traces for Codex CLI, exported to Phoenix or Arize AX. This is the +[lifldev fork](https://github.com/lifldev/coding-harness-tracing) of +[Arize's coding-harness-tracing](https://github.com/Arize-ai/coding-harness-tracing). +The bounded rollout reader incorporates prior art from upstream +[PR #114](https://github.com/Arize-ai/coding-harness-tracing/pull/114). ## Setup -The installer prompts for your backend (Phoenix or Arize AX) and project name, writes credentials to `~/.arize/harness/config.json`, and registers the hook entries plus the `notify` token-usage backstop in `~/.codex/config.toml`. After installing, approve the hooks via Codex's `/hooks` command (one time per user account). -Pass `--with-skills` to also symlink the `manage-codex-tracing` skill into the current directory's `.agents/skills/` so coding agents in this workspace can help manage Codex tracing configuration. - -### Remote setup - -#### macOS / Linux - -Install: - -```bash -curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.sh | bash -s -- codex -``` - -Uninstall: - -```bash -curl -sSL https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.sh | bash -s -- uninstall codex -``` - -#### Windows (PowerShell) - -Install: - -```powershell -iwr -useb https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.bat -OutFile $env:TEMP\install.bat -& $env:TEMP\install.bat codex -``` - -Uninstall: - -```powershell -iwr -useb https://raw.githubusercontent.com/Arize-ai/coding-harness-tracing/main/install.bat -OutFile $env:TEMP\install.bat -& $env:TEMP\install.bat uninstall codex -``` - -### Local setup - -```bash -git clone https://github.com/Arize-ai/coding-harness-tracing.git -cd coding-harness-tracing -``` - -**macOS / Linux** - -Install: +From a local checkout: ```bash ./install.sh codex ``` -Uninstall: +Or install the fork: ```bash -./install.sh uninstall codex -``` - -**Windows (PowerShell)** - -Install: - -```powershell -install.bat codex +curl -sSL https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.sh | bash -s -- codex ``` -Uninstall: +Windows: ```powershell -install.bat uninstall codex -``` - -## Default Settings - -| Setting | Default | -|---------|---------| -| Harness key | `codex` | -| Project name | `codex` | -| Phoenix endpoint | `http://localhost:6006` | -| Arize AX endpoint | `otlp.arize.com:443` | -| Hook config file | `~/.codex/config.toml` | -| Hook events handled | `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PermissionRequest`, `Stop` (via real Codex hooks); `agent-turn-complete` (via `notify`) for token usage | -| Env override file | `~/.codex/arize-env.sh` | -| State directory | `~/.arize/harness/state/codex/` (state files + tool span JSONLs) | -| Log file | `~/.arize/harness/logs/codex.log` | - -## Trust prompt - -Codex requires explicit user trust for non-managed hooks before they fire. After install, run: - -1. `codex` (start a session) -2. Type `/hooks` and approve each `arize-hook-codex-*` entry. - -Without this one-time approval, hooks won't fire and traces will be limited to the `notify`-based fallback (single LLM span per turn, no tool spans). - -## Verifying tracing - -Run any Codex command: - -```bash -codex exec "explain what this file does" path/to/file.py +iwr -useb https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.bat -OutFile $env:TEMP\install.bat +& $env:TEMP\install.bat codex ``` -Then check: - -- Hook activity in `~/.arize/harness/logs/codex.log`. -- Per-thread state files in `~/.arize/harness/state/codex/` show recent activity. -- Spans appear in your configured project in Arize AX or Phoenix. - -Errors are always logged. For routine hook activity, add `export ARIZE_VERBOSE=true` to `~/.codex/arize-env.sh` (or your shell) and re-run. See the [main README's Environment variables section](../../README.md#environment-variables) for the full list of runtime overrides (`ARIZE_TRACE_ENABLED`, `ARIZE_DRY_RUN`, `ARIZE_TRACE_DEBUG`, etc.). - -## Troubleshooting - -**Hooks not firing.** Run `codex` → `/hooks` and confirm the `arize-hook-codex-*` entries are listed and trusted. If they aren't listed at all, re-run the installer. - -**No spans appear.** Re-source your shell profile (or open a new terminal) so `~/.codex/arize-env.sh` is loaded. Check `~/.arize/harness/logs/codex.log` for backend/auth errors. Confirm the hooks are trusted via `/hooks`. - -**Disable temporarily.** Untrust the entries via `codex` → `/hooks`, or set `ARIZE_TRACE_ENABLED=false` in `~/.codex/arize-env.sh` and restart Codex. Full uninstall: `./install.sh uninstall codex`. +The installer prompts for the backend, project and content-logging preferences, +then registers `arize-hook-codex-notify` in Codex's `notify` configuration. +This exporter uses `agent-turn-complete` notifications and persisted rollout +JSONL; lifecycle hooks and `/hooks` trust are not required. Existing unrelated +hooks are preserved. `--with-skills` also links the management skill. + +`CODEX_HOME` selects the Codex configuration and sessions directory; otherwise +`~/.codex` is used. An explicit home must already exist. Backend configuration is +stored in `~/.arize/harness/config.json`; the optional env override file is +`$CODEX_HOME/arize-env.sh` (default `~/.codex/arize-env.sh`). + +Uninstall with `./install.sh uninstall codex` or `install.bat uninstall codex`. + +## Trace contract + +Each observed turn has a **CHAIN** root. Individual model responses are **LLM** +children; function, custom, web, discovery, local-shell and image-generation +calls are represented separately. Code-mode `exec` is a CHAIN container with +actual observed `CommandExecution` TOOL children named `exec_command`. +JavaScript source alone never establishes that an inner tool executed. + +`token_usage_record.response_id` identifies exact response usage. Its `usage` +is counted once, ignoring duplicate records and legacy token-count broadcasts +for that turn. Older formats use distinct `token_count` snapshots to close +observed response cycles. Input tokens already include cached input; cache and +reasoning are details, never added again. Only LLM spans carry OpenInference +token counts; the turn root carries no duplicate token totals. Observed zero +counts are retained and unknown fields are omitted. + +Command lifecycle timestamps, exit codes, outputs and reported durations are +preserved. Nonzero exits are errors. Response timestamps describe persisted +observations, not provider request latency. Tools without lifecycle timing use +persisted item times. Missing results/completion remain unknown; aborted turns +are errors. Malformed input and ambiguous associations produce diagnostics +instead of fabricated success or parents. + +Native subagent relationships require both +`session_meta.source.subagent.thread_spawn.parent_thread_id` and authoritative +`turn_attribution.parent_turn_id`. Copied history is excluded using the child's +`subagent_history_start_ordinal`. Known spawned child IDs can be replayed at the +parent's notification; nested and background children can also notify later. +The exporter does not infer native lineage from agent names, prompts or Orca +worker dispatch messages. + +IDs are deterministic. Successful per-span delivery hashes are stored under +`~/.arize/harness/state/codex/delivery/` behind a file lock, so repeated notify +callbacks skip unchanged spans and failed sends remain retryable. A later +completion updates the same span IDs. A transport timeout after backend +acceptance can still cause a retry; this is not an exactly-once network guarantee. +Dry runs do not write successful-delivery receipts. + +## Privacy and limits + +- `ARIZE_LOG_PROMPTS` gates prompts and assistant text. +- `ARIZE_LOG_TOOL_DETAILS` gates arguments, commands and tool-specific details. +- `ARIZE_LOG_TOOL_CONTENT` gates results, including results copied into subsequent + model-input attributes. +- Structured binary image/audio blocks and built-in image results are omitted. + Encrypted reasoning is never exported. Enabled content is capped at 64 KiB + per attribute. Delivery receipts contain hashes, not transcript content. + +Reads are restricted to regular files, at most 64 MiB, 1 MiB per line and +200,000 records. Child replay is bounded to 64 observed turns and lineage depth +8. Ephemeral runs or missing rollouts produce an unknown CHAIN from notify data, +with no invented model usage or request timing. Forks without a trustworthy +history boundary cannot be reconstructed safely. Sessions that never notify +and whose child IDs are not observed are unavailable; there is no background +watcher or guessed thread discovery. Legacy rollouts lack exact response IDs +and request timings, so their response-cycle boundaries remain inferred. + +## Verification + +Inspect `~/.arize/harness/logs/codex.log` and the configured Phoenix or Arize +project after an authorized Codex run. `ARIZE_VERBOSE=true` enables routine +activity logging. `ARIZE_DRY_RUN=true` prevents backend sends. See the main +[environment variables](../../README.md#environment-variables) reference for +configuration details. A local parser replay verifies reconstruction only; +backend rendering and deployment need separate runtime evidence. diff --git a/tracing/codex/hooks/delivery.py b/tracing/codex/hooks/delivery.py new file mode 100644 index 00000000..d18026c9 --- /dev/null +++ b/tracing/codex/hooks/delivery.py @@ -0,0 +1,55 @@ +"""Successful-delivery receipts contain hashes only, never transcript content.""" + +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path + +from core.common import FileLock, env +from core.constants import STATE_BASE_DIR + +_STATE_DIR = STATE_BASE_DIR / "codex" / "delivery" + + +def deliver(payload: dict, send, state_dir: Path | None = None) -> bool: + spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"] + if not spans: + return False + if env.dry_run: + return send(payload) + root = Path(state_dir) if state_dir is not None else _STATE_DIR + key = hashlib.sha256(spans[0]["traceId"].encode()).hexdigest() + root.mkdir(parents=True, exist_ok=True, mode=0o700) + receipt = root / f"{key}.json" + # A timed-out lock must never remove another live notify's lock inode. + with FileLock(root / f"{key}.lock", break_on_timeout=False): + try: + previous = json.loads(receipt.read_text()) + if not isinstance(previous, dict): + previous = {} + except (OSError, ValueError): + previous = {} + hashes = {s["spanId"]: hashlib.sha256(json.dumps(s, sort_keys=True).encode()).hexdigest() for s in spans} + changed = [s for s in spans if previous.get(s["spanId"]) != hashes[s["spanId"]]] + if not changed: + return True + # Avoid mutating the caller's payload, so retry uses identical IDs/content. + envelope = dict(payload) + resource = dict(payload["resourceSpans"][0]) + scope = dict(resource["scopeSpans"][0]) + scope["spans"] = changed + resource["scopeSpans"] = [scope] + envelope["resourceSpans"] = [resource] + if not send(envelope): + return False + previous.update(hashes) + temp = receipt.with_suffix(f".{os.getpid()}.tmp") + try: + temp.write_text(json.dumps(previous, sort_keys=True)) + temp.chmod(0o600) + temp.replace(receipt) + finally: + temp.unlink(missing_ok=True) + return True diff --git a/tracing/codex/hooks/graph.py b/tracing/codex/hooks/graph.py new file mode 100644 index 00000000..c4cada72 --- /dev/null +++ b/tracing/codex/hooks/graph.py @@ -0,0 +1,327 @@ +"""Adapt Codex observations to the shared event model and OpenInference spans.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from core.common import build_multi_span, build_span, env, redact_content +from core.event_model import EventGraph, EventStatus, ModelCallEvent, ToolEvent, TurnEvent, Usage +from tracing.codex.hooks.adapter import SCOPE_NAME, SERVICE_NAME +from tracing.codex.hooks.transcript import text + +_MAX_CONTENT_CHARS = 64 * 1024 +TOKEN_ATTRS = ( + ("prompt_tokens", "llm.token_count.prompt"), + ("completion_tokens", "llm.token_count.completion"), + ("total_tokens", "llm.token_count.total"), + ("cached_input_tokens", "llm.token_count.prompt_details.cache_read"), + ("cache_write_input_tokens", "llm.token_count.prompt_details.cache_write"), + ("reasoning_output_tokens", "llm.token_count.completion_details.reasoning"), +) + + +def stable_id(*parts: str, size: int = 16) -> str: + return hashlib.sha256(json.dumps(parts, separators=(",", ":")).encode()).hexdigest()[:size] + + +def content(enabled: bool, value: object) -> str: + raw = text(_without_binary(value)) + if not enabled: + return redact_content(False, raw) + if len(raw) > _MAX_CONTENT_CHARS: + return raw[: _MAX_CONTENT_CHARS - 40] + "\n" + return raw + + +def _without_binary(value: object) -> object: + if isinstance(value, list): + return [_without_binary(item) for item in value] + if isinstance(value, dict): + kind = value.get("type") + if isinstance(kind, str) and any(part in kind.lower() for part in ("image", "audio")): + return {"type": kind, "content": ""} + return { + key: _without_binary(item) + for key, item in value.items() + if key not in ("encrypted_content", "b64_json", "base64", "image_url", "audio_url") + } + return value + + +def status(value: str) -> EventStatus: + try: + return EventStatus(value) + except ValueError: + return EventStatus.UNKNOWN + + +def build_graph(thread_id: str, turn_id: str, turn: dict) -> tuple[EventGraph, dict]: + root_id = f"turn:{thread_id}:{turn_id}" + graph = EventGraph() + observations: dict = {} + start, end = turn.get("turn_start_ms") or None, turn.get("turn_end_ms") or None + root = TurnEvent( + root_id, + thread_id, + turn_id, + 0, + start, + end, + status(turn.get("status", "unknown")), + input=turn.get("user_prompt"), + output=turn.get("assistant_output"), + ) + graph.events.append(root) + observations[root_id] = turn + calls = turn.get("llm_calls") or [] + if "llm_calls" not in turn and (turn.get("token_usage") or turn.get("tool_calls")): + calls = [ + { + "start_ts": start, + "end_ts": end, + "token_usage": turn.get("token_usage"), + "tool_calls": turn.get("tool_calls", []), + "assistant_output": turn.get("assistant_output"), + "input_parts": [{"kind": "prompt", "value": turn.get("user_prompt")}], + } + ] + tool_ids = {} + for number, call in enumerate(calls, 1): + rid = call.get("response_id") or str(number) + eid = f"response:{thread_id}:{turn_id}:{rid}" + tokens = call.get("token_usage") or {} + model_usage = ( + Usage( + input_tokens=tokens.get("prompt_tokens", 0), + output_tokens=tokens.get("completion_tokens", 0), + cache_read_tokens=tokens.get("cached_input_tokens", 0), + cache_write_tokens=tokens.get("cache_write_input_tokens", 0), + reported_total_tokens=tokens.get("total_tokens"), + ) + if tokens + else None + ) + graph.events.append( + ModelCallEvent( + eid, + thread_id, + turn_id, + len(graph.events), + call.get("start_ts"), + call.get("end_ts"), + status(call.get("status", "unknown")), + root_id, + input=call.get("input_parts"), + output=call.get("assistant_output"), + source_id=call.get("response_id") or None, + model=turn.get("model"), + usage=model_usage, + ) + ) + observations[eid] = call + for index, tool in enumerate(call.get("tool_calls") or []): + cid = tool.get("call_id") or f"{number}:{index}" + tid = f"tool:{thread_id}:{turn_id}:{cid}" + if tid in observations: + continue + tool_ids[cid] = tid + graph.events.append( + ToolEvent( + tid, + thread_id, + turn_id, + len(graph.events), + tool.get("start_ts"), + tool.get("end_ts"), + status(tool.get("status", "unknown")), + eid, + input=tool.get("args"), + output=tool.get("output"), + tool_call_id=cid, + tool_name=tool.get("tool"), + ) + ) + observations[tid] = tool + for event in graph.events: + parent_call = observations[event.event_id].get("parent_call_id") + if parent_call and parent_call in tool_ids: + event.parent_event_id = tool_ids[parent_call] + for index, tool in enumerate(turn.get("tool_calls") or []): + cid = tool.get("call_id") or f"unassigned:{index}" + tid = f"tool:{thread_id}:{turn_id}:{cid}" + if tid not in observations: + graph.events.append( + ToolEvent( + tid, + thread_id, + turn_id, + len(graph.events), + tool.get("start_ts"), + tool.get("end_ts"), + status(tool.get("status", "unknown")), + root_id, + input=tool.get("args"), + output=tool.get("output"), + tool_call_id=cid, + tool_name=tool.get("tool"), + ) + ) + observations[tid] = tool + graph.validate() + return graph, observations + + +def render_turn(thread_id: str, turn_id: str, turn: dict, identity) -> dict: + graph, observations = build_graph(thread_id, turn_id, turn) + trace_id = turn.get("trace_id") or stable_id("codex", thread_id, turn_id, size=32) + project = env.project_name_for(SERVICE_NAME) or "codex" + cwd = turn.get("cwd") or "" + llm_system, llm_provider = identity(turn.get("model"), turn.get("model_provider")) + payloads = [] + for event in graph.events: + obs = observations[event.event_id] + attrs: dict = { + "session.id": thread_id, + "codex.thread_id": thread_id, + "codex.turn_id": turn_id, + "project.name": project, + "codex.status": event.status.value, + } + if env.get_user_id(SERVICE_NAME): + attrs["user.id"] = env.get_user_id(SERVICE_NAME) + if cwd: + attrs["codex.cwd"] = cwd[:4096] + attrs["codex.workspace"] = Path(cwd).name[:4096] + if isinstance(event, TurnEvent): + kind, name = "CHAIN", f"Turn {turn.get('trace_count') or 1}" + attrs.update( + { + "trace.number": str(turn.get("trace_count") or 1), + "input.value": content(env.log_prompts, event.input), + "output.value": content(env.log_prompts, event.output), + } + ) + if turn.get("diagnostics"): + attrs["codex.diagnostics"] = json.dumps(turn["diagnostics"]) + # Identity and messages retain current main's indexed attributes. + attrs["llm.system"] = llm_system + if llm_provider: + attrs["llm.provider"] = llm_provider + for prefix, role, value in ( + ("llm.input_messages", "user", attrs["input.value"]), + ("llm.output_messages", "assistant", attrs["output.value"]), + ): + if value: + attrs[f"{prefix}.0.message.role"] = role + attrs[f"{prefix}.0.message.content"] = value + for source, target in ( + ("permission_mode", "codex.approval_mode"), + ("sandbox_mode", "codex.sandbox_mode"), + ("duration_ms", "codex.turn.duration_ms"), + ): + if turn.get(source) is not None and turn.get(source) != "": + attrs[target] = turn[source] + elif isinstance(event, ModelCallEvent): + kind, name = "LLM", f"LLM response: {event.source_id or event.sequence}" + parts = event.input or [] + attrs["input.value"] = content( + True, + "\n".join( + content(env.log_tool_content if p.get("kind") == "tool_output" else env.log_prompts, p.get("value")) + for p in parts + ), + ) + attrs["output.value"] = content(env.log_prompts, event.output) + attrs["codex.timing_source"] = "persisted_response_items" + attrs["llm.system"] = llm_system + if llm_provider: + attrs["llm.provider"] = llm_provider + if event.model: + attrs["llm.model_name"] = event.model + if event.source_id: + attrs["llm.message.id"] = event.source_id + for source, target in TOKEN_ATTRS: + if type((obs.get("token_usage") or {}).get(source)) is int: + attrs[target] = obs["token_usage"][source] + if obs.get("token_usage"): + attrs["codex.token_usage"] = json.dumps(obs["token_usage"]) + for index, part in enumerate(parts): + tool_result = part.get("kind") == "tool_output" + prefix = f"llm.input_messages.{index}.message" + attrs[f"{prefix}.role"] = "tool" if tool_result else "user" + attrs[f"{prefix}.content"] = content( + env.log_tool_content if tool_result else env.log_prompts, part.get("value") + ) + if part.get("call_id"): + attrs[f"{prefix}.tool_call_id"] = part["call_id"] + if attrs["output.value"]: + attrs["llm.output_messages.0.message.role"] = "assistant" + attrs["llm.output_messages.0.message.content"] = attrs["output.value"] + originated = [tool for tool in obs.get("tool_calls", []) if not tool.get("parent_call_id")] + for index, tool in enumerate(originated): + prefix = f"llm.output_messages.0.message.tool_calls.{index}.tool_call" + attrs["llm.output_messages.0.message.role"] = "assistant" + attrs[f"{prefix}.id"] = tool.get("call_id") or "" + attrs[f"{prefix}.function.name"] = tool.get("tool") or "unknown_tool" + attrs[f"{prefix}.function.arguments"] = content(env.log_tool_details, tool.get("args")) + else: + assert isinstance(event, ToolEvent) + kind, name = "TOOL", event.tool_name or "unknown_tool" + if obs.get("container"): + kind = "CHAIN" + attrs.update( + { + "tool.name": name, + "tool.id": event.tool_call_id, + "tool.call.id": event.tool_call_id, + "codex.tool.call_id": event.tool_call_id, + "input.value": content(env.log_tool_details, event.input), + "output.value": content(env.log_tool_content, event.output), + "codex.timing_source": obs.get("timing_source", "persisted_item"), + } + ) + args = event.input + if isinstance(args, str): + try: + args = json.loads(args) + except ValueError: + args = {} + if isinstance(args, dict): + for key, target in ( + ("command", "tool.command"), + ("cmd", "tool.command"), + ("cwd", "tool.cwd"), + ("url", "tool.url"), + ("query", "tool.query"), + ): + if key in args: + attrs[target] = content(env.log_tool_details, args[key]) + if type(obs.get("exit_code")) is int: + attrs["tool.exit_code"] = obs["exit_code"] + if isinstance(obs.get("duration"), dict): + attrs["codex.tool.observed_duration"] = json.dumps(obs["duration"]) + attrs["openinference.span.kind"] = kind + parent = stable_id(event.parent_event_id) if event.parent_event_id else turn.get("parent_span_id", "") + code = ( + 1 + if event.status == EventStatus.COMPLETED + else 2 if event.status in (EventStatus.FAILED, EventStatus.CANCELLED) else 0 + ) + payloads.append( + build_span( + name, + kind, + stable_id(event.event_id), + trace_id, + parent, + event.started_at_ms or 0, + event.ended_at_ms or event.started_at_ms or 0, + attrs, + SERVICE_NAME, + SCOPE_NAME, + status_code=code, + ) + ) + return build_multi_span(payloads, SERVICE_NAME, SCOPE_NAME) diff --git a/tracing/codex/hooks/handlers.py b/tracing/codex/hooks/handlers.py index ab24e217..64e0ea48 100644 --- a/tracing/codex/hooks/handlers.py +++ b/tracing/codex/hooks/handlers.py @@ -1,13 +1,9 @@ #!/usr/bin/env python3 """Codex notify handler -- rollout-JSONL-driven span emission. -Codex's `agent-turn-complete` notify callback is the only signal we listen -for. When it fires, we locate the session's rollout JSONL at -``~/.codex/sessions/YYYY/MM/DD/rollout--.jsonl`` and extract -the full turn's data: user prompt, assistant message, token usage, and every -tool call (shell, apply_patch, web_search, open_page) with structured args, -output, and timing. We then ship one OTLP payload with the parent LLM span -plus all TOOL child spans. +The agent-turn-complete callback replays bounded rollout observations as shared +typed events, then renders a CHAIN turn, individual LLM responses and tools. +Delivery receipts suppress duplicate callbacks without storing private content. """ from __future__ import annotations @@ -16,28 +12,26 @@ import os import re import sys -from datetime import datetime from pathlib import Path from core.common import ( - build_multi_span, build_span, - debug_dump, env, error, - generate_span_id, - generate_trace_id, - get_timestamp_ms, log, - redact_content, ) from core.common import send_span as send_span_to_backend from core.constants import MODEL_FAMILY_SYSTEMS from tracing.codex.constants import get_codex_home from tracing.codex.hooks.adapter import SCOPE_NAME, SERVICE_NAME, check_requirements, load_env_file +from tracing.codex.hooks.delivery import deliver +from tracing.codex.hooks.graph import content, render_turn, stable_id +from tracing.codex.hooks.lineage import child_turns, context +from tracing.codex.hooks.transcript import _extract_turn_from_rollout, _iso_to_ms, _open_regular_text # Root of Codex's per-session rollout transcripts. _CODEX_SESSIONS_ROOT = Path.home() / ".codex" / "sessions" +_SESSION_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$") # --------------------------------------------------------------------------- @@ -49,7 +43,7 @@ def _flex_get(d: dict, *keys, default: str = "") -> str: """Return the first non-empty value among `keys`, else `default`.""" for key in keys: val = d.get(key) - if val is not None and val != "": + if isinstance(val, str) and val: return val return default @@ -71,309 +65,32 @@ def _find_rollout_file(session_id: str, sessions_root: "Path | None" = None) -> root = get_codex_home() / "sessions" else: root = _CODEX_SESSIONS_ROOT - if not root.is_dir() or not session_id: + if not isinstance(session_id, str) or not _SESSION_ID_RE.fullmatch(session_id) or not root.is_dir(): return None try: + root_resolved = root.resolve() for path in root.rglob(f"rollout-*-{session_id}.jsonl"): - return path - except OSError: - return None - return None - - -# --------------------------------------------------------------------------- -# Rollout extraction -# --------------------------------------------------------------------------- - - -def _iso_to_ms(ts: str) -> int: - """Convert an ISO-8601 timestamp string (e.g. ``2026-05-20T23:42:45.649Z``) to ms. - - Returns 0 on any parse failure -- callers tolerate zero timestamps. - """ - if not ts: - return 0 - try: - # Python's fromisoformat doesn't accept the trailing Z prior to 3.11; - # normalize by swapping Z for +00:00 for compatibility. - normalized = ts.replace("Z", "+00:00") - dt = datetime.fromisoformat(normalized) - return int(dt.timestamp() * 1000) - except (ValueError, TypeError): - return 0 - - -def _extract_turn_from_rollout(rollout_path: Path, turn_id: str) -> "dict | None": - """Walk the rollout JSONL and extract everything for one turn. Returns None if the - turn isn't found.""" - if not turn_id or not rollout_path.is_file(): - return None - - codex_token_count_fields = ( - "input_tokens", - "output_tokens", - "total_tokens", - "cached_input_tokens", - "cache_write_input_tokens", - "reasoning_output_tokens", - ) - token_sums: dict = {k: 0 for k in codex_token_count_fields} - observed_fields: set = set() - prev_total_token_usage: "dict | None" = None - - in_turn = False - trace_count = 0 - turn_start_ms = 0 - turn_end_ms = 0 - duration_ms: "int | None" = None - user_prompt = "" - assistant_output = "" - model = "" - model_provider: "str | None" = None - cwd = "" - permission_mode = "" - sandbox_mode = "" - - tool_calls: list = [] - pending_func: dict = {} # call_id -> entry being filled - pending_custom: dict = {} # call_id -> Code Mode entry being filled - pending_search_end: "dict | None" = None # most recent unmatched web_search_end - - try: - with open(rollout_path, "r", encoding="utf-8") as f: - for line in f: - line = line.strip() - if not line: - continue - try: - obj = json.loads(line) - except json.JSONDecodeError: - continue - - outer = obj.get("type") - payload = obj.get("payload") or {} - ptype = payload.get("type") if isinstance(payload, dict) else None - ts_ms = _iso_to_ms(obj.get("timestamp", "")) - - # session_meta is the rollout's first record and carries the - # authoritative provider id for the whole session. It arrives - # before any task_started, so it must be read outside the - # in_turn gate below. - if outer == "session_meta" and isinstance(payload, dict): - model_provider = payload.get("model_provider") - continue - - # turn_context records carry per-turn settings (model, cwd, sandbox). - if outer == "turn_context" and isinstance(payload, dict): - if payload.get("turn_id") == turn_id: - model = payload.get("model") or model - cwd = payload.get("cwd") or cwd - permission_mode = payload.get("approval_policy") or permission_mode - sandbox_mode = (payload.get("sandbox_policy") or {}).get("type") or sandbox_mode - continue - - if outer != "event_msg" and outer != "response_item": - continue - - # Turn boundaries - if outer == "event_msg" and ptype == "task_started": - if in_turn: - # Next turn started after ours -- stop walking. - break - trace_count += 1 - if payload.get("turn_id") == turn_id: - in_turn = True - # started_at is unix seconds; convert to ms. - started_at = payload.get("started_at") - if isinstance(started_at, int): - turn_start_ms = started_at * 1000 - elif ts_ms: - turn_start_ms = ts_ms - continue - - if not in_turn: - continue - - # task_complete: final assistant message + accurate timing - if outer == "event_msg" and ptype == "task_complete": - msg = payload.get("last_agent_message") - if msg: - assistant_output = msg - # completed_at is unix seconds; convert to ms. - completed_at = payload.get("completed_at") - if isinstance(completed_at, int): - turn_end_ms = completed_at * 1000 - d = payload.get("duration_ms") - if isinstance(d, int): - duration_ms = d - continue - - # User prompt - if outer == "event_msg" and ptype == "user_message": - msg = payload.get("message") - if msg: - user_prompt = msg - continue - - # Intermediate assistant message (overwritten by task_complete if both present) - if outer == "event_msg" and ptype == "agent_message": - msg = payload.get("message") - if msg: - assistant_output = msg - continue - - # Token counts -- sum per-call deltas - if outer == "event_msg" and ptype == "token_count": - info = payload.get("info") or {} - total = info.get("total_token_usage") - # rate-limit-only rebroadcasts repeat the prior snapshot (openai/codex#14489) - if isinstance(total, dict) and total == prev_total_token_usage: + if path.is_symlink() or root_resolved not in path.resolve().parents: + continue + with _open_regular_text(path) as handle: + for line in handle: + try: + row = json.loads(line) + except ValueError: continue - if isinstance(total, dict): - prev_total_token_usage = total - last = info.get("last_token_usage") or {} - for k in codex_token_count_fields: - v = last.get(k) - if isinstance(v, int): - token_sums[k] += v - observed_fields.add(k) - continue - - # Shell / apply_patch tool call - if outer == "response_item" and ptype == "function_call": - call_id = payload.get("call_id") or "" - entry = { - "tool": payload.get("name") or "function_call", - "args": payload.get("arguments") or "", - "output": "", - "call_id": call_id, - "start_ts": ts_ms, - "end_ts": ts_ms, - "decision": None, - } - tool_calls.append(entry) - if call_id: - pending_func[call_id] = entry - continue - - if outer == "response_item" and ptype == "function_call_output": - call_id = payload.get("call_id") or "" - pending = pending_func.get(call_id) if call_id else None - if pending is not None: - pending["output"] = payload.get("output") or "" - pending["end_ts"] = ts_ms or pending["end_ts"] - continue - - # Code Mode exposes its outer exec invocation as a custom tool - # call rather than a function_call. Pair it with the durable - # output record by call_id so it is rendered like other tools. - if outer == "response_item" and ptype == "custom_tool_call": - call_id = payload.get("call_id") or "" - entry = { - "tool": payload.get("name") or "custom_tool_call", - "args": payload.get("input") or "", - "output": "", - "call_id": call_id, - "start_ts": ts_ms, - "end_ts": ts_ms, - "decision": None, - } - tool_calls.append(entry) - if call_id: - pending_custom[call_id] = entry - continue - - if outer == "response_item" and ptype == "custom_tool_call_output": - call_id = payload.get("call_id") or "" - pending = pending_custom.get(call_id) if call_id else None - if pending is not None: - pending["output"] = payload.get("output") or "" - pending["end_ts"] = ts_ms or pending["end_ts"] - continue - - # Web search: web_search_end (event_msg, has call_id) is paired with - # the next web_search_call (response_item) by emission order. - if outer == "event_msg" and ptype == "web_search_end": - pending_search_end = { - "call_id": payload.get("call_id") or "", - "ts_ms": ts_ms, - } - continue - - if outer == "response_item" and ptype == "web_search_call": - action = payload.get("action") or {} - action_type = action.get("type") or "search" - if action_type == "open_page": - tool_name = "open_page" - args = action.get("url") or "" - else: - tool_name = "web_search" - args = action.get("query") or "" - start_ts = ts_ms - call_id = "" - if pending_search_end is not None: - call_id = pending_search_end["call_id"] - start_ts = pending_search_end["ts_ms"] or start_ts - pending_search_end = None - tool_calls.append( - { - "tool": tool_name, - "args": args, - "output": payload.get("status") or "", - "call_id": call_id, - "start_ts": start_ts, - "end_ts": ts_ms, - "decision": None, - } - ) - continue - except OSError: - return None - - if not in_turn: + if not isinstance(row, dict) or row.get("type") != "session_meta": + continue + meta = row.get("payload") + if not isinstance(meta, dict) or meta.get("id") != session_id: + break + return path + else: + # Older formats may have no metadata; the literal filename + # still identifies the requested session. + return path + except (OSError, UnicodeError, RuntimeError): return None - - if not turn_end_ms: - candidates = [e["end_ts"] for e in tool_calls if e.get("end_ts")] - turn_end_ms = max(candidates) if candidates else turn_start_ms - - token_usage: "dict | None" = None - if observed_fields: - token_usage = {"model": model or ""} - codex_token_count_to_token_usage = { - "input_tokens": "prompt_tokens", - "output_tokens": "completion_tokens", - "total_tokens": "total_tokens", - "cached_input_tokens": "cached_input_tokens", - "cache_write_input_tokens": "cache_write_input_tokens", - "reasoning_output_tokens": "reasoning_output_tokens", - } - for field, key in codex_token_count_to_token_usage.items(): - if field in observed_fields: - token_usage[key] = token_sums[field] - # Codex derives non_cached_input_tokens rather than serializing it - # we do the same, but only when BOTH input and cached are observed - # otherwise, we'd be fabricating a number from unknown cache data - if "input_tokens" in observed_fields and "cached_input_tokens" in observed_fields: - token_usage["non_cached_input_tokens"] = max( - token_sums["input_tokens"] - token_sums["cached_input_tokens"], 0 - ) - - return { - "trace_count": trace_count, - "turn_start_ms": turn_start_ms or get_timestamp_ms(), - "turn_end_ms": turn_end_ms or get_timestamp_ms(), - "duration_ms": duration_ms, - "user_prompt": user_prompt, - "assistant_output": assistant_output, - "model": model, - "model_provider": model_provider, - "cwd": cwd, - "permission_mode": permission_mode, - "sandbox_mode": sandbox_mode, - "token_usage": token_usage, - "tool_calls": tool_calls, - } + return None # --------------------------------------------------------------------------- @@ -436,139 +153,13 @@ def _put_indexed_message(attrs: dict, prefix: str, role: str, content: str) -> N def _build_and_send_spans(thread_id: str, turn_id: str, turn: dict) -> None: - """Assemble the LLM + TOOL spans from an extracted turn and ship them.""" - project_name = env.project_name_for(SERVICE_NAME) or "codex" - user_id = env.get_user_id(SERVICE_NAME) or "" - - trace_id = generate_trace_id() - parent_span_id = generate_span_id() - - user_prompt = redact_content(env.log_prompts, turn.get("user_prompt") or "") - assistant_output = redact_content(env.log_prompts, turn.get("assistant_output") or "") - final_output = assistant_output or "(No response)" - cwd = turn.get("cwd") or "" - workspace = Path(cwd).name if cwd else "" - - attrs: dict = { - "session.id": thread_id, - "trace.number": str(turn.get("trace_count") or 1), - "project.name": project_name, - "openinference.span.kind": "LLM", - "input.value": user_prompt, - "output.value": final_output, - "codex.thread_id": thread_id, - } - if cwd: - attrs["codex.cwd"] = cwd - if workspace: - attrs["codex.workspace"] = workspace - if turn_id: - attrs["codex.turn_id"] = turn_id - if user_id: - attrs["user.id"] = user_id - if turn.get("model"): - attrs["llm.model_name"] = turn["model"] - if turn.get("permission_mode"): - attrs["codex.approval_mode"] = turn["permission_mode"] - if turn.get("sandbox_mode"): - attrs["codex.sandbox_mode"] = turn["sandbox_mode"] - if turn.get("duration_ms") is not None: - attrs["codex.turn.duration_ms"] = turn["duration_ms"] - - llm_system, llm_provider = _llm_identity(turn.get("model"), turn.get("model_provider")) - attrs["llm.system"] = llm_system - if llm_provider: - attrs["llm.provider"] = llm_provider - - _put_indexed_message(attrs, "llm.input_messages", "user", user_prompt) - _put_indexed_message(attrs, "llm.output_messages", "assistant", assistant_output) - - usage = turn.get("token_usage") or {} - for src, dst in ( - ("prompt_tokens", "llm.token_count.prompt"), - ("completion_tokens", "llm.token_count.completion"), - ("total_tokens", "llm.token_count.total"), - ): - v = usage.get(src) - if isinstance(v, int): - attrs[dst] = v - # map the token_usage keys to the OpenInference attribute names - for src, dst in ( - ("cached_input_tokens", "llm.token_count.prompt_details.cache_read"), - ("cache_write_input_tokens", "llm.token_count.prompt_details.cache_write"), - ("reasoning_output_tokens", "llm.token_count.completion_details.reasoning"), - ): - v = usage.get(src) - if isinstance(v, int): - attrs[dst] = v - if usage: - attrs["codex.token_usage"] = json.dumps(usage) - - child_spans: list = [] - for entry in turn.get("tool_calls") or []: - tool_name = entry.get("tool") or "unknown_tool" - args_raw = entry.get("args") or "" - output_raw = entry.get("output") or "" - tool_attrs: dict = { - "openinference.span.kind": "TOOL", - "tool.name": tool_name, - "input.value": redact_content(env.log_tool_details, args_raw), - "output.value": redact_content(env.log_tool_content, output_raw), - "session.id": thread_id, - } - if cwd: - tool_attrs["codex.cwd"] = cwd - if workspace: - tool_attrs["codex.workspace"] = workspace - if entry.get("call_id"): - tool_attrs["tool.id"] = entry["call_id"] - tool_attrs["codex.tool.call_id"] = entry["call_id"] - child_start = entry.get("start_ts") or turn["turn_start_ms"] - child_end = entry.get("end_ts") or child_start - child = build_span( - tool_name, - "TOOL", - generate_span_id(), - trace_id, - parent_span_id, - child_start, - child_end, - tool_attrs, - SERVICE_NAME, - SCOPE_NAME, - ) - child_spans.append(child) - - parent_span = build_span( - f"Turn {turn.get('trace_count') or 1}", - "LLM", - parent_span_id, - trace_id, - "", - turn["turn_start_ms"], - turn["turn_end_ms"], - attrs, - SERVICE_NAME, - SCOPE_NAME, - ) - - debug_dump(f"notify_{thread_id}_parent_span", parent_span) - - if child_spans: - payload = build_multi_span([parent_span] + child_spans, SERVICE_NAME, SCOPE_NAME) - debug_dump(f"notify_{thread_id}_multi_span", payload) - else: - payload = parent_span - + payload = render_turn(thread_id, turn_id, turn, _llm_identity) if not send_span_to_backend(payload): - error("Failed to send span to backend") - else: - log(f"Turn sent (thread={thread_id}, turn={turn_id}, children={len(child_spans)})") + error("Failed to send Codex turn") def _send_legacy_single_span(thread_id: str, turn_id: str, input_json: dict) -> None: - """Fallback when no rollout file or turn is found - emit a single LLM span from - the notify payload alone.""" + """Represent unavailable rollout data as an unknown CHAIN observation.""" assistant_msg = ( input_json.get("last-assistant-message") or input_json.get("last_assistant_message") @@ -604,23 +195,24 @@ def _send_legacy_single_span(thread_id: str, turn_id: str, input_json: dict) -> elif isinstance(user_msgs, str): user_prompt = user_msgs - user_prompt = redact_content(env.log_prompts, user_prompt) - assistant_output = redact_content(env.log_prompts, assistant_msg if isinstance(assistant_msg, str) else "") - final_output = assistant_output or "(No response)" + user_prompt = content(env.log_prompts, user_prompt) + assistant_output = content(env.log_prompts, assistant_msg if isinstance(assistant_msg, str) else "") + final_output = assistant_output - trace_id = generate_trace_id() - span_id = generate_span_id() - now = get_timestamp_ms() + trace_id = stable_id("codex", thread_id, turn_id, size=32) + span_id = stable_id(f"turn:{thread_id}:{turn_id}") + now = _iso_to_ms(input_json.get("timestamp")) attrs = { "session.id": thread_id, "project.name": env.project_name_for(SERVICE_NAME) or "codex", - "openinference.span.kind": "LLM", + "openinference.span.kind": "CHAIN", "input.value": user_prompt, "output.value": final_output, "codex.thread_id": thread_id, "codex.turn_id": turn_id, "codex.notify_fallback": "true", + "codex.diagnostics": '["rollout_unavailable"]', # No rollout here, so the real model/provider is unknown. "llm.system": "codex", } @@ -632,7 +224,7 @@ def _send_legacy_single_span(thread_id: str, turn_id: str, input_json: dict) -> parent_span = build_span( "Turn", - "LLM", + "CHAIN", span_id, trace_id, "", @@ -641,9 +233,9 @@ def _send_legacy_single_span(thread_id: str, turn_id: str, input_json: dict) -> attrs, SERVICE_NAME, SCOPE_NAME, + status_code=0, ) - debug_dump(f"notify_fallback_{thread_id}_{turn_id}_span", parent_span) - if not send_span_to_backend(parent_span): + if not deliver(parent_span, send_span_to_backend): error("Failed to send fallback span to backend") else: log(f"Turn sent via fallback (thread={thread_id}, turn={turn_id})") @@ -656,14 +248,15 @@ def _send_legacy_single_span(thread_id: str, turn_id: str, input_json: dict) -> def _handle_notify(input_json: dict) -> None: """Handle one Codex notify event.""" - if input_json.get("type") != "agent-turn-complete": - log(f"Ignoring event type: {input_json.get('type')}") + if not isinstance(input_json, dict) or input_json.get("type") != "agent-turn-complete": return thread_id = _flex_get(input_json, "thread-id", "thread_id", "threadId") turn_id = _flex_get(input_json, "turn-id", "turn_id", "turnId") - debug_dump(f"notify_{thread_id or 'unknown'}_{turn_id or 'unknown'}_raw", input_json) + if not _SESSION_ID_RE.fullmatch(thread_id) or not _SESSION_ID_RE.fullmatch(turn_id): + error("Codex notify missing or invalid thread/turn identity") + return rollout_path = _find_rollout_file(thread_id) if rollout_path is None: @@ -677,8 +270,31 @@ def _handle_notify(input_json: dict) -> None: _send_legacy_single_span(thread_id, turn_id, input_json) return - debug_dump(f"notify_{thread_id}_{turn_id}_extracted", turn) - _build_and_send_spans(thread_id, turn_id, turn) + _export_observed_turn(thread_id, turn_id, turn, set()) + + +def _export_observed_turn(thread_id: str, turn_id: str, turn: dict, visited: set) -> None: + if (thread_id, turn_id) in visited or len(visited) >= 64: + return + visited.add((thread_id, turn_id)) + _, agent_payloads = context(thread_id, turn_id, turn, _find_rollout_file) + payload = render_turn(thread_id, turn_id, turn, _llm_identity) + for agent in agent_payloads: + payload["resourceSpans"][0]["scopeSpans"][0]["spans"].insert( + 0, agent["resourceSpans"][0]["scopeSpans"][0]["spans"][0] + ) + if not deliver(payload, send_span_to_backend): + error("Failed to deliver observed Codex turn") + # Child IDs must be observed in structured spawn results/activity, then + # independently confirmed against native child metadata and attribution. + for child_id in sorted(set(turn.get("child_thread_ids", [])))[:64]: + path = _find_rollout_file(child_id) + if path is None: + continue + for child_turn_id in child_turns(path, thread_id, turn_id): + child = _extract_turn_from_rollout(path, child_turn_id) + if child is not None: + _export_observed_turn(child_id, child_turn_id, child, visited) # --------------------------------------------------------------------------- diff --git a/tracing/codex/hooks/lineage.py b/tracing/codex/hooks/lineage.py new file mode 100644 index 00000000..059aa767 --- /dev/null +++ b/tracing/codex/hooks/lineage.py @@ -0,0 +1,98 @@ +"""Native Codex lineage verified against child metadata and turn attribution.""" + +from __future__ import annotations + +from pathlib import Path + +from core.common import build_span +from tracing.codex.hooks.adapter import SCOPE_NAME, SERVICE_NAME +from tracing.codex.hooks.graph import stable_id +from tracing.codex.hooks.transcript import _extract_turn_from_rollout, own_rows, records, session_metadata + +_MAX_DEPTH = 8 +_MAX_CHILD_TURNS = 64 + + +def native_parent(meta: dict) -> str: + source = meta.get("source") + if not isinstance(source, dict): + return "" + subagent = source.get("subagent") + spawn = subagent.get("thread_spawn") if isinstance(subagent, dict) else None + parent = spawn.get("parent_thread_id") if isinstance(spawn, dict) else None + return parent if isinstance(parent, str) else "" + + +def context(thread_id: str, turn_id: str, turn: dict, find, visited=()) -> tuple[str, list]: + local_trace = stable_id("codex", thread_id, turn_id, size=32) + meta = turn.get("session_meta") or {} + parent = native_parent(meta) + attribution = turn.get("turn_attribution") or {} + parent_turn = attribution.get("parent_turn_id") + if not parent: + return local_trace, [] + if not isinstance(parent_turn, str) or not parent_turn: + turn.setdefault("diagnostics", []).append("missing_parent_turn_attribution") + return local_trace, [] + if thread_id in visited or parent in (*visited, thread_id) or len(visited) >= _MAX_DEPTH: + turn.setdefault("diagnostics", []).append("lineage_cycle_or_depth_limit") + return local_trace, [] + path = find(parent) + parent_data = _extract_turn_from_rollout(path, parent_turn) if path else None + if parent_data is None: + turn.setdefault("diagnostics", []).append("parent_turn_unavailable") + return local_trace, [] + parent_meta = parent_data.get("session_meta") or {} + if parent_meta.get("id") != parent: + turn.setdefault("diagnostics", []).append("parent_metadata_mismatch") + return local_trace, [] + trace, _ = context(parent, parent_turn, parent_data, find, (*visited, thread_id)) + if "lineage_cycle_or_depth_limit" in parent_data.get("diagnostics", []): + turn.setdefault("diagnostics", []).append("lineage_cycle_or_depth_limit") + return local_trace, [] + agent_id = stable_id(f"agent:{thread_id}:{turn_id}") + parent_span_id = stable_id(f"turn:{parent}:{parent_turn}") + turn["parent_span_id"] = agent_id + turn["trace_id"] = trace + attrs = { + "openinference.span.kind": "AGENT", + "session.id": thread_id, + "subagent.id": thread_id, + "codex.parent_thread_id": parent, + "codex.parent_turn_id": parent_turn, + "codex.lineage_source": "session_meta.source.subagent.thread_spawn+turn_attribution", + } + agent = build_span( + "Codex subagent", + "AGENT", + agent_id, + trace, + parent_span_id, + turn.get("turn_start_ms") or 0, + turn.get("turn_end_ms") or 0, + attrs, + SERVICE_NAME, + SCOPE_NAME, + status_code=0, + ) + # Ancestors are emitted by their own turn export; emitting them with a child's + # end time would invent the parent's duration and overwrite better evidence. + return trace, [agent] + + +def child_turns(path: Path, parent_thread: str, parent_turn: str) -> list[str]: + rows = records(path, []) + meta = session_metadata(rows) + if native_parent(meta) != parent_thread: + return [] + result = [] + for row in own_rows(rows, meta): + p = row["payload"] + if row.get("type") != "event_msg" or p.get("type") not in ("task_started", "turn_started"): + continue + attr = p.get("turn_attribution") + if isinstance(attr, dict) and attr.get("parent_turn_id") == parent_turn and isinstance(p.get("turn_id"), str): + result.append(p["turn_id"]) + if len(result) >= _MAX_CHILD_TURNS: + break + return result diff --git a/tracing/codex/hooks/transcript.py b/tracing/codex/hooks/transcript.py new file mode 100644 index 00000000..56903682 --- /dev/null +++ b/tracing/codex/hooks/transcript.py @@ -0,0 +1,542 @@ +"""Bounded, fail-soft reconstruction of persisted Codex observations. + +The regular-file reader is adapted from upstream PR #114. Response timestamps +are observed persistence boundaries, never fabricated provider request times. +""" + +from __future__ import annotations + +import json +import os +import re +import stat +from contextlib import contextmanager +from datetime import datetime +from pathlib import Path +from typing import Iterator + +# Reading is streamed, but hard budgets keep notify latency and memory bounded +# for malformed, very large, or concurrently growing rollout files. +_MAX_ROLLOUT_BYTES = 64 << 20 # 64 MiB +_MAX_ROLLOUT_LINE_BYTES = 1 << 20 # 1 MiB +_MAX_ROLLOUT_RECORDS = 200_000 + + +# --------------------------------------------------------------------------- +# Rollout extraction +# --------------------------------------------------------------------------- + + +@contextmanager +def _open_regular_text(path: Path) -> Iterator[Iterator[str]]: + """Yield bounded UTF-8 lines from one verified regular-file descriptor.""" + descriptor = -1 + try: + flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_CLOEXEC", 0) + flags |= getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(path, flags) + file_stat = os.fstat(descriptor) + if not stat.S_ISREG(file_stat.st_mode): + raise OSError("rollout candidate is not a regular file") + if file_stat.st_size > _MAX_ROLLOUT_BYTES: + raise OSError("rollout exceeds safe byte limit") + + handle = os.fdopen(descriptor, "rb") + descriptor = -1 # fdopen owns and closes it from here. + + def bounded_lines() -> Iterator[str]: + total_bytes = 0 + records = 0 + while True: + raw_line = handle.readline(_MAX_ROLLOUT_LINE_BYTES + 1) + if not raw_line: + return + total_bytes += len(raw_line) + records += 1 + if len(raw_line) > _MAX_ROLLOUT_LINE_BYTES: + raise OSError("rollout line exceeds safe byte limit") + if total_bytes > _MAX_ROLLOUT_BYTES: + raise OSError("rollout exceeds safe byte limit") + if records > _MAX_ROLLOUT_RECORDS: + raise OSError("rollout exceeds safe record limit") + yield raw_line.decode("utf-8") + + with handle: + yield bounded_lines() + finally: + if descriptor >= 0: + os.close(descriptor) + + +def _iso_to_ms(ts: object) -> int: + """Convert an ISO-8601 timestamp string to milliseconds, or return zero.""" + if not isinstance(ts, str) or not ts: + return 0 + try: + normalized = ts.replace("Z", "+00:00") + dt = datetime.fromisoformat(normalized) + return int(dt.timestamp() * 1000) + except (ValueError, TypeError, OverflowError, OSError): + return 0 + + +def text(value: object) -> str: + if value is None: + return "" + if isinstance(value, str): + return value + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def count(value: object) -> bool: + return type(value) is int and value >= 0 + + +def usage(raw: object) -> dict: + if not isinstance(raw, dict): + return {} + result = {} + for source, target in ( + ("input_tokens", "prompt_tokens"), + ("output_tokens", "completion_tokens"), + ("total_tokens", "total_tokens"), + ("cached_input_tokens", "cached_input_tokens"), + ("cache_write_input_tokens", "cache_write_input_tokens"), + ("reasoning_output_tokens", "reasoning_output_tokens"), + ): + if count(raw.get(source)): + result[target] = raw[source] + if "prompt_tokens" in result and "cached_input_tokens" in result: + result["non_cached_input_tokens"] = max(result["prompt_tokens"] - result["cached_input_tokens"], 0) + return result + + +def records(path: Path, diagnostics: list) -> list: + result = [] + try: + with _open_regular_text(path) as handle: + for line in handle: + try: + obj = json.loads(line) + except (ValueError, TypeError): + diagnostics.append("malformed_record") + continue + if not isinstance(obj, dict) or not isinstance(obj.get("payload"), dict): + diagnostics.append("malformed_record") + continue + result.append(obj) + except (OSError, UnicodeError): + diagnostics.append("rollout_read_failed") + return result + + +def session_metadata(rows: list) -> dict: + # Forks prepend their own metadata, followed by copied parent history. + return next((r["payload"] for r in rows if r.get("type") == "session_meta"), {}) + + +def own_rows(rows: list, meta: dict) -> list: + boundary = meta.get("subagent_history_start_ordinal") + if count(boundary): + return [r for r in rows if count(r.get("ordinal")) and r["ordinal"] >= boundary] + # Old fork formats without a boundary cannot safely separate inherited history. + if meta.get("forked_from_id"): + return [] + return rows + + +def message(payload: dict) -> str: + content = payload.get("content", []) + if isinstance(content, str): + return content + if not isinstance(content, list): + return "" + return "\n".join(p["text"] for p in content if isinstance(p, dict) and isinstance(p.get("text"), str)) + + +def _extract_turn_from_rollout(rollout_path: Path, turn_id: str) -> "dict | None": + if not isinstance(turn_id, str) or not turn_id: + return None + diagnostics: list = [] + rows = records(rollout_path, diagnostics) + meta = session_metadata(rows) + rows = own_rows(rows, meta) + selected = [] + trace_count = 0 + started = False + for row in rows: + p = row["payload"] + if row.get("type") == "event_msg" and p.get("type") in ("task_started", "turn_started"): + if started: + break + trace_count += 1 + started = p.get("turn_id") == turn_id + if started: + selected.append(row) + if row.get("type") == "event_msg" and p.get("type") in ("task_complete", "task_completed", "turn_aborted"): + if p.get("turn_id") in (None, "", turn_id): + break + if not selected: + return None + modern = any(r.get("type") == "token_usage_record" and r["payload"].get("turn_id") == turn_id for r in selected) + turn: dict = { + "trace_count": trace_count, + "turn_start_ms": 0, + "turn_end_ms": 0, + "duration_ms": None, + "user_prompt": "", + "assistant_output": "", + "model": "", + "cwd": "", + "permission_mode": "", + "sandbox_mode": "", + "model_provider": meta.get("model_provider"), + "token_usage": None, + "tool_calls": [], + "llm_calls": [], + "diagnostics": diagnostics, + "status": "unknown", + "session_meta": meta, + "turn_attribution": {}, + } + tools: list = turn["tool_calls"] + calls: list = turn["llm_calls"] + pending: dict = {} + seen_items: set = set() + seen_usage: dict = {} + previous_total = None + active: dict | None = None + search_ends: dict = {} + inputs: list = [] + open_wrappers: list = [] + + def response(ts: int) -> dict: + nonlocal active + if active is None: + active = { + "start_ts": ts, + "end_ts": ts, + "input_parts": list(inputs), + "assistant_output": "", + "token_usage": None, + "tool_calls": [], + "response_id": "", + "status": "unknown", + } + inputs.clear() + active["end_ts"] = max(active["end_ts"], ts) + return active + + def close_response(ts: int, tokens: dict, response_id: str = "") -> None: + nonlocal active + call = response(ts) + call.update( + token_usage=tokens or None, response_id=response_id, status="completed", end_ts=max(ts, call["end_ts"]) + ) + calls.append(call) + active = None + + def add_tool(name: str, args: object, cid: str, ts: int, output=None, owner=None) -> dict: + if cid and cid in pending: + return pending[cid] + call = owner if owner is not None else response(ts) + entry = { + "tool": name, + "args": args, + "output": output, + "call_id": cid, + "start_ts": ts, + "end_ts": ts, + "status": "unknown", + "decision": None, + "response": call, + "timing_source": "persisted_item", + } + tools.append(entry) + if call: + call["tool_calls"].append(entry) + if cid: + pending[cid] = entry + return entry + + entry: dict | None + for row in selected: + outer, p = row.get("type"), row["payload"] + kind = p.get("type") + ts = _iso_to_ms(row.get("timestamp")) + turn["turn_end_ms"] = max(turn["turn_end_ms"], ts) + if p.get("turn_id") not in (None, "", turn_id): + continue + if outer == "turn_context": + for src, dst in (("model", "model"), ("cwd", "cwd"), ("approval_policy", "permission_mode")): + if isinstance(p.get(src), str): + turn[dst] = p[src] + sandbox = p.get("sandbox_policy") + if isinstance(sandbox, dict): + turn["sandbox_mode"] = sandbox.get("type", "") + elif outer == "token_usage_record": + rid = p.get("response_id") + tokens = usage(p.get("usage")) + if not isinstance(rid, str) or not rid or not tokens: + diagnostics.append("invalid_response_usage") + continue + if rid in seen_usage: + if seen_usage[rid] != tokens: + diagnostics.append("conflicting_response_usage") + continue + seen_usage[rid] = tokens + close_response(ts, tokens, rid) + elif outer == "event_msg": + if kind in ("task_started", "turn_started"): + start = p.get("started_at") + turn["turn_start_ms"] = start * 1000 if count(start) else ts + attr = p.get("turn_attribution") + turn["turn_attribution"] = attr if isinstance(attr, dict) else {} + elif kind in ("task_complete", "task_completed"): + turn["status"] = "completed" + if isinstance(p.get("last_agent_message"), str): + turn["assistant_output"] = p["last_agent_message"] + if count(p.get("completed_at")): + turn["turn_end_ms"] = p["completed_at"] * 1000 + if count(p.get("duration_ms")): + turn["duration_ms"] = p["duration_ms"] + elif kind in ("turn_aborted", "task_interrupted", "task_failed"): + turn["status"] = "failed" if kind == "task_failed" else "cancelled" + elif kind == "user_message" and isinstance(p.get("message"), str): + turn["user_prompt"] = p["message"] + if not inputs or inputs[-1] != {"kind": "prompt", "value": p["message"]}: + inputs.append({"kind": "prompt", "value": p["message"]}) + elif kind == "agent_message" and isinstance(p.get("message"), str): + turn["assistant_output"] = p["message"] + response(ts)["assistant_output"] = p["message"] + elif kind == "token_count" and not modern: + info = p.get("info") + if not isinstance(info, dict): + continue + total = info.get("total_token_usage") + if isinstance(total, dict) and previous_total == total: + continue + previous_total = total + tokens = usage(info.get("last_token_usage")) + if tokens: + close_response(ts, tokens) + elif kind == "web_search_end": + cid = p.get("call_id") + if isinstance(cid, str): + search_ends[cid] = (ts, p) + elif kind in ("item_started", "item_completed"): + item = p.get("item") + if not isinstance(item, dict): + diagnostics.append("malformed_item") + continue + itype = item.get("type") + cid = item.get("id") + if not isinstance(cid, str) or not cid: + diagnostics.append("missing_item_id") + continue + if itype == "CommandExecution": + entry = pending.get(cid) + if entry is None: + wrapper = open_wrappers[-1] if len(open_wrappers) == 1 else None + direct = [] + for candidate in tools: + if ( + candidate["tool"].rsplit(".", 1)[-1] != "exec_command" + or candidate["output"] is not None + ): + continue + args = candidate["args"] + if isinstance(args, str): + try: + args = json.loads(args) + except ValueError: + args = None + if isinstance(args, dict) and args.get("cmd", args.get("command")) == item.get("command"): + direct.append(candidate) + if len(direct) == 1 and wrapper is None: + entry = direct[0] + pending[cid] = entry + else: + owner = wrapper["response"] if wrapper else False + entry = add_tool( + "exec_command", + {k: item[k] for k in ("command", "cwd", "parsed_cmd") if k in item}, + cid, + ts, + owner=owner, + ) + if wrapper is None: + diagnostics.append("command_parent_unobserved") + if wrapper: + entry["parent_call_id"] = wrapper["call_id"] + start, end = p.get("started_at_ms"), p.get("completed_at_ms") + if count(start): + entry["start_ts"] = start + entry["timing_source"] = "item_lifecycle" + if count(end): + entry["end_ts"] = end + elif kind == "item_completed": + entry["end_ts"] = ts + if kind == "item_completed": + entry["output"] = item.get("aggregated_output") + entry["exit_code"] = item.get("exit_code") + entry["duration"] = item.get("duration") + entry["status"] = ( + "failed" + if type(item.get("exit_code")) is int and item["exit_code"] != 0 + else _status(item.get("status")) + ) + if entry["status"] == "completed" and type(item.get("exit_code")) is not int: + entry["status"] = "unknown" + diagnostics.append("command_result_unknown") + elif itype == "SubAgentActivity": + # Interactions/notifications are not evidence of a new invocation. + if item.get("kind") == "spawned" and isinstance(item.get("agent_thread_id"), str): + turn.setdefault("child_thread_ids", []).append(item["agent_thread_id"]) + elif outer == "response_item": + cid = p.get("call_id") or p.get("id") or "" + if not isinstance(cid, str): + diagnostics.append("invalid_call_id") + continue + if kind in ( + "function_call", + "custom_tool_call", + "local_shell_call", + "tool_search_call", + "image_generation_call", + "web_search_call", + ): + item_key = (kind, cid) if cid else (kind, row.get("ordinal"), ts) + if item_key in seen_items: + continue + seen_items.add(item_key) + name, args = p.get("name") or kind.removesuffix("_call"), p.get("arguments", p.get("input", "")) + if not isinstance(name, str): + name = "unknown_tool" + if kind == "web_search_call": + action = p.get("action") if isinstance(p.get("action"), dict) else {} + name = {"open_page": "open_page", "find_in_page": "find_in_page", "search": "web_search"}.get( + action.get("type") or "", "web_search_other" + ) + args = action.get("url") if name == "open_page" else action.get("query", action) + if kind == "local_shell_call": + args = p.get("action") + if kind == "tool_search_call": + args = {"arguments": p.get("arguments"), "execution": p.get("execution")} + if kind == "image_generation_call": + args = p.get("revised_prompt", "") + entry = add_tool(name, args, cid, ts) + if kind == "custom_tool_call" and name.rsplit(".", 1)[-1] == "exec": + entry["container"] = True + open_wrappers.append(entry) + if kind in ("web_search_call", "image_generation_call", "local_shell_call"): + entry["status"] = _status(p.get("status")) + entry["output"] = p.get("status") + if kind == "image_generation_call" and p.get("result"): + entry["output"] = "" + if cid in search_ends: + entry["end_ts"] = max(ts, search_ends[cid][0]) + elif kind in ("function_call_output", "custom_tool_call_output", "tool_search_output"): + entry = pending.get(cid) + output = p.get("tools") if kind == "tool_search_output" else p.get("output") + if entry is not None: + if entry["timing_source"] != "item_lifecycle": + entry["output"] = output + entry["end_ts"] = max(entry["start_ts"], ts) + entry["status"] = ( + "failed" + if type(entry.get("exit_code")) is int and entry["exit_code"] != 0 + else _output_status(output) + ) + if entry in open_wrappers: + open_wrappers.remove(entry) + if entry["tool"].rsplit(".", 1)[-1] == "spawn_agent": + result = output + if isinstance(result, str): + try: + result = json.loads(result) + except ValueError: + result = None + if isinstance(result, dict) and isinstance(result.get("agent_id"), str): + turn.setdefault("child_thread_ids", []).append(result["agent_id"]) + else: + diagnostics.append("orphan_tool_output") + inputs.append({"kind": "tool_output", "value": output, "call_id": cid}) + elif kind in ("message", "agent_message"): + msg = message(p) + if p.get("role") == "user": + turn["user_prompt"] = msg + part = {"kind": "prompt", "value": msg} + if not inputs or inputs[-1] != part: + inputs.append(part) + elif p.get("role") == "assistant" or kind == "agent_message": + call = response(ts) + if msg: + if call["assistant_output"] != msg: + call["assistant_output"] += ("\n" if call["assistant_output"] else "") + msg + turn["assistant_output"] = msg + elif kind == "reasoning": + response(ts) + if active is not None: + # Persisted response items are observations, even without usage/completion. + calls.append(active) + if turn["status"] == "unknown": + diagnostics.append("missing_completion") + if turn["status"] == "completed" and any(e["status"] == "unknown" for e in tools): + diagnostics.append("incomplete_tool_result") + turn["status"] = "unknown" + if turn["status"] != "completed": + for call in calls: + if call["status"] == "unknown": + call["status"] = turn["status"] + sums: dict = {} + for call in calls: + for k, v in (call["token_usage"] or {}).items(): + sums[k] = sums.get(k, 0) + v + if sums: + if "prompt_tokens" in sums and "cached_input_tokens" in sums: + sums["non_cached_input_tokens"] = max(sums["prompt_tokens"] - sums["cached_input_tokens"], 0) + sums["model"] = turn["model"] + turn["token_usage"] = sums + for entry in tools: + entry.pop("response", None) + if entry["end_ts"] < entry["start_ts"]: + diagnostics.append("invalid_tool_timing") + entry["end_ts"] = entry["start_ts"] + turn["diagnostics"] = sorted(set(diagnostics)) + return turn + + +def _status(value: object) -> str: + if value in ("completed", "success", "succeeded"): + return "completed" + if value in ("failed", "error", "declined", "denied"): + return "failed" + if value in ("cancelled", "interrupted", "aborted"): + return "cancelled" + return "unknown" + + +def _output_status(value: object) -> str: + if isinstance(value, list): + return "failed" if any(_output_status(item) == "failed" for item in value) else "completed" + if isinstance(value, dict): + if value.get("isError") is True or value.get("error"): + return "failed" + if type(value.get("exit_code")) is int and value["exit_code"] != 0: + return "failed" + if value.get("type") == "text": + return _output_status(value.get("text")) + if isinstance(value, str): + try: + structured = json.loads(value) + except ValueError: + structured = None + if isinstance(structured, (dict, list)): + return _output_status(structured) + # Unified-exec's result envelope is an observed result, not source code. + exit_match = re.search(r"(?m)^Process exited with code (-?\d+)\s*$", value) + if exit_match and int(exit_match[1]) != 0: + return "failed" + # A persisted output proves completion, but text is not a structured error signal. + return "completed" if value is not None else "unknown" diff --git a/tracing/codex/skills/manage-codex-tracing/SKILL.md b/tracing/codex/skills/manage-codex-tracing/SKILL.md index e0faddaf..097f44e0 100644 --- a/tracing/codex/skills/manage-codex-tracing/SKILL.md +++ b/tracing/codex/skills/manage-codex-tracing/SKILL.md @@ -1,326 +1,70 @@ --- name: manage-codex-tracing -description: Set up and configure Arize tracing for OpenAI Codex CLI sessions. Use when users want to set up Codex tracing, configure Arize AX or Phoenix for Codex, enable/disable tracing, or troubleshoot Codex tracing issues. Triggers on "set up codex tracing", "configure Arize for Codex", "configure Phoenix for Codex", "enable codex tracing", "setup-codex-tracing", or any request about connecting Codex to Arize or Phoenix for observability. +description: Set up, configure or troubleshoot Codex CLI rollout tracing to Phoenix or Arize AX, including missing model responses, tools, token usage and native subagent lineage. --- -# Setup Codex Tracing +# Manage Codex tracing -Configure OpenInference tracing for OpenAI Codex CLI sessions to Arize AX (cloud) or Phoenix (self-hosted). +Read `tracing/codex/README.md` in the installed repository for the current trace +contract and limits. This is the +[lifldev fork](https://github.com/lifldev/coding-harness-tracing) of +[Arize's exporter](https://github.com/Arize-ai/coding-harness-tracing). -## Architecture Overview +## Installation and configuration -Codex tracing uses real Codex CLI lifecycle hooks plus the legacy `notify` hook as a token-usage backstop. Spans are sent directly to the backend from the `Stop` hook: +Use the repository installer, `./install.sh codex` (`install.bat codex` on +Windows), or the fork installer URL: -1. **Direct send** (`core/common.py`) — spans are sent directly to Phoenix (REST) or Arize AX (gRPC) from the hook handlers via `send_span()`. Per-harness backend credentials are read from `harnesses.codex.*` in config. - -2. **Real Codex hooks** — `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PermissionRequest`, and `Stop` events are dispatched to three entry points: - - `arize-hook-codex-session` (`SessionStart`, `UserPromptSubmit`) — mutates per-thread state file at `~/.arize/harness/state/codex/state_.json`. - - `arize-hook-codex-tool` (`PreToolUse`, `PostToolUse`, `PermissionRequest`) — appends rows to `~/.arize/harness/state/codex/spans_.jsonl`. - - `arize-hook-codex-stop` (`Stop`) — reads state + JSONL, builds the parent LLM span plus TOOL child spans, sends the multi-span payload, then clears turn-scoped state and deletes the JSONL. - -3. **Notify hook** (`arize-hook-codex-notify`) — Fires on `agent-turn-complete`. Real Codex hook payloads don't carry exact token counts, so `notify` is kept purely as a token-usage backstop: it extracts `token_usage` and `last-assistant-message` from the notify payload and writes them into the state file. If the state file doesn't exist (hooks not yet trusted, first run), notify falls back to its legacy behavior of emitting a single flat Turn span. - -``` -Codex CLI - | - |-- SessionStart / UserPromptSubmit --> arize-hook-codex-session - | |--> updates state_.json - | - |-- PreToolUse / PostToolUse / PermissionRequest --> arize-hook-codex-tool - | |--> appends row to spans_.jsonl - | - |-- agent-turn-complete (notify) --> arize-hook-codex-notify - | |--> writes token_usage into state_.json - | - |-- Stop --> arize-hook-codex-stop - |--> reads state + spans JSONL - |--> builds parent LLM span + TOOL child spans - |--> send_span() --> Phoenix/Arize AX - |--> clears turn-scoped state, deletes spans JSONL -``` - -**Graceful degradation**: If hooks aren't trusted yet (Codex requires explicit `/hooks` approval), the `notify` hook still produces a single flat Turn span. - -## Trust prompt - -Codex requires explicit user trust for non-managed hooks before they fire. After install, the user must: - -1. Start a Codex session: `codex` -2. Type `/hooks` and approve each `arize-hook-codex-*` entry. - -Without this one-time approval, the real hooks never fire and tracing falls back to `notify`-only (single LLM span per turn, no tool spans). - -## How to Use This Skill - -**This skill follows a decision tree workflow.** Start by asking the user where they are in the setup process: - -1. **Do they already have credentials?** - - Yes → Jump to [Configure Codex](#configure-codex) - - No → Continue to step 2 - -2. **Which backend do they want to use?** - - Phoenix (self-hosted) → Go to [Set Up Phoenix](#set-up-phoenix) - - Arize AX (cloud) → Go to [Set Up Arize AX](#set-up-arize-ax) - -3. **Are they troubleshooting?** - - Yes → Jump to [Troubleshoot](#troubleshoot) - -**Important:** Only follow the relevant path for the user's needs. Don't go through all sections. - -## Set Up Phoenix - -Phoenix is self-hosted and requires no Python dependencies for tracing (spans are sent directly via `send_span()` using stdlib `urllib`). - -### Install Phoenix - -Ask if they already have Phoenix running. If not, walk through: - -```bash -# Option A: pip -pip install arize-phoenix && phoenix serve - -# Option B: Docker -docker run -p 6006:6006 arizephoenix/phoenix:latest -``` - -Phoenix UI will be available at `http://localhost:6006`. Confirm it's running: - -```bash -curl -sf http://localhost:6006/v1/traces >/dev/null && echo "Phoenix is running" || echo "Phoenix not reachable" -``` - -Then proceed to [Configure Codex](#configure-codex) with `PHOENIX_ENDPOINT=http://localhost:6006`. - -## Set Up Arize AX - -Arize AX is available as a SaaS platform or as an on-prem deployment. Users need an account, a space, and an API key. - -**First, ask the user: "Are you using the Arize SaaS platform or an on-prem instance?"** - -- **SaaS** → Uses the default endpoint (`otlp.arize.com:443`). Continue below. -- **On-prem** → The user will need to provide their custom OTLP endpoint (e.g., `otlp.mycompany.arize.com:443`). Ask for it and note it for the configure step where it will be set as `ARIZE_OTLP_ENDPOINT`. - -### 1. Create an account - -If the user doesn't have an Arize account: -- **SaaS**: Sign up at https://app.arize.com/auth/join -- **On-prem**: Contact their administrator for access - -### 2. Get Space ID and API key - -Walk the user through finding their credentials: -1. Log in to their Arize instance (https://app.arize.com for SaaS, or their on-prem URL) -2. Click **Settings** (gear icon) in the left sidebar -3. The **Space ID** is shown on the Space Settings page -4. Go to the **API Keys** tab -5. Click **Create API Key** or copy an existing one - -Both `ARIZE_API_KEY` and `ARIZE_SPACE_ID` are required. - -### 3. Python dependencies (bundled with the package) - -Arize AX uses gRPC for export, but the gRPC dependencies are bundled with the package — they are **not** required in the user's Python environment. No `pip install` step is needed for basic tracing. - -Then proceed to [Configure Codex](#configure-codex). - -## Configure Codex - -This section configures: -1. **Backend config** at `~/.arize/harness/config.json` -2. **Environment variables** in `~/.codex/arize-env.sh` -3. **Hook entries** in `~/.codex/config.toml` (real Codex hooks + `notify` token-usage backstop) -4. **Trust prompt** inside Codex (`/hooks`) — required before non-managed hooks fire - -### Determine the integration path - -Ask the user: **"Where is the Codex tracing directory located?"** - -Common locations: -- If cloned: `./coding-harness-tracing/tracing/codex` -- If installed via the curl installer: `~/.arize/harness/tracing/codex` - -Store this as `INTEGRATION_PATH` for the hook config. - -### Step 1: Write the backend config - -Write `~/.arize/harness/config.json` with the backend credentials. The config file is the single source of truth for backend and harness settings. - -**Important: read-merge-write.** If `~/.arize/harness/config.json` already exists, read it first, add or update the `harnesses.codex` entry, and preserve existing backend credentials. Only prompt the user for backend credentials if there is no existing config. - -**Phoenix:** -```bash -mkdir -p ~/.arize/harness/{logs,state/codex} -# Merge: add/update harnesses.codex, preserve existing backend settings -arize-config set harnesses.codex.project_name codex -``` - -If no config exists yet, create it: -```json -{ - "harnesses": { - "codex": { - "project_name": "codex", - "target": "phoenix", - "endpoint": "http://localhost:6006", - "api_key": "" - } - } -} -``` - -**Arize AX:** -```bash -mkdir -p ~/.arize/harness/{logs,state/codex} -arize-config set harnesses.codex.project_name codex -``` - -If no config exists yet, create it: -```json -{ - "harnesses": { - "codex": { - "project_name": "codex", - "target": "arize", - "endpoint": "otlp.arize.com:443", - "api_key": "", - "space_id": "" - } - } -} -``` - -### Step 2: Write the environment file (optional) - -Environment variables are optional overrides — all backend credentials are in `~/.arize/harness/config.json`. If the user needs env-var overrides, create `~/.codex/arize-env.sh`: - -```bash -cat > ~/.codex/arize-env.sh << 'EOF' -export ARIZE_TRACE_ENABLED=true -EOF -chmod 600 ~/.codex/arize-env.sh -``` - -If the user wants to associate spans with a user ID, add `export ARIZE_USER_ID=""`. - -### Step 3: Add the hook entries to config.toml - -Read `~/.codex/config.toml`. Add the `notify` line at the top level (NOT inside any `[section]`) — this is the token-usage backstop: - -```toml -notify = ["~/.arize/harness/venv/bin/arize-hook-codex-notify"] -``` - -Then add one `[[hooks.]]` entry per real Codex lifecycle event: - -```toml -[[hooks.SessionStart]] -command = ["~/.arize/harness/venv/bin/arize-hook-codex-session"] - -[[hooks.UserPromptSubmit]] -command = ["~/.arize/harness/venv/bin/arize-hook-codex-session"] - -[[hooks.PreToolUse]] -command = ["~/.arize/harness/venv/bin/arize-hook-codex-tool"] - -[[hooks.PostToolUse]] -command = ["~/.arize/harness/venv/bin/arize-hook-codex-tool"] - -[[hooks.PermissionRequest]] -command = ["~/.arize/harness/venv/bin/arize-hook-codex-tool"] - -[[hooks.Stop]] -command = ["~/.arize/harness/venv/bin/arize-hook-codex-stop"] -``` - -**Important:** If `notify` already exists in the config, update the existing line. If `[[hooks.]]` entries already exist that match our handlers (managed block), leave them alone — the installer manages the block idempotently. - -### Step 4: Approve the hooks inside Codex - -Codex requires explicit user trust for non-managed hooks before they fire. The user must: - -1. Start a Codex session: `codex` -2. Type `/hooks` and approve each `arize-hook-codex-*` entry. - -Until this is done, only the `notify` token-usage backstop will run (flat single-span tracing). The real hooks will not fire. - -**Note:** The installer handles Steps 1-3 automatically. Step 4 (the `/hooks` trust prompt) is a one-time user action — the installer cannot automate it. - -### Validate - -After writing the config, validate: - -1. **Check config.toml is valid:** -```bash -cat ~/.codex/config.toml -``` -Visually confirm the `notify` line is at the top level and the `[[hooks.SessionStart]]`, `[[hooks.UserPromptSubmit]]`, `[[hooks.PreToolUse]]`, `[[hooks.PostToolUse]]`, `[[hooks.PermissionRequest]]`, and `[[hooks.Stop]]` entries are present. - -2. **Check env file:** -```bash -source ~/.codex/arize-env.sh && echo "ARIZE_TRACE_ENABLED=$ARIZE_TRACE_ENABLED" -``` - -3. **Check the hooks are trusted inside Codex:** - Start `codex`, run `/hooks`, and confirm each `arize-hook-codex-*` entry is listed and approved. - -4. **Phoenix connectivity** (if using Phoenix): ```bash -curl -sf ${PHOENIX_ENDPOINT}/v1/traces >/dev/null && echo "Phoenix reachable" || echo "Phoenix not reachable" +curl -sSL https://raw.githubusercontent.com/lifldev/coding-harness-tracing/main/install.sh | bash -s -- codex ``` -5. **Dry run test:** -```bash -ARIZE_DRY_RUN=true arize-hook-codex-notify '{"type":"agent-turn-complete","thread-id":"test-123","turn-id":"turn-1","cwd":"/tmp","input-messages":"hello","last-assistant-message":"hi there"}' -``` -Should print: `[arize] DRY RUN:` followed by the span name. - -### Confirm - -Tell the user: -- Configuration saved to `~/.codex/config.toml`, `~/.codex/arize-env.sh`, and `~/.arize/harness/config.json` -- Spans are sent directly to the backend from the `Stop` hook -- The real Codex hooks (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PermissionRequest`, `Stop`) build rich span trees with TOOL children per tool call -- The `notify` hook is now a token-usage backstop — it writes exact token counts into the per-thread state file so they appear on the parent LLM span -- Until the user approves the hooks via `/hooks` inside Codex, only the `notify`-based fallback runs (single flat LLM span per turn) -- Mention `ARIZE_DRY_RUN=true` to test without sending data -- Mention `ARIZE_VERBOSE=true` and `ARIZE_TRACE_DEBUG=true` for debug output -- Logs: `~/.arize/harness/logs/codex.log` (errors always; routine activity requires `ARIZE_VERBOSE=true` in `~/.codex/arize-env.sh` or the shell) - -### Environment Variables Reference - -At runtime, project variables override `harnesses.codex.project_name` in `config.json`. During installation, project overrides come only from the file named by `ARIZE_ENV_FILE`. The installer ignores inherited process project variables. Reinstalling preserves the saved name unless a file setting or typed answer replaces it. - -| Variable | Required | Default | Description | -|----------|----------|---------|-------------| -| `ARIZE_API_KEY` | For AX | - | Arize AX API key | -| `ARIZE_SPACE_ID` | For AX | - | Arize AX space ID | -| `ARIZE_OTLP_ENDPOINT` | No | `otlp.arize.com:443` | OTLP gRPC endpoint (on-prem Arize) | -| `PHOENIX_ENDPOINT` | For Phoenix | `http://localhost:6006` | Phoenix collector URL | -| `PHOENIX_API_KEY` | No | - | Phoenix API key for auth | -| `ARIZE_PROJECT_NAME` | No | Saved project | Arize AX runtime override. New installs default to `harness/`, or `codex` if no email is available. | -| `PHOENIX_PROJECT`, `PHOENIX_PROJECT_NAME` | No | Saved project | Phoenix runtime override. New installs default to `codex`. `PHOENIX_PROJECT` wins when both are set. | -| `ARIZE_USER_ID` | No | - | User ID to attach to all spans as `user.id` attribute | -| `ARIZE_TRACE_ENABLED` | No | `true` | Enable/disable tracing | -| `ARIZE_DRY_RUN` | No | `false` | Print spans instead of sending | -| `ARIZE_VERBOSE` | No | `false` | Enable verbose logging | -| `ARIZE_TRACE_DEBUG` | No | `false` | Write debug JSON to `~/.arize/harness/state/codex/debug/` | -| `ARIZE_LOG_FILE` | No | `~/.arize/harness/logs/codex.log` | Log file path | - -## Troubleshoot - -Common issues and fixes: - -| Problem | Fix | -|---------|-----| -| Traces not appearing | Check `ARIZE_TRACE_ENABLED` is `true` in `~/.codex/arize-env.sh` | -| Hooks not firing | Run `codex` → `/hooks` and confirm each `arize-hook-codex-*` entry is trusted. If they aren't listed at all, re-run the installer. | -| `notify` hook not firing | Verify `notify` line in `~/.codex/config.toml` points to correct path | -| Phoenix unreachable | Verify Phoenix is running: `curl -sf /v1/traces` | -| No output in terminal | Hooks run in background; check `~/.arize/harness/logs/codex.log` | -| Want to test without sending | Set `ARIZE_DRY_RUN=true` in env or `export ARIZE_DRY_RUN=true` | -| Want verbose logging | Set `ARIZE_VERBOSE=true` in env or `export ARIZE_VERBOSE=true` | -| Wrong project name | Check `harnesses.codex.project_name` in `~/.arize/harness/config.json`. For a runtime override, set `ARIZE_PROJECT_NAME` for AX or `PHOENIX_PROJECT` for Phoenix in `~/.codex/arize-env.sh`. | -| Existing `notify` hook | Codex supports only one `notify` — create a wrapper script that calls both | -| Stale state files | Run: `rm -rf ~/.arize/harness/state/codex/state_*.json ~/.arize/harness/state/codex/spans_*.jsonl` | -| Flat spans only (no children) | The real hooks haven't been trusted yet. Run `codex` → `/hooks` and approve each `arize-hook-codex-*` entry. | -| User ID not appearing on spans | Set `ARIZE_USER_ID` in `~/.codex/arize-env.sh` or export before running Codex | +The installer registers `arize-hook-codex-notify` in `$CODEX_HOME/config.toml` +(default `~/.codex/config.toml`). It uses `agent-turn-complete` and rollout JSONL, +not lifecycle hooks. Do not instruct users to approve `/hooks` for this exporter. +Preserve unrelated hook/notify configuration and use the installer to uninstall. +An explicit `CODEX_HOME` must exist. + +Use `arize-config` for backend/project/content settings. Credentials belong in +`~/.arize/harness/config.json` or the documented env override file, never in chat +or committed files. Check existing configuration before asking for missing +information. Obtain authorization before any install/configuration change, +external send or model launch that is outside the user's requested scope. + +## Expected reconstruction + +- One CHAIN per turn, individual LLM response spans and named TOOL spans. +- Code-mode exec wrappers group real structured `CommandExecution` observations. + Do not parse JavaScript source as evidence that a command ran. +- Response usage comes from `token_usage_record.usage`, deduplicated by + `response_id`; older snapshots are a fallback. Cache/reasoning are details of + input/output, not additional totals. Token counts belong only on LLM spans. +- Response timing is observed persistence timing, not provider request timing. + Commands use observed lifecycle timing and nonzero exits fail. +- Native lineage requires child session metadata and parent-turn attribution. + Exclude inherited history. Orca worker dispatch is not Codex native lineage. +- Missing completion/results are unknown and malformed records fail soft with + diagnostics. Never turn an incomplete rollout into claimed success. + +## Troubleshooting safely + +1. Check the active Codex home and literal rollout session identity. Never read + credentials or print raw private prompts/results into an issue or artifact. +2. Check `~/.arize/harness/logs/codex.log`, notify configuration, trace-enabled + setting and backend/project resolution. Do not assume unset process env means + configuration is absent. +3. Replay only an existing authorized rollout with backend sends mocked, or use + `ARIZE_DRY_RUN=true`. Verify response IDs, per-response usage, command item IDs, + lifecycle times, result statuses and parent attribution. Commit synthetic + fixtures, never copied private rollout content. +4. Check content gates independently: `ARIZE_LOG_PROMPTS`, + `ARIZE_LOG_TOOL_DETAILS`, `ARIZE_LOG_TOOL_CONTENT`. Tool results in following + model inputs use the tool-content gate. Binary image/audio and encrypted + reasoning are omitted; enabled attributes are bounded. +5. Duplicate notify delivery uses deterministic IDs and successful per-span hash + receipts in `~/.arize/harness/state/codex/delivery/`. Failed sends remain + retryable; do not delete receipts casually or claim exactly-once transport. +6. Report unsupported cases plainly: ephemeral/missing rollouts, forks without + history boundaries, unavailable parents, unobserved/non-notifying background + sessions, and missing provider request timestamps. Parser checks do not verify + a live backend UI or deployment.