Repository navigation
fix(functiontool): keep tool panics out of the model's function response - #2120
Conversation
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.
wolo-lab
left a comment
There was a problem hiding this comment.
Two small test changes before merge, both about what the tests pin rather than the code. The fix itself does what the description says: the two new tests fail on main and pass here, and reverting either recover site, either call site, or the stack in PanicError.Error() turns a test red.
Must change before merge (details on the lines):
- No test pins that
AfterToolcallbacks still get the full panic text. - The
OnToolErrorassertion inTestCallToolonly passes when the panic row runs, sogo test -runon any other row fails.
Worth handling here or in a follow-up: with the first-party retry-and-reflect plugin installed, the panic value and stack still reach the model, the session and REST clients. Its OnToolError callback builds its own response from toolErr.Error() (plugin/retryandreflect/plugin.go#L244-L245), so callTool returns that map and never reaches toolErrorText. Main behaves the same way, so this is not a regression, but the description's "the model and REST clients get the generic message" does not hold for anyone using that plugin. error_type in that response now also reads *toolinternal.PanicError. The plugin is in the same module, so it can check for PanicError the way the flow does.
Repro through the runner (fails on this branch and on main)
Run with go test -count=1 -v -run TestPanicRetryAndReflect ./internal/reprotest/ after adding the file as internal/reprotest/panic_repro_test.go.
package reprotest
import (
"fmt"
"strings"
"testing"
"google.golang.org/genai"
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/internal/testutil"
"google.golang.org/adk/v2/plugin"
"google.golang.org/adk/v2/plugin/retryandreflect"
"google.golang.org/adk/v2/runner"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/functiontool"
)
func TestPanicRetryAndReflect(t *testing.T) {
pt, err := functiontool.New(functiontool.Config{Name: "lookup_order"}, func(agent.Context, struct{}) (struct{}, error) {
panic("secret-user-data-123")
})
if err != nil {
t.Fatal(err)
}
m := &testutil.MockModel{Responses: []*genai.Content{
{Role: "model", Parts: []*genai.Part{{FunctionCall: &genai.FunctionCall{ID: "c1", Name: "lookup_order", Args: map[string]any{}}}}},
genai.NewContentFromText("done", "model"),
}}
a, err := llmagent.New(llmagent.Config{Name: "a", Model: m, Tools: []tool.Tool{pt}})
if err != nil {
t.Fatal(err)
}
p, err := retryandreflect.New()
if err != nil {
t.Fatal(err)
}
r := testutil.NewTestAgentRunnerWithPluginManager(t, a, runner.PluginConfig{Plugins: []*plugin.Plugin{p}})
var resp string
for ev, err := range r.Run(t, "s1", "hi") {
if err != nil {
t.Fatal(err)
}
if ev.LLMResponse.Content == nil {
continue
}
for _, part := range ev.LLMResponse.Content.Parts {
if part.FunctionResponse != nil {
resp = fmt.Sprint(part.FunctionResponse.Response)
}
}
}
if strings.Contains(resp, "secret-user-data-123") || strings.Contains(resp, "goroutine") {
t.Errorf("panic text reached the function response: %.200q", resp)
}
}panic text reached the function response: "map[error_details:panic in tool \"lookup_order\": secret-user-data-123\nstack: goroutine 28 [running]:\nruntime/debug.Stack()\n\t.../src/runtime/debug/stack.go:26 +0x5e\ngoogle.golang.org/adk/v2/tool/functiontool.(*functio"
24efc64 to
94cdc33
Compare
A recovered panic became an error carrying the panic value and the goroutine stack, and the flow sent that text to the model, the session and REST clients. Mark it as toolinternal.PanicError and replace it with a generic message where the function response is built. Callbacks still get the full text.
The panic row registered only an OnToolError callback, so nothing caught a flow that replaced the error before the AfterTool step. Its assertions also ran after the table loop, which made every other row fail under 'go test -run'; they move into a per-row check.
The plugin answers OnToolError with a response of its own, built from the tool error's text and Go type, so callTool returns that map and never reaches the flow's check for a recovered panic. With the plugin installed the panic value and the stack still reach the model, the session and REST clients. The flow's check moves to toolinternal.ModelErrorText so both call sites share it, and the plugin reports a recovered panic as the type 'internal error' with the same generic message the flow sends. Renames NewPanicError's first parameter to toolName, which no longer shadows the tool package.
Both checks used errors.As already, but nothing pinned the unwrapping, and a callback that handles the error and returns its own is free to wrap it, as agenttool and the workflow tool node do. Each check now has a test row that wraps the panic error. Also drops a second errors.As from the plugin's path, and the 'internal error: ... internal error' repetition the plugin put in its reflection guidance.
ModelErrorText now reports whether it substituted, so the plugin asks it rather than repeating the errors.As check, and its doc no longer claims callers it does not have. On the test side: each panic row records into its own map and asserts its own callbacks ran, the error_type assertion compares against the literal rather than the constant it pins, and the end-to-end test checks that the plugin, not the flow, answered the failed call.
94cdc33 to
a868c45
Compare
|
All four review points are addressed, plus the retry-and-reflect one, which I handled here rather than in a follow-up — your reading was right, and the description's claim did not hold with that plugin installed. Rebased on main, all 14 checks green.
A second pass over the change found two more things, in 5ae9741 and a868c45:
Follow-ups filed and linked from the description: #2152 for the streaming panic going unrecorded, #2153 for the Commits, one fix each:
I ran 13 mutants in a scratch copy, one per guard in the change, and all 13 turned the suite red. The list is in the testing section of the description. |
Both items from this review are fixed on the current head. The remaining test gaps are tracked in #2172.
Resolve conflicts with upstream google#2120 PanicError while keeping live-mode BeforeHandler preservation for streaming tool failure reporting.
…tifactstool fixes (#1961, #2120, #2115, #2283, #2307) (#2356) * fix(functiontool): preserve streaming consumer panics (#1961) (cherry picked from commit 1af51a3) * fix(functiontool): keep tool panics out of the model's function response (#2120) (cherry picked from commit e83ab5b) * fix(mcptoolset): let a CommandTransport reconnect (#2115) (cherry picked from commit 1a84f04) * fix(skilltoolset): list skills under "result" and trim SKILL.md instructions (#2283) (cherry picked from commit 8ed375d) * fix(loadartifactstool): return an error result for non-string names (#2307) (cherry picked from commit f1f0d2d)
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.
Resolve conflicts with upstream google#2120 PanicError while keeping live-mode BeforeHandler preservation for streaming tool failure reporting.
#2120 keeps a recovered tool panic out of the model's function response. Four of the properties it states had no test that fails when they break, so a regression in any of them merged green. No non-test file changes. ModelErrorText promises the generic message however deeply the panic is wrapped, and every test wrapped once. TestModelErrorText covers depths 1, 2 and 5, a panic joined with another error, and an ordinary error that has to keep its own text. The real two-level path gets a runner test of its own: a panicking functiontool behind a workflow ToolNode, called through agenttool, so ToolNode wraps the error and agenttool wraps it again before the flow sees it. Plugins are handed the error itself, panic value and stack included, because that is what a deployment logs; only the model's function response gets the generic message. The test plugin manager now records the error each of its tool callbacks was handed, and TestCallToolPanics states it per case: the panic error, the ordinary error the tool returned when the agent's OnToolError is the step that panics, or no error at all when the call has not failed by the time the plugin's AfterTool runs. The panic texts became named constants, since each is now named two or three times in one case. retryandreflect builds "<type>: <details>" for the guidance the model reads. Dropping the type prefix, or emptying the error block of the retry-limit template, passed every test; it now fails TestRetryAndReflect_GuidanceCarriesErrorTypeAndText. The "wrapped panic" case justified itself with a route that cannot happen: an earlier OnToolError callback wrapping the error before this plugin sees it. PluginManager.RunOnToolErrorCallback returns as soon as a plugin answers or fails, and the agent's own callbacks run only after the plugins return nothing. The comment now names the route that exists. Fixes #2172 Co-authored-by: João Westerberg <[email protected]>
Linked issue
Problem:
When a function tool panics, ADK recovers the panic into an error whose text includes the panic value and the goroutine stack. Outside live mode that text becomes the tool's function response, so the model, the session and REST clients all see it. The stack exposes source paths, module versions and package names, and the panic value can carry user data.
Solution:
Both recover blocks in
functiontoolnow return an internaltoolinternal.PanicError, whoseError()text is unchanged. Where a tool error becomes the function response, the code askstoolinternal.ModelErrorText, which returnsInvoking `<tool>()` failed with an internal error.for a recovered panic at any wrapping depth, and the error's own text for anything else. Two places call it:callTool, and the streaming branch ofhandleFunctionCallsoutside live mode. Callbacks run before that point, soOnToolErrorandAfterTool, and the logging and BigQuery plugins with them, still get the full text. Errors a tool returns keep their text, because returning an error is how a Go tool tells the model what went wrong.plugin/retryandreflectneeded the same check. It answersOnToolErrorwith a response of its own, built from the error's text and Go type, socallToolreturns that map and never reaches the substitution — with that plugin installed the panic value and the stack still reached the model. It now reports a recovered panic as the typepanicwith the same generic message.The generic message is the one adk-python sends for a failed streaming tool in live mode (_live_caller.py#L271-L289). Outside live mode adk-python re-raises and ends the run (_caller.py#L584-L597). ADK Go keeps recovering the panic so the run continues, as it does today. Live mode is left to #1980.
Behavior change
When a tool panics outside live mode:
Invoking `<tool>()` failed with an internal error.instead of the panic value and stack trace. A non-streaming tool that panics in live mode gets the same message, since it goes through the same path.fmt.Errorf("lookup failed: %w", err)loses its ownlookup failed:prefix along with the panic text.plugin/retryandreflectinstalled, the response'serror_typereadspanicrather than the error's Go type, anderror_detailsand the reflection guidance carry the generic message.*toolinternal.PanicErrorrather than an*errors.errorString.Errors a tool returns are unchanged.
One limitation I did not fix here: a plugin outside this module that answers
OnToolErrorwith a response of its own has no way to recognize a recovered panic, becausePanicErrorlives ininternal/. Giving it one is a public API addition, so it is #2154 instead.Testing Plan
Unit Tests:
go test -race -mod=readonly -count=1 -shuffle=on workpasses, golangci-lint v2.3.1 reports no issues, andgo mod tidy -diffis clean in both modules.With your source change reverted and your tests kept, which test fails?
TestCallTool/tool_panic_is_hidden_from_the_model_but_not_from_callbacks,TestHandleFunctionCalls_StreamingToolErrors/panic_is_hidden_from_the_model,TestRetryAndReflect_ToolPanicandTestToolPanicThroughRunner.I ran 13 mutants in a scratch copy, one per guard, and each one turned the suite red: reverting either recover block, either call site in the flow, or the plugin's check; dropping the stack from
PanicError.Error(); swappingerrors.Asfor a direct type assertion in either check; hiding every error instead of only panics, in either check; emptying the plugin'spanicerror type; substituting the generic message before theAfterToolstep; skipping theOnToolErrorcallbacks; and the plugin no longer answering at all.Manual End-to-End (E2E) Tests:
Not run against a live model. The change is in how ADK builds the function response before the next model call.
TestToolPanicThroughRunnerdrives a panicking tool through a full run with the plugin installed, against a mock model.Checklist
Additional context
Three things found here that need their own change, now filed:
ToolNodeends the run, and adkrest streams that error text, stack included, to the client.