Skip to content

feat(agentanalytics): add event provenance, context walkers, and callback stack helpers - #2380

Merged
wojtas000 merged 1 commit into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2182-4-event-provenance-and-ctx-walkers
Nov 19, 2026
Merged

wojtas000 merged 1 commit into
google:mainfrom
haiyuan-eng-google:fix/bqaa-2182-4-event-provenance-and-ctx-walkers

Conversation

@haiyuan-eng-google

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

Copy link
Copy Markdown
Contributor

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/agentanalytics that ADK does not expose directly to plugins:

  1. Event creation provenance (session.NewEvent vs. hand-built session.Event): session.NewEvent obtains Event.ID from platform.NewUUID(ctx), which produces an RFC 4122 UUIDv4 unless a custom platform.UUIDProvider was installed on the creating activation's context via platform.WithUUIDProvider. However, OnEventCallback receives 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 with platform.WithUUIDProvider(ctx, nil), and looks in the outer invocation when a custom agent forwards events from a nested runner.Runner.
  2. After-agent callback EventActions map identity & cycle/race-safe context unwrapping: Recognizing callback-originated events (StateDelta and ArtifactDelta map pointers), node paths (contextPath), and parent maps (contextParentMap) without racing on custom application context types, triggering allocating reflect.Value.FieldByName searches, or letting GC reclaim replaced map addresses requires unwrapping only allowlisted stdlib context and ADK context structs via direct field access while keeping captured maps reachable.
  3. Active runAfterAgentCallbacks stack depth without losing currentGoroutine() headroom: Counting agent.runAfterAgentCallbacks frames on the current goroutine requires validating runtime.Stack headers across plain, GOTRACEBACK=system, Go 1.26 GODEBUG=tracebacklabels=1, and Go 1.27 tracebacklabels=1 formats while preserving main's inline runtime.Stack call depth in currentGoroutine() 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 #2380 commit adds internal event-provenance, allowlisted directStructField context-unwrapping, goroutine stack-header/frame helpers, and retiredSwallower / retiredCause tracking for plugin/agentanalytics, with zero exported API or emitted-row changes over #2381 (while this branch remains stacked ahead of main, the branch diff against origin/main also carries the 9 additive exports from #2180—Config.OnSchemaReady, Config.OnSchemaError, Config.ToolResultClassifier, ToolResultClassifier, ToolResultDecision, ToolResultVerdict, ToolResultAbstain, ToolResultOK, ToolResultError—and the #2180/#2381 behavior changes underneath until those PRs land):

Helper / Type in #2380 Purpose Callers in #2380 & Downstream Split PRs
hasNewEventUUID Checks the canonical 36-byte RFC 4122 UUIDv4 format returned by default platform.NewUUID. Called by hasEventCreationProvenance and (*traceManager).hasEventCreationProvenance.
contextHasCustomUUIDProvider, discoverUUIDProviderCtxKey Discovers ADK's unexported platform.WithUUIDProvider context key once (sync.Once) from a probe context and performs one ctx.Value lookup (walking the context.Context chain, O(context depth), with panic recovery and nil-provider shadowing matching platform.NewUUID). Called in #2380 at run start (invocationSpan) and agent start (pushAgentSpan) before taking tm.mu; also consumed by the final AfterAgentCallback / event-attribution split PR.
uuidProviderLedger, uuidProviderKey, uuidProviderState, noteUUIDProviderLocked, compactForCompleted Per-invocation bounded ledger (maxUUIDProviderEntries = 512 live, maxCompletedUUIDProviderEntries = 32 compacted per map) from {name, branch, path} (plus anyBranch, anyPath, and bounded branchStates / branchSummaryOverflow branch-wide summaries) to a 4-state lattice (unseen, custom, default, mixed). lookupInvocationWithUUID pre-attaches inv.uuidProviders under tm.mu when customUUIDs is true so capacity eviction cannot race the first observation; markEvictedLocked and rememberCompletedAtLocked compact per-path entries (<= 32 keys per map across states and branchStates; < 1 KB measured for states in the 20,000-path workflow test); noteUUIDProviderLocked initializes compacted: inv.isLate, pathOverflowed: inv.isLate so late activations after default-provider runs stay capped at 32 keys per map. Recorded in #2380 from invocationSpan and pushAgentSpan; read by (*traceManager).eventUUIDProvider and (*traceManager).eventUUIDProviderFor.
hasEventCreationProvenance, (*traceManager).hasEventCreationProvenance, (*traceManager).eventUUIDProvider, (*traceManager).eventUUIDProviderFor Heuristic checking whether ev carries a UUIDv4 or was created under a custom platform.UUIDProvider recorded for the producing activation (failing closed when an untracked foreign ev.InvocationID mismatches a tracked id.invocationID, consulting id.agentName when ev.Author is "user" or empty, failing closed on disabled/mixed worker branches and dot-separated sub-branches via branchState/branchOverflow, and falling back to delivery ctx only when neither invocation is tracked; eventUUIDProvider acquires tm.mu, so callers must not hold tm.mu). Exercised by unit and runner.Run integration tests in #2380; consumed in production by the final AfterAgentCallback / event-attribution split PR.
callbackAfterAgentActions, callbackAfterAgentActionMaps, actionMaps, actionMaps.shares, eventActionMaps, mapPointer Unwraps only Go stdlib "context" structs (Context, cancelCtx, c) and ADK agent structs (context -> commonContext, with a 512-step cap, lazy cycle tracking steps >= 32 / derefs >= 4, and recover guard) via directStructField and derefContextStructValueLazy to extract StateDelta and ArtifactDelta map pointers, pinning both referents in [2]unsafe.Pointer so GC cannot reclaim or reissue their addresses while keep is held. actionMaps is used in #2389 production struct fields (retiredActivation.afterAgentActions); consumed in production by the final AfterAgentCallback / event-attribution split PR.
adkContextChildren, contextStructQueue, directStructField, derefContextStructValue, derefContextStructValueLazy Allowlisted context-unwrapping helpers: adkContextChildren and stack-backed [16]reflect.Value contextStructQueue are used by contextPath and contextParentMap to restrict traversal to Go stdlib "context", agent (commonContext, invocationContext, callbackContextWrapper, toolContextWrapper), internal/context (InvocationContext, ReadonlyContext), internal/llminternal (cancelledToolContext), agent/remoteagent/v2 (authContext), and server/adka2a/v2 (executorContext) via directStructField and lazy cycle sets (derefContextStructValueLazy, steps >= 32 / derefs >= 4), never reading application-owned struct fields and eliminating reflect.Value.FieldByName heap allocations. extractCallbackAfterAgentActionsValue shares directStructField and derefContextStructValueLazy (restricted to stdlib "context" and agent), and derefContextStructValue is tested directly in unit tests. adkContextChildren/contextStructQueue in contextPath & contextParentMap; directStructField/derefContextStructValueLazy also shared with extractCallbackAfterAgentActionsValue.
currentGoroutineTrace, afterAgentCallbackRunsOfTrace, isGoroutineTraceHeader, cutTracebackLabels, cutTracebackLabelString, visitTraceFrameNames Captures the current goroutine's stack, validates plain, GOTRACEBACK=system, Go 1.26 [status labels:{"k": "v"}], and Go 1.27 [status] {k: v} headers, shares frame-name scanning with attemptSiteOfTrace (visitTraceFrameNames), and counts agent.runAfterAgentCallbacks frames while preserving main's inline runtime.Stack call depth in currentGoroutine(). visitTraceFrameNames is called by attemptSiteOfTrace in #2380; currentGoroutineTrace and afterAgentCallbackRunsOfTrace are consumed by downstream #2182 PRs.
retiredSwallower, retiredSwallower.matches, retiredCause.addSwallower, retiredCause.hasSwallowerSpan Tracks retired custom ancestors eligible to clear a drained child failure, using swallowerShared (*atomic.Int64) for geometric backing-array growth (O(N) copies across chain depth N) and isolating value-copied sibling slices. Used in #2389 alongside downstream attribution PRs.

