Skip to content

refactor(observability): stop depending on lmnr to propagate trace context into tool workers - #4360

Merged
simonrosenberg merged 3 commits into
mainfrom
fix-parallel-tool-span-context
Aug 4, 2026
Merged

simonrosenberg merged 3 commits into
mainfrom
fix-parallel-tool-span-context

Conversation

@simonrosenberg

@simonrosenberg simonrosenberg commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

HUMAN:

Explicitly propagate trace context on parallel tool calls


AGENT:

This changes nothing about the traces we emit today. With lmnr initialized —
the only configuration in which TOOL spans exist at all — the exported trace shape
is byte-identical before and after. Merge this for the dependency it removes and
the canary it adds, not for a defect it fixes. It fixes none.

Why

When tool_concurrency_limit > 1, ParallelToolExecutor dispatches tool calls to a
raw ThreadPoolExecutor — executor.submit on the sync path, loop.run_in_executor
on the async one (which calls submit internally). Neither copies contextvars.

Tool spans nest correctly anyway, because lmnr monkeypatches
concurrent.futures.ThreadPoolExecutor.submit
and propagates its isolated context —
the context @observe parents new spans against:

  • lmnr/opentelemetry_lib/opentelemetry/instrumentation/threading/__init__.py (__wrap_thread_pool_submit)
  • installed unconditionally in TracerWrapper.__new__ (lmnr/opentelemetry_lib/tracing/__init__.py:149),
    before and independent of the instruments= / block_instruments filter

So correct span parentage on our hottest observability path is currently a property of
a third-party monkeypatch of a stdlib method. That dependency is undocumented, outside
our control, and pinned only as lmnr>=0.7.56,<0.8.0 — free to move inside the range,
with a 0.8 bump foreseeable.

The problem is not the likelihood, it is the failure mode. If that patch ever changes,
tool spans orphan silently: no exception, no failing test, no alert. The corruption
surfaces months later in an exported training corpus. That is exactly the detection
latency that made the dataset-utils#39 trace-quality investigation expensive.

This PR does two things about that:

  1. Makes propagation ours. The context is copied explicitly, so parentage no longer
    depends on lmnr patching stdlib.
  2. Adds a canary. _assert_lmnr_wraps_submit() fails loudly the moment lmnr stops
    wrapping submit, instead of degrading into a silently-passing test.

It also closes two gaps lmnr does not cover, since lmnr propagates only its own
isolated context — measured inside a worker thread with lmnr live:

dispatcher   lmnr_isolated=975cee…  otel_global=975cee…  plain_cv=set-by-dispatcher
before       lmnr_isolated=975cee…  otel_global=0000…    plain_cv=UNSET
after        lmnr_isolated=975cee…  otel_global=975cee…  plain_cv=set-by-dispatcher

Nothing in the SDK creates spans with a raw OTel tracer today, so that gap is latent —
but any standard OTel auto-instrumentation used inside a tool would hit it.

Summary

  • Copy the dispatching thread's contextvars into each ParallelToolExecutor worker,
    on both the sync (executor.submit) and async (run_in_executor) paths.
  • A fresh copy_context() per submitted task: one contextvars.Context cannot be
    entered by two threads at once (RuntimeError: cannot enter context ... is already entered), which a shared-context implementation would hit precisely when the batch
    is parallel enough to matter.
  • Tests split explicitly into *_without_lmnr (raw TracerProvider — the gap this
    change closes) and *_with_lmnr (real TracerWrapper, guarded by the canary), so
    neither configuration can be mistaken for the other.
  • No change to agent.py. No change to laminar.py.

Issue Number

Context: #4358. This PR does not fix Bug 1 of that issue, and deliberately carries
no closing keyword.

Bug 1's diagnosis — that parallel dispatch orphans TOOL spans — does not hold; lmnr's
threading instrumentation already prevents it in every reachable configuration. The
actual cause of the unmatched tool calls in the dataset-utils#39 sample was
consumer-side: positional call/result pairing in the export tooling, since fixed there.
A correction is posted on #4358. #4359 covers Bug 2.

How to Test

uv run pytest tests/sdk/agent/test_parallel_tool_span_context.py -q   # 11 passed
uv run pytest tests/sdk/agent/ tests/sdk/observability/ -q            # 851 passed
uv run ruff check <changed files>                                     # All checks passed!
uv run ruff format --check <changed files>                            # 2 files already formatted
uv run pyright <changed files>                                        # 0 errors, 0 warnings

Reverting only parallel_executor.py to this PR's base gives 10 failed, 1 passed.
The single pass is test_lmnr_isolated_context_survives_the_context_copy, which is a
no-regression guard and is supposed to pass without the change — stated here rather
than presented as evidence for it.

Stability under contention (the parallel paths are timing-sensitive): 25 consecutive
runs of the new file and 5 full-suite runs under pytest -n 4, zero failures.

Production-shape check. A real Agent + Conversation at
tool_concurrency_limit=2 with lmnr initialized, exported spans diffed before/after:
identical — 2 TOOL spans under agent.step either way, on both dispatch paths. This is
the evidence for the "changes nothing today" claim at the top.

Video/Screenshots

Not applicable — observability plumbing, covered by the span-parentage assertions above.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

The one real behaviour delta. An auto-instrumented span created in a worker thread
outside an observe span was previously parentless and is now parented under
agent.step. Almost certainly an improvement, but it is a change, and it is the only
one.

A smaller alternative, if the code is not wanted. Keep only the canary tests and
drop the parallel_executor.py change. That still converts a future silent lmnr
regression into a loud CI failure, at the cost of reacting to a broken build rather
than never being exposed. Merging the full change and merging only the canary are both
defensible; merging nothing leaves the silent failure mode in place.

Rejected alternative. #4358 suggested making _root_span_from_args
(observability/laminar.py) see the conversation so the existing reattachment fires
for TOOL spans. Verified empirically that this re-parents TOOL spans onto the
conversation root span, flattening them out from under agent.step — and it would do
so on the default sequential path too, changing trace shape for every user.

Same gap, not addressed here. AgentBase.astep (agent/base.py:665) does
loop.run_in_executor(None, self.step, …) with no context copy — it would orphan an
entire step rather than just TOOL spans. Agent and ACPAgent both override astep,
so the exposure is limited to third-party subclasses. Also four run_in_executor sites
in llm/llm.py (965, 1952, 2259, 2316).


Agent Server images for this PR

• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:e3dc96f-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-e3dc96f-python \
  ghcr.io/openhands/agent-server:e3dc96f-python

All tags pushed for this build

ghcr.io/openhands/agent-server:e3dc96f-golang-amd64
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-golang-amd64
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-golang-amd64
ghcr.io/openhands/agent-server:e3dc96f-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:e3dc96f-golang-arm64
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-golang-arm64
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-golang-arm64
ghcr.io/openhands/agent-server:e3dc96f-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:e3dc96f-java-amd64
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-java-amd64
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-java-amd64
ghcr.io/openhands/agent-server:e3dc96f-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:e3dc96f-java-arm64
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-java-arm64
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-java-arm64
ghcr.io/openhands/agent-server:e3dc96f-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:e3dc96f-python-amd64
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-python-amd64
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-python-amd64
ghcr.io/openhands/agent-server:e3dc96f-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:e3dc96f-python-arm64
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-python-arm64
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-python-arm64
ghcr.io/openhands/agent-server:e3dc96f-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:e3dc96f-golang
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-golang
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-golang
ghcr.io/openhands/agent-server:e3dc96f-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:e3dc96f-java
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-java
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-java
ghcr.io/openhands/agent-server:e3dc96f-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:e3dc96f-python
ghcr.io/openhands/agent-server:e3dc96f4fe6dc746be0f19a5111aeebfefdde48f-python
ghcr.io/openhands/agent-server:fix-parallel-tool-span-context-python
ghcr.io/openhands/agent-server:e3dc96f-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., e3dc96f-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., e3dc96f-python-amd64) are also available if needed

ThreadPoolExecutor.submit and loop.run_in_executor do not copy contextvars,
so every tool call dispatched off the main thread under
tool_concurrency_limit > 1 started a parentless OTel context and its TOOL
span was orphaned from the conversation trace.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/agent
   parallel_executor.py82890%142, 213, 217–221, 226
TOTAL389291114371% 

lmnr's vendored ThreadingInstrumentor already patches
ThreadPoolExecutor.submit, so TOOL spans are not orphaned in the
configuration the SDK actually runs in. Add tests that bring up a real
TracerWrapper and pin what the context copy does buy there -- the OTel
global context and plain ContextVars, which lmnr does not carry -- and
narrow the docstring and comments to match.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@simonrosenberg simonrosenberg changed the title fix(observability): propagate trace context into parallel tool execution refactor(observability): own trace-context propagation into parallel tool execution Aug 4, 2026
@simonrosenberg simonrosenberg self-assigned this Aug 4, 2026

all-hands-bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟢 Taste Rating: Good taste

The production change is intentionally small: copy the caller context once per dispatched tool task, with fresh Context objects so parallel workers cannot trip over contextvars re-entry. The new coverage exercises both raw OpenTelemetry and lmnr-initialized paths, including the important guard that lmnr isolated context still survives.

I’m leaving this as a COMMENT, not an APPROVE, because this repository’s review guide asks automation not to approve changes touching tool execution / potential eval behavior without eval-monitor evidence or human maintainer confirmation. From code review perspective, I did not find blocking issues.

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM
    This touches parallel tool dispatch context propagation, so the behavioral blast radius is not zero. The implementation itself is minimal, avoids shared Context objects, and the captured PR status shows the SDK/cross/workspace/agent-server checks passing.

VERDICT:
✅ Worth merging: Core logic is sound; human maintainer should make the final call after the repo’s lightweight eval expectations are satisfied.

KEY INSIGHT:
Owning context propagation at the executor boundary is the right abstraction; relying on lmnr’s stdlib monkeypatch is hidden coupling.

Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:

  1. Add a .agents/skills/custom-codereview-guide.md file to your branch (or edit it if one already exists) with the /codereview trigger and the context the reviewer is missing. See the customization docs for the required frontmatter format.
  2. Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
  3. When your PR is merged, the guideline file goes through normal code review by repository maintainers.

Resolve with AI? Install the iterate skill in your agent and run /iterate to automatically drive this PR through CI, review, and QA until it’s merge-ready.

Was this review helpful? React with 👍 or 👎 to give feedback.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

@simonrosenberg simonrosenberg changed the title refactor(observability): own trace-context propagation into parallel tool execution refactor(observability): stop depending on lmnr to propagate trace context into tool workers Aug 4, 2026
@simonrosenberg
simonrosenberg marked this pull request as ready for review August 4, 2026 13:34

all-hands-bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟢 Good taste — Elegant, minimal solution to a real, well-documented problem.

Summary

This PR removes a hidden dependency: correct TOOL span parentage in parallel tool workers was silently riding on lmnr's monkeypatch of ThreadPoolExecutor.submit. This is undocumented, outside the SDK's control, and fails silently — spans orphan with no exception, no test failure. The fix is the correct, stdlib-only approach: contextvars.copy_context() per dispatched task.

Both dispatch paths are covered:

  • Sync (execute_batch): contextvars.copy_context().run passed directly to executor.submit() — one line, zero complexity.
  • Async (_arun_safe): explicit ctx = copy_context() captured in the event-loop coroutine, wrapped in a no-arg closure for run_in_executor — necessary because run_in_executor (unlike asyncio.to_thread) does not propagate contextvars.

The fresh-copy-per-task requirement is also correct: a single Context cannot be entered by two threads simultaneously (RuntimeError: cannot enter context: ... is already entered). The tests verify this under forced concurrency via threading.Barrier.

Test quality

The test suite is excellent:

  • Exercises real code paths (actual ParallelToolExecutor, actual ThreadPoolExecutor, actual contextvars machinery) — not a pile of mocks.
  • Asserts on outputs and state (span parent IDs, ContextVar values).
  • Barrier-based concurrency tests that would fail if a shared Context were used instead of per-task copies.
  • Canary (_assert_lmnr_wraps_submit) that converts a future silent lmnr regression into an immediate loud CI failure.
  • Without-lmnr and with-lmnr configurations tested separately so neither can be mistaken for the other.
  • Revert evidence is included: reverting parallel_executor.py alone gives 10 failed/1 passed.

What this changes in production

As documented: traces are byte-identical today (lmnr's patch was already covering the span-nesting case). The only observable delta is that OTel spans created directly (raw tracer, not via @observe) in a worker thread are now parented under agent.step rather than being roots. That is a strict improvement.

Remaining gaps (documented, out of scope)

The PR correctly calls out AgentBase.astep and four run_in_executor sites in llm/llm.py as separate issues. No action needed here.

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟢 LOW
    Pure internal plumbing change. No API surface modified. Production trace shape is identical to current behavior (verified via exported span diff). The only observable delta — OTel-raw spans in workers becoming parented — is an improvement. Comprehensive test coverage including concurrency stress.

VERDICT:
✅ Worth merging: Implementation is correct, tests are solid, evidence is thorough.

KEY INSIGHT:
Converting an implicit, undocumented dependency on a third-party stdlib monkeypatch into an explicit, first-party copy_context() call is exactly the right move — it makes the invariant ours to maintain.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

@simonrosenberg
simonrosenberg merged commit 1ae6a16 into main Aug 4, 2026
39 of 40 checks passed
@simonrosenberg
simonrosenberg deleted the fix-parallel-tool-span-context branch August 4, 2026 14:09
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