Skip to content

fix(ai): record tool outcome on Claude Agent SDK and LangChain tool spans - #1282

Merged
DanielVisca merged 4 commits into
mainfrom
perch/ai-tool-span-outcomes
Nov 24, 2026
Merged

DanielVisca merged 4 commits into
mainfrom
perch/ai-tool-span-outcomes

Conversation

@DanielVisca

@DanielVisca DanielVisca commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Tool spans from two AI integrations can't tell you whether the tool worked, so per-tool failure rates can't be computed:

  • Claude Agent SDK (posthog.ai.claude_agent_sdk): the tool $ai_span was captured as soon as the ToolUseBlock was seen, before the tool ran. It never had $ai_output_state, $ai_is_error, $ai_error or $ai_latency. This affected both query() / PostHogClaudeAgentProcessor and PostHogClaudeSDKClient.
  • LangChain (CallbackHandler): tool runs were captured as untyped $ai_spans (no $ai_span_type: "tool"). A tool error handled by handle_tool_error ends the run normally with a ToolMessage(status="error"), so it was recorded as a success. ToolMessages in $ai_input also lost tool_call_id, name and status, so tool results couldn't be matched to tool names.

Changes

Claude Agent SDK (processor.py, client.py)

  • A tool span is now held by tool_use_id and emitted when its matching ToolResultBlock arrives. It then carries:
    • $ai_output_state: the result content, redacted and truncated like tool results in $ai_input
    • $ai_is_error: from block.is_error
    • $ai_error: the result text, only when the tool errored
    • $ai_latency: time from tool use to tool result
  • Privacy mode: $ai_is_error and $ai_latency are still sent; the output and error text are not.
  • Results inside subagent messages also close their spans. Previously subagent UserMessages were skipped entirely, but their tool spans were still emitted.
  • Spans whose result never arrives are still emitted, without an outcome:
    • query(): on ResultMessage, or in a finally if the stream ends early, fails or is cancelled
    • PostHogClaudeSDKClient: on ResultMessage and on disconnect()
  • The query() loop is wrapped in try/finally, which re-indents it. Review with whitespace changes hidden.

LangChain (callbacks.py)

  • Tool runs set $ai_span_type: "tool". Chains, retrievers and agent steps are unchanged.
  • In on_tool_end, a ToolMessage output with status == "error" sets $ai_is_error: True and $ai_error to the message text. $ai_error is None in privacy mode.
  • _convert_message_to_dict keeps tool_call_id and name on tool messages, plus status when it is "error".

Also adds a sampo changeset (patch).

Before / After

Printed by a small script that runs each integration against a MagicMock PostHog client and prints the $ai_span properties: (a) a Claude Agent SDK Bash tool call whose ToolResultBlock has is_error=True; (b) a LangChain @tool that raises ToolException with handle_tool_error=True, invoked with a tool call inside a chain. Trimmed to the relevant keys.

Before

(a) Claude Agent SDK $ai_span:
[{"$ai_span_name": "Bash", "$ai_span_type": "tool", "$ai_input_state": {"command": "foo"}}]
(b) LangChain $ai_span:
[{"$ai_span_name": "get_weather",
  "$ai_input_state": "{'city': 'Paris'}",
  "$ai_output_state": "content='weather service unavailable for Paris' name='get_weather' tool_call_id='call_1' status='error'",
  "$ai_latency": 0.0003371238708496094}]

After

(a) Claude Agent SDK $ai_span:
[{"$ai_span_name": "Bash", "$ai_span_type": "tool", "$ai_input_state": {"command": "foo"},
  "$ai_output_state": "bash: foo: command not found",
  "$ai_is_error": true,
  "$ai_error": "bash: foo: command not found",
  "$ai_latency": 0.003941774368286133}]
(b) LangChain $ai_span:
[{"$ai_span_name": "get_weather", "$ai_span_type": "tool",
  "$ai_input_state": "{'city': 'Paris'}",
  "$ai_output_state": "content='weather service unavailable for Paris' name='get_weather' tool_call_id='call_1' status='error'",
  "$ai_is_error": true,
  "$ai_error": "weather service unavailable for Paris",
  "$ai_latency": 0.0005731582641601562}]