How (*traceManager).hasEventCreationProvenance(ctx, id, ev) evaluates non-UUIDv4 IDs

  • When ev.InvocationID != "" and ev.InvocationID != id.invocationID, checks ev.InvocationID first so events forwarded by a custom agent from a nested runner.Runner sharing the plugin are evaluated in the nested invocation. If ev.InvocationID is not tracked while id.invocationID is tracked (live, evicted, or completed), it fails closed (false) so a stale or foreign ev.InvocationID cannot bypass a sub-agent's platform.WithUUIDProvider(ctx, nil) by escaping to delivery ctx.
  • Consults contextHasCustomUUIDProvider(ctx) only when neither ev.InvocationID nor id.invocationID is tracked (never seen or pruned past eviction/completion caches). Evicted invocations (tm.evicted) and restored evicted invocations (restoreEvicted) preserve their compacted uuidProviderLedger, and lookupInvocationWithUUID pre-attaches inv.uuidProviders under tm.mu before concurrent eviction can observe an empty pointer.
  • Returns false immediately when a tracked invocation has a nil ledger (no custom provider was ever seen in that invocation).
  • Queries the ledger for ev.Author on ev.Branch (or anyBranch: true when ev.Branch == "") starting at ev.NodeInfo.Path (or id.path when ev.NodeInfo is empty within the same invocation), walking up non-empty / ancestors for at most maxUUIDProviderAncestorSteps = 8 lookups (stopping before "" so a nested workflow path such as wf@1/fn@1 never falls back to a direct top-level activation at path == "") and then consulting anyPath: true:
    • Function and dynamic workflow node outputs carry ev.Author == <workflow> and ev.NodeInfo.Path == "<wf>@1/<node>@1", matching either the non-empty ancestor path where <workflow> ran or <workflow>'s anyPath entry.
    • Nested workflow agents run as a node at <outer>@1/<inner>@1 while their own nodes emit paths starting at <inner>@1/..., matching <inner>'s anyPath entry (failing closed if <inner> also ran without a custom provider elsewhere).
  • When ev.Author is "user" or empty and has no recorded activation, also checks id.agentName (fallbackAuthor on cmp.Or(ev.Branch, id.branch)) so a worker activation that disabled custom UUIDs fails closed.
  • When author lookup returns uuidProviderUnseen and cmp.Or(branch, fallbackBranch) is non-empty, walks dot-separated branch prefixes in branchStates (falling back to branchSummaryOverflow if overflowed) so disabled or mixed worker branches and their sub-branches fail closed (false, true) rather than inheriting run.isRunCustom() || late.isRunCustom().
  • The first matching observation decides and passes only if s == uuidProviderCustom; uuidProviderMixed fails closed (false). Otherwise it falls back to run.isRunCustom() || late.isRunCustom().

Known limitations

  • Pre-custom-provider activations: Because uuidProviders stays nil until a custom platform.UUIDProvider appears in the invocation (keeping default runs allocation-free), any activation of an author A that started earlier in the invocation under the default provider left no ledger entry. If another activation of A later 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 match uuidProviderCustom through author fallback keys if it ran on an enabled or unrecorded branch.
  • Mixed keys and overflow folding fail closed: When the same lookup key (or summary tier after maxUUIDProviderEntries overflow, > 8 path segments, or compactForCompleted) observes both custom and default providers, uuidProviderMixed rejects non-UUIDv4 IDs for that key, including genuine custom-provider IDs on the mixed key.
  • Pruned invocations: Once an invocation is pruned out of tm.evicted and tm.completed, it is untracked and falls back to contextHasCustomUUIDProvider(ctx) unless paired with a tracked outer id.invocationID.
  • Heuristic and external-storage scope: As documented on hasEventCreationProvenance, ID provenance does not prove a non-zero creation timestamp if a custom agent explicitly sets ID: platform.NewUUID(ctx) while leaving Timestamp zero, under an active custom provider any non-empty ev.ID from that custom-provider activation passes, and stored events re-emitted or forwarded from external session storage carry whatever ID and Timestamp that external storage assigned.

Performance & memory overhead

  • Without a custom provider: invocationSpan and pushAgentSpan each do one ctx.Value lookup and one atomic.Pointer.Load(). Zero ledger maps or slices are allocated, and completedTrace retains nil.
  • Bounded eviction, completion, and late ledgers: Live uuidProviderLedger.states is capped at maxUUIDProviderEntries = 512, markEvictedLocked compacts evictedTrace.uuidProviders via compactForCompleted() (<= 32 summary keys per map across states and branchStates), rememberCompletedAtLocked retains <= 32 summary keys per map (< 1 KB measured for states in the 20,000-path workflow test), and late activations starting after a default-provider completion initialize with compacted: true, pathOverflowed: true so late ledgers also stay bounded at <= 32 keys per map.
  • Context lookup microbenchmarks (BenchmarkContextLookups, verified on tree 9d57e921 / commit 01821a6c):
    • 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 #2380 commit under review):

Nothing in the BigQuery rows or exported API emitted by plugin/agentanalytics, because the new provenance, callback action-map, stack-counter, and retiredSwallower helpers have no row-writing callers in this commit yet. Two internal runtime behaviors execute on existing paths:

  • Run start (invocationSpan) and agent start (pushAgentSpan) perform one ctx.Value lookup using ADK's platform.WithUUIDProvider key before acquiring locks, pre-attaching and recording into a bounded per-invocation uuidProviderLedger only if a non-nil custom provider appears.
  • contextParentMap and contextPath use directStructField over allowlisted Go stdlib "context" and ADK context structs via adkContextChildren and derefContextStructValueLazy, never reading application-owned wrapper struct fields and avoiding reflect.Value.FieldByName allocations and cyclic pointer loops.

Carried underneath from the stacked base PRs until #2180 and #2381 land on main:

  • From #2180: Adds 9 additive exports (Config.OnSchemaReady, Config.OnSchemaError, Config.ToolResultClassifier, ToolResultClassifier, ToolResultDecision, ToolResultVerdict, ToolResultAbstain, ToolResultOK, ToolResultError), rejects non-TABLE BigQuery destinations before OnSchemaReady, verifies HTTP 409 / AlreadyExists view DDL conflicts via resolveDDLConflict with structured status-only unverifiedViewConflictError messages (implementing DeadlineExceeded unwrap), omits tool/function names from runToolResultClassifier warning logs, reads platform.Now(ctx) before inv.mu in pushAgentSpan, reconciles evicted+restored invocations on completion, and hardens finish_task span attribution across reused call IDs.
  • From #2381: Classifies built-in retry-and-reflect structured tool payloads as TOOL_ERROR before Config.ToolResultClassifier runs (writing a fixed fallback error_message instead of copying error_details or error_type when Config.ContentFormatter != nil or "content" is in Config.PayloadColumnDenylist, including finish_task in onEvent), suppresses duplicate TOOL_COMPLETED / AGENT_RESPONSE emissions after OnToolErrorCallback while still noting recovered finish_task sentinel attempts, retires completedTools scoped by dispatch EventActions, 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): newClockedPlugin sets config.DisableFlushOnRunEnd = true (matching newQueuedRowsPlugin) because it constructs an in-memory Plugin directly with a nil BigQuery streamWriter. Real runner.Run tests that invoke AfterRunCallback on a clockedPlugin (such as TestEventCreationProvenance_RealRun) would panic in flushRunEnd without DisableFlushOnRunEnd = 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 in trace_manager_test.go:

  • TestHasNewEventUUID, TestContextHasCustomUUIDProviderAndProvenance, TestCallbackAfterAgentActionMaps, TestContextLookups_WrapperIsolationAndSafety (including allowlisted ADK/stdlib wrappers, non-ADK cyclic wrappers ignored, and -race concurrent application wrapper field mutations), TestRetiredSwallowerAndCause, TestActionMapsShares, TestIsGoroutineTraceHeader, TestAfterAgentCallbackRunsOfTrace, TestEventCreationProvenance_RealRun, TestUUIDProviderStateWith, TestEventUUIDProvider (including eviction-window race under maxTracked = 1 and disabled worker branches / overflow / sub-branches), TestUUIDProviderLedger_DistinctPaths, TestUUIDProviderLedger_BoundedAcrossDistinctPathsAndCompletedRuns (including evicted ledger compaction and bounded <= 32 late-activation ledgers), TestEventCreationProvenance_RealRunShapes, TestAfterAgentCallbackRunsOfTrace_RealRun, BenchmarkEndInvocationDistinctPaths, and BenchmarkContextLookups (contextHasCustomUUIDProvider, callbackAfterAgentActionMaps, contextPath, contextPathEmpty, contextParentMap), plus TestWorkflowRetry_DeepBeforeAgentStackAtTracebackLimit_EmitsCompleted pinning inline runtime.Stack frame depth in currentGoroutine().

