Repository navigation
feat(agentanalytics): add event provenance, context walkers, and callback stack helpers - #2380
Conversation
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2380 (review).
|
Thanks for the thorough review! Addressed everything in new fast-forward commits (
|
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2380 (review).
wojtas000
left a comment
There was a problem hiding this comment.
Two things need to change before this merges: hasAfterAgentCallbacks is still computed on every agent start with nothing reading it, and the comments on the callback-actions helpers say callbacks can't reach their EventActions, which they can.
Must change before merge:
runningAgentChildrenfillshasAfterAgentCallbackson everyBeforeAgentCallback(trace_manager.go#L1098), but no production code reads it. ThespanRecordthatpushAgentSpanbuilds fromagentChildren(L2227-L2251) leaves it out, and only tests look at it. With this push, the first agent start in a process also builds an agent, a runner and an in-memory session and callsRunLiveto find thePluginManagerkey (L5494-L5529). Let's move the field, the probe, therunnerimport and theselfPluginwiring into the part that reads them, so users don't pay for them in the meantime.- The comments on
callbackAfterAgentActionMapsandcallbackAfterAgentActions(L5678-L5697) say a callback can't reach itsEventActions, and the argument thatkeepstops a map address from being reused rests on that. A callback can:WithDelta(nil)returns the*commonContextitself (common_context_delta.go#L53-L55), and itsActions()returns the live struct (common_context.go#L686-L688). I ran a pluginAfterAgentCallbackthroughrunner.Runthat captured the maps, setctx.WithDelta(nil).Actions().StateDelta = map[string]any{"replaced": true}, and captured them again. The event the runner yielded carried the new map, not the first one. The comments should say so, and the address match in the next part has to cope with a callback replacing a map.
The smaller notes are inline. I ran the build, go vet, gofmt and the plugin module's tests with -race on this head, all clean.
|
Thank you both for the thorough reviews — pushed follow-up commits
All checks pass on |
|
Thanks for the PR, @haiyuan-eng-google. One thing before review. Our contribution guide asks for an issue behind each change, and I could not find one linked here.
If this is a small doc or typo fix, ignore me. A maintainer can open the issue for you if you would rather. |
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2380 (review).
|
Updated in Reply to @caohy1988 (Review 5946557721)Thanks for catching these! Updated in the latest push:
Reply to @wojtas000 (Review 5935172508)Thanks for the review! Addressed the remaining feedback:
|
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2380 (review).
Every item in this review is fixed on the current head.
wojtas000
left a comment
There was a problem hiding this comment.
One thing needs to change before this merges: the UUID-provider scope recording added in the last push has no production reader, and its cost grows quadratically with the number of agent-node runs in one invocation.
Must change before merge:
noteUUIDProviderLockedappends a scope on every callback underinv.mu. At run end the scopes are merged in O(K²) undertm.muand copied into the completed and late traces. The only reader ishasEventCreationProvenance, and onlyTestEventCreationProvenance_RealRuncalls it. Throughrunner.Run, a dynamic workflow node that callsworkflow.RunNode3,000 times took about 0.4 s longer per run (35% more) and 1.2 MB more than the same code with the recording skipped. A plain sequential agent pays about 2 KB per run. Please move the recording and the copies into the PR that reads them, or return early when no custom provider is set, as caohy1988 suggested.
Both items from my earlier review are fixed: the probe and hasAfterAgentCallbacks are gone, and the callback-actions comments match the code. The two provenance-check doc claims, a sibling run passing and the path mismatch under an llmagent root, change no row while the reader is test-only, so they can wait for the PR that wires it in.
Reply to @wojtas000 (Review 5953325257)Thanks for catching this and measuring the
Reply to @caohy1988 (Review 5950890408)Thanks for the detailed breakdown—all items from this round are included as well:
|
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2380 (review).
|
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. |
16ecc4e to
75e301f
Compare
|
@wojtas000 Thanks! I rebased #2380 cleanly onto #2381 as Layer 4 of the linear stack ( |
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2380 (review).
75e301f to
0ca6483
Compare
|
Thanks @caohy1988 for the thorough review! Rebased the stack (
|
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2380 (review).
The must-fix in this review is fixed: with no custom UUID provider, the scope recording does no work, and the 3,000-RunNode benchmark matches with recording forced off.
0ca6483 to
01821a6
Compare
|
Thanks @caohy1988 and @wojtas000 for the detailed reviews — rebased the stack cleanly onto
|
caohy1988
left a comment
There was a problem hiding this comment.
The view-conflict handling looks solid now: it checks the stored object type and compares the stored query before accepting a competing view creation, and the errors keep their deadline information. A few problems remain in the response/activation matching, though. The second and third items below reproduce with targeted tests that fail at this head and pass at the merge base, so they look introduced by this change.
- Decorated workflow nodes lose their path (
bigquery_agent_analytics_plugin.go~2398, ~2405;trace_manager.go~1697): traversal stops at an application decorator that embedsagent.Context, and thePath()fallback only checks the outer callback wrapper, so two sibling nodes with the same agent and branch both register with an empty path. A state change from the left node then lands under the right node's span (STATE_DELTA.span_idmatches the right node'sAGENT_STARTING). The same test picks the left node at both the parent commit and the merge base. Unwrapping through the framework wrapper and consulting the decorator's publicPath()would fix it. - A rewritten
finish_taskresult can close the wrong activation (trace_manager.go~5592, ~5618): exact dispatch matches are only accepted for pending attempts, so when a later callback turns an observed completion into a retry, the stale completion survives and can consume a sibling's completion when the sibling reuses the call ID. The second activation'sAGENT_COMPLETEDends up with the first activation's span. Retiring the attempt identified by the response's dispatch maps when its delivered result is nonterminal should cover it. - Late tool completion reverts to the pre-eviction trace ID (
trace_manager.go~4062, ~3489): when the first publication of an evicted invocation creates a late state, the restored copy's open calls are merged into it without the trace ID the restored invocation adopted, so a tool started on the adopted trace finishes under a different trace ID. The adopted identity needs to be reconciled when merging open calls. - Race on a later dispatch's actions (
trace_manager.go~6328, ~6359, ~6364): when an older buffered response arrives with the same call ID, the code reads the later dispatch's liveStateDelta/ArtifactDeltawhile anOnToolErrorCallbackon another goroutine can replace them without the invocation lock. Buffering the firstcall_0response while the second call's error callback replaces both maps trips the race detector on both fields. Snapshotting the map identities when handling the error would avoid it.
Two smaller things. Provider tracking can accept hand-built IDs on explicitly disabled branches: overflow is only consulted when no recorded ancestor matches, and an unknown author's custom-provider summary is accepted before checking the exact branch setting (no production row-writing caller uses this yet). And resolving distinct finish_task IDs in a merged response scans every previously seen ID under the invocation lock, which grows quadratically (about 20 ms at 4,096 IDs) even when no task activation matches; checking for a task activation first and using a set would fix that. Also a small one: the TestTraceManager_UnobservedTaskLocked "ambiguous" subtest name says a non-empty call ID returns -1, but the assertions expect the newest activation for both cases.
Full race-enabled package tests, vet, lint, go mod tidy -diff and gofmt are all clean at this head.
wojtas000
left a comment
There was a problem hiding this comment.
Approving. The context walkers no longer follow app-owned fields: an app struct with an unrelated context in a field named InvocationContext now gives an empty path and no race. At 3,000 workflow.RunNode calls the run allocates the same with UUID-scope recording on or forced off. Build, vet, tidy and the race suite pass on the head and on its merge with main.
01821a6 to
28b2b88
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.
…back stack helpers Add the helpers on which attributing the events of AfterAgentCallbacks builds. Agent activations record their UUID provider as they start, but OnEventCallback does not consult the provenance check yet, and nothing outside the tests calls the after-agent action and stack helpers. - Event creation provenance: hasEventCreationProvenance tells an event that session.NewEvent created (hasNewEventUUID) from a hand-built one. Each run keeps a bounded uuidProviderLedger of custom platform.WithUUIDProvider activations (pre-attached under tm.mu in lookupInvocationWithUUID before releasing the lock so eviction cannot race the first observation, compacted on eviction in markEvictedLocked and on completion in rememberCompletedAtLocked, bounded at maxCompletedUUIDProviderEntries for late activations after default runs, and tracking per-branch state so disabled worker branches fail closed). When the run ends, the compacted ledger moves to its completed entry and is shared with its late state. - Context lookups: contextHasCustomUUIDProvider reads the provider key once without invoking it. callbackAfterAgentActions/callbackAfterAgentActionMaps, contextPath, and contextParentMap unwrap only allowlisted Go stdlib and ADK context structs via directStructField (never reading application-owned wrapper fields or allocating FieldByName searches) using stack-backed queues and lazy cycle tracking (derefContextStructValueLazy), and retain StateDelta/ArtifactDelta pointers in actionMaps via [2]unsafe.Pointer. - Callback stack helpers: currentGoroutineTrace and afterAgentCallbackRunsOfTrace count agent.runAfterAgentCallbacks frames and fail closed on incomplete or elided traces; isGoroutineTraceHeader accepts Go 1.26 and Go 1.27 pprof label forms. - retiredCause records retired custom ancestors that drained a child failure (retiredSwallower) with copy-on-write swallower slices.
The merge-base changed after approval.
28b2b88 to
402b155
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.
…back stack helpers (google#2380) Add the helpers on which attributing the events of AfterAgentCallbacks builds. Agent activations record their UUID provider as they start, but OnEventCallback does not consult the provenance check yet, and nothing outside the tests calls the after-agent action and stack helpers. - Event creation provenance: hasEventCreationProvenance tells an event that session.NewEvent created (hasNewEventUUID) from a hand-built one. Each run keeps a bounded uuidProviderLedger of custom platform.WithUUIDProvider activations (pre-attached under tm.mu in lookupInvocationWithUUID before releasing the lock so eviction cannot race the first observation, compacted on eviction in markEvictedLocked and on completion in rememberCompletedAtLocked, bounded at maxCompletedUUIDProviderEntries for late activations after default runs, and tracking per-branch state so disabled worker branches fail closed). When the run ends, the compacted ledger moves to its completed entry and is shared with its late state. - Context lookups: contextHasCustomUUIDProvider reads the provider key once without invoking it. callbackAfterAgentActions/callbackAfterAgentActionMaps, contextPath, and contextParentMap unwrap only allowlisted Go stdlib and ADK context structs via directStructField (never reading application-owned wrapper fields or allocating FieldByName searches) using stack-backed queues and lazy cycle tracking (derefContextStructValueLazy), and retain StateDelta/ArtifactDelta pointers in actionMaps via [2]unsafe.Pointer. - Callback stack helpers: currentGoroutineTrace and afterAgentCallbackRunsOfTrace count agent.runAfterAgentCallbacks frames and fail closed on incomplete or elided traces; isGoroutineTraceHeader accepts Go 1.26 and Go 1.27 pprof label forms. - retiredCause records retired custom ancestors that drained a child failure (retiredSwallower) with copy-on-write swallower slices.
Please ensure you have read the contribution guide before creating a pull request.
Stacked PR: depends on #2180 and #2381; 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.
Downstream parts of the #2182 split need three capabilities inside
plugin/agentanalyticsthat ADK does not expose directly to plugins:session.NewEventvs. hand-builtsession.Event):session.NewEventobtainsEvent.IDfromplatform.NewUUID(ctx), which produces an RFC 4122 UUIDv4 unless a customplatform.UUIDProviderwas installed on the creating activation's context viaplatform.WithUUIDProvider. However,OnEventCallbackreceives the runner's context rather than the creating sub-agent's or workflow node's context, so inspecting the delivery context alone misses a custom provider installed for one sub-agent, falsely accepts hand-built IDs when a sub-agent explicitly disabled the runner's provider withplatform.WithUUIDProvider(ctx, nil), and looks in the outer invocation when a custom agent forwards events from a nestedrunner.Runner.EventActionsmap identity & cycle/race-safe context unwrapping: Recognizing callback-originated events (StateDeltaandArtifactDeltamap pointers), node paths (contextPath), and parent maps (contextParentMap) without racing on custom application context types, triggering allocatingreflect.Value.FieldByNamesearches, or letting GC reclaim replaced map addresses requires unwrapping only allowlisted stdlibcontextand ADK context structs via direct field access while keeping captured maps reachable.runAfterAgentCallbacksstack depth without losingcurrentGoroutine()headroom: Countingagent.runAfterAgentCallbacksframes on the current goroutine requires validatingruntime.Stackheaders across plain,GOTRACEBACK=system, Go 1.26GODEBUG=tracebacklabels=1, and Go 1.27tracebacklabels=1formats while preservingmain's inlineruntime.Stackcall depth incurrentGoroutine()so workflow retry detection does not lose a frame at Go's 100-frame traceback ceiling.Solution:
A clear and concise description of what you want to happen and why you choose
this solution.
Relative to #2381, the top
#2380commit adds internal event-provenance, allowlisteddirectStructFieldcontext-unwrapping, goroutine stack-header/frame helpers, andretiredSwallower/retiredCausetracking forplugin/agentanalytics, with zero exported API or emitted-row changes over#2381(while this branch remains stacked ahead ofmain, the branch diff againstorigin/mainalso carries the 9 additive exports from#2180—Config.OnSchemaReady,Config.OnSchemaError,Config.ToolResultClassifier,ToolResultClassifier,ToolResultDecision,ToolResultVerdict,ToolResultAbstain,ToolResultOK,ToolResultError—and the#2180/#2381behavior changes underneath until those PRs land):#2380#2380& Downstream Split PRshasNewEventUUIDplatform.NewUUID.hasEventCreationProvenanceand(*traceManager).hasEventCreationProvenance.contextHasCustomUUIDProvider,discoverUUIDProviderCtxKeyplatform.WithUUIDProvidercontext key once (sync.Once) from a probe context and performs onectx.Valuelookup (walking thecontext.Contextchain,O(context depth), with panic recovery andnil-provider shadowing matchingplatform.NewUUID).#2380at run start (invocationSpan) and agent start (pushAgentSpan) before takingtm.mu; also consumed by the finalAfterAgentCallback/ event-attribution split PR.uuidProviderLedger,uuidProviderKey,uuidProviderState,noteUUIDProviderLocked,compactForCompletedmaxUUIDProviderEntries = 512live,maxCompletedUUIDProviderEntries = 32compacted per map) from{name, branch, path}(plusanyBranch,anyPath, and boundedbranchStates/branchSummaryOverflowbranch-wide summaries) to a 4-state lattice (unseen,custom,default,mixed).lookupInvocationWithUUIDpre-attachesinv.uuidProvidersundertm.muwhencustomUUIDsis true so capacity eviction cannot race the first observation;markEvictedLockedandrememberCompletedAtLockedcompact per-path entries (<= 32keys per map acrossstatesandbranchStates;< 1 KBmeasured forstatesin the 20,000-path workflow test);noteUUIDProviderLockedinitializescompacted: inv.isLate, pathOverflowed: inv.isLateso late activations after default-provider runs stay capped at32keys per map.#2380frominvocationSpanandpushAgentSpan; read by(*traceManager).eventUUIDProviderand(*traceManager).eventUUIDProviderFor.hasEventCreationProvenance,(*traceManager).hasEventCreationProvenance,(*traceManager).eventUUIDProvider,(*traceManager).eventUUIDProviderForevcarries a UUIDv4 or was created under a customplatform.UUIDProviderrecorded for the producing activation (failing closed when an untracked foreignev.InvocationIDmismatches a trackedid.invocationID, consultingid.agentNamewhenev.Authoris"user"or empty, failing closed on disabled/mixed worker branches and dot-separated sub-branches viabranchState/branchOverflow, and falling back to deliveryctxonly when neither invocation is tracked;eventUUIDProvideracquirestm.mu, so callers must not holdtm.mu).runner.Runintegration tests in#2380; consumed in production by the finalAfterAgentCallback/ event-attribution split PR.callbackAfterAgentActions,callbackAfterAgentActionMaps,actionMaps,actionMaps.shares,eventActionMaps,mapPointer"context"structs (Context,cancelCtx,c) and ADKagentstructs (context->commonContext, with a512-step cap, lazy cycle trackingsteps >= 32/derefs >= 4, andrecoverguard) viadirectStructFieldandderefContextStructValueLazyto extractStateDeltaandArtifactDeltamap pointers, pinning both referents in[2]unsafe.Pointerso GC cannot reclaim or reissue their addresses whilekeepis held.actionMapsis used in#2389production struct fields (retiredActivation.afterAgentActions); consumed in production by the finalAfterAgentCallback/ event-attribution split PR.adkContextChildren,contextStructQueue,directStructField,derefContextStructValue,derefContextStructValueLazyadkContextChildrenand stack-backed[16]reflect.ValuecontextStructQueueare used bycontextPathandcontextParentMapto restrict traversal to Go stdlib"context",agent(commonContext,invocationContext,callbackContextWrapper,toolContextWrapper),internal/context(InvocationContext,ReadonlyContext),internal/llminternal(cancelledToolContext),agent/remoteagent/v2(authContext), andserver/adka2a/v2(executorContext) viadirectStructFieldand lazy cycle sets (derefContextStructValueLazy,steps >= 32/derefs >= 4), never reading application-owned struct fields and eliminatingreflect.Value.FieldByNameheap allocations.extractCallbackAfterAgentActionsValuesharesdirectStructFieldandderefContextStructValueLazy(restricted to stdlib"context"andagent), andderefContextStructValueis tested directly in unit tests.adkContextChildren/contextStructQueueincontextPath&contextParentMap;directStructField/derefContextStructValueLazyalso shared withextractCallbackAfterAgentActionsValue.currentGoroutineTrace,afterAgentCallbackRunsOfTrace,isGoroutineTraceHeader,cutTracebackLabels,cutTracebackLabelString,visitTraceFrameNamesGOTRACEBACK=system, Go 1.26[status labels:{"k": "v"}], and Go 1.27[status] {k: v}headers, shares frame-name scanning withattemptSiteOfTrace(visitTraceFrameNames), and countsagent.runAfterAgentCallbacksframes while preservingmain's inlineruntime.Stackcall depth incurrentGoroutine().visitTraceFrameNamesis called byattemptSiteOfTracein#2380;currentGoroutineTraceandafterAgentCallbackRunsOfTraceare consumed by downstream#2182PRs.retiredSwallower,retiredSwallower.matches,retiredCause.addSwallower,retiredCause.hasSwallowerSpanswallowerShared(*atomic.Int64) for geometric backing-array growth (O(N)copies across chain depthN) and isolating value-copied sibling slices.#2389alongside downstream attribution PRs.How
(*traceManager).hasEventCreationProvenance(ctx, id, ev)evaluates non-UUIDv4 IDsev.InvocationID != ""andev.InvocationID != id.invocationID, checksev.InvocationIDfirst so events forwarded by a custom agent from a nestedrunner.Runnersharing the plugin are evaluated in the nested invocation. Ifev.InvocationIDis not tracked whileid.invocationIDis tracked (live, evicted, or completed), it fails closed (false) so a stale or foreignev.InvocationIDcannot bypass a sub-agent'splatform.WithUUIDProvider(ctx, nil)by escaping to deliveryctx.contextHasCustomUUIDProvider(ctx)only when neitherev.InvocationIDnorid.invocationIDis tracked (never seen or pruned past eviction/completion caches). Evicted invocations (tm.evicted) and restored evicted invocations (restoreEvicted) preserve their compacteduuidProviderLedger, andlookupInvocationWithUUIDpre-attachesinv.uuidProvidersundertm.mubefore concurrent eviction can observe an empty pointer.falseimmediately when a tracked invocation has anilledger (no custom provider was ever seen in that invocation).ev.Authoronev.Branch(oranyBranch: truewhenev.Branch == "") starting atev.NodeInfo.Path(orid.pathwhenev.NodeInfois empty within the same invocation), walking up non-empty/ancestors for at mostmaxUUIDProviderAncestorSteps = 8lookups (stopping before""so a nested workflow path such aswf@1/fn@1never falls back to a direct top-level activation atpath == "") and then consultinganyPath: true:ev.Author == <workflow>andev.NodeInfo.Path == "<wf>@1/<node>@1", matching either the non-empty ancestor path where<workflow>ran or<workflow>'sanyPathentry.<outer>@1/<inner>@1while their own nodes emit paths starting at<inner>@1/..., matching<inner>'sanyPathentry (failing closed if<inner>also ran without a custom provider elsewhere).ev.Authoris"user"or empty and has no recorded activation, also checksid.agentName(fallbackAuthoroncmp.Or(ev.Branch, id.branch)) so a worker activation that disabled custom UUIDs fails closed.uuidProviderUnseenandcmp.Or(branch, fallbackBranch)is non-empty, walks dot-separated branch prefixes inbranchStates(falling back tobranchSummaryOverflowif overflowed) so disabled or mixed worker branches and their sub-branches fail closed (false, true) rather than inheritingrun.isRunCustom() || late.isRunCustom().s == uuidProviderCustom;uuidProviderMixedfails closed (false). Otherwise it falls back torun.isRunCustom() || late.isRunCustom().Known limitations
uuidProvidersstaysniluntil a customplatform.UUIDProviderappears in the invocation (keeping default runs allocation-free), any activation of an authorAthat started earlier in the invocation under the default provider left no ledger entry. If another activation ofAlater starts with a custom provider in the same invocation, a hand-built non-UUIDv4 event from that earlier unrecorded activation evaluated once the custom activation has started can matchuuidProviderCustomthrough author fallback keys if it ran on an enabled or unrecorded branch.maxUUIDProviderEntriesoverflow,> 8path segments, orcompactForCompleted) observes both custom and default providers,uuidProviderMixedrejects non-UUIDv4 IDs for that key, including genuine custom-provider IDs on the mixed key.tm.evictedandtm.completed, it is untracked and falls back tocontextHasCustomUUIDProvider(ctx)unless paired with a tracked outerid.invocationID.hasEventCreationProvenance, ID provenance does not prove a non-zero creation timestamp if a custom agent explicitly setsID: platform.NewUUID(ctx)while leavingTimestampzero, under an active custom provider any non-emptyev.IDfrom that custom-provider activation passes, and stored events re-emitted or forwarded from external session storage carry whateverIDandTimestampthat external storage assigned.Performance & memory overhead
invocationSpanandpushAgentSpaneach do onectx.Valuelookup and oneatomic.Pointer.Load(). Zero ledger maps or slices are allocated, andcompletedTraceretainsnil.uuidProviderLedger.statesis capped atmaxUUIDProviderEntries = 512,markEvictedLockedcompactsevictedTrace.uuidProvidersviacompactForCompleted()(<= 32summary keys per map acrossstatesandbranchStates),rememberCompletedAtLockedretains<= 32summary keys per map (< 1 KBmeasured forstatesin the 20,000-path workflow test), and late activations starting after a default-provider completion initialize withcompacted: true, pathOverflowed: trueso late ledgers also stay bounded at<= 32keys per map.BenchmarkContextLookups, verified on tree9d57e921/ commit01821a6c):contextHasCustomUUIDProvider:67.03–69.44 ns/op(0 B/op,0 allocs/op)callbackAfterAgentActionMaps:635.5–750.3 ns/op(0 B/op,0 allocs/op)contextPath:6749–7623 ns/op(0 B/op,0 allocs/op)contextPathEmpty:15519–31535 ns/op(336 B/op,2 allocs/op)contextParentMap:53114–57750 ns/op(2520 B/op,13 allocs/op)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
#2381(the top#2380commit under review):Nothing in the BigQuery rows or exported API emitted by
plugin/agentanalytics, because the new provenance, callback action-map, stack-counter, andretiredSwallowerhelpers have no row-writing callers in this commit yet. Two internal runtime behaviors execute on existing paths:invocationSpan) and agent start (pushAgentSpan) perform onectx.Valuelookup using ADK'splatform.WithUUIDProviderkey before acquiring locks, pre-attaching and recording into a bounded per-invocationuuidProviderLedgeronly if a non-nil custom provider appears.contextParentMapandcontextPathusedirectStructFieldover allowlisted Go stdlib"context"and ADK context structs viaadkContextChildrenandderefContextStructValueLazy, never reading application-owned wrapper struct fields and avoidingreflect.Value.FieldByNameallocations and cyclic pointer loops.Carried underneath from the stacked base PRs until
#2180and#2381land onmain:#2180: Adds 9 additive exports (Config.OnSchemaReady,Config.OnSchemaError,Config.ToolResultClassifier,ToolResultClassifier,ToolResultDecision,ToolResultVerdict,ToolResultAbstain,ToolResultOK,ToolResultError), rejects non-TABLEBigQuery destinations beforeOnSchemaReady, verifies HTTP 409 /AlreadyExistsview DDL conflicts viaresolveDDLConflictwith structured status-onlyunverifiedViewConflictErrormessages (implementingDeadlineExceededunwrap), omits tool/function names fromrunToolResultClassifierwarning logs, readsplatform.Now(ctx)beforeinv.muinpushAgentSpan, reconciles evicted+restored invocations on completion, and hardensfinish_taskspan attribution across reused call IDs.#2381: Classifies built-in retry-and-reflect structured tool payloads asTOOL_ERRORbeforeConfig.ToolResultClassifierruns (writing a fixed fallbackerror_messageinstead of copyingerror_detailsorerror_typewhenConfig.ContentFormatter != nilor"content"is inConfig.PayloadColumnDenylist, includingfinish_taskinonEvent), suppresses duplicateTOOL_COMPLETED/AGENT_RESPONSEemissions afterOnToolErrorCallbackwhile still noting recoveredfinish_tasksentinel attempts, retirescompletedToolsscoped by dispatchEventActions, and handles empty/missing function-call IDs cleanly.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.
Shared test fixture note (
newClockedPlugin):newClockedPluginsetsconfig.DisableFlushOnRunEnd = true(matchingnewQueuedRowsPlugin) because it constructs an in-memoryPlugindirectly with anilBigQuerystreamWriter. Realrunner.Runtests that invokeAfterRunCallbackon aclockedPlugin(such asTestEventCreationProvenance_RealRun) would panic influshRunEndwithoutDisableFlushOnRunEnd = true.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.
This commit adds 16 unit/integration
Test*functions and 2 benchmarks intrace_manager_test.go:TestHasNewEventUUID,TestContextHasCustomUUIDProviderAndProvenance,TestCallbackAfterAgentActionMaps,TestContextLookups_WrapperIsolationAndSafety(including allowlisted ADK/stdlib wrappers, non-ADK cyclic wrappers ignored, and-raceconcurrent application wrapper field mutations),TestRetiredSwallowerAndCause,TestActionMapsShares,TestIsGoroutineTraceHeader,TestAfterAgentCallbackRunsOfTrace,TestEventCreationProvenance_RealRun,TestUUIDProviderStateWith,TestEventUUIDProvider(including eviction-window race undermaxTracked = 1and disabled worker branches / overflow / sub-branches),TestUUIDProviderLedger_DistinctPaths,TestUUIDProviderLedger_BoundedAcrossDistinctPathsAndCompletedRuns(including evicted ledger compaction and bounded<= 32late-activation ledgers),TestEventCreationProvenance_RealRunShapes,TestAfterAgentCallbackRunsOfTrace_RealRun,BenchmarkEndInvocationDistinctPaths, andBenchmarkContextLookups(contextHasCustomUUIDProvider,callbackAfterAgentActionMaps,contextPath,contextPathEmpty,contextParentMap), plusTestWorkflowRetry_DeepBeforeAgentStackAtTracebackLimit_EmitsCompletedpinning inlineruntime.Stackframe depth incurrentGoroutine().Please include a summary of passed go test results (verified at commit
01821a6c9c4d21c20479b715141c21c1dfc85725, tree9d57e921b7e28411f942d28d96caa4a30a349d07):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):0 issues.(rc=0).apidiffbetween#2381(8f3621c8) and#2380(01821a6c) forgoogle.golang.org/adk/plugin/agentanalytics(plus0modified files outsideplugin/agentanalytics): zero exported API changes (APIDIFF_LEN=0).go -C plugin/agentanalytics test -mod=readonly -count=3 -run '^$' -bench '^BenchmarkContextLookups$' -benchmem .(on identical tree9d57e921): PASS (19.514s;0 B/op, 0 allocs/oponcontextHasCustomUUIDProvider,callbackAfterAgentActionMaps, andcontextPath).go -C plugin/agentanalytics test -race -mod=readonly -count=1: PASS (12.566slive on01821a6c).go -C plugin/agentanalytics test -mod=readonly -count=1 ./...(on identical tree9d57e921inplugin/agentanalytics): PASS (154.451s).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.
No live BigQuery table writes change in the top
#2380commit relative to#2381because none of the new helpers alter emitted rows yet.Checklist
Additional context
Add any other context or screenshots about the feature request here.
main <- #2180 <- #2381 <- #2380(with#2389stacked on top of#2380;#2375has merged ontomain). Once#2180and#2381land onmain, this branch will be rebased ontomainso only the top#2380commit remains in the PR diff.#2381(8f3621c8) and#2380(01821a6c),apidiffconfirms zero exported API changes (againstorigin/main, the stacked branch carries only the 9 additive exports from#2180).