Add explicit parent/child hierarchy to agent process events
Context
I'm currently refactoring the observability module and to add an evaluation module for agents, actions, tools, and LLM calls.
This evaluation module needs a reliable way to know the exact hierarchy of what happened during an agent run.
Today, observation listeners (e.g. EmbabelTracingObservationHandler) must reconstruct the hierarchy between spans (Agent → LLM Call → Tool Loop → Tool Call) by maintaining maps and guessing relationships based on timing or keys.
Most of teh time it worked, but this approach is fragile, especially when there is heavy parallelism at multiple levels:
- Multiple agents running concurrently
- Multiple actions executing in parallel within an agent
- Multiple LLM calls happening simultaneously within an action
- User code creating its own threads inside actions or methods used as tools
In these scenarios, reconstructing the correct parent/child relationships after the fact becomes unreliable - timing-based heuristics break down and map lookups can match the wrong parent.
For an evaluation module, this is a blocker: you can't evaluate what you can't accurately observe.
Proposal
Introduce explicit observationNodeId / parentObservationNodeId fields in the event model so that the hierarchy is captured at emission time and forms a tree:
Agent (root, parentNodeId = null) └─ LLM Call (parentNodeId = agent.nodeId) └─ Tool Loop (parentNodeId = llmCall.nodeId) └─ Tool Call (parentNodeId = toolLoop.nodeId)
Each node generates its own nodeId (UUID) and passes it down to its children. Listeners then just do a simple map.get(parentNodeId) instead of scanning maps and guessing relationships.
Something like:
abstract class AbstractAgentProcessEvent(
val agentProcess: AgentProcess,
val observationNodeId: String = UUID.randomUUID().toString(),
val parentObservationNodeId: String? = null, // null for root agent
)
Whenever the core code fires a child event, it passes the parent's observationNodeId as parentObservationNodeId.
For example, when starting a Tool Loop, the code already has a reference to the LLM call that triggered it - so it would just pass llmCallEvent.observationNodeId as the parent.
Goal
Build an arbitrary-depth observation tree where:
- The hierarchy is explicit and correct by construction
- No reconstruction or heuristics are needed on the listener side
- Parallel calls are handled naturally (each gets its own nodeId), even when users spawn their own threads
- The tree can support future nesting levels without listener changes
- The upcoming evaluation module can reliably correlate metrics to the exact node in the execution tree
Question
Is there already a mechanism in the core (OperationContext, AgentProcess, etc.) that would let a child event know which node launched it?
I've already implemented and tested this approach locally - it works. I'm opening this issue to check whether there's an easier or more idiomatic way to achieve the same result using existing mechanisms in the core, before submitting a PR.
@azanux - speaking about AgentProcess in general: a. child agent process has reference to parent b. all children for a given parent can be obtained by API findbyParent Idin AgentProcessRepository
Im not familiar in depth with observability implementation, and I assumed your inquiry is how to factor observability cleanly into SubAgents, AgenticTool, and ParallelToolLoop.
Thank you
@igordayen
Thanks for the clarification!
What I'm looking for is actually an intra-agent hierarchy -- tracking the elements within the agent process itself: Agent -> Action -> LLM Call -> Tool Loop -> Tool Call, and so on.
In the same way an AgentProcess can find its parent via parentId, I need the inner elements (Action, LLM Call, Tool Loop, Tool Call) to also have a way to find their parent in the execution tree.
If I understand correctly, there's currently no existing mechanism in the core for this intra-agent hierarchy -- the parentId / findByParentId only covers the agent-to-agent relationship.
Can you confirm?
Would it be sufficient to gather this information through the listener mechanism, with AgenticEventListener.onProcessEvent? Are the payloads sufficiently informative for this to work?
@johnsonr
Great question - the listener mechanism with onProcessEvent works well for sequential flows, but the current payloads don't carry enough information to reliably reconstruct the hierarchy under parallelism.
What works today: Each event carries contextual references like action, interactionId, and correlationId. In a single-threaded sequential execution, a listener can use these to infer parent/child relationships (e.g., "this tool loop belongs to this LLM call because they share the same interactionId").
Where it breaks down: When multiple actions, LLM calls, or tool loops run concurrently, these shared references become ambiguous - there's no way for the listener to determine which specific LLM call triggered which specific tool loop. This is further complicated by the fact that tool loops can call tools that themselves trigger LLM calls, creating nested and potentially recursive hierarchies. The listener has to fall back to timing heuristics or tracer.currentSpan(), and it works, but both fail under to complicated parallelism - especially with user-spawned threads in action/tools
The proposed fix: Add two fields to AbstractAgentProcessEvent:
- observationNodeId - a unique UUID for each event
- parentObservationNodeId - pointing to the event that triggered it
The key insight is that the emitting code already has the parent context at hand - for example, when ToolLoopLlmOperations starts a tool loop, it already holds a reference to the LlmRequestEvent that triggered it. So the hierarchy information exists in the core; it's just not surfaced in the event payloads today.
By adding these two fields, we make the payloads self-describing: each event knows where it sits in the tree. The listener mechanism stays exactly the same - onProcessEvent still receives all events - but listeners no longer need to infer relationships. They just read them.
maybe introduce ObservationContext as { observationNodeId, parentObservationNodeId). Also be advised that randomUUID is not really unique. If you need real uniqueness you may want to consider custom UUID generator in order to factor in threadId and JVM instance.
@igordayen
Thanks for the idea! We followed your suggestion and introduced ObservationContext with { observationNodeId, parentObservationNodeId } on the events.
Regarding randomUUID, noted. In the context of AI agents (llm latency) where observation volumes are far from a billion per second, the collision probability is negligible - I think it's a good trade-off.
@azanux - could you please update, thank you
@igordayen Started working on it, but not finished - will continue this weekend.
@igordayen
Just found this ticket. Wanted to chime in and say we currently experience the problems outlined by @azanux in the initial post. Using ChatBot, PARALLEL mode and custom logic running async in agents, the observability breaks down.
Langfuse has the concepts of Observation, Trace, Session
In my opinion a trace should encapsulate all observations within a single agent run e.g. from UserMessage until AgentProcess reaches a state which requires new user input e.g. COMPLETED, FAILED, TERMINATED, KILLED, STUCK
Especially the in the ChatBot case we usually land in the STUCK state after a successful turn, which is also marked as an error, but actually the expected state.
A session should span across all traces with the same conversationId. I think using the agentProcessId might lead to not having the whole conversation in a session as a new agentProcess might be spawned for example after an application restart.
Todos I see:
- Define what a session and trace should encapsulate, also for the ChatBot case
- Introduce processing of user data e.g. userId so that backends can group by users e.g. Langfuse has a own tab for that
- STUCK should not be an error state with ChatBot usage as it is the expected state after a successful run
@stefanks-px Thanks a lot for feedbacks - really useful input, and your framing of trace/session and the STUCK point shaped the direction here.
Here's a small update on this issue
Parallelism / async hierarchy - The hierarchy is now explicit on the events. Each AbstractAgentProcessEvent carries an ObservationContext with:
nodeId- a unique UUID per event;parentNodeId- the parent context'snodeId, resolved from the surroundingObservationScopeor set explicitly viachild().
A ContextPropagatingExecutor decorator propagates the current node id (and the AgentProcess) onto worker threads, so parent/child resolution holds under PARALLEL mode and custom async logic instead of relying on thread-locals.
Trace. The trace closes on the states that hand control back for good - COMPLETED, FAILED, KILLED, TERMINATED - each ending the root span, (with error status only where it applies, e.g. FAILED, or a TERMINATED flagged error=true).
STUCK deliberately does not close the trace. In the ChatBot case a single AgentProcess lives across the whole conversation and resumes on the next UserMessage, so closing the root span on STUCK would orphan the spans of the following turn
STUCK is no longer reported as an error. You were right: the core already models it as non-error , so STUCK is now a normal span (state still queryable via embabel.lifecycle.state = STUCK) and no longer shows up red.
Session. agentProcessId was used because the chat layer was still early when the observability module landed. We now have a better key: the chat layer binds a Conversation (StableIdentified, stable id) into the blackboard, stable across all AgentProcess runs of one conversation. So gen_ai.conversation.id resolves to Conversation.id (resolved at span close, since the conversation is bound after the creation event), giving Langfuse a session spanning all turns
Open question: for non-conversational runs (no
Conversationin the blackboard) I currently fall back torunId. OK for you, or should it be left unset?
User. Available via ChatSession.user / Chatbot.createSession(user, …), it flows into the process as ProcessOptions.identities.forUser and exposes id / username / displayName / email. We read it at creation to set the user.id span attribute (Langfuse "Users" grouping); when anonymous (null), no attribute is emitted.
@igordayen @stefanks-px happy to discuss and hear your opinion on it.
Session.
agentProcessIdwas used because the chat layer was still early when the observability module landed. We now have a better key: the chat layer binds aConversation(StableIdentified, stable id) into the blackboard, stable across allAgentProcessruns of one conversation. Sogen_ai.conversation.idresolves toConversation.id(resolved at span close, since the conversation is bound after the creation event), giving Langfuse a session spanning all turnsOpen question: for non-conversational runs (no
Conversationin the blackboard) I currently fall back torunId. OK for you, or should it be left unset?
- agree. to have conv id , and if its not avail - agent id, thanks
@igordayen @azanux
Thanks for the cooperation and incorporation of the feedback.
Open question: for non-conversational runs (no
Conversationin the blackboard) I currently fall back torunId. OK for you, or should it be left unset?* agree. to have conv id , and if its not avail - agent id, thanks
Also agree.
If the trace is not closed on STUCK will the whole conversation appear as one trace in the backend e.g. Langfuse? The metrics for latency might not be meaningful then.
If the trace is not closed on STUCK will the whole conversation appear as one trace in the backend e.g. Langfuse? The metrics for latency might not be meaningful then.
@stefanks-px you are right, I see two possible solutions here: either modify the RAG directly to close and create a new agent id, or handle this case directly in the observability layer - where, when there's a STUCK, the agent span is automatically closed, then reopened afterwards when the agent continues its execution. Let me think about the best solution.
@stefanks-px
The "turn" Span
Here's some thinking on how to handle the turn in the chat case.
The "turn" span opens and closes on two points of the agent's lifecycle.
Note: this is specific to the chat case -
UserMessageandChatTriggeronly exist in a chat context, so for a non-chat (one-shot) agent no turn span is opened and the current behavior is unchanged.
Open - when a new turn starts
We listen to ObjectAddedEvent: if the added object is a UserMessage (user's message) or a ChatTrigger (automatic trigger), a turn is starting → we open the span.
Close - when the agent has finished working
We listen to the event emitted when run() exits. In the chat case it's almost always AgentProcessStuckEvent (the agent is waiting for the next message). But a turn can also end with one of the following → we close the span on any of these five:
AgentProcessStuckEventAgentProcessWaitingEventAgentProcessCompletedEventAgentProcessFailedEventAgentProcessPausedEvent
This way the span covers exactly the agent's work, from receiving the message until it pauses - without the idle wait that follows.
Span hierarchy
⏺ Session = Conversation.id (replaces the role of "the agent across the whole conversation")
│
├─ Trace — Turn 1
│ └─ turn span (ROOT, replaces the "agent" span) ← UserMessage → STUCK [5s]
│ ├─ action A span
│ │ ├─ LLM span
│ │ └─ tool-loop span
│ │ └─ tool call span
│ └─ action B span
│ └─ LLM span
│
├─ Trace — Turn 2
│ └─ turn span (ROOT) ← UserMessage → STUCK [8s]
│ └─ action C span
│ └─ LLM span
│
└─ Trace — Turn 3
└─ turn span (ROOT) ← UserMessage → COMPLETED [12s]
├─ action D span
│ └─ LLM span
└─ action E span
Just. have another idea for that. @stefanks-px simple that above
Agent span latency in chat: segmenting by active period
Problem
In chat, there's a single long-lived AgentProcess per conversation. The agent span opens on AgentProcessCreationEvent and only closes on Completed/Failed. Between turns, the process goes back to STUCK (the normal resting state) but the span stays open → its duration in Langfuse includes all the idle time while the user is thinking. The reported latency no longer reflects the agent's actual work.
Constraint
A span (OTel/Micrometer) has duration = end − start. You cannot pause it. The only way to exclude idle time is to segment: close the span on STUCK, open a fresh one on resume. The gap between two segments is covered by no span → excluded from latency.
Solution (observability only, zero core changes)
Make the agent span scoped to the active period:
| Event | Action |
|---|---|
Stuck / Waiting / Paused |
close the segment + clean up its nodeId |
ReadyToPlan |
reopen a fresh segment if none is open (idempotent) |
Completed / Failed |
unchanged |
ReadyToPlan is the first observable event of every run(), so it's a reliable resume signal.
Guards (otherwise other cases break)
Only act if isRootProcess() && blackboard.last(Conversation) != null:
- excludes sub-agents (non-null
parentId) → they stay nested; - excludes one-shot agents (no
Conversation) → behavior unchanged.
The tricky part - reattaching children despite a constant runId
Children don't attach to the runId; they resolve a nodeId via the runId:
will try this and see