Skip to content

feat(agentanalytics): add bounded retired-activation ledger and after-agent detection - #2389

Merged
wojtas000 merged 1 commit into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2182-5-retired-activation-ledger
Nov 19, 2026
Merged

wojtas000 merged 1 commit into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2182-5-retired-activation-ledger

Conversation

@haiyuan-eng-google

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

Copy link
Copy Markdown
Contributor

Please ensure you have read the contribution guide before creating a pull request.

Stacked PR: depends on #2180, #2381, and #2380; review the top commit only.

Linked issue

1. Link the issue this change is for. Required for everything except small
documentation and typo fixes. If no issue exists yet, please open one first.

2. Describe the change:

If applicable, please follow the issue templates to provide as much detail as
possible.

Problem:
A clear and concise description of what the problem is.

Agent activations in plugin/agentanalytics can emit delayed AfterAgent callback deltas or late events after an activation span pops from the live stack, including across concurrent peer activations, wrapped agents, other registered AfterAgentCallback plugins (running either before or after agentanalytics), live replacement of StateDelta/ArtifactDelta maps, replayed retirement/settlement passes, and detached/unjoined or multi-parent enclosing branches. Without conservative after-agent callback detection, a strictly bounded O(R + U) retired-activation ledger, unjoined-task-preserving hull compaction, and replay-safe response-credit settlement backed by monotonic source-span credit watermarks, attribution predicates in the follow-up lifecycle wire-up cannot distinguish legitimate post-pop events owned by a retired activation from unrelated peer events without unbounded growth, compacted-replay credit theft, or false exclusion.

Solution:
A clear and concise description of what you want to happen and why you choose
this solution.

