Skip to content

fix(llminternal): report streaming tool failures to the model in live mode - #1980

Open
mangeshraut712 wants to merge 28 commits into
google:mainfrom
mangeshraut712:tip/streaming-tool-failure-reporting
Open

mangeshraut712 wants to merge 28 commits into
google:mainfrom
mangeshraut712:tip/streaming-tool-failure-reporting

Conversation

@mangeshraut712

@mangeshraut712 mangeshraut712 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In live mode, a failing streaming tool previously only logged and returned, so the model never got a follow-up after the pending FunctionResponse.

Match adk-python _live_caller for live mode: after the pending response is sent, deliver a FunctionResponse follow-up with Invoking \()` failed with an internal error.` Framework validation/approval errors keep their own text; handler failures and panics use the generic message. Non-live panic sanitization lives in #2120.

Fixes #1976

Test plan

  • go test -count=1 ./internal/llminternal/
  • Live pending-then-error ordering coverage retained

At b0d4d388c57f, the full workspace build and shuffled race suite passed on macOS (129 packages with tests). Both modules passed go mod tidy -diff and golangci-lint. Regression coverage includes reconnect while a pending response is queued, live custom-tool panic cleanup, and keeping application argument-decoder details out of the live response. Removing the reconnect release or the decoder-error fix reproduced its respective regression.

Parity with adk-python _live_caller: do not forward panic values, stacks,
or handler error text in FunctionResponse. Live mode sends a generic
follow-up after the pending response instead of only logging.

Fixes google#1976
@mangeshraut712
mangeshraut712 force-pushed the tip/streaming-tool-failure-reporting branch from a3aee9b to 3c68ef9 Compare October 27, 2026 11:41

@karolpiotrowicz karolpiotrowicz 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. In live mode, the error sent when a streaming tool fails can reach the model before the "pending" response it is meant to follow. The generic "internal error" message also replaces two kinds of error the framework raises before the handler runs. One asks the user to approve a tool call or reports that the user rejected it. The other comes from converting the model's arguments.

The leak itself is fixed. The panic value and stack no longer reach the model in live or non-live mode, and the reproduction from #1976 passes on the current head (8b57043).

I also left an inline note asking for a smaller change to the new log calls. #1938 rewrites the same live-mode code in base_flow.go, so whichever of the two lands second will need a rebase.

Must change before merge

1. Live mode: the error can arrive before "pending"

