Visitar URL original
Agent analytics can drop or mis-parent AGENT_STARTING spans after #2379 · Issue #2413 · google/adk-go · GitHub
Skip to content

Agent analytics can drop or mis-parent AGENT_STARTING spans after #2379 #2413

Description

@caohy1988

#2379 changed how the analytics plugin decides which open agent a child run belongs to. It now walks the child's context with reflection while the invocation mutex is held, and a few ordinary wrapper shapes make that walk go wrong.

I rechecked this on current main (f01ccf87) and on the #2379 merge itself (673050266). Same failures in both places.

What breaks

In plugin/agentanalytics/trace_manager.go, launcherLocked (starting at line 1274):

  • Line 1290 returns immediately if the activation isn't a pointer, so a struct value that embeds context.Context loses launch lineage. Line 1283 has the same pointer-only check when recording known activations.
  • Line 1301 uses FieldByName("Context") on whatever struct it landed on. If that name is a promoted field behind a nil embedded pointer, the lookup panics. beforeAgent recovers it (bigquery_agent_analytics_plugin.go:1066, logged at line 705) and the AGENT_STARTING row is dropped. If Context is just some other field, the walk can follow the wrong parent.
  • Line 1261 caps the walk at 64 steps (maxLaunchLineage), so a chain of ordinary context.WithValue wrappers deeper than that also loses lineage.
  • Lines 1302 and 1305 call IsNil / Interface on that field without using any lock the context value itself might be using. go test -race flags a read there against a concurrent write to a wrapper that guards its parent with an RWMutex.

There's a related case with two nested workers of the same name and a peer worker still open: the leaf is attributed to root instead of the unique selected parent on its branch (appendPossibleOwnersLocked at line 1426, then the ambiguity handling around 1397–1412).

Expected vs actual

I used a small dispatcher fixture: root starts worker 1, worker 1 stays open, and worker 2 submits the leaf. The leaf's AGENT_STARTING parent should be worker 2, and that start row should always be emitted.

On main:

  • pointer wrapper: parent is worker 2 (this one is fine)
  • value wrapper: leaf parent is worker 1
  • nil optional embedded *struct{ Context context.Context }: 0 AGENT_STARTING rows for the leaf, 1 AGENT_COMPLETED, and dropped AGENT_STARTING event: recovered panic of type string
  • side field named Context pointing at root: parent is root
  • 70 stacked context.WithValue wrappers: parent is worker 1

A second fixture, worker → mid → worker → selected with a sibling worker still open and the leaf started from a two-hop context.WithoutCancel helper, records the leaf under root instead of selected.

The race test (TestReviewSynchronizedContext with -race) fails on a read in launcherLocked at trace_manager.go:1302 (and :1305) during beforeAgent.

Repro

