WeKnora/internal/agent/tool_goroutine_panic_test.go

72 lines
2.5 KiB
Go
Raw Normal View History

fix(agent): 工具自起 goroutine 的 panic 自行兜底,MCP 预热不再带走进程 (#3846) recover 只对调用它的那个 goroutine 生效。executeRecovered(registry.go)覆盖的是 tool.Execute 这次调用本身,act.go 的 errgroup 回调同理:工具自己起的 goroutine 上 发生 panic,两处都接不到,整个进程退出,正在进行的对话、上传、同步全部中断。 修复站点: - mcp_exposure.go 的 catalog 预热 goroutine 与最多 8 个 worker 各装一道屏障;worker 内按服务再兜一层,panic 时沿用文件里既有的 store/status 机制把该服务标记为 "error"(与加载报错同一个状态)、清掉 partial snapshot,close(preloadDone) 照常 执行,prepareMCPToolsWithMode 的 select 仍能返回。 - search_knowledge.go 检索扇出的三处 goroutine(embedding 分组、合并 KB 检索、单 KB 检索):panic 记日志后按既有的 fail() 机制把对应知识库报成失败,工具调用降级为 失败结果而不是进程退出。 - think.go 的 stream stall 看门狗改用同一屏障(stallTimeout 非正时 NewTicker 会 panic)。 新增 internal/agent/tools/goroutine.go: - GoRecovered(ctx, fn):起 goroutine 并兜住 panic,供工具内部统一使用; - RecoverGoroutine(ctx, label, onPanic):defer 形式,onPanic 在同一 goroutine 上记录 失败单元,panic 值不外传。 registry.go 的 executeRecovered 注释补上"recover 只覆盖本 goroutine,工具自起的 goroutine 必须自己兜底"。 回归测试: - TestMCPPreloadWorkerPanicIsContained:loader panic 后进程存活、PrepareMCPTools 正常 返回、该服务 status 为 error 且不保留缓存工具; - TestMCPPreloadFailureMarkingKeepsReadySnapshots:协调者屏障只标记未完成的加载, ready 快照不动; - TestToolChildGoroutinePanicDegradesToFailedResult:走真实 executeToolCallsParallel, 子 goroutine panic 降级为失败结果; - TestGoRecoveredContainsPanicAndRunsDefers / TestRecoverGoroutineReportsPanicToCaller。 去掉屏障后上述用例的测试进程 exit=1,装回后全部通过。 Fixes #3837 Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:24:36 +00:00
package agent
import (
"context"
"encoding/json"
"sync/atomic"
"testing"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/types"
)
// A tool that hands adapter work to a goroutine of its own must contain the
// panic there: executeRecovered (registry.go) only covers the goroutine that
// calls tool.Execute, so before the child barrier a panic from an MCP client,
// a retrieval adapter or an SDK killed the whole process instead of failing
// one tool call.
type goroutineBarrierPanicTool struct {
agenttools.BaseTool
}
func (t *goroutineBarrierPanicTool) Execute(ctx context.Context, _ json.RawMessage) (*types.ToolResult, error) {
var panicked atomic.Bool
done := make(chan struct{})
go func() {
defer close(done)
// RecoverGoroutine runs before close(done) and marks the failed unit of
// work; this is the convention tools use in production.
defer agenttools.RecoverGoroutine(ctx, "test adapter", func() { panicked.Store(true) })
panic("test: tool adapter panicked on a child goroutine")
}()
<-done
if panicked.Load() {
return &types.ToolResult{Success: false, Error: "adapter failed with an internal error"}, nil
}
return &types.ToolResult{Success: true}, nil
}
func runAgentToolCall(t *testing.T, tool types.Tool) *types.AgentStep {
t.Helper()
engine := newTestEngine(t, &mockChat{})
engine.toolRegistry = agenttools.NewToolRegistry()
engine.toolRegistry.RegisterTool(tool)
response := &types.ChatResponse{ToolCalls: []types.LLMToolCall{
{ID: "a", Function: types.FunctionCall{Name: agenttools.ToolSearchKnowledge, Arguments: `{}`}},
}}
step := &types.AgentStep{}
engine.executeToolCallsParallel(context.Background(), response, step, 0, "session", "message")
return step
}
// A child-goroutine panic is degraded into a failed tool result and the test
// process survives; removing the barrier makes this binary exit with the panic.
func TestToolChildGoroutinePanicDegradesToFailedResult(t *testing.T) {
tool := &goroutineBarrierPanicTool{
BaseTool: agenttools.NewBaseTool(
agenttools.ToolSearchKnowledge, "", json.RawMessage(`{"type":"object"}`),
),
}
step := runAgentToolCall(t, tool)
if len(step.ToolCalls) != 1 {
t.Fatalf("expected 1 tool call record, got %d", len(step.ToolCalls))
}
result := step.ToolCalls[0].Result
if result == nil || result.Success {
t.Fatalf("expected a failed tool result, got %+v", result)
}
if result.Error == "" {
t.Fatal("failed result must carry an error the model can act on")
}
}