WeKnora/internal/agent/tools/goroutine_test.go

44 lines
1.2 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 tools
import (
"testing"
"time"
)
// GoRecovered must contain a panic raised on the goroutine it starts and still
// run the deferred calls fn installed. Without the barrier this test binary
// dies with "test: adapter panicked on a helper goroutine".
func TestGoRecoveredContainsPanicAndRunsDefers(t *testing.T) {
cleaned := make(chan struct{})
GoRecovered(catalogTestContext(), func() {
defer close(cleaned)
panic("test: adapter panicked on a helper goroutine")
})
select {
case <-cleaned:
case <-time.After(5 * time.Second):
t.Fatal("GoRecovered did not run fn")
}
}
// RecoverGoroutine is the deferred form: it reports the failure through onPanic
// on the panicking goroutine, before the caller's own deferred hooks run.
func TestRecoverGoroutineReportsPanicToCaller(t *testing.T) {
ctx := catalogTestContext()
var marked bool
done := make(chan struct{})
go func() {
defer close(done)
defer RecoverGoroutine(ctx, "test retrieval", func() { marked = true })
panic("test: adapter panicked on a caller-owned goroutine")
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("RecoverGoroutine did not contain the panic")
}
if !marked {
t.Fatal("RecoverGoroutine did not report the panic to onPanic")
}
}