Skip to content

fix(agentanalytics): log recovered tool errors as TOOL_ERROR (#2046) - #2177

Closed
haiyuan-eng-google wants to merge 22 commits into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2046-recovered-tool-error
Closed

haiyuan-eng-google wants to merge 22 commits into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2046-recovered-tool-error

Conversation

@haiyuan-eng-google

@haiyuan-eng-google haiyuan-eng-google commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Summary

Fixes #2046 by logging recovered tool errors as a single TOOL_ERROR row rather than a duplicate TOOL_COMPLETED row when OnToolErrorCallback or plugin/retryandreflect (retryandreflect.New, in either registration order) intercepts a tool failure and returns a replacement result map alongside nil error.

  • Problem: In ADK's tool execution pipeline, OnToolErrorCallback runs when a tool returns a non-nil error, and AfterToolCallback subsequently runs if an OnToolErrorCallback plugin recovers the error into a replacement result map (err == nil). Previously, plugin/agentanalytics recorded TOOL_ERROR in onToolError and then also recorded TOOL_COMPLETED (and honored finish_task / FinalResponseToolNames completion promotion) for the same tool span in afterTool.
  • Solution:
    • Tracks per-tool-call error recovery state across beforeTool -> onToolError -> afterTool so that when onToolError has already settled a tool call as TOOL_ERROR (or when the replacement result carries plugin/retryandreflect's ERROR_HANDLED_BY_REFLECT_AND_RETRY_PLUGIN response type), afterTool suppresses the duplicate TOOL_COMPLETED row and suppresses finish_task / FinalResponseToolNames final-response promotion (matching adk-python v2.13.0 for TOOL_COMPLETED and AGENT_RESPONSE; see doc.go for task-mode AGENT_COMPLETED handling when a failed finish_task is recovered with "Task completed."). Confirmation outcomes (ErrConfirmationRequired / rejection) remain unchanged.
    • Gates normal-path noteTaskFinishedWithArgs on isTaskCompletedResult(result) (result["result"] == "Task completed."), caps spanRecord.finishedTasks at maxTaskToolDeltas = 64 via keepLatest, calls endUnfinishedFinishTask when afterTool sees a non-completed finish_task result, scopes noteTaskFinishedWithArgs rejection cleanup to rej.modelCallSeq != rec.modelCallSeq so a later same-batch sibling never erases an earlier sibling's rejection, and records noteTaskRejectedWithArgs (pruning the cleared call from later unattributedFinishFailures via answerFinishCallSlotsLocked and reconciling via resolveUnattributedFinishFailuresLocked) with turn-scoped taskDeltaRef (m, ptr, call, pinned, epoch, modelCallSeq, capped at maxTaskToolDeltas = 64 and released on non-partial FunctionResponse delivery via releaseTaskToolDeltas) plus firstInBatch (whether the call was the model batch's first finish_task call in emitted part order, matched across concurrent goroutines in idlePendingFinishCallLocked by batch-wide unique emitted Args map identity argsPtr—retaining argsMap on pendingFinishCalls only until clearFinishCall or clearTaskDeltas, and stripped via .withoutArgsMap() in finishCallSlotsLocked and untakenFinishCallsLocked so completionCalls never retains user argument maps—before falling back to batch-wide unique untruncated boundedArgsDigest, gating firstInBatch on uniqueArgsPtrInBatch and uniqueArgsDigestInBatch computed across all same-ID calls in the batch so overlapping BeforeToolCallback dispatch on aliased, nil, or cloned indistinguishable maps never leaves a lone remaining idle slot claiming firstInBatch) when a recovered finish_task error still returns "result": "Task completed.". When ADK's runTask terminates a task activation on that recovered completion response (ev.Output != nil), popTaskAgentSpanWithEvent retires the task activation's span without emitting AGENT_COMPLETED for the worker and marks its delegating parent taskDelegated so the coordinator's interrupted activation writes AGENT_COMPLETED and its next activation is parented under the invocation span rather than the retired worker span; when an enclosing workflow.NewWorkflowNode strips Event.Output, retireEndedRejected sets endedRejected and popEndedRejectedTasksForDelegator retires the worker and marks its delegating parent when that parent re-enters BeforeAgentCallback with matching LLM parent identity, direct parentSpanID, child membership, and goroutine and with no intervening model, tool, error, or finish transitions.
    • Aligns merged finish_task FunctionResponse handling with llmagent.isFinishTaskSuccessFR's first-response rule: only the first finish_task FunctionResponse in an event decides whether the task-mode activation completes (taskCompletedCalls / hasTaskCompletedResponse), while any subsequent finish_task responses in the same event end their calls (superseded in functionResponseCallSpecs) and consume their open calls (when !fr.unfinished, or for fr.unfinished when StateDelta identifies the batch or the event shows owner — or soleTaskOwnerForCall proves sole ownership across open, ended-rejecting, and retired task frames — and every untaken or finished call of owner with that ID belongs to that open call's single (epoch, modelCallSeq) batch via multiTurnOrUnknownFor, ordering named finish_task spans ahead of rec.toolName == "" spans in finishOpen, pre-matching rec.toolName == "" spans against named non-finish_task responses and non-finish_task spare counts, skipping supersededByBatchRejection open spans when !fr.unfinished, and deleting open spans from inv.toolSpans only when matched), remaining finishedTasks entries (both paired / pairedFinished and matchedSuperseded scoped by evBatchModelSeq when StateDelta identifies the batch and excluding supersededByBatchRejection entries from paired, finishedCall, openFinishCallBy, finishEvidenceBy, finishedInBatch, settledIdx, finishedTaskLocked, and popTaskAgentSpanWithEvent'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 gating matchedSuperseded when !ownerKnown via ownerHasSupersededBatch counting finish_task/owner slots across finishedTasks, finishCallSlotsLocked, rejectedTasks, and deferredRejections with explicit spanRecord.rejectedTasksEvicted tracking via appendRejectedTask / appendDeferredRejection), or (when ownerKnown || soleTaskOwnerForCall(fr.call) and the owner has no remaining untaken call with that ID in the event's batch, scoped to evBatchModelSeq when StateDelta identifies the batch) the owner's matching rejectedTasks / deferredRejections entry (matchesRej excluding rej.firstInBatch and scoped to evBatchModelSeq when StateDelta identifies the batch, or when hasEvBatchModelSeq is false to otherCallSeqs collected solely from answeredProvesBatch-qualified entries — excluding unowned or multi-turn paired/finishOpen entries — and provenWithoutDelta when !ownerKnown && !rej.delta.empty() && evDeltaPtr == 0, gating fr.unfinished open-span entries on !inv.hasEvictedFailureCallLocked(o.call), owner slots directly attributed by recordUnfinishedTaskResponseWithLocked when !inv.hasEvictedFailureCallLocked(c.call), and owner modelCallSeq values proven by resolveUnattributedFinishFailuresWithLocked to 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), preserving modelCallSeq on finishCallSlot and ignoring attributions to rec != owner — never matching failed responses against owner.finishedTasks, never matching firstInBatch rejections against superseded responses, 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 via retireDeferredTaskWithProofLocked) without retiring the rejecting activation. As documented under "Best-effort inspection of ADK internals" in doc.go, if an earlier plugin replaces an earlier turn's failed finish_task response event and a later turn merges a cached tool with a same-ID failure and a recovered superseded finish_task, the ambiguous sibling failure is conservatively not attributed to the newer batch (suppressing AGENT_COMPLETED for 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 unrecognized StateDelta while owner's newer sibling slot sits in a single turn and model batch (with !inv.hasEvictedFailureCallLocked(c.call)), recordUnfinishedTaskResponseWithLocked (or finishOpen when shown != nil) can attribute that sibling to the newer batch and consume the newer rejection.
    • Records toolName on spanRecord, matches open tool spans by both call ID and tool name (matchesOpenToolCall), records only finish_task calls in settledTaskCalls (each with the turn epoch in which its call started) and hasOpenOrSettledFinishEvidence, checks evStateDelta provenance and finish-state ownership before scanning peer credits, scopes unseenModelFinishCalls pruning on function responses to the answered batch's modelCallSeq, and uses deferredTaskFinish / deferredAgentCompletion so an older activation's unconsumed rejectedTasks entry never swallows a hidden-callback peer's sole valid finish_task response.
    • Keeps the tool batch of a task-mode function response event when its StateDelta shows it (batchEpochOf / batchModelSeqOf): answeredKeys filters open inv.toolSpans by modelCallSeq == evBatchModelSeq (and turnEpoch <= evEpoch), recordUnfinishedTaskResponseWithLocked scopes evDeltaPtr unfinished-call attribution to d.modelCallSeq, and on the deltaOwnerIdx branch of popTaskAgentSpanWithEvent finishedInBatch, the rec.finishedTasks consumption loop (bounding slot pruning by deltaRef.shownSince(c) when hasDeltaRef is true), openFinishCallBy, finishEvidenceBy, and answerBatchFinishCallsLocked (exactBatch, receiving remaining rather than full calls so duplicate call IDs consumed by finishedTasks are not double-counted) scope to evBatchSeq / d.modelCallSeq (and turnEpoch <= evEpoch) while storing the exact answered []taskFinishCall slots in spanRecord.completionCalls (shared by unfinishedResponseSlotsLocked and soleTaskOwnerForCall) 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.
    • Processes finish_task responses that report no completion (functionResponseCall.unfinished): once the response shows which task-mode activation it belongs to (the open call that it answers when StateDelta identifies the batch or !multiTurnOrUnknown with a single (epoch, modelCallSeq) batch of untaken/finished/answered calls for that ID, the StateDelta that it carries scoped to d.modelCallSeq, or when shown == nil the only open activation whose finish_task call 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 in unfinishedFinishCalls), 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-event eventID and at most maxTaskToolDeltas = 64 candidate slots are reconciled in resolveUnattributedFinishFailuresWithLocked (dirty-only re-resolution, O(1) (activation, callSeq) candidate indexing, and bounded per-invocation evictedFailureCalls saturated at maxTaskToolDeltas via evictedFailureCallsSaturated, reset across all invocation teardown paths) while retired task frames drop callback contexts and unreachable parent references (dropRetiredContextsLocked / pruneRetiredFrameRefsLocked), and nameless open finish_task spans (span.toolName == "" && span.finishCall.call != "") remain visible to finishCallSlotsLocked and unfinishedResponseSlotsLocked.
    • Correlates BeforeTool, OnToolError, and AfterTool (including across AfterRun late-state handoff) using per-attempt identity (toolCallIdentity: ctxPtr, the attempt's EventActions, per-activation turnEpochs, and race-safe boundedArgsDigest via argsDigester using hash/maphash, sorted map keys with upfront key-byte charging, up to 32 levels of container nesting via maxDigestDepth = 32, ancestor-stack cycle detection, and opaque truncated = true handling for reflect.Pointer and reflect.Struct values without dereferencing pointers or reading struct fields). unwrapToolContextActions reads unexported fields only of ADK's tool and callback context wrappers, the commonContext that they wrap, and the standard library's context types (knownContextFields); a context of any other type tells its EventActions through its Actions() method, so a custom context's private fields, which it may guard with its own synchronization, are never read.
    • Unifies recovered-error suppression in errorEndedSameAttempt: when curID.hasActions() is true (every stock ADK tool dispatch via agent.NewToolContext), recovered AfterToolCallback rows are suppressed unconditionally in all plugin registration orders (including [loggingplugin, analytics], [analytics, loggingplugin], and split before/after plugins) and even when an earlier callback mutates args in place; when curID.hasActions() is false on a custom pointer context (curID.ctxPtr != 0), suppression requires unchanged untruncated JSON-shaped arguments (rec.toolCallID.sameArgs(curID)); when unrecoveredErr is true and curID.hasAttemptIdentity() is true, deduplication matches on rec.toolCallID.sameContext(curID) and rec.turnEpoch == curEpoch without requiring unchanged or untruncated argument digests. On a value context without attempt identity, the error marker keeps the arguments map that OnToolErrorCallback saw when its digest is complete (errArgs): an error-bearing AfterToolCallback that sees another map whose complete digest differs belongs to another attempt and gets its own row (argsShowOtherAttempt), and a recovered AfterToolCallback consumes the marker of its turn while keeping its TOOL_COMPLETED row. Reusing a single tool.Context or session.EventActions across separate tool dispatches in the same model turn is documented as unsupported.

Behavior change

Tool errors recovered into a replacement map by OnToolErrorCallback or plugin/retryandreflect now emit only a single TOOL_ERROR row (and no longer emit a trailing TOOL_COMPLETED row, mark finish_task complete, or promote a FinalResponseToolNames AGENT_RESPONSE), matching adk-python v2.13.0 on tool and final-response rows (for custom tool.Context implementations without Actions() or a top-level pointer identity, suppression requires a non-empty FunctionCallID; reusing a single tool.Context or session.EventActions across separate tool dispatches in the same model turn is unsupported). When a failed finish_task call is recovered with {"result": "Task completed."} by an agent or later-plugin OnToolErrorCallback (including when a subsequent finish_task call 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's runTask still ends the task activation on that response without running AfterAgentCallback; Go retires the activation's span then (or, when a nested workflow.NewWorkflowNode clears Event.Output, once its delegating parent re-enters BeforeAgentCallback) and marks its delegating parent so the coordinator's interrupted activation emits AGENT_COMPLETED and its next activation is parented cleanly, while omitting AGENT_COMPLETED for the task activation whose finish_task failed (documented under "Behavioral Differences from adk-python" in doc.go, since adk-python writes AGENT_COMPLETED via after_agent_callback; when a later plugin or agent AfterToolCallback recovers the failure instead, analyticsPlugin.afterTool sees nil and records the call as unfinished so the task activation still writes AGENT_COMPLETED, pinned by TestRunner_RecoveredFinishTaskEndsWorkerSpanAndDelegator/later_after_tool_callback_recovers_finish_task as existing behavior). If a runner (including ADK main via cloneArgs) clones indistinguishable (identical or digest-truncated) argument maps for duplicate-ID finish_task calls in one batch or two parts alias the same map pointer, batch position is best-effort and callback start order never proves firstInBatch (preserving any clean completion rather than dropping it). Merged finish_task FunctionResponse events follow llmagent.isFinishTaskSuccessFR's first-response rule: only the first finish_task response in an event can complete the task activation, while later finish_task responses 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" in doc.go). On custom value contexts, a later failure of the same call in the same turn whose BeforeToolCallback and OnToolErrorCallback were both skipped gets its own TOOL_ERROR row unless its arguments are the failed call's own map, equal, or past the digest bounds, as the EventToolError godoc documents. Unrecovered tool errors, normal tool completions, and HITL tool-confirmation flows are unchanged.

Testing Plan

  • Merged main (11f4e29f) into the branch in 9bb2b9af without rewriting history. main moved the package documentation into doc.go, so this PR's "Best-effort inspection of ADK internals" section now lives in doc.go ahead of "Behavioral Differences from adk-python", and bigquery_agent_analytics_plugin.go no longer carries a package comment; TestDocGo_ParityBulletsReferenceExistingTests and the TestDocParity_* tests pass.
  • All plugin/agentanalytics unit and -race tests pass locally at 5c2da4b6 (on top of 48f6a6f2) under both GOWORK=off (adk/v2 v2.0.0) and merged origin/main (02b1d0b5) + go work init && go work use -r .: go -C plugin/agentanalytics test -race -mod=readonly -shuffle=on -count=1 -parallel=2 ./... (341.661s with GOWORK=off; 344.176s merged with 02b1d0b5 + go.work), GOWORK=off go -C plugin/agentanalytics test -mod=readonly -count=1 -parallel=2 -coverprofile=... ./... (94.1% package statements; 0/0 executable blocks/statements in 48f6a6f2..5c2da4b6 since 5c2da4b6 changes only docs/comments and tests, 44/44 blocks / 75/75 statements = 100.00% over 78c2735b..5c2da4b6, and 114/114 blocks / 224/224 statements = 100.00% over 45d922a1..5c2da4b6 across bigquery_agent_analytics_plugin.go and trace_manager.go), GOWORK=off go vet -mod=readonly ./... (both modules), GOWORK=off go build -mod=readonly ./... and merged origin/main + go.work go -C plugin/agentanalytics build -mod=readonly ./..., GOWORK=off go mod tidy -diff (both modules) and merged origin/main + go.work go -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 merged origin/main + go.work), and golangci-lint (0 issues across fmt --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 merged origin/main + go.work --new-from-rev=02b1d0b5 --enable=modernize ./... in plugin/agentanalytics), plus 2/2 targeted mutant kills at 5c2da4b6 (0 survivors). (Root-module -race subsets ./agent/llmagent/... ./agent/remoteagent/... ./internal/... ./workflow/... last ran at 48f6a6f2; 5c2da4b6 touches only plugin/agentanalytics/.)
  • Tests that fail with the PR's source changes reverted against origin/main (and noting changes at 45d922a1 and 78c2735b):
    • TestPlugin_RecoveredToolError_AgentCallback
    • TestPlugin_RecoveredToolError_LaterPlugin
    • TestPlugin_RecoveredToolError_RetryAndReflectBeforeAnalytics
    • TestPlugin_RecoveredToolError_RetryAndReflectAfterThisPlugin
    • TestPlugin_RecoveredToolError_LoggingPluginOrder
    • TestPlugin_RecoveredToolError_ArgumentsMutatedInPlace
    • TestPlugin_RecoveredToolError_SharedNestedArgsUnrecovered
    • TestPlugin_RecoveredToolError_HiddenBatchLeaderDelayedRejectedFinish
    • TestPlugin_RecoveredToolError_CustomExecutorReusedContextCachedRetry
    • TestPlugin_RecoveredToolError_ChangedArgumentsOnReusedContext
    • TestPlugin_RecoveredToolError_ConcurrentPeerTurn
    • TestPlugin_RecoveredToolError_TaskToolDeltasReleased
    • TestPlugin_RecoveredToolError_AmbiguousOverlapUnrecovered
    • TestPlugin_RecoveredToolError_FinalResponseToolSuppressed
    • TestPlugin_RecoveredToolError_FinishTaskDoesNotNoteTaskFinished
    • TestPlugin_RecoveredToolError_FinishTaskCrossActivationDroppedOrSuppressed
    • TestPlugin_RecoveredToolError_DelayedRejectedFinishLeavesNewPeerOpen
    • TestPlugin_RecoveredToolError_RunnerDelayedRejectedFinish
    • TestPlugin_RecoveredToolError_RunnerRejectedFinishSingleRun
    • TestPlugin_RecoveredToolError_RejectedFinishPeerStartedAfter
    • TestPlugin_RecoveredToolError_RejectedFinishConcurrentBothSkipped
    • TestPlugin_RecoveredToolError_ReusedContextSkippedBefore
    • TestPlugin_RecoveredToolError_UnrecoveredValueContext
    • TestPlugin_RecoveredToolError_AmbiguousOverlapNoBorrowedSpan
    • TestPlugin_RecoveredToolError_AmbiguousOverlapBothFail
    • TestPlugin_RecoveredToolError_AmbiguousOverlapDistinctArgs
    • TestPlugin_RecoveredToolError_DelayedRejectionConsumedBeforeHiddenPeerFinish
    • TestPlugin_RecoveredToolError_UnfinishedFinishTaskClearsPendingCall
    • TestPlugin_RecoveredToolError_TaskToolDeltasKeepLaterCalls
    • TestPlugin_RecoveredToolError_TaskToolDeltasKeepLaterTurns
    • TestPlugin_RecoveredToolError_OpaqueStructAndPointerArgsRaceSafe
    • TestPlugin_RecoveredToolError_RejectedFinishThreeHoles
    • TestPlugin_RecoveredToolError_SequentialRetry
    • TestPlugin_RecoveredToolError_OverlappedEmptyIDRecovery
    • TestPlugin_RecoveredToolError_EmptyIDEdgeCases
    • TestPlugin_RecoveredToolError_LateValueContextHandoff
    • TestPlugin_RecoveredToolError_MutableLockedContextNoRace
    • TestPlugin_RecoveredToolError_SkippedAfterCallbackSameArgsRetry
    • TestPlugin_RecoveredToolError_ClosureFactoryOverlapPreservesValidCompletion
    • TestPlugin_RecoveredToolError_CyclicArgsMapConstantTime
    • TestPlugin_RecoveredToolError_SkippedCallbacksReusedID
    • TestPlugin_RecoveredToolError_ValueContextSkippedBefore
    • TestPlugin_RecoveredToolError_RejectedFinishDifferentGoroutine
    • TestPlugin_RecoveredToolError_SameContextOverlap
    • TestPlugin_RecoveredToolError_CustomContextPrivateActionsNotRead
    • TestPlugin_RecoveredToolError_StaleValueContextMarker
    • TestPlugin_RecoveredToolError_DelayedRejectionThenPeerFinishFails
    • TestRunner_SupersededRejectedFinishDoesNotLeakRejection
    • TestRunner_SupersededBatchWithRejectedAndFinishedDoesNotLeakFinishedTask
    • TestRunner_HiddenEarlierResponseAndCachedCompletionKeepsSupersededRejection
    • TestRunner_RecoveredFinishTaskEndsWorkerSpanAndDelegator (and later_after_tool_callback_recovers_finish_task pins existing AfterToolCallback recovery behavior)
    • TestRunner_DuplicateIDFinishTaskBatchOrder (added at 78c2735b, expanded at 48f6a6f2, updated at 5c2da4b6 for cloneArgs; 10 subtests verifying first_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 through runner.New under both direct FunctionCall.Args dispatch and cloneArgs dispatch)
    • TestTraceManager_DuplicateIDFinishTaskCloningVsDirectArgsBinding (new at 5c2da4b6; 11 subtests covering direct non-cloning argsPtr binding for identical, oversized >64 KiB, and in-place-mutated maps alongside cloneArgs-style fresh map copies for distinct-args boundedArgsDigest binding and identical/oversized/pre-mutated ambiguous-batch fail-safe fallback)
    • TestTraceManager_DuplicateIDFinishTaskAmbiguousFallback (new at 48f6a6f2; pins cloned identical/oversized maps, aliased map pointer, skipped-BeforeToolCallback map-pointer ordering + cloned fallback, overlapping BeforeToolCallback ambiguous-args dispatch across aliased/nil/cloned-identical/cloned-oversized maps in both completion orders, and argsMap GC release on settlement and StateDelta-backed completionCalls retirement)
    • TestTraceManager_FinishedTasksCappedAtMaxTaskToolDeltas (new at 48f6a6f2; pins the 64-entry cap on spanRecord.finishedTasks)
    • TestDocParity_RecoveredFinishTaskOmitsWorkerAgentCompleted
    • TestPlugin_OverlappingTaskActivations_LateFunctionResponseKeepsRetryEcho
    • TestTraceManager_MergedFinishResponsesAnswerCallsOnce
    • TestTraceManager_PeerMergedFailedCompletedDoesNotEndOpenCallWhenOwnerHasFinishedTask
    • TestTraceManager_SupersededRejectionBatchModelSeqAndDeferredPeer
    • TestTraceManager_SupersededFinishedTaskAndSoleOwnerCrossTurn (updated same_batch_duplicate_id_rejected_and_clean_consumes_rejection and added same_batch_duplicate_id_first_clean_second_rejected_emits_completion at 78c2735b)
    • TestTraceManager_TaskBatchScopingAndEndedRejected
    • TestTraceManager_OtherCallSeqsCountsOnlyAttributedSlots
    • TestTraceManager_EvictedFailureCallsSaturationAndRejOverflowBoundary (new at 78c2735b; pins evictedFailureCalls saturation at 64 distinct IDs, exact 64 vs 65 re-eviction/overflow boundaries, rejectedTasksEvicted on rejectedTasks / deferredRejections, and teardown reset)
    • TestTraceManager_DuplicateIDFirstRejectedBranches (new at 78c2735b; pins deltaOwner, deferredRejections, finishedInBatch, settledIdx, openFinishCallBy / finishOpen, finishEvidenceBy, paired, matchesRej, and finishedTaskLocked under supersededByBatchRejection / firstInBatch)
    • TestTraceManager_PopTaskAgentSpanRecoveredFinishBranches
    • TestResolveUnattributedFinishFailures_BoundedCandidatesAndDirtySkip
    • TestBoundedArgsDigest_NestedMapsChargeKeysAtAdmissionAndBoundDepth
    • TestTraceManager_RetiredTaskFrameDropsCallbackContexts
    • TestTraceManager_DrainedDescendantDropsCallbackContexts
    • TestTraceManager_PruneRetiredFrameRefsAfterChildCallEnds
    • TestTraceManager_UnwrapContext_CustomLayouts
    • TestTraceManager_EmptyToolCallContextCleanup
    • TestTraceManager_TurnEpochsLateHandoffAndCleanup
    • TestTraceManager_TaskDeltaRetentionAndCleanup
    • TestTraceManager_UnwrapContext_WithoutCancel
    • TestBoundedArgsDigest
    • TestTraceManager_RecoveredToolErrorEmitsOnlyToolError
  • Guard / regression tests that pass on origin/main and pin multi-turn / cross-activation behavior alongside the PR changes:
    • TestRunner_TwoFinishCallsFirstFails (verifies ADK's isFinishTaskSuccessFR first-response rule when the first finish_task call in a batch fails and the second succeeds)
    • TestRunner_SupersededRejectedFinishWithoutStateDeltaDoesNotLeakToLaterActivation (pins cross-activation isolation under an unrecorded StateDelta)
  • TestPlugin_RecoveredToolError_VisibleFailureKeepsHiddenPeerDeferral passes at 45d922a1 and 78c2735b: it pins that a failure reported in plain sight by another activation does not cancel a hidden-callback peer's deferred completion.
  • Updated three earlier unit tests in trace_manager_test.go at 45d922a1 — TestTraceManager_FunctionResponseEndsWaitForModelEvent, TestTraceManager_FailureOfOwnRunTakesOpenCall/context_of_run (plus single_turn_context_of_run), and TestTraceManager_FailedResponseEndsFailedCallOfItsTurn/multi_turn_without_delta_waits_for_count — to pin the deliberate behavior change where a single failure with no recognized StateDelta across same-ID calls in multiple turns is now kept instead of ending the earliest turn's call.

caohy1988

This comment was marked as outdated.

…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
@haiyuan-eng-google
haiyuan-eng-google force-pushed the fix/bqaa-2046-recovered-tool-error branch from 20cd923 to 696dff5 Compare November 7, 2026 00:57
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed in 696dff50f686dc91aadb9e8fe8d7cb11144e9979: assertNoFinalResponseFromTool now decodes the Arrow JSON attributes column via jsonObjectColumn(t, row, "attributes") (matching TestFinalResponseToolNames), and TestPlugin_RecoveredToolError_SequentialRetry covers sequential failure-then-success retry cycles for both distinct and empty FunctionCall.ID values as well as finish_task.

caohy1988

This comment was marked as outdated.

caohy1988

This comment was marked as outdated.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed Review 5814022576 in commit e6d14f4ea2e6b3547d8819baad2b65a8bb3260a1:

  1. Per-tool.Context isolation for overlapping empty-ID tool calls (trace_manager.go, bigquery_agent_analytics_plugin.go):
    • Added pushToolCallSpan and popToolCallSpan (beforeTool, onToolError, afterTool), allocating an internal per-invocation sequence token (tc<seq>) keyed by (ctx, baseKey) whenever FunctionCallID is empty (resolveToolCallKeyLocked / resolveEmptyToolSeqLocked).
    • Kept toolKeyCall returning the trailing tool name/call ID after the last NUL byte and omitted synthetic tokens from eventData.functionCallID, so BigQuery TOOL_STARTING / TOOL_ERROR / TOOL_COMPLETED rows preserve empty function_call_id while attributing spans, latency_ms, closedByError suppression, FinalResponseToolNames AGENT_RESPONSE promotion, and finish_task completion to the exact overlapping call.
  2. Dynamic comparability safety & zero context retention:
    • Added safeComparableKey (unhashableProbe under recover()) so custom tool.Context implementations carrying dynamically unhashable concrete values inside any fields fall back cleanly without panicking.
    • Released live context map entries immediately in AfterToolCallback and unconditionally in endInvocation, handing off non-retaining emptyToolPtrKey (reflect.Type, uintptr, baseKey) entries only for spans still open at AfterRun (verified with weak.Pointer + runtime.GC).
  3. Regression coverage:
    • Added TestPlugin_RecoveredToolError_OverlappedEmptyIDRecovery (error-first, success-first, and concurrent -race empty-ID recovery), TestPlugin_RecoveredToolError_EmptyIDEdgeCases (sequential context reuse, unhashable/value contexts, late post-AfterRun isolation, overlapping empty-ID finish_task), and TestTraceManager_EmptyToolCallContextCleanup.

Verified on a clean git archive checkout with gofmt, go vet ./..., go mod tidy -diff, golangci-lint, .github/scripts/apidiff.sh, and go test -race -count=1 ./... (plugin/agentanalytics + root module).

caohy1988

This comment was marked as outdated.

caohy1988

This comment was marked as outdated.

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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed all findings from both reviews on e6d14f4e in 76ca71c8:

  1. Same-context overlap & non-comparable value-context disambiguation (plugin/agentanalytics/bigquery_agent_analytics_plugin.go, plugin/agentanalytics/trace_manager.go):

    • Replaced the single-slot emptyToolCallIDs / emptyToolCallPtrs maps with a unified non-retaining (ctxType, ctxHash, baseKey) -> []emptyToolCallEntry multi-slot table (fingerprintToolValue / fingerprintToolArgs / hashReflectValue with bounded depth/length/map traversal and order-independent map hashing).
    • Threaded args into pushToolCallSpan / popToolCallSpan so overlapping empty-FunctionCallID calls that reuse a single context resolve via argsPtr -> argsHash -> FIFO (pickOpenEmptyToolEntry / pickAfterEmptyToolEntry), and distinct non-comparable value contexts (slices, maps, functions, unexported fields) receive distinct tc<seq> span and recovery identities without retaining tool.Context or args references.
  2. Unified AfterRun late handoff across value and pointer contexts (plugin/agentanalytics/trace_manager.go):

    • Updated rememberCompletedLocked and lateLocked to carry surviving emptyToolCalls slices into completedTrace.endedEmptyTools / late.emptyToolCalls, preserving starting spans, latency_ms, and closedByError suppression when OnToolErrorCallback and/or AfterToolCallback run after AfterRun for comparable value, non-comparable value, and pointer contexts alike.
  3. Regression & GC non-retention coverage (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go, plugin/agentanalytics/trace_manager_test.go):

    • Added TestPlugin_RecoveredToolError_SameContextOverlap and TestPlugin_RecoveredToolError_NonComparableOverlap (both error_first and success_first orders, distinct & shared args, FinalResponseToolNames, and finish_task), TestPlugin_RecoveredToolError_LateValueContextHandoff, and weak.Pointer + runtime.GC() assertions on both ctx and args.

caohy1988

This comment was marked as outdated.

caohy1988

This comment was marked as outdated.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed the empty-ID correlation and finish_task recovery findings in commit 7c8be06911f9:

  1. O(1) race-free empty-FunctionCallID correlation (trace_manager.go): Removed recursive ctx and args reflection/hashing (fingerprintToolValue, fingerprintToolArgs) in favor of O(1) non-dereferencing top-level pointer identity (emptyToolCtxPtr), eliminating concurrent map/struct data races, unstable closure-pointer hashes, and cyclic args map traversal overhead (TestPlugin_RecoveredToolError_MutableLockedContextNoRace, TestPlugin_RecoveredToolError_CyclicArgsMapConstantTime).
  2. Orphan errored eviction & conservative overlap fallback (trace_manager.go): Evicts prior errored empty-ID entries on BeforeTool when an earlier plugin short-circuited AfterToolCallback (TestPlugin_RecoveredToolError_SkippedAfterCallbackSameArgsRetry), and marks overlapping open empty-ID calls sharing the same context identity ambiguous = true so valid sibling TOOL_COMPLETED and AGENT_RESPONSE rows are never suppressed (TestPlugin_RecoveredToolError_ClosureFactoryOverlapPreservesValidCompletion).
  3. Recovered finish_task rejection & cross-activation reconciliation (bigquery_agent_analytics_plugin.go, trace_manager.go): Gates noteTaskFinished on isTaskCompletedResult(result) and records noteTaskRejected when a recovered finish_task error returns "result": "Task completed.", prioritizing matching open finishedTasks over rejectedTasks in popTaskAgentSpan so neither recovered errors nor dropped/suppressed prior FunctionResponse events misattribute AGENT_COMPLETED (TestPlugin_RecoveredToolError_FinishTaskDoesNotNoteTaskFinished, TestPlugin_RecoveredToolError_FinishTaskCrossActivationDroppedOrSuppressed).

caohy1988

This comment was marked as outdated.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed all four findings from review 5820050781 in fast-forward commit d9e76e8573e8e0afd8334e0b114a93a182b1c915:

  1. Context-bound error markers for reused non-empty call IDs across skipped callbacks (trace_manager.go):

    • popToolCallSpan / popToolSpanWithKind bind completedTools error-recovery markers to non-zero callback context pointer identity (toolCtxPtr on spanRecord via emptyToolCtxPtr + emptyToolPtr.valid()). When a prior attempt's AfterToolCallback and a cached retry's BeforeToolCallback are both skipped on a reused non-empty FunctionCallID, the retry's distinct callback context pointer evicts the stale marker instead of suppressing TOOL_COMPLETED and AGENT_RESPONSE.
    • Regression coverage: TestPlugin_RecoveredToolError_SkippedCallbacksReusedID.
  2. Conservative fallback when callback context lacks pointer identity (trace_manager.go):

    • Non-pointer value contexts (!ptr.valid()) are treated as unavailable identity rather than a shared match: popToolSpanWithKind and resolveToolCallKeyLocked never record or match errored / completedTools completion-suppression markers when !ptr.valid(), preserving healthy completions across skipped BeforeToolCallback calls.
    • Regression coverage: TestPlugin_RecoveredToolError_ValueContextSkippedBefore (/value, /slice, /closure, /pointer).
  3. Cross-goroutine finish_task rejection supersession (trace_manager.go):

    • rejectedTasks now stores monotonic rejectedTaskCall sequences (seq), completeResponse records settledTaskCalls when clearing short-circuited open finish_task spans before popTaskAgentSpan, and popTaskAgentSpan removes the same-goroutine restriction so any newer non-ancestor unnoted task activation (other.seq > rej.seq or holding an open/settled finish_task call) supersedes an older activation's stale rejection across goroutines.
    • Regression coverage: TestPlugin_RecoveredToolError_RejectedFinishDifferentGoroutine.
  4. Span and latency preservation on ambiguous empty-ID overlaps (trace_manager.go):

    • When resolveToolCallKeyLocked handles fromError on an ambiguous open entry, it leaves open entries and their toolSpans untouched and allocates a synthetic sequence key (recordCompleted = false) so TOOL_ERROR emits on a synthetic child span with no inherited latency while completions retain their own starting spans and latencies.
    • Regression coverage: TestPlugin_RecoveredToolError_SameContextOverlap (requireAmbiguousOverlapSpans, shared/nil/fresh args in both orders).

Verified on a clean git archive HEAD checkout with -race and non-race go test ./..., golangci-lint, apidiff, and conventional-commit checks.

caohy1988

This comment was marked as outdated.

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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed all 5 items from review 5821441436 in fast-forward commit 3130a41e12254680b18809d958fe6cf32d787670:

  1. P1 — Delayed rejected finish_task response vs. unfinished peer activations (trace_manager.go, bigquery_agent_analytics_plugin.go):

    • Removed the seq > rej.seq start-order supersession heuristic in popTaskAgentSpanWithDelta.
    • Retained per-activation taskDeltaRef (map[string]any + ptr + pinnedCtx across all parallel tool calls toolStateDeltas and rejected calls rejectedTasks, cleared via clearTaskDeltas on retirement/purge/end) and matched eventStateDelta(ev) (deltaOwnerIdx) first so buffered single and merged parallel FunctionResponse events ([echo, finish_task]) bind to their originating activation, and a rejection is superseded only on positive finish evidence (finishedTasks, an open finish_task call on inv.toolSpans, or settledTaskCalls).
    • Added regressions in TestReviewDelayedRejectedFinishLeavesNewPeerOpen, TestReviewRunnerDelayedRejectedFinish (including single and parallel batched [echo, finish_task] tool calls across distinct and reused call IDs), TestReviewRunnerRejectedFinishSingleRun, TestReviewProbeRejectedFinishConcurrentBothSkipped, and TestTraceManager_TaskDeltaRetentionAndCleanup.
  2. P1 — Reused callback context when earlier plugins short-circuit AfterTool and the next BeforeTool (trace_manager.go, bigquery_agent_analytics_plugin.go):

    • Bound tool attempt records (emptyToolCallEntry and completedTools keys) to per-attempt identity combining toolCtxPtr, actionsPtr (ctx.Actions() or unwrapToolContextActions across WithValue / WithoutCancel / WithCancel / WithTimeout wrappers onto internal/context.invocationContext), and bounded argsDigest (boundedArgsDigest).
    • Recorded settled EventActions weak pointers in endedToolActions (wasToolActionsEndedLocked, preserved across AfterRun late-state handoff), and scoped hasEarlierShortCircuitPlugin (contextHasEarlierBeforeAndAfterToolPlugin) to contexts where curActions == nil or wasToolActionsEndedLocked(curActions) is true — so reusing the exact same callback context across a skipped AfterTool + skipped BeforeTool retry never suppresses the healthy retry, while registering stock loggingplugin before analytics ([loggingplugin, analytics]) preserves recovered-error suppression on fresh runner contexts.
    • Added regressions in TestReviewReusedContextSkippedBefore (all 6 subtests plus late-state handoff) and TestPlugin_RecoveredToolError_LoggingPluginOrder.
  3. P2 — Non-pointer value tool.Context error-recording evidence and docs (trace_manager.go, bigquery_agent_analytics_plugin.go):

    • Preserved completedTools[callID] and endedEmptyTools error markers for value contexts (!ptr.valid()) using actionsPtr + argsDigest (and callID for non-empty IDs) so unrecovered BeforeTool -> OnToolError -> AfterTool(sameErr) emits a single TOOL_ERROR row (TestReviewUnrecoveredValueContext), and updated EventToolCompleted godoc to state the exact scope for custom value contexts with empty FunctionCallID and nil Actions().
  4. P2 — Ambiguous same-context empty-ID completions borrowing starting spans (trace_manager.go, bigquery_agent_analytics_plugin_test.go):

    • Extended the ambiguous synthetic-span guard in popToolCallSpan to fromError == false when multiple open entries share the same context identity, so indistinguishable overlapping empty-ID completions emit uncorrelated synthetic spans without crossing starting spans or latencies (TestReviewAmbiguousRecoveryFirstMustNotBorrowHealthySpan and TestPlugin_RecoveredToolError_SameContextOverlap).
  5. NIT — Correlation helper parameter and type naming (trace_manager.go):

    • Renamed emptyToolCtxPtr to toolCtxPtr (extractToolCtxPtr) and wired args into boundedArgsDigest inside resolveToolCallKeyLocked.

caohy1988

This comment was marked as outdated.

…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.
caohy1988

This comment was marked as outdated.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and the repro! Addressed all five points in 5bcd7b57:

  1. First finish_task response decides task completion (bigquery_agent_analytics_plugin.go:1113, :1133, :1187; trace_manager.go:4759, :5143). taskCompletedCalls, hasTaskCompletedResponse, and functionResponseCallSpecs now mirror llmagent.isFinishTaskSuccessFR: only the first finish_task FunctionResponse in an event can complete the task activation. Any later finish_task responses in that event are marked unfinished (and superseded when their payload carried "Task completed."), so completeResponseEvent ends their calls and consumes any corresponding finishedTasks entry without retiring the activation. Updated the comments in trace_manager.go along with TestTraceManager_MergedFinishResponsesAnswerCallsOnce (trace_manager_test.go:23991) and TestTraceManager_SameTurnFinishCallsWithMixedOutcomes (trace_manager_test.go:30616), and added TestRunner_TwoFinishCallsFirstFails (bigquery_agent_analytics_plugin_test.go:14100).
  2. Bounded resolveUnattributedFinishFailuresLocked on the event path (trace_manager.go:5333, :5446, :5491, :5653). Replaced the linear slices.IndexFunc candidate scan with an O(1) map[finishCallKey]int keyed by (activation, callSeq), gated reconciliation behind unattributedFailuresDirty so events that neither add an unattributed failure nor shrink a kept failure's candidate slots skip reconciliation altogether, and capped candidate slots per kept failure at maxTaskToolDeltas (64 — at admission, with at most 64 failures retained, a failure with > 64 candidate slots cannot force any call to end; dropping it rather than truncating its slots never ends a wrong call and simply forgoes later resolutions if other evidence subsequently narrows its candidates). On BenchmarkResolveUnattributedFinishFailures (trace_manager_test.go:31322), a 64-failure x 64-slot reconciliation runs in 0.42 ms/op, steady-state per-event latency after 70 delegations x 20 failed call_0 attempts is 4.9 µs/op (384 B/op), and the full 70-delegation end-to-end benchmark drops from 74.1 s/op to 0.17–0.21 s/op (covered by TestResolveUnattributedFinishFailures_BoundedCandidatesAndDirtySkip at trace_manager_test.go:31223).
  3. Late function responses vs. turn N+1 unseenModelFinishCalls (trace_manager.go:2895, :3686, :5000). Entries in unseenModelFinishCalls now record the modelCallSeq at which AfterModelCallback noted them, and completeResponseEvent resolves the answered batch's modelCallSeq (from StateDelta, answered open tool spans, or matching finished/rejected/unfinished calls) and drops only entries with modelCallSeq <= batchModelSeq (falling back to clearing unseenModelFinishCalls only when no batch evidence is present and no concurrent peer has an earlier pending call, preserving TestTraceManager_FunctionResponseEndsWaitForModelEvent). noteTaskFinishCalls also checks pendingEchoOf for an existing latest-turn pending call whose model event has not been seen yet before attributing a model event as an unseen call to a peer activation. Covered by TestPlugin_OverlappingTaskActivations_LateFunctionResponseKeepsRetryEcho (bigquery_agent_analytics_plugin_test.go:14169).
  4. Upfront map-key byte charging and nesting depth bound in boundedArgsDigest (trace_manager.go:8657, :8737, :8864, :8902). sortedMapKeys now returns keyBytes and argsDigester.hash deducts d.bytes -= keyBytes immediately upon map admission (while hashMapKey hashes admitted string keys without double-charging), alongside maxDigestDepth = 32 across nested maps and slices. Covered by TestBoundedArgsDigest_NestedMapsChargeKeysAtAdmissionAndBoundDepth (trace_manager_test.go:31493).
  5. Dropping callback contexts on retired task frames (trace_manager.go:4265, :4532, :5760, :8124, :8144). Unified dropRetiredContextsLocked and pruneRetiredFrameRefsLocked across live and late traces so retired, purged, and drained agent frames immediately clear ended, activation, retiredCauses, and nodeRuns (recording hasActivation as a plain boolean), and clear canceled and parent as soon as no open child span or call reaches them. Verified with weak.Pointer across runtime.GC() in TestTraceManager_RetiredTaskFrameDropsCallbackContexts (trace_manager_test.go:31576).

caohy1988

This comment was marked as outdated.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for catching that superseded-rejection edge case and the cleanup items! Pushed 0df884bf to address each point:

  • Superseded finish_task response leaving rejectedTasks behind: In the trailing loop of completeResponseEvent (plugin/agentanalytics/trace_manager.go:5167-5193), when fr.superseded && ownerKnown && len(inv.untakenFinishCallsLocked(owner, fr.call, answered)) == 0, we now delete the owner's matching rejectedTasks (or deferredRejections) entry and skip recordUnfinishedTaskResponseLocked. All TestTraceManager_MergedFinishResponsesAnswerCallsOnce subtests (including succeed_succeed) remain green, and TestRunner_SupersededRejectedFinishDoesNotLeakRejection (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go:14320-14559) covers both a cached-callback retry in the same activation and a later activation reusing the call ID after standard completion.
  • ownerKnown (len(owner.finishedTasks) > 0): Dropped len(owner.finishedTasks) > 0 from ownerKnown (plugin/agentanalytics/trace_manager.go:5090, :5144) so only self > 0 || hasEvEpoch proves event ownership. Added TestTraceManager_PeerMergedFailedCompletedDoesNotEndOpenCallWhenOwnerHasFinishedTask (plugin/agentanalytics/trace_manager_test.go:31735-31798).
  • Unreachable pendingEchoOf and latestModelEventSeen: Confirmed every path that clears the latest unseenModelFinishCalls entry would also have set latestModelEventSeen while echoOf matches first, so both pendingEchoOf and latestModelEventSeen have been removed (plugin/agentanalytics/trace_manager.go:410, :3664-3705). TestPlugin_OverlappingTaskActivations_LateFunctionResponseKeepsRetryEcho stays green.
  • EventToolCompleted godoc: Documented the 32-level container nesting bound (maxDigestDepth = 32) alongside the existing string, byte, entry, and total-node bounds (plugin/agentanalytics/bigquery_agent_analytics_plugin.go:88-93), and pinned the exact 32- vs. 33-level boundary in TestBoundedArgsDigest_NestedMapsChargeKeysAtAdmissionAndBoundDepth (plugin/agentanalytics/trace_manager_test.go:31546-31579).
  • Drained-descendant test, deterministic reconciliation test, and minor polish:
    • Added TestTraceManager_DrainedDescendantDropsCallbackContexts (plugin/agentanalytics/trace_manager_test.go:31800-31929) exercising the draining branch of retireDrainedDescendantsLocked and verifying callback contexts and parent references are dropped and garbage-collected.
    • Removed the wall-clock timing assertions from TestResolveUnattributedFinishFailures_BoundedCandidatesAndDirtySkip (plugin/agentanalytics/trace_manager_test.go:31223-31326), keeping deterministic structural assertions on slot caps and unattributedFailuresDirty while leaving timing to BenchmarkResolveUnattributedFinishFailures.
    • Removed the garbled trailing comment in resolveUnattributedFinishFailuresLocked (plugin/agentanalytics/trace_manager.go:5738) and skipped open frames in pruneRetiredFrameRefsLocked's fast-path check (plugin/agentanalytics/trace_manager.go:8130-8144).
  • PR description: Refreshed the PR description to document the first-response finish_task completion rule and update the test/lint verification notes to 0df884bf.

Agreed on the separate nil-args finish_task behavior in runTask (agent/llmagent/llm_agent_wrapper.go:693-699, where maps.Clone(nil) leaves pendingFCArgs == nil so runTask keeps running while isTaskCompletedResult treats the response as completed) — happy to track and handle that in a focused follow-up PR so this one stays scoped to #2046.

caohy1988

This comment was marked as outdated.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and clear repros! Pushed d84b1c8c to address all five items:

  • Cross-turn modelCallSeq scoping on superseded rejections: Added batchModelSeqOf (plugin/agentanalytics/trace_manager.go:2991-3006) to resolve the tool batch's modelCallSeq from toolStateDeltas, rejectedTasks, or deferredRejections, and restricted superseded-rejection matching across both rejectedTasks and deferredRejections in completeResponseEvent (plugin/agentanalytics/trace_manager.go:5062, :5312-5333) as well as the batch-fallback lookup in popTaskAgentSpanWithEvent (plugin/agentanalytics/trace_manager.go:3324-3345) to rej.modelCallSeq == evBatchModelSeq whenever StateDelta identifies the batch. Pinned by TestTraceManager_SupersededRejectionBatchModelSeqAndDeferredPeer/cross_turn_reused_id_delayed_batch_preserves_newer_rejection (plugin/agentanalytics/trace_manager_test.go:32186-32258) and TestTraceManager_PopTaskAgentSpanRecoveredFinishBranches/deltaOwner_batchRejected_deferredRejections_and_modelCallSeq/older_batch_sibling_delta_preserves_newer_rejection (plugin/agentanalytics/trace_manager_test.go:33614-33730).
  • Superseded-rejection cleanup when ownerKnown is false: Extended the superseded branch in completeResponseEvent (plugin/agentanalytics/trace_manager.go:5270-5311) with soleTaskOwnerForCall(fr.call), which runs when owner is the only open frame for the task, no ended rejecting frame (endedRejectingFrames) for the task holds a rejection for that call, and no retired task frame (taskFrames) for the task holds a finishedTasks entry or an unanswered untakenFinishCallsLocked slot for that call (accounting for completionCalls). Pinned by TestRunner_SupersededRejectedFinishDoesNotLeakRejection/same_activation_cached_first_call_and_retry (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go:14560-14650), TestTraceManager_SupersededRejectionBatchModelSeqAndDeferredPeer/ended_rejecting_frame_blocks_unowned_superseded_cleanup (plugin/agentanalytics/trace_manager_test.go:32260-32361), retired_pending_finish_blocks_unowned_superseded_cleanup (:32525-32624), retired_finished_task_blocks_unowned_superseded_cleanup (:32626-32727), and retired_completed_same_call_and_unrelated_ended_frame_allow_cleanup (:32729-32991).
  • Failed finish_task recovered with {"result": "Task completed."}: Kept noteTaskRejected so the existing rejected-finish row contract holds (TOOL_ERROR emitted; TOOL_COMPLETED, AGENT_RESPONSE, and the failed worker activation's AGENT_COMPLETED omitted), and wired popTaskAgentSpanWithEvent(..., ev.Output != nil) (plugin/agentanalytics/bigquery_agent_analytics_plugin.go:1043, plugin/agentanalytics/trace_manager.go:3122, :3241-3265) so that when ADK's runTask terminates the task on that completion response (ev.Output != nil) and the worker has started no later model or tool work, retireEndedRejected retires the worker's span and marks its delegating parent via markTaskDelegatorLocked (plugin/agentanalytics/trace_manager.go:3686-3699). Documented this behavioral difference from adk-python in plugin/agentanalytics/doc.go:98-106, :220-234 and in the PR description, and pinned all retained popTaskAgentSpanWithEvent branches in TestRunner_RecoveredFinishTaskEndsWorkerSpanAndDelegator (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go:14653-14884), TestDocParity_RecoveredFinishTaskOmitsWorkerAgentCompleted (plugin/agentanalytics/doc_test.go:1095-1174), and TestTraceManager_PopTaskAgentSpanRecoveredFinishBranches (plugin/agentanalytics/trace_manager_test.go:33275-34262).
  • matchesDelta removal and deferredRejections peer settlement: Removed the two unreachable matchesDelta arms in completeResponseEvent, kept the deferredRejections arm scoped by modelCallSeq, and wired it to settle the peer holding the deferral immediately via retireDeferredTaskWithProofLocked (plugin/agentanalytics/trace_manager.go:4041-4090, :5319-5331) and logDeferredTaskCompletions (plugin/agentanalytics/bigquery_agent_analytics_plugin.go:1019-1031). Pinned by TestTraceManager_SupersededRejectionBatchModelSeqAndDeferredPeer/deferred_rejection_in_superseded_batch_settles_peer_immediately (plugin/agentanalytics/trace_manager_test.go:32363-32523) and superseded_batch_clears_failed_deferring_peer_and_removes_unattributed_slot (:32993-33272).
  • Pinning the remaining unpinned lines:
    • pruneRetiredFrameRefsLocked (plugin/agentanalytics/trace_manager.go:8271-8315): pinned across both taskFrames and endedRejectingFrames in TestTraceManager_PruneRetiredFrameRefsAfterChildCallEnds (plugin/agentanalytics/trace_manager_test.go:32008-32172).
    • endTaskStateLocked(d) in the draining branch (plugin/agentanalytics/trace_manager.go:5919): pinned in TestTraceManager_DrainedDescendantDropsCallbackContexts (plugin/agentanalytics/trace_manager_test.go:31857-32006).
    • Slice and array depth bound (plugin/agentanalytics/trace_manager.go:8957-8960) and literal 32-level depth limit (maxDigestDepth = 32 at :8785): pinned with literal 31 vs. 32 nesting counts across maps, slices, and arrays in TestBoundedArgsDigest_NestedMapsChargeKeysAtAdmissionAndBoundDepth (plugin/agentanalytics/trace_manager_test.go:31555-31637).

caohy1988

This comment was marked as outdated.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for catching these edge cases and the clear repros! Pushed f112ede7 on top of d84b1c8c to address all six items:

  1. Batch modelCallSeq scoping on finishedTasks pairing and superseded consumption: Restricted both pairedFinished (plugin/agentanalytics/trace_manager.go:5276-5290) and matchedSuperseded (plugin/agentanalytics/trace_manager.go:5298-5310) in completeResponseEvent with !hasEvBatchModelSeq || c.modelCallSeq == evBatchModelSeq, so a delayed older batch with StateDelta provenance can neither steal an open call's response nor consume a newer turn's owner.finishedTasks entry. Pinned by TestTraceManager_SupersededFinishedTaskAndSoleOwnerCrossTurn/older_superseded_batch_preserves_newer_finished_tasks_on_original_span (plugin/agentanalytics/trace_manager_test.go:34276-34370) and TestTraceManager_TaskBatchScopingAndEndedRejected/paired_finished_older_batch_does_not_steal_open_call (plugin/agentanalytics/trace_manager_test.go:34929-34989).

  2. Cross-turn batch scoping and call-order guard on rejection cleanup: When hasEvBatchModelSeq is false, otherCallSeqs (plugin/agentanalytics/trace_manager.go:5412-5428) collects modelCallSeq values from answered (matchedSuperseded and finishOpen), completed paired entries from owner.finishedTasks (plugin/agentanalytics/trace_manager.go:5285), and finishCallSlotsLocked for finish_task calls in the event, restricting matchesRej (plugin/agentanalytics/trace_manager.go:5434-5450) across both sole-owner and context-shown events (replacing the unscoped !hasEvBatchModelSeq fallback) so a failed response never matches a newer completed owner.finishedTasks entry and an unrelated older batch cannot delete a newer rejection. In addition, taskFinishCall (plugin/agentanalytics/trace_manager.go:2922-2929) and rejectedTaskCall (plugin/agentanalytics/trace_manager.go:2890-2896) record firstInBatch in noteTaskFinishCalls (plugin/agentanalytics/trace_manager.go:3891-3905) and noteTaskRejected (plugin/agentanalytics/trace_manager.go:4318-4327); because ADK merges function responses in call order, matchesRej never consumes a firstInBatch rejection on a superseded response (unless a same-ID, same-batch completion already paired in paired). That closes the cross-turn ID-reuse cases where the newer batch's first finish_task call was rejected alongside a pending or plain-sight-failed sibling (first_in_batch_rejection_survives_older_superseded_batch_with_pending_sibling, first_in_batch_rejection_survives_older_superseded_batch_with_failed_sibling, first_finish_after_non_finish_tool_survives_older_superseded_batch, and same_batch_duplicate_id_rejected_and_clean_consumes_rejection at plugin/agentanalytics/trace_manager_test.go:34536-34713). Narrower residual documented at plugin/agentanalytics/trace_manager.go:5405-5411: when hasEvBatchModelSeq is false and rej.firstInBatch is false (not first in its model batch, or batch order unobserved) while another call in that batch shares its ID with a call in otherCallSeqs (for example, a still-pending or plain-sight-failed sibling in the delayed older merged event), matchesRej consumes the newer rejection and the newer batch's subsequent response emits AGENT_COMPLETED for the failed finish_task. Also pinned by sole_owner_unknown_batch_preserves_newer_rejection (:34372-34444), failed_response_does_not_match_newer_finished_single / _merged (:34446-34535), shown_ctx_unknown_delta_preserves_non_first_newer_rejection_without_shared_sibling (:34715-34791), ev_batch_model_seq_mismatch_preserves_newer_non_first_rejection (:34793-34879), other_call_seqs_answered_source (:35596-35652), other_call_seqs_paired_finished_source (:35654-35711), other_call_seqs_ignores_non_finish_tool (:35713-35764), and superseded_cleanup_preserves_other_call_when_shown_without_delta (:35519-35594).

  3. Worker retirement below a nested workflow.NewWorkflowNode: Added spanRecord.endedRejected (plugin/agentanalytics/trace_manager.go:298), set by retireEndedRejected when taskEnded is false (plugin/agentanalytics/trace_manager.go:3273-3276) and cleared whenever the activation starts any subsequent model, tool, error, or finish transition (pushLLMSpan, pushToolSpanWithKind, recordError, noteTaskFinishCalls, noteTaskFinished, noteTaskRejected, noteTaskUnfinished, and empty-call completeResponseEvent). Wired popEndedRejectedTasksForDelegator (plugin/agentanalytics/trace_manager.go:4231-4263) into beforeAgent right before popDelegatingAgentSpan (plugin/agentanalytics/bigquery_agent_analytics_plugin.go:1226), retiring the worker and marking its delegator when the LLM parent with matching name/branch/path, direct parentSpanID, and child membership re-enters BeforeAgentCallback on the same goroutine. Pinned in TestRunner_RecoveredFinishTaskEndsWorkerSpanAndDelegator/nested_workflow_node_retires_worker_and_completes_delegator (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go:14886-14993) and TestTraceManager_TaskBatchScopingAndEndedRejected (intervening_model_call_clears_ended_rejected :35477-35517, clear_ended_rejected_* :35766-35860, pop_ended_rejected_* :35862-36216).

  4. Narrowed doc.go bullet vs. later AfterToolCallback and re-entry timing: Scoped the bullet title and lead in plugin/agentanalytics/doc.go:221-239 to recovery via OnToolErrorCallback, clarified that ADK's runTask still ends the task activation on that recovered response while this plugin retires the activation's span then (or, below a nested workflow.NewWorkflowNode that clears Event.Output, on delegator BeforeAgentCallback re-entry), and noted that if a later plugin or agent AfterToolCallback recovers the failure instead, analyticsPlugin.afterTool sees nil and records the call as unfinished so the task activation still writes [EventAgentCompleted]. Pinned as existing behavior by TestRunner_RecoveredFinishTaskEndsWorkerSpanAndDelegator/later_after_tool_callback_recovers_finish_task (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go:14995-15066).

  5. Pinning guards and dropping redundant checks: Kept || hasEvBatchModelSeq in ownerKnown (plugin/agentanalytics/trace_manager.go:5272), dropped redundant hasEvEpoch || in ownerKnown (batchEpochOf is a strict subset of batchModelSeqOf), post-reindex if i > 0 (plugin/agentanalytics/trace_manager.go:5471), and !deferred (plugin/agentanalytics/trace_manager.go:3576-3581), and pinned the remaining guards in TestTraceManager_TaskBatchScopingAndEndedRejected:

    • sole_owner_blocked_by_other_open_task_frame (:34991-35047): other open task activation blocking soleTaskOwnerForCall.
    • sole_owner_blocked_by_retired_unfinished_call_despite_completion_calls (:35049-35118): retired activation's unfinishedFinishCalls condition despite matching completionCalls.
    • deferred_peer_started_before_owner_reindexes_owner (:35120-35216): starting a deferring peer before owner so retireDeferredTaskWithProofLocked shifts owner's index before lineageLocked(i).
    • retire_deferred_with_proof_records_completion_calls (:35218-35323): rec.completionCalls = []string{df.call} (plugin/agentanalytics/trace_manager.go:4085) allowing later soleTaskOwnerForCall cleanup.
    • pending_finish_call_blocks_deferred_batch_arm (:35325-35396): pendingFinishCalls guard on deferredRejections batch fallback (plugin/agentanalytics/trace_manager.go:3356-3359).
    • owner_known_preserves_batch_model_seq_after_delta_eviction (:35398-35475): || hasEvBatchModelSeq after >64 tool deltas evict StateDelta from toolStateDeltas.
    • pop_ended_rejected_ignores_non_llm_parent, pop_ended_rejected_requires_matching_parent_*, and pop_ended_rejected_requires_direct_parent_span (:35973-36216): pinning parent.nonLLM, parent name/branch/path, and rec.parentSpanID == parent.spanID.
  6. Docstrings and package documentation: Moved the detailed contract comment onto popTaskAgentSpanWithEvent (plugin/agentanalytics/trace_manager.go:3095-3135), updated remaining popTaskAgentSpanWithDelta comment references (plugin/agentanalytics/bigquery_agent_analytics_plugin.go:1000, trace_manager.go), and replaced the internal "rejecting frame" phrasing in plugin/agentanalytics/doc.go:104-107.

caohy1988

This comment was marked as outdated.

- 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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Pushed 45d922a1 on top of f112ede7 to close the otherCallSeqs batch-attribution, ownerHasSupersededBatch, single-owner runner.New OnEventCallback, and nameless open-span cases and document the hidden-observation residuals in doc.go:

  • Count only batch-proving attributed slots in otherCallSeqs, scope StateDelta / answeredKeys / completionCalls, and prove kept failures via bipartite matching: In plugin/agentanalytics/trace_manager.go, completeResponseEvent (:5036-5071, :5201-5215, :5474-5498, :5510-5635, :5636-5693), popTaskAgentSpanWithEvent (:3168-3177, :3184-3188, :3338-3385, :3673-3724), noteTaskRejected (:4338-4368), recordUnfinishedTaskResponseWithLocked (:5743-5797), noteEvictedFailureCallLocked (:5944-5949), keepFinishFailureLocked (:5951-5973), endFinishCallLocked (:5989-5998), answerBatchFinishCallsLocked / answerLatestFinishCallsLocked / answerFinishCallsLocked (:6048-6108), and resolveUnattributedFinishFailuresWithLocked (:6173-6321, with forced current-event eventID matching checks at :6243-6285) keep slot/batch boundaries exact via spanRecord.completionCalls (:420-438), per-invocation evictedFailureCalls (:736-743, cleared on invocation teardown at :1897, :6897, :6966, :7002), and unattributedFinishFailure.eventID / finishCallSlot.modelCallSeq (:2960-2976), while keeping the retire/cleanup tests that break when the slots loop is simply dropped passing unmodified.
  • Include rejectedTasks/deferredRejections and filter nameless responses in ownerHasSupersededBatch, and preserve same-batch rejections in noteTaskFinished: In plugin/agentanalytics/trace_manager.go, ownerHasSupersededBatch (:5424-5473) scopes need (:5436-5441) to fr.name == finishTaskToolName || (fr.name == "" && (fr.unfinished || fr.superseded || fr.call == finishTaskToolName || isOwnerFinishSlot(fr.call))) (isOwnerFinishSlot at :5428-5435), sums have (:5443-5471) across owner.finishedTasks, finishCallSlotsLocked, owner.rejectedTasks, and owner.deferredRejections matching (call, seq), and tolerates keepLatest collapsing repeated same-ID rejections past maxTaskToolDeltas (64) when hasRejected && rejOverflowed (:5442, :5468). noteTaskFinished (:4314-4318) filters sameCall with rej.modelCallSeq != rec.modelCallSeq so a later same-batch sibling never erases an earlier sibling's rejection before ownerHasSupersededBatch runs.
  • Restore sole-owner multiTurnOrUnknownFor/supersededCleanup and guard matchesRej against stale non-empty deltas on runner.New: Moved soleTaskOwnerForCall (:5363-5392, also checking completionCalls on retired taskFrames) before multiTurnOrUnknownFor (:5413-5423, returning true when !ownerKnown && !soleTaskOwnerForCall(c.call) or when owner has another (epoch, modelCallSeq) slot) and before supersededCleanup (:5648). In matchesRej (:5659-5675), when !ownerKnown && !rej.delta.empty() && evDeltaPtr == 0, stale rejectedTasks with a non-empty prior delta are cleared only via provenWithoutDelta (:5595, :5609-5628, :5671-5673), while otherCallSeqs (:5594, :5596-5607) continues proving zero-delta slots. In plugin/agentanalytics/trace_manager_test.go, other_call_seqs_answered_source (:35660-35715) and other_call_seqs_paired_finished_source (:35717-35770) updated their synthetic nil-StateDelta fixtures (reused no longer carries a StateDelta, and bad is now a real batch call) because the synthetic no-StateDelta outcome when rej.delta is non-empty and !ownerKnown intentionally flipped to preserve the earlier rejection and defer a later activation's completion until run end under those previous synthetic nil-StateDelta fixtures (now pinned by finishedTasks_completed_unknown_owner_preserves_turn1_rejection at :38966-39056), whereas stock ADK merged FunctionResponse events always carry the first call's non-nil StateDelta map.
  • Close and attribute nameless (rec.toolName == "") open tool spans safely: In plugin/agentanalytics/trace_manager.go, completeResponseEvent sorts finishOpen (:5279-5289) with named finish_task spans ahead of rec.toolName == "" spans (:5290-5298), nonFinishResp/spare tracking (:5341-5356) prevents nameless open spans from stealing spare counts needed by finish_task failures, o.rec.toolName == "" spans pre-match named non-finish_task responses (:5501-5509) with fallback matching for nameless non-finish_task responses (:5547-5555), and open spans are deleted from inv.toolSpans only when matched (:5556-5558). unfinishedResponseSlotsLocked (:5846) and finishCallSlotsLocked (:6130) also count (span.toolName == "" && span.finishCall.call != "") so nameless open finish_task spans participate in slot discovery and ownerHasSupersededBatch.
  • Document hidden-observation and overflow-eviction trade-offs in doc.go and pin with runner.New tests: Because the slot evidence that previously deleted a newer rejection on a delayed older response is the same evidence that deleted a batch's own rejection when an earlier plugin replaced or delayed a prior turn's failed finish_task response event past the later turn's merged response, tightening otherCallSeqs carries a symmetric trade-off under non-recommended plugin orders ([replacer, cache, analytics, recover] with reused call IDs: T1 finish_task c1 fails and its response event is replaced or delayed past T2; T2 merges cached lookup l2, failed c1, and failed+recovered c2 carrying lookup's unrecorded StateDelta map while c1 has two candidate slots c1@T1 and c1@T2; T3 finish_task c2 is answered by cache — c1 is not attributed to T2, c2's T2 rejection is kept, and T3's cached completion omits AGENT_COMPLETED for the worker and its interrupted delegating coordinator activation, whereas delivering T1's response event in order or letting T3's tool callbacks reach analytics emits both AGENT_COMPLETED rows). plugin/agentanalytics/doc.go (:107-126, under "Best-effort inspection of ADK internals") now documents both this conservative suppression and the pre-existing case where a completely hidden earlier turn's delayed merged response arrives with an unrecognized StateDelta after a newer turn's same-ID rejection, as well as the per-invocation maxTaskToolDeltas (64) evictedFailureCalls bound.
  • Regression tests: Added TestTraceManager_OtherCallSeqsCountsOnlyAttributedSlots (plugin/agentanalytics/trace_manager_test.go:36278-40128, a new test function vs f112ede7 covering delayed-older-batch vs newer-rejection preservation, paired/matchedSuperseded/finishOpen/deltaOwner scoping, answerBatchFinishCallsLocked same-epoch exactBatch filtering at :38768-38854, nameless open spans and isOwnerFinishSlot need matching across :39379-40127, and maxTaskToolDeltas keepLatest overflow in duplicate_rejected_call_id_collapsed_by_keepLatest at :39602) and TestRunner_HiddenEarlierResponseAndCachedCompletionKeepsSupersededRejection (:40407-40572, failing against both f112ede7 and origin/main), plus end-to-end runner.New tests TestRunner_SupersededBatchWithRejectedAndFinishedDoesNotLeakFinishedTask (:40130-40236, failing against origin/main and passing at f112ede7 via stock merged StateDelta) and TestRunner_SupersededRejectedFinishWithoutStateDeltaDoesNotLeakToLaterActivation (:40238-40405, passing at both origin/main and f112ede7 while guarding cross-activation isolation under an unrecorded StateDelta). Also updated three earlier unit tests in trace_manager_test.go — TestTraceManager_FunctionResponseEndsWaitForModelEvent (:24213-24267, pending calls 2 -> 3 plus a kept-failure assertion), TestTraceManager_FailureOfOwnRunTakesOpenCall/context_of_run (:29466-29550, expectation flipped to keep the failure over both slots, plus single_turn_context_of_run added at :29468-29488), and TestTraceManager_FailedResponseEndsFailedCallOfItsTurn/earliest_turn_takes_failure (:30900-31004, renamed multi_turn_without_delta_waits_for_count at :30953 with its expectation reversed) — to pin the deliberate change where a single failure with no recognized StateDelta across same-ID calls in multiple turns is now kept instead of ending the earliest turn's call.
  • Verification (45d922a1): go -C plugin/agentanalytics test -race -mod=readonly -shuffle=on -count=1 -parallel=1 ./..., go -C plugin/agentanalytics test -mod=readonly -count=1 -coverprofile=... ./... (94.0% package statements; 367/367 = 100.0% over added/modified statement blocks in f112ede7..45d922a1), go test -race -mod=readonly -count=1 ./agent/llmagent/... ./internal/... ./workflow/..., go vet ./..., go build -mod=readonly ./..., go mod tidy -diff, gofmt -l, git diff --check origin/main -- plugin/agentanalytics/, golangci-lint (0 issues across --new-from-rev=origin/main ./plugin/agentanalytics/..., fmt --diff ./plugin/agentanalytics/..., and --new-from-rev=f112ede7 --enable=modernize ./plugin/agentanalytics/...), .github/scripts/check-conventional-subject.sh, and git merge-tree --write-tree origin/main HEAD all pass (agent/llmagent/llm_agent_wrapper.go and plugin/agentanalytics/doc_test.go unchanged vs f112ede7).

caohy1988

This comment was marked as outdated.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the review — all five items are addressed in 78c2735b on top of 45d922a1:

  • Saturate evictedFailureCalls at maxTaskToolDeltas (64): Added invocationTrace.evictedFailureCallsSaturated (trace_manager.go:750) along with hasEvictedFailureCallLocked (:6018) and noteEvictedFailureCallLocked (:6028). Once evictedFailureCalls reaches 64 distinct call IDs, any additional distinct evicted ID flips evictedFailureCallsSaturated = true without growing the map (while re-evicting an already-recorded ID at 64 does not saturate), disabling attribution-based rejection cleanup across all call IDs until invocation teardown (rememberCompletedLocked :1905 and popUnclosedAgentSpans :6996, :7066, :7103), and updated doc.go:126.
  • Honor emitted part order for same-batch duplicate-ID finish_task calls: finishTaskFunctionCalls (bigquery_agent_analytics_plugin.go:1153) now emits finishTaskCallSpec (:1145) with boundedArgsDigest in part order into noteTaskFinishCallSpecs (trace_manager.go:3850, keeping noteTaskFinishCalls at :3842 for callers without args), afterTool / endUnfinishedFinishTask pass args into noteTaskFinishedWithArgs / noteTaskRejectedWithArgs / noteTaskUnfinishedWithArgs (:4366, :4409, :4457), and idlePendingFinishCallLocked (:4109) prefers exact untruncated argsDigest matches before falling back to FIFO pending order so concurrent same-ID calls keep their true firstInBatch (:3960-4009). Added hasFirstInBatchRejection (:2955) and supersededByBatchRejection (:2967) and gated finishedCall (:3190), openFinishCallBy (:3198), finishEvidenceBy (:3216), finishedInBatch (:3371), settledIdx (:3509), popTaskAgentSpanWithEvent consumption (:3717), finishedTaskLocked (:3797), paired (:5479), finishOpen (:5592, :5595), and matchesRej (:5741) so a superseded non-first sibling never stands in for a rejected first call (distinct or duplicate ID). Updated doc.go:246-249, aligned TestTraceManager_SupersededFinishedTaskAndSoleOwnerCrossTurn/same_batch_duplicate_id_rejected_and_clean_consumes_rejection (trace_manager_test.go:34700), and added same_batch_duplicate_id_first_clean_second_rejected_emits_completion (:34792), TestTraceManager_DuplicateIDFirstRejectedBranches (:40983), and TestRunner_DuplicateIDFinishTaskBatchOrder (bigquery_agent_analytics_plugin_test.go:15069).
  • Explicit eviction flag for rejOverflowed: Added spanRecord.rejectedTasksEvicted (trace_manager.go:350) set by appendRejectedTask (:9049) and appendDeferredRejection (:9056), preserved by endTaskStateLocked (:8732), cleared by clearTaskDeltas (:8749), and read by ownerHasSupersededBatch (:5523) so an exact 64-entry slice without eviction is no longer treated as overflowed.
  • Comments: Restored keepFinishFailureLocked's doc comment right above keepFinishFailureLocked (trace_manager.go:6049) with dedicated docs on hasEvictedFailureCallLocked and noteEvictedFailureCallLocked, and updated noteTaskFinished (:4353-4361) to document that earlier-batch rejections for the same call are cleared while same-batch rejections (rej.modelCallSeq == rec.modelCallSeq) are preserved.
  • Verification (78c2735b):
    • go -C plugin/agentanalytics test -race -mod=readonly -shuffle=on -count=1 ./...: pass (235.008s)
    • go -C plugin/agentanalytics test -mod=readonly -count=1 -coverprofile=... ./...: pass (94.0% package statements; 83/83 blocks and 173/173 statements = 100.00% across changed lines in 45d922a1..78c2735b)
    • go test -race -mod=readonly -count=1 ./agent/llmagent/... ./internal/... ./workflow/...: pass
    • golangci-lint (fmt --diff ./plugin/agentanalytics/..., run --new-from-rev=11f4e29f ./..., run --new-from-rev=origin/main ./plugin/agentanalytics/..., run --new-from-rev=45d922a1 --enable=modernize ./plugin/agentanalytics/...): 0 issues
    • ./.github/scripts/apidiff.sh origin/main: No incompatible changes.
    • go vet ./..., go -C plugin/agentanalytics vet ./..., go build -mod=readonly ./..., go -C plugin/agentanalytics build -mod=readonly ./..., go mod tidy -diff (both modules), gofmt -l plugin/agentanalytics, git diff --check 45d922a1..HEAD, and ./.github/scripts/check-conventional-subject.sh: all pass; 26/26 targeted mutation checks killed (0 survivors, 0 build errors).

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the careful catch on idlePendingFinishCallLocked and the two cleanup notes — addressed in 48f6a6f2:

  1. Duplicate-ID finish_task batch ordering & ambiguous fallback (trace_manager.go, bigquery_agent_analytics_plugin.go, doc.go):

    • Checked internal/llminternal/base_flow.go: stock ADK handleFunctionCalls passes each fnCall.Args map pointer directly to BeforeToolCallback, OnToolErrorCallback, and AfterToolCallback without cloning.
    • finishTaskCallSpec / taskFinishCall now retain the emitted Args map (argsMap + argsPtr) only while the slot is pending (cleared on settlement in clearFinishCall and on activation retirement in clearTaskDeltas, and stripped via .withoutArgsMap() in finishCallSlotsLocked and untakenFinishCallsLocked so completionCalls never retains user argument maps). idlePendingFinishCallLocked matches by batch-wide unique exact map-pointer identity (argsPtr) first, surviving identical, >64 KiB truncated, and in-place-mutated arguments under stock dispatch, before falling back to a batch-wide unique complete boundedArgsDigest.
    • noteTaskFinishCallSpecs computes uniqueArgsPtrInBatch and uniqueArgsDigestInBatch across all emitted same-ID slots in the batch, and idlePendingFinishCallLocked gates firstInBatch on those batch-wide flags when only one idle slot remains (for example, during overlapping BeforeToolCallback dispatch on aliased, nil, or cloned indistinguishable maps). Whenever batch position is indistinguishable, firstInBatch is cleared instead of claiming batch position by callback start order, so a recovered failure on a later goroutine never drops a clean survivor's AGENT_COMPLETED row. doc.go and finishTaskCallSpec now describe the emitted map-identity + digest matching and note this best-effort limit.
    • Expanded TestRunner_DuplicateIDFinishTaskBatchOrder with deterministic reversed-dispatch cases for identical, >64 KiB, and mutated-in-place arguments in each failure position, and added TestTraceManager_DuplicateIDFinishTaskAmbiguousFallback (covering cloned identical/oversized maps, aliased map pointers, skipped BeforeToolCallback dispatch, overlapping BeforeToolCallback ambiguous-args dispatch across aliased/nil/cloned maps in both completion orders, and GC release of argsMap on both settlement and StateDelta-backed completionCalls retirement).
  2. Cap finishedTasks at 64 (trace_manager.go):

    • noteTaskFinishedWithArgs now appends to spanRecord.finishedTasks via keepLatest (bounded at maxTaskToolDeltas = 64), pinned by TestTraceManager_FinishedTasksCappedAtMaxTaskToolDeltas.
  3. Remove test-only parallel wrappers (trace_manager.go, bigquery_agent_analytics_plugin.go, trace_manager_test.go):

    • Removed noteTaskFinished, noteTaskRejected, noteTaskUnfinished, noteTaskFinishCalls, and popTaskAgentSpanWithDelta from trace_manager.go, updated stale internal doc comments to reference the production methods, and migrated all test call sites directly to noteTaskFinishedWithArgs, noteTaskRejectedWithArgs, noteTaskUnfinishedWithArgs, noteTaskFinishCallSpecs, and popTaskAgentSpanWithEvent.

…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.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Pushed 5c2da4b6 on top of 48f6a6f2 to fix the TestRunner_DuplicateIDFinishTaskBatchOrder CI failure under main commit e0cbfd30 (fix(llminternal): give tool callbacks a copy of the call arguments) and update the docs and unit coverage for cloned tool arguments:

  • Root cause: e0cbfd30 changed internal/llminternal/base_flow.go (handleFunctionCalls) to call cloneArgs(fnCall.Args) once per tool call before BeforeToolCallbacks, the tool, OnToolErrorCallbacks, and AfterToolCallbacks. Callbacks of the same call still share that single cloned args map pointer, but mapPtr(args) no longer equals mapPtr(part.FunctionCall.Args). TestRunner_DuplicateIDFinishTaskBatchOrder previously identified calls in BeforeToolCallback/tool/OnToolErrorCallback by comparing mapPtr(args) against the emitted firstMap/secondMap pointers, causing all subtests to miss every hook when merged with main.
  • Production audit & documentation: idlePendingFinishCallLocked in plugin/agentanalytics/trace_manager.go already handles both dispatch modes — matching by emitted Args map pointer (argsPtr) for non-cloning callers/runners and falling back to batch-wide unique untruncated boundedArgsDigest for cloned distinct arguments, while clearing firstInBatch (preserving clean completion) when cloned arguments are identical, digest-truncated (>64 KiB), or pre-mutated. Updated the comments on finishTaskCallSpec (plugin/agentanalytics/bigquery_agent_analytics_plugin.go), idlePendingFinishCallLocked (plugin/agentanalytics/trace_manager.go), and the "Best-effort inspection of ADK internals" / "Behavioral Differences from adk-python" sections in plugin/agentanalytics/doc.go to describe both direct and cloneArgs dispatch accurately.
  • Tests (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go, plugin/agentanalytics/trace_manager_test.go):
    • Updated TestRunner_DuplicateIDFinishTaskBatchOrder (10 subtests, adding reversed_dispatch_distinct_args_*) to claim/match calls by args["result"] / claimedSecond and atomic callback-entry map pointers (failCallPtr / secondCallPtr) so BeforeToolCallback, the tool, OnToolErrorCallback, and AfterToolCallback stay correlated on the same call under both GOWORK=off (adk/v2 v2.0.0, direct Args) and merged main (02b1d0b5 + go.work, cloneArgs), and to assert sawClonedArgs parity for indistinguishable cloned batches vs direct non-cloning dispatch.
    • Added TestTraceManager_DuplicateIDFinishTaskCloningVsDirectArgsBinding (11 subtests) to cover direct non-cloning argsPtr binding (identical, >64 KiB, and in-place-mutated maps) alongside cloneArgs-style fresh map copies (distinct-args boundedArgsDigest binding and identical/>64 KiB/pre-mutated ambiguous-batch fail-safe fallback).
  • Verification (5c2da4b6): go -C plugin/agentanalytics test -race -mod=readonly -shuffle=on -count=1 -parallel=2 ./... passes under both merged origin/main (02b1d0b5 + go work init && go work use -r ., 344.176s) and GOWORK=off (341.661s); GOWORK=off go -C plugin/agentanalytics test -mod=readonly -count=1 -parallel=2 -coverprofile=... ./... passes (94.1% package statements; 114/114 blocks / 224/224 statements = 100.00% over 45d922a1..5c2da4b6); gofmt -l, go vet ./..., go build -mod=readonly ./..., go mod tidy -diff, golangci-lint (0 issues across fmt --diff, GOWORK=off --new-from-rev=48f6a6f2/45d922a1/11f4e29f, and merged origin/main --new-from-rev=02b1d0b5 --enable=modernize), .github/scripts/check-conventional-subject.sh, .github/scripts/apidiff.sh 11f4e29f (No incompatible changes.) all pass.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thank you @caohy1988 for the detailed review! Agreed on all points — especially keeping the base AGENT_COMPLETED rule for task activations (matching adk-python) and limiting #2046 strictly to TOOL_ERROR, TOOL_COMPLETED, and AGENT_RESPONSE, which eliminates rejectedTasks, deferredRejections, ended-rejection frames, and firstInBatch binding along with both task-rejection edge cases.

To make review straightforward, this PR has been split into two focused, main-merged PRs that adopt that exact scope:

Part PR Scope Status
1 / 2 #2377 Bounded args digest, retryAnswerError extraction, and context identity helpers (261b655d, merged with main) Open, CI green
2 / 2 #2381 Suppress recovered TOOL_COMPLETED / AGENT_RESPONSE and log plugin/retryandreflect errors (e0770381, stacked on #2377 and merged with main, keeping the base AGENT_COMPLETED activation rule) Open, CI green

Keeping #2177 open as a reference pointer until #2377 and #2381 merge.

@wojtas000

Copy link
Copy Markdown
Contributor

Closing this one, since you split it into #2180 and #2381 and both are on main now. The recovered-error behavior from #2046 is covered by the TestPlugin_RecoveredToolError_* tests that came with it, so I'll close the issue too.

@wojtas000 wojtas000 closed this Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

agentanalytics: a recovered tool error is logged as a successful TOOL_COMPLETED

3 participants