Please include a summary of passed go test results (verified at commit 01821a6c9c4d21c20479b715141c21c1dfc85725, tree 9d57e921b7e28411f942d28d96caa4a30a349d07):

  • 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): 0 issues. (rc=0).
  • apidiff between #2381 (8f3621c8) and #2380 (01821a6c) for google.golang.org/adk/plugin/agentanalytics (plus 0 modified files outside plugin/agentanalytics): zero exported API changes (APIDIFF_LEN=0).
  • go -C plugin/agentanalytics test -mod=readonly -count=3 -run '^$' -bench '^BenchmarkContextLookups$' -benchmem . (on identical tree 9d57e921): PASS (19.514s; 0 B/op, 0 allocs/op on contextHasCustomUUIDProvider, callbackAfterAgentActionMaps, and contextPath).
  • Targeted go -C plugin/agentanalytics test -race -mod=readonly -count=1: PASS (12.566s live on 01821a6c).
  • Full go -C plugin/agentanalytics test -mod=readonly -count=1 ./... (on identical tree 9d57e921 in plugin/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 #2380 commit relative to #2381 because none of the new helpers alter emitted rows yet.

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 in order main <- #2180 <- #2381 <- #2380 (with #2389 stacked on top of #2380; #2375 has merged onto main). Once #2180 and #2381 land on main, this branch will be rebased onto main so only the top #2380 commit remains in the PR diff.
  • Between #2381 (8f3621c8) and #2380 (01821a6c), apidiff confirms zero exported API changes (against origin/main, the stacked branch carries only the 9 additive exports from #2180).

@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 #2380 (review).

@haiyuan-eng-google

haiyuan-eng-google commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review! Addressed everything in new fast-forward commits (4aafda67, d2a87486) on top of 1063191b:

  1. Replaced reflective walkContextStructs with ctx.Value using sync.Once-discovered keys:

    • discoverUUIDProviderCtxKey probes platform.WithUUIDProvider(context.Background(), ...) once and caches the unexported key; contextHasCustomUUIDProvider calls ctx.Value(key) directly and checks p, ok := ... .(platform.UUIDProvider); ok && p != nil (respecting WithUUIDProvider(child, nil) / typed-nil shadowing without invoking the provider).
    • discoverPluginManagerCtxKey (via probePluginManagerCtxKey) lazily probes an in-memory runner.Runner once via runner.RunLive (with platform.WithUUIDProvider and a sentinel error, avoiding init(), crypto/rand, and OTel invocation/agent span emission) and caches the unexported PluginManagerCtxKey, PluginManager struct type, and plugins slice field index; contextHasLaterAfterAgentPlugin calls ctx.Value(key), verifies pointer/type identity (elem.Type() == pluginManagerStructType), and matches self by pointer (falling back to pluginName only when self == nil).
    • agentHasAfterAgentCallbacks uses reflect.TypeAssert[llmagent.Config] / reflect.TypeAssert[*llmagent.Config] directly on the cached Config field index so ADK's any-typed State.Config and concrete Config fields both work with 0 allocations.
    • callbackAfterAgentActions no longer uses walkContextStructs either: it unwraps only the known delegation chain (directStructField, never calling FieldByName across embedded nil pointers, never reading invocationContext, and never scanning arbitrary struct fields).
    • This resolves all five issues you flagged:
      • agent.NewContext(cbCtx).WithAgentContext(context.Background()) now matches platform.NewUUID and pluginManagerFromContext (false) and preserves isolation from cbCtx's actions.
      • Mutex-guarded swappable parent contexts and wrappers with concurrently mutated unrelated context.Context fields are -race-clean.
      • >250-deep nested contexts and wrappers embedding nil struct pointers succeed without panics or a 512-step cutoff.
      • Hot-path lookup latency (BenchmarkContextLookups):
        • contextHasCustomUUIDProvider: 107,390 ns/op (138 allocs) -> 58.12 ns/op (0 B/op, 0 allocs)
        • contextHasLaterAfterAgentPlugin: 165,816 ns/op (138 allocs) -> 399.2 ns/op (0 B/op, 0 allocs)
        • hasAfterAgentCallbacks (agentHasAfterAgentCallbacks || contextHasLaterAfterAgentPlugin, with per-type field index caching on agentHasAfterAgentCallbacks): 600.0 ns/op (0 B/op, 0 allocs — well under 1 µs; agentHasAfterAgentCallbacks/anyConfig: 196.3 ns/op, 0 allocs; concreteConfig: 122.0 ns/op, 0 allocs)
        • runningAgentChildren: 77,662 ns/op (168 allocs) -> 5,271 ns/op (1448 B/op, 22 allocs)
  2. Clarified hasEventCreationProvenance doc comment:

    • Updated the doc comments on hasEventCreationProvenance and hasNewEventUUID (and the PR description) to explicitly describe hasEventCreationProvenance as a heuristic rather than strict creation-vs-delivery proof, noting both the &session.Event{ID: platform.NewUUID(ctx)} zero-Timestamp case and that any non-empty ev.ID passes when a custom platform.WithUUIDProvider is active.
  3. Pinned all guards with unit and real-run integration tests (plugin/agentanalytics/trace_manager_test.go):

    • Added TestDiscoverPluginManagerCtxKey covering lazy sync.Once stability, uncached probePluginManagerCtxKey() via runner.RunLive, and ctx.Value(key) equivalence across both runner.Run and runner.RunLive callback contexts.
    • Added TestContextLookups_WrapperIsolationAndSafety (WithAgentContext(context.Background()) over a real agent.NewCallbackContext + shadowICWrapper, -race mutex-guarded swappable & unrelated context.Context fields, >250-deep nesting + nil embedded struct pointers, and panicking Value() recovery).
    • Expanded TestAgentHasAfterAgentCallbacks to verify any-typed Config holding llmagent.Config / *llmagent.Config, typed-nil/empty/unrelated configs, and concrete llmagent.Config.
    • Expanded TestContextHasLaterAfterAgentPlugin to verify spoofing/typed-nil rejection under the real PluginManager key and selfPlugin identity distinction against another same-named plugin.
    • Expanded TestRetiredSwallowerAndCause to verify slices.Clone isolation in addSwallower when copying retiredCause with spare capacity.
    • Added real runner.Run integration tests TestEventCreationProvenance_RealRun (tying hasNewEventUUID / hasEventCreationProvenance to real session.NewEvent / platform.NewUUID output) and TestAfterAgentCallbackRunsOfTrace_RealRun (tying afterAgentCallbackRunsOfTrace to real agent.runAfterAgentCallbacks frames across plugin, agent, and nested runs).
  4. Cleanup & follow-up go.mod note:

    • Simplified newNoopAnalyticsPluginForTest so it constructs baseplugin.New directly instead of building and discarding setupTestPlugin(t).
    • Audited and updated comments across the diff (hasAfterAgentCallbacks, contextHasCustomUUIDProvider, contextHasLaterAfterAgentPlugin) to match the implementation.
    • Left plugin/agentanalytics/go.mod untouched in this PR as requested; noted the adk/v2 dependency bump suggestion for a dedicated follow-up PR.

@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 #2380 (review).

@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.

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:

  • runningAgentChildren fills hasAfterAgentCallbacks on every BeforeAgentCallback (trace_manager.go#L1098), but no production code reads it. The spanRecord that pushAgentSpan builds from agentChildren (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 calls RunLive to find the PluginManager key (L5494-L5529). Let's move the field, the probe, the runner import and the selfPlugin wiring into the part that reads them, so users don't pay for them in the meantime.
  • The comments on callbackAfterAgentActionMaps and callbackAfterAgentActions (L5678-L5697) say a callback can't reach its EventActions, and the argument that keep stops a map address from being reused rests on that. A callback can: WithDelta(nil) returns the *commonContext itself (common_context_delta.go#L53-L55), and its Actions() returns the live struct (common_context.go#L686-L688). I ran a plugin AfterAgentCallback through runner.Run that captured the maps, set ctx.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.

Comment thread plugin/agentanalytics/trace_manager.go Resolved
Comment thread plugin/agentanalytics/trace_manager.go Resolved
Comment thread plugin/agentanalytics/trace_manager.go Resolved
Comment thread plugin/agentanalytics/trace_manager.go Resolved
Comment thread plugin/agentanalytics/trace_manager.go Resolved
Comment thread plugin/agentanalytics/trace_manager.go Resolved
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thank you both for the thorough reviews — pushed follow-up commits e14e995b and d4cc3046 (merging main including #2020) addressing every comment:

  1. Moved unused after-agent plugin probing and trace-map state out of this PR:
    • Removed hasAfterAgentCallbacks, agentHasAfterAgentCallbacks, contextHasLaterAfterAgentPlugin, discoverPluginManagerCtxKey (and the runner / session / plugin / iter / weak probe imports), selfPlugin, and pluginState.traces so this PR introduces zero startup RunLive probe cost and retains no unused per-trace fields. Those belong in the downstream PR that consumes them.
  2. Fixed the -race bug, narrowed unwrapping, and pinned captured map pointers directly:
    • callbackAfterAgentActions now unwraps only Go stdlib "context" structs (Context, cancelCtx, c) and google.golang.org/adk/v2/agent wrappers (context), stopping on commonContext or any default: user/third-party struct so mutex-guarded custom contexts are never read without their synchronization.
    • extractCallbackAfterAgentActions pins the captured StateDelta and ArtifactDelta map pointers directly in [2]unsafe.Pointer (avoiding any boxing in callbackAfterAgentActionMaps, 0 B/op, 0 allocs/op), so GC cannot reclaim or reuse the captured map addresses while keep is held even after live replacement via ctx.WithDelta(nil).Actions().
    • Removed unused cycle-tracking state and unreachable defer recover() blocks from callbackAfterAgentActions and discoverUUIDProviderCtxKey (while keeping recover() on contextHasCustomUUIDProvider, which calls ctx.Value).
  3. Clarified doc comments, Go 1.27 trace headers, & tests:
    • Updated callbackAfterAgentActionMaps and callbackAfterAgentActions doc comments to reflect live ctx.WithDelta(nil).Actions() mutation/replacement semantics and direct [2]unsafe.Pointer GC pinning.
    • Removed the out-of-place ctx-fallback note from hasNewEventUUID.
    • Shared stack-frame name scanning via visitTraceFrameNames, updated afterAgentCallbackRunsOfTrace's doc comment for runAfterAgentCallbacks early returns and the workflow-node llmagent goroutine boundary, and updated isGoroutineTraceHeader to validate both goroutine N [...]: and Go 1.27 tracebacklabels=1 goroutine N [...] {...}: headers while rejecting malformed ones.
    • Updated tests to exercise WithCancel, WithTimeout, WithoutCancel, WithValue, NewCallbackContext, NewToolContext, accurate NewContext/WithAgentContext shadowing, live WithDelta(nil).Actions() replacement + GC churn pinning both captured maps, panickingValueContext through contextHasCustomUUIDProvider, lockedEmbeddedContext / mutexSwappableContext under -race, llmagent.New stack frame behavior, and Go 1.27 labeled + negative goroutine stack headers.

All checks pass on d4cc3046 (go test -coverprofile at 93.5% statement coverage, go test -race -shuffle=on -parallel=1, go vet, go mod tidy -diff, golangci-lint, and apidiff.sh origin/main).

@github-actions

Copy link
Copy Markdown

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 an issue already exists, add Closes: #<number> or Related: #<number> to the description.
  • If not, open one — the link prefills the bug template with your PR title — then reference it the same way.

If this is a small doc or typo fix, ignore me. A maintainer can open the issue for you if you would rather.

@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 #2380 (review).

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Updated in 1111cc89:

Reply to @caohy1988 (Review 5946557721)

Thanks for catching these! Updated in the latest push:

  • newClockedPlugin end-of-run flush: Set config.DisableFlushOnRunEnd = true in newClockedPlugin(t) (consistent with newQueuedRowsPlugin) so afterRun leaves rows queued in processor instead of panicking on a nil streamWriter during flushRunEnd.
  • TestEventCreationProvenance_RealRun child WithUUIDProvider propagation: Applied Branch via WithICDelta and wrapped Context via .WithContext(platform.WithUUIDProvider(...)) so commonContext.Context carries the child UUID provider for both session.NewEvent and BeforeAgentCallback while keeping sibling/other-branch runs isolated.
  • No time.Sleep in TestCallbackAfterAgentActionMaps: Replaced the wall-clock sleep poll with bounded runtime.GC() + runtime.Gosched() cycles.
  • Traceback-limit calibration in TestWorkflowRetry_DeepBeforeAgentStackAtTracebackLimit_EmitsCompleted: Calibrated rawMax directly via runtime.Stack (not currentGoroutine()), added an explicit check that currentGoroutine() loses no frame headroom relative to direct runtime.Stack, and bound callbacks directly on cp.analyticsPlugin so *clockedPlugin promoted-method wrappers do not shift frame depth under -race.
  • contextParentMap deref deduplication: Reused derefContextStructValue(queue[0], seen) directly in contextParentMap.

Reply to @wojtas000 (Review 5935172508)

Thanks for the review! Addressed the remaining feedback:

  • Deduplicated the pointer/interface dereference and cycle-tracking loop in contextParentMap by reusing derefContextStructValue.
  • Removed time.Sleep from the weak-pointer GC check in TestCallbackAfterAgentActionMaps and tightened the real-run provenance and 100-frame stack-ceiling retry tests so they run cleanly under both standard and -race builds.
  • Updated the PR description with a direct helper-to-consumer PR mapping table showing how the helpers here are used in #2380 and consumed across the downstream split PRs.

@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 #2380 (review).

@wojtas000
wojtas000 dismissed their stale review November 18, 2026 08:49

Every item in this review is fixed on the current head.

@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.

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:

  • noteUUIDProviderLocked appends a scope on every callback under inv.mu. At run end the scopes are merged in O(K²) under tm.mu and copied into the completed and late traces. The only reader is hasEventCreationProvenance, and only TestEventCreationProvenance_RealRun calls it. Through runner.Run, a dynamic workflow node that calls workflow.RunNode 3,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.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Reply to @wojtas000 (Review 5953325257)

Thanks for catching this and measuring the runner.Run numbers! Updated in the latest push, and merged current origin/main (0cc3907b, including #2377 2924008f and #2378 0cc3907b):

  • Early return when no custom platform.UUIDProvider is set (0 B allocated on default runs): Replaced the []uuidProviderScope slice and mergeUUIDProviderScopes scan with uuidProviders atomic.Pointer[uuidProviderLedger], which stays nil until a run or agent activation actually starts with a non-nil platform.UUIDProvider. On default runs, noteUUIDProviderLocked does a single atomic pointer load and returns immediately without allocating, scanning, or storing anything on invocationTrace, completedTrace, or the late trace.
  • Recorded only at run start and agent start, with O(1) map lookup when custom providers are active: Removed noteUUIDProviderLocked from noteRootAgentLocked (so model/tool callbacks, popTaskAgentSpan, and agentNamed do not touch it); only invocationSpan and pushAgentSpan record into the map[uuidProviderKey]uuidProviderState ledger, and rememberCompletedLocked / lateLocked share the ledger pointer directly with no copy or O(K²) merge under tm.mu.
  • Re-measured both runner.Run scenarios (go test -bench harness driving runner.Run under the default UUID provider, 24-vCPU Xeon):
    • Dynamic workflow node calling workflow.RunNode 3,000 times:
      • origin/main (2924008f): 741.9–823.4 ms/op (median 745.6 ms), 146.75 MB/op (146,743,117–146,802,330 B/op), 1,693,981 allocs/op
      • Previous push (1111cc89): 962.3–1,055.8 ms/op (median 984.0 ms, +32%), 147.87 MB/op (+1.12 MB/op)
      • This update: 671.2–767.9 ms/op (median 722.4 ms), 146.75 MB/op (146,742,976–146,807,538 B/op), 1,693,981 allocs/op (0 B scope-tracking overhead)
    • Plain 3-step sequentialagent run:
      • origin/main (2924008f): 313,180–313,389 B/op, 4,452 allocs/op
      • Previous push (1111cc89): 315,192–315,425 B/op (+2.0 KB/op), 4,461 allocs/op
      • This update: 313,198–313,400 B/op, 4,452 allocs/op (+0 B, +0 allocs/op vs. origin/main)
    • Also tightened the provenance lookup and its doc comments now (ancestor-path + anyPath / anyBranch resolution for workflow/llmagent node paths, conflict-aware uuidProviderMixed state on same-scope reruns, tm.mu locking contract on eventUUIDProvider, and explicit note on unrecorded pre-custom-provider activations—including fallback-key inheritance across ancestor paths, "", anyPath, and empty-branch anyBranch when another activation of the same author starts with a custom provider on the same or another path/branch) so the follow-up consumer PR inherits clean contracts, and resolved the trace_manager.go import conflict with fix(agentanalytics): match an error-ended tool call to its own attempt #2377.

Reply to @caohy1988 (Review 5950890408)

Thanks for the detailed breakdown—all items from this round are included as well:

  • Scope bookkeeping: Dropped the slice, O(N²) completion merge, and late re-note loop in favor of the lazy uuidProviderLedger map (nil until a custom provider is seen, shared by pointer across live, completed, and late states). Running BenchmarkEndInvocationDistinctPaths directly (1111cc89 vs. HEAD across 20,000 distinct node paths), endInvocation without a custom provider dropped from 2.60–3.11 s (12.99 MB/op) on 1111cc89 back to 10.9–12.0 µs (5,080 B/op, matching the pre-ledger endInvocation baseline across 20,000 distinct paths without UUID-provider scope fields at e374e9e5 / 2924008f: 10.9–12.3 µs, 5,032 B/op), and is 45.6–48.1 µs with a custom provider; TestUUIDProviderLedger_DistinctPaths pins 0 allocations and nil ledger retention.
  • hasEventCreationProvenance accuracy & tests:
    • Keys use a 4-state lattice (unseen, custom, default, mixed) where mixed evaluates to false, rejecting hand-built IDs when a worker reruns on the same (name, branch, path) without its first run's provider (with the pre-custom-provider unrecorded-activation trade-off—across both shared keys and ancestor/"", anyPath, and empty-branch anyBranch fallbacks when another activation of the same author later starts with a custom provider—and mixed-key fail-closed behavior documented in code comments and the PR description).
    • platform.WithUUIDProvider(ctx, nil) records uuidProviderDefault, delivery ctx is consulted only when !tracked (so a runner's custom provider never overrides a tracked sub-agent that disabled it), and popTaskAgentSpan / agentNamed no longer record under another activation's identity.
    • eventUUIDProvider (which documents that it acquires tm.mu) matches anyBranch when ev.Branch == "" and walks ev.NodeInfo.Path -> / ancestors -> "" -> anyPath (covering workflow function/dynamic node outputs and nested workflow agents), and (*traceManager).hasEventCreationProvenance uses cmp.Or(ev.InvocationID, id.invocationID) for nested-runner forwarded events.
    • Dropped the redundant finished re-check (live-to-completed handoff and pointer reads both happen under tm.mu) and added unit + runner.Run tests pinning every branch (43/43 single-branch go test -overlay mutants killed).
  • completedTrace.parentAgent: Removed along with all three clone/copy sites so late-callback parent placement matches main without per-completion map clones.
  • Smaller items:
    • Rewrote isGoroutineTraceHeader (cutTracebackLabels / cutTracebackLabelString) to parse quoted strings, accepting both Go 1.26 [status labels:{"k": "v"}] (including ] [ inside label values) and Go 1.27 [status] {k: v} headers (14/14 header mutants killed), while preserving main's inline runtime.Stack call depth in currentGoroutine() (pinned by anti-regression test TestWorkflowRetry_DeepBeforeAgentStackAtTracebackLimit_EmitsCompleted).
    • Added a direct derefContextStructValue subtest pinning the visited-pointer check, pointer-type disambiguation at the same address, and 511 vs. 513 dereferences around the 512-dereference bound (3/3 deref mutants killed), and clarified the comment on the outer 512-step cycle cases.
    • Updated the actionMaps comment to state GC reachability rather than stack-growth movement, replaced hasSubstr with strings.Contains, fixed the PR description (ctx.Value chain walk rather than O(1), separate retiredSwallower/retiredCause row clarifying O(N) backing-array slice copies vs. O(N²) duplicate-check comparisons across an N-ancestor chain, and explicit note on newClockedPlugin's DisableFlushOnRunEnd = true), and scoped the mutex-guarded context subtest name to the two helpers it exercises.

@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 #2380 (review).

@wojtas000

Copy link
Copy Markdown
Contributor

This conflicts with main in trace_manager_test.go. Could you resolve it along with the scope-tracking change from my review?

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 #2380 cleanly onto #2381 as Layer 4 of the linear stack (main <- #2375 <- #2180 <- #2381 <- #2380 <- #2389). The zero-alloc uuidProviders scope-tracking fix from review is preserved intact, and all 15 CI checks are green.

@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 #2380 (review).

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks @caohy1988 for the thorough review! Rebased the stack (#2375 -> #2180 -> #2381 -> #2380 -> #2389) and addressed both the blocking stack-description mismatch and all non-blocking points:

  1. Blocking — Stack scope, PR description, and upstream fixes (#2375, #2180, #2381):

    • Updated the PR description to state right at the top: Stacked PR: depends on #2375, #2180, and #2381; review the top commit only.
    • Restated the API, apidiff, and behavior claims relative to #2381 (zero exported API or emitted-row changes in the top #2380 commit relative to #2381), while explicitly listing the 9 additive #2180 exports (Config.OnSchemaReady, Config.OnSchemaError, Config.ToolResultClassifier, ToolResultClassifier, ToolResultDecision, ToolResultVerdict, ToolResultAbstain, ToolResultOK, ToolResultError) and the #2375/#2180/#2381 behavior changes carried underneath until those PRs merge.
    • Rebased onto the updated #2375, #2180, and #2381 heads, where all of the inherited issues you flagged are fixed underneath:
      • #2180 (views.go, bigquery_agent_analytics_plugin.go, trace_manager.go): unverifiedViewConflictError.Error() formats only structured fields (view name, operation, and HTTP/gRPC status codes) while exposing the underlying DDL and GetMetadata errors exclusively via Unwrap() []error (preventing raw HTTP response bodies from leaking into SyncViews errors or startup logs), runToolResultClassifier warning logs omit tool/function names from call events, and finish_task span matching is scoped across reused call IDs so a sibling activation's failed attempt or delayed completion does not misattribute spans.
      • #2381 (bigquery_agent_analytics_plugin.go, trace_manager.go): Built-in retry-and-reflect error_details/error_type extraction honors suppressesToolPayload() (writing the fixed fallback error_message whenever Config.ContentFormatter != nil or "content" is in Config.PayloadColumnDenylist), built-in retry-and-reflect classification as TOOL_ERROR runs before Config.ToolResultClassifier so an OK return from a custom classifier cannot hide a retry-and-reflect payload, duplicate TOOL_COMPLETED / AGENT_RESPONSE rows after an already-recorded TOOL_ERROR are suppressed, and empty/missing function-call IDs are handled cleanly.
  2. Bounded uuidProviderLedger & compacted completedTrace retention (trace_manager.go, trace_manager_test.go):

    • Capped live per-invocation uuidProviderLedger.states at maxUUIDProviderEntries = 512. Once full, new path-specific observations fold conservatively into the (name, branch, anyPath: true) and (name, anyBranch: true, anyPath: true) summary keys without growing the map, preserving uuidProviderCustom for pure custom histories and failing closed (uuidProviderMixed) on mixed custom/default histories. Default-provider runs still allocate 0 B (nil ledger).
    • Added compactForCompleted() in rememberCompletedAtLocked, dropping per-path keys into a freshly allocated summary map (<= 32 entries, < 1 KB retained per completedTrace even after 20,000 distinct node paths).
    • Pinned live bounding, mixed-overflow fail-closed behavior, and < 1 KB completed-run retention in TestUUIDProviderLedger_BoundedAcrossDistinctPathsAndCompletedRuns.
  3. Eviction preservation, untracked ev.InvocationID, "user" author, and bounded / walk (trace_manager.go, bigquery_agent_analytics_plugin.go, trace_manager_test.go):

    • Eviction & restoration: Carried uuidProviders on evictedTrace (savedIdentity()) and restored it in restoreEvicted (and consulted tm.evicted in eventUUIDProviderFor / isTrackedInvocation) so provenance verdicts do not flip across eviction and restoration.
    • Untracked foreign ev.InvocationID: When ev.InvocationID != "" and ev.InvocationID != id.invocationID, hasEventCreationProvenance uses ev.InvocationID if tracked (nested runner sharing the plugin), and fails closed (false) if ev.InvocationID is untracked while id.invocationID is tracked rather than falling back to delivery ctx.
    • "user" / empty ev.Author & / ancestor walk: eventUUIDProviderFor checks id.agentName on "user" or empty ev.Author before falling back to run.isRunCustom() (so WithUUIDProvider(ctx, nil) sub-agents fail closed), caps / ancestor walks at maxUUIDProviderAncestorSteps = 8 without falling back to path == "", and documents the external-storage provenance boundary on hasEventCreationProvenance.
    • Added unit subtests in TestEventUUIDProvider covering each case.
  4. Cycle-safe contextParentMap & contextPath (bigquery_agent_analytics_plugin.go, trace_manager.go, trace_manager_test.go):

    • Switched both the outer wrapper dereference loop and the inner params dereference loop in contextPath (and contextParentMap) to derefContextStructValue, and added "InvocationContext" and "ReadonlyContext" to the struct-field lists walked by contextPath and contextParentMap (while keeping extractCallbackAfterAgentActionsValue restricted to stdlib "Context"/"cancelCtx"/"c" and ADK agent "context").
    • Added "contextParentMap, contextPath, and identityOf survive cyclic ctx any and params any wrappers" in TestContextLookups_WrapperIsolationAndSafety (running contextParentMap, contextPath, and identityOf against self-referential cyclic ctx and params any wrappers so reverting either contextParentMap or contextPath to its old inline loop fails the test), alongside "nil, cyclic, deep-bounded, and panicking Value contexts fail closed" covering cyclic inputs to callbackAfterAgentActions / extractCallbackAfterAgentActionsValue.

@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 #2380 (review).

@wojtas000
wojtas000 dismissed their stale review November 19, 2026 10:51

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.

@haiyuan-eng-google
haiyuan-eng-google force-pushed the fix/bqaa-2182-4-event-provenance-and-ctx-walkers branch from 0ca6483 to 01821a6 Compare November 19, 2026 19:06
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks @caohy1988 and @wojtas000 for the detailed reviews — rebased the stack cleanly onto main (#2180 (621b5462) -> #2381 (8f3621c8) -> #2380 (01821a6c)) and addressed every item on #2380 (while all inherited #2180/#2381 items are also fixed underneath):

  1. Allowlisted, directStructField-based contextPath & contextParentMap (Blocking Add continuous integration #3 & @wojtas000 alloc optimization; bigquery_agent_analytics_plugin.go, trace_manager.go, trace_manager_test.go):

    • Replaced arbitrary reflect.Value.FieldByName searches and field traversal with a shared allowlist (adkContextChildren) restricted to Go stdlib "context" (Context, cancelCtx, c), agent (commonContext, invocationContext, callbackContextWrapper, toolContextWrapper), internal/context (InvocationContext, ReadonlyContext), internal/llminternal (cancelledToolContext), agent/remoteagent/v2 (authContext), and server/adka2a/v2 (executorContext) using directStructField. Non-ADK / application-owned struct fields are skipped unread.
    • Eliminated routine walker heap allocations using precomputed package-path variables, duplicate-child pointer deduplication in adkContextChildren, a stack-backed [16]reflect.Value queue (contextStructQueue), and lazy cycle tracking (steps >= 32 / derefs >= 4 in derefContextStructValueLazy).
    • Updated TestContextLookups_WrapperIsolationAndSafety (verifying both allowlisted ADK/stdlib wrappers and that non-ADK/concurrently mutated application wrappers fail closed with zero races under -race) and extended BenchmarkContextLookups (contextPath: 6749–7623 ns/op, 0 B/op, 0 allocs/op; callbackAfterAgentActionMaps: 635.5–750.3 ns/op, 0 B/op, 0 allocs/op; contextHasCustomUUIDProvider: 67.03–69.44 ns/op, 0 B/op, 0 allocs/op; contextPathEmpty: 336 B/op, 2 allocs/op; contextParentMap: 2520 B/op, 13 allocs/op).
  2. Smaller Bump the go_modules group across 1 directory with 2 updates #1 — Compact evictedTrace.uuidProviders in markEvictedLocked (trace_manager.go, trace_manager_test.go):

    • markEvictedLocked now compacts ev.uuidProviders = ev.uuidProviders.compactForCompleted(), bounding retained keys on evicted traces to maxCompletedUUIDProviderEntries (32). Pinned in TestUUIDProviderLedger_BoundedAcrossDistinctPathsAndCompletedRuns/evicted_invocations_compact_uuidProviders_to_<=_maxCompletedUUIDProviderEntries.
  3. Smaller Initial commit of Go ADK #2 — Cap late-activation ledgers after default-provider completions (trace_manager.go, trace_manager_test.go):

    • noteUUIDProviderLocked initializes new ledgers with compacted: inv.isLate, pathOverflowed: inv.isLate so late activations following a default-provider run stay capped at maxCompletedUUIDProviderEntries (32). Pinned in TestUUIDProviderLedger_BoundedAcrossDistinctPathsAndCompletedRuns/late_activations_after_default-provider_completion_stay_bounded_at_maxCompletedUUIDProviderEntries.
  4. Smaller Add continuous integration #3 — Prevent eviction racing first custom-provider observation (trace_manager.go, trace_manager_test.go):

    • invocationSpan and pushAgentSpan compute customUUIDs := contextHasCustomUUIDProvider(ctx) before acquiring tm.mu and pre-attach inv.uuidProviders (and late.uuidProviders) inside lookupInvocationWithUUID while tm.mu is held, so a concurrent evictLocked shares the live *uuidProviderLedger pointer with tm.evicted[id]. Pinned deterministically and concurrently under -race with maxTracked = 1 in TestEventUUIDProvider/eviction_between_lookup_and_noteUUIDProviderLocked_preserves_first_custom_provider_observation.
  5. Smaller Fix lint errors #4 — Fail closed on disabled worker branches in eventUUIDProviderFor (trace_manager.go, trace_manager_test.go):

    • uuidProviderLedger now tracks bounded per-branch summary state (branchStates + branchSummaryOverflow, also compacted to <= 32 entries in compactForCompleted), and eventUUIDProviderFor checks dot-separated ancestor branch prefixes of cmp.Or(branch, fallbackBranch) (plus overflow) so unrecorded authors, "user"/"" authors delivered under root, and nested sub-branches under a WithUUIDProvider(ctx, nil) worker branch fail closed (false, true). Pinned in TestEventUUIDProvider/disabled_worker_branch_fails_closed_for_unrecorded_authors,_user/empty_authors,_and_sub-branches.
  6. Base stack & verification at 01821a6c (identical tree 9d57e921):

    • Rebased onto #2180 (621b5462, including platform.Now(ctx) before inv.mu in pushAgentSpan, finish_task attribution, reconciled evicted+restored completion, and sanitized logger arguments) and #2381 (8f3621c8, including dispatch-scoped completedTools retirement); #2380 preserves uuidProviders across the reconciled evicted+restored completion path.
    • 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 between #2381 (8f3621c8) and #2380 (01821a6c): 0 API changes (APIDIFF_LEN=0).
    • Targeted -race -mod=readonly -count=1 on 01821a6c: PASS (12.566s); full plain go -C plugin/agentanalytics test -mod=readonly -count=1 ./... (on identical tree 9d57e921): PASS (154.451s).

@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 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 embeds agent.Context, and the Path() 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_id matches the right node's AGENT_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 public Path() would fix it.
  • A rewritten finish_task result 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's AGENT_COMPLETED ends 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 live StateDelta/ArtifactDelta while an OnToolErrorCallback on another goroutine can replace them without the invocation lock. Buffering the first call_0 response 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
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 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.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 Rebased cleanly onto #2381 (cdd02642, on main 98275d2f) -> 28b2b88f (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.

@wojtas000

Copy link
Copy Markdown
Contributor

#2381 is merged. Same as before: git rebase --onto main cdd02642 on this branch replays only your commit, and it applies cleanly on main. #2389 then goes on top. Both are approved.

…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.
@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-4-event-provenance-and-ctx-walkers branch from 28b2b88 to 402b155 Compare November 19, 2026 21:42
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 Rebased cleanly onto main (b758093d, dropping the merged #2381 commit) -> 402b155c, and stacked #2389 (483a00b8) on top (0-byte diff in plugin/agentanalytics/ relative to the approved trees). CI is running now.

@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 0fe0615 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
…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.
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