Drop the test below into plugin/agentanalytics and run it with a go.work that uses both the repo root and ./plugin/agentanalytics (the plugin module pins google.golang.org/adk/v2 v2.0.0, which won't build on its own):

go test -mod=readonly -count=1 -run '^TestReviewDispatcher$' .
package agentanalytics

import (
	"context"
	"iter"
	"sync/atomic"
	"testing"

	"google.golang.org/adk/v2/agent"
	"google.golang.org/adk/v2/session"
)

type reviewValueContext struct{ context.Context }
type reviewContextMethods interface{ context.Context }
type reviewMetadata struct{ Context context.Context }
type reviewOptionalMetadata struct {
	reviewContextMethods
	*reviewMetadata
}
type reviewSideContext struct {
	reviewContextMethods
	Context context.Context
}
type reviewKey struct{}

func reviewWrap(ctx, outer context.Context, kind string) context.Context {
	switch kind {
	case "pointer":
		return &reviewValueContext{ctx}
	case "value":
		return reviewValueContext{ctx}
	case "nil_optional":
		return &reviewOptionalMetadata{reviewContextMethods: ctx}
	case "side_field":
		return &reviewSideContext{reviewContextMethods: ctx, Context: outer}
	case "deep":
		for i := 0; i < 70; i++ {
			ctx = context.WithValue(ctx, reviewKey{}, i)
		}
		return ctx
	default:
		return ctx
	}
}

func TestReviewDispatcher(t *testing.T) {
	for _, kind := range []string{"direct", "pointer", "value", "nil_optional", "side_field", "deep"} {
		t.Run(kind, func(t *testing.T) { reviewRunDispatcher(t, kind) })
	}
}

func reviewRunDispatcher(t *testing.T, kind string) {
	p, requests, _ := setupTestPlugin(t)
	leaf := newOneEventAgent(t, "leaf", nil)
	type item struct {
		ev  *session.Event
		err error
	}
	var dispatch chan<- func()
	var workerCalls atomic.Int32
	var rootCtx context.Context
	worker, err := agent.New(agent.Config{
		Name:      "worker",
		SubAgents: []agent.Agent{leaf},
		Run: func(ctx agent.InvocationContext) iter.Seq2[*session.Event, error] {
			return func(yield func(*session.Event, error) bool) {
				if workerCalls.Add(1) == 1 {
					ev := session.NewEvent(ctx, ctx.InvocationID())
					ev.Author = "worker"
					ev.Branch = ctx.Branch()
					ev.Content = textContent("model", "worker 1 ok")
					yield(ev, nil)
					return
				}
				leafEvents := make(chan item, 4)
				job := func() {
					defer close(leafEvents)
					for ev, runErr := range leaf.Run(ctx.WithContext(reviewWrap(ctx, rootCtx, kind))) {
						leafEvents <- item{ev: ev, err: runErr}
					}
				}
				if kind == "nil_optional" || kind == "side_field" {
					job()
				} else {
					select {
					case dispatch <- job:
					case <-ctx.Done():
						yield(nil, ctx.Err())
						return
					}
				}
				for it := range leafEvents {
					if !yield(it.ev, it.err) || it.err != nil {
						return
					}
				}
			}
		},
	})
	if err != nil {
		t.Fatalf("agent.New(worker): %v", err)
	}
	root, err := agent.New(agent.Config{
		Name: "root",
		Run: func(ctx agent.InvocationContext) iter.Seq2[*session.Event, error] {
			return func(yield func(*session.Event, error) bool) {
				jobs := make(chan func())
				dispatcherDone := make(chan struct{})
				go func() {
					defer close(dispatcherDone)
					for job := range jobs {
						job()
					}
				}()
				defer func() {
					close(jobs)
					<-dispatcherDone
				}()
				rootCtx = ctx
				dispatch = jobs
				for ev, runErr := range worker.Run(ctx) {
					worker2Events := make(chan item, 8)
					go func() {
						defer close(worker2Events)
						for ev, runErr := range worker.Run(ctx) {
							worker2Events <- item{ev: ev, err: runErr}
						}
					}()
					for it := range worker2Events {
						if !yield(it.ev, it.err) {
							return
						}
					}
					if !yield(ev, runErr) {
						return
					}
				}
			}
		},
	})
	if err != nil {
		t.Fatalf("agent.New(root): %v", err)
	}
	for _, runErr := range newTestRunner(t, root, p).Run(t.Context(), "u1", "s1", textContent("user", "go"), agent.RunConfig{}) {
		if runErr != nil {
			t.Fatalf("runner.Run error: %v", runErr)
		}
	}

	rows := collectRows(t, requests, untilInvocationEnd)
	onlyRowOfType(t, rows, EventInvocationCompleted)
	workerStarts := agentRowsOfType(rows, EventAgentStarting, "worker")
	if len(workerStarts) != 2 {
		t.Fatalf("worker AGENT_STARTING count = %d, want 2", len(workerStarts))
	}
	w1Span := workerStarts[0]["span_id"]
	w2Span := workerStarts[1]["span_id"]
	roots := agentRowsOfType(rows, EventAgentStarting, "root")
	leaves := agentRowsOfType(rows, EventAgentStarting, "leaf")
	ends := agentRowsOfType(rows, EventAgentCompleted, "leaf")
	if len(roots) != 1 || len(leaves) != 1 || len(ends) != 1 {
		t.Fatalf("root starts %d, leaf starts %d, leaf completions %d; want one of each", len(roots), len(leaves), len(ends))
	}
	got := leaves[0]["parent_span_id"]
	if got != w2Span {
		t.Fatalf("leaf parent matches worker 1=%t, root=%t; want worker 2", got == w1Span, got == roots[0]["span_id"])
	}
}

Activity

  1. caohy1988 commented on Nov 18, 2026

    @caohy1988
    Author

    I can reproduce this on main at f01ccf8. The direct and pointer-wrapper cases attribute the leaf correctly to worker 2, but the other shapes in the report fail as described.

    Confirmed cases, roughly in order of how much they matter:

    • Nil embedded metadata drops the start row. FieldByName("Context") at trace_manager.go:1301 walks through the nil embedded pointer and panics; beforeAgent recovers it and the leaf gets 0 AGENT_STARTING, 1 AGENT_COMPLETED and a drop. With a same-named leaf already open, the stray completion also reuses that leaf's span ID through the name fallback. That wrapper shape is unusual but valid, so I'd treat this as the most important one.
    • Data race on synchronized wrappers. IsNil/Interface at lines 1302 and 1305 read a parent field that the wrapper updates under its own write lock; the invocation mutex can't protect that. go test -race flags it, and the older contextPath walk races the same way independently of duplicate agents. Worth fixing promptly even if mutable wrappers are rare.
    • Value wrappers and context.WithoutCancel. The pointer-only checks at lines 1283 and 1290 stop at an intermediate value, so both select worker 1. Detached background jobs make this a practical case, since WithoutCancel forwards values through a private parent field.
    • A side field named Context sends the walk to the wrong parent (root), and a deep WithValue chain loses lineage at the 64-step cap (62 layers reach the parent, 63 miss).
    • Nested same-name workers with a live peer demote the leaf to root because the outer and inner workers both count the same descendant. Assigning qualifying spans to their nearest eligible member, and only demoting when distinct members have independent matches, would fix it while keeping the genuinely ambiguous case at root.
    • One more along the same lines: with distinct siblings on the same branch and path, a leaf launched by left with its original context is attributed to the newer sibling right, because distinct names skip the launcher lookup and the reverse stack scan wins.

    For the longer-term fix, I think the reflection walk is the wrong foundation. Installing an immutable per-run token at agent.Run entry, linked to the submitter's token and read through a supported accessor before taking the invocation mutex, would resolve the nearest open activation through any value-forwarding wrapper at any depth and remove the race. In the short term, the plugin could stop inspecting unfamiliar context types, always emit the start row, and guard completions against claiming a different known activation. The open design question is how to attribute a child whose caller deliberately discards inherited values; a unique branch/path owner, or failing that the common ancestor, seems like a conservative fallback.

    None of the open agentanalytics PRs (#2375, #2180, #2381, #2380, #2389) change launcherLocked, excludePeerLookalikesLocked, parentForRunLocked or appendPossibleOwnersLocked, so this stays open after they land. I'd put it at high priority given the dropped start row and the race.

    One note on the repro: the plugin module pins google.golang.org/adk/v2 v2.0.0, which doesn't build standalone, so it needs a go.work using both the repo root and the plugin (and the checkout currently wants Go 1.26.10).

  2. added
    bug
    on Nov 19, 2026
  3. added 4 commits that reference this issue on Nov 19, 2026
    f37e54c
    e98ddf5
    0351594
    a725e2c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions