Repository navigation
fix(agentanalytics): log recovered tool errors as TOOL_ERROR (#2046) - #2177
haiyuan-eng-google wants to merge 22 commits into
Conversation
…2046) When a tool failure is recovered by an agent OnToolErrorCallback, a later plugin, or plugin/retryandreflect (in either registration order), emit a single TOOL_ERROR row and suppress TOOL_COMPLETED, finish_task completion tracking, and FinalResponseToolNames AGENT_RESPONSE. Part of google#2014 Fixes google#2046
20cd923 to
696dff5
Compare
|
Addressed in |
…ack context When multiple concurrent or overlapping calls to the same tool carry an empty FunctionCallID, keying toolSpans and completedTools only by agent activation and tool name causes later calls to overwrite earlier open spans and steal or discard each other's closedByError state. Add pushToolCallSpan and popToolCallSpan so empty-ID tool calls receive a unique per-invocation sequence number keyed by callback context (safely falling back on non-comparable contexts without panicking), deleted on AfterToolCallback and cleared on endInvocation with non-retaining pointer tokens handed off for late-state callbacks.
|
Addressed Review
Verified on a clean |
Replace split emptyToolCallIDs and emptyToolCallPtrs maps with a unified non-retaining (ctxType, ctxHash, baseKey) -> []emptyToolCallEntry table across live invocations and AfterRun late handoff, disambiguating same-context overlapping calls via argsPtr/argsHash while supporting pointer, comparable value, and non-comparable value contexts identically without retaining heap references.
|
Addressed all findings from both reviews on
|
… recovered finish_task events
|
Addressed the empty-ID correlation and
|
…cks and goroutines Address code review findings on recovered tool error correlation and task-mode completion tracking: - Require matching callback context pointer identity (toolCtxPtr) when consuming or recording completedTools markers under pushToolCallSpan/popToolCallSpan so reused call IDs with skipped AfterTool or BeforeTool callbacks cannot suppress later valid completions. - Require a non-zero callback context pointer (emptyToolPtr.valid) before recording or matching errored suppression entries on empty function call IDs so unrelated value contexts do not suppress each other. - Leave overlapping ambiguous empty-ID entries intact on OnToolError so ambiguous errors emit on a synthetic span without latency while both healthy and recovered calls preserve their TOOL_STARTING spans and latencies. - Track sequence numbers on rejectedTasks entries and supersede older rejected finish_task markers across goroutines when a newer non-ancestor activation started after the rejection or holds an open finish_task span.
|
Addressed all four findings from review
Verified on a clean |
Address review findings on task-mode finish_task rejection correlation, reused tool context suppression, value-context error deduplication, and ambiguous same-context overlapping spans: - Replace start-sequence supersession (other.seq > rej.seq) in popTaskAgentSpan with positive-only Event.Actions.StateDelta map provenance across all parallel tool calls of an open task activation (and strong map/context references cleared on retirement/end), alongside positive finish_task evidence (pendingFinishCalls / settledTaskCalls / open finish_task spans) so a delayed or batched rejected finish_task response (including [echo, finish_task]) never completes its own or a peer activation without positive finish evidence. - Replace raw callback context pointer matching with toolCallIdentity (unwrapping ToolContext EventActions pointers across context wrappers including WithoutCancel and timerCtx, backed by weak.Pointer retention of ended ToolContext EventActions), per-model-turn turnEpochs across live and late state, boundedArgsDigest (cycle-safe, O(1)-capped), and earlier-plugin BeforeTool+AfterTool short-circuit detection scoped to missing or reused EventActions pointers so stock earlier plugins like loggingplugin preserve recovered-error suppression. - Separate unrecovered AfterTool(err != nil) TOOL_ERROR deduplication from recovered TOOL_COMPLETED suppression so unrecovered value contexts deduplicate identically to pointer contexts, and align the recovered-error suppression documentation on EventToolCompleted. - Retire and drop leaked entries on ambiguous empty-ID overlaps in both completion orders while keeping TOOL_ERROR and TOOL_COMPLETED on synthetic unborrowed spans without latency.
|
Addressed all 5 items from review
|
…g state Address review findings on recovered tool error deduplication, finish_task provenance, and the bounds of per-activation tracking state: - Make the tool argument digest deterministic: hash map keys in sorted order, detect cycles with the stack of ancestors only, so that a value shared between map entries hashes in full wherever it appears, hash strings in full up to 64 KiB, and hash up to 256 entries of each map, slice, or struct. A digest past these bounds is marked truncated and no longer proves that two calls had equal arguments. - Treat an AfterToolCallback that ends the call with an error, because it still sees the error or a plugin/retryandreflect payload reports it, as the attempt whose TOOL_ERROR row OnToolErrorCallback wrote when its tool context and turn match, without comparing the arguments, which an earlier callback may have changed in place. Value contexts without EventActions still compare argument digests. - Keep the TOOL_COMPLETED row of a recovered call whenever plugins registered before this one register both a BeforeToolCallback and an AfterToolCallback, as loggingplugin does: such plugins can hide the failed attempt's AfterToolCallback and the BeforeToolCallback of a retry that reuses its tool context. Without such plugins the arguments are not compared; when the runner's plugins cannot be found, they must match in full. This replaces the record of ended EventActions. - Key turn epochs by agent activation instead of by agent, so that a model turn of a concurrent activation of the same agent breaks neither the suppression nor the deduplication of another activation's tool error. - Let only an open or settled finish_task call supersede a recorded rejection: a finish_task function call that a model response made but that has not run no longer does, since the event may be the delayed response of the rejected call. A finish_task call that ends without completing its task leaves the pending calls. - Release the StateDelta references of a task-mode activation once the function response event of their calls is seen: the event's own map and, for each other call of the event, the oldest map of a call with the same ID or tool name recorded in the same turn. Keep at most 64. - Count ambiguous overlapping empty-ID calls on one callback context, so that the overlap ends with one TOOL_ERROR row per failed call and one TOOL_COMPLETED row per other call. Distinct arguments tell the calls apart, and a later failure in the overlap takes over the pending error of a recovered call that already ended, so that no span of the overlap stays open. - Document which rows change when the best-effort inspection of ADK internals misses, and move misplaced doc comments to their functions.
… cases Check when a finish_task response ends a task-mode activation, not only how many AGENT_COMPLETED rows each activation gets, and pin the edge cases of tool error deduplication and StateDelta release: - A newer activation's finish_task call that fails validation no longer counts as evidence that a later response answers it, so the older activation's response ends the older activation when it arrives. - A delayed rejected finish_task response that arrives while a peer's call with the same ID has not run consumes the rejection, so the peer's own response still ends the peer when an earlier plugin answers both of its tool callbacks. - A plugin/retryandreflect payload that follows this plugin's OnToolErrorCallback adds no second TOOL_ERROR row: through the runner with loggingplugin registered first, on custom contexts, and in an overlap of empty-ID calls. - Overlapping empty-ID calls that both fail leave no span open, distinct arguments tell the calls of an overlap apart, and a failure that this plugin's OnToolErrorCallback did not see still writes its TOOL_ERROR row. - A late function response event releases the StateDelta maps of its own calls only, leaving those of later calls and later turns, so that the batch that made them still ends no peer activation.
…nt reconciliation - Match llmagent.isFinishTaskSuccessFR by letting only the first finish_task FunctionResponse decide task completion while ending later finish_task responses in the same event without retiring the activation. - Bound resolveUnattributedFinishFailuresLocked with an O(1) (activation, callSeq) candidate map, dirty-only re-resolution, and a maxTaskToolDeltas per-failure slot cap. - Scope unseenModelFinishCalls pruning to the answered batch modelCallSeq and recognize pending latest-turn finish_task echoes when late FunctionResponses arrive across overlapping activations. - Charge admitted map string key bytes upfront in boundedArgsDigest and enforce maxDigestDepth across nested maps and slices. - Drop callback contexts and unreachable parent references from retired, purged, and drained task frames.
|
Thanks for the thorough review and the repro! Addressed all five points in
|
…ghten ownership - Consume the owner's matching rejectedTasks (or deferredRejections) entry in completeResponseEvent when a superseded finish_task FunctionResponse shows its owner and the owner has no other untaken call with that ID. - Drop len(owner.finishedTasks) > 0 from ownerKnown so a peer's merged [failed, completed] response without provenance cannot end another activation's still-running finish_task call. - Remove unreachable pendingEchoOf and latestModelEventSeen bookkeeping, skip open frames in pruneRetiredFrameRefsLocked fast-path checks, and document the 32-level nesting depth bound on EventToolCompleted. - Add regression tests for superseded rejection cleanup, peer merged [failed, completed] ownership, and drained-descendant context release, and make reconciliation tests purely structural.
|
Thanks for catching that superseded-rejection edge case and the cleanup items! Pushed
Agreed on the separate nil-args |
…ded task spans - Scope superseded finish_task rejection cleanup (both rejectedTasks and deferredRejections) and batch-level popTaskAgentSpanWithEvent lookups to the answered batch's modelCallSeq when StateDelta identifies the batch, and immediately settle any peer activation holding the deferral. - Allow superseded finish_task rejection cleanup when ownerKnown is false if the owner is the sole task frame that could have written the call (no other open frame for the task and no retired or ended frame holding a rival call or rejection). - Retire an open rejecting task activation's span without emitting AGENT_COMPLETED and mark its delegating parent taskDelegated when ADK's runTask ends the task on a recovered completion response (ev.Output != nil), documenting the behavioral difference from adk-python in doc.go. - Add regression and parity tests covering cross-turn call ID reuse, cached first-call batch retries, immediate deferred-peer settlement, recovered finish_task worker span retirement, retired frame ref pruning, drained descendant endTaskStateLocked state transfer, and literal 32-level map/slice/array digest bounds.
|
Thanks for the thorough review and clear repros! Pushed
|
…flow retirement - Scope completeResponseEvent finishedTasks pairing and superseded consumption to evBatchModelSeq when StateDelta identifies the tool batch so older batches preserve newer finishedTasks entries. - Restrict rejection cleanup for superseded responses without evBatchModelSeq provenance via otherCallSeqs (answered calls, completed paired entries from owner.finishedTasks, and finishCallSlotsLocked slots) across both sole-owner and context-shown events, replacing the unscoped !hasEvBatchModelSeq fallback so failed responses never match newer finishedTasks entries and unrelated delayed batches cannot delete newer rejections. Record taskFinishCall.firstInBatch so matchesRej also preserves a batch's first finish_task rejection against superseded responses (unless a same-ID, same-batch completion already paired), closing the cross-turn ID-reuse residual for first-in-batch rejections and documenting the narrower residual when !firstInBatch and !hasEvBatchModelSeq with a shared call ID in otherCallSeqs. - Track endedRejected task activations when Event.Output is stripped (such as below workflow.NewWorkflowNode) and retire them when their delegating parent re-enters BeforeAgentCallback on the same goroutine with no intervening model, tool, error, or finish transitions; pin parent.nonLLM, parent identity (name/branch/path), rec.parentSpanID, child membership, goroutine, and all clear sites. - Scope doc.go's recovered-finish_task bullet title and lead to OnToolErrorCallback recovery, clarify ADK runTask termination vs. plugin span retirement timing and later AfterToolCallback recovery, replace internal frame phrasing, and align popTaskAgentSpanWithEvent comment references. - Drop redundant hasEvEpoch || in ownerKnown, post-reindex i > 0, and !deferred checks, and add regression tests for all batch-scoping, sole-owner, firstInBatch, re-index, completionCalls, deferred-batch, and endedRejected guards.
|
Thanks for catching these edge cases and the clear repros! Pushed
|
- Split unfinished finish_task response handling in completeResponseEvent into non-superseded attribution (plus resolveUnattributedFinishFailuresWithLocked) before superseded rejection cleanup, so otherCallSeqs collects modelCallSeq only from batch-proving answered entries, completed paired entries, and owner slots directly attributed or proven by current-event failures during the same event; gate fr.unfinished open-span entries in answered on !inv.evictedFailureCalls[o.call] (matching noteAttributed and resolveUnattributedFinishFailuresWithLocked), defer finishOpen for fr.unfinished without a matching StateDelta when the owner is neither shown nor the sole task frame for o.call or holds untaken slots for that call ID across multiple turns or model batches, keep completed paired, matchedSuperseded, and finishOpen entries out of otherCallSeqs under the same multiTurnOrUnknownFor check (allowing a single-turn, single-batch sole task owner without recognized StateDelta to still clear same-batch superseded rejections when evDeltaPtr != 0 or rej.delta is empty), prevent matchedSuperseded from stripping owner.finishedTasks on an unowned guessed peer whose batch lacks matching call counts (ownerHasSupersededBatch, while counting owner.rejectedTasks/deferredRejections and finishCallSlotsLocked for the batch and restricting need to finish_task responses and owner slots), preserve same-batch rejections in noteTaskFinished when multiple finish_task calls share an ID, sort named finish_task open spans before nameless (rec.toolName == "") spans, match nameless open spans to named non-finish_task responses before answersOpen without decrementing spare for non-finish_task responses, include nameless open finish_task spans (span.toolName == "" && span.finishCall.call != "") in unfinishedResponseSlotsLocked and finishCallSlotsLocked, close nameless non-finish_task open spans cleanly, and only delete an open finish_task span from inv.toolSpans when matched by a response in calls. - Defer single-owner multi-turn unattributed finish_task failures without StateDelta to keepFinishFailureLocked (same as shown-context calls) so neither earlier delayed batches nor later retries greedily consume the wrong turn's modelCallSeq, while keeping same-turn batch resolution intact; scope evDeltaPtr unfinished-response resolution and supersededCleanup's untaken-slot check to the identified batch's modelCallSeq when StateDelta shows it. - Scope answeredKeys in completeResponseEvent, finishedTasks consumption on the deltaOwner retirement branch (plus openFinishCallBy, finishEvidenceBy, and finishedInBatch) in popTaskAgentSpanWithEvent, and answerBatchFinishCallsLocked (exactBatch) by the identified batch's modelCallSeq (and turnEpoch) when StateDelta identifies the batch so open, settled, or finished calls from other batches do not suppress, consume, or get closed by another turn's event. On the deltaOwner branch of popTaskAgentSpanWithEvent, bound finishedTasks slot pruning by deltaRef.shownSince(c) and pass remaining (not calls) to answerBatchFinishCallsLocked so duplicate call IDs are not double-counted; store exact answered taskFinishCall slots in spanRecord.completionCalls (returned by answerBatchFinishCallsLocked and answerLatestFinishCallsLocked) so unfinishedResponseSlotsLocked and soleTaskOwnerForCall exclude the exact answered batch slot rather than subtracting from the tail when a later batch's slot is also pending. - Prune cleared finish_task slots from later unattributedFinishFailures and reconcile in noteTaskRejected (so a rejected call cannot keep a later multi-turn failure stranded against an earlier turn), and scope the pendingFinishCalls guard against deferredRejections in popTaskAgentSpanWithEvent to the event's batch (evBatchSeq). - Tag unattributedFinishFailure entries with a per-event eventID, clear evictedFailureCalls on invocation teardown, and check in resolveUnattributedFinishFailuresWithLocked whether forbidding edges from current-event failures to (owner, modelCallSeq) strictly reduces the group's maximum matching size (suppressing owner reporting if any failure for that call ID was dropped or evicted by maxTaskToolDeltas bounds), so prior-event failures and other task frames never leak into otherCallSeqs. - Document the hidden-observation and overflow-eviction residuals under "Best-effort inspection of ADK internals" in doc.go, update spanRecord.completionCalls, completeResponseEvent, popTaskAgentSpanWithEvent, and recordUnfinishedTaskResponseLocked comments, align test expectations for !ownerKnown and multi-turn unattributed calls, and add regression tests covering multi-turn and unknown-owner paired and superseded finishedTasks non-seeding, peer finishedTasks preservation, superseded batches mixing unfinished, finished, and recovered-rejected finish_task calls (including empty and duplicate call IDs and nameless owner-slot need matching), single-owner runner.New superseded rejection cleanup and replaced-earlier-event plus cached-completion behavior, nameless open span ordering, pre-matching, spare preservation, and slot accounting, deltaOwner remaining and shownSince handling, finishOpen multi-turn deferral and unmatched-open-span preservation, evictedFailureCalls gating, batch-scoped answeredKeys/openFinishCallBy/ finishEvidenceBy/finishedInBatch/deltaOwner, exact completionCalls slot agreement, prior-event kept-failure non-leakage, forced-matching proofs, overflow/eviction suppression, superseded-vs-unfinished ordering, cross-frame non-leakage, noteTaskRejected slot pruning, batch-scoped evDeltaPtr and supersededCleanup, and batch-scoped pendingFinishCalls against deferredRejections.
|
Thanks for the review. Pushed
|
…atch order - Saturate invocationTrace.evictedFailureCalls at maxTaskToolDeltas (64) distinct call IDs via evictedFailureCallsSaturated (checked by hasEvictedFailureCallLocked, flipped in noteEvictedFailureCallLocked, and reset across all invocation teardown paths), avoiding unbounded map growth while preserving conservative suppression of attribution-based rejection cleanup; update doc.go to document the 64-ID saturation rule. - Align same-batch duplicate-ID finish_task handling with llmagent.runTask's first-response rule and doc.go: carry finishTaskCallSpec (call ID + boundedArgsDigest) from finishTaskFunctionCalls through noteTaskFinishCallSpecs, idlePendingFinishCallLocked, noteTaskFinishedWithArgs, noteTaskRejectedWithArgs, and noteTaskUnfinishedWithArgs so concurrent same-ID calls bind to their emitted part order, mark only the batch's first call firstInBatch, ignore superseded non-first calls when a batch's first call was rejected after error recovery (hasFirstInBatchRejection / supersededByBatchRejection across finishedCall, openFinishCallBy, finishEvidenceBy, finishedInBatch, settledIdx, paired, finishOpen, matchesRej, finishedTasks consumption, and finishedTaskLocked), and update doc.go parity notes and TraceManager/Runner tests. - Track exact rejection slice eviction on spanRecord.rejectedTasksEvicted via appendRejectedTask / appendDeferredRejection (preserved across endTaskStateLocked and cleared in clearTaskDeltas) instead of treating a 64-element slice length as overflowed in ownerHasSupersededBatch. - Fix the misplaced keepFinishFailureLocked doc comment above noteEvictedFailureCallLocked and update the noteTaskFinished doc comment to note that same-batch rejections are preserved while earlier-batch rejections for the same call are cleared.
|
Thanks for the review — all five items are addressed in
|
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2177 (review).
…nd cap finishedTasks - Bind pending finish_task calls in idlePendingFinishCallLocked by batch-wide unique emitted Args map identity (argsPtr, keeping argsMap live only until the slot settles or retires in clearFinishCall / clearTaskDeltas) before falling back to batch-wide unique untruncated boundedArgsDigest, surviving identical, >64 KiB truncated, and in-place-mutated arguments under stock ADK dispatch. - Track uniqueArgsPtrInBatch and uniqueArgsDigestInBatch across all emitted same-ID slots in noteTaskFinishCallSpecs so overlapping BeforeToolCallback dispatch on aliased, nil, or cloned indistinguishable maps never leaves a lone remaining idle slot claiming firstInBatch; clear firstInBatch whenever batch position is indistinguishable, and document this best-effort limit in doc.go and finishTaskCallSpec. - Strip argsMap via pending.withoutArgsMap() in finishCallSlotsLocked and untakenFinishCallsLocked so retired completionCalls never retain user argument maps. - Cap spanRecord.finishedTasks at maxTaskToolDeltas (64) via keepLatest. - Remove the five test-only parallel wrapper methods (noteTaskFinished, noteTaskRejected, noteTaskUnfinished, noteTaskFinishCalls, popTaskAgentSpanWithDelta) from trace_manager.go, update stale internal doc comments to reference the production methods, and migrate test callers directly. - Expand TestRunner_DuplicateIDFinishTaskBatchOrder with deterministic reversed-dispatch cases for identical, >64 KiB, and mutated-in-place arguments in each failure position, and add TestTraceManager_DuplicateIDFinishTaskAmbiguousFallback (including overlapping BeforeToolCallback ambiguous-args subtests and GC release across both settlement and StateDelta-backed completionCalls retirement) and TestTraceManager_FinishedTasksCappedAtMaxTaskToolDeltas.
|
Thanks for the careful catch on
|
…ask tests and docs - Update TestRunner_DuplicateIDFinishTaskBatchOrder so runner hooks correlate calls without assuming FunctionCall.Args map-pointer identity when ADK clones per-call arguments before tool callbacks run, add reversed-dispatch distinct-args coverage, and verify both direct-pointer binding and cloning ambiguous-batch fallback. - Add TestTraceManager_DuplicateIDFinishTaskCloningVsDirectArgsBinding covering non-cloning argsPtr binding (identical, >64 KiB, and in-place-mutated maps) and cloning boundedArgsDigest / ambiguous-batch fallback (distinct, identical, >64 KiB, and pre-mutated maps) under reversed dispatch. - Clarify finishTaskCallSpec, idlePendingFinishCallLocked, and doc.go comments to distinguish non-cloning map-pointer binding, cloning bounded-digest binding, and ambiguous-batch fallback.
|
Pushed
|
caohy1988
left a comment
There was a problem hiding this comment.
The TOOL_ERROR part reads well and I didn't find anything blocking at this head. A few things are worth sorting out before merge, mostly in the task-completion handling.
The branch no longer merges cleanly with main. main enabled the modernize linter after this branch last merged it, and that rewrote five spots in trace_manager.go that this PR also moves (the inner.Interface().(agent.Agent) assertion, two strings.Index uses, the index loop in openFailureCauseLocked, and two more near the end of the file). The merge reports three conflict hunks. Taking the PR side compiles and passes tests but brings back the patterns the linter now rejects, so the rewrites need to be re-applied by hand when resolving.
A rejection bound to a non-first finish_task call can still drop the first call's completion. On the StateDelta-owner path in popTaskAgentSpanWithEvent, batchRejected matches a rejection by batch and call ID only and ignores firstInBatch. With a repeated call ID in one response, a rejection recorded for the second call gets applied to the event's first response whenever the first call's own completion wasn't seen by this plugin's AfterToolCallback. That can happen when a later AfterToolCallback recovers the failure or an earlier plugin answers it. The worker then gets no AGENT_COMPLETED, which the base commit does write. A related case: when the argument map is cloned and another callback normalizes the second call's arguments to match the first call's, the unique-digest match marks the wrong call as first and again suppresses a clean completion. Recording whether a call's batch position was actually proven, and only letting proven-first rejections suppress the row, fixes both in my testing without breaking the existing suite.
Rejections that never get a completing response stay around. If a later callback replaces the recovered "Task completed." with a payload that reports no completion, the rejectedTasks entry is never cleared. A later retry with the same call ID whose callbacks are hidden by an earlier plugin then gets taken as that stale rejection's delayed response. The result is no AGENT_COMPLETED for the worker or the coordinator, and the coordinator's next activation is parented under the worker span, while the invocation still reports OK. Once an event that identifies a batch has been processed, any leftover rejection for that batch can be dropped.
The bigger question is whether the AGENT_COMPLETED rule belongs in this PR. #2046 is about TOOL_ERROR, TOOL_COMPLETED and AGENT_RESPONSE, and says successful calls should keep writing the same rows. The rule that a recovered finish_task failure writes no AGENT_COMPLETED (and no AGENT_ERROR either) goes beyond that, differs from adk-python, which writes AGENT_COMPLETED for every agent run, and isn't consistent: the same ADK outcome writes the row when recovery happens in AfterToolCallback but not in OnToolErrorCallback. Most of the new state (rejectedTasks, deferredRejections, the ended-rejection frames, firstInBatch binding) exists to support it, and the two bugs above both live there. I'd keep the base rule for the activation, limit this PR to the tool rows and AGENT_RESPONSE, and, if a "recovered" signal is wanted, add it as an attribute on AGENT_COMPLETED in a follow-up. That would remove most of the complexity along with the two issues above.
|
Thank you @caohy1988 for the detailed review! Agreed on all points — especially keeping the base To make review straightforward, this PR has been split into two focused,
Keeping #2177 open as a reference pointer until #2377 and #2381 merge. |
Linked issue
Summary
Fixes #2046 by logging recovered tool errors as a single
TOOL_ERRORrow rather than a duplicateTOOL_COMPLETEDrow whenOnToolErrorCallbackorplugin/retryandreflect(retryandreflect.New, in either registration order) intercepts a tool failure and returns a replacement result map alongsidenilerror.OnToolErrorCallbackruns when a tool returns a non-nilerror, andAfterToolCallbacksubsequently runs if anOnToolErrorCallbackplugin recovers the error into a replacement result map (err == nil). Previously,plugin/agentanalyticsrecordedTOOL_ERRORinonToolErrorand then also recordedTOOL_COMPLETED(and honoredfinish_task/FinalResponseToolNamescompletion promotion) for the same tool span inafterTool.beforeTool->onToolError->afterToolso that whenonToolErrorhas already settled a tool call asTOOL_ERROR(or when the replacement result carriesplugin/retryandreflect'sERROR_HANDLED_BY_REFLECT_AND_RETRY_PLUGINresponse type),afterToolsuppresses the duplicateTOOL_COMPLETEDrow and suppressesfinish_task/FinalResponseToolNamesfinal-response promotion (matchingadk-python v2.13.0forTOOL_COMPLETEDandAGENT_RESPONSE; seedoc.gofor task-modeAGENT_COMPLETEDhandling when a failedfinish_taskis recovered with"Task completed."). Confirmation outcomes (ErrConfirmationRequired/ rejection) remain unchanged.noteTaskFinishedWithArgsonisTaskCompletedResult(result)(result["result"] == "Task completed."), capsspanRecord.finishedTasksatmaxTaskToolDeltas = 64viakeepLatest, callsendUnfinishedFinishTaskwhenafterToolsees a non-completedfinish_taskresult, scopesnoteTaskFinishedWithArgsrejection cleanup torej.modelCallSeq != rec.modelCallSeqso a later same-batch sibling never erases an earlier sibling's rejection, and recordsnoteTaskRejectedWithArgs(pruning the cleared call from laterunattributedFinishFailuresviaanswerFinishCallSlotsLockedand reconciling viaresolveUnattributedFinishFailuresLocked) with turn-scopedtaskDeltaRef(m,ptr,call,pinned,epoch,modelCallSeq, capped atmaxTaskToolDeltas = 64and released on non-partialFunctionResponsedelivery viareleaseTaskToolDeltas) plusfirstInBatch(whether the call was the model batch's firstfinish_taskcall in emitted part order, matched across concurrent goroutines inidlePendingFinishCallLockedby batch-wide unique emittedArgsmap identityargsPtr—retainingargsMaponpendingFinishCallsonly untilclearFinishCallorclearTaskDeltas, and stripped via.withoutArgsMap()infinishCallSlotsLockedanduntakenFinishCallsLockedsocompletionCallsnever retains user argument maps—before falling back to batch-wide unique untruncatedboundedArgsDigest, gatingfirstInBatchonuniqueArgsPtrInBatchanduniqueArgsDigestInBatchcomputed across all same-ID calls in the batch so overlappingBeforeToolCallbackdispatch on aliased,nil, or cloned indistinguishable maps never leaves a lone remaining idle slot claimingfirstInBatch) when a recoveredfinish_taskerror still returns"result": "Task completed.". When ADK'srunTaskterminates a task activation on that recovered completion response (ev.Output != nil),popTaskAgentSpanWithEventretires the task activation's span without emittingAGENT_COMPLETEDfor the worker and marks its delegating parenttaskDelegatedso the coordinator's interrupted activation writesAGENT_COMPLETEDand its next activation is parented under the invocation span rather than the retired worker span; when an enclosingworkflow.NewWorkflowNodestripsEvent.Output,retireEndedRejectedsetsendedRejectedandpopEndedRejectedTasksForDelegatorretires the worker and marks its delegating parent when that parent re-entersBeforeAgentCallbackwith matching LLM parent identity, directparentSpanID, child membership, and goroutine and with no intervening model, tool, error, or finish transitions.finish_taskFunctionResponsehandling withllmagent.isFinishTaskSuccessFR's first-response rule: only the firstfinish_taskFunctionResponsein an event decides whether the task-mode activation completes (taskCompletedCalls/hasTaskCompletedResponse), while any subsequentfinish_taskresponses in the same event end their calls (supersededinfunctionResponseCallSpecs) and consume their open calls (when!fr.unfinished, or forfr.unfinishedwhenStateDeltaidentifies the batch or the event showsowner— orsoleTaskOwnerForCallproves sole ownership across open, ended-rejecting, and retired task frames — and every untaken or finished call ofownerwith that ID belongs to that open call's single(epoch, modelCallSeq)batch viamultiTurnOrUnknownFor, ordering namedfinish_taskspans ahead ofrec.toolName == ""spans infinishOpen, pre-matchingrec.toolName == ""spans against named non-finish_taskresponses and non-finish_taskspare counts, skippingsupersededByBatchRejectionopen spans when!fr.unfinished, and deleting open spans frominv.toolSpansonly when matched), remainingfinishedTasksentries (bothpaired/pairedFinishedandmatchedSupersededscoped byevBatchModelSeqwhenStateDeltaidentifies the batch and excludingsupersededByBatchRejectionentries frompaired,finishedCall,openFinishCallBy,finishEvidenceBy,finishedInBatch,settledIdx,finishedTaskLocked, andpopTaskAgentSpanWithEvent's consumption loop so a superseded same-ID or distinct-ID sibling in a batch whose first call was rejected never stands in as completion evidence, and gatingmatchedSupersededwhen!ownerKnownviaownerHasSupersededBatchcountingfinish_task/owner slots acrossfinishedTasks,finishCallSlotsLocked,rejectedTasks, anddeferredRejectionswith explicitspanRecord.rejectedTasksEvictedtracking viaappendRejectedTask/appendDeferredRejection), or (whenownerKnown || soleTaskOwnerForCall(fr.call)and the owner has no remaining untaken call with that ID in the event's batch, scoped toevBatchModelSeqwhenStateDeltaidentifies the batch) the owner's matchingrejectedTasks/deferredRejectionsentry (matchesRejexcludingrej.firstInBatchand scoped toevBatchModelSeqwhenStateDeltaidentifies the batch, or whenhasEvBatchModelSeqis false tootherCallSeqscollected solely fromansweredProvesBatch-qualified entries — excluding unowned or multi-turnpaired/finishOpenentries — andprovenWithoutDeltawhen!ownerKnown && !rej.delta.empty() && evDeltaPtr == 0, gatingfr.unfinishedopen-span entries on!inv.hasEvictedFailureCallLocked(o.call),ownerslots directly attributed byrecordUnfinishedTaskResponseWithLockedwhen!inv.hasEvictedFailureCallLocked(c.call), andownermodelCallSeqvalues proven byresolveUnattributedFinishFailuresWithLockedto be answered by failures recorded during this event in every maximum matching of the call ID's bipartite failure-slot group when!inv.hasEvictedFailureCallLocked(callID), preservingmodelCallSeqonfinishCallSlotand ignoring attributions torec != owner— never matching failed responses againstowner.finishedTasks, never matchingfirstInBatchrejections againstsupersededresponses, resolving unfinished non-superseded calls and unattributed failures before superseded rejection cleanup so[unfinished, superseded]and[superseded, unfinished]behave identically, and immediately settling any peer activation holding the deferral viaretireDeferredTaskWithProofLocked) without retiring the rejecting activation. As documented under "Best-effort inspection of ADK internals" indoc.go, if an earlier plugin replaces an earlier turn's failedfinish_taskresponse event and a later turn merges a cached tool with a same-ID failure and a recovered supersededfinish_task, the ambiguous sibling failure is conservatively not attributed to the newer batch (suppressingAGENT_COMPLETEDfor the worker and its interrupted delegating parent activation if the completing turn's tool callbacks are also hidden); conversely, if an entire earlier turn (model response and tool callbacks) was hidden and its delayed merged response arrives with an unrecognizedStateDeltawhileowner's newer sibling slot sits in a single turn and model batch (with!inv.hasEvictedFailureCallLocked(c.call)),recordUnfinishedTaskResponseWithLocked(orfinishOpenwhenshown != nil) can attribute that sibling to the newer batch and consume the newer rejection.toolNameonspanRecord, matches open tool spans by both call ID and tool name (matchesOpenToolCall), records onlyfinish_taskcalls insettledTaskCalls(each with the turn epoch in which its call started) andhasOpenOrSettledFinishEvidence, checksevStateDeltaprovenance and finish-state ownership before scanning peer credits, scopesunseenModelFinishCallspruning on function responses to the answered batch'smodelCallSeq, and usesdeferredTaskFinish/deferredAgentCompletionso an older activation's unconsumedrejectedTasksentry never swallows a hidden-callback peer's sole validfinish_taskresponse.StateDeltashows it (batchEpochOf/batchModelSeqOf):answeredKeysfilters openinv.toolSpansbymodelCallSeq == evBatchModelSeq(andturnEpoch <= evEpoch),recordUnfinishedTaskResponseWithLockedscopesevDeltaPtrunfinished-call attribution tod.modelCallSeq, and on thedeltaOwnerIdxbranch ofpopTaskAgentSpanWithEventfinishedInBatch, therec.finishedTasksconsumption loop (bounding slot pruning bydeltaRef.shownSince(c)whenhasDeltaRefis true),openFinishCallBy,finishEvidenceBy, andanswerBatchFinishCallsLocked(exactBatch, receivingremainingrather than fullcallsso duplicate call IDs consumed byfinishedTasksare not double-counted) scope toevBatchSeq/d.modelCallSeq(andturnEpoch <= evEpoch) while storing the exact answered[]taskFinishCallslots inspanRecord.completionCalls(shared byunfinishedResponseSlotsLockedandsoleTaskOwnerForCall) so open, settled, finished, or later-batch pending calls neither mask nor split slots across batches, and an older merged[echo, finish_task]response can neither end a retry's open call nor retire its activation early.finish_taskresponses that report no completion (functionResponseCall.unfinished): once the response shows which task-mode activation it belongs to (the open call that it answers whenStateDeltaidentifies the batch or!multiTurnOrUnknownwith a single(epoch, modelCallSeq)batch of untaken/finished/answered calls for that ID, theStateDeltathat it carries scoped tod.modelCallSeq, or whenshown == nilthe only open activation whosefinish_taskcall with that ID may still be answered and whose untaken calls with that ID belong to a single turn and model batch, including one that ended visibly without completion, tracked inunfinishedFinishCalls), it consumes that activation's call and cancels its deferred completion; while ownership or turn attribution across multiple turns is unresolved, kept failures tagged with their per-eventeventIDand at mostmaxTaskToolDeltas = 64candidate slots are reconciled inresolveUnattributedFinishFailuresWithLocked(dirty-only re-resolution, O(1)(activation, callSeq)candidate indexing, and bounded per-invocationevictedFailureCallssaturated atmaxTaskToolDeltasviaevictedFailureCallsSaturated, reset across all invocation teardown paths) while retired task frames drop callback contexts and unreachable parent references (dropRetiredContextsLocked/pruneRetiredFrameRefsLocked), and nameless openfinish_taskspans (span.toolName == "" && span.finishCall.call != "") remain visible tofinishCallSlotsLockedandunfinishedResponseSlotsLocked.BeforeTool,OnToolError, andAfterTool(including acrossAfterRunlate-state handoff) using per-attempt identity (toolCallIdentity:ctxPtr, the attempt'sEventActions, per-activationturnEpochs, and race-safeboundedArgsDigestviaargsDigesterusinghash/maphash, sorted map keys with upfront key-byte charging, up to 32 levels of container nesting viamaxDigestDepth = 32, ancestor-stack cycle detection, and opaquetruncated = truehandling forreflect.Pointerandreflect.Structvalues without dereferencing pointers or reading struct fields).unwrapToolContextActionsreads unexported fields only of ADK's tool and callback context wrappers, thecommonContextthat they wrap, and the standard library's context types (knownContextFields); a context of any other type tells itsEventActionsthrough itsActions()method, so a custom context's private fields, which it may guard with its own synchronization, are never read.errorEndedSameAttempt: whencurID.hasActions()istrue(every stock ADK tool dispatch viaagent.NewToolContext), recoveredAfterToolCallbackrows are suppressed unconditionally in all plugin registration orders (including[loggingplugin, analytics],[analytics, loggingplugin], and split before/after plugins) and even when an earlier callback mutatesargsin place; whencurID.hasActions()isfalseon a custom pointer context (curID.ctxPtr != 0), suppression requires unchanged untruncated JSON-shaped arguments (rec.toolCallID.sameArgs(curID)); whenunrecoveredErristrueandcurID.hasAttemptIdentity()istrue, deduplication matches onrec.toolCallID.sameContext(curID)andrec.turnEpoch == curEpochwithout requiring unchanged or untruncated argument digests. On a value context without attempt identity, the error marker keeps the arguments map thatOnToolErrorCallbacksaw when its digest is complete (errArgs): an error-bearingAfterToolCallbackthat sees another map whose complete digest differs belongs to another attempt and gets its own row (argsShowOtherAttempt), and a recoveredAfterToolCallbackconsumes the marker of its turn while keeping itsTOOL_COMPLETEDrow. Reusing a singletool.Contextorsession.EventActionsacross separate tool dispatches in the same model turn is documented as unsupported.Behavior change
Tool errors recovered into a replacement map by
OnToolErrorCallbackorplugin/retryandreflectnow emit only a singleTOOL_ERRORrow (and no longer emit a trailingTOOL_COMPLETEDrow, markfinish_taskcomplete, or promote aFinalResponseToolNamesAGENT_RESPONSE), matchingadk-python v2.13.0on tool and final-response rows (for customtool.Contextimplementations withoutActions()or a top-level pointer identity, suppression requires a non-emptyFunctionCallID; reusing a singletool.Contextorsession.EventActionsacross separate tool dispatches in the same model turn is unsupported). When a failedfinish_taskcall is recovered with{"result": "Task completed."}by an agent or later-pluginOnToolErrorCallback(including when a subsequentfinish_taskcall in the same model batch, with a distinct ID or a duplicate ID distinguishable by emitted argument-map identity or complete argument digest, succeeds cleanly), ADK Go'srunTaskstill ends the task activation on that response without runningAfterAgentCallback; Go retires the activation's span then (or, when a nestedworkflow.NewWorkflowNodeclearsEvent.Output, once its delegating parent re-entersBeforeAgentCallback) and marks its delegating parent so the coordinator's interrupted activation emitsAGENT_COMPLETEDand its next activation is parented cleanly, while omittingAGENT_COMPLETEDfor the task activation whosefinish_taskfailed (documented under "Behavioral Differences from adk-python" indoc.go, sinceadk-pythonwritesAGENT_COMPLETEDviaafter_agent_callback; when a later plugin or agentAfterToolCallbackrecovers the failure instead,analyticsPlugin.afterToolseesniland records the call as unfinished so the task activation still writesAGENT_COMPLETED, pinned byTestRunner_RecoveredFinishTaskEndsWorkerSpanAndDelegator/later_after_tool_callback_recovers_finish_taskas existing behavior). If a runner (including ADKmainviacloneArgs) clones indistinguishable (identical or digest-truncated) argument maps for duplicate-IDfinish_taskcalls in one batch or two parts alias the same map pointer, batch position is best-effort and callback start order never provesfirstInBatch(preserving any clean completion rather than dropping it). Mergedfinish_taskFunctionResponseevents followllmagent.isFinishTaskSuccessFR's first-response rule: only the firstfinish_taskresponse in an event can complete the task activation, while laterfinish_taskresponses in the same event end their calls without retiring the activation (with hidden-observation and overflow-eviction fallbacks documented under "Best-effort inspection of ADK internals" indoc.go). On custom value contexts, a later failure of the same call in the same turn whoseBeforeToolCallbackandOnToolErrorCallbackwere both skipped gets its ownTOOL_ERRORrow unless its arguments are the failed call's own map, equal, or past the digest bounds, as theEventToolErrorgodoc documents. Unrecovered tool errors, normal tool completions, and HITL tool-confirmation flows are unchanged.Testing Plan
main(11f4e29f) into the branch in9bb2b9afwithout rewriting history.mainmoved the package documentation intodoc.go, so this PR's "Best-effort inspection of ADK internals" section now lives indoc.goahead of "Behavioral Differences from adk-python", andbigquery_agent_analytics_plugin.gono longer carries a package comment;TestDocGo_ParityBulletsReferenceExistingTestsand theTestDocParity_*tests pass.plugin/agentanalyticsunit and-racetests pass locally at5c2da4b6(on top of48f6a6f2) under bothGOWORK=off(adk/v2 v2.0.0) and mergedorigin/main(02b1d0b5) +go work init && go work use -r .:go -C plugin/agentanalytics test -race -mod=readonly -shuffle=on -count=1 -parallel=2 ./...(341.661swithGOWORK=off;344.176smerged with02b1d0b5+go.work),GOWORK=off go -C plugin/agentanalytics test -mod=readonly -count=1 -parallel=2 -coverprofile=... ./...(94.1%package statements;0/0executable blocks/statements in48f6a6f2..5c2da4b6since5c2da4b6changes only docs/comments and tests,44/44blocks /75/75statements =100.00%over78c2735b..5c2da4b6, and114/114blocks /224/224statements =100.00%over45d922a1..5c2da4b6acrossbigquery_agent_analytics_plugin.goandtrace_manager.go),GOWORK=off go vet -mod=readonly ./...(both modules),GOWORK=off go build -mod=readonly ./...and mergedorigin/main+go.workgo -C plugin/agentanalytics build -mod=readonly ./...,GOWORK=off go mod tidy -diff(both modules) and mergedorigin/main+go.workgo -C plugin/agentanalytics mod tidy -diff,gofmt -l plugin/agentanalytics,git diff --check 48f6a6f2..HEAD,./.github/scripts/check-conventional-subject.sh .github/release-please-config.json,./.github/scripts/apidiff.sh 11f4e29f(No incompatible changes.under mergedorigin/main+go.work), andgolangci-lint(0issues acrossfmt --diff plugin/agentanalytics,GOWORK=off --new-from-rev=48f6a6f2 --enable=modernize ./...,GOWORK=off --new-from-rev=45d922a1 --enable=modernize ./...,GOWORK=off --new-from-rev=11f4e29f ./..., and mergedorigin/main+go.work--new-from-rev=02b1d0b5 --enable=modernize ./...inplugin/agentanalytics), plus2/2targeted mutant kills at5c2da4b6(0survivors). (Root-module-racesubsets./agent/llmagent/... ./agent/remoteagent/... ./internal/... ./workflow/...last ran at48f6a6f2;5c2da4b6touches onlyplugin/agentanalytics/.)origin/main(and noting changes at45d922a1and78c2735b):TestPlugin_RecoveredToolError_AgentCallbackTestPlugin_RecoveredToolError_LaterPluginTestPlugin_RecoveredToolError_RetryAndReflectBeforeAnalyticsTestPlugin_RecoveredToolError_RetryAndReflectAfterThisPluginTestPlugin_RecoveredToolError_LoggingPluginOrderTestPlugin_RecoveredToolError_ArgumentsMutatedInPlaceTestPlugin_RecoveredToolError_SharedNestedArgsUnrecoveredTestPlugin_RecoveredToolError_HiddenBatchLeaderDelayedRejectedFinishTestPlugin_RecoveredToolError_CustomExecutorReusedContextCachedRetryTestPlugin_RecoveredToolError_ChangedArgumentsOnReusedContextTestPlugin_RecoveredToolError_ConcurrentPeerTurnTestPlugin_RecoveredToolError_TaskToolDeltasReleasedTestPlugin_RecoveredToolError_AmbiguousOverlapUnrecoveredTestPlugin_RecoveredToolError_FinalResponseToolSuppressedTestPlugin_RecoveredToolError_FinishTaskDoesNotNoteTaskFinishedTestPlugin_RecoveredToolError_FinishTaskCrossActivationDroppedOrSuppressedTestPlugin_RecoveredToolError_DelayedRejectedFinishLeavesNewPeerOpenTestPlugin_RecoveredToolError_RunnerDelayedRejectedFinishTestPlugin_RecoveredToolError_RunnerRejectedFinishSingleRunTestPlugin_RecoveredToolError_RejectedFinishPeerStartedAfterTestPlugin_RecoveredToolError_RejectedFinishConcurrentBothSkippedTestPlugin_RecoveredToolError_ReusedContextSkippedBeforeTestPlugin_RecoveredToolError_UnrecoveredValueContextTestPlugin_RecoveredToolError_AmbiguousOverlapNoBorrowedSpanTestPlugin_RecoveredToolError_AmbiguousOverlapBothFailTestPlugin_RecoveredToolError_AmbiguousOverlapDistinctArgsTestPlugin_RecoveredToolError_DelayedRejectionConsumedBeforeHiddenPeerFinishTestPlugin_RecoveredToolError_UnfinishedFinishTaskClearsPendingCallTestPlugin_RecoveredToolError_TaskToolDeltasKeepLaterCallsTestPlugin_RecoveredToolError_TaskToolDeltasKeepLaterTurnsTestPlugin_RecoveredToolError_OpaqueStructAndPointerArgsRaceSafeTestPlugin_RecoveredToolError_RejectedFinishThreeHolesTestPlugin_RecoveredToolError_SequentialRetryTestPlugin_RecoveredToolError_OverlappedEmptyIDRecoveryTestPlugin_RecoveredToolError_EmptyIDEdgeCasesTestPlugin_RecoveredToolError_LateValueContextHandoffTestPlugin_RecoveredToolError_MutableLockedContextNoRaceTestPlugin_RecoveredToolError_SkippedAfterCallbackSameArgsRetryTestPlugin_RecoveredToolError_ClosureFactoryOverlapPreservesValidCompletionTestPlugin_RecoveredToolError_CyclicArgsMapConstantTimeTestPlugin_RecoveredToolError_SkippedCallbacksReusedIDTestPlugin_RecoveredToolError_ValueContextSkippedBeforeTestPlugin_RecoveredToolError_RejectedFinishDifferentGoroutineTestPlugin_RecoveredToolError_SameContextOverlapTestPlugin_RecoveredToolError_CustomContextPrivateActionsNotReadTestPlugin_RecoveredToolError_StaleValueContextMarkerTestPlugin_RecoveredToolError_DelayedRejectionThenPeerFinishFailsTestRunner_SupersededRejectedFinishDoesNotLeakRejectionTestRunner_SupersededBatchWithRejectedAndFinishedDoesNotLeakFinishedTaskTestRunner_HiddenEarlierResponseAndCachedCompletionKeepsSupersededRejectionTestRunner_RecoveredFinishTaskEndsWorkerSpanAndDelegator(andlater_after_tool_callback_recovers_finish_taskpins existingAfterToolCallbackrecovery behavior)TestRunner_DuplicateIDFinishTaskBatchOrder(added at78c2735b, expanded at48f6a6f2, updated at5c2da4b6forcloneArgs; 10 subtests verifyingfirst_rejected_second_clean_omits_worker_completed,first_clean_second_rejected_emits_worker_completed,reversed_dispatch_distinct_args_*, and deterministic reversed-dispatch cases with identical, oversized >64 KiB, and in-place-mutated arguments in each failure position end to end throughrunner.Newunder both directFunctionCall.Argsdispatch andcloneArgsdispatch)TestTraceManager_DuplicateIDFinishTaskCloningVsDirectArgsBinding(new at5c2da4b6; 11 subtests covering direct non-cloningargsPtrbinding for identical, oversized >64 KiB, and in-place-mutated maps alongsidecloneArgs-style fresh map copies for distinct-argsboundedArgsDigestbinding and identical/oversized/pre-mutated ambiguous-batch fail-safe fallback)TestTraceManager_DuplicateIDFinishTaskAmbiguousFallback(new at48f6a6f2; pins cloned identical/oversized maps, aliased map pointer, skipped-BeforeToolCallbackmap-pointer ordering + cloned fallback, overlappingBeforeToolCallbackambiguous-args dispatch across aliased/nil/cloned-identical/cloned-oversized maps in both completion orders, andargsMapGC release on settlement andStateDelta-backedcompletionCallsretirement)TestTraceManager_FinishedTasksCappedAtMaxTaskToolDeltas(new at48f6a6f2; pins the 64-entry cap onspanRecord.finishedTasks)TestDocParity_RecoveredFinishTaskOmitsWorkerAgentCompletedTestPlugin_OverlappingTaskActivations_LateFunctionResponseKeepsRetryEchoTestTraceManager_MergedFinishResponsesAnswerCallsOnceTestTraceManager_PeerMergedFailedCompletedDoesNotEndOpenCallWhenOwnerHasFinishedTaskTestTraceManager_SupersededRejectionBatchModelSeqAndDeferredPeerTestTraceManager_SupersededFinishedTaskAndSoleOwnerCrossTurn(updatedsame_batch_duplicate_id_rejected_and_clean_consumes_rejectionand addedsame_batch_duplicate_id_first_clean_second_rejected_emits_completionat78c2735b)TestTraceManager_TaskBatchScopingAndEndedRejectedTestTraceManager_OtherCallSeqsCountsOnlyAttributedSlotsTestTraceManager_EvictedFailureCallsSaturationAndRejOverflowBoundary(new at78c2735b; pinsevictedFailureCallssaturation at 64 distinct IDs, exact 64 vs 65 re-eviction/overflow boundaries,rejectedTasksEvictedonrejectedTasks/deferredRejections, and teardown reset)TestTraceManager_DuplicateIDFirstRejectedBranches(new at78c2735b; pinsdeltaOwner,deferredRejections,finishedInBatch,settledIdx,openFinishCallBy/finishOpen,finishEvidenceBy,paired,matchesRej, andfinishedTaskLockedundersupersededByBatchRejection/firstInBatch)TestTraceManager_PopTaskAgentSpanRecoveredFinishBranchesTestResolveUnattributedFinishFailures_BoundedCandidatesAndDirtySkipTestBoundedArgsDigest_NestedMapsChargeKeysAtAdmissionAndBoundDepthTestTraceManager_RetiredTaskFrameDropsCallbackContextsTestTraceManager_DrainedDescendantDropsCallbackContextsTestTraceManager_PruneRetiredFrameRefsAfterChildCallEndsTestTraceManager_UnwrapContext_CustomLayoutsTestTraceManager_EmptyToolCallContextCleanupTestTraceManager_TurnEpochsLateHandoffAndCleanupTestTraceManager_TaskDeltaRetentionAndCleanupTestTraceManager_UnwrapContext_WithoutCancelTestBoundedArgsDigestTestTraceManager_RecoveredToolErrorEmitsOnlyToolErrororigin/mainand pin multi-turn / cross-activation behavior alongside the PR changes:TestRunner_TwoFinishCallsFirstFails(verifies ADK'sisFinishTaskSuccessFRfirst-response rule when the firstfinish_taskcall in a batch fails and the second succeeds)TestRunner_SupersededRejectedFinishWithoutStateDeltaDoesNotLeakToLaterActivation(pins cross-activation isolation under an unrecordedStateDelta)TestPlugin_RecoveredToolError_VisibleFailureKeepsHiddenPeerDeferralpasses at45d922a1and78c2735b: it pins that a failure reported in plain sight by another activation does not cancel a hidden-callback peer's deferred completion.trace_manager_test.goat45d922a1—TestTraceManager_FunctionResponseEndsWaitForModelEvent,TestTraceManager_FailureOfOwnRunTakesOpenCall/context_of_run(plussingle_turn_context_of_run), andTestTraceManager_FailedResponseEndsFailedCallOfItsTurn/multi_turn_without_delta_waits_for_count— to pin the deliberate behavior change where a single failure with no recognizedStateDeltaacross same-ID calls in multiple turns is now kept instead of ending the earliest turn's call.