Part 5 of 6 split out from #2182, stacked on #2380, implementing conservative after-agent callback detection, the bounded retired-activation ledger, cap-8 pending after-agent hull compaction with a hard per-invocation cap of 128, O(R + U) per-pass ledger indexing and shrinking, and replay-safe response-credit settlement and event-ownership predicates:

  • Conservative agent and plugin after-agent callback detection (plugin/agentanalytics/bigquery_agent_analytics_plugin.go, plugin/agentanalytics/trace_manager.go):
    • Adds agentHasAfterAgentCallbacks (with lookupAgentAfterCBLayout / fieldPathExported / safeFieldByIndex checking llmagent.Config and exported wrapper Agent chains up to 3 hops, treating only ADK's concrete *agent.agent as terminal owner of afterAgentCallbacks so an opaque wrapper exposing an empty callback slice while hiding a delegate or holding a typed-nil inner Agent still fails closed conservatively to true).
    • Adds contextHasAfterAgentPlugin (inspecting all other registered plugins both before and after selfPlugin since ADK builds the single after-agent event after every AfterAgentCallback runs, returning conservative true when self != nil and PluginManager or self cannot be resolved, returning true when any plugins element is nil, unexpected type, or lacks a reflect.Func afterAgentCallback field or panics while inspecting PluginManager, and returning false when all entries are verified callback-free or self == nil with no PluginManager), discoverPluginManagerCtxKey / probePluginManagerCtxKey, traceManager.selfPlugin, and agentChildren.hasAfterAgentCallbacks propagation into spanRecord in pushAgentSpan.
    • Extracts newBigQueryAgentAnalyticsPluginWithTraces so plugin identity tests inspect traceManager directly without adding test-only fields to pluginState.
  • Bounded O(R + U) retiredActivation ledger, length-prefixed llmKey/parseLLMKey, & hasUnjoinedTask hulls (plugin/agentanalytics/trace_manager.go):
    • Adds retiredActivation, popRetirement, foldedCredit, agentIdentityKey, length-prefixed llmKey/parseLLMKey (<pathLen>:<path><nameLen>:<name>:<branch>), activeSwallower, afterAgentState, spanRecord provenance/lifecycle fields (ownResponse, startPlatformTime, hasAfterAgentCallbacks, hasCustomUUIDProvider, runEndSeq, runEndPlatformTime, popRetirement, recordedAfterAgentCredit, recordedModelCredits), and invocationTrace ledger fields (unrespondedRetiredTools, retiredActivations, creditGroupRem, nextCreditGroupID).
    • Retains the [2]unsafe.Pointer map pins returned by callbackAfterAgentActions on popRetirement / retiredActivation.afterAgentActionsRef so captured maps cannot have their addresses reused across GC if a callback replaces StateDelta or ArtifactDelta.
    • Tracks hasUnjoinedTask bool explicitly across compactKey, foldRetiredCapHull, and foldPendingAfterAgentWithIndexLocked (combined via ||, while keeping completedOrTask/joinedAtRetire &&-folded for excludedByEventTimestamp) so folding an unjoined task with a returned non-task preserves unjoinedTaskRetirement() == true and keeps post-retirement events attributable.
    • Builds a per-pass unrespondedRetiredIndex (newUnrespondedRetiredIndexLocked) once per retirement, pruning, cap-enforcement, and pending-fold pass (O(R + U) instead of O(R * U) parseLLMKey scans), and calls shrinkRetiredActivationsLocked to release oversized inv.retiredActivations backing arrays after pruning (even when pruneSettledRetiredActivationsWithIndexLocked finds no > 3-member buckets).
    • Enforces a hard per-invocation ledger bound (128 entries) alongside cap-8 pending after-agent hull compaction (maxPendingAfterAgent = 8), preserves foldedCredits links (including afterAgentCredit provenance) into creditGroupRem across partial cap-128 group folds so surviving peers keep balanced group capacities without credit leaks or peer credit theft, and guards detached/unjoined child activations against inheriting an ancestor's parentRetiredAtPlatformTime.
  • Replay-safe response-credit settlement & monotonic source-span credit watermarks (plugin/agentanalytics/trace_manager.go):
    • Tracks granted vs consumed credits separately across duplicate/replayed retirement merges and persists monotonic recordedAfterAgentCredit and recordedModelCredits high-water marks on the source spanRecord, so recordRetiredActivationLocked grants only net-new credit deltas (creditSettled: false on zero-delta replays), recordRetiredActivationEntryLocked applies strictly higher incremental deltas on settled entries only when a prior grant watermark exists (preventing synthetic creditSettled duplicate merges from re-arming), and replaying an already-retired activation after hull compaction or pruning cannot allocate fresh credits or spend a later peer's unrespondedRetired count.
    • Implements remainingCredits, allocCreditGroupIDLocked, settleCreditGroupIfExhaustedLocked, mergeCreditGroupsLocked, clearExhaustedAfterAgentCreditsLocked, consumeAfterAgentCreditLocked (guarded on live creditGroupRem[gid] > 0 balances), settleRetiredResponseCreditLocked (guarded on creditGroupRem[gid] > 0 across both afterAgentCredit and modelCredits paths as well as foldedCredits, and honoring canOwnEventCreatedAt for post-retirement mapless afterAgentCredit entries and cap-128 hulls), createdInRun, unjoinedTaskRetirement, canOwnEventCreatedAt, canOwnEventAt, excludedByEventTimestamp, hasGuardedRetiredPeerForEventLocked, soleOpenAuthorLocked, and provenAfterAllRetiredLocked.
  • Unit & regression tests + module dependencies (plugin/agentanalytics/bigquery_agent_analytics_plugin_test.go, plugin/agentanalytics/trace_manager_test.go, plugin/agentanalytics/after_agent_events_test.go, plugin/agentanalytics/go.mod, plugin/agentanalytics/go.sum):
    • Covers TestContextHasAfterAgentPlugin (including nil/unreadable PluginManager.plugins elements failing closed), TestDiscoverPluginManagerCtxKey, TestDiscoverPluginManagerCtxKey_LazyAndZeroSideEffects, TestAgentHasAfterAgentCallbacks (including opaque empty-slice wrappers hiding a delegate and typed-nil inner Agent wrapper delegates failing closed), TestParseLLMKey, TestLLMKeyAndParseLLMKey_NULBytesAndDelimiters, TestRetiredActivation_ActionMapPinAcrossLiveReplacement, TestRetiredActivationLedger_DetachedChildGoroutineNotStampedByCustomParentReturn, TestRetiredActivation_PreservesHasUnjoinedTaskAcrossCompaction, TestRetiredActivationLedger_CompactedReplayDoesNotStealLaterWorkerCredit, TestRetiredActivationLedger_IndexAndShrinkCapacity, TestRetiredActivationLedger_PartialCapFoldSharedGroupAfterAgent, TestRetiredActivationLedger_PartialCapFoldSharedGroupModelCredits, TestRetiredActivationLedger_IncrementalCreditGrantAfterSettled, TestRetiredActivationLedger_CapFoldPostRetirementAfterAgentCredit, detached unjoined child and multi-parent hull bounds, hard cap 128 eviction/compaction, separate granted vs consumed credit replay invariants, and coordinator-forwarding finish_task call_0 reuse regression coverage.
    • Promotes go.opentelemetry.io/otel and go.opentelemetry.io/otel/sdk from indirect to direct requires in plugin/agentanalytics/go.mod / go.sum for the new OTel zero-side-effect runner tests (TestDiscoverPluginManagerCtxKey_LazyAndZeroSideEffects).

Behavior change

What behaves differently for someone already on the current release?

Write "nothing" if that is the answer. Bug fixes count: a fix that alters an
observable result is still a behavior change.

Relative to #2380's head: pushAgentSpan records hasAfterAgentCallbacks on spanRecord, llmKey/parseLLMKey encode <pathLen>:<path><nameLen>:<name>:<branch> length-prefixed keys, and newBigQueryAgentAnalyticsPlugin stores a weak selfPlugin pointer on traceManager so after-agent callback presence on agents and other registered plugins can be inspected without retaining the plugin. The retired-activation ledger, hard per-invocation cap, hull compaction, credit-settlement helpers, and event-ownership predicates added in this commit are internal traceManager state and helpers unit-tested here in Part 5 and wired into live pushAgentSpan/popAgentSpan/onEvent callback dispatch in the Part 6 follow-up PR (0 public API delta relative to #2380's head; relative to main, the stacked branch carries only the 9 additive exports introduced earlier in #2180, with 0 incompatible API changes).

Testing Plan

Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes.

Unit Tests:

  • All unit tests pass locally.

With your source change reverted and your tests kept, which test fails?

Name it. If nothing fails, the tests do not yet cover the change. This is the
cheapest moment to find that out.

TestContextHasAfterAgentPlugin, TestDiscoverPluginManagerCtxKey, TestDiscoverPluginManagerCtxKey_LazyAndZeroSideEffects, TestAgentHasAfterAgentCallbacks, TestParseLLMKey, TestLLMKeyAndParseLLMKey_NULBytesAndDelimiters, TestRetiredActivation_ActionMapPinAcrossLiveReplacement, TestRetiredActivationLedger_DetachedChildGoroutineNotStampedByCustomParentReturn, TestUnjoinedParentDoesNotStampParentRetiredTime, TestRetiredActivationSettlementAndHullConjuncts, TestSoleOpenAuthor, TestAfterAgentCreditSettlesOnlyItsOwnActivation, TestProvenAfterAllRetiredLockedAndExclusionEdges, TestRetiredActivation_PreservesHasUnjoinedTaskAcrossCompaction, TestRetiredActivationLedger_CompactedReplayDoesNotStealLaterWorkerCredit, TestRetiredActivationLedger_IndexAndShrinkCapacity, TestRetiredActivationLedger_PartialCapFoldSharedGroupAfterAgent, TestRetiredActivationLedger_PartialCapFoldSharedGroupModelCredits, TestRetiredActivationLedger_IncrementalCreditGrantAfterSettled, and TestRetiredActivationLedger_CapFoldPostRetirementAfterAgentCredit.

Please include a summary of passed go test results (verified at commit 622438b85a0647901d70e9897eac89a9881aefed):

  • gofmt -l plugin/agentanalytics, git diff --check, and GOWORK=off go -C plugin/agentanalytics mod tidy -diff: clean (rc=0).
  • go -C plugin/agentanalytics vet ./... and golangci-lint run --max-same-issues=0 --max-issues-per-linter=0 ./... (in plugin/agentanalytics): PASS (0 issues.).
  • apidiff between #2380 (01821a6c) and #2389 (622438b8) for google.golang.org/adk/plugin/agentanalytics (plus 0 modified files outside plugin/agentanalytics): 0 exported API changes (apidiff_bytes=0).
  • Targeted go -C plugin/agentanalytics test -race -mod=readonly -count=1 -run 'TestRetiredActivation|TestProvenAfterAllRetired|TestSoleOpenAuthor|TestAfterAgent|TestAgentHasAfterAgentCallbacks|TestContextHasAfterAgentPlugin|TestDiscoverPluginManagerCtxKey|TestParseLLMKey|TestLLMKey|TestUnjoinedParent|TestPlugin_FinishTask_Call0Reuse|TestContextLookups' ./...: PASS (13.040s).
  • Full stack-tip go -C plugin/agentanalytics test -race -mod=readonly -count=1 -shuffle=on ./...: PASS (412.142s).

Manual End-to-End (E2E) Tests:

Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix.

Not manually tested end-to-end against a live BigQuery dataset in this PR; covered by deterministic unit, race, and newTestRunner execution tests in plugin/agentanalytics.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

Additional context

Add any other context or screenshots about the feature request here.

Stacked PR order: main <- #2180 <- #2381 <- #2380 <- #2389 (#2375 has merged onto main). Until the parent PRs merge into main, GitHub's cumulative diff against main includes commits from #2180, #2381, and #2380; please review the top commit only for Part 5's changes relative to #2380's head.

@haiyuan-eng-google
haiyuan-eng-google requested a review from a team as a code owner November 17, 2026 13:04

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2389 (review).

wojtas000
wojtas000 previously approved these changes Nov 18, 2026

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving this part. The ledger has no caller outside tests until the next part lands, so nothing in a real run changes yet, and the restored after-agent detection costs well under a microsecond per agent start.

Optional notes, none blocking here, that are worth settling in the part that wires the ledger in:

  • Several field comments say pushAgentSpan or popAgentSpan set popRetirement, startPlatformTime and hasCustomUUIDProvider, which this PR doesn't do yet. The retiredPeerCount comment describes an exemption completeResponse doesn't implement yet.
  • The doc block above pruneOrphanedCreditGroupsLocked describes pruneSettledRetiredActivationsLocked.
  • contextHasLaterAfterAgentPlugin checks only plugins registered after this one, but an earlier plugin's AfterAgentCallback can also write StateDelta.
  • Pinned ledger entries have no cap while a peer stays open: TestPeerRetirementsStayUncompactedWhilePeerOpen keeps 15.

@wojtas000

Copy link
Copy Markdown
Contributor

This conflicts with main in trace_manager.go and trace_manager_test.go. Could you resolve it once #2380 is rebased?

These PRs touch the same files, so could you rebase them as one stack, each on top of the one before: #2375, #2180, #2381, then #2380 and #2389? I'll merge each one as soon as it's up to date with main and green.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 Thanks! I rebased #2389 cleanly onto #2380 at the top of the 5-PR linear stack (main <- #2375 <- #2180 <- #2381 <- #2380 <- #2389), updated the PR description, and confirmed all 15 CI checks are green across every PR in the stack.

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2389 (review).

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks @wojtas000 and @caohy1988 for the thorough reviews! I have rebased the stack onto the updated parent branches and updated the top commit to address every point:

  1. Blocking finish_task call_0 reuse (@caohy1988): Fixed in parent PR feat(agentanalytics): add ToolResultClassifier hook and schema lifecycle callbacks #2180 and rebased through fix(agentanalytics): suppress recovered tool completions and log retryandreflect errors #2381 -> feat(agentanalytics): add event provenance, context walkers, and callback stack helpers #2380 -> feat(agentanalytics): add bounded retired-activation ledger and after-agent detection #2389. I also added an explicit coordinator-forwarding runner regression test here in feat(agentanalytics): add bounded retired-activation ledger and after-agent detection #2389 to pin that reused provider call_0 tool-call IDs on finish_task forward cleanly without collision or misattribution.
  2. UUID-provider ledger bounds (512-entry cap with folding and completed-run compaction) (@caohy1988): Fixed in parent PR feat(agentanalytics): add event provenance, context walkers, and callback stack helpers #2380 and inherited cleanly here after rebasing onto feat(agentanalytics): add event provenance, context walkers, and callback stack helpers #2380's updated head.
  3. Conservative unknown vs. known-no-after-agent + scanning all plugins before and after selfPlugin (@wojtas000, @caohy1988): Renamed contextHasLaterAfterAgentPlugin to contextHasAfterAgentPlugin and updated it to check every other plugin in PluginManager both before and after selfPlugin (since ADK builds the single after-agent event only after all AfterAgentCallbacks complete). When self != nil and either PluginManager or self cannot be resolved (for example, when wrapped inside a composing plugin or when Context shadows PluginManager), it now conservatively returns true so legitimate post-retirement after-agent events are never falsely excluded, while returning false when PluginManager and self are resolved with no other AfterAgentCallback plugin (and preserving false when self == nil and no PluginManager is on ctx for direct traceManager unit tests).
  4. Hard per-invocation cap (128) and length-prefixed llmKey/parseLLMKey (@wojtas000, @caohy1988): Added a hard per-invocation cap of 128 retired activations on invocationTrace.retiredActivations alongside the per-bucket cap-8 pending after-agent hull compaction, and replaced NUL-delimited llmKey/parseLLMKey encoding with length-prefixed <pathLen>:<path><nameLen>:<name>:<branch> keys so arbitrary NUL bytes or colons in path, agent, or branch names cannot collide or misparse.
  5. Separate granted vs. consumed credits on replay (@caohy1988): Split granted-credit state from consumed-credit accounting so duplicate or replayed retirement/merge passes are idempotent and cannot re-grant exhausted credits or double-consume a sibling activation's credit.
  6. Detached unjoined child parent-bound guard (@caohy1988): Guarded parent retirement timestamp propagation so a detached/unjoined child activation does not inherit an ancestor's parentRetiredAtPlatformTime when retired without joining its enclosing parent run.
  7. Doc comment placement and accuracy (@wojtas000): Moved and tightened doc comments so each comment sits directly above the declaration it documents and accurately describes the conservative plugin check, ledger bounds, and settlement invariants.
  8. Real newTestRunner in TestDiscoverPluginManagerCtxKey_LazyAndZeroSideEffects (@caohy1988): Updated TestDiscoverPluginManagerCtxKey_LazyAndZeroSideEffects to exercise newTestRunner directly while asserting lazy sync.Once key discovery and zero OTel spans, BigQuery writes, or traceManager side effects.

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2389 (review).

@haiyuan-eng-google
haiyuan-eng-google force-pushed the fix/bqaa-2182-5-retired-activation-ledger branch from 006e5e7 to 622438b Compare November 19, 2026 19:06
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks @caohy1988 and @wojtas000 for the thorough reviews — rebased cleanly across #2180 (621b5462) -> #2381 (8f3621c8) -> #2380 (01821a6c) -> #2389 (622438b8) and addressed every remaining item:

  1. Unjoined-task preservation across compaction folds (Blocking Add continuous integration #3; trace_manager.go, after_agent_events_test.go):

    • Added monotonic hasUnjoinedTask bool to retiredActivation (set when rec.taskMode && !rec.completed && !rec.runDone, normalized when recording entries, checked in unjoinedTaskRetirement(), included in compactKey, and folded with || in both foldRetiredCapHull and foldPendingAfterAgentWithIndexLocked) while keeping completedOrTask and joinedAtRetire &&-folded for excludedByEventTimestamp.
    • Folding an unjoined task with a returned non-task now preserves unjoinedTaskRetirement() == true so post-retirement events from the detached task are not dropped or misattributed to a later worker. Pinned in TestRetiredActivation_PreservesHasUnjoinedTaskAcrossCompaction.
  2. Monotonic source-span credit watermarks, incremental grants, & cap-128 group preservation (Blocking Fix lint errors #4; trace_manager.go, after_agent_events_test.go):

    • Added monotonic recordedAfterAgentCredit and recordedModelCredits high-water marks on spanRecord and updated recordRetiredActivationLocked to grant only net-new credit deltas (keeping creditSettled: false on zero-delta replays so live uncompacted entries are not prematurely cleared).
    • Updated recordRetiredActivationEntryLocked to apply strictly higher incremental deltas on already-settled entries only when a recorded grant watermark (grantedAfterAgentCredit || grantedModelCredits > 0) already existed, clearing creditSettled and funding its credit group so legitimate incremental grants settle reliably while synthetic creditSettled duplicate merges do not re-arm.
    • Preserved foldedCredits links (including afterAgentCredit provenance) into creditGroupRem across foldRetiredCapHull / enforceRetiredActivationCapWithIndexLocked (avoiding subtracting folded credits from surviving peers' shared creditGroupRem), guarded consumeAfterAgentCreditLocked and settleRetiredResponseCreditLocked on creditGroupRem[gid] > 0, and allowed post-retirement canOwnEventCreatedAt matching in settleRetiredResponseCreditLocked for mapless afterAgentCredit entries and foldedCredit.afterAgentCredit cap-128 hulls.
    • Replaying an already-retired activation after compaction or pruning grants 0 credits and cannot create a fresh credit group or spend another worker's unrespondedRetired count, while partial cap-128 folds neither strand surviving peer or post-retirement afterAgentCredit events nor allow modelCredits theft from later peers. Pinned in TestRetiredActivationLedger_CompactedReplayDoesNotStealLaterWorkerCredit, TestRetiredActivationLedger_PartialCapFoldSharedGroupAfterAgent, TestRetiredActivationLedger_PartialCapFoldSharedGroupModelCredits, TestRetiredActivationLedger_IncrementalCreditGrantAfterSettled, and TestRetiredActivationLedger_CapFoldPostRetirementAfterAgentCredit.
  3. Conservative fail-closed agentHasAfterAgentCallbacks & contextHasAfterAgentPlugin (Smaller Initial commit of Go ADK #2; bigquery_agent_analytics_plugin.go, trace_manager.go, trace_manager_test.go):

    • agentHasAfterAgentCallbacks now treats only ADK's concrete *agent.agent (vt.PkgPath() == agentPkgPath && vt.Name() == "agent") as terminal owner of afterAgentCallbacks, removes the !hasEmptyAfterCB bypass on failed delegate unwraps, and fails closed (true) when an inner Agent delegate holds a nil/typed-nil pointer at hop > 0.
    • contextHasAfterAgentPlugin now fails closed (true) whenever any element in PluginManager.plugins is nil, has an unexpected type, lacks a reflect.Func afterAgentCallback field (for both non-nil self and self == nil paths), or panics while inspecting a resolved PluginManager. Pinned in TestAgentHasAfterAgentCallbacks and TestContextHasAfterAgentPlugin.
  4. O(R + U) per-pass ledger indexing & capacity shrinking (Smaller Add continuous integration #3; trace_manager.go, after_agent_events_test.go):

    • Added unrespondedRetiredIndex (newUnrespondedRetiredIndexLocked), constructed once per pass across recordRetiredActivationsAtLocked, pruneSettledRetiredActivationsWithIndexLocked, enforceRetiredActivationCapWithIndexLocked, and foldPendingAfterAgentWithIndexLocked, removing repeated parseLLMKey scans inside the R loop (O(R + U)).
    • Added shrinkRetiredActivationsLocked() and wired it across every pruning, compaction, and cap-enforcement exit path (including the !needsCompaction early return in pruneSettledRetiredActivationsWithIndexLocked) so oversized backing arrays shrink after pruning. Pinned in TestRetiredActivationLedger_IndexAndShrinkCapacity.
  5. Inherited #2180 / #2381 / #2380 fixes & verification at 622438b8:

    • Inherited fixes in #2180 (retireFailedTaskAttempts timestamp, finishedTaskLocked earliest-recorded tie-breaker and overruledEndingCallIDs, pre-lock platform.Now(ctx), reconciled evicted+restored completion, sanitized logger payloads), #2381 (dispatch-scoped completedTools retirement, recovered finish_task sentinel attempts), and #2380 (allowlisted directStructField walkers, compacted evicted/late UUID ledgers, branch fail-closed checks) are cleanly rebased underneath.
    • gofmt -l plugin/agentanalytics, git diff --check, GOWORK=off go -C plugin/agentanalytics mod tidy -diff, go -C plugin/agentanalytics vet ./..., and golangci-lint run --max-same-issues=0 --max-issues-per-linter=0 ./... (0 issues.): clean.
    • apidiff vs #2380 (01821a6c): 0 API changes (apidiff_bytes=0).
    • Targeted go -C plugin/agentanalytics test -race -mod=readonly -count=1 -run 'TestRetiredActivation|TestProvenAfterAllRetired|TestSoleOpenAuthor|TestAfterAgent|TestAgentHasAfterAgentCallbacks|TestContextHasAfterAgentPlugin|TestDiscoverPluginManagerCtxKey|TestParseLLMKey|TestLLMKey|TestUnjoinedParent|TestPlugin_FinishTask_Call0Reuse|TestContextLookups' ./...: PASS (13.040s).
    • Full stack-tip go -C plugin/agentanalytics test -race -mod=readonly -count=1 -shuffle=on ./...: PASS (412.142s).

@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 length-prefixed llmKey encoding and the schema readiness tests (failed view, manual sync interrupting startup, closure during the final view operation) look good. There are still a few correctness problems in the retirement and credit ledger, though. The first two reproduce with targeted tests that fail at this head and pass at the merge base.

  • Race between buffered response delivery and a later error callback (trace_manager.go ~9021, ~9052): delivery pulls a later attempt's live EventActions through the weak pointer and reads its map fields while that attempt's error callback can replace StateDelta on its own goroutine; the invocation mutex only covers the reader. The race detector flags exactly that read/write pair. Capturing an immutable dispatch identity when the error is recorded would avoid touching another goroutine's actions.
  • A failed response batch can swap two workers' completion spans (trace_manager.go ~8314, ~8368): when an earlier plugin handled a trailing finish_task, analytics has no record of that attempt, so the fallback searches other activations and retires the older worker's successful attempt with the same call ID. Both AGENT_COMPLETED span IDs came out swapped in five of five runs. Once the leading action maps identify the batch owner, only that activation's attempts should be retired.
  • Duplicate retirement merge drops afterAgentEventSeen (trace_manager.go ~1967-2044): the merge ORs the other monotonic callback/provider flags but not this one, so replaying an entry with it set into one without leaves it false. That stale value then drives map recapture (~2042) and post-retirement ownership (~2549), so an activation whose single after-agent event was already delivered can still own a later event and soleOpenAuthorLocked can't prove the real author. A logical OR plus a regression test covering both replay orders would fix it.
  • Folded credits mix kinds (trace_manager.go ~1348, ~1442): a post-retirement event is admitted if any matching credit is an after-agent credit, but then all positive groups for the identity are merged, so a replayed callback can spend a model-response credit belonging to a worker that finished earlier. Keeping separate balances per credit kind through compaction would prevent it.
  • Unjoined tasks stay eligible forever (trace_manager.go ~1492, ~1355): a task unjoined at retirement is treated as eligible for any later creation time, ignoring the recorded parent-join and callback-completion times, so it can consume credit for an event created after its parent joined and starve the worker's own response.
  • Credit storage isn't bounded by the 128-entry cap (trace_manager.go ~2058, ~2965, ~979): each retirement gets its own group and compaction copies each one into foldedCredits, so with a single identity going from 256 to 512 retirements grows creditGroupRem from 256 to 512 and foldedCredits from 129 to 385. Consolidating groups held only by the compacted entry, and including both structures in the bound test, would close that.

Smaller: action-map settlement during pruning (~2699, ~1768) doesn't reuse the per-pass index and rescans every outstanding key for each retained map, so cost grows with retirements × outstanding keys under the invocation lock.

The full race-enabled package suite, build, vet, go mod tidy -diff and gofmt are clean at this head.

wojtas000
wojtas000 previously approved these changes Nov 19, 2026

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving. The unjoined-task flag now survives both compaction folds, replayed retirements only grant net-new credit, and the after-agent detectors fail closed; reverting each one fails its new test. The ledger still has no production caller, so the wiring PR is where it will need end-to-end coverage. Optional: flipping the missing-field branch in contextHasAfterAgentPlugin back to false leaves the tests green.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 Rebased cleanly onto #2380 (28b2b88f, stack main <- #2381 <- #2380 <- #2389) -> b5e7e1d9 (0-byte diff in plugin/agentanalytics/ relative to the approved tree). CI is running now.

wojtas000
wojtas000 previously approved these changes Nov 19, 2026

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-approving after the rebase onto main. The commit is the same patch I approved earlier today.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 Rebased cleanly onto #2380 (402b155c, on main b758093d) -> 483a00b8 (0-byte diff in plugin/agentanalytics/ relative to the approved tree). CI is running now.

@haiyuan-eng-google
haiyuan-eng-google dismissed wojtas000’s stale review November 19, 2026 21:42

The merge-base changed after approval.

@haiyuan-eng-google
haiyuan-eng-google force-pushed the fix/bqaa-2182-5-retired-activation-ledger branch from b5e7e1d to 483a00b Compare November 19, 2026 21:42
wojtas000
wojtas000 previously approved these changes Nov 19, 2026

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-approving after the rebase onto main. The commit is the same patch I approved earlier today.

Implement after-agent callback detection, the bounded retired-activation ledger, pending after-agent hull compaction, and response-credit ownership predicates in plugin/agentanalytics:

- Add agentHasAfterAgentCallbacks (across up to 3 exported agent wrapper hops, treating only ADK's base *agent.agent as terminal callback owner and failing closed conservatively on opaque wrappers even with an empty afterAgentCallbacks slice or typed-nil inner Agent delegates) and contextHasAfterAgentPlugin (checking all other registered plugins via lazy PluginManager discovery, failing closed to true when PluginManager, self, or any plugin element/afterAgentCallback field cannot be verified or panics during inspection).

- Record retiredActivation and popRetirement state with [2]unsafe.Pointer pins for StateDelta and ArtifactDelta maps across live replacement, length-prefixed llmKey/parseLLMKey (<pathLen>:<path><nameLen>:<name>:<branch>) lookups, cap-8 pending after-agent hull compaction, monotonic hasUnjoinedTask tracking preserved via || across compaction folds, per-pass O(R+U) unrespondedRetiredIndex matching, shrinkRetiredActivationsLocked backing-array release, and a hard per-invocation cap of 128 retired activations whose hulls preserve foldedCredits links (including afterAgentCredit provenance for post-retirement mapless settlement) into creditGroupRem across partial group folds.

- Track granted vs consumed response credits separately alongside monotonic recordedAfterAgentCredit and recordedModelCredits watermarks on source spanRecord values so replays apply only net-new incremental deltas (re-arming settled entries only when a recorded grant watermark already existed without re-arming synthetic creditSettled-only merges), guard credit consumption on live creditGroupRem balances, and keep detached unjoined child activations free of parentRetiredAtPlatformTime.

- Add unit and regression coverage for plugin/agent callback detection (including typed-nil inner wrapper delegates), newTestRunner lazy discovery with zero side effects, map-pin retention, unjoined-task hull preservation, partial cap-128 shared credit-group folds (afterAgentCredit, modelCredits, and post-retirement mapless settlement), incremental credit grants after settlement, compacted-replay credit safety, per-pass index + shrink bounds, and coordinator forwarding with reused finish_task call_0 IDs.
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 #2380 merged — rebased #2389 cleanly onto main (0fe06155, dropping the merged #2380 commit) -> 51c5ce29 (1 commit above main, 0-byte diff in plugin/agentanalytics/ relative to the approved tree). CI is running now.

@haiyuan-eng-google
haiyuan-eng-google dismissed wojtas000’s stale review November 19, 2026 21:51

The merge-base changed after approval.

@haiyuan-eng-google
haiyuan-eng-google force-pushed the fix/bqaa-2182-5-retired-activation-ledger branch from 483a00b to 51c5ce2 Compare November 19, 2026 21:51

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-approving after the rebase onto main. The commit is the same patch I approved earlier today.

@wojtas000
wojtas000 merged commit b4383d8 into google:main Nov 19, 2026
15 checks passed
indurireddy-TF pushed a commit to indurireddy-TF/adk-go_local that referenced this pull request Nov 24, 2026
…oogle#2389)

Implement after-agent callback detection, the bounded retired-activation ledger, pending after-agent hull compaction, and response-credit ownership predicates in plugin/agentanalytics:

- Add agentHasAfterAgentCallbacks (across up to 3 exported agent wrapper hops, treating only ADK's base *agent.agent as terminal callback owner and failing closed conservatively on opaque wrappers even with an empty afterAgentCallbacks slice or typed-nil inner Agent delegates) and contextHasAfterAgentPlugin (checking all other registered plugins via lazy PluginManager discovery, failing closed to true when PluginManager, self, or any plugin element/afterAgentCallback field cannot be verified or panics during inspection).

- Record retiredActivation and popRetirement state with [2]unsafe.Pointer pins for StateDelta and ArtifactDelta maps across live replacement, length-prefixed llmKey/parseLLMKey (<pathLen>:<path><nameLen>:<name>:<branch>) lookups, cap-8 pending after-agent hull compaction, monotonic hasUnjoinedTask tracking preserved via || across compaction folds, per-pass O(R+U) unrespondedRetiredIndex matching, shrinkRetiredActivationsLocked backing-array release, and a hard per-invocation cap of 128 retired activations whose hulls preserve foldedCredits links (including afterAgentCredit provenance for post-retirement mapless settlement) into creditGroupRem across partial group folds.

- Track granted vs consumed response credits separately alongside monotonic recordedAfterAgentCredit and recordedModelCredits watermarks on source spanRecord values so replays apply only net-new incremental deltas (re-arming settled entries only when a recorded grant watermark already existed without re-arming synthetic creditSettled-only merges), guard credit consumption on live creditGroupRem balances, and keep detached unjoined child activations free of parentRetiredAtPlatformTime.

- Add unit and regression coverage for plugin/agent callback detection (including typed-nil inner wrapper delegates), newTestRunner lazy discovery with zero side effects, map-pin retention, unjoined-task hull preservation, partial cap-128 shared credit-group folds (afterAgentCredit, modelCredits, and post-retirement mapless settlement), incremental credit grants after settlement, compacted-replay credit safety, per-pass index + shrink bounds, and coordinator forwarding with reused finish_task call_0 IDs.
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