Repository navigation
fix(agentanalytics): harden trace late-retirement, Close/afterRun lifecycle, and RowErrors isolation - #2182
fix(agentanalytics): harden trace late-retirement, Close/afterRun lifecycle, and RowErrors isolation#2182haiyuan-eng-google wants to merge 12 commits into
Conversation
…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
c5e19db to
63b226e
Compare
…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).
|
Addressed in 4ec5225:
|
…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.
|
Addressed both
Verified on a clean |
…ion recovery is ambiguous
|
Thanks for the review! Addressed the buffered multi-response attribution finding in
|
…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.
|
Addressed the causal recovery ordering, open-activation disambiguation, zero-timestamp provenance, and compaction findings in commit
|
…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.
|
Addressed both findings from review
Verified on a clean |
…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.
|
Addressed all 5 items from review
|
…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.
|
Addressed all 7 findings from Review
|
…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.
|
Thanks for the review. All six findings are addressed in 1. P1: copying a recovery event's
|
|
(Continued from the previous comment for VerificationOn a clean
|
…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.
|
Thanks for the review and for catching the stack-elision gap. Addressed in Stack-trace elision & truncation fail-closed fix
Regression tests
Follow-upsAcknowledged on the three Verification
|
caohy1988
left a comment
There was a problem hiding this comment.
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.goaround 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.Configdocuments this. - Attribution still depends on the private
actionsfield, theuuidProviderKeytype name and theagent.runAfterAgentCallbacksframe name. The tripwire tests catch a rename today, but exported accessors would be nicer when the framework offers them.
|
Thank you for the thorough re-review on Agree on all three documented follow-ups; keeping
|
|
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. |
Linked issue
Related: #2014
Summary
Implements the
v1.0.0resilience hardening items from#2014acrosstraceManager, pluginClose()/afterRunlifecycle guards, andBatchProcessorpartial-batchRowErrorsisolation:trace_manager.go,bigquery_agent_analytics_plugin.go,config.go,events.go):openFailureCausefrom retired drained descendants to the nearest open ancestor across retired non-propagating custom ancestors inretireDrainedDescendantsLocked(preserving the earliest unretiredfailurePlatformTimeand monotonicfailureSeqso 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.ancestorSpanIDs,joinedAtRetire(rec.completed || rec.runDone), andsettledByParent(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 wherestartandNewEventshare 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.evCreatedAt > failure platformTimeon live activations acrossclearRetiredCauseForEventLocked,completeResponseAt, andunrecoveredErrors) 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 registersAfterAgentCallback), 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 (StateDeltaorArtifactDelta) of the callback context (afterAgentActions).afterAgentActionsRefkeeps those maps reachable through theEventActionsthat holds them (callbackAfterAgentActions), not through the callback context, so a retired record keeps nothing else of the run. An earlier plugin'sOnEventCallbackthat 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 ineventAuthorLocked.popAgentSpanhands the maps, the credit and the peer flag to the entry asretireAgentAtLockedrecords it (popRetirement), beforepruneSettledRetiredActivationsLockedruns, 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 insideagent.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;pushAgentSpansettles 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.agentStackas disambiguation candidates ineventAuthorLocked/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 anAfterAgentCallbackrecovery 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, andselectResponseOwnerWithIDLockedabsorbs 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 theunrespondedRetiredcredit 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 withevActions) wheneverselectResponseOwnerWithIDLockedabsorbs an event because a retired activation of its author created it while another activation of the same agent is open (retiredAuthor), on the branch thatresolveEventBranchLockedresolved. 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-UUIDunforwardedModelEventsdelivered after an unrecovered error from claiming response ownership over openllmSpans(selectResponseOwnerWithIDLockedpasses activation-awarehasIDFor(base)so child-scopedplatform.WithUUIDProvidermodel errors preserveunforwardedModelEvents).soleOpenAuthorLocked), even when it holds a failure andretiredPeerCountrecords 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.runningLookalikeLockedinparentForRunLocked), 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 thatcompleteResponserouted to the peer as its own (ownResponseinreconcileConcurrentResponseOnPopLocked), 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. Afinish_taskretirement whose run had not synchronized (unjoinedTaskRetirement) may own events created after it retired (canOwnEventCreatedAt), andhasGuardedRetiredPeerForEventLockedskips retired activations that cannot have created an event at its creation time.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, assession.NewEventleaves 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 leftBranchempty. 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 onparand 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 inselectResponseOwnerWithIDLocked, 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).session.NewEventcreation provenance viahasEventCreationProvenance(ctx, ev)(accepting canonical RFC 4122 UUIDv4 IDs viahasNewEventUUIDor non-empty IDs when an active non-nilplatform.WithUUIDProvideris present on the delivery context, an open activation context onagentStack, or a matching retired activation'shasCustomUUIDProvider, without trusting mutableev.Actionsmaps as proof of construction), tracks per-spanownResponse(unrespondedAtPop), combines agentAfterAgentCallbacks(agentHasAfterAgentCallbacks) with later registered plugins definingAfterAgentCallbackin the innermostPluginManager(contextHasLaterAfterAgentPluginusing aweak.PointerselfPluginontraceManagerwithpluginNamefallback so inner sub-runner managers shadow outer ones), and enforces parent/self creation time windows viacanOwnEventCreatedAt.pruneSettledRetiredActivationsLockedto at most three representatives per compaction key (first, an optional union-timestampcompactedHullacross middle iterations withgoroutineIDcleared so differing errgroup worker goroutines compact inO(1)and ancestor chains intersected, andlast;joinedAtRetireandsettledByParentare 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, sosoleOpenAuthorLockedstill 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, sosoleOpenAuthorLockedstill finds every retired peer.completeResponsejust 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 (completeResponseForEventandclearLastPartialForEventreport that they took the event as such, andonEventkeeps the report on its own stack and passes it toemitSessionEventSignalsandeventSpanAt, so another event that the invocation handles in between cannot change where the first event's rows go).Configdoc):session.Eventstruct literals lacking an RFC 4122 UUIDv4 ID under the default provider (including literals with non-nilActions.StateDeltaandActions.ArtifactDeltamaps) 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 UUIDv4IDor run under an invocation/agent-scoped customplatform.WithUUIDProviderremain indistinguishable fromsession.NewEventat the plugin boundary.OnEventCallbackmay replace theStateDeltaor theArtifactDeltamap 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'sOnEventCallbacknever 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.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.Branch: an event is never attributed to an activation on a sibling branch. An event without aBranchcan be that of an activation on any branch, and one with aBranchthat 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 ownAfterAgentCallbackevent, which carries its action maps, unless an earlier plugin replaced both).platform.WithUUIDProvideroverrides must be installed on the invocation or agentcontext.Context; call-site-only overrides passed exclusively tosession.NewEvent(platform.WithUUIDProvider(...), ...)fail closed becauseplugin/agentanalytics/go.modpinsgoogle.golang.org/adk/v2 v2.0.0andsession.Eventcarries no provider provenance across the module boundary.platform.WithTimeProvider, only single-activationAfterAgentCallbackcontent 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.CloseFunc&afterRunPanic Safety (bigquery_agent_analytics_plugin.go):CloseFuncinsync.OnceValueso repeatedClose()calls from both callerdeferand launcher shutdown are idempotent and return the initial close error.afterRunwith deferredendInvocationandflushRunEndcleanup even ifpopUnclosedAgentSpanspanics.AppendRowsResponse.RowErrorsIsolation (batch_processor.go,config.go):AppendRowsResponse.RowErrorsfailures inappendChunkRows(including whenError == nilwith non-emptyRowErrors), counting dropped rows underDropStats.RowErrorDrops(included inTotalDrops) and resending remaining valid rows while preserving uncommittedstreamOffsetinExactlyOnceDeliverymode, unlessRowErrorsfollows an earlier ambiguous send inExactlyOnceDeliverymode, in which casestreamWriter.appendfails closed (offsetDesynced = true, counted underAppendFailureDrops) without replaying potentially committed survivors onto a rotated stream.ConfiglistsRowErrorsafter an attempt with an unknown outcome next toOutOfRangeandNotFoundamong the responses that drop the batch and replace the stream before the next one.Behavior change
AppendRowsResponse.RowErrorsrejections on unambiguous sends now drop only the rejected row indices (counted in newDropStats.RowErrorDropsandTotalDrops) and retry the remaining valid rows in the batch rather than failing/dropping the entire batch; whenRowErrorsfollows an ambiguous send inExactlyOnceDeliverymode, the uncertain batch fails closed without survivor replay and rotates the stream before the next independent batch.Plugin.Close()more than once is now idempotent (sync.OnceValue), and a panic duringafterRunspan unwinding still ends the invocation trace and flushes queued run-end rows whilerecoverCallbackcontains the panic.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 unjoinedfinish_taskretirements (unjoinedTaskRetirement), live open-activation ambiguity checks acrossagentStack[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 mapsafterAgentActions/afterAgentActionsRef, kept through the callback'sEventActions, recorded for every activation with after-agent callbacks before any pruning and kept while needed (needsAfterAgentActionsLocked,afterAgentCallbacksReturnedOnLockedoutside running after-agent callbacks (afterAgentCallbackRunsOfTrace), settled only once a starting activation is open (settleAfterAgentActionsOnLocked), bounded per parent byfoldPendingAfterAgentLockedexcept while a peer is open (hasOpenPeerLocked)), for post-retirement and same-tick callback recovery, and activation-aware provenance gating onunforwardedModelEventsafter errors), andO(1)-per-keyretiredActivationshull compaction (<= 3per 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 16dfacdfwithgo work init && go work use -r .(as in CI),-mod=readonly, go1.27.3 and the defaultGOMAXPROCS(24 on this machine), unless noted.gofmt -l .,GOWORK=off go mod tidy -diff,go build ./...andgo vet ./...are clean in the repository root and inplugin/agentanalytics. In a clone checked out at16dfacdf:git diff --check origin/main..HEADis clean,golangci-lint run --new-from-merge-base=origin/main ./...reports0 issues.in the repository root and inplugin/agentanalytics, and.github/scripts/apidiff.sh origin/mainreportsNo incompatible changes.plugin/agentanalytics:go test -p 1 -parallel 1 -race -shuffle=on -count=1 -v ./...passes (ok ... 251.859s, shuffle seed1794521085567369042, 636 top-level tests pass, 0 data races), as dogo test -p 1 -parallel 1 -race -count=1 ./...(ok ... 266.479s, 0 data races) andgo test -p 1 -parallel 1 -shuffle=on -count=1 -v ./...(ok ... 119.102s, shuffle seed1794521638689925797, 636 top-level tests pass).-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,TestStartingActivationKeepsSameAgentAfterAgentMapsandTestSettledAfterAgentPlacementSurvivesInterleavedEvent.TestAfterAgentRecoveryWithCopiedActionMaps_RunnerandTestCallbackAfterAgentActionMapspass under-race -count=10(20 of 20).go test -p 2 -count=1 ./...passes (114 packagesok, 0 failures).git archive 97404825with 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 besidesTestSameTickStartKeepsHeldAfterAgentEvent_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 asINVOCATION_ERROR, an unrecovered failure asINVOCATION_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_failurestill reports the failure there, but places the summary'sAGENT_RESPONSErow under the failing activation ofinner, and inTestSameTickStartKeepsHeldAfterAgentEvent_Runnerthe 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 at16dfacdf. The unit tests added with them use symbols that97404825does not have, so the mutants below pin them.RowErrorspartial-batch isolation,ExactlyOnceDeliveryoffset preservation, & ambiguous-send fail-closed guard:TestBatchProcessor_RowErrorsIsolation,TestBatchProcessor_DropStats,TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivorsCloseFuncsync.OnceValueidempotency &afterRunpanic cleanup:TestPlugin_CloseOnceAndAfterRunPanic,TestClose_SecondCallAfterCleanCloseSucceeds,TestGCSOffloading_CloseReportsTheCloseErrorsTestCleanAfterAgentEventKeepsPeerFailure_Runner,TestGuardlessRetirementKeepsAfterAgentEntry,TestRetiredAfterAgentEntriesStayBounded_Runner,TestPendingAfterAgentHull,TestAfterAgentCallbacksReturnedOn,TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner,TestRetiredAuthorBranchResolution,TestRetiredEventBranch,TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner,TestSettleRetiredResponseCredit,TestSettledAfterAgentEventPlacementTestRetireDrainedDescendants_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_RetiresSettledActivationTestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner,TestSubBranchEventKeepsEnclosingBranchFailure_Runner,TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner,TestOpenPeerRecoveryAfterManyPeersRetired_Runner,TestAfterAgentDoneBoundsRetiredEvents,TestResolveEventBranch,TestRetiredEventBranch,TestPeerRetirementsStayUncompactedWhilePeerOpen,TestAfterAgentEventOwnershipSettlesCreditTestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner,TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner,TestAfterAgentSharerResolvesEventBranch,TestOpenPeerRecoveryAfterManyPeersRetired_Runner,TestPeerRetirementsStayUncompactedWhilePeerOpen,TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner,TestAfterAgentCallbacksStillRunning,TestSameTickStartKeepsHeldAfterAgentEvent_Runner,TestStartingActivationKeepsSameAgentAfterAgentMaps,TestSettledAfterAgentPlacementSurvivesInterleavedEventpopAgentSpanonly under the earlier condition:TestCleanAfterAgentEventKeepsPeerFailure_Runner,TestGuardlessRetirementKeepsAfterAgentEntry.retireAgentAtLockedpruned; letting pruning delete a guardless entry that holds an after-agent event, an open span under it or a peer credit:TestGuardlessRetirementKeepsAfterAgentEntry.TestCleanAfterAgentEventKeepsPeerFailure_Runner,TestRetiredActivationSettlementAndHullConjuncts.TestCleanAfterAgentEventKeepsPeerFailure_Runner,TestCausalRecoveryOrderingAndProvenanceGuards.foldPendingAfterAgentLocked:TestRetiredAfterAgentEntriesStayBounded_Runner,TestPendingAfterAgentHull.excludedByEventTimestamp); not letting a pending hull own an event created after its members retired (eventAuthorLocked):TestPendingAfterAgentHull.needsAfterAgentActionsLockedthat 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.needsAfterAgentActionsLocked:TestAfterAgentCallbacksReturnedOn.afterAgentCallbacksReturnedOnLockeda no-op and not marking inpushAgentSpanthe callbacks that returned:TestAfterAgentCallbacksReturnedOn,TestCleanParallelIterationsBoundRetiredActivations_Runner.completeResponseWithEvent; keeping the event's own branch for a retired author incompleteResponseWithEvent:TestRecoveryWithoutOwnBranchSettlesRetiredAuthor_Runner,TestRetiredAuthorBranchResolution.resolveEventBranchLockedwhen activations on two branches can have created it; ignoring an activation on the event's branch itself ineventAuthorBranchesLocked:TestRetiredEventBranch.TestRetiredPeerRunAndAfterAgentEventsSettleOneCredit_Runner,TestSettleRetiredResponseCredit.consumeAfterAgentCreditLockedthat the credit was settled; lettingcreatedInRunignore when the activation started:TestSettleRetiredResponseCredit.eventSpanAt:TestSettledAfterAgentEventPlacement,TestCleanAfterAgentEventKeepsPeerFailure_Runner.completeResponseForEvent:TestSettledAfterAgentPlacementSurvivesInterleavedEvent,TestCleanAfterAgentEventKeepsPeerFailure_Runner.eventSpan):TestTraceManager_FinalResponseToolRow,TestTraceManager_AgentNesting,TestSettledAfterAgentEventPlacement.findAgent:TestCrossBranchEventAuthor,TestTraceManager_AgentNesting.findEventAgentLocked:TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner,TestCrossBranchEventAuthor,TestTraceManager_AgentNesting.findAgent's open activation incompleteResponseWithEvent; leaving out retired activations ineventAuthorBranchesLocked:TestCrossBranchRetiredPeerEventKeepsSiblingFailure_Runner,TestCrossBranchEventAuthor.eventAuthorBranchesLocked; ignoring creation provenance there; ignoring when open activations started there; leaving out swallowers there; tracking partial events withfindAgent:TestCrossBranchEventAuthor.TestEventCreatedBeforeLaterActivationStarted_Runner,TestEventCreatedBeforeOpenActivationsStarted.TestEventCreatedBeforeOpenActivationsStarted,TestRetireDrainedDescendants_NestedRetiredCustomAncestors.TestEventCreatedBeforeOpenActivationsStarted,TestFixedTimeProviderRecovery_Runner.TestEventCreatedBeforeLaterActivationStarted_Runner,TestEventCreatedBeforeOpenActivationsStarted,TestCrossBranchEventAuthor.TestEventCreatedBeforeLaterActivationStarted_Runner.TestLookalikeSubAgentOnHelperGoroutine_Runner,TestRunningLookalikeLocked.enclosingOpenSpanLockedreturn a retired span:TestRunningLookalikeLocked.TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner,TestClearLastPartialForEvent.clearLastPartialinonEvent:TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner.clearLastPartialForEvent; dropping its provenance step; dropping its credit step:TestClearLastPartialForEvent.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 itsEventActions:TestAfterAgentRecoveryAfterEarlierProgressWithHeldChildEvent_Runner.soleOpenAuthorLocked; ignoringafterAgentEventSeen:TestOpenPeerRecoveryAfterConcurrentPeerFinished_Runner,TestAfterAgentFunctionResponseSettlesOwnCredit_Runner,TestSoleOpenAuthor.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.TestRetiredAuthorEventWhilePeerOpen.TestAfterAgentCreditSettlesOnlyItsOwnActivation.TestLookalikeParentPrefersRunningGoroutine_Runner,TestRunningLookalikeLocked.ownResponsecheck:TestReconcileConcurrentResponseOnPopKeepsInheritedPeerResponse.runningLookalikeLockedreturn the last-started lookalike:TestAfterAgentRecoveryAfterConcurrentPeerRetired_Runner.afterAgentSharerLockedabsorption inselectResponseOwnerWithIDLocked:TestRetiredAuthorEventWhilePeerOpen,TestAfterAgentRecoveryWithOpenPeerAwaitingEvent_Runner.RowErrorsisolation:TestBatchProcessor_RowErrorsIsolation,TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors.TestBatchProcessor_AmbiguousSendRowErrorsDoesNotReplaySurvivors.sync.OnceValuearoundCloseFunc:TestPlugin_CloseOnceAndAfterRunPanic,TestClose_SecondCallAfterCleanCloseSucceeds.afterAgentDoneAtbound incanOwnEventAt; not recording that time inmarkAfterAgentCallbacksReturnedOnLocked:TestAfterAgentEventHeldPastNextActivationKeepsRecovery_Runner,TestAfterAgentDoneBoundsRetiredEvents.markAfterAgentDone; bounding an event that carries the activation's after-agent maps by that time incanOwnEventAt; not passing that an event carries the activation's maps tocanOwnEventAtineventAuthorLocked; keeping the first member's time in a pending hull; keeping the first middle member's time in a compacted hull:TestAfterAgentDoneBoundsRetiredEvents.resolveEventBranchLockedwithout looking at other branches:TestSubBranchEventKeepsEnclosingBranchFailure_Runner,TestResolveEventBranch.TestSubBranchEventKeepsEnclosingBranchFailure_Runner,TestRetiredEventBranch.TestRetiredBranchRecoveryWhileLaterSiblingOpen_Runner,TestResolveEventBranch.findAgent's activation infindEventAgentLocked:TestCrossBranchEventAuthor,TestTraceManager_AgentNesting.TestOpenPeerRecoveryAfterManyPeersRetired_Runner,TestPeerRetirementsStayUncompactedWhilePeerOpen.selectResponseOwnerWithIDLocked; settling the credit of a sharer that cannot own the event incompleteResponseWithEvent:TestAfterAgentEventOwnershipSettlesCredit.ownsAfterAgentEvent; dropping the timestamp test ofownsAfterAgentEvent:TestAfterAgentEventOwnershipSettlesCredit,TestClearLastPartialForEvent.resolveEventBranchLocked, so that activations on a branch under its branch make it no one's:TestEnclosingBranchAfterAgentRecoveryWhileSubBranchOpen_Runner,TestEnclosingBranchAfterAgentCreditWhileSubBranchOpen_Runner,TestAfterAgentSharerResolvesEventBranch.clearLastPartialForEvent:TestAfterAgentSharerResolvesEventBranch.foldPendingAfterAgentLocked:TestOpenPeerRecoveryAfterManyPeersRetired_Runner,TestPeerRetirementsStayUncompactedWhilePeerOpen.foldPendingAfterAgentLocked; folding entries whose callbacks were seen to return while a peer is open:TestPeerRetirementsStayUncompactedWhilePeerOpen.pushAgentSpan; ignoring them at an agent's end inpopAgentSpan:TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner.TestAfterAgentCallbacksStillRunning,TestAfterAgentCallbackRunningAgentKeepsItsMaps_Runner.TestAfterAgentCallbacksStillRunning.pushAgentSpan:TestSameTickStartKeepsHeldAfterAgentEvent_Runner,TestStartingActivationKeepsSameAgentAfterAgentMaps.onEventtoemitSessionEventSignals:TestCleanAfterAgentEventKeepsPeerFailure_Runner.clearLastPartialForEvent:TestAfterAgentSharerResolvesEventBranch.selectResponseOwnerWithIDLocked:TestAfterAgentEventOwnershipSettlesCredit.