Repository navigation
fix(llminternal): report streaming tool failures to the model in live mode - #1980
mangeshraut712 wants to merge 28 commits into
Conversation
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
a3aee9b to
3c68ef9
Compare
karolpiotrowicz
left a comment
There was a problem hiding this comment.
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.
…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.
|
Thanks for the detailed review and the tests. Pushed 8315662.
|
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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)}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.
|
@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. |
|
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 You were right about re-yielded errors, and my earlier comment was wrong: |
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.
…failure-reporting
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.
|
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 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 |
This reverts commit 38607fe.
|
Thanks, the code is back to the live-only version. The CLA check fails now, though: 38607fe carries a |
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.
|
The CLA check still fails at |
Everything this review asked for is fixed on the current head.
karolpiotrowicz
left a comment
There was a problem hiding this comment.
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:
- 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.TestLiveErrorFollowUpOrdercatches a merge that never releases the gate, but not this case. fmt.Errorf("%w", err)instreaming_function.goalso changes what the model gets outside live mode, which this PR otherwise leaves to #2120. An error type with its ownFormatmethod now reaches the model as that output instead ofError(), and anError()that panics reaches it as%!v(PANIC=Error method: …). Let's keepError()as the text, asHandlerErrordid.
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.
|
Thanks @karolpiotrowicz for catching both subtleties! Both items (and the
Rechecked on November 28 at |
b0d4d38 to
59cc037
Compare
…failure-reporting
|
Both items from the Nov 17 review are in place at
Measured locally on
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
left a comment
There was a problem hiding this comment.
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 thependingSentgate so follow-ups never overtake the pending response.
|
Thanks for the precise reproduction — it held up exactly as described. Pushed 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: What changed instead — the gate opens on a confirmed write:
Differential,
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]>
ba87ea6 to
fc34215
Compare
jjsasha63
left a comment
There was a problem hiding this comment.
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 thependingSentgate and write confirmation becuase Go runs tool and sender goroutines preemptively. Python's single-threadedasyncioloop queuesevent.contentontolive_request_queuewithout waiting on a write acknowledgement.
…ilure-reporting Signed-off-by: Mangesh Raut <[email protected]>
…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]>
|
Thanks for the precise review, and for spelling out both interleavings. Both are addressed in 1. Exactly your diagnosis, and your fix: One addition to the shape you suggested. I put the report on
2.
What I could not do is prove it. I wrote a scenario for your described case, the server dropping connection 1 during 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:
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 Verification on
I removed the |
…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]>
|
A correction to my own work on this branch, since the previous push ( What failed. Two tests, neither in the changed path: Why. My regression test, not the fix. That is visible directly: 34 goroutines were alive after the test, against 2 on a clean run. What changed (
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 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 |
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_callerfor live mode: after the pending response is sent, deliver a FunctionResponse follow-up withInvoking \()` 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/At
b0d4d388c57f, the full workspace build and shuffled race suite passed on macOS (129 packages with tests). Both modules passedgo mod tidy -diffand 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.