Tests

  • posthog/test/ai/claude_agent_sdk/test_processor.py:
    • a successful result and an errored result (list content)
    • privacy mode
    • a subagent's tool result
    • a span flushed when the query ends without a result
    • spans emitted in order (generation → span → generation → trace)
  • posthog/test/ai/claude_agent_sdk/test_client.py: tool results arriving out of order match their own spans, and a span without a result is still emitted. Both run against query() and PostHogClaudeSDKClient.
  • posthog/test/ai/langchain/test_callbacks.py:
    • $ai_span_type is set on tool spans only
    • a handled tool error, with and without privacy mode
    • an unhandled tool error
    • ToolMessage conversion

uv run pytest posthog/test/ai/claude_agent_sdk posthog/test/ai/langchain: 251 passed, 8 skipped. ruff format --check, ruff check and mypy | mypy-baseline filter are clean.

Open questions for reviewers

  • $ai_output_state on Claude tool spans uses the same 5000-character truncation as tool results in $ai_input.
  • LangChain $ai_output_state for a ToolMessage is still its str() form (unchanged). I left it alone to keep this PR small.
  • Claude tool spans are now emitted when the result arrives rather than when the tool use is seen. Their timestamps move later, and they now arrive after the generation that called the tool.

🤖 Generated with Claude Code

…pans

Claude Agent SDK: hold each tool $ai_span until its ToolResultBlock arrives
and emit it with $ai_output_state, $ai_is_error, $ai_error and $ai_latency.
Spans without a result are flushed on ResultMessage, when the query stream
ends, and on client disconnect. Applies to query() and PostHogClaudeSDKClient.

LangChain: set $ai_span_type "tool" on tool spans, mark tool errors handled
by handle_tool_error (ToolMessage status "error") with $ai_is_error and
$ai_error, and keep tool_call_id, name and error status on ToolMessages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DanielVisca
DanielVisca requested a review from a team as a code owner November 20, 2026 03:05
@veria-ai

veria-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

PR overview

No security issues were found in this pull request.

Reviews

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostHog Review · Standard · reviewed 4d24e9d: 3 Should fix.

See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.

Comment thread posthog/ai/langchain/callbacks.py Resolved
Comment thread posthog/ai/langchain/callbacks.py Resolved
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

SDK performance: posthog-python

Benchmarks completed. No changes flagged for review.

Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate.

View all results
Test Measurement Before PR With PR Change Assessment
Capture and deliver events (32-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Queue an event (32-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (32-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Refresh 1,000 flag definitions
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocated memory per operation 133.67 KiB/op 133.67 KiB/op <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocations per operation 1,345.52 count/op 1,345.51 count/op <0.1% fewer Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 76.85 µs/op 77.12 µs/op 0.4% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 37.66 MiB 37.68 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 40.11 MiB 40.12 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 40.11 MiB 40.12 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 80.28 µs/op 79.87 µs/op 0.5% less time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 40.36 MiB 40.36 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocated memory per operation 185.75 KiB/op 185.75 KiB/op <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocations per operation 1,337.51 count/op 1,337.51 count/op <0.1% fewer Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 100.42 µs/op 100.31 µs/op 0.1% less time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 41.23 MiB 41.2 MiB <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 47.02 MiB 46.98 MiB <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 47.02 MiB 46.98 MiB <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 96.42 µs/op 97.42 µs/op 1% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 51.4 MiB 51.38 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocated memory per operation 138.73 KiB/op 138.73 KiB/op <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocations per operation 1,390.31 count/op 1,390.3 count/op <0.1% fewer Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Time per operation 88.41 µs/op 88.21 µs/op 0.2% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 37.6 MiB 37.55 MiB 0.1% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 37.78 MiB 37.72 MiB 0.2% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 37.78 MiB 37.72 MiB 0.2% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 90.24 µs/op 90.08 µs/op 0.2% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.36 MiB 40.36 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocated memory per operation 190.9 KiB/op 190.9 KiB/op <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 1,382.19 count/op 1,382.19 count/op <0.1% more Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 105.47 µs/op 105.26 µs/op 0.2% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 41.1 MiB 41.01 MiB 0.2% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 41.55 MiB 41.45 MiB 0.3% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 41.16 MiB 41.05 MiB 0.3% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 101.88 µs/op 101.3 µs/op 0.6% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 41.46 MiB 41.39 MiB 0.2% less memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 57.39 µs/op 57.54 µs/op 0.3% more time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 57.39 µs/op 57.54 µs/op 0.3% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 56.97 µs/op 56.99 µs/op <0.1% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 56.97 µs/op 56.99 µs/op <0.1% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocated memory per operation 225.43 KiB/op 225.43 KiB/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocations per operation 2,279.42 count/op 2,279.42 count/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Time per operation 82.25 µs/op 82.16 µs/op 0.1% less time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 82.23 µs/op 82.16 µs/op <0.1% less time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocated memory per operation 2.17 MiB/op 2.17 MiB/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocations per operation 22,413.69 count/op 22,413.69 count/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Time per operation 772.65 µs/op 767.86 µs/op 0.6% less time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 772.65 µs/op 767.88 µs/op 0.6% less time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocated memory per operation 21.63 MiB/op 21.63 MiB/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocations per operation 223,655.44 count/op 223,655.44 count/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Time per operation 7.69 ms/op 7.64 ms/op 0.6% less time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 7.69 ms/op 7.64 ms/op 0.6% less time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 43.89 MiB 43.84 MiB 0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 44.2 MiB 44.17 MiB <0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 44.2 MiB 44.17 MiB <0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 43.95 MiB 44.09 MiB 0.3% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 42.98 MiB 42.97 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 42.99 MiB 42.98 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 42.99 MiB 42.98 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 42.81 MiB 43.16 MiB 0.8% more memory Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocated memory per operation 15.74 KiB/op 15.74 KiB/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocations per operation 162.77 count/op 162.77 count/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Time per operation 8.2 µs/op 8.25 µs/op 0.6% more time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 8.2 µs/op 8.25 µs/op 0.6% more time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocated memory per operation 24.6 KiB/op 24.6 KiB/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocations per operation 239.28 count/op 239.28 count/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Time per operation 11.41 µs/op 11.39 µs/op 0.1% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 11.41 µs/op 11.39 µs/op 0.1% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocated memory per operation 39.81 KiB/op 39.81 KiB/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocations per operation 388.27 count/op 388.27 count/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Time per operation 16.34 µs/op 16.42 µs/op 0.5% more time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 16.34 µs/op 16.42 µs/op 0.5% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocated memory per operation 60.59 KiB/op 60.59 KiB/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocations per operation 584.27 count/op 584.27 count/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Time per operation 23.46 µs/op 23.46 µs/op <0.1% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 23.46 µs/op 23.46 µs/op <0.1% more time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocated memory per operation 59.22 KiB/op 59.22 KiB/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocations per operation 567.77 count/op 567.77 count/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Time per operation 22.3 µs/op 22.13 µs/op 0.8% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 22.3 µs/op 22.13 µs/op 0.8% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocated memory per operation 19.04 KiB/op 19.04 KiB/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocations per operation 192.27 count/op 192.27 count/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Time per operation 9.25 µs/op 9.18 µs/op 0.9% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 9.26 µs/op 9.18 µs/op 0.9% less time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocated memory per operation 20.66 KiB/op 20.66 KiB/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocations per operation 197.77 count/op 197.77 count/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Time per operation 9.79 µs/op 9.8 µs/op <0.1% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 9.79 µs/op 9.8 µs/op <0.1% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocated memory per operation 14.89 KiB/op 14.89 KiB/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocations per operation 152.77 count/op 152.77 count/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Time per operation 7.71 µs/op 7.73 µs/op 0.3% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 7.71 µs/op 7.74 µs/op 0.3% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocated memory per operation 15.9 KiB/op 15.9 KiB/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocations per operation 166.77 count/op 166.77 count/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Time per operation 8.54 µs/op 8.51 µs/op 0.3% less time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 8.54 µs/op 8.51 µs/op 0.3% less time Not flagged

Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals.

Each shard uses its own runner; compare Before PR against With PR within a row, not across shards.

Compared 44ac220377d12cf33da00abc5d3505ed86363b64 → 5995fc6e939797c7e70bcbdc40fb711717e96a90.

Full report and diagnostics

102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in comparison.json, including per-runner environments, resource limits, measurement methods, samples and checkpoints.

…ing tool spans

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code looks good; no qualifying findings. Verdict: correct.

@marandaneto

Copy link
Copy Markdown
Member

Agent-drafted and reviewed by Manoel.

question: This PR changes what consumers of these events see. Are all of these changes intended, and is it OK to ship them as a patch release?

  • Claude Agent SDK: tool $ai_span events are now sent when the ToolResultBlock arrives, not when the ToolUseBlock is seen. Their timestamps move later, and they now arrive after the $ai_generation that called the tool. The PR description says this, but anything that relies on event order or timestamps (trace tree rendering, timelines, ingestion-side ordering) will change. Subagent tool results now also close their spans.
  • LangChain: tool spans now include $ai_span_type: "tool". In $ai_input, ToolMessage dicts now include tool_call_id, name and, on errors, status. That changes the shape of downstream data for anything that parses $ai_input or groups spans by type.
  • Public API: SpanMetadata and GenerationMetadata gain a keyword-only span_type field. Positional calls still work, so this one is additive.

Has the LLM analytics UI or ingestion been checked against the new ordering and fields? If any of this is unintended, should it be opt-in or called out in the changelog?

@marandaneto

Copy link
Copy Markdown
Member

Agent-drafted and reviewed by Manoel.

question: Could the new pending tool span buffer in PostHogClaudeSDKClient grow without limit in a long-lived session?

posthog/ai/claude_agent_sdk/client.py now keeps every unfinished tool span in self._pending_tools, including its $ai_input_state. That input only goes through media redaction, with no length cap. Spans leave the buffer only when their ToolResultBlock arrives, on ResultMessage, or on disconnect(). query() in the processor also clears the buffer in a finally, but receive_response() has no equivalent. So if the caller breaks out of receive_response() early, calls interrupt(), or a turn ends without a ResultMessage, those spans stay in memory until disconnect(). A long-running agent that keeps one client open and hits this repeatedly accumulates large tool inputs. Those spans are also reported late or never.

In a normal turn, ResultMessage clears the buffer, so this is probably bounded in practice. Is that guaranteed? If not, would it make sense to clear the buffer in a finally in receive_response(), like query() does, and/or cap the number of pending spans?

DanielVisca and others added 2 commits November 23, 2026 15:56
A turn that ended without a ResultMessage, or that the caller stopped
early, kept its pending tool spans in memory until disconnect().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A chain or root trace that returned a handled tool error was also marked
$ai_is_error, double-counting the failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DanielVisca

Copy link
Copy Markdown
Contributor Author

Answers to both questions:

Buffer growth: it wasn't guaranteed to be bounded. The processor's query() cleared the buffer in a finally, but receive_response() didn't. 115c7f7 fixes that: receive_response() now flushes unfinished tool spans in a finally, so a break, interrupt() or a turn that ends without a ResultMessage emits them (without an outcome) instead of holding them until disconnect(). There is a test for it in test_client.py. The remaining buffer is bounded by the tools in flight within one turn. I haven't added a hard cap, because a cap would drop or emit spans early for legitimate parallel tool calls. Say if you want one anyway.

Consumer-visible changes: these are intended.

  • Claude Agent SDK: tool $ai_span events are emitted when the ToolResultBlock arrives. That is the only point where $ai_is_error, $ai_error, $ai_output_state and a real $ai_latency are known. Timestamps move later and spans arrive after the calling $ai_generation, but $ai_parent_id, $ai_trace_id and $ai_span_id are unchanged. Tree rendering goes through those IDs, not arrival order. A tool whose result never arrives is still emitted at the end of the turn or on disconnect.
  • LangChain: $ai_span_type: "tool" is new on tool spans only. tool_call_id, name and an error status on ToolMessage dicts in $ai_input are additive keys.
  • Public API: span_type is keyword-only and the snapshot is updated.

I haven't checked the LLM analytics UI or ingestion against the new ordering. Nothing in the diff changes the ID fields they key on, but I can't prove that from this repo. The changeset already describes the new behaviour. I kept it as a patch release because the changes only add fields. The one behaviour change is that Claude Agent SDK tool spans arrive and are timestamped later, and the changeset says so. If you want that behind an opt-in, that is your call and the author's.

🤖 Daniel's agent · perch shepherd

DanielVisca added a commit that referenced this pull request Nov 24, 2026
Brings over two fixes from the duplicate PR #1282:
- receive_response() flushes unfinished tool spans in a finally, so a turn
  that stops early or ends without a ResultMessage doesn't hold them until
  disconnect().
- A tool span drops its buffered $ai_input_state if privacy mode was turned
  on while the tool ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DanielVisca
DanielVisca merged commit 6f4cccc into main Nov 24, 2026
82 of 84 checks passed
@DanielVisca
DanielVisca deleted the perch/ai-tool-span-outcomes branch November 24, 2026 17:47
@DanielVisca

Copy link
Copy Markdown
Contributor Author

Production check, round 1. posthog-python 8.2.2 (contains 6f4cccc) was published to PyPI at 2026-11-24 17:52:57Z. posthoganalytics 8.2.2 is also out. I queried at 18:12Z against PostHog US, project 2.

Check Baseline (before 17:52Z) Now (since release) Result
Tool $ai_span with $ai_span_type='tool', plus $ai_is_error from posthog-python ≥ 8.2.2 0 tool-typed spans across all versions in the last 3 days. Expected, since earlier versions didn't set it. 0 events from 8.2.2. The newest posthog-python $ai_span traffic is 8.1.0 (langchain, 510k spans in 3 days) and older. no signal: nothing in project 2 runs 8.2.2 yet
Daily $ai_span / $ai_generation volume from posthog-python 11–23 Nov weekdays: 345k–488k spans and 3.3k–7.9k gens per day. Weekends: 112k–143k spans. 24 Nov up to 18:12Z: 324k spans, 3.5k gens. On pace with a normal weekday. no signal: all of this traffic is from older versions, so it says nothing about this change

Both checks depend on an app adopting 8.2.2. In project 2 that mostly means the PostHog app picking up posthoganalytics 8.2.2. Perch will run this round again later.

🤖 Daniel's agent · perch shepherd

DanielVisca added a commit that referenced this pull request Nov 24, 2026
…nt when sent

Follow-up to #1282, rebuilt on main:
- $ai_error comes from _format_tool_error: "ToolError" in privacy mode or for
  empty content, media redacted, plain string items kept
- Claude Agent SDK tool input is redacted when the span is sent, so settings
  changed while the tool ran apply
- the public query() closes the processor stream when the caller stops early,
  so pending tool spans are sent
- PostHogMiddleware tool spans set $ai_span_type "tool"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DanielVisca

Copy link
Copy Markdown
Contributor Author

Production check, round 1, retried at 2026-11-25 00:14Z. posthog-python 8.2.2 (contains 6f4cccc) has been on PyPI since 2026-11-24 17:52:57Z. Queries ran against PostHog US, project 2.

Check Baseline (before 17:52Z) Now (since release) Result
Tool $ai_span with $ai_span_type='tool' and $ai_is_error, posthog-python 8.2.2, last 1 day 0 tool-typed spans on any version in the 3 days before release 8.2.2 / langchain: 2,094 tool spans, 130 with $ai_is_error = true, out of 20,586 spans. Last event at 00:12Z pass
posthog-python $ai_span / $ai_generation volume, 17:53Z to now, compared with the same window 7 days earlier 127,265 spans, 1,510 gens 120,365 spans (−5.4%), 2,390 gens (+58%). 8.2.2 already carries 20,535 of those spans and 125 of those gens pass: spans are within normal weekday spread (345k–488k per day last week) and generations are up. Neither shows a drop caused by the release

Tool spans now carry the outcome fields in production, so per-tool failure rates can be computed. Here that is 130 / 2,094 ≈ 6.2% for LangChain tools on 8.2.2.

🤖 Daniel's agent · perch shepherd

@DanielVisca

DanielVisca commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Production check, round 2, run at 2026-11-25 00:16Z. That is 6.5 hours after the merge and 6.4 hours after posthog-python 8.2.2 reached PyPI (17:52Z). Queries ran against PostHog US, project 2.

Check Baseline Now Result
Tool $ai_span events ($ai_span_type='tool') with $ai_is_error, posthog-python 8.2.2, last 1 day 0 tool-typed spans on any version before the release 8.2.2 / langchain: 2,150 tool spans, 133 with $ai_is_error = true, out of 21,007 spans pass
posthog-python $ai_span / $ai_generation volume from 17:53Z to now, compared with the same window 7 days earlier 127,569 spans, 1,510 gens 120,839 spans (−5.3%), 2,390 gens (+58%). 8.2.2 accounts for 21,134 of these events pass. The span count is within normal weekday spread (345k–488k per day last week) and generations went up

Round 2 matches round 1. LangChain tool spans on 8.2.2 now carry their outcome, with a failure rate of about 6.2% (133 of 2,150).

🤖 Daniel's agent · perch shepherd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants