Repository navigation
refactor(observability): stop depending on lmnr to propagate trace context into tool workers - #4360
Conversation
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>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
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>
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 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 sharedContextobjects, 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:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing. See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- 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
/iterateto 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
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 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().runpassed directly toexecutor.submit()— one line, zero complexity. - Async (
_arun_safe): explicitctx = copy_context()captured in the event-loop coroutine, wrapped in a no-arg closure forrun_in_executor— necessary becauserun_in_executor(unlikeasyncio.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, actualThreadPoolExecutor, actualcontextvarsmachinery) — 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.pyalone 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
HUMAN:
Explicitly propagate trace context on parallel tool calls
AGENT:
Why
When
tool_concurrency_limit > 1,ParallelToolExecutordispatches tool calls to araw
ThreadPoolExecutor—executor.submiton the sync path,loop.run_in_executoron the async one (which calls
submitinternally). Neither copiescontextvars.Tool spans nest correctly anyway, because lmnr monkeypatches
concurrent.futures.ThreadPoolExecutor.submitand propagates its isolated context —the context
@observeparents new spans against:lmnr/opentelemetry_lib/opentelemetry/instrumentation/threading/__init__.py(__wrap_thread_pool_submit)TracerWrapper.__new__(lmnr/opentelemetry_lib/tracing/__init__.py:149),before and independent of the
instruments=/block_instrumentsfilterSo 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#39trace-quality investigation expensive.This PR does two things about that:
depends on lmnr patching stdlib.
_assert_lmnr_wraps_submit()fails loudly the moment lmnr stopswrapping
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:
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
contextvarsinto eachParallelToolExecutorworker,on both the sync (
executor.submit) and async (run_in_executor) paths.copy_context()per submitted task: onecontextvars.Contextcannot beentered by two threads at once (
RuntimeError: cannot enter context ... is already entered), which a shared-context implementation would hit precisely when the batchis parallel enough to matter.
*_without_lmnr(rawTracerProvider— the gap thischange closes) and
*_with_lmnr(realTracerWrapper, guarded by the canary), soneither configuration can be mistaken for the other.
agent.py. No change tolaminar.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#39sample wasconsumer-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
Reverting only
parallel_executor.pyto this PR's base gives 10 failed, 1 passed.The single pass is
test_lmnr_isolated_context_survives_the_context_copy, which is ano-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+Conversationattool_concurrency_limit=2with lmnr initialized, exported spans diffed before/after:identical — 2 TOOL spans under
agent.stepeither way, on both dispatch paths. This isthe evidence for the "changes nothing today" claim at the top.
Video/Screenshots
Not applicable — observability plumbing, covered by the span-parentage assertions above.
Type
Notes
The one real behaviour delta. An auto-instrumented span created in a worker thread
outside an
observespan was previously parentless and is now parented underagent.step. Almost certainly an improvement, but it is a change, and it is the onlyone.
A smaller alternative, if the code is not wanted. Keep only the canary tests and
drop the
parallel_executor.pychange. That still converts a future silent lmnrregression 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 firesfor 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 doso on the default sequential path too, changing trace shape for every user.
Same gap, not addressed here.
AgentBase.astep(agent/base.py:665) doesloop.run_in_executor(None, self.step, …)with no context copy — it would orphan anentire step rather than just TOOL spans.
AgentandACPAgentboth overrideastep,so the exposure is limited to third-party subclasses. Also four
run_in_executorsitesin
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
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:e3dc96f-pythonRun
All tags pushed for this build
About Multi-Architecture Support
e3dc96f-python) is a multi-arch manifest supporting both amd64 and arm64e3dc96f-python-amd64) are also available if needed