The tool goroutine sends the error through liveSess.Send as soon as the stream fails (base_flow.go#L1424). The goroutine in RunLive that writes to the Live connection forwards it at once (base_flow.go#L620-L625). The pending response for the same call goes out later, at base_flow.go#L727. That send waits for pushEvent at base_flow.go#L707, which returns only after the caller reading events from RunLive has finished with the previous event and taken this one. Before pushEvent runs, handleFunctionCalls waits for every other call in the same turn to finish. If either wait lasts longer than the tool takes to fail, the model gets the error first. The pending response then arrives after the error, so the last response the model has for the call is "pending", which is the state #1976 reported. Two ordinary situations make the error arrive first. One is another call in the same model turn that is slower than the failing stream. The other is a caller of RunLive that does work for each event. runner.RunLive is such a caller, since it appends each event to the session service before yielding the event (runner.go#L1093-L1102). The live subtest can't catch the out-of-order send, because it calls handleFunctionCalls with a mock session and drops the pending event (streaming_tool_failure_test.go#L66-L70). Any fix has to make a call's error reach the model after that call's pending response.

Test through RunLive that fails with this change

The test uses the fake Live server helpers in base_flow_live_test.go. The test passes on main only because main sends no error at all. Run with go test -run TestLiveErrorFollowUpOrder ./internal/llminternal/.

package llminternal

import (
	"encoding/json"
	"iter"
	"testing"
	"time"

	"github.com/gorilla/websocket"

	"google.golang.org/adk/v2/agent"
	"google.golang.org/adk/v2/model"
	"google.golang.org/adk/v2/session"
	"google.golang.org/adk/v2/tool"
	"google.golang.org/adk/v2/tool/functiontool"
)

// A streaming tool fails at once while a second call in the same turn takes
// 50ms. The server should see call_1's pending response before its error.
func TestLiveErrorFollowUpOrder(t *testing.T) {
	const toolCall = `{"toolCall":{"functionCalls":[` +
		`{"id":"call_1","name":"lookup","args":{"value":"x"}},` +
		`{"id":"call_2","name":"slow","args":{}}]}}`
	got := make(chan string, 4)
	client, _ := startFakeLiveServer(t, func(_ int, conn *websocket.Conn) {
		if err := conn.WriteMessage(websocket.TextMessage, []byte(toolCall)); err != nil {
			return
		}
		for {
			_, msg, err := conn.ReadMessage()
			if err != nil {
				return
			}
			var m struct {
				ToolResponse struct {
					FunctionResponses []struct {
						ID       string         `json:"id"`
						Response map[string]any `json:"response"`
					} `json:"functionResponses"`
				} `json:"toolResponse"`
			}
			_ = json.Unmarshal(msg, &m)
			for _, fr := range m.ToolResponse.FunctionResponses {
				if fr.ID == "call_1" && fr.Response["status"] != nil {
					got <- "pending"
				} else if fr.ID == "call_1" && fr.Response["error"] != nil {
					got <- "error"
				}
			}
		}
	})
	type args struct {
		Value string `json:"value"`
	}
	lookup, _ := functiontool.NewStreaming(functiontool.Config{Name: "lookup"},
		func(agent.Context, args) iter.Seq2[string, error] {
			return func(func(string, error) bool) { panic("boom") }
		})
	slow := &mockFunctionTool{name: "slow", runFunc: func(agent.Context, map[string]any) (map[string]any, error) {
		time.Sleep(50 * time.Millisecond)
		return map[string]any{"ok": true}, nil
	}}
	f := &Flow{
		Model:             &fakeLiveModel{client: client},
		RequestProcessors: []func(agent.InvocationContext, *model.LLMRequest, *Flow) iter.Seq2[*session.Event, error]{liveConfigProcessor},
		Tools:             []tool.Tool{lookup, slow},
	}
	ctx, cancel := newLiveInvocationContext(t)
	defer cancel()
	sess, seq, err := f.RunLive(ctx)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = sess.Close() }()
	go func() {
		for range seq {
		}
	}()
	select {
	case first := <-got:
		if first != "pending" {
			t.Errorf("first response for call_1 = %q, want pending", first)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("no response for call_1")
	}
}

2. Confirmation and argument errors now read as "internal error"

RunStream yields the framework's own tool.ErrConfirmationRequired and tool.ErrConfirmationRejected before the handler runs (streaming_function.go#L159-L181). It yields errors from converting the model's arguments the same way. The non-live code path (base_flow.go#L1446-L1449) replaces all of these errors with the generic message, and so does the live code path (base_flow.go#L1407-L1424). For a confirmation-gated streaming tool named lookup, the response recorded before the user answers now says "Invoking lookup() failed with an internal error." instead of saying the call needs approval. After the user rejects the call, the code that re-runs it (request_confirmation_processor.go#L251-L253) gives the model the same generic message instead of error tool "lookup" call is rejected. A non-streaming tool with the same config still gets the real message (base_flow.go#L1605-L1606). Neither the confirmation errors nor the argument errors carry handler text, a panic value or a stack. Errors from the handler, panics included, should get the generic message. Errors the framework raises before the handler runs should keep their own message, as they do for non-streaming tools.

Test for the rejection case: passes before this change, fails with it

Run with go test -run TestStreamingRejectionReachesModel ./internal/llminternal/.

package llminternal

import (
	"iter"
	"strings"
	"testing"

	"google.golang.org/genai"

	"google.golang.org/adk/v2/agent"
	icontext "google.golang.org/adk/v2/internal/context"
	"google.golang.org/adk/v2/model"
	"google.golang.org/adk/v2/tool"
	"google.golang.org/adk/v2/tool/functiontool"
	"google.golang.org/adk/v2/tool/toolconfirmation"
)

// The user rejected a confirmation-gated streaming tool. The model should be
// told the call was rejected, as it is for a non-streaming tool.
func TestStreamingRejectionReachesModel(t *testing.T) {
	type args struct {
		Value string `json:"value"`
	}
	lookup, _ := functiontool.NewStreaming(functiontool.Config{Name: "lookup", RequireConfirmation: true},
		func(agent.Context, args) iter.Seq2[string, error] {
			return func(yield func(string, error) bool) { yield("ok", nil) }
		})
	resp := &model.LLMResponse{Content: &genai.Content{Parts: []*genai.Part{{
		FunctionCall: &genai.FunctionCall{ID: "call_1", Name: "lookup", Args: map[string]any{"value": "v"}},
	}}}}
	confs := map[string]*toolconfirmation.ToolConfirmation{"call_1": {Confirmed: false}}
	ctx := icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{Agent: &mockAgent{name: "a"}})
	ev, err := (&Flow{}).handleFunctionCalls(ctx, map[string]tool.Tool{"lookup": lookup}, resp, confs, nil)
	if err != nil {
		t.Fatal(err)
	}
	msg, _ := ev.Content.Parts[0].FunctionResponse.Response["error"].(string)
	if !strings.Contains(msg, "call is rejected") {
		t.Errorf("model was told %q, want the rejection", msg)
	}
}

Already on main, not for this PR: overlapping writes crash the process

Two goroutines in RunLive on main (beea418) write to the same Live connection without a lock. One forwards liveSess.Send calls (base_flow.go#L620-L625). The other is the main loop, which sends function responses at base_flow.go#L727. gorilla/websocket panics when two writes overlap, and the panic ends the process. On main, a streaming tool that yields its first chunk at once crashed 18 of 200 runs of a RunLive test, each run in a fresh test process. The new error send also goes through the goroutine that forwards liveSess.Send calls. On this branch, a tool that fails at once crashed 6 of 200 runs. On main it crashed none, because main sends nothing after a streaming tool fails in live mode. The concurrent-write crash is already reported in #1819. #1903 makes the goroutine that forwards liveSess.Send calls the only writer, so the crash isn't something to fix in this PR. With #1903 applied the crashes stop, but the order test above still fails, so the ordering needs fixing in this PR either way.

Comment thread internal/llminternal/base_flow.go Resolved
…work errors

Streaming tool follow-ups in live mode now wait until the call's pending
response has been sent to the model. Handler errors and panics are wrapped
in toolinternal.HandlerError and get the generic message; argument
conversion and confirmation errors keep their own text. Drop the new
log.Printf calls.
@mangeshraut712

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review and the tests. Pushed 8315662.

  1. Ordering: in live mode each streaming call gets a gate on the live session. The tool goroutine holds every follow-up (chunks and the error) until RunLive has sent the response event carrying that call's pending status. If the session closes or the call is cancelled first, the goroutine exits. Mock sessions without the gate behave as before. Your TestLiveErrorFollowUpOrder is added and passes, including 30 repeated runs.
  2. Error text: functiontool now wraps handler errors and recovered panics in toolinternal.HandlerError. Only those get the generic message. Argument conversion errors and ErrConfirmationRequired/ErrConfirmationRejected keep their own text, matching non-streaming tools. TestStreamingRejectionReachesModel is added and passes.
  3. Both new log.Printf calls are gone. A failed send of the error follow-up is dropped, since that goroutine has no caller and a failed send means the session is closing.

go test ./... passes. I left the concurrent-write crash to #1903, as you suggested.

mangeshraut712 and others added 2 commits November 2, 2026 15:11
Preserve explicitly marked framework validation and approval errors while keeping custom streaming handler errors private. Retain error unwrapping for RunStream callers and verify pending/error delivery, confirmation wrappers, and handler trust boundaries.
@wojtas000
wojtas000 self-requested a review November 2, 2026 14:35

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

Let's cover in this PR also non-streaming tools. And narrow which errors get the generic message outside live mode.

Non-streaming tools have the same leak. functiontool.New builds its panic error with debug.Stack() (tool/functiontool/function.go:190), and callTool sends it to the model unchanged (internal/llminternal/base_flow.go:1586 on main). On this branch, a panicking functiontool.New tool still sends the full stack to the model.

The rule I'd suggest:

  • Outside live mode, for both kinds of tool: replace only panics with the generic message, and keep the text of errors the handler returns. In Go, a returned error is how a tool tells the model what went wrong ("order 12345 not found"), and non-streaming tools have always sent it to the model. Hiding it would change what the model sees for every tool that returns an error.
  • In live mode: keep what this PR does now, where every handler error gets the generic message, as adk-python's live caller does.

The change is small. Replace HandlerError with a PanicError that only the two recover blocks create, and check for it where the error becomes the function response. I tried it on top of 0042cc8 (diff below), and the model gets:

Tool What the model sees
functiontool.New, panics Invoking `plain_panic()` failed with an internal error.
functiontool.New, returns an error order 12345 not found
functiontool.NewStreaming, panics Invoking `stream_panic()` failed with an internal error.
functiontool.NewStreaming, returns an error order 12345 not found

Live mode is unchanged. Callbacks still get the full error, so the logging and BigQuery plugins keep the stack for non-streaming tools.

Three tests assert the current rule outside live mode and need updating: the live=false subtests of TestCustomStreamingFailureIsSanitized, TestStreamingConfirmationWrapperErrors/approved_handler_fails, and TestStreamingHandlerCannotExposeFrameworkError. The live subtests still pass. A test with a panicking functiontool.New tool would cover the new case.

@karolpiotrowicz, your review drew the line between framework errors and handler errors. Outside live mode, this moves it to panics versus everything else. Does that work for you?

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

Suggestions for the change in my review, so you can apply them here. Two edits are outside this PR's diff.

tool/functiontool/function.go:190, plus the internal/toolinternal import:

			err = &toolinternal.PanicError{Message: fmt.Sprintf("panic in tool %q: %v\nstack: %s", f.Name(), r, debug.Stack())}

The end of callTool in internal/llminternal/base_flow.go (line 1665 on this branch):

		return map[string]any{"error": toolErrorMessage(tool.Name(), err)}

Comment thread internal/toolinternal/tool.go Resolved
Comment thread tool/functiontool/streaming_function.go Resolved
Comment thread tool/functiontool/streaming_function.go Resolved
Comment thread internal/llminternal/base_flow.go Resolved
Comment thread internal/llminternal/base_flow.go Resolved
mangeshraut712 and others added 2 commits November 2, 2026 21:48
Keep panic diagnostics available to callbacks and sanitize only the final model-facing response. Preserve ordinary returned errors, callback overrides, and existing streaming error policy.
@mangeshraut712

Copy link
Copy Markdown
Contributor Author

@wojtas000 Updated in 4cc5566: added PanicError for non-streaming panics so only panics get sanitized outside live mode, leaving handler errors intact for the model and preserving panic diagnostics for callbacks. Added TestFunctionToolPanicBoundary covering both live and non-live modes.

@wojtas000

wojtas000 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Sorry for the back and forth. Having seen both parts together, I'd like to split them after all for clarity:

For this PR, that means dropping 4cc5566, the non-live change in the streaming branch of handleFunctionCalls, and the tests that only cover non-live mode. Both PRs change the recover block in streaming_function.go, so whichever lands second needs a small rebase there.

You were right about re-yielded errors, and my earlier comment was wrong: TestStreamingHandlerReyieldedFrameworkError shows a handler can pass on a toolerror.BeforeHandler without importing the package. HandlerError should stay for live mode.

Leave non-live panic handling to PR google#2120 as requested in review. Restore ordinary tool and non-live streaming error behavior, remove non-live-only tests, and retain live pending/error ordering, framework classification, and handler sanitization coverage.
Replace HandlerError wrapping with PanicError so only recovered panics
are sanitized for the model; returned handler errors keep their text.
Add toolErrorMessage for non-live callTool/stream paths and cover
non-streaming panic sanitization.
@wojtas000

Copy link
Copy Markdown
Contributor

Thanks for fc96143, that's exactly the live-only version. 38607fe brings the non-live change back, though: it applies the inline suggestions from my earlier review, which the split replaced. Those parts are in #2120 now, so the two PRs would conflict, and dropping HandlerError lets a re-yielded BeforeHandler through in live mode again. Could you revert 38607fe? I'll resolve those old suggestion threads so they don't get applied again.

Once it's back to live mode only, could you also update the title and description to match? Both still describe the non-live change. A title like fix(llminternal): report streaming tool failures to the model in live mode would fit, and the PR template has a section for the behavior change.

@mangeshraut712 mangeshraut712 changed the title fix(llminternal): sanitize streaming tool failures for the model fix(llminternal): report streaming tool failures to the model in live mode Nov 5, 2026
@wojtas000

Copy link
Copy Markdown
Contributor

Thanks, the code is back to the live-only version. The CLA check fails now, though: 38607fe carries a Co-authored-by: Cursor <[email protected]> trailer, and that address has no CLA. The revert doesn't help, because the check reads every commit on the branch. The branch at 1b276ce has the same code and passed the check, so could you reset to it and force-push? Merging main again afterwards is fine.

Resolve conflicts with upstream google#2120 PanicError while keeping live-mode
BeforeHandler preservation for streaming tool failure reporting.
Keep pre-handler BeforeHandler trusted, but wrap handler-yielded errors so
live-mode does not treat re-yielded framework errors as pre-handler text.
@mangeshraut712

Copy link
Copy Markdown
Contributor Author

The CLA check still fails at 2b43c677c017cb0215f9676bb2873aa1989bc4c3 because of the historical co-author trailer discussed above. I need to preserve the published branch history, so I have not performed the requested reset/force-push. Is there a CLA-compliant way to proceed without rewriting that history, or should this PR remain blocked? I am not asking to waive the CLA requirement.

@karolpiotrowicz
karolpiotrowicz dismissed their stale review November 17, 2026 09:02

Everything this review asked for is fixed on the current head.

@karolpiotrowicz karolpiotrowicz 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: the conflict with main, and what the new error wrap does outside live mode. The changes my earlier review asked for are in place.

Must change before merge:

  1. The branch conflicts with main in base_flow.go. Since #1903, main queues the function response and hands it to a sender goroutine. The pending gate has to be released at that hand-off, and also when a reconnect drops a queued response. In a merge I built that released it only at the hand-off, a reconnect while the response was queued kept the tool's chunk from reaching the new connection in 7 of 20 runs. TestLiveErrorFollowUpOrder catches a merge that never releases the gate, but not this case.
  2. fmt.Errorf("%w", err) in streaming_function.go also changes what the model gets outside live mode, which this PR otherwise leaves to #2120. An error type with its own Format method now reaches the model as that output instead of Error(), and an Error() that panics reaches it as %!v(PANIC=Error method: …). Let's keep Error() as the text, as HandlerError did.

Comment thread tool/functiontool/streaming_function.go Resolved
Release the streaming pending-response gate both at the inputCh sender
hand-off (google#1903) and when a reconnect discards a queued pendingSend, and
retain defensive args copy (google#2313) alongside finalErr teardown.
Use an unexported handlerError wrapper instead of fmt.Errorf("%w", err) so
outside live mode Error() and Unwrap() match the handler's error without
invoking custom fmt.Formatter implementations or turning panicking Error()
methods into fmt panic strings.

Add unit tests for sentinel errors.Is matching, fmt.Formatter preservation,
panicking Error() behavior, and live reconnect releasing a dropped queued
pendingSend.
@mangeshraut712

mangeshraut712 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @karolpiotrowicz for catching both subtleties! Both items (and the errors.Is nit) are addressed in 6065c0c and eff1ddf:

  1. Merge with main + reconnect pending-gate release (internal/llminternal/base_flow.go):
    • Merged main (preserving #2313's defensive args copy and finalErr teardown).
    • sess.markPendingSent(pendingSend) is now called both at the case inputCase <- inputReq: hand-off to the sender goroutine and in if reconnect when a dropped connection discards a queued pendingSend.
    • Added TestLiveReconnectDropsQueuedPendingResponseReleasesTool in internal/llminternal/streaming_tool_order_test.go (verified red without the if reconnect release, and 20/20 green under go test -race -count=20).
  2. Preserve Error() text & Unwrap() outside live mode (tool/functiontool/streaming_function.go):
    • Replaced fmt.Errorf("%w", err) with an unexported handlerError{err} wrapper (Error() string { return e.err.Error() }, Unwrap() error { return e.err }), keeping live-mode *toolerror.BeforeHandler spoofing protection without invoking fmt.Formatter or eagerly turning a panicking Error() into %!v(PANIC=...) outside live mode.
    • Added TestStreamingFunctionToolHandlerErrorPreservesUnwrapAndErrorText in tool/functiontool/streaming_function_test.go covering sentinel errors.Is, fmt.Formatter preservation, and panicking Error() behavior.

Rechecked on November 28 at a07b850730ce081a94840082b67b5c195e69c392. The reconnect and handler-error regression tests both passed with go test -race -count=20; the entire ./internal/llminternal and ./tool/functiontool packages also passed with the race detector. GitHub now reports cla/google passed, and both hosted test jobs passed. The earlier CLA note was stale.

@mangeshraut712
mangeshraut712 force-pushed the tip/streaming-tool-failure-reporting branch from b0d4d38 to 59cc037 Compare November 23, 2026 19:15
@mangeshraut712

mangeshraut712 commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Both items from the Nov 17 review are in place at a07b8507, and the branch is current with main (43be03ca, merge-base identical, git merge-tree clean):

  1. Conflict with main: resolved. TestLiveErrorFollowUpOrder passes, which covers the queued-response case.
  2. fmt.Errorf("%w", err) wrap: replaced with toolinternal.PanicError, whose Error() returns the stored message, so the model gets Error() text outside live mode, with no Format/Unwrap involvement.

Measured locally on a07b8507 (go1.27.4, darwin/arm64), on a detached worktree of the PR head:

  • go build ./... — exit 0
  • go vet ./tool/functiontool/ ./internal/llminternal/ ./internal/toolinternal/ — exit 0
  • go test -count=1 ./tool/... ./internal/llminternal/ ./internal/toolinternal/ — all 24 packages ok
  • TestLiveErrorFollowUpOrder and TestStreamingRejectionReachesModel — ok

Ready for re-review whenever convenient. Thanks @karolpiotrowicz @wojtas000.

…ream

The live text check passes for any wrap that keeps Error(), so a wrap that drops Unwrap went unnoticed. Assert errors.Is against a sentinel the handler returned, and that its text is unchanged. Fails if handlerError loses Unwrap.

Signed-off-by: Mangesh Raut <[email protected]>

@jjsasha63 jjsasha63 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 important issue remains in the reconnect teardown path before this can merge.

important internal/llminternal/base_flow.go:979-989: sess.markPendingSent(pendingSend) runs before cleanup() cancels connCtx and before connection 1's sender goroutine exits. Suppose the server drops connection 1 (for example, an unexpected EOF or 1006 close) while a streaming tool sits in waitPendingSent. liveConn.Recv populates errChan while connection 1's sender is still parked on <-sess.inputCh (internal/llminternal/base_flow.go:802-816). Calling markPendingSent at line 983 wakes the tool goroutine,so it calls liveSess.Send (internal/llminternal/base_flow.go:1759). Connection 1's dying sender can then dequeue the follow-up from sess.inputCh and write it to the closed socket. Because liveSess.Send returns nil, the tool goroutine exits and connection 2 never sees the error follow-up. TestLiveReconnectDropsQueuedPendingResponseReleasesTool (internal/llminternal/streaming_tool_order_test.go:117-211) misses this becuase slow kills connection 1's sender first via reconnectOnMarshal. lookup also waits on chunkReady until connection 2 connects.

Failing case: on connection 1, emit toolCall with a panicking streaming tool lookup and a 30ms slow tool. Close connection 1 from the server side so liveConn.Recv triggers reconnect. In a 20-run local check, connection 1's sender dequeued lookup's error follow-up after errChan triggered reconnect, and connection 2 timed out waiting for it.

Fix: track the sender goroutine's exit with a done channel. Call cleanup(), wait for the sender goroutine to exit, and only then call sess.markPendingSent(pendingSend) on reconnect.

Parity vs src/google/adk/flows/llm_flows/tools/_live_caller.py at adk-python 2.15.1:

  • Matches: live streaming tool failures send a FunctionResponse (Role: "user") with {"error": "Invoking () failed with an internal error."}. Handler errors and panics get sanitized, while framework validation and confirmation errors keep their text.
  • Diverges: Go drops the live goroutine log call where Python calls logger.exception. Go also adds the pendingSent gate so follow-ups never overtake the pending response.

@mangeshraut712

mangeshraut712 commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the precise reproduction — it held up exactly as described. Pushed fc34215c.

Your suggested fix (cleanup → wait for the sender → markPendingSent) was not sufficient on its own, so this goes one step further. With only the reconnect path guarded, the same follow-up was still lost: 3/160 runs at GOMAXPROCS=1, 1/160 at the default. The reason is that the gate was also opened by the normal path — case inputCase <- inputReq: sess.markPendingSent(pendingSend) — the moment the sender dequeued the pending response, before the write. A dequeued response can still fail to write on a dying socket, so the gate opened, the tool sent its follow-up, and connection 1's still-parked sender took it. Traced directly: [conn#23 id=call_1 keys=[error]] dequeued by connection 1's sender on the guarded-only build.

What changed instead — the gate opens on a confirmed write:

  • The loop names the pending response on a per-connection reportTarget before the sender can take it. After a successful SendContent, the sender reports that content on written, and only then does the loop markPendingSent.
  • On reconnect: cleanup(), <-senderDone, then markPendingSent — as you proposed — for a response this connection never wrote.
  • Only that one content is ever reported, so ordinary traffic never waits on the loop draining the channel. Verified: user text reaches the wire in 1–2 ms while the loop is inside a 400 ms tool.

Differential, TestLiveReconnectWaitsForOldSenderBeforeReleasingPending (server drops conn 1 without reading the pending response; panicking lookup + 30 ms slow; repeated 8× since it's scheduling-dependent):

build GOMAXPROCS=1, ×20 default, ×20
reviewed head a6c47c82 3 fail / 160 subtests 1 fail
cleanup→wait→mark only 4 fail / 150 (earlier single-shot) 0
this head fc34215c 0 / 160 0 / 160

go test -race -shuffle=on -count=5 ./internal/llminternal/ clean; golangci-lint 0 issues; ./tool/... passes.

One thing to flag for your judgment: the reconnect path now carries the gate across connections but, as before, not the pending response itself — the next connection is opened without re-sending it (that remains #1819 territory). I left that boundary unchanged.

…se is written

When the server dropped a live connection while a streaming tool sat in
waitPendingSent, the tool's error follow-up could be lost: the reconnect
path called markPendingSent before cleanup cancelled connCtx, so the
tool's Send landed on inputCh while connection 1's sender was still
parked there. That sender dequeued the follow-up and wrote it to the
closed socket; Send reported nil, the tool goroutine exited, and the
next connection never saw it.

Guarding only the reconnect path was not enough. The normal path opened
the gate the moment the sender dequeued the pending response, before the
write, and a dequeued response can still fail to write on a dying
socket: measured on the reviewed head, a gate opened on dequeue lost the
follow-up in 3 of 160 runs at GOMAXPROCS=1 and 1 of 160 at the default.

Open the gate on a confirmed write instead. The loop names the pending
response on a per-connection reportTarget before the sender can take it;
after a successful SendContent the sender reports that content on
written, and only then does the loop mark it sent. Only that one content
is ever reported, so user text and audio never wait on the loop draining
the channel (verified: 1-2ms to the wire while the loop is inside a 400ms
tool). On reconnect, cleanup runs and the loop waits on senderDone before
opening the gate for a response this connection never wrote, so the
follow-ups can only reach the next connection's sender.

TestLiveReconnectWaitsForOldSenderBeforeReleasingPending drops connection
1 from the server side, without reading the pending response, with a
panicking streaming tool and a 30ms tool, repeated 8 times since the
interleaving depends on scheduling. Before this change it fails 3/20 top
level at GOMAXPROCS=1; after, 20/20 pass, and the package is clean under
go test -race -shuffle=on -count=5.

Signed-off-by: Mangesh Raut <[email protected]>
@mangeshraut712
mangeshraut712 force-pushed the tip/streaming-tool-failure-reporting branch from ba87ea6 to fc34215 Compare December 2, 2026 06:32

@jjsasha63 jjsasha63 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 concurrency issues in internal/llminternal/base_flow.go need fixes before this can merge.

blocking internal/llminternal/base_flow.go:836-837: the sender goroutine takes from reportTarget after every successful SendContent call and drops the value when target != req.Content. RunLive pushes pendingSend into reportTarget at internal/llminternal/base_flow.go:976 before the sender dequeues pendingSend from sess.inputCh. Any concurrent content write (user text via sess.Send, or a chunk from an active streaming tool) can finish first and discard pendingSend. When the sender later writes pendingSend, reportTarget is empty,so nothing goes to written. RunLive stays stuck at internal/llminternal/base_flow.go:895 with both eventCase and inputCase set to nil, and sess.markPendingSent(pendingSend) never runs.

Failing case: send user text via sess.Send in a loop (or stream chunks from an earlier tool) while the model calls a tool. After reading the tool response, the server replies "pong". Locally on fc34215, the server receives the tool response and sends "pong". RunLive hangs in select at internal/llminternal/base_flow.go:895, and the reader blocks at internal/llminternal/base_flow.go:790. Neither "pong" nor any follow-up chunk arrives.

Fix: replace reportTarget with var reportTarget atomic.Pointer[genai.Content]. Call reportTarget.Store(pendingSend) at internal/llminternal/base_flow.go:976. Replace internal/llminternal/base_flow.go:835-845 with if reportTarget.CompareAndSwap(req.Content, nil) before sending to written. Add a regression test that writes concurrent content while a tool response is pending.

important internal/llminternal/base_flow.go:895: the select loop does not prioritize errChan over inputCase and writtenCase. When the server closes connection 1 during handleFunctionCalls, liveConn.Recv hits EOF and blocks on errChan at internal/llminternal/base_flow.go:765. Once handleFunctionCalls returns, inputCase and errChan are both ready, so Go can pick inputCase first. Writing the pending frame to a half-closed socket buffer can return nil before the peer RST arrives. The sender then reports on written and parks on sess.inputCh. When RunLive loops back to select, writtenCase and errChan are both ready. Picking writtenCase calls sess.markPendingSent(pendingSend) at internal/llminternal/base_flow.go:985 before cleanup() and <-senderDone (internal/llminternal/base_flow.go:1032-1040). Connection 1's sender can then dequeue and lose the tool's follow-up.

Fix: buffer errChan := make(chan liveConnError, 2) at internal/llminternal/base_flow.go:735. Drain errChan with a non-blocking select at the top of for !reconnect before arming inputCase or reading writtenCase.

Parity vs src/google/adk/flows/llm_flows/tools/_live_caller.py and src/google/adk/flows/llm_flows/base_llm_flow.py at adk-python 2.15.1.

  • Matches: live streaming tool failures send a FunctionResponse (Role: "user") with {"error": "Invoking () failed with an internal error."}. Handler errors and panics get sanitized, while pre-handler validation and confirmation errors keep their text.
  • Diverges: Go drops the live goroutine log call where Python calls logger.exception. Go also uses the pendingSent gate and write confirmation becuase Go runs tool and sender goroutines preemptively. Python's single-threaded asyncio loop queues event.content onto live_request_queue without waiting on a write acknowledgement.

…ites

The live sender took a value from reportTarget after every successful
SendContent and dropped it when the content was not its own. RunLive
pushed pendingSend into that channel before the sender dequeued it from
inputCh, so a concurrent content write, user text or a streaming tool's
chunk, could finish first and discard it. When the sender later wrote
pendingSend there was nothing left to report, and RunLive sat in its
select with eventCase and inputCase both nil, never opening the gate.

reportTarget is now an atomic.Pointer. RunLive stores the pending
response, and the sender claims it with CompareAndSwap only when the
content it just wrote is that very pointer, so a write of anything else
leaves it in place. The report goes out on written before the claim is
released, so a sender that loses its connection in between cannot leave
the loop holding a gate its own write had satisfied.

A connection error also now outranks the loop's other cases. errChan is
buffered, and the loop drains it with a non-blocking select at the top of
every iteration, before arming inputCase or reading writtenCase. Without
that a select could pick a ready handoff over a parked error, hand
pendingSend to a sender whose socket was already gone, and open the gate
before cleanup. The error policy itself is unchanged; it moved into one
handleConnError closure that the priority check and the blocking select
both call.

TestLiveConcurrentUserWriteDoesNotLosePendingReport writes user text
through sess.Send while a tool response is pending and fails unless the
model's reply comes back. On the previous code it fails 8 of 8 runs,
each on the 3s deadline; with this change it passes 8 of 8.

Signed-off-by: Mangesh Raut <[email protected]>
@mangeshraut712

Copy link
Copy Markdown
Contributor Author

Thanks for the precise review, and for spelling out both interleavings. Both are addressed in a1c67048, with main merged in 44517ab4. I want to be exact about what I could verify, because the two items ended up with different evidence behind them.

1. reportTarget loses the pending report to a concurrent write (blocking) — fixed, and I have a test that fails without it.

Exactly your diagnosis, and your fix: reportTarget is now an atomic.Pointer[genai.Content]. RunLive calls Store(pendingSend), and the sender claims it only when the content it just wrote is that same pointer, so a write of user text or a tool chunk leaves the target in place for its own write. Nothing is discarded any more, so the gate cannot be left armed on nothing.

One addition to the shape you suggested. I put the report on written before the CompareAndSwap that releases the claim, rather than after. The reason: written is buffered, so the report itself never blocks, but a sender that cleared the target and then hit connCtx.Done() before the report was taken would leave the loop holding a gate its own write had already satisfied. Releasing the claim only after the report is in the buffer closes that. CompareAndSwap is still what stops a second write of the same content from reporting twice.

TestLiveConcurrentUserWriteDoesNotLosePendingReport sends user text through sess.Send in four loops while a tool response is pending, and fails unless the model's reply comes back through the session. On fc34215c it fails 8 of 8 runs on the 3s deadline, with RunLive parked in the select at :900 and the sender idle on inputCh. With the change it passes 8 of 8.

2. errChan must outrank the other cases (important) — implemented as you specified, but I could not build a test that isolates it, so please read this one rather than take it on my word.

errChan is buffered to 2, and the loop drains it with a non-blocking select at the top of every iteration, before inputCase is armed or writtenCase is read. The error policy is unchanged; it moved into one handleConnError closure that the priority check and the blocking arm both call, so there is a single copy of the resumable scoring, backoff reset and terminal-error buffering.

What I could not do is prove it. I wrote a scenario for your described case, the server dropping connection 1 during handleFunctionCalls with concurrent traffic, and it does not distinguish the fixed code from fc34215c: it fails on both. I traced why, and it is not the ordering you flagged. In every traced run the pending response was never written on connection 1 at all, so there was no written report to race the error; the priority check was seeing the error with pendingSend still queued and the reconnect path was opening the gate correctly after <-senderDone. The follow-up was still lost, on fc34215c and on my branch alike.

So that scenario is hitting something else, and I am not going to label it fixed. I removed the test rather than ship one that fails. Two things I owe you on this:

  • I do not know whether the drain is load-bearing for a case I failed to construct, or whether the gate ordering was already sufficient after fc34215c. You reproduced it locally and I did not, so I would trust your reproduction over my failure to build one.
  • If you can share the harness you used for the 20-run check, I will turn it into the regression test this item should have. I would rather ask than guess at the interleaving again.

A pre-existing limitation I found while tracing, not introduced here. If connection 1 drops after the pending response is written and reported, the gate legitimately opens on connection 1, and the streaming tool's follow-up goes onto inputCh where connection 1's sender is still parked. It dequeues the follow-up and writes it to the closed socket, where Send reports nil, so the follow-up is lost and connection 2 never sees it. The Dec 1 ordering handles the case where the gate is opened by the reconnect path; this window is the gate opening through the normal written path just before the connection dies. It is on fc34215c too. I have not attempted a fix, since it touches the same ordering you are reviewing and I did not want to widen this PR without your say.

Verification on a1c67048

  • go test ./internal/llminternal/ -race: pass, no data races. ./tool/functiontool/ with -race: pass.
  • golangci-lint run ./internal/llminternal/...: 0 issues.
  • The three existing tests in streaming_tool_order_test.go, including TestLiveReconnectWaitsForOldSenderBeforeReleasingPending, pass unchanged.
  • One unrelated flake, so you are not surprised by it: TestStreamingResponseAggregatorDoesNotRecopyText failed once in roughly ten runs of the live subset, then passed 5 of 5 in isolation and 0 failures across 4 full runs on both fc34215c and this branch. It only matched my filter because of the word "Streaming". I did not touch it.

I removed the Co-authored-by: Cursor trailer from both new commits before pushing, per the CLA thread above; cla/google is green on a1c67048.

…st ends

The regression test added for the lost pending report started four
writers per run and stopped them only at the end of the function. The
path that matters, the model's reply arriving, returns from inside the
select, so the stop never ran. Eight runs left thirty-two goroutines
sending as fast as they could for the rest of the binary's life.

TestStreamingResponseAggregatorDoesNotRecopyText reads TotalAlloc for
the whole process, so it counted those bytes as its own. Measured over
ten full-suite runs it failed five times before this change and has
not failed since; thirty-four goroutines were alive after this test
before and two are now.

The writers are stopped by a defer so they end with the function
however it ends. Sending is otherwise unchanged, and the test still
fails on the code before the fix, sixteen subtests out of sixteen.

Signed-off-by: Mangesh Raut <[email protected]>
@mangeshraut712

Copy link
Copy Markdown
Contributor Author

A correction to my own work on this branch, since the previous push (a1c67048) went red on test (.).

What failed. Two tests, neither in the changed path: TestHandleFunctionCallsAsync (1131ms against a 1000ms wall-clock budget) and TestRunLiveCeilingSparesAnIntermediaryCycledSession (its fake server's websocket upgrade hit a closed connection).

Why. My regression test, not the fix. concurrentUserWriteKeepsPendingReport starts four writer goroutines per run and stopped them only at the end of the function. The path that matters, the model's reply arriving, returns from inside the select, so the stop never ran. Eight runs left 32 goroutines sending as fast as they could for the rest of the binary's life.

That is visible directly: 34 goroutines were alive after the test, against 2 on a clean run. TestStreamingResponseAggregatorDoesNotRecopyText reads TotalAlloc, which is process-wide, so it counted those bytes as its own. Over ten full-suite runs it failed five times before this change and has not failed since. The two tests that went red in CI are timing-sensitive and were running while those goroutines were live, so I take the red as mine rather than as runner noise. I could not re-run the job to confirm (no admin rights), so the push is the re-run.

What changed (e1809bff, test file only; base_flow.go is untouched):

  • The writers are stopped by a defer, so they end with the function however it ends.
  • The two manual cleanup sites are removed, since the defer owns them.

Evidence. The test still fails on the code before the fix, 16 subtests out of 16 (it was 14/16 before, with earlier runs' leaked writers interfering with later ones). Green under -race; golangci-lint 0 issues; full package under -race clean.

I got here the wrong way round first and want to be plain about it: I initially read the red as runner flakiness, and only found the leak after measuring the allocation test's failure rate on this branch versus main (5/10 versus 0/10). Pacing the writers was a dead end; the leak was the cause.

This branch has not been deployed

No deployments
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.

llminternal: streaming tool failures send panic details to the model, and live mode never reports them

4 participants