Skip to content

fix(functiontool): keep tool panics out of the model's function response - #2120

Merged
wolo-lab merged 9 commits into
google:mainfrom
wojtas000:fix/tool-panic-stack-trace
Nov 6, 2026
Merged

wolo-lab merged 9 commits into
google:mainfrom
wojtas000:fix/tool-panic-stack-trace

Conversation

@wojtas000

@wojtas000 wojtas000 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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 functiontool now return an internal toolinternal.PanicError, whose Error() text is unchanged. Where a tool error becomes the function response, the code asks toolinternal.ModelErrorText, which returns Invoking `<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 of handleFunctionCalls outside live mode. Callbacks run before that point, so OnToolError and AfterTool, 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/retryandreflect needed the same check. It answers OnToolError with a response of its own, built from the error's text and Go type, so callTool returns 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 type panic with 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:

  • The model and REST clients get 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.
  • That holds however deeply the panic error is wrapped, so a callback that handles the panic and returns fmt.Errorf("lookup failed: %w", err) loses its own lookup failed: prefix along with the panic text.
  • With plugin/retryandreflect installed, the response's error_type reads panic rather than the error's Go type, and error_details and the reflection guidance carry the generic message.
  • The tool's trace span records the generic message as its error, where it used to record the panic text. The span error is rebuilt from the function response, so it follows what the model sees.
  • Callbacks and plugins receive the same error text as before, now carried by a *toolinternal.PanicError rather than an *errors.errorString.

Errors a tool returns are unchanged.

One limitation I did not fix here: a plugin outside this module that answers OnToolError with a response of its own has no way to recognize a recovered panic, because PanicError lives in internal/. Giving it one is a public API addition, so it is #2154 instead.

Testing Plan

Unit Tests:

  • All unit tests pass locally.

go test -race -mod=readonly -count=1 -shuffle=on work passes, golangci-lint v2.3.1 reports no issues, and go mod tidy -diff is 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_ToolPanic and TestToolPanicThroughRunner.

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(); swapping errors.As for a direct type assertion in either check; hiding every error instead of only panics, in either check; emptying the plugin's panic error type; substituting the generic message before the AfterTool step; skipping the OnToolError callbacks; 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. TestToolPanicThroughRunner drives a panicking tool through a full run with the plugin installed, against a mock model.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

Additional context

Three things found here that need their own change, now filed:

mangeshraut712 added a commit to mangeshraut712/adk-go that referenced this pull request Nov 3, 2026
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.
@wojtas000
wojtas000 requested a review from wolo-lab November 3, 2026 11:57

@wolo-lab wolo-lab 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 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 AfterTool callbacks still get the full panic text.
  • The OnToolError assertion in TestCallTool only passes when the panic row runs, so go test -run on 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"

Comment thread internal/llminternal/base_flow_test.go Resolved
Comment thread internal/llminternal/base_flow_test.go Resolved
Comment thread internal/llminternal/base_flow.go Resolved
Comment thread internal/toolinternal/tool.go Resolved
@wojtas000
wojtas000 force-pushed the fix/tool-panic-stack-trace branch from 24efc64 to 94cdc33 Compare November 5, 2026 23:48
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.
@wojtas000

Copy link
Copy Markdown
Contributor Author

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.

modelError now asks toolinternal.ModelErrorText, which reports whether it substituted, so the panic check lives in one place. A recovered panic becomes error_type: "panic" with the generic message, in the reflection response, the retry-limit-exceeded response, and the guidance text built from them. Your repro is in the tree as TestToolPanicThroughRunner in plugin/retryandreflect/plugin_test.go; it fails with the plugin change reverted, and it asserts response_type so that it cannot pass on the flow's own substitution instead.

A second pass over the change found two more things, in 5ae9741 and a868c45:

  • Both checks used errors.As already, but nothing pinned the unwrapping — swapping it for a direct type assertion left the suite green. That matters: an error on its way out of a tool is wrapped more than once, and a callback that handles the panic and returns its own error is free to wrap it. Each check now has a test row that wraps the panic error.
  • A plugin outside this module cannot recognize a recovered panic at all, since PanicError is in internal/. That needs a public sentinel, so it is tool: no public way for a plugin to recognize a recovered tool panic #2154 rather than part of this PR.

Follow-ups filed and linked from the description: #2152 for the streaming panic going unrecorded, #2153 for the ToolNode path, which sends the stack to REST clients and which #2120 does not reach, and #2154.

Commits, one fix each:

  • 6c7c24e — the two test changes you asked for.
  • f22cb0f — the plugin fix, and the toolName rename.
  • 5ae9741 — wrapped panics.
  • a868c45 — folding the check into one place, and the test precision that came out of re-reviewing it.

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.

@wojtas000
wojtas000 requested a review from wolo-lab November 6, 2026 12:10

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

Thanks, code looks good.

Small follow-ups: #2172 and #2173

@wolo-lab
wolo-lab merged commit e83ab5b into google:main Nov 6, 2026
21 of 27 checks passed
mangeshraut712 added a commit to mangeshraut712/adk-go that referenced this pull request Nov 7, 2026
Resolve conflicts with upstream google#2120 PanicError while keeping live-mode
BeforeHandler preservation for streaming tool failure reporting.
@wojtas000
wojtas000 deleted the fix/tool-panic-stack-trace branch November 12, 2026 15:03
wolo-lab added a commit that referenced this pull request Nov 16, 2026
…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)
mangeshraut712 added a commit to mangeshraut712/adk-go that referenced this pull request Nov 23, 2026
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.
mangeshraut712 added a commit to mangeshraut712/adk-go that referenced this pull request Nov 23, 2026
Resolve conflicts with upstream google#2120 PanicError while keeping live-mode
BeforeHandler preservation for streaming tool failure reporting.
baptmont added a commit that referenced this pull request Nov 25, 2026
#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]>
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.

functiontool: a panicking tool sends its panic value and stack trace to the model and REST clients

2 participants