Repository navigation
feat(agentanalytics): add bounded retired-activation ledger and after-agent detection - #2389
Conversation
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2389 (review).
wojtas000
left a comment
There was a problem hiding this comment.
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
pushAgentSpanorpopAgentSpansetpopRetirement,startPlatformTimeandhasCustomUUIDProvider, which this PR doesn't do yet. TheretiredPeerCountcomment describes an exemptioncompleteResponsedoesn't implement yet. - The doc block above
pruneOrphanedCreditGroupsLockeddescribespruneSettledRetiredActivationsLocked. contextHasLaterAfterAgentPluginchecks only plugins registered after this one, but an earlier plugin'sAfterAgentCallbackcan also writeStateDelta.- Pinned ledger entries have no cap while a peer stays open:
TestPeerRetirementsStayUncompactedWhilePeerOpenkeeps 15.
|
This conflicts with main in 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. |
67c1dae to
30d6d08
Compare
|
@wojtas000 Thanks! I rebased #2389 cleanly onto #2380 at the top of the 5-PR linear stack ( |
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2389 (review).
30d6d08 to
006e5e7
Compare
|
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:
|
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2389 (review).
006e5e7 to
622438b
Compare
|
Thanks @caohy1988 and @wojtas000 for the thorough reviews — rebased cleanly across
|
caohy1988
left a comment
There was a problem hiding this comment.
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 liveEventActionsthrough the weak pointer and reads its map fields while that attempt's error callback can replaceStateDeltaon 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 trailingfinish_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. BothAGENT_COMPLETEDspan 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 andsoleOpenAuthorLockedcan'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 intofoldedCredits, so with a single identity going from 256 to 512 retirements growscreditGroupRemfrom 256 to 512 andfoldedCreditsfrom 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
left a comment
There was a problem hiding this comment.
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.
622438b to
b5e7e1d
Compare
|
@wojtas000 Rebased cleanly onto |
wojtas000
left a comment
There was a problem hiding this comment.
Re-approving after the rebase onto main. The commit is the same patch I approved earlier today.
|
@wojtas000 Rebased cleanly onto |
The merge-base changed after approval.
b5e7e1d to
483a00b
Compare
wojtas000
left a comment
There was a problem hiding this comment.
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.
|
@wojtas000 |
The merge-base changed after approval.
483a00b to
51c5ce2
Compare
wojtas000
left a comment
There was a problem hiding this comment.
Re-approving after the rebase onto main. The commit is the same patch I approved earlier today.
…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.
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/agentanalyticscan emit delayedAfterAgentcallback deltas or late events after an activation span pops from the live stack, including across concurrent peer activations, wrapped agents, other registeredAfterAgentCallbackplugins (running either before or afteragentanalytics), live replacement ofStateDelta/ArtifactDeltamaps, replayed retirement/settlement passes, and detached/unjoined or multi-parent enclosing branches. Without conservative after-agent callback detection, a strictly boundedO(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:plugin/agentanalytics/bigquery_agent_analytics_plugin.go,plugin/agentanalytics/trace_manager.go):agentHasAfterAgentCallbacks(withlookupAgentAfterCBLayout/fieldPathExported/safeFieldByIndexcheckingllmagent.Configand exported wrapperAgentchains up to 3 hops, treating only ADK's concrete*agent.agentas terminal owner ofafterAgentCallbacksso an opaque wrapper exposing an empty callback slice while hiding a delegate or holding a typed-nil innerAgentstill fails closed conservatively totrue).contextHasAfterAgentPlugin(inspecting all other registered plugins both before and afterselfPluginsince ADK builds the single after-agent event after everyAfterAgentCallbackruns, returning conservativetruewhenself != nilandPluginManagerorselfcannot be resolved, returningtruewhen anypluginselement is nil, unexpected type, or lacks areflect.FuncafterAgentCallbackfield or panics while inspectingPluginManager, and returningfalsewhen all entries are verified callback-free orself == nilwith noPluginManager),discoverPluginManagerCtxKey/probePluginManagerCtxKey,traceManager.selfPlugin, andagentChildren.hasAfterAgentCallbackspropagation intospanRecordinpushAgentSpan.newBigQueryAgentAnalyticsPluginWithTracesso plugin identity tests inspecttraceManagerdirectly without adding test-only fields topluginState.O(R + U)retiredActivationledger, length-prefixedllmKey/parseLLMKey, &hasUnjoinedTaskhulls (plugin/agentanalytics/trace_manager.go):retiredActivation,popRetirement,foldedCredit,agentIdentityKey, length-prefixedllmKey/parseLLMKey(<pathLen>:<path><nameLen>:<name>:<branch>),activeSwallower,afterAgentState,spanRecordprovenance/lifecycle fields (ownResponse,startPlatformTime,hasAfterAgentCallbacks,hasCustomUUIDProvider,runEndSeq,runEndPlatformTime,popRetirement,recordedAfterAgentCredit,recordedModelCredits), andinvocationTraceledger fields (unrespondedRetiredTools,retiredActivations,creditGroupRem,nextCreditGroupID).[2]unsafe.Pointermap pins returned bycallbackAfterAgentActionsonpopRetirement/retiredActivation.afterAgentActionsRefso captured maps cannot have their addresses reused across GC if a callback replacesStateDeltaorArtifactDelta.hasUnjoinedTask boolexplicitly acrosscompactKey,foldRetiredCapHull, andfoldPendingAfterAgentWithIndexLocked(combined via||, while keepingcompletedOrTask/joinedAtRetire&&-folded forexcludedByEventTimestamp) so folding an unjoined task with a returned non-task preservesunjoinedTaskRetirement() == trueand keeps post-retirement events attributable.unrespondedRetiredIndex(newUnrespondedRetiredIndexLocked) once per retirement, pruning, cap-enforcement, and pending-fold pass (O(R + U)instead ofO(R * U)parseLLMKeyscans), and callsshrinkRetiredActivationsLockedto release oversizedinv.retiredActivationsbacking arrays after pruning (even whenpruneSettledRetiredActivationsWithIndexLockedfinds no> 3-member buckets).128entries) alongside cap-8 pending after-agent hull compaction (maxPendingAfterAgent = 8), preservesfoldedCreditslinks (includingafterAgentCreditprovenance) intocreditGroupRemacross 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'sparentRetiredAtPlatformTime.plugin/agentanalytics/trace_manager.go):recordedAfterAgentCreditandrecordedModelCreditshigh-water marks on the sourcespanRecord, sorecordRetiredActivationLockedgrants only net-new credit deltas (creditSettled: falseon zero-delta replays),recordRetiredActivationEntryLockedapplies strictly higher incremental deltas on settled entries only when a prior grant watermark exists (preventing syntheticcreditSettledduplicate merges from re-arming), and replaying an already-retired activation after hull compaction or pruning cannot allocate fresh credits or spend a later peer'sunrespondedRetiredcount.remainingCredits,allocCreditGroupIDLocked,settleCreditGroupIfExhaustedLocked,mergeCreditGroupsLocked,clearExhaustedAfterAgentCreditsLocked,consumeAfterAgentCreditLocked(guarded on livecreditGroupRem[gid] > 0balances),settleRetiredResponseCreditLocked(guarded oncreditGroupRem[gid] > 0across bothafterAgentCreditandmodelCreditspaths as well asfoldedCredits, and honoringcanOwnEventCreatedAtfor post-retirement maplessafterAgentCreditentries and cap-128 hulls),createdInRun,unjoinedTaskRetirement,canOwnEventCreatedAt,canOwnEventAt,excludedByEventTimestamp,hasGuardedRetiredPeerForEventLocked,soleOpenAuthorLocked, andprovenAfterAllRetiredLocked.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):TestContextHasAfterAgentPlugin(including nil/unreadablePluginManager.pluginselements failing closed),TestDiscoverPluginManagerCtxKey,TestDiscoverPluginManagerCtxKey_LazyAndZeroSideEffects,TestAgentHasAfterAgentCallbacks(including opaque empty-slice wrappers hiding a delegate and typed-nil innerAgentwrapper 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 cap128eviction/compaction, separate granted vs consumed credit replay invariants, and coordinator-forwardingfinish_taskcall_0reuse regression coverage.go.opentelemetry.io/otelandgo.opentelemetry.io/otel/sdkfrom indirect to direct requires inplugin/agentanalytics/go.mod/go.sumfor 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:
pushAgentSpanrecordshasAfterAgentCallbacksonspanRecord,llmKey/parseLLMKeyencode<pathLen>:<path><nameLen>:<name>:<branch>length-prefixed keys, andnewBigQueryAgentAnalyticsPluginstores a weakselfPluginpointer ontraceManagerso 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 internaltraceManagerstate and helpers unit-tested here in Part 5 and wired into livepushAgentSpan/popAgentSpan/onEventcallback dispatch in the Part 6 follow-up PR (0public API delta relative to #2380's head; relative tomain, the stacked branch carries only the 9 additive exports introduced earlier in #2180, with0incompatible 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:
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, andTestRetiredActivationLedger_CapFoldPostRetirementAfterAgentCredit.Please include a summary of passed go test results (verified at commit
622438b85a0647901d70e9897eac89a9881aefed):gofmt -l plugin/agentanalytics,git diff --check, andGOWORK=off go -C plugin/agentanalytics mod tidy -diff: clean (rc=0).go -C plugin/agentanalytics vet ./...andgolangci-lint run --max-same-issues=0 --max-issues-per-linter=0 ./...(inplugin/agentanalytics): PASS (0 issues.).apidiffbetween#2380(01821a6c) and#2389(622438b8) forgoogle.golang.org/adk/plugin/agentanalytics(plus0modified files outsideplugin/agentanalytics):0exported API changes (apidiff_bytes=0).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).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
newTestRunnerexecution tests inplugin/agentanalytics.Checklist
Additional context
Add any other context or screenshots about the feature request here.
Stacked PR order:
main <- #2180 <- #2381 <- #2380 <- #2389(#2375has merged ontomain). Until the parent PRs merge intomain, GitHub's cumulative diff againstmainincludes commits from #2180, #2381, and #2380; please review the top commit only for Part 5's changes relative to #2380's head.