Skip to content

fix(agentanalytics): harden trace late-retirement, Close/afterRun lifecycle, and RowErrors isolation - #2182

Closed
haiyuan-eng-google wants to merge 12 commits into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2014-v1-hardening
Closed

haiyuan-eng-google wants to merge 12 commits into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2014-v1-hardening

Conversation

@haiyuan-eng-google

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

Copy link
Copy Markdown
Contributor

Linked issue

Related: #2014

Draft Notice: Held in Draft until #2020 merges so overlapping trace_manager.go and events.go hunks rebase cleanly onto main.

Summary

Implements the v1.0.0 resilience hardening items from #2014 across traceManager, plugin Close() / afterRun lifecycle guards, and BatchProcessor partial-batch RowErrors isolation:

  1. Late Trace Retirement, Settled Parallel Subtrees, Causal Recovery Ordering & Bounded Activation Provenance (trace_manager.go, bigquery_agent_analytics_plugin.go, config.go, events.go):
    • Carries openFailureCause from retired drained descendants to the nearest open ancestor across retired non-propagating custom ancestors in retireDrainedDescendantsLocked (preserving the earliest unretired failurePlatformTime and monotonic failureSeq so delayed replay draining does not stamp replay wall time over prior failure timestamps) and drops settled late contexts. An activation that an enclosing retirement left open after its run was known to be over records that point (runEndSeq, runEndPlatformTime), and its later retirement as a drained descendant is dated there, so a first iteration's child that a buffered event retires after the next iteration started does not look like a peer that could have created the later child's events.
    • Tracks ancestorSpanIDs, joinedAtRetire (rec.completed || rec.runDone), and settledByParent (markSettledRetiredActivationsLocked) on retired activations so both cleanly exited subtrees (includeSelf=true) and failed parallel branches drained and recovered by an enclosing agent settle cleanly across sequential iterations (including clean-then-recovered sequences, open-parent live recovery, differing errgroup goroutines, coarse/quantized advancing clocks where start and NewEvent share a tick past prior retirement, a custom ancestor that holds every event of both iterations and replays them in order, and an ancestor that holds the first iteration's events until the second iteration is open), while preserving the earliest unrecovered iteration cause and keeping delayed buffered branch events fail-closed.
    • Enforces fail-closed post-failure causal ordering (evCreatedAt > failure platformTime on live activations across clearRetiredCauseForEventLocked, completeResponseAt, and unrecoveredErrors) so buffered pre-failure progress, same-tick non-callback live events, and buffered zero-timestamp UUIDv4 literals held from a clean earlier run cannot clear a later unrecovered failure (even when the agent or a later plugin registers AfterAgentCallback), while genuine post-failure recovery clears it. An event created after an activation retired counts as that activation's only when it is the event ADK built from its after-agent callbacks, recognized by either action map (StateDelta or ArtifactDelta) of the callback context (afterAgentActions). afterAgentActionsRef keeps those maps reachable through the EventActions that holds them (callbackAfterAgentActions), not through the callback context, so a retired record keeps nothing else of the run. An earlier plugin's OnEventCallback that replaces one map with a copy keeps the recovery, and the same recognition gives same-tick callback recovery its creation-order evidence and excludes open peer activations that have not run their after-agent callbacks yet in eventAuthorLocked.
    • Records those maps for every activation with after-agent callbacks, whether or not it responded and whether or not another activation of its agent is open, so a clean activation's summary is never taken for another activation of the same agent: one that started while ADK ran the callbacks and then failed, one whose run the summary's timestamp falls in when a custom ancestor holds the summary, or one under an intermediate parent that retired while an open custom ancestor still held the summary. popAgentSpan hands the maps, the credit and the peer flag to the entry as retireAgentAtLocked records it (popRetirement), before pruneSettledRetiredActivationsLocked runs, so the entry of an activation without an open custom ancestor, such as the agent of a workflow node, is no longer deleted first. The maps stay until the after-agent event arrives or nothing could take that event for another activation's (needsAfterAgentActionsLocked): the callbacks are known to have returned once another agent starts or ends on the goroutine that retired the activation outside them (afterAgentCallbacksReturnedOnLocked; an agent that the callbacks themselves run there starts and ends inside agent.runAfterAgentCallbacks, whose frames the plugin counts in the goroutine's stack trace, afterAgentCallbackRunsOfTrace, markAfterAgentCallbacksReturnedOnLocked), or once the run of its parent returned, and then the maps go unless an open activation of the agent, a swallower of a recorded cause, an open span under the activation or another one of the agent, or an outstanding credit still needs them; pushAgentSpan settles them only once the starting activation is open (settleAfterAgentActionsOnLocked), so a held after-agent event created in the tick in which the next activation of its agent starts stays recognized. The activation can then own no event created after the point at which its callbacks were seen to return (afterAgentDoneAt), so an open activation's later recovery counts even when the after-agent event that a custom ancestor held arrives unrecognized, only changes state, or never comes, while an event that carries its after-agent maps stays its own whenever it was created (canOwnEventAt). So an agent that yielded progress before it drained a sub-agent's failure is still recognized when a custom ancestor holds the sub-agent's event and the recovery and delivers both in the order in which they were created.
    • Includes all open agent activations on agentStack as disambiguation candidates in eventAuthorLocked / clearRetiredCauseForEventLocked (including concurrent peers, unless the event carries an action map of a retired activation's after-agent callbacks). An event that holds such a map of exactly one retired activation is that activation's alone if it can own the event, and no one's otherwise (afterAgentSharerLocked); on the branches that the event's branch covers, such a map resolves the event to that activation's branch before activations on another of those branches can make it no one's (afterAgentSharerWithinLocked), so an AfterAgentCallback recovery on an enclosing branch counts, and settles its activation's credit, while another activation of the agent runs on a branch under it. So a concurrent activation of the same agent that retired later, and whose run the event's timestamp falls in, no longer makes the event authorless, and selectResponseOwnerWithIDLocked absorbs and settles such an event before an open peer that awaits a model, tool or partial event can claim it. An event that two retired activations claim still has no author. Such an event settles only the unrespondedRetired credit that its own activation left when it retired unresponded while a peer was open (afterAgentCredit, consumeAfterAgentCreditLocked), whether or not its content holds a function response, and never a tool credit or another activation's credit, and only when that activation can own it, with creation provenance and a timestamp at which it can have created it (ownsAfterAgentEvent). The plugin also settles the retired author (settleRetiredAuthorLocked: retiring its drained descendants and clearing the causes it swallowed with evActions) whenever selectResponseOwnerWithIDLocked absorbs an event because a retired activation of its author created it while another activation of the same agent is open (retiredAuthor), on the branch that resolveEventBranchLocked resolved. For a retired author, an event without a branch, or with an enclosing branch that the workflow scheduler stamped, resolves to the only branch whose activations can have created it, also while a later activation of the author runs on another branch, so the drained descendants retire and the swallowed causes clear on that branch; when activations on more than one branch can have created it, it clears nothing and settles nothing. An event of a retired activation's run settles that activation's own credit when only it can have created the event (settleRetiredResponseCreditLocked, createdInRun, creditSettled), so a retired activation that left a credit and created both a run event and an after-agent event settles one credit, not two, and an open llmagent peer no longer takes another retired activation's held response as its awaited model event. It skips open peers that started after an event was created when picking the event's owner (the creation window used for retired activations), and prevents delayed non-UUID unforwardedModelEvents delivered after an unrecovered error from claiming response ownership over open llmSpans (selectResponseOwnerWithIDLocked passes activation-aware hasIDFor(base) so child-scoped platform.WithUUIDProvider model errors preserve unforwardedModelEvents).
    • Gives an open activation the events that only it can have created (soleOpenAuthorLocked), even when it holds a failure and retiredPeerCount records a retired peer. The event must have creation evidence, no other open activation of the agent may have started by then, and no retired activation of the agent may be able to have created it. A retired activation can have created an event created after it retired only while its after-agent event may still come: it has after-agent callbacks, that event, with or without content, was not delivered yet (afterAgentEventSeen), and its callbacks were not seen to return before the event was created (afterAgentDoneAt). The event that ADK builds when after-agent callbacks return no content but change state or artifacts counts as delivered when it carries either action map of exactly one retired activation on the branches that the event's branch covers that can own it (clearLastPartialForEvent); it recovers nothing itself and settles only that activation's credit. A retired peer that no longer has an entry of its own (peerRetirement), or a swallower that a recorded cause names, leaves the event unproven, and peer retirements are not compacted while a peer of theirs is open. So a custom agent that drains a sub-agent's failure and yields its own recovery after a concurrent activation of the same agent finished clears that failure.
    • Places an agent that starts on a goroutine under the open activation of its parent's agent, branch and node path that runs on that goroutine, or, when none does, the one whose goroutine started it (runningLookalikeLocked in parentForRunLocked), not under the lookalike that started last. So when a custom agent runs the same agent on goroutines of its own, a failure that one run's sub-agent swallowed is recorded with that run as its swallower and another run's recovery does not clear it. The runtime names only the goroutine that directly started another, so when neither goroutine identifies one of several lookalikes, as for a sub-agent started from a helper goroutine that runs no ADK callback, the agent runs under the nearest open span that encloses them all (enclosingOpenSpanLocked), and the lookalike that started last can no longer clear a failure that another one swallowed. A retiring activation takes back from an open peer of the same agent only a response that completeResponse routed to the peer as its own (ownResponse in reconcileConcurrentResponseOnPopLocked), not one that the peer inherited from an event of an activation under it, so the retiring activation's after-agent action maps are recorded and its recovery event is not attributed to the peer. A finish_task retirement whose run had not synchronized (unjoinedTaskRetirement) may own events created after it retired (canOwnEventCreatedAt), and hasGuardedRetiredPeerForEventLocked skips retired activations that cannot have created an event at its creation time.
    • Matches a session event with an open activation of its author only on the event's branch or a branch under it (findAgent), so an event of one branch of a parallel agent is never taken for an activation of the same agent on a sibling branch; before, a retired activation's after-agent event, or a run event that its parent held, could clear a failure that an open activation of the same agent on a sibling branch swallowed and never recovered from. An event without a branch, as session.NewEvent leaves it, can be that of an activation on any branch, and one with a branch that of an activation on it or on a branch under it, since the workflow scheduler stamps its node run's branch on an event that left Branch empty. Every session event is attributed only when the activations of its author on a single one of those branches can have created it (resolveEventBranchLocked, eventAuthorBranchesLocked), and otherwise clears no failure and settles no credit, also when one activation ran on par and another on a branch under it. An event created before every open activation of its author, branch and node path started (startedAfterEvent) is absorbed and settled as a retired activation's in selectResponseOwnerWithIDLocked, so it no longer takes the pending model or tool event of the only open activation, and its rows and stream tracking go under the latest open activation that had started by then (eventActivationLocked, eventSpanAt, recordStreamedAt).
    • Verifies session.NewEvent creation provenance via hasEventCreationProvenance(ctx, ev) (accepting canonical RFC 4122 UUIDv4 IDs via hasNewEventUUID or non-empty IDs when an active non-nil platform.WithUUIDProvider is present on the delivery context, an open activation context on agentStack, or a matching retired activation's hasCustomUUIDProvider, without trusting mutable ev.Actions maps as proof of construction), tracks per-span ownResponse (unrespondedAtPop), combines agent AfterAgentCallbacks (agentHasAfterAgentCallbacks) with later registered plugins defining AfterAgentCallback in the innermost PluginManager (contextHasLaterAfterAgentPlugin using a weak.Pointer selfPlugin on traceManager with pluginName fallback so inner sub-runner managers shadow outer ones), and enforces parent/self creation time windows via canOwnEventCreatedAt.
    • Bounds non-surviving clean entries in pruneSettledRetiredActivationsLocked to at most three representatives per compaction key (first, an optional union-timestamp compactedHull across middle iterations with goroutineID cleared so differing errgroup worker goroutines compact in O(1) and ancestor chains intersected, and last; joinedAtRetire and settledByParent are part of the key, so a hull never merges entries that differ in either). Entries that keep after-agent maps, a credit or an open span under them are not compacted, so compaction never strips a pending after-agent event or credit; entries that keep maps or an open span under them, or a credit or peer mark while an activation of their agent is open, are not deleted either, and entries with a peer mark are not compacted while an activation of their agent is open, so soleOpenAuthorLocked still finds every retired peer. Where nothing shows that the callbacks returned, as for activations that a parent runs on goroutines that it does not wait for, at most eight such entries (maxPendingAfterAgent) stay per parent, agent and branch, and the oldest fold into a hull that stands for their after-agent events (foldPendingAfterAgentLocked, afterAgentPending): an event that one of them can have created clears no failure until the parent's run returns. While a peer of those entries is open (hasOpenPeerLocked, shared with pruning), neither peer retirements nor entries whose callbacks were seen to return are folded, so soleOpenAuthorLocked still finds every retired peer.
    • Places the rows of an event that completeResponse just took for a retired activation's after-agent event under the invocation span, as for other events of a retired author, rather than under an overlapping open activation of the same agent that started earlier (completeResponseForEvent and clearLastPartialForEvent report that they took the event as such, and onEvent keeps the report on its own stack and passes it to emitSessionEventSignals and eventSpanAt, so another event that the invocation handles in between cannot change where the first event's rows go).
    • Documented Provenance & Clock Boundaries (Config doc):
      • Bare zero-timestamp session.Event struct literals lacking an RFC 4122 UUIDv4 ID under the default provider (including literals with non-nil Actions.StateDelta and Actions.ArtifactDelta maps) fail closed under runner fallback timestamping, and an event created after the tick in which an activation retired counts as that activation's only when it carries an action map of its after-agent callback context, so buffered zero-timestamp UUIDv4 literals held from a clean earlier run stay fail-closed across later unrecovered iterations. Single-activation zero-timestamp struct literals that manually populate a valid RFC 4122 UUIDv4 ID or run under an invocation/agent-scoped custom platform.WithUUIDProvider remain indistinguishable from session.NewEvent at the plugin boundary.
      • An earlier-registered plugin's OnEventCallback may replace the StateDelta or the ArtifactDelta map of an after-agent recovery event with a copy; an event whose two maps it both replaces is no longer attributed to the retired activation after the retirement tick, and the failure stays reported (as does an event that an earlier plugin replaces, which this plugin's OnEventCallback never sees). An after-agent event is recognized whether or not the agent responded earlier, for as long as a custom ancestor may still deliver it or another activation of the same agent could be taken for its author. When a parent runs more than eight activations of one agent on one branch on goroutines that it does not wait for, the after-agent events of the oldest are no longer told apart until the parent's run returns: an event of that agent that one of them can have created clears no failure, and an open activation of that agent under a custom ancestor records no response with it. While another activation of that agent on that branch and node path is open, none of them is folded that way, nor is an activation whose callbacks were seen to return.
      • Concurrent activations of one agent on the same branch and node path, such as the sub-agents of two concurrent runs of one custom agent, are told apart by when their events were created: an event that one of them created while the other ran, and that an open custom ancestor delivers only after the other retired, could be either's and records no response, so a failure of the activation that created it stays reported even when a custom ancestor recovers from it. Delivering such an event before either activation ends avoids this. An event that the open activation creates after the other retired is its own once the retired one has no AfterAgentCallback (of its agent or of a later plugin), its after-agent event, with or without content, was already delivered, or its callbacks were seen to return before the event was created (another agent started or ended on the goroutine that ran them, outside them, or the run of its parent returned; an agent that a callback runs shows nothing about them); until then it could be that after-agent event with both maps replaced, and the failure stays reported.
      • Activations of one agent on different branches are told apart by each event's Branch: an event is never attributed to an activation on a sibling branch. An event without a Branch can be that of an activation on any branch, and one with a Branch that of an activation on it or under it, so such an event is attributed only when the activations of its author on a single one of those branches can have created it, and otherwise records no response, also when one activation ran on a branch and another on a branch under it; a failure is then recovered only by an event that the others cannot have created (ev.Branch = ctx.Branch() when no other activation of the agent runs under that branch, an event created after the others retired with no after-agent event to come, or the activation's own AfterAgentCallback event, which carries its action maps, unless an earlier plugin replaced both).
      • The runtime names only the goroutine that directly started another, so a sub-agent that concurrent activations of one custom agent each run on a goroutine started by a helper goroutine that runs no ADK callback is placed under the nearest span that encloses those activations, and only that span or the agents above it recover its failure; running such sub-agents on the custom agent's goroutine, or on one that it starts directly, keeps them under their own activation.
      • Custom platform.WithUUIDProvider overrides must be installed on the invocation or agent context.Context; call-site-only overrides passed exclusively to session.NewEvent(platform.WithUUIDProvider(...), ...) fail closed because plugin/agentanalytics/go.mod pins google.golang.org/adk/v2 v2.0.0 and session.Event carries no provider provenance across the module boundary.
      • Under a constant platform.WithTimeProvider, only single-activation AfterAgentCallback content recovery succeeds on the same tick; non-callback recovery and repeated sequential activations under an open custom ancestor require advancing clocks, because on a constant clock nothing in such an event shows whether it was created after the failure or earlier in the same tick.
  2. Idempotent CloseFunc & afterRun Panic Safety (bigquery_agent_analytics_plugin.go):
    • Wraps CloseFunc in sync.OnceValue so repeated Close() calls from both caller defer and launcher shutdown are idempotent and return the initial close error.
    • Guards afterRun with deferred endInvocation and flushRunEnd cleanup even if popUnclosedAgentSpans panics.
  3. Per-Row AppendRowsResponse.RowErrors Isolation (batch_processor.go, config.go):
    • Isolates row-level AppendRowsResponse.RowErrors failures in appendChunkRows (including when Error == nil with non-empty RowErrors), counting dropped rows under DropStats.RowErrorDrops (included in TotalDrops) and resending remaining valid rows while preserving uncommitted streamOffset in ExactlyOnceDelivery mode, unless RowErrors follows an earlier ambiguous send in ExactlyOnceDelivery mode, in which case streamWriter.append fails closed (offsetDesynced = true, counted under AppendFailureDrops) without replaying potentially committed survivors onto a rotated stream. Config lists RowErrors after an attempt with an unknown outcome next to OutOfRange and NotFound among the responses that drop the batch and replace the stream before the next one.

Behavior change

  1. Partial-batch AppendRowsResponse.RowErrors rejections on unambiguous sends now drop only the rejected row indices (counted in new DropStats.RowErrorDrops and TotalDrops) and retry the remaining valid rows in the batch rather than failing/dropping the entire batch; when RowErrors follows an ambiguous send in ExactlyOnceDelivery mode, the uncertain batch fails closed without survivor replay and rotates the stream before the next independent batch.
  2. Calling Plugin.Close() more than once is now idempotent (sync.OnceValue), and a panic during afterRun span unwinding still ends the invocation trace and flushes queued run-end rows while recoverCallback contains the panic.
  3. Retired custom non-propagating agent spans carry drained descendant failure causes up to the nearest open ancestor with causal timestamp ordering (evCreatedAt > failure platformTime), settled parallel subtree tracking (ancestorSpanIDs, joinedAtRetire, settledByParent), run-end dating of late drained-descendant retirements (runEndSeq, runEndPlatformTime), retired-author settlement when an event is absorbed while another activation of the same agent is open (eventAuthorLocked, settleRetiredAuthorLocked) on the retired author's resolved branch (resolveEventBranchLocked), at most one credit per retired activation across its run and after-agent events (settleRetiredResponseCreditLocked), exclusive attribution of an event that carries one retired activation's after-agent action map ahead of open peers, of later-retired concurrent peers and of activations on branches under the event's branch (afterAgentSharerLocked, afterAgentSharerWithinLocked) with credit settlement limited to that activation and to events it can own (consumeAfterAgentCreditLocked, ownsAfterAgentEvent), no ownership of events created after a retired activation's after-agent callbacks were seen to return (afterAgentDoneAt), ownership of events that only one open activation can have created (soleOpenAuthorLocked, afterAgentEventSeen, peerRetirement), parent resolution among concurrent lookalike activations by goroutine (runningLookalikeLocked), falling back to their nearest enclosing open span when no goroutine identifies one (enclosingOpenSpanLocked), branch-scoped event attribution that treats an event on a branch as possibly that of an activation under it (findAgent, resolveEventBranchLocked, eventAuthorBranchesLocked), no ownership by open activations that started after an event was created (startedAfterEvent, eventActivationLocked, eventSpanAt, recordStreamedAt), recognition of after-agent events without content (clearLastPartialForEvent), response reclaim on pop limited to a peer's own responses (ownResponse), post-retirement event ownership for unjoined finish_task retirements (unjoinedTaskRetirement), live open-activation ambiguity checks across agentStack[1:] (leaving open activations out when an event carries a retired activation's after-agent action map) with creation-window owner selection among open peers, event creation-window and provenance checks (hasEventCreationProvenance, hasNewEventUUID, contextHasCustomUUIDProvider, contextHasLaterAfterAgentPlugin, unrespondedAtPop, canOwnEventCreatedAt, after-agent callback action maps afterAgentActions/afterAgentActionsRef, kept through the callback's EventActions, recorded for every activation with after-agent callbacks before any pruning and kept while needed (needsAfterAgentActionsLocked, afterAgentCallbacksReturnedOnLocked outside running after-agent callbacks (afterAgentCallbackRunsOfTrace), settled only once a starting activation is open (settleAfterAgentActionsOnLocked), bounded per parent by foldPendingAfterAgentLocked except while a peer is open (hasOpenPeerLocked)), for post-retirement and same-tick callback recovery, and activation-aware provenance gating on unforwardedModelEvents after errors), and O(1)-per-key retiredActivations hull compaction (<= 3 per key across differing errgroup goroutines, never over entries that keep after-agent maps, a credit or an open span under them, nor over peer retirements while a peer is open), preserving unrecovered failures whenever buffered, pre-failure, missing-provenance, or multi-activation recovery attribution is ambiguous, while releasing settled late-context map entries promptly.

Testing Plan

All results below are from a clean git archive 16dfacdf with go work init && go work use -r . (as in CI), -mod=readonly, go1.27.3 and the default GOMAXPROCS (24 on this machine), unless noted.

  • gofmt -l ., GOWORK=off go mod tidy -diff, go build ./... and go vet ./... are clean in the repository root and in plugin/agentanalytics. In a clone checked out at 16dfacdf: git diff --check origin/main..HEAD is clean, golangci-lint run --new-from-merge-base=origin/main ./... reports 0 issues. in the repository root and in plugin/agentanalytics, and .github/scripts/apidiff.sh origin/main reports No incompatible changes.
  • plugin/agentanalytics: go test -p 1 -parallel 1 -race -shuffle=on -count=1 -v ./... passes (ok ... 251.859s, shuffle seed 1794521085567369042, 636 top-level tests pass, 0 data races), as do go test -p 1 -parallel 1 -race -count=1 ./... (ok ... 266.479s, 0 data races) and go test -p 1 -parallel 1 -shuffle=on -count=1 -v ./... (ok ... 119.102s, shuffle seed 1794521638689925797, 636 top-level tests pass).
  • These runner and unit tests pass under -race -count=30 (1110 of 1110 top-level runs, ok ... 430.942s), with 0 data races: TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner, TestSubBranchEventKeepsEnclosingBranchFailure_Runner, TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner, TestOpenPeerRecoveryAfterManyPeersRetired_Runner, TestAfterAgentDoneBoundsRetiredEvents, TestAfterAgentEventOwnershipSettlesCredit, TestPeerRetirementsStayUncompactedWhilePeerOpen, TestResolveEventBranch, TestRetiredEventBranch, TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner, TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner, TestRetiredAfterAgentEntriesStayBounded_Runner, TestGuardlessRetirementKeepsAfterAgentEntry, TestRetiredAuthorBranchResolution, TestAfterAgentRecoveryAfterConcurrentPeerRetired_Runner, TestAfterAgentRecoveryWithOpenPeerAwaitingEvent_Runner, TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner, TestEventCreatedBeforeLaterActivationStarted_Runner, TestLookalikeSubAgentOnHelperGoroutine_Runner, TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner, TestCleanParallelIterationsBoundRetiredActivations_Runner, TestAfterAgentFunctionResponseSettlesOwnCredit_Runner, TestCrossBranchEventAuthor, TestSoleOpenAuthor, TestPendingAfterAgentHull, TestAfterAgentCallbacksReturnedOn, TestSettleRetiredResponseCredit, TestRetiredActivationSettlementAndHullConjuncts, TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner, TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner, TestAfterAgentSharerResolvesEventBranch, TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner, TestAfterAgentCallbacksStillRunning, TestSameTickStartKeepsHeldAfterAgentEvent_Runner, TestStartingActivationKeepsSameAgentAfterAgentMaps and TestSettledAfterAgentPlacementSurvivesInterleavedEvent. TestAfterAgentRecoveryWithCopiedActionMaps_Runner and TestCallbackAfterAgentActionMaps pass under -race -count=10 (20 of 20).
  • Repository root: go test -p 2 -count=1 ./... passes (114 packages ok, 0 failures).
  • The runner tests added for the after-agent fixes fail on a clean git archive 97404825 with only those tests and the test helpers that they use added: the four for after-agent events on an enclosing branch, agents that after-agent callbacks run and same-tick starts (TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner, TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner, TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner, TestSameTickStartKeepsHeldAfterAgentEvent_Runner), the four for after-agent callbacks seen to return, branch resolution, retired-branch recovery and peer retirements (TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner, TestSubBranchEventKeepsEnclosingBranchFailure_Runner, TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner, TestOpenPeerRecoveryAfterManyPeersRetired_Runner), 21 failing subtests among them besides TestSameTickStartKeepsHeldAfterAgentEvent_Runner, which has none and fails as a whole, and the three for after-agent retention, retired-author branches and credits (TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner, TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner), 10 failing subtests. In each failing case, a recovery is reported as INVOCATION_ERROR, an unrecovered failure as INVOCATION_COMPLETED, held events take an open llmagent's awaited model event, or a summary's row is placed under an open activation's span instead of the invocation span: TestCleanAfterAgentEventKeepsPeerFailure_Runner/fifth_activation/summary_delivered_while_the_failing_activation_is_open/keeps_the_failure still reports the failure there, but places the summary's AGENT_RESPONSE row under the failing activation of inner, and in TestSameTickStartKeepsHeldAfterAgentEvent_Runner the held summary both takes the llmagent's awaited model event and goes under its span. Every negative control passes there, and all of them pass at 16dfacdf. The unit tests added with them use symbols that 97404825 does not have, so the mutants below pin them.
  • Tests covering each change:
    • RowErrors partial-batch isolation, ExactlyOnceDelivery offset preservation, & ambiguous-send fail-closed guard: TestBatchProcessor_RowErrorsIsolation, TestBatchProcessor_DropStats, TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors
    • CloseFunc sync.OnceValue idempotency & afterRun panic cleanup: TestPlugin_CloseOnceAndAfterRunPanic, TestClose_SecondCallAfterCleanCloseSucceeds, TestGCSOffloading_CloseReportsTheCloseErrors
    • After-agent map retention for clean activations, entries recorded before pruning, bounded pending entries, retired-author branch resolution, one credit per retired activation, and after-agent row placement: TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestGuardlessRetirementKeepsAfterAgentEntry, TestRetiredAfterAgentEntriesStayBounded_Runner, TestPendingAfterAgentHull, TestAfterAgentCallbacksReturnedOn, TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner, TestRetiredAuthorBranchResolution, TestRetiredEventBranch, TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner, TestSettleRetiredResponseCredit, TestSettledAfterAgentEventPlacement
    • Drained-descendant, settled parallel subtrees, causal recovery ordering, open-activation disambiguation, retired-author settlement on peer absorption, after-agent map attribution among concurrent and open peers, open-peer ownership after a peer retired, lookalike parent resolution, own-response reclaim, after-agent credit settlement, branch-scoped attribution, events created before an activation started, after-agent events without content, scoped-UUID/fixed-clock provenance & bounded hull compaction: TestRetireDrainedDescendants_CarriesCauseAndDropsLateContexts, TestRetireDrainedDescendants_NestedRetiredCustomAncestors, TestNestedRetiredRecovery_Runner, TestSequentialRecoveredParallelIterations_Runner, TestAfterAgentRecoveryWhileConcurrentPeerOpen_Runner, TestCleanParallelIterationsBoundRetiredActivations_Runner, TestDelayedRecoveryDoesNotClearLaterActivation_Runner, TestBufferedPreFailureContent_Runner, TestLaterLiveResponseDoesNotClearRetiredFailure_Runner, TestZeroTimestampBufferedCleanRun_Runner, TestLaterPluginAfterAgentRecovery_Runner, TestAfterAgentRecoveryWithCopiedActionMaps_Runner, TestAfterAgentRecoveryAfterEarlierProgressWithHeldChildEvent_Runner, TestCustomUUIDProviderRecovery_Runner, TestFixedTimeProviderRecovery_Runner, TestAfterAgentActionMapsGCReuse_Runner, TestHasNewEventUUID, TestCausalRecoveryOrderingAndProvenanceGuards, TestRetiredActivationSettlementAndHullConjuncts, TestResponseOwnerCreationWindowAndRunEndRetirement, TestRetiredAuthorEventWhilePeerOpen, TestAfterAgentRecoveryAfterConcurrentPeerRetired_Runner, TestAfterAgentRecoveryWithOpenPeerAwaitingEvent_Runner, TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner, TestAfterAgentFunctionResponseSettlesOwnCredit_Runner, TestLookalikeParentPrefersRunningGoroutine_Runner, TestLookalikeSubAgentOnHelperGoroutine_Runner, TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner, TestEventCreatedBeforeLaterActivationStarted_Runner, TestSoleOpenAuthor, TestAfterAgentCreditSettlesOnlyItsOwnActivation, TestRunningLookalikeLocked, TestCrossBranchEventAuthor, TestEventCreatedBeforeOpenActivationsStarted, TestClearLastPartialForEvent, TestTraceManager_AgentNesting, TestTraceManager_FinalResponseToolRow, TestReconcileConcurrentResponseOnPopKeepsInheritedPeerResponse, TestCallbackAfterAgentActionMaps, TestContextHasLaterAfterAgentPlugin, TestContextHasCustomUUIDProviderAndProvenance, TestLatePopSpanEarlyReturn_RetiresSettledActivation
    • After-agent callbacks seen to return, branch resolution across an event's branch and the branches under it, retired-branch recovery while a later activation runs on another branch, peer retirements under an open peer, and after-agent credit ownership: TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner, TestSubBranchEventKeepsEnclosingBranchFailure_Runner, TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner, TestOpenPeerRecoveryAfterManyPeersRetired_Runner, TestAfterAgentDoneBoundsRetiredEvents, TestResolveEventBranch, TestRetiredEventBranch, TestPeerRetirementsStayUncompactedWhilePeerOpen, TestAfterAgentEventOwnershipSettlesCredit
    • After-agent events on an enclosing branch while an activation runs on a branch under it, no folding of peer entries while a peer is open, agents that after-agent callbacks run, same-tick starts, and the settlement report on the stack: TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner, TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner, TestAfterAgentSharerResolvesEventBranch, TestOpenPeerRecoveryAfterManyPeersRetired_Runner, TestPeerRetirementsStayUncompactedWhilePeerOpen, TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner, TestAfterAgentCallbacksStillRunning, TestSameTickStartKeepsHeldAfterAgentEvent_Runner, TestStartingActivationKeepsSameAgentAfterAgentMaps, TestSettledAfterAgentPlacementSurvivesInterleavedEvent
  • Mutants checked at this head: each of these 95 compiling mutants makes every listed test fail (the unmutated tree passes the same tests).
    • Recording the after-agent maps in popAgentSpan only under the earlier condition: TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestGuardlessRetirementKeepsAfterAgentEntry.
    • Handing the credit, peer flag and maps to the entry only after retireAgentAtLocked pruned; letting pruning delete a guardless entry that holds an after-agent event, an open span under it or a peer credit: TestGuardlessRetirementKeepsAfterAgentEntry.
    • Dropping a responded child's maps when its parent retires under an open custom ancestor: TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestRetiredActivationSettlementAndHullConjuncts.
    • Compacting entries that keep maps, a credit or an open span under them: TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestCausalRecoveryOrderingAndProvenanceGuards.
    • Disabling foldPendingAfterAgentLocked: TestRetiredAfterAgentEntriesStayBounded_Runner, TestPendingAfterAgentHull.
    • Letting a later activation exclude a pending hull by timestamp (excludedByEventTimestamp); not letting a pending hull own an event created after its members retired (eventAuthorLocked): TestPendingAfterAgentHull.
    • Ignoring in needsAfterAgentActionsLocked that the callbacks may still run; ignoring an open activation of the same agent there; not marking a child's callbacks as returned once its parent's run returned (recordRetiredActivationsAtLocked): TestRetiredActivationSettlementAndHullConjuncts.
    • Ignoring another activation's outstanding credit in needsAfterAgentActionsLocked: TestAfterAgentCallbacksReturnedOn.
    • Making afterAgentCallbacksReturnedOnLocked a no-op and not marking in pushAgentSpan the callbacks that returned: TestAfterAgentCallbacksReturnedOn, TestCleanParallelIterationsBoundRetiredActivations_Runner.
    • Keeping the event's own branch for a found open activation in completeResponseWithEvent; keeping the event's own branch for a retired author in completeResponseWithEvent: TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner, TestRetiredAuthorBranchResolution.
    • Keeping the event's branch in resolveEventBranchLocked when activations on two branches can have created it; ignoring an activation on the event's branch itself in eventAuthorBranchesLocked: TestRetiredEventBranch.
    • Settling one credit of the key for every retired author's event, as before: TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner, TestSettleRetiredResponseCredit.
    • Settling a credit again after the activation's credit was settled; not recording in consumeAfterAgentCreditLocked that the credit was settled; letting createdInRun ignore when the activation started: TestSettleRetiredResponseCredit.
    • Ignoring the settlement report in eventSpanAt: TestSettledAfterAgentEventPlacement, TestCleanAfterAgentEventKeepsPeerFailure_Runner.
    • Returning no settlement report from completeResponseForEvent: TestSettledAfterAgentPlacementSurvivesInterleavedEvent, TestCleanAfterAgentEventKeepsPeerFailure_Runner.
    • Applying the settlement report to the rows that a callback places (eventSpan): TestTraceManager_FinalResponseToolRow, TestTraceManager_AgentNesting, TestSettledAfterAgentEventPlacement.
    • Matching an event's branch loosely in findAgent: TestCrossBranchEventAuthor, TestTraceManager_AgentNesting.
    • Skipping findEventAgentLocked: TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner, TestCrossBranchEventAuthor, TestTraceManager_AgentNesting.
    • Taking findAgent's open activation in completeResponseWithEvent; leaving out retired activations in eventAuthorBranchesLocked: TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner, TestCrossBranchEventAuthor.
    • Counting every retired activation in eventAuthorBranchesLocked; ignoring creation provenance there; ignoring when open activations started there; leaving out swallowers there; tracking partial events with findAgent: TestCrossBranchEventAuthor.
    • Not absorbing an event created before every open activation started: TestEventCreatedBeforeLaterActivationStarted_Runner, TestEventCreatedBeforeOpenActivationsStarted.
    • Absorbing such an event without settling a credit: TestEventCreatedBeforeOpenActivationsStarted, TestRetireDrainedDescendants_NestedRetiredCustomAncestors.
    • Treating an equal start time as a later one: TestEventCreatedBeforeOpenActivationsStarted, TestFixedTimeProviderRecovery_Runner.
    • Placing an event under an open activation that started after it: TestEventCreatedBeforeLaterActivationStarted_Runner, TestEventCreatedBeforeOpenActivationsStarted, TestCrossBranchEventAuthor.
    • Placing session-event rows without the event's creation time: TestEventCreatedBeforeLaterActivationStarted_Runner.
    • Keeping the last-started lookalike when no goroutine identifies one: TestLookalikeSubAgentOnHelperGoroutine_Runner, TestRunningLookalikeLocked.
    • Letting enclosingOpenSpanLocked return a retired span: TestRunningLookalikeLocked.
    • Ignoring an after-agent event without content: TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner, TestClearLastPartialForEvent.
    • Handling an after-agent event without content with clearLastPartial in onEvent: TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner.
    • Dropping the ownership step of clearLastPartialForEvent; dropping its provenance step; dropping its credit step: TestClearLastPartialForEvent.
    • Dropping the keep for an open span under the activation in needsAfterAgentActionsLocked; dropping, together with that keep, the maps on an enclosing retirement without an open custom ancestor while a span under the activation is open; keeping the callback context instead of its EventActions: TestAfterAgentRecoveryAfterEarlierProgressWithHeldChildEvent_Runner.
    • Disabling soleOpenAuthorLocked; ignoring afterAgentEventSeen: TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner, TestAfterAgentFunctionResponseSettlesOwnCredit_Runner, TestSoleOpenAuthor.
    • Dropping the retired-ownership condition of soleOpenAuthorLocked; dropping its start window; dropping its peer-entries condition; dropping its swallower condition; dropping its zero-timestamp condition; dropping its pending model or tool event condition: TestSoleOpenAuthor.
    • Restoring the earlier credit handling for an open peer: TestRetiredAuthorEventWhilePeerOpen.
    • Restoring the earlier credit handling with no open activation: TestAfterAgentCreditSettlesOnlyItsOwnActivation.
    • Weighing the starting goroutine like the running one: TestLookalikeParentPrefersRunningGoroutine_Runner, TestRunningLookalikeLocked.
    • Dropping the ownResponse check: TestReconcileConcurrentResponseOnPopKeepsInheritedPeerResponse.
    • Making runningLookalikeLocked return the last-started lookalike: TestAfterAgentRecoveryAfterConcurrentPeerRetired_Runner.
    • Disabling the afterAgentSharerLocked absorption in selectResponseOwnerWithIDLocked: TestRetiredAuthorEventWhilePeerOpen, TestAfterAgentRecoveryWithOpenPeerAwaitingEvent_Runner.
    • Skipping RowErrors isolation: TestBatchProcessor_RowErrorsIsolation, TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors.
    • Skipping the ambiguous-send guard: TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors.
    • Removing the sync.OnceValue around CloseFunc: TestPlugin_CloseOnceAndAfterRunPanic, TestClose_SecondCallAfterCleanCloseSucceeds.
    • Dropping the afterAgentDoneAt bound in canOwnEventAt; not recording that time in markAfterAgentCallbacksReturnedOnLocked: TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner, TestAfterAgentDoneBoundsRetiredEvents.
    • Not recording it once the parent's run returned; keeping the latest sighting in markAfterAgentDone; bounding an event that carries the activation's after-agent maps by that time in canOwnEventAt; not passing that an event carries the activation's maps to canOwnEventAt in eventAuthorLocked; keeping the first member's time in a pending hull; keeping the first middle member's time in a compacted hull: TestAfterAgentDoneBoundsRetiredEvents.
    • Giving an event to an open activation on the event's own branch in resolveEventBranchLocked without looking at other branches: TestSubBranchEventKeepsEnclosingBranchFailure_Runner, TestResolveEventBranch.
    • Giving an event to a retired activation on the event's own branch without looking at other branches: TestSubBranchEventKeepsEnclosingBranchFailure_Runner, TestRetiredEventBranch.
    • Treating an event of a single retired branch as no one's while an activation of its author runs on another branch: TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner, TestResolveEventBranch.
    • Giving an event that is no one's to findAgent's activation in findEventAgentLocked: TestCrossBranchEventAuthor, TestTraceManager_AgentNesting.
    • Compacting peer retirements while a peer is open: TestOpenPeerRecoveryAfterManyPeersRetired_Runner, TestPeerRetirementsStayUncompactedWhilePeerOpen.
    • Settling the credit of a sharer that cannot own the event in selectResponseOwnerWithIDLocked; settling the credit of a sharer that cannot own the event in completeResponseWithEvent: TestAfterAgentEventOwnershipSettlesCredit.
    • Dropping the creation provenance test of ownsAfterAgentEvent; dropping the timestamp test of ownsAfterAgentEvent: TestAfterAgentEventOwnershipSettlesCredit, TestClearLastPartialForEvent.
    • Resolving an event that carries a retired activation's after-agent map without that activation in resolveEventBranchLocked, so that activations on a branch under its branch make it no one's: TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner, TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner, TestAfterAgentSharerResolvesEventBranch.
    • Matching only the event's own branch in clearLastPartialForEvent: TestAfterAgentSharerResolvesEventBranch.
    • Dropping the open-peer skip in foldPendingAfterAgentLocked: TestOpenPeerRecoveryAfterManyPeersRetired_Runner, TestPeerRetirementsStayUncompactedWhilePeerOpen.
    • Folding peer retirements while a peer is open in foldPendingAfterAgentLocked; folding entries whose callbacks were seen to return while a peer is open: TestPeerRetirementsStayUncompactedWhilePeerOpen.
    • Ignoring the runs of after-agent callbacks that enclose an agent's start in pushAgentSpan; ignoring them at an agent's end in popAgentSpan: TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner.
    • Not counting the runs of after-agent callbacks in a goroutine's stack trace: TestAfterAgentCallbacksStillRunning, TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner.
    • Keeping the activations that retired last on the goroutine, instead of first, as the ones whose callbacks still run: TestAfterAgentCallbacksStillRunning.
    • Dropping the maps that no longer seem needed before the starting activation is open in pushAgentSpan: TestSameTickStartKeepsHeldAfterAgentEvent_Runner, TestStartingActivationKeepsSameAgentAfterAgentMaps.
    • Passing no settlement report from onEvent to emitSessionEventSignals: TestCleanAfterAgentEventKeepsPeerFailure_Runner.
    • Reporting no settlement from clearLastPartialForEvent: TestAfterAgentSharerResolvesEventBranch.
    • Reporting no settlement from selectResponseOwnerWithIDLocked: TestAfterAgentEventOwnershipSettlesCredit.

…ecycle, and RowErrors isolation

- Carry openFailureCause from retired drained descendants to the nearest open
  ancestor (re-attributing across retired non-propagating custom ancestors so
  recovery responses in completeResponse clear drained causes consistently in
  both open-owner and retired-author orders) and drop settled late contexts in
  retireDrainedDescendantsLocked.
- Uniformly defer retireLateSettledLocked after inv.mu.Unlock across
  popAgentSpan, popTaskAgentSpan, popDelegatingAgentSpan, popLLMSpan, and
  popToolSpan; use deferred mutex unlocks in endInvocation; remove write-only
  eventData.customMetadataScrubbed.
- Guard CloseFunc with sync.OnceValue and ensure afterRun runs endInvocation
  and flushRunEnd in deferred cleanup even if popUnclosedAgentSpans panics.
- Isolate row-level AppendRowsResponse.RowErrors failures in tryAppendBatch,
  counting dropped rows under DropStats.RowErrorDrops (included in TotalDrops)
  and resending remaining valid rows while preserving uncommitted streamOffset
  in ExactlyOnceDelivery mode (including Error == nil with non-empty RowErrors).
  Each reported row is dropped and counted once, whatever the order or
  repetition of its index, and indices are read against the rows of their own
  request when a batch is split; indices outside the request are logged and
  ignored, and fail the request when no reported index names a row.

Refs: google#2014
@haiyuan-eng-google
haiyuan-eng-google force-pushed the fix/bqaa-2014-v1-hardening branch from c5e19db to 63b226e Compare November 7, 2026 00:54
caohy1988

This comment was marked as outdated.

…ss retired ancestors

- Keep every eligible custom swallower identity (inner and outer) on retiredCause across both retireDrainedDescendantsLocked and retireAgentLocked without overwriting inner swallowers or collapsing distinct sibling causes.
- Preserve unrelated sibling failure causes when only one nested custom branch recovers via AfterAgentCallback.
- Add trace-level regression coverage (TestRetireDrainedDescendants_NestedRetiredCustomAncestors) and end-to-end Runner coverage (TestNestedRetiredRecovery_Runner).
caohy1988

This comment was marked as outdated.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed in 4ec5225:

  1. Nested retired custom ancestor recovery attribution (plugin/agentanalytics/trace_manager.go):
    • Preserved individual retiredCauses entries and accumulated every eligible non-propagating healthy custom ancestor (name, branch, path) (retiredSwallower / retiredCause.swallowers) across both retireDrainedDescendantsLocked and retireAgentLocked without overwriting inner recovery carriers or collapsing unrelated sibling causes.
    • Kept propagatesChildError workflow barriers and failed-context wrappers excluded from swallowing, and preserved unrelated sibling failures when only one nested branch recovers.
    • Added trace-level (TestRetireDrainedDescendants_NestedRetiredCustomAncestors) and end-to-end runner.Run callback (TestNestedRetiredRecovery_Runner) regression coverage across inner recovery, outer recovery, non-recovery, workflow barriers, and sibling failures in both retirement orderings.
  2. PR description wording: Updated the afterRun bullet under Behavior change to note that recoverCallback contains the panic after deferred trace cleanup and run-end flush.

caohy1988

This comment was marked as outdated.

caohy1988

This comment was marked as outdated.

…iguous RowErrors

Scope retiredCause swallower attribution to specific spanID/seq activations so delayed recovery from an earlier activation only clears causes linked to the earliest matching retired swallower and preserves unrecovered failures from other activations.

In ExactlyOnceDelivery mode, reject AppendRows responses carrying RowErrors after an earlier ambiguous send with an explicit uncertain-outcome error instead of isolating and replaying surviving rows onto a rotated committed stream, preserving all uncertain rows for AppendFailureDrops and rotating before the next independent batch.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed both P1 findings from Review 5814169326 in commit d90303891646b29ab17084ed2c2a495842e60f7f:

  1. Per-activation swallower identity for delayed recovery (trace_manager.go):
    • Added spanID and seq to retiredSwallower (deduplicating retiredCause.addSwallower by spanID) and replaced clearRetiredCauseFor with (*invocationTrace).clearRetiredCauseForLocked (wired in completeResponse and selectResponseOwnerLocked).
    • Recovery events now resolve the earliest matching retired swallower activation (min(seq)) across inv.agentStack and clear only causes carrying that activation's spanID, keeping all causes drained through that activation grouped while leaving unrecovered failures from later activations intact (INVOCATION_ERROR).
    • Added runner-level and trace-level regressions in TestDelayedRecoveryDoesNotClearLaterActivation_Runner and TestRetireDrainedDescendants_NestedRetiredCustomAncestors (activation/... subtests).
  2. Fail-closed ExactlyOnceDelivery guard when RowErrors follows an ambiguous send (batch_processor.go):
    • In streamWriter.append, when ExactlyOnceDelivery && hadAmbiguousSend && len(recvRes.GetRowErrors()) > 0, append now returns a terminal uncertain-outcome error (while defer marks s.offsetDesynced = true) before appendChunkRows strips bad rows or retries survivors — preventing potentially already-committed survivor rows from being replayed onto a freshly rotated committed stream, counting the uncertain batch under AppendFailureDrops, and rotating cleanly before the next independent batch.
    • Added TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors covering both Error == nil and codes.InvalidArgument RowErrors variants alongside DropStats and next-batch rotation assertions, and updated the PR description accordingly.

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 ./... across plugin/agentanalytics and root packages.

caohy1988

This comment was marked as outdated.

caohy1988

This comment was marked as outdated.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Addressed the buffered multi-response attribution finding in 356767e2:

  • Independent retired-activation provenance (retiredActivation & clearRetiredCauseForEventLocked): Retiring agent spans now record lightweight activation metadata (spanID, seq, retiredAtSeq, completedOrTask, concurrentPeer, goroutineID, startPlatformTime, and open non-propagating ancestor guardSpanIDs) in inv.retiredActivations independently of surviving retiredCauses. When a delayed response arrives after retirement, clearRetiredCauseForEventLocked excludes earlier completed same-goroutine activations only when event-creation timestamp provenance (ev.Timestamp.After(laterStartPlatformTime)) proves the event could not have originated from them, and clears causes only when a single candidate activation remains unambiguous (len(matchedIDs)+fallbackCount == 1). Two buffered responses from an earlier activation (or a delayed response from a clean activation after an earlier activation failed) therefore never advance to clear another activation's unrecovered failure.
  • Open-activation protection under buffered peer & prior-turn events (hasGuardedRetiredPeerForEventLocked, unforwardedModelEvents / unforwardedToolEvents, & unrecErrTiming): Preserved unforwarded model and tool event credits across multi-turn spans and retirement (reconcileConcurrentResponseOnPopLocked), guarded open activations in selectResponseOwnerLocked and completeResponseAt against buffered events from guarded retired peers, and absorbed pre-error / equal-timestamp buffered events (hasFuncCall or !evCreatedAt.After(errTime) across recordedError.platformTime and retiredCause.platformTime) onto the parent without clearing open failures.
  • Regression coverage: Expanded TestDelayedRecoveryDoesNotClearLaterActivation_Runner and TestRetireDrainedDescendants_NestedRetiredCustomAncestors with Runner E2E and direct traceManager tests covering two buffered responses from a recovered first run, buffered responses from a clean first run, nested wrapper AfterAgentCallback tails, buffered FunctionCall/FunctionResponse/plain-text events across tool and model failures (including frozen-clock platform.WithTimeProvider), and same-goroutine sequential recovery.

caohy1988

This comment was marked as outdated.

caohy1988

This comment was marked as outdated.

…ivation compaction

- Enforce post-failure causal ordering (evCreatedAt > failure platform time)
  across clearRetiredCauseForEventLocked, completeResponseAt, and
  drained-descendant failure times so pre-failure buffered progress cannot
  clear later errors while genuine post-failure recovery still clears them.
- Include all open agent activations on agentStack when disambiguating
  retired failure causes and separate retiredPeerCount absorption from guarded
  retired peer absorption in selectResponseOwnerLocked.
- Verify runner-created UUIDv4 provenance via hasNewEventUUID across
  clearRetiredCauseForEventLocked and unforwardedModelEvents error recovery,
  track per-span ownResponse (unrespondedAtPop) and agent-level
  AfterAgentCallback presence, and enforce parent/self creation time windows
  via canOwnEventCreatedAt so delayed non-UUID buffered events stay fail-closed.
- Bound non-surviving clean entries per state tuple in
  pruneSettledRetiredActivationsLocked to <= 3 representatives per key (exact
  earliest/latest entries plus one compacted middle timestamp hull) and add
  unit + end-to-end runner test coverage.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed the causal recovery ordering, open-activation disambiguation, zero-timestamp provenance, and compaction findings in commit 366937b9e891:

  1. Post-failure causal ordering (trace_manager.go): Enforced evCreatedAt > failure platformTime (canClearCauseAt, canClearOwnerCauseAt) across clearRetiredCauseForEventLocked, completeResponseAt, and unrecoveredErrors, while preserving the earliest unretired failurePlatformTime across retireAgentAtLocked and retireDrainedDescendantsAtLocked so buffered pre-failure events cannot clear later failures while genuine post-failure recovery replays still clear them (TestBufferedPreFailureContent_Runner).
  2. Live open-activation disambiguation (trace_manager.go): Included live open activations on inv.agentStack[1:] in clearRetiredCauseForEventLocked and separated retiredPeerCount[k] > 0 absorption from hasGuardedRetiredPeerForEventLocked absorption in selectResponseOwnerLocked, preventing a live subsequent activation or open failing concurrent peer from clearing an earlier retired failure (TestLaterLiveResponseDoesNotClearRetiredFailure_Runner, TestCausalRecoveryOrderingAndProvenanceGuards).
  3. Zero-timestamp buffered event provenance & non-UUID guard (bigquery_agent_analytics_plugin.go, trace_manager.go): Added RFC 4122 UUIDv4 provenance checking (hasNewEventUUID(ev.ID)), unrespondedAtPop (!ownResponse), agentHasAfterAgentCallbacks, canOwnEventCreatedAt creation-window bounds, and !hasEventID gating on unforwardedModelEvents under hasUnrecErr so runner-stamped zero-timestamp buffered events stay fail-closed (TestZeroTimestampBufferedCleanRun_Runner, TestHasNewEventUUID).
  4. Bounded O(1)-per-key retiredActivations compaction (trace_manager.go): Bounded clean non-surviving entries in pruneSettledRetiredActivationsLocked to <= 3 representatives (first, union-window compactedHull, and last) per state-and-guard key (TestCausalRecoveryOrderingAndProvenanceGuards).

caohy1988

This comment was marked as outdated.

…rovenance

Address both review findings without crossing module boundaries or creating reference cycles:
- Inspect the innermost PluginManager via weak selfPlugin identity (with pluginName fallback) so AfterAgentCallback recovery from plugins registered after agentanalytics clears drained child failures while honoring inner sub-runner shadowing.
- Inspect the innermost platform.WithUUIDProvider context entry (stopping on nil shadow overrides without invoking the provider) so valid non-UUIDv4 session.NewEvent IDs satisfy creation-timestamp provenance while empty event IDs still fail closed.
- Add real-runner and unit regressions for both fixes.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed both findings from review 5820050911 in fast-forward commit 1dc07e5f4b8d2f05b44cc8379990d6b2f3b893cd:

  1. Later-plugin AfterAgentCallback recovery window (bigquery_agent_analytics_plugin.go, trace_manager.go):

    • newBigQueryAgentAnalyticsPlugin records weak.Make(adkPlugin) on traces.selfPlugin (avoiding strong reference cycles) and runningAgentChildren computes hasAfterAgentCallbacks from agentHasAfterAgentCallbacks(a) || contextHasLaterAfterAgentPlugin(ctx, selfPlugin).
    • contextHasLaterAfterAgentPlugin walks the context chain innermost-first so sub-runner PluginManager overrides (including typed-nil resets) shadow outer managers without leaking outer plugin state, checking plugins registered after this analytics instance for a non-nil AfterAgentCallback.
    • Regression coverage: TestLaterPluginAfterAgentRecovery_Runner (/laterPlugin_false, /laterPlugin_true, and sub-runner shadowing control) and TestContextHasLaterAfterAgentPlugin.
  2. Custom platform.WithUUIDProvider event provenance (bigquery_agent_analytics_plugin.go, trace_manager.go):

    • Replaced the raw hasNewEventUUID(ev.ID) call in onEvent with hasEventCreationProvenance(ctx, ev.ID) (id != "" && (hasNewEventUUID(id) || contextHasCustomUUIDProvider(ctx))).
    • contextHasCustomUUIDProvider inspects the innermost platform uuidProviderKey on ctx without invoking the provider function (preserving stateful sequential providers and honoring WithUUIDProvider(childCtx, nil) overrides), while rejecting empty IDs and keeping the retirement-window and post-failure causal ordering guards intact.
    • Regression coverage: TestCustomUUIDProviderRecovery_Runner (post-failure custom-ID recovery, provider call-count invariance, WithUUIDProvider(childCtx, nil) override, and zero-timestamp buffered clean runs) and TestContextHasCustomUUIDProviderAndProvenance.

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.

…ovenance

Propagate session.NewEvent action-map and activation-scoped platform.WithUUIDProvider provenance so child-scoped and event-scoped recovery events clear drained failures without extra provider invocations while bare struct literals lacking UUIDv4 IDs, active providers, and initialized action maps fail closed.

Support same-tick evCreatedAt.Equal(causeTime) recovery under a constant platform.WithTimeProvider for AfterAgentCallback content via pinned afterAgentStateDelta identity (afterAgentStateDeltaPtr paired with afterAgentStateDeltaRef cleared on match, compaction, and invocation end, without bypassing open or later-activation disambiguation) and retiredAtSeq > causeSeq, while keeping non-callback same-tick ties fail-closed so held pre-failure progress cannot clear a drained failure and non-callback recovery events require a monotonically advancing clock.

Document the exact provenance rules and fixed-clock vs advancing-clock recovery contract on Config and plugin constructors with regression tests, pin compacted hull time-union bounds across startPlatformTime, retiredAtPlatformTime, and parentRetiredAtPlatformTime, and clarify appendChunkWithRotationBudget confirmed row cardinality.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed all 5 items from review 5821233942 in fast-forward commit 6b3a5ed25fb5ce9deebe5227d8601aa20563e718:

  1. P1 — Child-scoped and event-scoped platform.WithUUIDProvider provenance (bigquery_agent_analytics_plugin.go, trace_manager.go):

    • Recorded customUUIDProvider on agentSpanInfo at pushAgentSpan and propagated it onto retiredActivation at popAgentSpan, so hasEventCreationProvenance / hasActivationUUIDProvenanceLocked recognizes custom non-empty event IDs when platform.WithUUIDProvider was installed on a child invocation context rather than the outer runner context.
    • Added hasNewEventActions(ev) (checking non-empty ev.ID plus non-nil ev.Actions.StateDelta and ev.Actions.ArtifactDelta, both initialized by session.NewEvent), so recovery events constructed with session.NewEvent(platform.WithUUIDProvider(ctx, ...), ...) on an event-scoped context retain provenance without invoking the provider, while zero-timestamp or struct-literal &session.Event{} events stay fail-closed.
    • Added real-runner coverage in TestCustomUUIDProviderRecovery_Runner (child-scoped_WithUUIDProvider_recovers_via_AfterAgentCallback, child-scoped_WithUUIDProvider_recovers_via_session.NewEvent, event-scoped_WithUUIDProvider_recovers_via_session.NewEvent, and zero-timestamp / struct-literal negative controls).
  2. P2 — Fixed platform.WithTimeProvider recovery vs. same-tick stale progress (trace_manager.go, bigquery_agent_analytics_plugin.go):

    • Added monotonic traceManager.lastSeq (causeSeq / failureSeq on failure causes and retiredAtSeq on retiredActivation), plus afterAgentStateDeltaPtr and a live reference keep-alive (afterAgentStateDeltaRef, cleared on match, compaction, deletion, or endInvocation so GC cannot recycle the map address while the invocation is active) linking a retired activation to the session.Event synthesized by runAfterAgentCallbacks.
    • Under a fixed TimeProvider, retired AfterAgentCallback recovery events matched by afterAgentStateDeltaPtr with retiredAtSeq > causeSeq clear the drained cause on the same tick (provided no later open/retired activation is ambiguous), whereas live non-callback same-tick events require evCreatedAt.After(causeTime) and fail closed on same-tick ties so buffered pre-failure progress cannot clear a same-tick failure.
    • Added real-runner regressions in TestFixedTimeProviderRecovery_Runner and TestAfterAgentStateDeltaGCReuse_Runner.
  3. P2 — Document session.NewEvent provenance and advancing TimeProvider requirements (config.go, bigquery_agent_analytics_plugin.go):

    • Documented on Config and all plugin constructors (NewPlugin, NewBigQueryAgentAnalyticsPlugin, NewPluginWithOptions) that recovery events clearing a drained child failure must carry session.NewEvent creation provenance (default UUIDv4 Event.ID, platform.WithUUIDProvider on the invocation/agent context, or the Actions.StateDelta and Actions.ArtifactDelta maps initialized by session.NewEvent; AfterAgentCallback content qualifies automatically) and that live non-callback recovery requires an advancing TimeProvider (ev.Timestamp > failure timestamp).
  4. P2 — Pin pruneSettledRetiredActivationsLocked compacted-hull time-union merge (trace_manager_test.go):

    • Extended TestCausalRecoveryOrderingAndProvenanceGuards (compacted_middle_hull_preserves_later_middle_window_t0+30ms_and_min-start_t0+12ms) to probe both t0+30ms (upper-bound union across middle activations) and t0+12ms (min-start union across middle activations), failing if the hull merge lines in pruneSettledRetiredActivationsLocked are removed.
  5. NIT — appendChunkWithRotationBudget doc comment (batch_processor.go):

    • Updated the appendChunkWithRotationBudget comment to state that the returned integer is the cardinality of rows settled prior to the terminal error (which may be a non-prefix subset after RowErrors isolation) and directed callers needing per-row identity to appendChunkRows.

caohy1988

This comment was marked as outdated.

…vent provenance

Track ancestor span chains, joined-at-retire status, and parent-recovery settlement on retired activations so both cleanly exited subtrees and failed branches drained and recovered by an enclosing agent settle cleanly. Subsequent sequential iterations—including across clean-then-recovered sequences, open-parent live recovery, differing errgroup goroutines, and coarse advancing clocks where start and NewEvent share a tick past prior retirement—then exclude settled or joined-responded predecessors without absorbing onto the parallel parent, while unrecovered failures (preserving the earliest unrecovered iteration cause) and delayed buffered branch events remain fail-closed.

Let a retired activation own an event created in a tick after the one in which it retired only when the event carries the StateDelta of that activation's after-agent callbacks, the only events ADK creates for it once its run returned. A zero-timestamp event that an ancestor held from a clean earlier run, and that the runner stamped on delivery, then no longer clears a later unrecovered failure when the agent or a later plugin defines an AfterAgentCallback, on advancing and coarse clocks alike. Also settle retired activations when clearRetiredCauseForEventWithStateLocked clears retired causes on a retiring activation, and drop the same-tick exclusion's retirement-order conjunct, which the ownership check already implies.

Guard AfterAgentCallback StateDelta keep-alive capture in popAgentSpan to activations that are unresponded or active swallowers, and preserve callback StateDelta references across intermediate parent retirement whenever a surviving swallower or unresponded guarded entry still needs fixed-clock delivery, while clearing refs on compacted middle hulls and retired non-swallowers to keep bounds O(1) across differing goroutine IDs.

Drop Actions-map heuristics from hasEventCreationProvenance so bare zero-timestamp struct literals with initialized StateDelta and ArtifactDelta maps fail closed under runner fallback stamping; pass activation-aware event-ID checks in selectResponseOwnerWithIDLocked so child-scoped platform.WithUUIDProvider model errors preserve unforwardedModelEvents; omit taskMode from joinedAtRetire; hoist agentIdentityKey and document Config constant-clock repeated-iteration semantics and retiredActivation fields.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed all 7 findings from Review 5837710477 (2 P1, 3 P2, 2 NIT) in commit 97404825fd7fd249e9aef67c944dd602a3639d65:

  1. P1 — A recovered failed branch blocks a later recovered iteration (trace_manager.go, bigquery_agent_analytics_plugin_test.go, trace_manager_test.go):

    • Fix: Added ancestorSpanIDs, joinedAtRetire: rec.completed || rec.runDone (excluding taskMode so unjoined finish_task retirements do not waive goroutine proof), and settledByParent (markSettledRetiredActivationsLocked) on retiredActivation. Both cleanly exited activations (retireAgentAtLocked when !hasFailedInSubtree && !spanHasSurvivingFailure, with includeSelf=true) and failed parallel branches whose failure cause was recovered by an enclosing agent (completeResponseWithEvent and clearRetiredCauseForEventWithStateLocked) mark their joined, non-failing retired subtree activations as settled (stopping at any intermediate ancestor between parentSpanID and the entry that is still open or holds a surviving failure).
    • In excludedByEventTimestamp, settled activations (ra.joinedAtRetire && ra.settledByParent, waiving ra.unrespondedAtPop) and joined responded activations (ra.joinedAtRetire && !ra.unrespondedAtPop) are excluded for events created strictly after laterStartPlatformTime (or on coarse/quantized advancing clocks where evCreatedAt >= laterStartPlatformTime and !ra.canOwnEventCreatedAt(evCreatedAt, hasEventID)), across differing parallelagent errgroup goroutines.
    • In clearRetiredCauseForEventWithStateLocked, post-retirement ownership (evCreatedAt.After(r.retiredAtPlatformTime)) requires !r.compactedHull && evStateDeltaPtr != 0 && evStateDeltaPtr == r.afterAgentStateDeltaPtr (applied across candidate selection, the later exclusion loop, and targetIdx validation) so a zero-timestamp UUIDv4 literal buffered by an open ancestor from a clean earlier iteration cannot clear a later unrecovered failure even when the agent or a later plugin registers AfterAgentCallback.
    • Proving tests: TestSequentialRecoveredParallelIterations_Runner (AfterAgentCallback recovery across 2 iterations, live session.NewEvent recovery across 2 iterations, clean first iteration followed by AfterAgentCallback / live recovery with and without callbacks, open-parent live recovery, quantized advancing clock sequential live recovery, outer AfterAgentCallback recovery followed by inner live session.NewEvent recovery, outer live session.NewEvent recovery followed by inner live session.NewEvent recovery, plus distinct-error negative control unrecovered first iteration negative control verifying iteration 1's cause survives), TestZeroTimestampBufferedCleanRun_Runner (including unresponded and responded first runs with inner AfterAgentCallback and later AfterAgentCallback plugin), and TestCausalRecoveryOrderingAndProvenanceGuards/markSettledRetiredActivationsLocked_failure_and_ancestor_guards.
  2. P1 — Initialized Actions maps treated as creation provenance (bigquery_agent_analytics_plugin.go, bigquery_agent_analytics_plugin_test.go, trace_manager_test.go):

    • Fix: Removed hasNewEventActions from hasEventCreationProvenance(ctx, ev). Provenance now requires a non-empty ev.ID that either satisfies hasNewEventUUID(ev.ID) (canonical RFC 4122 UUIDv4) or runs under an active custom platform.WithUUIDProvider on the delivery context, an open activation context on agentStack, or a matching retired activation's customUUIDProvider.
    • Disclosure of module-boundary & baseline trade-offs:
      • Bare zero-timestamp session.Event struct literals without an RFC 4122 UUIDv4 ID under the default provider—including literals with initialized Actions: EventActions{StateDelta: map[string]any{}, ArtifactDelta: map[string]int64{}}—now fail closed under runner fallback timestamping.
      • Single-activation zero-timestamp struct literals that manually populate a valid RFC 4122 UUIDv4 ID or run under an invocation/agent-scoped custom platform.WithUUIDProvider remain indistinguishable from session.NewEvent at the plugin/agentanalytics module boundary (and for multi-activation buffered replays, post-retirement AfterAgentCallback StateDelta pointer matching now keeps them fail-closed across later unrecovered iterations).
    • Proving tests: TestBufferedPreFailureContent_Runner/buffered_zero-timestamp_struct_literal_with_non-nil_StateDelta_and_ArtifactDelta_maps_fails_closed, TestNestedRetiredRecovery_Runner/buffered_zero-timestamp_struct_literal_with_non-nil_StateDelta_and_ArtifactDelta_maps_from_retired_parent_fails_closed, and TestContextHasCustomUUIDProviderAndProvenance.
  3. P2 — Fixed-clock non-callback recovery & constant-clock repeated-iteration boundary (config.go, trace_manager.go, bigquery_agent_analytics_plugin_test.go):

    • Fix: Documented on [Config] that under a constant platform.WithTimeProvider, only single-activation AfterAgentCallback content recovery (disambiguated via the activation's AfterAgentCallback StateDelta map identity) succeeds on the same tick; non-callback recovery and repeated sequential activations under an open custom ancestor require advancing clocks (evCreatedAt > failurePlatformTime). Also preserved afterAgentStateDeltaRef/afterAgentStateDeltaPtr across intermediate parent retirement whenever a surviving swallower or unresponded guarded entry still needs fixed-clock buffered delivery (isActiveSwallowerLocked).
    • Proving tests: TestFixedTimeProviderRecovery_Runner (AfterAgentCallback_recovers_under_fixed_clock, nested_buffered_AfterAgentCallback_recovery_across_retired_parent_under_fixed_clock/buffer_inner, /buffer_all, live_session.NewEvent_fails_closed_under_fixed_clock, and repeated_sequential_recovered_iterations_fail_closed_under_constant_clock).
  4. P2 — Retained entry and context growth across clean parallel iterations (trace_manager.go, bigquery_agent_analytics_plugin_test.go, trace_manager_test.go):

    • Fix: Removed goroutineID from compactKey in pruneSettledRetiredActivationsLocked (and cleared goroutineID on compacted middle hulls) so clean parallel iterations across differing errgroup worker goroutines compact to <= 3 entries per (agentName, branch, guardedBySpanID) key (O(1)), gated afterAgentStateDeltaRef capture in popAgentSpan to activations that are unresponded or active swallowers (rec.unresponded || tm.isActiveSwallowerLocked(inv, rec.spanID)), and cleared afterAgentStateDeltaRef/afterAgentStateDeltaPtr on compacted middle hulls and retired non-swallowers.
    • Proving tests: TestCleanParallelIterationsBoundRetiredActivations_Runner (without_child_AfterAgentCallback, with_child_AfterAgentCallback, and direct_clean_child_with_AfterAgentCallback) and TestCausalRecoveryOrderingAndProvenanceGuards/pruneSettledRetiredActivationsLocked_compacts_differing_goroutineIDs_into_hull.
  5. P2 — Event-scoped platform.WithUUIDProvider with stripped Actions (config.go, trace_manager.go, bigquery_agent_analytics_plugin_test.go, trace_manager_test.go):

    • Fix & Disclosure: Because plugin/agentanalytics/go.mod pins google.golang.org/adk/v2 v2.0.0 and session.Event carries no provider provenance field across that module boundary, removing the mutable hasNewEventActions heuristic means call-site-only platform.WithUUIDProvider overrides passed exclusively to session.NewEvent(platform.WithUUIDProvider(...), ...) (absent from the invocation or agent context.Context) now fail closed even when Actions maps are intact. Updated [Config] documentation and the PR description to state that custom UUID providers must be installed on the invocation or agent context.Context, and updated selectResponseOwnerWithIDLocked to pass activation-aware hasIDFor(base) so child-scoped platform.WithUUIDProvider model errors preserve unforwardedModelEvents.
    • Proving tests: TestCustomUUIDProviderRecovery_Runner (invocation-scoped, agent-scoped_via_BeforeAgentCallback, nested_agent-scoped_on_retired_custom_parent, and call-site-only_WithUUIDProvider_passed_only_to_session.NewEvent_fails_closed) and TestCausalRecoveryOrderingAndProvenanceGuards/selectResponseOwnerWithIDLocked_child-scoped_UUIDProvider_with_model_error_preserves_unforwardedModelEvents.
  6. NIT — Duplicate recovery paragraph across constructors (bigquery_agent_analytics_plugin.go, config.go):

    • Fix: Consolidated the recovery and provenance contract onto [Config] and pointed NewBigQueryAgentAnalyticsPlugin, NewBigQueryAgentAnalyticsPluginWithSignal, and NewPlugin to [Config].
  7. NIT — agentIdentityKey and retiredActivation field documentation (trace_manager.go):

    • Fix: Hoisted agentIdentityKey to package level and documented ancestorSpanIDs, joinedAtRetire, and settledByParent on retiredActivation.

caohy1988

This comment was marked as outdated.

…nts and date late drained retirements

An event that ADK builds from an AfterAgentCallback's content after this plugin retired the activation was recognized only by the StateDelta map of the callback context. An earlier plugin's OnEventCallback that replaced that public map with an identical copy therefore turned a successful recovery into INVOCATION_ERROR. ADK copies the callback context's EventActions into that one event, which shares both its StateDelta and its ArtifactDelta map, so the event now counts as the retired activation's after-agent event when it carries either map, for post-retirement ownership and for the same-tick tie-break alike. The EventActions that holds both maps stays referenced, rather than the callback context, so neither address can be reused while it is compared and a retired record keeps nothing else of the run, in the late state of a completed run too. An event whose two maps were both replaced still fails closed, as Config states.

The maps are recorded for every activation with after-agent callbacks, as popAgentSpan retires it and before anything prunes the entries of its agent, and kept until its after-agent event arrives or nothing could take that event for another activation's (needsAfterAgentActionsLocked). Before, they were recorded only when the event might recover a failure, so a clean activation's summary was taken for another activation of the same agent: one that started while ADK ran the callbacks and then failed, or one whose run the summary's timestamp fell in when a custom ancestor held the summary. The summary then cleared that activation's unrecovered failure: INVOCATION_COMPLETED instead of INVOCATION_ERROR. The same happened when an intermediate parent retired under an open custom ancestor that still held the summary, which dropped the maps of a child that had responded, and when compaction folded more than three such entries into a hull without maps. An activation that yielded progress before it drained a sub-agent's failure is covered too: its maps stay while a span under it is still open, since that span's failure moves up with it among its swallowers once it retires. And because popAgentSpan set the retirement's credit, peer flag and maps only after retireAgentAtLocked had pruned, the entry of an activation without an open custom ancestor, such as the agent of a workflow node, was deleted first: its after-agent event with content then cleared another activation's failure, and one that only changed state found no entry and left the activation's credit (unrespondedRetired) outstanding, which keeps an open peer of the same agent from taking its own model and tool events. popAgentSpan now hands all three to the entry as it is recorded, which TestGuardlessRetirementKeepsAfterAgentEntry checks through popAgentSpan under a parent that forwards errors, as a workflow agent does for the agent of a node.

The callbacks are known to have returned once another agent starts or ends on the goroutine that retired the activation, outside them, or once the run of its parent returned, after which any after-agent event of it that can still be delivered was created. The maps then go unless an open activation of the agent, a swallower of a recorded cause, an open span under the activation or another one of the agent, or an outstanding credit still needs them; that the activation retired without a response keeps nothing by itself. Entries that keep maps, a credit or an open span under them are not compacted. Where nothing shows that the callbacks returned, as for the activations that a parent runs on goroutines that it does not wait for, at most eight such entries stay per parent, agent and branch, and the oldest fold into a hull that stands for their after-agent events (foldPendingAfterAgentLocked): an event that one of them can have created clears no failure until the parent's run returns. Config states this boundary, and that nothing is folded that way while a peer of those activations is open (see below).

A custom ancestor that held every event of two recovered root -> inner -> parallel -> child iterations and replayed them in order made the run report AGENT_ERROR and INVOCATION_ERROR. Open-peer response selection now skips peers that started after the event was created, the window that retired-cause clearing already applies to open activations, so the first child's event no longer goes to the second child. And an activation that an enclosing retirement left open after its run was known to be over now records that point. When a buffered event later retires it as a drained descendant, its retirement is dated there, not at that late point, after the next activation of the same agent started, so it no longer looks like a peer that could have created the later activation's events.

When completeResponse absorbs an event because a retired activation of its author created it while another activation of the same agent is open, settle that retired activation (retiring its drained descendants and clearing the causes it swallowed with the event's action maps).

An event that holds an action map of one retired activation's after-agent callback context is now that activation's alone, if it can own the event, and no one's otherwise (afterAgentSharerLocked). eventAuthorLocked no longer lets a concurrent activation of the same agent that retired later, and whose run the event's timestamp falls in, make the event authorless, and selectResponseOwnerWithIDLocked absorbs and settles such an event before any open peer that awaits a model, tool or partial event can claim it. An event that two retired activations claim still has no author. Such an event settles the unrespondedRetired credit that its own activation left when it retired unresponded while a peer was open, and nothing else: it took a tool credit instead when its content held a function response, and could take a credit that another activation left. It settles that credit, and is placed as that activation's after-agent event, only when the activation can own it, with creation provenance and a timestamp at which it can have created it (ownsAfterAgentEvent), as for an after-agent event without content; an event that carries the map but whose ID or Timestamp an earlier plugin rewrote settles nothing.

Once a concurrent activation of an agent retired, retiredPeerCount made every later event of an open activation of the same agent that held a failure be absorbed, so the recovery that a custom agent yields after it drained a sub-agent's failure never cleared that failure once a peer had finished. An event that only one open activation, awaiting no model or tool event, can have created, and that no retired activation of the agent can have created, is now that activation's (soleOpenAuthorLocked). A retired activation can have created an event created after it retired only while its after-agent event may still come: it has after-agent callbacks, that event was not delivered yet (afterAgentEventSeen), and its callbacks were not seen to return before the event was created (afterAgentDoneAt). A peer retirement whose entry was pruned or compacted, a swallower of a recorded cause, or an event created while the peer ran keeps the event unproven and the failure reported.

When a custom agent runs the same agent on goroutines of its own, an agent that starts on a goroutine now runs under the open lookalike that runs on that goroutine, or, when none does, the one whose goroutine started it (runningLookalikeLocked), not under the one that started last. Before, the parallel agent of the first of two concurrent activations of a custom agent was placed under the second, so a failure that the first swallowed was recorded as the second's, and the second's recovery cleared it. And when one activation ran on that goroutine and a newer one on the goroutine that started it, the newer one was taken.

A retiring activation now takes back only a response that completeResponse routed to an open peer of the same agent as its own (ownResponse), not one the peer inherited from an event of an activation under it. Taking an inherited response retired the activation as responded, so its after-agent action maps went unrecorded, and its recovery event was then attributed to the peer and could clear a failure that the peer swallowed.

A finish_task retirement whose run had not synchronized may still create events after it retired, so canOwnEventCreatedAt no longer bounds its events by its retirement, and hasGuardedRetiredPeerForEventLocked skips retired activations that cannot have created an event at its creation time. Config states that an event that one of two concurrent activations of one agent on the same branch and node path created while the other ran, and that an open custom ancestor delivers only after the other retired, records no response, so the failure of the activation that created it stays reported, and when a later event of the open activation counts as its own.

Drop the hull's joinedAtRetire and settledByParent conjunctions, which the compaction key already makes uniform within a bucket, and pin the settlement and hull conditions with unit cases that each condition decides alone. The reflection that reads the callback context's action maps keeps a tripwire test against a real run, now for both maps and for what keeps them reachable. Config also explains why non-callback recovery under a constant clock still fails closed.

An event is no longer attributed to an activation of its author on a sibling branch. findAgent fell back to any open activation with the author's name, so when one custom agent ran under two branches of a parallel agent and the first branch's activation retired before its after-agent event, or a run event that its parent held, arrived, that event went to the second branch's open activation and cleared a failure that this activation had swallowed and never recovered from: INVOCATION_COMPLETED instead of INVOCATION_ERROR. A non-empty branch now matches only activations on that branch or on a branch under it, which the workflow scheduler's stamping of an enclosing branch on events that left Branch empty needs. An event without a branch, as session.NewEvent leaves it, still matches an activation on any branch, and an event with one an activation on that branch or under it, but only when the activations of its author on a single one of those branches can have created it (resolveEventBranchLocked); otherwise it clears no failure and settles no credit. Row placement and stream tracking follow the same rule.

An event created before every open activation of its author, branch and node path started is none of theirs. With a single open activation, selectResponseOwnerWithIDLocked gave it that activation, which took the activation's pending model or tool event and placed the earlier activation's row under the later one. Such an event is now absorbed and settled as a retired activation's, settling a credit that such an activation left, and its rows go under the latest open activation that had started by then, if any. An event created on the tick on which the activation started, as under a constant clock, is still the activation's.

runningLookalikeLocked cannot tell which of several open activations of one custom agent started a sub-agent on a goroutine that a helper goroutine of one of them started, because the runtime names only the helper as the creator. It placed the sub-agent under the activation that started last, whose later response then cleared a failure that another activation had swallowed and never recovered from. Such a sub-agent now runs under the nearest open span that encloses all of them, so only that span or the agents above it can recover its failure. Config states this boundary.

The event that ADK builds when after-agent callbacks return no content but change state or artifacts now counts as the retired activation's delivered after-agent event when it carries either action map (clearLastPartialForEvent), so a peer whose callbacks only set state no longer keeps an open peer's later recovery from counting. The event recovers nothing itself, and with both maps replaced by an earlier plugin it still changes nothing.

completeResponse resolved the branch of an event without one, or with an enclosing branch that the workflow scheduler stamped, only for an open activation of its author. When a custom ancestor delivered a retired activation's recovery later, the event kept its own branch, so it neither retired the drained descendants nor cleared the failure that the activation swallowed on its branch, and a recovered run reported INVOCATION_ERROR; an event that completeResponse absorbed for a retired author while a later activation was open was settled with that stale branch too. The branch now resolves from the activations that can have created the event for a retired author too (resolveEventBranchLocked).

A retired activation that left a credit and created both an event in its run and an after-agent event settled two credits, so an open llmagent peer later took another retired activation's held response as its awaited model event. An event of a retired activation's run now settles that activation's own credit when only it can have created the event (settleRetiredResponseCreditLocked), and the activation's other events settle none.

The rows of an event that completeResponse takes for a retired activation's after-agent event now go under the invocation span, as for other events of a retired author, rather than under an overlapping open activation of the same agent that started earlier. Config also lists RowErrors after an attempt with an unknown outcome among the responses that drop the batch and replace the stream before the next one.

A retired activation whose after-agent callbacks were seen to return can own no event created after that point (afterAgentDoneAt, canOwnEventCreatedAt). ADK builds the after-agent event on the goroutine that ran the callbacks before that goroutine starts or ends another agent, and before the run of the parent returns, which is how the plugin sees that the callbacks returned. Before, such an activation stayed a possible author of every later event of its agent until its after-agent event was recognized. When a custom agent ran two activations of an agent one after the other on its goroutine, the first one retired without a response, and the custom agent held the first one's after-agent event until the second one was open, the first one's maps were already gone, so the held event was not recognized, and the second one's recovery from a failure that it swallowed was absorbed: INVOCATION_ERROR. This happened whether the held event had content or only changed state, and also when the callbacks built no event at all, so keeping the maps until a custom ancestor delivers the event would not have fixed it, and would have kept them for every such activation for as long as the custom ancestor runs. An event that carries the activation's after-agent maps is still its own whenever it was created, as when the callbacks ran an agent on another goroutine and waited for it. A hull keeps the latest such point of its members, and none when a member has none. Config states this.

Every session event now has the branch of the activations that can have created it resolved before anything else, whether its author has an open activation or not (resolveEventBranchLocked). findAgent prefers an activation on the event's own branch, which is right for the callbacks of an activation but not for a session event: session.NewEvent leaves Branch empty, and the workflow scheduler stamps its node run's branch on an event that left Branch empty, so an event can be that of an activation on its branch or on any branch under it, and nothing tells the two apart, not even an activation on par that sets Branch to par itself. So when one activation of an agent ran on the root branch or on par, and another one on a branch under it, an event without a branch, or with par's branch, that the latter created went to the former and cleared a failure that the former swallowed: INVOCATION_COMPLETED instead of INVOCATION_ERROR, whether both were open or both had retired. Such an event is now no one's, as Config states. And when only a retired activation on one branch could have created an event while a later activation of the same agent ran on another branch, the event was no one's and the retired activation's recovery was lost: INVOCATION_ERROR. It now settles the retired activation on its branch.

Entries that counted as a peer retirement are no longer compacted while a peer of theirs is open, as they were already not deleted then. Once four or more peers of an open activation had retired, compaction replaced the middle ones with a hull, so soleOpenAuthorLocked found fewer entries than retiredPeerCount counts and the open activation's recovery never counted. A credit, and a settled one, is only ever left by a peer retirement, so their entries stay as well.

An after-agent event of an activation on a branch was dropped as no one's whenever an activation of the same agent ran, or had retired and could still create events, on a branch under it: resolveEventBranchLocked counted both branches before anything looked at the event's action maps. So when an activation of an agent on the root branch, or on outer.wa, drained a failure and its AfterAgentCallback recovered while another activation of the agent was open on par.wb, or on outer.wa.par.wb, the recovery was lost: INVOCATION_ERROR. And an activation that had retired unresponded while a peer ran kept the credit that it left (unrespondedRetired) and stayed a possible author of later events, so the peer's awaited model event, or its recovery, was later absorbed against that credit. An event that carries an action map of exactly one retired activation on the branches that the event's branch covers now resolves to that activation's branch first (afterAgentSharerWithinLocked), and is then that activation's after-agent event if it can own it; an event without such a map, or with both maps replaced, stays no one's. clearLastPartialForEvent finds that activation on those branches too.

foldPendingAfterAgentLocked folded entries into a hull that stands for after-agent events that may still come without looking at whether a peer of theirs was open. With an AfterAgentCallback on the agent, more than eight short activations that retired one after another while a long one was open had their oldest entries folded into such a hull without their peer marks, so soleOpenAuthorLocked found fewer entries than retiredPeerCount counts and the long activation's recovery was absorbed: INVOCATION_ERROR. While a peer is open (hasOpenPeerLocked, which pruning now shares), neither a peer retirement nor an entry whose callbacks were seen to return is folded: the latter keeps its maps then because the open peer could be taken for the author of its after-agent event, not because that event may still come. Once no peer is open, they fold or compact as before.

An agent that an AfterAgentCallback runs on the goroutine that runs the callbacks starts and ends while they run, but its start or end counted as their return: it recorded that the retired activation's callbacks had returned and dropped its maps. When another activation of the same agent then started and failed before the callbacks returned their summary, the summary was taken for the other activation's event and cleared its failure: INVOCATION_COMPLETED instead of INVOCATION_ERROR. The callback context does not show such a run, since a callback cannot run an agent with it (its WithContext returns nil) and runs one with a context from elsewhere, such as its own activation's. But ADK runs an activation's after-agent callbacks inside agent.runAfterAgentCallbacks on that goroutine, so when an agent starts or ends there, the plugin now counts those frames in the goroutine's stack trace (afterAgentCallbackRunsOfTrace) and does not record the activations whose callbacks still run: every start or end on the goroutine records every other activation retired there, so those are the ones that retired first among the ones not recorded yet (markAfterAgentCallbacksReturnedOnLocked).

pushAgentSpan dropped the maps of the activations whose callbacks it saw return before the starting agent was on agentStack, since an agent that starts later did not create an earlier event. On a coarse clock, though, the after-agent event can share the tick in which the next activation of the same agent starts, so when a custom agent held a clean activation's summary and started an llmagent of the same name on its goroutine in that tick, the summary took the llmagent's awaited model event and its rows went under the llmagent's span. The maps are now settled, and the entries pruned, only once the starting activation is open, so the retired activation keeps them while an activation of its agent runs.

completeResponseForEvent and clearLastPartialForEvent return whether they took the event for a retired activation's after-agent event, and onEvent keeps that report on its own stack and passes it to emitSessionEventSignals and eventSpanAt. Taking the event and placing its rows happen under two separate locks, and the invocation's callbacks can handle another event in between, so the report is not stored on the invocation, where that event could overwrite it and change where the first event's rows go.

Three tests that exist at the parent commit are adjusted for the attribution rules above: TestTraceManager_SameAgentConcurrentNodePaths created its session events before the activations that they belong to started and now creates them once the activations run; TestRetireDrainedDescendants_NestedRetiredCustomAncestors compared synthetic event times with a span started on the real clock and now dates that start before the events; and TestTraceManager_AgentNesting now expects an event on a sibling branch, or one without a branch while the author runs on two branches, under the invocation span. TestRetiredAuthorEventWhilePeerOpen, which this change adds, dates one span start the same way. Two more tests that exist at the parent commit change with the after-agent action maps. TestCleanParallelIterationsBoundRetiredActivations_Runner, which expected no entry to keep maps, now expects the latest child that root runs directly, whose callbacks nothing shows to have returned while root still runs, to keep its maps, with the bound on entries unchanged and none kept for par's children. TestCausalRecoveryOrderingAndProvenanceGuards records the action maps where it recorded the StateDelta address and adds a case in which an event with the callback's StateDelta and another ArtifactDelta clears the cause. Its case for an event that holds a retired activation's map while a later retired activation could own the event by its timestamp expected the failure to stay and now expects it cleared, because the map makes the event that activation's alone (afterAgentSharerLocked); the same event without the map still leaves the failure. Its compaction case expects the maps to go once nothing needs them and at the end of the invocation rather than by compaction. TestSequentialRecoveredParallelIterations_Runner only gains cases, and the tripwire tests TestCallbackAfterAgentStateDeltaPtr and TestAfterAgentStateDeltaGCReuse_Runner are now TestCallbackAfterAgentActionMaps and TestAfterAgentActionMapsGCReuse_Runner, for both maps.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All six findings are addressed in 16dfacdf65421303d0deb6ae77e8aaae85aca7e5, one commit on top of 97404825. Extending the tests for findings 1 and 2 to concurrent activations of inner, to agents that respond before they recover, and to one agent running under several branches, turned up further attribution problems, which the same commit fixes (sections 7 to 12).

1. P1: copying a recovery event's StateDelta map turned a recovery into INVOCATION_ERROR

The four variants from the review reproduced here: INVOCATION_ERROR in 4 of 4 at 97404825.

Why a replacement, not a removal. ADK builds the after-agent event only after this plugin's AfterAgentCallback has returned, from the callback context's EventActions (event.Actions = *actions). This plugin first sees the event in OnEventCallback, after the plugins registered before it. The event's ID and timestamp come from the invocation context's providers, which a plugin can neither observe nor tag. So the only link between the event and the callback is the two maps that ADK copies from the callback context. Dropping the check is still not an option. On main the runner stamps a held zero-timestamp event before OnEventCallback (stampTimestamp in runner/runner.go), so without the check a held UUIDv4 literal from an earlier run would count as the retired activation's recovery.

Fix. A post-retirement event now counts as the retired activation's after-agent event when it carries either the StateDelta or the ArtifactDelta map of the context in which that activation's after-agent callbacks ran (actionMaps.shares). ADK hands both maps to this one event and to no other. The plugin keeps the EventActions that holds both maps (callbackAfterAgentActions), not the callback context, so both maps stay reachable and neither address can be reused, while a retired record keeps nothing else of the run. An earlier plugin that swaps one map for a copy, as in your repro, no longer breaks recovery. An event whose two maps were both replaced still fails closed, and Config now says so. The same-tick callback tie-break uses the same check. An event that carries such a map of exactly one retired activation is that activation's alone if it can own the event, and no one's otherwise (afterAgentSharerLocked): an open activation has not run its after-agent callbacks yet, and another retired activation ran them with maps of its own. An event that two retired activations claim has no author. Section 7 covers the cases in which concurrent activations of inner made this matter.

Proving tests. TestAfterAgentRecoveryWithCopiedActionMaps_Runner sits next to the callback-recovery runner tests. It runs root -> inner -> parallel -> child with immediate and with buffered delivery, with and without earlier progress from inner, under the default clock and IDs. In each run an earlier plugin copies StateDelta or ArtifactDelta. Each run asserts that the caller gets exactly one recovery response and that the invocation ends with INVOCATION_COMPLETED. All eight runs pass 10/10 under -race -count=10 on a clean git archive 16dfacdf. A further case copies both maps and asserts INVOCATION_ERROR. TestAfterAgentRecoveryWhileConcurrentPeerOpen_Runner covers concurrent activations of inner under root where the first inner's AfterAgentCallback recovers (immediately or after a delay) while the second inner is still open on agentStack, plus the negative control where only the second inner's callback returns content. TestCausalRecoveryOrderingAndProvenanceGuards and TestRetiredAuthorEventWhilePeerOpen keep the post-retirement and open-peer assertions. An event with no maps, or with other maps, does not clear the cause. An event with a copied StateDelta and the callback's ArtifactDelta clears it, and so does the reverse. TestCallbackAfterAgentActionMaps also checks that what keeps the maps reachable is the EventActions value and not a context.

2. P1: replaying every buffered event of two recovered iterations reported a failure

The probe reproduced here: AGENT_ERROR and INVOCATION_ERROR at 97404825. Instrumenting it showed three pieces:

  1. Open-peer selection. Response-owner selection among open peers now skips peers that started after the event was created. clearRetiredCauseForEventWithStateLocked already uses this window for open activations. The first child's event no longer goes to the second child.
  2. Late retirement date. With only that change the probe still failed, as you saw. The cause was not a lost swallower chain, though. The first recovery retires the first child as a drained descendant, and that retirement was dated at that point, after the second child had started. The first child therefore looked like a peer that could have created the second child's event. That event was then absorbed, and the second child stayed unresponded. Now, when an enclosing retirement leaves an activation open after its run is known to be over, the plugin records that point (runEndSeq, runEndPlatformTime). The activation's later retirement is dated there, because its run created all its events by then.
  3. Settling a retired author when an open peer absorbs its event. When the first iteration's buffered events are flushed after the second iteration has already opened on agentStack (or while a concurrent peer is open), selectResponseOwnerWithIDLocked absorbs the retired activation's event onto the parent (retiredAuthor = true), and completeResponseWithEvent calls settleRetiredAuthorLocked with the event's evActions: retiring the drained descendants of that retired author (eventAuthorLocked) and clearing the causes it swallowed.

With these changes, the first child's cause carries inner's first activation as its swallower, and the first recovery clears it whether the buffered events are flushed after both iterations complete or while the second iteration is already open.

Proving tests. TestSequentialRecoveredParallelIterations_Runner covers both full_buffer_replayed_in_order_across_two_recovered_iterations_with_* and *_recovery_held_with_*_until_the_next_iteration_is_open_clears_the_failure across live session.NewEvent recovery and AfterAgentCallback recovery (holding either the first inner's events or every event of the first iteration until the second iteration yields its first event), along with the matching negative controls (full_buffer_replayed_in_order_keeps_an_unrecovered_first_iteration_failed_with_* and progress_before_the_failure_held_with_*_until_the_next_iteration_is_open_keeps_the_failure_with_*_callbacks). TestResponseOwnerCreationWindowAndRunEndRetirement and TestRetiredAuthorEventWhilePeerOpen pin each part separately, including that an activation whose run may still be going gets no run end and that only the drained descendants of the retired author retire when a peer is open. The stale same-tick, delayed-recovery, unrecovered-first-iteration and zero-timestamp controls pass unchanged.

One buffering shape stays fail-closed: holding only the child's event until after inner's recovery was delivered (checked at 16dfacdf, with and without earlier progress from inner). In that shape the child's event arrives after the recovery that would have settled it. Supporting it would mean letting a recovery that was already processed clear a descendant that retires later, which I left out.

3. P2: fixed-clock non-callback and repeated recovery

I kept the documented divergence, and Config now says why. The callback tie-break has creation-time evidence: the event carries the callback maps of an activation that retired after the failure was recorded. Under a constant clock a non-callback event has none. Its ID is random, its timestamp is the constant, and the only order the plugin sees is delivery order. A sequence number drawn at delivery comes after every recorded cause, so it would also clear the held pre-failure rows that TestFixedTimeProviderRecovery_Runner keeps failing closed (stale_progress/fixed_clock). Those rows are unchanged.

4. P2: call-site-only custom UUID providers

No change. A provider passed only to session.NewEvent(platform.WithUUIDProvider(ctx, p), invID) never reaches a context the plugin sees, and session.Event carries no provider provenance across the pinned google.golang.org/adk/v2 v2.0.0 boundary. Config still states the limitation and the supported ctx.WithContext(platform.WithUUIDProvider(ctx, p)) scope. TestCustomUUIDProviderRecovery_Runner keeps the fail-closed case, and action maps are not used as proof of construction.

5. NIT: reflection over the unexported actions field

The callback context still has no exported accessor, on main too: its Actions() logs "not supported for callback context" and returns nil. The reflection now reads both maps (callbackAfterAgentActionMaps). The tripwire test is renamed TestCallbackAfterAgentActionMaps. It runs a real after-agent callback and requires that both maps are found, that they equal the delivered event's maps, that the value kept to hold them is the callback's EventActions, and that nothing is logged. A renamed field fails it.

6. NIT: settlement and hull conjuncts

TestRetiredActivationSettlementAndHullConjuncts adds, for each condition, a pair of cases that differ only in that condition:

  • the surviving-swallower term
  • the ancestor-scope test
  • the active-swallower term in recordRetiredActivationsAtLocked
  • the hull's ancestor intersection, asserting the compacted hull's ancestorSpanIDs directly

The hull's joinedAtRetire/settledByParent && could not be pinned. Both fields are part of compactKey, so every member of a hull's bucket has the same values and the &&->|| mutant is equivalent. I removed those two no-op lines, so the hull keeps its first member's values, and pinned the invariant that makes this safe: entries that differ in either field never share a hull.

7. Concurrent activations of one custom agent

The runner tests for findings 1 and 2 run inner sequentially or next to a peer that emits nothing but content. With two activations of inner running at once under a custom root, or an open peer that is in a model call, a tool call or a stream, the attribution above was not enough. These are the cases and their fixes:

  • An open peer awaiting a model, tool or partial event could claim a retired activation's after-agent event. Response-owner selection matched such pending evidence before it looked at action maps, so the open peer took the recovery event, and the retired activation's failure stayed. selectResponseOwnerWithIDLocked now receives the event's action maps, and an event that carries a retired activation's after-agent map is absorbed and settled as that activation's before any open peer is considered.
  • A concurrent activation that retired later made the event authorless. When root delivered the first inner's after-agent event only after the second inner had also retired, the event's timestamp fell in the second activation's run, so both retired activations were candidates and nobody cleared the cause. The action map now decides on its own (afterAgentSharerLocked in eventAuthorLocked), with retiredCanOwn still required of the activation it names.
  • Sub-agents of concurrent runs were placed under the wrong run. parentFor picks the lookalike that started last, so the parallel agent of the first of two concurrent inner activations was placed under the second. A failure that the first inner swallowed was then recorded with the second as its swallower, and the second's recovery cleared it. An agent that starts on a goroutine now runs under the open lookalike that runs on that goroutine, or, when none does, the one whose goroutine started it (runningLookalikeLocked in parentForRunLocked). Goroutine IDs are never reused within a process. Section 9 covers a sub-agent that a helper goroutine starts, which neither identifies.
  • A retiring activation could take a response that its peer inherited. When one inner retired unresponded while the other was open, reconcileConcurrentResponseOnPopLocked moved the open peer's hasResponse to the retiring activation even when the peer had only inherited it from its own child's event. The retiring activation then counted as responded, so its after-agent action maps were not recorded, and its recovery event was attributed to the peer by timestamp, which cleared a failure that the peer had swallowed and nobody recovered. Only a response that completeResponse routed to the peer as its own (ownResponse) moves now, which is what the function's documentation already said it did.
  • An unjoined finish_task retirement may still create events. Its run had not synchronized when it retired, so canOwnEventCreatedAt no longer bounds its events by its retirement (unjoinedTaskRetirement). And hasGuardedRetiredPeerForEventLocked now skips retired activations that cannot have created the event at its creation time, which a buffering ancestor preserves when it replays events.

One shape stays fail-closed, and Config now says so: concurrent activations of one agent on the same branch and node path are told apart only by when their events were created. An event that one of them created while the other ran, and that an open custom ancestor delivers only after the other retired, could be either's and records no response, so the failure of the activation that created it stays reported even when a custom ancestor recovers from it. Delivering such an event before either activation ends avoids this.

Proving tests.

  • TestAfterAgentRecoveryWithOpenPeerAwaitingEvent_Runner holds the first inner's after-agent recovery while a second inner awaits a model event (sequential, with and without earlier progress, and concurrent), streams a partial event, or awaits a tool event with a function-response recovery. Each asserts INVOCATION_COMPLETED. Two negative controls without recovery keep the failure.
  • TestAfterAgentRecoveryAfterConcurrentPeerRetired_Runner runs two concurrent activations of inner (and the shape where the second starts after the first was popped but before its AfterAgentCallback ran), with root delivering the recovery only after both retired:
    • The recovery completes the run in both delivery orders, with and without earlier progress.
    • With both action maps copied, the run fails closed.
    • When both activations drain a failure of their own and only one recovers, the run reports the other one's failure (child-1 failure) and no row for the recovered one.
    • When the recovering run's child creates its event while the other child runs and root holds that event until both inner activations retired, the recovered failure stays reported, as Config states.
  • TestReconcileConcurrentResponseOnPopKeepsInheritedPeerResponse pins the reclaim rule in both directions: an inherited peer response stays with the peer, and an own peer response still moves.
  • New cases in TestCausalRecoveryOrderingAndProvenanceGuards and TestRetiredAuthorEventWhilePeerOpen pin the action-map attribution: the event stays its activation's although a later retired or concurrent activation could own it by timestamp; a compacted hull's map, another agent's map, or a sharer that cannot own the event takes nothing; two claimants settle nothing; a recovery clears only the causes that its own activation swallowed; and an after-agent event absorbs from every kind of open peer.

8. Agents that respond before they recover, and open peers after a peer finished

Four more cases came up while extending these tests:

  • An agent that yielded progress before it drained a failure. The action maps were recorded only for an activation that retired unresponded or that had swallowed a cause that was still recorded. When inner yields progress, then drains a parallel child's failure, and root holds the child's event and inner's after-agent recovery and delivers them in the order in which they were created, the child is still open when inner retires, so neither held, and the recovery was reported as INVOCATION_ERROR. The maps are now also recorded, and kept across the retirement of an enclosing activation, while a span under the activation is open (afterAgentState, needsAfterAgentActionsLocked): once that span retires, its failure moves up with the activation among its swallowers. Section 10 extends the recording to every activation with after-agent callbacks.
  • An open custom peer's recovery after its peer finished. Once one activation of inner retired while another was open, retiredPeerCount made every later event of the open one that held a failure be absorbed. So when the second inner drained its child's failure and yielded its own recovery after the first had finished cleanly, the failure stayed. An event that only one open activation can have created, while it awaits no model or tool event, and that no retired activation of the agent can have created, is now that open activation's (soleOpenAuthorLocked). A retired activation can have created an event created after it retired only while its after-agent event may still come: it has after-agent callbacks and that event was not delivered yet (afterAgentEventSeen; section 9 extends this to an after-agent event without content, and section 11 ends it once the callbacks were seen to return). This is what keeps both-maps-copied after-agent events fail-closed here too. A retired peer that no longer has an entry of its own (peerRetirement), or a swallower that a recorded cause names, leaves the event unproven. Config states when such a recovery counts.
  • After-agent credits. A retired activation's after-agent event settled an unrespondedRetired or unrespondedRetiredTools credit chosen by whether its content held a function response, whichever activation had left it. It now settles only the credit that its own activation left when it retired unresponded while a peer was open (afterAgentCredit, consumeAfterAgentCreditLocked). The model and tool credits stand for events of that run that may still come.
  • Lookalike tie-break. When one activation of inner runs on a goroutine and a newer one runs on the goroutine that started it, an agent that starts on the first goroutine matched both, and the newer one won. The activation that runs on the goroutine now comes first, as in section 7.

Proving tests.

  • TestAfterAgentRecoveryAfterEarlierProgressWithHeldChildEvent_Runner runs that shape directly under root and under an intermediate custom agent that retires while the child is open. The recovery completes the run, and the retired inner keeps its maps, but not through a context. Without the recovery the run reports the child's failure, and with both maps copied it fails closed with INVOCATION_ERROR.
  • TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner completes the run when the finished peer has no after-agent callbacks, and when its after-agent event was delivered first. It keeps the failure when nothing recovers, when the finished peer's after-agent callbacks ran but no event of theirs arrived, and when the recovery was created while the peer still ran and root held it until the peer retired. TestSoleOpenAuthor pins each condition on its own.
  • TestAfterAgentFunctionResponseSettlesOwnCredit_Runner retires the first inner unresponded with an after-agent function response while the second runs and later recovers: the run completes and no credit is left. No tool credit is outstanding when that event arrives, so the earlier credit handling would settle the same credit there; the test fails with soleOpenAuthorLocked disabled or afterAgentEventSeen ignored. TestAfterAgentCreditSettlesOnlyItsOwnActivation and TestRetiredAuthorEventWhilePeerOpen check that the event settles only its own activation's credit and no tool credit, and fail with the earlier credit handling.
  • TestLookalikeParentPrefersRunningGoroutine_Runner runs the first inner on a goroutine of root's and the second inline. Its parallel agent runs under the first, whose after-agent recovery clears the child's failure, and the failure stays reported without it. TestRunningLookalikeLocked pins the order directly.

Each of these tests fails with its fix reverted (see the mutants under Verification).

9. One agent under several branches, events created before an activation started, helper goroutines, and after-agent events without content

Running one custom agent in more shapes turned up four more cases:

  • An event of one branch of a parallel agent went to an activation of the same agent on a sibling branch. findAgent fell back to any open activation with the author's name. When one custom agent ran under two branches of a parallel agent, and the first branch's activation retired before its after-agent event, or a run event that its parent held, arrived, the event went to the second branch's open activation and cleared a failure that this activation had swallowed and never recovered from: INVOCATION_COMPLETED instead of INVOCATION_ERROR, with the first branch's row under the second branch's span. A non-empty branch now matches only activations on that branch or on a branch under it, which the workflow scheduler needs: it stamps its node run's branch on an event that left Branch empty. An event without a branch, as session.NewEvent leaves it, still matches an activation on any branch, but only when the activations of its author on a single branch that the event's covers can have created it: open ones that had started by then, retired ones that can own it, and swallowers of a recorded cause (eventAuthorBranchesLocked; section 11 applies this to every session event, resolveEventBranchLocked). Otherwise it clears no failure and settles no credit, and its rows go under the invocation span.
  • An event created before the only open activation started was that activation's. selectResponseOwnerWithIDLocked applied the creation window of section 2 only among several open peers, so a held event of an earlier, retired activation of the agent went to a later llmagent activation, took the model event that it awaited and was placed under its span. An event created before every open activation of its author, branch and node path started (startedAfterEvent) is now absorbed and settled as a retired activation's, and settles a credit that such an activation left; rows and stream tracking place it under the latest open activation that had started by then, if any (eventActivationLocked, eventSpanAt, recordStreamedAt). An event created on the tick on which the activation started still counts as the activation's, so constant clocks are unaffected. Such an event could not clear a failure of the later activation before either: clearing requires the event to postdate the failure, which came after the activation started.
  • A sub-agent started from a helper goroutine. runningLookalikeLocked finds the activation that runs a sub-agent by the goroutine that runs it or started it. The runtime names only the goroutine that directly started another, and the pinned google.golang.org/adk/v2 v2.0.0 offers no public way to tell from a context which activation started a run, so when a custom agent starts the sub-agent from a goroutine of a helper goroutine that runs no ADK callback, no goroutine that the plugin sees identifies the activation. With several open activations, the sub-agent went under the one that started last, and that activation's later answer cleared a failure that another one swallowed and never recovered from (INVOCATION_COMPLETED). Such a sub-agent now runs under the nearest open span that encloses all of them (enclosingOpenSpanLocked), so only that span or the agents above it can recover its failure. Following longer goroutine chains would not help: an intermediate goroutine that runs an ADK callback runs an activation of its own, which the one-hop rule already uses, and one that runs none leaves nothing that the plugin can see. The sub-agent's context does lead back to the run that started it, but only through the unexported fields of every context type in between, user-supplied ones included, so I did not build on that. Config states this boundary and how to stay inside it.
  • An after-agent event without content. When a retired peer's after-agent callbacks only set state, ADK builds an event without content that carries the callback context's maps. The plugin ignored it, so the peer still looked as if its after-agent event could come, and the open peer's later recovery failed closed. Such an event now marks the retired activation's after-agent event as delivered and settles its credit (clearLastPartialForEvent), on the same conditions as the content case: exactly one retired activation holds a map of it, and that activation can own it. It recovers nothing itself, and with both maps replaced it changes nothing.

Proving tests.

  • TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner runs one custom agent under both branches of a parallel agent. The second branch's activation drains its child's failure and stays open while the first branch delivers an event of its retired activation created after that failure: from its AfterAgentCallback, held from its run, or held from its run without a branch. Each keeps the failure and places the event elsewhere than under the second branch's activation, as another agent on the first branch does, and a recovery that the second branch's activation creates on its own branch still completes the run in each shape.
  • TestEventCreatedBeforeLaterActivationStarted_Runner delivers a held event of a retired custom activation while a later llmagent activation of the same agent awaits its model event. The event is not placed under the later activation, which still awaits its model event afterwards, and the later activation's own answer is placed under it.
  • TestLookalikeSubAgentOnHelperGoroutine_Runner runs the sub-agent on the activation's own goroutine (its recovery completes the run, and the other activation's answer does not) and from a helper goroutine (the sub-agent runs under root, and neither the other activation's answer nor the activation's own recovery clears the failure, as Config states).
  • TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner gains a finished peer whose after-agent callbacks only set state (the recovery completes, and the failure stays without it), the same with both maps copied by an earlier plugin (fails closed), and a control in which the copier alone does not block recovery.
  • TestCrossBranchEventAuthor, TestEventCreatedBeforeOpenActivationsStarted, TestClearLastPartialForEvent and new cases in TestRunningLookalikeLocked pin each condition directly, including that an event created on the activation's start tick, or without creation provenance, still counts as the open activation's.

Each of these tests fails with its fix reverted (see the mutants under Verification).

10. After-agent events of activations that finished cleanly, retired authors' branches, and one credit per retired activation

Running the after-agent recognition against more interleavings turned up these cases:

  • A clean activation's summary cleared another activation's failure. The action maps were recorded only when the after-agent event might recover a failure: when the activation retired unresponded or as a concurrent peer, swallowed a cause that was still recorded, or had an open span under it. Four shapes lost them, and in each the summary of an activation that finished cleanly was then taken for a failing activation of the same agent and cleared its failure (INVOCATION_COMPLETED instead of INVOCATION_ERROR):

    • inner yields progress and returns, and root starts the next inner while ADK runs the first one's AfterAgentCallback. No other activation was open when the first one retired, so nothing was recorded, and the summary went to the second one, open or retired, once it had failed.
    • An intermediate custom agent runs both activations and retires while an open root still holds the first one's summary. Its retirement dropped the maps of the child that had responded.
    • popAgentSpan set the credit, the peer flag and the maps only after retireAgentAtLocked had pruned the entries of the agent. The entry of an activation without an open custom ancestor, such as the agent of a workflow node, was therefore deleted first: its after-agent event with content cleared another activation's failure, and one that only changed state found no entry and left its credit (unrespondedRetired) outstanding, which keeps an open peer of the same agent from taking its own model and tool events; it does not fail a run by itself.
    • Compaction folded more than three clean entries into a hull without maps or credit, so a middle activation's summary went to a later failing activation.

    popAgentSpan now records the maps for every activation with after-agent callbacks and hands them, the credit and the peer flag to the entry as retireAgentAtLocked records it (popRetirement), before anything prunes. The maps stay until the after-agent event arrives or nothing could take that event for another activation's (needsAfterAgentActionsLocked). The callbacks are known to have returned once another agent starts or ends on the goroutine that retired the activation (afterAgentCallbacksReturnedOnLocked), or once the run of its parent returned (afterAgentDone; section 11 also records when, afterAgentDoneAt). After that the maps go unless an open activation of the agent, a swallower of a recorded cause, an open span under the activation or another one of the agent, or an outstanding credit still needs them. Entries that keep maps, a credit or an open span under them are not compacted. Where nothing shows that the callbacks returned, as for activations that a parent runs on goroutines that it does not wait for, at most eight such entries stay per parent, agent and branch, and the oldest fold into a hull that stands for their after-agent events (foldPendingAfterAgentLocked, afterAgentPending): an event that one of them can have created clears no failure until the parent's run returns; while a peer of those entries is open, none of them is folded (section 12). Config states this boundary. Clean waves stay bounded: after 50 clean parallel iterations under an open root, TestCleanParallelIterationsBoundRetiredActivations_Runner still finds between one and eight entries.

  • A retired author's event without its own branch. completeResponseWithEvent resolved the branch of an event without one (as session.NewEvent leaves it), or with an enclosing branch that the workflow scheduler stamped, only for an open activation of its author. For a retired author the branch stayed empty or the enclosing one, so retiring the drained descendants, clearing the swallowed causes and settling credits, which all match the branch exactly, missed, and a recovered run reported INVOCATION_ERROR. When an open activation's event was absorbed for a retired author, settleRetiredAuthorLocked got the stale branch too. The branch now resolves to the only branch whose activations can have created the event, for a retired author too (resolveEventBranchLocked, section 11); when activations on more than one branch can have, the event clears nothing and settles nothing, as in section 9.

  • Two credits from one retired activation. A retired activation that left a credit and created both an event in its run, which its parent held, and an after-agent event settled two credits: one of its agent for the run event, and its own for the after-agent event. With a second such activation and an open llmagent of the same agent awaiting its model event, the second activation's held event then found no credit left and was given to the llmagent as that model event. An event of a retired activation's run now settles that activation's own credit when only it can have created the event (settleRetiredResponseCreditLocked, createdInRun), nothing once that credit was settled (creditSettled), and one credit of the agent otherwise, as before.

  • Where the rows of a settled after-agent event go. completeResponse drops the maps when it settles the after-agent event, so the event's AGENT_RESPONSE row was then placed under an overlapping open activation of the same agent that started earlier. completeResponse now reports that it took the event for a retired activation's after-agent event, and eventSpanAt places that event's rows under the invocation span, as for other events of a retired author (section 12 shows how the report reaches it). Rows that a callback places stay where they were.

Config now describes how long the after-agent maps are kept, and lists RowErrors after an attempt with an unknown outcome next to OutOfRange and NotFound among the responses that drop the batch and replace the stream before the next one.

Proving tests.

  • TestCleanAfterAgentEventKeepsPeerFailure_Runner runs the first, second and fourth shapes above (pop_then_push, mid_retired, fifth_activation), delivering the summary while the failing activation is open and once it retired. The failure stays in each, and the failing activation's own recovery still completes the run.
  • TestGuardlessRetirementKeepsAfterAgentEntry is a unit test: it retires an activation through popAgentSpan under a parent that forwards errors, as a workflow agent does for a node's agent, rather than running a workflow agent. The entry holds the credit, the peer flag and the maps from the start. Its after-agent event without content settles the credit (unrespondedRetired goes from 1 to 0), and its event with content keeps the other activation's failure.
  • TestRetiredAfterAgentEntriesStayBounded_Runner, TestPendingAfterAgentHull, TestAfterAgentCallbacksReturnedOn and new cases in TestRetiredActivationSettlementAndHullConjuncts pin when the maps stay, when they go and how the pending entries are bounded.
  • TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner recovers a retired inner on par.inner with an event without a branch or with par's branch, after par finished or while the next activation of inner is open, and keeps the failure without the recovery. TestRetiredAuthorBranchResolution and TestRetiredEventBranch pin the resolution directly.
  • TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner holds the events of two retired custom activations while an llmagent of the same agent awaits its model event: with only an after-agent event (the control) and with a run event and an after-agent event from the first activation, the llmagent still awaits its model event afterwards, and its own answer is placed under it. TestSettleRetiredResponseCredit pins each case of the settlement.
  • TestSettledAfterAgentEventPlacement places the settled after-agent event's rows under the invocation span and leaves other rows where they were.

The three runner tests above fail on a clean git archive 97404825 with only those tests added, and pass at 16dfacdf (see Verification).

11. After-agent callbacks that returned, branches under branches, peer retirements under an open peer, and after-agent credits

Running these shapes against more interleavings turned up five more cases:

  • A held after-agent event of an activation whose callbacks had returned. A custom agent runs two activations of inner one after the other on its goroutine. The first yields nothing in its run, so it retires without a response, and the custom agent holds the event that ADK builds from its AfterAgentCallback until the second activation is open. Starting the second activation on that goroutine shows that the first one's callbacks returned (section 10), and the first one's maps went then, since nothing else needed them. So the held event was not recognized when it arrived, the first activation still counted as one whose after-agent event may come (afterAgentEventSeen stayed false), and when the second activation recovered from a failure that it swallowed, the recovery was absorbed: INVOCATION_ERROR. That happened whether the held event had content or only changed state, and also when the callbacks built no event at all. Keeping the maps until a custom ancestor delivers the event would therefore not fix it, and it would keep them for every such activation while the custom ancestor runs, which the bounds of section 10 (50 clean iterations, silent loop iterations) rule out. Instead, the plugin now records when it saw the callbacks return (afterAgentDoneAt). ADK builds the after-agent event on the goroutine that ran the callbacks before that goroutine starts or ends another agent, and before the run of the parent returns, so the retired activation can own no event created after that point (canOwnEventCreatedAt). An event that carries its after-agent maps is still its own whenever it was created, as when the callbacks ran an agent themselves (canOwnEventAt). A hull keeps the latest such point of its members, and none when one of them has none. Config states this.
  • An event that an activation on a branch under another one created. Section 9 resolved the branch of an event only when findAgent found an open activation on another branch than the event's, and section 10 did so for a retired author only when nothing of it ran on the event's own branch. Both stopped as soon as an activation of the author ran on the event's own branch. But an event can be that of an activation on its branch or on any branch under it: session.NewEvent leaves Branch empty, and the workflow scheduler stamps its node run's branch on an event that left Branch empty. So when one activation of worker ran on the root branch, or on par, and drained a failure, and another one ran on a branch under it and created an event without a branch, or with par's branch, that event went to the first one and cleared its failure: INVOCATION_COMPLETED instead of INVOCATION_ERROR, whether both were open or both had retired. Nothing tells which of them created such an event: even an activation on par that sets Branch itself sets it to par. Every session event now has the branch of the activations that can have created it resolved first (resolveEventBranchLocked; section 12 lets the event's after-agent maps decide before that), for open and retired authors alike, and an event that activations on two of those branches can have created is no one's: it clears no failure and settles no credit. TestRetiredEventBranch expected an activation on par to take such an event ahead of one on par.inner; it now expects no author, and still expects par when the activation on par.inner cannot have created the event. findAgent keeps preferring the event's own branch for the callbacks of an activation, which always carry the activation's own branch, and hasGuardedRetiredPeerForEventLocked and soleOpenAuthorLocked only run once the event's branch has been resolved to a single one.
  • A retired activation's recovery while a later activation runs on another branch. When worker on top.b1 recovered with an event without a branch and retired, and a custom agent delivered the recovery only once worker on top.b2, which started after the recovery was created, was open, only the retired activation could have created the event. The plugin still treated it as no one's, because no activation on top.b1 was open: INVOCATION_ERROR. It now settles the retired activation on top.b1: its drained descendants retire, its swallowed failure clears and its credit settles.
  • Peer retirements under an open peer. soleOpenAuthorLocked (section 8) gives an open activation its event only while every retired peer that retiredPeerCount counts still has an entry of its own (peerRetirement). Pruning kept such entries while a peer was open, but compaction did not, so once four or more peers of an open activation had retired, it replaced the middle ones with a hull, and the open activation's recovery never counted. Such entries are no longer compacted while a peer of theirs is open either. A credit, settled or not, is only ever left by a peer retirement, so those entries stay too. Once no peer is open, they compact as before.
  • After-agent credits of an event that its activation cannot own. completeResponse and selectResponseOwnerWithIDLocked settled the credit of the activation whose after-agent map an event carried, and placed the event as that activation's after-agent event, without checking that the activation can own the event, which clearing its causes and clearLastPartialForEvent both check. An event that carries the map but whose ID or Timestamp an earlier plugin rewrote, or that carries maps of two retired activations, now settles nothing and is placed like an event of no retired activation (ownsAfterAgentEvent).

Proving tests.

  • TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner runs the first shape with a held after-agent event that has content, one that only changes state, and no event at all. The second activation's recovery completes the run in each, and without it the failure stays.
  • TestSubBranchEventKeepsEnclosingBranchFailure_Runner runs worker as A on the root branch and as B on par.wb, and as A on outer.wa and B on outer.wa.par.wb with outer.wa on B's event, and delivers B's event while both are open or once both retired. B's event keeps A's failure in all four, A's failure stays without it, and A's recovery once B retired, which B cannot have created, completes the run.
  • TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner runs the third shape with a recovery without a branch and with top's branch. Each completes the run, and the failure stays without the recovery.
  • TestOpenPeerRecoveryAfterManyPeersRetired_Runner retires three, four and six short peers while a long one is open (section 12 adds cases with after-agent callbacks). The long one's recovery completes the run in each, and the failure stays without it.
  • TestAfterAgentDoneBoundsRetiredEvents, TestResolveEventBranch, TestRetiredEventBranch, TestPeerRetirementsStayUncompactedWhilePeerOpen and TestAfterAgentEventOwnershipSettlesCredit pin each condition directly, including that an after-agent event created after the callbacks were seen to return is still its activation's, and that an event that carries an activation's map settles its credit only with creation provenance and a timestamp at which the activation can have created it.

The four runner tests above fail on a clean git archive 97404825 with only those tests added, and pass at 16dfacdf (see Verification).

12. After-agent events on an enclosing branch, peer entries and the pending hull, agents that after-agent callbacks run, same-tick starts, and the settlement report

Running these shapes against more interleavings turned up four more cases, and the settlement report of section 10 stays on the stack of the call that handles the event:

  • An after-agent event on a branch that covers another activation's. resolveEventBranchLocked (section 11) counted the branches whose activations can have created an event before anything looked at the event's action maps. So when an activation A of worker on the root branch, or on outer.wa, drained a failure and its AfterAgentCallback recovered while another activation B of worker was open on par.wb, or on outer.wa.par.wb, the recovery carried A's branch, which covers B's, and was dropped as no one's: INVOCATION_ERROR. And an activation that had retired unresponded while a peer ran kept the credit that it left (unrespondedRetired) when its summary arrived while B ran, and stayed a possible author of later events, so the peer's awaited model event, or its recovery, was later absorbed against that credit. An event that carries an action map of exactly one retired activation on the branches that the event's branch covers now resolves to that activation's branch first (afterAgentSharerWithinLocked), and is then that activation's after-agent event if it can own it (ownsAfterAgentEvent, section 11). An event without such a map, or with both maps replaced, stays no one's, as before. clearLastPartialForEvent finds that activation on those branches too, so an after-agent event without content on an enclosing branch is recognized and settles its credit.
  • Peer entries folded into the pending hull. foldPendingAfterAgentLocked (section 10) folded entries into a hull that stands for after-agent events that may still come without looking at whether a peer of theirs was open. With an AfterAgentCallback on worker, more than eight short activations that retired one after another while a long one was open had their oldest entries folded into such a hull without their peer marks, so soleOpenAuthorLocked found fewer entries than retiredPeerCount counts and the long activation's recovery was absorbed: INVOCATION_ERROR. While a peer is open (hasOpenPeerLocked, which pruning now shares), neither a peer retirement nor an entry whose callbacks were seen to return is folded: the latter keeps its maps then because the open peer could be taken for the author of its after-agent event, not because that event may still come. Once no peer is open, they fold or compact as before, so the bounds of section 10 still hold (TestCleanParallelIterationsBoundRetiredActivations_Runner, TestRetiredAfterAgentEntriesStayBounded_Runner).
  • An agent that an after-agent callback runs. An agent that an AfterAgentCallback runs on the goroutine that runs the callbacks starts and ends while they run, but its start or end counted as their return (section 10): it recorded that the retired activation's callbacks had returned and dropped its maps. When another activation of the same agent then started and failed before the callbacks returned their summary, the summary was taken for the other activation's event and cleared its failure: INVOCATION_COMPLETED instead of INVOCATION_ERROR. The callback context does not show such a run, since a callback cannot run an agent with it (its WithContext returns nil) and runs one with a context from elsewhere, such as its own activation's. But ADK runs an activation's after-agent callbacks inside agent.runAfterAgentCallbacks on that goroutine, so when an agent starts or ends there, the plugin now counts those frames in the goroutine's stack trace (afterAgentCallbackRunsOfTrace) and does not record the activations whose callbacks still run. Every start or end on the goroutine records every other activation retired there, so those are the ones that retired first among the ones not recorded yet (markAfterAgentCallbacksReturnedOnLocked). An agent that a callback runs on another goroutine shows nothing about them, as before.
  • A start in the tick of a held after-agent event. pushAgentSpan dropped the maps of the activations whose callbacks it saw return before the starting agent was on agentStack, since an agent that starts later did not create an earlier event. On a coarse clock, though, the after-agent event can share the tick in which the next activation of the same agent starts. So when a custom agent held a clean activation's summary and started an llmagent of the same name on its goroutine in that tick, the summary took the llmagent's awaited model event and its rows went under the llmagent's span. pushAgentSpan still records which callbacks returned before it pushes the starting activation, but it settles their maps and prunes the entries only once that activation is open (settleAfterAgentActionsOnLocked), so the retired activation keeps them while an activation of its agent runs.
  • An event handled between settlement and row placement. Taking an event for a retired activation's after-agent event (section 10) and placing its rows happen under two separate locks, and the invocation's callbacks can handle another event in between. If the report for the first event were kept on the invocation, that event could overwrite it and change where the first event's rows go. completeResponseForEvent and clearLastPartialForEvent return the report instead, and onEvent keeps it on its own stack and passes it to emitSessionEventSignals and eventSpanAt; nothing of it is stored on the invocation.

Config now states that nothing is folded into that hull while a peer is open, and that an agent that a callback runs on that goroutine does not show that the callbacks returned. Its after-agent and concurrency paragraphs are also split into shorter paragraphs and lists, with the same guarantees.

Proving tests.

  • TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner runs worker as A on the root branch and B on par.wb, and as A on outer.wa and B on outer.wa.par.wb. A's AfterAgentCallback recovery while B is open completes the run in both; with both maps copied by an earlier plugin, and without the recovery, the failure stays.
  • TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner retires an activation A1 of worker without a response while a peer A2 is open, and delivers A1's summary while B runs on par.wb. When A2 is an llmagent named worker, it still takes its own model event and the clean run completes without an AGENT_ERROR row; when A2 recovers from its child's failure, the run completes. Both also complete without B.
  • TestOpenPeerRecoveryAfterManyPeersRetired_Runner now also retires three, eight, nine and 15 short peers with an AfterAgentCallback on worker. The long one's recovery completes the run in each, and the failure stays without it.
  • TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner has inner's AfterAgentCallback run the custom agent helper on that goroutine before it returns, while a second activation of inner drains its child's failure and stays open. The first activation's clean summary keeps the second's failure, the second's own recovery completes the run, and the first's callback recovery from its own failure completes it too.
  • TestSameTickStartKeepsHeldAfterAgentEvent_Runner runs the fourth shape on a clock that advances only when the test says so: the llmagent still awaits its model event after the held summary arrives, the summary is not placed under it, and the llmagent's own answer is.
  • TestAfterAgentSharerResolvesEventBranch, TestPeerRetirementsStayUncompactedWhilePeerOpen, TestAfterAgentCallbacksStillRunning and TestStartingActivationKeepsSameAgentAfterAgentMaps pin each condition directly. TestSettledAfterAgentPlacementSurvivesInterleavedEvent handles an event of the open activation in full between completeResponse and eventSpanAt of a settled after-agent event, and checks where the rows of both go.

The four runner tests above that are new fail on a clean git archive 97404825 with only those tests added, as do the new cases of TestOpenPeerRecoveryAfterManyPeersRetired_Runner, and all pass at 16dfacdf (see Verification).

Existing tests that changed

Five tests that exist at 97404825 change:

  • TestTraceManager_AgentNesting pinned the sibling-branch fallback ("an author that does not run on the event's branch is found by name"). It now expects such an event, or one without a branch while the author runs on two branches, under the invocation span, and an event stamped with an enclosing branch under the agent (section 9).
  • TestTraceManager_SameAgentConcurrentNodePaths created its session events before the activations that they belong to started, and now creates them once those run (section 9).
  • TestRetireDrainedDescendants_NestedRetiredCustomAncestors compared synthetic event times with a span started on the real clock, and now dates that start before the events (section 9).
  • TestCleanParallelIterationsBoundRetiredActivations_Runner expected no entry to keep after-agent maps. It now expects the latest child that root runs directly, whose callbacks nothing shows to have returned while root still runs, to keep them, with the bound on entries unchanged and none kept for par's children (section 10).
  • TestCausalRecoveryOrderingAndProvenanceGuards records the action maps where it recorded the StateDelta address, and gains a case in which an event with the callback's StateDelta and another ArtifactDelta clears the cause (section 1). Its case for an event that holds a retired activation's map while a later retired activation could own the event by its timestamp expected the failure to stay; it now expects it cleared, because the map makes the event that activation's alone (afterAgentSharerLocked, section 7), and the same event without the map still leaves the failure. Its compaction case now expects the maps to go once nothing needs them and at the end of the invocation, rather than by compaction (section 10).

TestSequentialRecoveredParallelIterations_Runner only gains cases (section 2). The tripwire tests TestCallbackAfterAgentStateDeltaPtr and TestAfterAgentStateDeltaGCReuse_Runner are now TestCallbackAfterAgentActionMaps and TestAfterAgentActionMapsGCReuse_Runner, for both maps (section 5). TestRetiredAuthorEventWhilePeerOpen, TestRetiredEventBranch and TestAfterAgentCallbacksReturnedOn are new in this change, not ones that exist at 97404825; one case of the first dates a span start before synthetic event times in the same way. Counting top-level test functions in plugin/agentanalytics, 97404825 has 588 and 16dfacdf has 636: 48 are added and the 2 tripwire tests above are renamed, so there are 48 more, and the 6 tests named here change.

(Continued in the next comment with Verification details for 16dfacdf65421303d0deb6ae77e8aaae85aca7e5.)

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

(Continued from the previous comment for 16dfacdf65421303d0deb6ae77e8aaae85aca7e5.)

Verification

On a clean git archive 16dfacdf with go work init && go work use -r . (as in CI), -mod=readonly, go1.27.3 and the default GOMAXPROCS (24 on this machine):

  • gofmt -l ., GOWORK=off go mod tidy -diff, go build ./... and go vet ./... are clean in the repository root and in plugin/agentanalytics. In a clone checked out at 16dfacdf, git diff --check origin/main..HEAD is clean, golangci-lint run --new-from-merge-base=origin/main ./... reports 0 issues. in the repository root and in plugin/agentanalytics, and .github/scripts/apidiff.sh origin/main reports No incompatible changes.
  • In plugin/agentanalytics, go test -p 1 -parallel 1 -race -shuffle=on -count=1 -v ./... passes (ok ... 251.859s, shuffle seed 1794521085567369042, 636 top-level tests pass, 0 data races). So do go test -p 1 -parallel 1 -race -count=1 ./... (ok ... 266.479s, 0 data races) and go test -p 1 -parallel 1 -shuffle=on -count=1 -v ./... (ok ... 119.102s, shuffle seed 1794521638689925797, 636 top-level tests pass).
  • Under -race -count=30 (ok ... 430.942s, 0 data races, 0 failures), each of these passes 30/30, shown with its === RUN lines including parents: TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner (210), TestSubBranchEventKeepsEnclosingBranchFailure_Runner (390), TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner (150), TestOpenPeerRecoveryAfterManyPeersRetired_Runner (450), TestAfterAgentDoneBoundsRetiredEvents (180), TestAfterAgentEventOwnershipSettlesCredit (390), TestPeerRetirementsStayUncompactedWhilePeerOpen (210), TestResolveEventBranch (240), TestRetiredEventBranch (330), TestCleanAfterAgentEventKeepsPeerFailure_Runner (330), TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner (270), TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner (90), TestRetiredAfterAgentEntriesStayBounded_Runner (90), TestGuardlessRetirementKeepsAfterAgentEntry (120), TestRetiredAuthorBranchResolution (150), TestAfterAgentRecoveryAfterConcurrentPeerRetired_Runner (360), TestAfterAgentRecoveryWithOpenPeerAwaitingEvent_Runner (240), TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner (300), TestEventCreatedBeforeLaterActivationStarted_Runner (30), TestLookalikeSubAgentOnHelperGoroutine_Runner (150), TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner (360), TestCleanParallelIterationsBoundRetiredActivations_Runner (120), TestAfterAgentFunctionResponseSettlesOwnCredit_Runner (30), TestCrossBranchEventAuthor (810), TestSoleOpenAuthor (420), TestPendingAfterAgentHull (30), TestAfterAgentCallbacksReturnedOn (30), TestSettleRetiredResponseCredit (180), TestRetiredActivationSettlementAndHullConjuncts (540), TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner (210), TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner (150), TestAfterAgentSharerResolvesEventBranch (420), TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner (120), TestAfterAgentCallbacksStillRunning (30), TestSameTickStartKeepsHeldAfterAgentEvent_Runner (30), TestStartingActivationKeepsSameAgentAfterAgentMaps (30) and TestSettledAfterAgentPlacementSurvivesInterleavedEvent (30). Under -race -count=10 (ok ... 6.739s), TestAfterAgentRecoveryWithCopiedActionMaps_Runner (100) and TestCallbackAfterAgentActionMaps (10) pass 10/10.
  • Under -race -count=10 on their own (ok ... 3.898s), TestSameTickStartKeepsHeldAfterAgentEvent_Runner, TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner and TestAfterAgentRecoveryAfterEarlierProgressWithHeldChildEvent_Runner pass 10/10. The held-child shape in section 2 still reports INVOCATION_ERROR at 16dfacdf, with live and with callback recovery, with and without earlier progress (a temporary probe, 10 runs each under -race).
  • go test -p 2 -count=1 ./... in the repository root passes (114 packages ok, 0 failures).
  • The runner tests of sections 11 and 12, added with the test helpers that they use to a clean git archive 97404825, fail there in 21 subtests, every one of them a case that this change fixes. Of section 11's, the three recovery_completes subtests of TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner, the two of TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner and the seven of TestOpenPeerRecoveryAfterManyPeersRetired_Runner (three, four and six short peers, and three, eight, nine and 15 with after-agent callbacks) get INVOCATION_ERROR, and the four B's_event_keeps_A's_failure subtests of TestSubBranchEventKeepsEnclosingBranchFailure_Runner get INVOCATION_COMPLETED. Of section 12's, the two after-agent_recovery_completes subtests of TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner and both recovering_peer_completes subtests of TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner, with and without an activation on a sub-branch, get INVOCATION_ERROR, and clean_summary_keeps_the_other_activation's_failure of TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner gets INVOCATION_COMPLETED; TestSameTickStartKeepsHeldAfterAgentEvent_Runner, which has no subtests, fails too, because the held summary takes the llmagent's awaited model event and goes under its span. Every negative control and every other subtest of those eight tests passes there (28 of 49), among them own_recovery_completes and second_recovers_completes of TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner and both llm_peer_takes_its_model_event subtests of TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner. The three runner tests of section 10 fail there in 10 subtests, with the other 10 passing: four keeps_the_failure subtests of TestCleanAfterAgentEventKeepsPeerFailure_Runner get INVOCATION_COMPLETED, and the fifth, fifth_activation/summary_delivered_while_the_failing_activation_is_open/keeps_the_failure, still reports the failure but places the summary's AGENT_RESPONSE row under the failing activation of inner instead of the invocation span; the four recovery_completes subtests of TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner get INVOCATION_ERROR; and in run_event_and_after-agent_event of TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner the held events take the llmagent's awaited model event. The unit tests added with them use symbols that 97404825 does not have, so the mutants below pin them.
  • 95 compiling mutants each fail every listed test, and the unmutated tree passes them:
    • recording the after-agent maps in popAgentSpan only under the earlier condition (TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestGuardlessRetirementKeepsAfterAgentEntry)
    • handing the credit, peer flag and maps to the entry only after retireAgentAtLocked pruned; letting pruning delete a guardless entry that holds an after-agent event, an open span under it or a peer credit (TestGuardlessRetirementKeepsAfterAgentEntry)
    • dropping a responded child's maps when its parent retires under an open custom ancestor (TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestRetiredActivationSettlementAndHullConjuncts)
    • compacting entries that keep maps, a credit or an open span under them (TestCleanAfterAgentEventKeepsPeerFailure_Runner, TestCausalRecoveryOrderingAndProvenanceGuards)
    • disabling foldPendingAfterAgentLocked (TestRetiredAfterAgentEntriesStayBounded_Runner, TestPendingAfterAgentHull)
    • letting a later activation exclude a pending hull by timestamp (excludedByEventTimestamp); not letting a pending hull own an event created after its members retired (eventAuthorLocked) (TestPendingAfterAgentHull)
    • ignoring in needsAfterAgentActionsLocked that the callbacks may still run; ignoring an open activation of the same agent there; not marking a child's callbacks as returned once its parent's run returned (recordRetiredActivationsAtLocked) (TestRetiredActivationSettlementAndHullConjuncts)
    • ignoring another activation's outstanding credit in needsAfterAgentActionsLocked (TestAfterAgentCallbacksReturnedOn)
    • making afterAgentCallbacksReturnedOnLocked a no-op and not marking in pushAgentSpan the callbacks that returned (TestAfterAgentCallbacksReturnedOn, TestCleanParallelIterationsBoundRetiredActivations_Runner)
    • keeping the event's own branch for a found open activation in completeResponseWithEvent; keeping the event's own branch for a retired author in completeResponseWithEvent (TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner, TestRetiredAuthorBranchResolution)
    • keeping the event's branch in resolveEventBranchLocked when activations on two branches can have created it; ignoring an activation on the event's branch itself in eventAuthorBranchesLocked (TestRetiredEventBranch)
    • settling one credit of the key for every retired author's event, as before (TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner, TestSettleRetiredResponseCredit)
    • settling a credit again after the activation's credit was settled; not recording in consumeAfterAgentCreditLocked that the credit was settled; letting createdInRun ignore when the activation started (TestSettleRetiredResponseCredit)
    • ignoring the settlement report in eventSpanAt (TestSettledAfterAgentEventPlacement, TestCleanAfterAgentEventKeepsPeerFailure_Runner)
    • returning no settlement report from completeResponseForEvent (TestSettledAfterAgentPlacementSurvivesInterleavedEvent, TestCleanAfterAgentEventKeepsPeerFailure_Runner)
    • applying the settlement report to the rows that a callback places (eventSpan) (TestTraceManager_FinalResponseToolRow, TestTraceManager_AgentNesting, TestSettledAfterAgentEventPlacement)
    • matching an event's branch loosely in findAgent (TestCrossBranchEventAuthor, TestTraceManager_AgentNesting)
    • skipping findEventAgentLocked (TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner, TestCrossBranchEventAuthor, TestTraceManager_AgentNesting)
    • taking findAgent's open activation in completeResponseWithEvent; leaving out retired activations in eventAuthorBranchesLocked (TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner, TestCrossBranchEventAuthor)
    • counting every retired activation in eventAuthorBranchesLocked; ignoring creation provenance there; ignoring when open activations started there; leaving out swallowers there; tracking partial events with findAgent (TestCrossBranchEventAuthor)
    • not absorbing an event created before every open activation started (TestEventCreatedBeforeLaterActivationStarted_Runner, TestEventCreatedBeforeOpenActivationsStarted)
    • absorbing such an event without settling a credit (TestEventCreatedBeforeOpenActivationsStarted, TestRetireDrainedDescendants_NestedRetiredCustomAncestors)
    • treating an equal start time as a later one (TestEventCreatedBeforeOpenActivationsStarted, TestFixedTimeProviderRecovery_Runner)
    • placing an event under an open activation that started after it (TestEventCreatedBeforeLaterActivationStarted_Runner, TestEventCreatedBeforeOpenActivationsStarted, TestCrossBranchEventAuthor)
    • placing session-event rows without the event's creation time (TestEventCreatedBeforeLaterActivationStarted_Runner)
    • keeping the last-started lookalike when no goroutine identifies one (TestLookalikeSubAgentOnHelperGoroutine_Runner, TestRunningLookalikeLocked)
    • letting enclosingOpenSpanLocked return a retired span (TestRunningLookalikeLocked)
    • ignoring an after-agent event without content (TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner, TestClearLastPartialForEvent)
    • handling an after-agent event without content with clearLastPartial in onEvent (TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner)
    • dropping the ownership step of clearLastPartialForEvent; dropping its provenance step; dropping its credit step (TestClearLastPartialForEvent)
    • dropping the keep for an open span under the activation in needsAfterAgentActionsLocked; dropping, together with that keep, the maps on an enclosing retirement without an open custom ancestor while a span under the activation is open; keeping the callback context instead of its EventActions (TestAfterAgentRecoveryAfterEarlierProgressWithHeldChildEvent_Runner)
    • disabling soleOpenAuthorLocked; ignoring afterAgentEventSeen (TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner, TestAfterAgentFunctionResponseSettlesOwnCredit_Runner, TestSoleOpenAuthor)
    • dropping the retired-ownership condition of soleOpenAuthorLocked; dropping its start window; dropping its peer-entries condition; dropping its swallower condition; dropping its zero-timestamp condition; dropping its pending model or tool event condition (TestSoleOpenAuthor)
    • restoring the earlier credit handling for an open peer (TestRetiredAuthorEventWhilePeerOpen)
    • restoring the earlier credit handling with no open activation (TestAfterAgentCreditSettlesOnlyItsOwnActivation)
    • weighing the starting goroutine like the running one (TestLookalikeParentPrefersRunningGoroutine_Runner, TestRunningLookalikeLocked)
    • dropping the ownResponse check (TestReconcileConcurrentResponseOnPopKeepsInheritedPeerResponse)
    • making runningLookalikeLocked return the last-started lookalike (TestAfterAgentRecoveryAfterConcurrentPeerRetired_Runner)
    • disabling the afterAgentSharerLocked absorption in selectResponseOwnerWithIDLocked (TestRetiredAuthorEventWhilePeerOpen, TestAfterAgentRecoveryWithOpenPeerAwaitingEvent_Runner)
    • skipping RowErrors isolation (TestBatchProcessor_RowErrorsIsolation, TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors)
    • skipping the ambiguous-send guard (TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors)
    • removing the sync.OnceValue around CloseFunc (TestPlugin_CloseOnceAndAfterRunPanic, TestClose_SecondCallAfterCleanCloseSucceeds)
    • dropping the afterAgentDoneAt bound in canOwnEventAt; not recording that time in markAfterAgentCallbacksReturnedOnLocked (TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner, TestAfterAgentDoneBoundsRetiredEvents)
    • not recording it once the parent's run returned; keeping the latest sighting in markAfterAgentDone; bounding an event that carries the activation's after-agent maps by that time in canOwnEventAt; not passing that an event carries the activation's maps to canOwnEventAt in eventAuthorLocked; keeping the first member's time in a pending hull; keeping the first middle member's time in a compacted hull (TestAfterAgentDoneBoundsRetiredEvents)
    • giving an event to an open activation on the event's own branch in resolveEventBranchLocked without looking at other branches (TestSubBranchEventKeepsEnclosingBranchFailure_Runner, TestResolveEventBranch)
    • giving an event to a retired activation on the event's own branch without looking at other branches (TestSubBranchEventKeepsEnclosingBranchFailure_Runner, TestRetiredEventBranch)
    • treating an event of a single retired branch as no one's while an activation of its author runs on another branch (TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner, TestResolveEventBranch)
    • giving an event that is no one's to findAgent's activation in findEventAgentLocked (TestCrossBranchEventAuthor, TestTraceManager_AgentNesting)
    • compacting peer retirements while a peer is open (TestOpenPeerRecoveryAfterManyPeersRetired_Runner, TestPeerRetirementsStayUncompactedWhilePeerOpen)
    • settling the credit of a sharer that cannot own the event in selectResponseOwnerWithIDLocked; settling the credit of a sharer that cannot own the event in completeResponseWithEvent (TestAfterAgentEventOwnershipSettlesCredit)
    • dropping the creation provenance test of ownsAfterAgentEvent; dropping the timestamp test of ownsAfterAgentEvent (TestAfterAgentEventOwnershipSettlesCredit, TestClearLastPartialForEvent)
    • resolving an event that carries a retired activation's after-agent map without that activation in resolveEventBranchLocked, so that activations on a branch under its branch make it no one's (TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner, TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner, TestAfterAgentSharerResolvesEventBranch)
    • matching only the event's own branch in clearLastPartialForEvent (TestAfterAgentSharerResolvesEventBranch)
    • dropping the open-peer skip in foldPendingAfterAgentLocked (TestOpenPeerRecoveryAfterManyPeersRetired_Runner, TestPeerRetirementsStayUncompactedWhilePeerOpen)
    • folding peer retirements while a peer is open in foldPendingAfterAgentLocked; folding entries whose callbacks were seen to return while a peer is open (TestPeerRetirementsStayUncompactedWhilePeerOpen)
    • ignoring the runs of after-agent callbacks that enclose an agent's start in pushAgentSpan; ignoring them at an agent's end in popAgentSpan (TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner)
    • not counting the runs of after-agent callbacks in a goroutine's stack trace (TestAfterAgentCallbacksStillRunning, TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner)
    • keeping the activations that retired last on the goroutine, instead of first, as the ones whose callbacks still run (TestAfterAgentCallbacksStillRunning)
    • dropping the maps that no longer seem needed before the starting activation is open in pushAgentSpan (TestSameTickStartKeepsHeldAfterAgentEvent_Runner, TestStartingActivationKeepsSameAgentAfterAgentMaps)
    • passing no settlement report from onEvent to emitSessionEventSignals (TestCleanAfterAgentEventKeepsPeerFailure_Runner)
    • reporting no settlement from clearLastPartialForEvent (TestAfterAgentSharerResolvesEventBranch)
    • reporting no settlement from selectResponseOwnerWithIDLocked (TestAfterAgentEventOwnershipSettlesCredit)
  • Only plugin/agentanalytics changes. The tests use local fakes only: no live BigQuery and no credentials.

caohy1988

This comment was marked as outdated.

@haiyuan-eng-google
haiyuan-eng-google marked this pull request as ready for review November 13, 2026 06:12
…stack traces

afterAgentCallbackRunsOfTrace counted only the visible
agent.runAfterAgentCallbacks frames in a goroutine's stack trace. When
Go's runtime elided middle frames on a deep stack or currentGoroutineTrace
hit maxGoroutineTraceSize, an enclosing runAfterAgentCallbacks frame
could be absent from the trace. pushAgentSpan and popAgentSpan then
treated the underestimated count as exact, marking a still-running
activation's after-agent callbacks as returned and dropping its action
maps, so a clean summary returned by that callback could clear another
activation's failure.

afterAgentCallbackRunsOfTrace now takes complete bool and returns
(int, bool), returning (0, false) when the trace is incomplete, lacks a
header newline, contains a runtime elision line, or has a frame without
an argument list, matching attemptSiteOfTrace. pushAgentSpan and
popAgentSpan skip marking retired activations' callbacks returned when
the count is unknown, while pushAgentSpan keeps its post-append
settleAfterAgentActionsOnLocked call so already-done activations on the
goroutine whose last blocker was purged still settle.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the review and for catching the stack-elision gap. Addressed in 2bc75b614d3bc9ab385b39dbab1b3f212c5b48e3 (2bc75b61, on top of 81440609).

Stack-trace elision & truncation fail-closed fix

  • afterAgentCallbackRunsOfTrace(trace []byte, complete bool) (int, bool) (plugin/agentanalytics/trace_manager.go:7139-7168, doc comment :7130-7138): Mirrors attemptSiteOfTrace (plugin/agentanalytics/trace_manager.go:7019):
    • Returns (0, false) when !complete (buffer cap hit in currentGoroutineTrace at plugin/agentanalytics/trace_manager.go:7119) or when strings.Cut(string(trace), "\n") finds no header newline.
    • Iterates frame lines via strings.SplitSeq(frames, "\n"), skipping empty lines and \t-indented file:line lines, breaking at "created by ", returning (0, false) on any runtime elision line (strings.HasPrefix(line, "...")) or any frame line without a function argument list (paren := strings.LastIndexByte(line, '('); paren <= 0), and counting exact agent.runAfterAgentCallbacks matches before returning (runs, true).
  • pushAgentSpan (plugin/agentanalytics/trace_manager.go:4025-4031, :4194-4196, :4236-4245): Records afterAgentRuns, afterAgentRunsKnown = afterAgentCallbackRunsOfTrace(trace, complete) and calls inv.markAfterAgentCallbacksReturnedOnLocked(goid, startPlatformTime, afterAgentRuns) (:901) only when afterAgentRunsKnown is true. inv.settleAfterAgentActionsOnLocked(goid) at :4245 remains unconditional after appending rec: activations whose afterAgentDone is unset keep their maps in needsAfterAgentActionsLocked (:830), while any already-done activation on goid whose last open blocker was removed by purgeActivationLocked earlier in pushAgentSpan still settles.
  • popAgentSpan (plugin/agentanalytics/trace_manager.go:4330-4347): Computes afterAgentRuns = max(runs-1, 0) and sets afterAgentRunsKnown = true only when afterAgentCallbackRunsOfTrace(trace, complete) reports ok == true, guarding inv.afterAgentCallbacksReturnedOnLocked(goid, retiredAt, afterAgentRuns) (:880) on afterAgentRunsKnown.

Regression tests

  • Unit coverage (TestAfterAgentCallbacksStillRunning in plugin/agentanalytics/after_agent_events_test.go:1909-2043): Added table cases for ...42 frames elided... and ...additional frames elided... between two runAfterAgentCallbacks frames, elision with zero visible runAfterAgentCallbacks frames, elision after "created by ", truncated traces (complete == false, with and without a visible runAfterAgentCallbacks frame), missing header newline / empty trace / argumentless frame lines, live deep-stack elision via currentGoroutineTrace(), and state checks confirming that unknown counts leave pending activations on goid unmarked (afterAgentDone == false) with their action maps retained across settleAfterAgentActionsOnLocked.
  • Runner-level deep-stack reproduction (TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner in plugin/agentanalytics/attribution_runner_test.go:1105-1303, helpers callWithStackDepth at :1054-1060 and forwardRunAtDepth at :1064-1084): Added elided_stack/ subtests wrapping both the outer inner run on its goroutine and the AfterAgentCallback helper.Run call in 60 non-tail recursive frames (stackDepth = 60). Inside helper.Run (:1148-1158), the test asserts that currentGoroutineTrace() is complete, contains "frames elided", and omits agent.runAfterAgentCallbacks(, and asserts both while helper runs and after helper ends (:1119-1139, :1159, :1230) that inner-1 remains unmarked with its action maps intact, preserving INVOCATION_ERROR on elided_stack/clean_summary_keeps_the_other_activation's_failure (reproduced as fail-open INVOCATION_COMPLETED on 81440609 prior to the fix) and INVOCATION_COMPLETED on elided_stack/second_recovers_completes and elided_stack/own_recovery_completes.

Follow-ups

Acknowledged on the three Config-documented follow-up items — constant-clock non-callback recovery provenance (plugin/agentanalytics/config.go:264-277), isolated per-call platform.WithUUIDProvider provenance (plugin/agentanalytics/config.go:257-262), and an exported platform accessor for custom UUID provider detection — to track separately after this PR lands.

Verification

  • gofmt -l plugin/agentanalytics/trace_manager.go plugin/agentanalytics/trace_manager_test.go plugin/agentanalytics/after_agent_events_test.go plugin/agentanalytics/attribution_runner_test.go (clean)
  • go vet ./... and (cd plugin/agentanalytics && go vet ./...) (clean)
  • go mod tidy -diff (clean)
  • golangci-lint run --max-same-issues=0 --max-issues-per-linter=0 ./... and golangci-lint run --enable=modernize --max-same-issues=0 --max-issues-per-linter=0 ./... on root and plugin/agentanalytics (0 issues)
  • go -C plugin/agentanalytics test -race -count=1 ./... (PASS)
  • go -C plugin/agentanalytics test -race -count=10 -run '^(TestAfterAgentCallbacksStillRunning|TestAfterAgentCallbacksReturnedOn|TestAfterAgentDoneBoundsRetiredEvents|TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner|TestStartingActivationKeepsSameAgentAfterAgentMaps|TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner)$' . (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 stack-elision fix holds up. afterAgentCallbackRunsOfTrace now reports an unknown count for truncated, malformed or elided traces, and both marking paths skip unknown counts. Reverting either guard brings back the false INVOCATION_COMPLETED in the deep-stack runner case, so the new tests do their job. The earlier items are resolved too: copied StateDelta maps, recovery across two buffered iterations, settled parallel subtrees, the action-map provenance shortcut, bounded retention for clean iterations, later-plugin recovery, and the close/panic cleanup. The module race suite, vet, build and go mod tidy -diff are all clean. Nothing blocking from me.

Three things remain open, and they're fine as documented follow-ups:

  • On a constant clock, a genuine non-callback recovery (or repeated same-tick recovery) still reports INVOCATION_ERROR, because the live path needs a creation time strictly after the failure (trace_manager.go around 5573). Making that comparison inclusive would let stale events in, so this really needs explicit creation-order provenance.
  • A UUID provider attached only at session.NewEvent(platform.WithUUIDProvider(ctx, p), ...) gives no provenance signal, so that recovery fails closed. Config documents this.
  • Attribution still depends on the private actions field, the uuidProviderKey type name and the agent.runAfterAgentCallbacks frame name. The tripwire tests catch a rename today, but exported accessors would be nicer when the framework offers them.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thank you for the thorough re-review on 2bc75b61 and for confirming the stack-elision fix and prior items!

Agree on all three documented follow-ups; keeping #2182 scoped as-is with no further changes needed:

  1. Constant-clock non-callback recovery (plugin/agentanalytics/trace_manager.go:5573): requiring strict evCreatedAt.After(causeTime) avoids admitting stale events on constant clocks until explicit creation-order provenance is available.
  2. Isolated platform.WithUUIDProvider (plugin/agentanalytics/config.go:257-262): passing a non-UUID provider only to a standalone session.NewEvent call has no callback-observable provenance and intentionally fails closed.
  3. Internal framework hooks (plugin/agentanalytics/trace_manager.go:7147, 8238, 8277): runAfterAgentCallbacks, uuidProviderKey, and actions reflection remain guarded by tripwire tests (TestAfterAgentCallbacksStillRunning, TestContextHasCustomUUIDProviderAndProvenance, TestCallbackAfterAgentActionMaps) and can migrate cleanly once exported framework accessors exist.

@wojtas000

Copy link
Copy Markdown
Contributor

I'm closing this because one PR adds 23,557 lines for three unrelated changes, and most of that code handles event-buffering cases that came from review probes rather than from bugs users reported.

The plan in #2014 asks for items 3, 8 and 11 as small separate PRs. Here they come together: trace attribution, Close/afterRun cleanup and partial-batch row errors. Please send each one on its own.

The trace attribution work keeps growing. Each review round found a new buffering shape, such as an ancestor that holds events across iterations, a plugin that copies an event's StateDelta map, or a constant clock. Each fix added heuristics and another limitation to the Config docs. No issue shows a user hitting these cases. Please open an issue with a reproduction from a real setup before taking this part further.

Partial-batch row errors used to drop the whole batch. With this PR, only the rejected rows are dropped and the rest are resent. adk-python drops the whole batch as non-retryable (src/google/adk/plugins/bigquery_agent_analytics_plugin.py), and the change adds a new exported DropStats.RowErrorDrops field. If you want this behavior, please raise it in adk-python first.

Attribution now depends on reflection over context values and an unexported field, on counting callback frames in goroutine stack traces, and on map-pointer identity. A rename in the adk module would silently turn recovered runs into reported failures. Please keep any follow-up to the public API.

Some recoveries that complete on main are reported as failures with this PR, for example a recovery event created with a UUID provider passed only to session.NewEvent. A follow-up should not report a failure for a run that main completes.

The Close() idempotency and afterRun panic cleanup fix a real gap, and a small PR with just that change and its tests would be welcome.

@wojtas000 wojtas000 closed this Nov 18, 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.

3 participants