Repository navigation
fix(observability): mark utility LLM spans (title generation, ask_agent) - #4359
Conversation
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
|||||||||||||||||||||||||||||||||||||||||||||
…y runs Conversation titles in a deployed agent-server come from AutoTitleSubscriber, which calls generate_title_from_message directly rather than through the decorated LocalConversation.generate_title. Its LLM span was an orphan in its own trace, so the marker added for the SDK path never reached production. Route it through an observed helper that takes the conversation as its first positional argument, which is where observe finds the root span to re-attach across the create_task + run_in_executor hops. Drop the marker from RemoteConversation.ask_agent: it is pure HTTP delegation with no local LLM span, and no trace context is propagated to the server. 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: 🟢 Good taste. The change is targeted, solves a real observability problem (utility spans and main-loop turns are now distinguishable in traces), and ships with end-to-end tests that drive a real Laminar tracer through InMemorySpanExporter and assert on exported attributes — not a pile of mocks.
The new _generate_title_traced wrapper is the awkward bit, but the inline comment correctly captures the non-obvious invariant: it exists purely so that _maybe_use_root_span can find the root span via args[0] on the context-less executor thread. That is real architectural tech debt in _maybe_use_root_span (its args[0] heuristic forces this kind of fake-first-arg at every cross-context call site), not a smell introduced by this PR — worth a follow-up to make the root span explicit at the call site (e.g. with use_root_span(root): await loop.run_in_executor(...)), but not in scope here.
Tests are well-constructed: the subprocess indirection exists for a real reason (Laminar.initialize() mutates process-global tracing), and the unit test asserts on the kwargs handed to lmnr.observe at decoration time, which is the real wire contract.
[RISK ASSESSMENT]
- [Overall PR] Risk Assessment: 🟢 LOW
Adds new metadata on existing@observe-decorated spans and adds one thread-safe wrapper for the executor-thread title path. No public API change, no behavior change, no breaking surface. New tests are pure additions.
VERDICT: Worth merging.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation.
|
🤖 OpenHands is reviewing this PR. Head commit: This comment was posted by an AI agent (OpenHands). |
HUMAN:
Add metadata to ask_agent and title generation so they are distinguishable from regular agent outputs in Laminar.
AGENT:
Why
generate_titleandask_agentrun LLM completions alongside a conversation, andtheir LLM spans are indistinguishable from real agent turns. A consumer that fetches
"all LLM spans for this session" (dataset-utils rebuilding a training trajectory from
Laminar) splices their output in as a genuine assistant turn.
Confirmed in production data: a trace whose "assistant" step content is the whole
string
"💄 Generate Title with Emoji\x00"—generate_title's degenerate output,spliced into the middle of a real conversation and flagged downstream as text
corruption.
Nothing marked these calls as side utilities, so there was nothing to filter on:
agent.llm— the same LLM andusage_idas themain loop — so not even the usage id distinguishes it.
LocalConversation.ask_agenthad no@observeat all onmain, so its LLMspan had no distinguishing ancestor span either.
Titles do not come from
LocalConversation.generate_titlein production — theycome from
AutoTitleSubscriberinconversation_service.py, which calls themodule-level
generate_title_from_messagehelper directly from arun_in_executorworker thread. That thread inherits no OTel context, so thelitellm.completionspan was a root span in its own trace — while stillcarrying the conversation's
session_id. A session-keyed consumer thereforepicked it up with no ancestor to filter it out. This is the exact shape that
produced the corruption above.
Summary
OPERATION_METADATA_KEY = "openhands.operation"inopenhands/sdk/observability/laminar.py, exported fromopenhands.sdk.observability, so the marker downstream consumers filter on has asingle source of truth.
conversation_service.py): routeAutoTitleSubscriber's executor call through a new_generate_title_tracedhelper carrying
@observe(name="conversation.generate_title", metadata={...}).The conversation is passed as the helper's first positional argument — that
is where
observe's_maybe_use_root_spanlooks for_observability_root_span,and re-attaching it there is what turns the orphan into a real child of the
conversation trace across both the
asyncio.create_taskand therun_in_executorhop.LocalConversation.generate_title/RemoteConversation.generate_title: addmetadata={OPERATION_METADATA_KEY: "title_generation"}to the existing@observe.LocalConversation.ask_agent: add@observe(name="conversation.ask_agent", metadata={...: "ask_agent"})— itpreviously had no span at all. This one is on the deployed path:
POST /{id}/ask_agent→ConversationService.ask_agent→EventService.ask_agent→run_in_executor(..., self._conversation.ask_agent, ...).RemoteConversation.ask_agent: not decorated (see Notes for why).InMemorySpanExporterin a subprocess:tests/sdk/conversation/test_utility_llm_span_metadata.py(SDK conversationmethods) and
tests/agent_server/test_auto_title_span_metadata.py(theagent-server auto-title path, asserting both the marker and same-trace parenting).
LLM spans are not created by
@observe— they come from lmnr's LiteLLMauto-instrumentation as children of the enclosing
@observespan.metadata=isthe only lmnr channel that reaches them:
_setup_spanstampslmnr.association.properties.metadata.<key>,set_association_props_in_contextlifts it into the OTel context, and
LaminarSpanProcessor.on_startre-stamps itonto every descendant.
tags=does not propagate (it keeps thelmnr.association.properties.prefix, whichset_association_props_in_contextfilters out), and plain span attributes never propagate in OTel.
Issue Number
Partially addresses #4358 (Bug 2 of 2). Bug 1 — the TOOL-span parent loss under
ParallelToolExecutor— is PR #4360, so this one does not close the issue.How to Test
Everything below was run on this branch at
aacc6b136.1. The production auto-title path now joins the conversation trace
The new agent-server probe is directly runnable. It initializes a real
Laminartracer, swaps
LaminarSpanProcessor.instancefor aSimpleSpanProcessor(InMemorySpanExporter()), enables the realInstruments.LITELLMauto-instrumentation, builds a realConversationplus aStoredConversation, and firesAutoTitleSubscriberwith a userMessageEvent— i.e. the full
create_task→run_in_executor→litellm.completionchain,with
litellm's ownmock_responsestanding in for network I/O:Before (sources at the pre-PR base
8c2297b19) — the orphan:After — a real child of the conversation root, same trace, marked:
Note
lmnr.span.input—ignore_inputs=["conversation", "llm"]keeps theconversation object and the LLM out of the recorded span input.
2. End-to-end: the marker reaches the real exported LLM span (SDK methods)
Exported spans (name / parent / propagated metadata):
Three things this shows:
litellm.completionLLM span, notjust on the
@observespan — that is the property a session-level consumerneeds.
litellm.completionunderagent.stepdoes not carry it.
repo, supplied viaobservability_metadata) still reaches every span, so nothing regressed there.parent=Noneon the four top-level spans is the conversation root span, which isstill open (never ended) and therefore not in the exporter — normal, not a
regression.
3. Regression tests
Confirmed both tests actually catch the bug — with the three changed source files
reverted to the pre-PR base (
git checkout 8c2297b19 -- <3 source files>) and onlythe tests kept:
4. Existing suites, lint, types
Video/Screenshots
N/A — observability-only change; the span dumps in "How to Test" are the observable
output.
Type
Notes
Why the auto-title fix is shaped this way
Two options were on the table for covering
AutoTitleSubscriber:(a) Route it through
LocalConversation.generate_titleso it inherits theexisting decorator. Rejected: it changes behaviour.
AutoTitleSubscriberdeliberately extracts the message text before spawning its background task, to
avoid a race where the event is not yet in the events list;
generate_titlegoesback to
self._state.active_branch()and re-extracts, reopening that race. It alsoraises
ValueErrorwhen no user message is found, which would degrade the currenttruncation fallback into "no title at all" (the
except Exception: logger.warningswallows it).
(b) Decorate the auto-title call itself — chosen. The one trap is that a naive
decorator does not fix the orphan:
_maybe_use_root_span/_root_span_from_argsonly re-attach the root span when
args[0]carries_observability_root_span,and
_generate_and_saveis a zero-arg closure. So the helper takes theconversation as its first positional argument. That parameter is unused in the body
(
# noqa: ARG001) and carries a comment saying why it must stay — deleting itwould silently reintroduce the orphan with green CI. The "before/after" dump in
"How to Test" is the proof the reparenting works across both the
create_taskandrun_in_executorhops.Behaviour is otherwise untouched: still non-blocking/background, still swallows
exceptions with
logger.warning, still guards on "title already set", stilltitle_llm_profile→agent.llm→ truncation, and the LLM is still resolvedbefore the task is spawned.
RemoteConversation.ask_agentis deliberately not decoratedAn earlier revision of this PR decorated it for symmetry. Removed, because the
decoration buys nothing and costs something:
for the marker to reach.
traceparent(it does not import
opentelemetryat all), lmnr'sInstrumentsenum has nohttpx/requests instrumentor, and agent-server installs no OTel extract middleware.
So the server-side span is not in the client's trace either.
LocalConversation.ask_agent, which ison the deployed path via
POST /{id}/ask_agent.openhands.operationinto the client trace'smetadata — which, given the trace-level rollup below, makes a client trace
advertise a marker for which it holds no marked LLM span, and can
non-deterministically clobber the trace-level value when a client-side
generate_titlehappens in the same trace.RemoteConversation.generate_titleis genuinely different and keeps its marker: itruns
generate_conversation_titleclient-side, so there is a real local LLMspan to mark.
Metadata is trace-level in Laminar's data model — known trade-off
At the OTel level the marker is strictly subtree-scoped, proven by the tests above,
and that span-level view is what the downstream consumer actually reads. But
Laminar's ingestion also rolls per-span metadata up into the trace record: its
backend aggregates spans into a trace (
TraceAggregation::from_spans), merging thelmnr.association.properties.metadata.*of every span in the trace and upsertingwith
metadata = COALESCE(traces.metadata || EXCLUDED.metadata, ...). Laminar's owndocs say the same thing from the user side:
Consequences, stated plainly:
openhands.operationat trace level, in the Laminar UI and API.ask_agent, the trace-levelvalue is last-writer-wins and therefore non-deterministic.
RemoteConversation.ask_agent's decoration (above) removes one of the two waysthis could happen client-side.
(The backend specifics —
TraceAggregation::from_spans, theCOALESCEupsert —come from review of Laminar's server source, not from anything I ran here. The
docs quote and the span-level behaviour are both verified.)
I still went with metadata, because:
stable, subtree-scoped answer, which is the only thing needed to stop splicing
utility output into trajectories.
things (
user_id,session_id,trace_type,metadata); metadata is the onlynon-reserved one, so no span-subtree-scoped attribute channel exists in lmnr.
it yet.
If a reviewer would rather keep trace-level metadata pristine, the conflict-free
variant is one key per operation (
openhands.utility.title_generation = true,openhands.utility.ask_agent = true): each key then has exactly one possible value,so the merge is deterministic. It costs consumers a prefix match instead of an
equality check. Happy to switch.
Marker key: why
openhands.operationand not bareoperationobservability_metadatais a fully caller-controlled dict of arbitrary keys(
repo,repo_name, …) landing in the samelmnr.association.properties.metadata.*namespace, and_validate_observability_metadataaccepts any non-empty string key — including"openhands.operation"itself. So namespacing does not make collision impossible;it makes it implausible.
operationis a generic enough word that a caller couldalready be using it;
openhands.operationis unambiguously SDK-owned. The dottedkey round-trips cleanly through lmnr (
on_startstrips only the fixedlmnr.association.properties.metadata.prefix), as the span dumps show.Both tests assert the raw exported attribute name
lmnr.association.properties.metadata.openhands.operationas a literal, not viaOPERATION_METADATA_KEY. Renaming the constant's value would otherwise leave thesuite green while silently breaking every downstream filter.
ask_agentbehavior reviewself.agent.ask_agent, used byACPAgent'sfork_session) is untouched:@observewraps the call, the early return isinside the body, so return value and control flow are identical.
tests/sdk/agent/test_acp_agent.pyis green.LocalConversation.ask_agentis a real trace-shape change,and a beneficial one beyond the marker:
EventService.ask_agentdispatches vialoop.run_in_executor(None, self._conversation.ask_agent, question), i.e. apooled worker thread where
contextvarspropagation is unreliable. With thedecorator,
_maybe_use_root_spanfires —args[0]is the conversation — andre-attaches the conversation root span, exactly as the auto-title fix does.
Server-side
ask_agentLLM spans should now be correctly parented rather thanorphaned. Verified in-process by the span dump above; not verified against a live
agent-server.
@observe(name="conversation.send_message")alreadyrecords the user's full message text and
generate_titlealready records thegenerated title, so recording
ask_agent's question and answer is consistentwith what the SDK already emits. Note this is not because the codebase never
redacts —
hooks/executor.py:204usesignore_inputs=["self", "hook", "event"]and
ignore_output=Trueon perfectly serializable pydantic models, sosuppression for reasons other than serializability does have precedent. The
argument here is consistency with the sibling conversation methods, not a house
rule. Easy to add
ignore_input/ignore_outputif the team disagrees.Test isolation
Both end-to-end probes run in a subprocess.
Laminar.initialize()flipsprocess-global state that cannot be undone — global
TracerProvider, permanentshould_enable_observability() == True, global litellm instrumentation, and aBatchLogRecordProcessorbackground thread — which would silently change everylater test in the same pytest worker. The three in-process cases use the existing
patch("lmnr.observe", ...)pattern fromtests/sdk/observability/test_laminar.pyand exploit the lazy build in
observe's wrapper; the recorder returns the functionunchanged so the wrapper cache it leaves behind is behaviourally identical to no
decorator.
Deliberately out of scope (follow-ups)
A consumer trusting
openhands.operationalone is not yet fully protected —these LLM calls still emit unmarked spans inside a conversation trace:
context/condenser/llm_summarizing_condenser.py:293and:338). Same class of defect: a trajectory rebuilder will splice condensationsummaries in as assistant turns. A two-line follow-up using the same
OPERATION_METADATA_KEY.hooks/executor.py:204)._execute_agent_hookspawns a nestedLocalConversation, so its LLM spans are literally namedagent.stepinside theparent trace — indistinguishable by name from the real loop, and the worst case
for a name-based filter.
\x00NUL byte in title output. Real corruption seen in production(
"…Emoji\x00"), but it is a sanitization concern at the title/consumer boundary,not a span-tagging one.
usage_id/LLM profile for title generation. Would make theutility call distinguishable by usage id too, but it changes cost attribution and
other work is in flight there.
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:7785537-pythonRun
All tags pushed for this build
About Multi-Architecture Support
7785537-python) is a multi-arch manifest supporting both amd64 and arm647785537-python-amd64) are also available if needed