fix: 优雅停机停等任务 goroutine,根治 TempDir 清理竞态
ci / frontend (push) Successful in 53s
ci / backend (push) Successful in 2m11s

新增 Server.Close / Engine.StopAll:取消 ctx 后依次等 side-flusher、
后台循环、各任务 planner/worker、归档 worker 退出;测试用 defer s.Close()
在清理前排空 goroutine,遂把 tempDir 兜底改回 t.TempDir() 并删除 helper。
This commit is contained in:
wangdefa committed 2026-10-20 23:08:21 -07:00
1 parent f8454d310b
commit 98515a3974
10 files changed
+74 -5

No files matched your search

+2
View File
@@ -19,6 +19,7 @@ func TestChatUnavailableReasonDistinguishesStates(t *testing.T) {
defer m.Close()
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
// Start from a clean profile table; other tests in the shared DB may have left rows.
existing, _ := m.pg.ListProfiles()
@@ -69,6 +70,7 @@ func TestResolveChatAgentHonoursConversationProfile(t *testing.T) {
defer m.Close()
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
// Force the global fallback to nil so a non-nil result can ONLY come from the
// conversation's own profile — this is exactly the situation the user hit
+1
View File
@@ -25,6 +25,7 @@ func TestCoreTaskLifecyclePG(t *testing.T) {
defer m.Close()
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
tok, err := signJWT(s.jwtKey)
if err != nil {
+21
View File
@@ -290,6 +290,27 @@ func (e *Engine) StopTask(taskID string) {
e.deleteMu.Unlock()
}
// StopAll cancels every live task runtime and waits for its planner, worker and
// deadline goroutines to return. Used on server shutdown (Server.Close): unlike
// StopTask it does not purge the per-task Engine maps — the process/Server is going
// away — it only makes sure no task goroutine survives to keep writing (e.g., into
// a test's data dir while Go's t.TempDir cleanup is removing it). Cancelling the
// server context already signals these loops; this blocks until they have exited.
func (e *Engine) StopAll() {
e.runtimeMu.Lock()
rts := make([]*taskRuntime, 0, len(e.runtimes))
for _, rt := range e.runtimes {
rts = append(rts, rt)
}
e.runtimeMu.Unlock()
for _, rt := range rts {
rt.cancel()
}
for _, rt := range rts {
rt.wg.Wait()
}
}
// cancelExec cancels a task's current per-task exec context (any in-flight
// planner.Plan / worker.Execute), if present. Shared by Pause and the settle
// sequence's hard-drain backstop.
+1
View File
@@ -53,6 +53,7 @@ func TestInheritedActivityDetailAndRelationDeletion(t *testing.T) {
}
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
+1
View File
@@ -20,6 +20,7 @@ func TestMgmtAPI(t *testing.T) {
}
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
tok, err := signJWT(s.jwtKey)
if err != nil {
+42 -5
View File
@@ -42,6 +42,12 @@ type Server struct {
m *Manager
engine *Engine
ctx context.Context
// cancel tears down ctx; Close() calls it to stop every background goroutine
// started by New (scheduler, notifier, evidence GC, task-archive worker and all
// per-task planner/worker/deadline loops). bgWG tracks the server-level loops so
// Close can wait for them to return before the data dir is removed.
cancel context.CancelFunc
bgWG sync.WaitGroup
skillDir string // root directory for skill subdirectories
jwtKey []byte // HS256 signing key loaded from / generated into dataDir/jwt.key
@@ -145,7 +151,11 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
if err != nil {
log.Fatalf("[auth] JWT key: %v", err)
}
s := &Server{m: m, engine: NewEngine(m), ctx: ctx, skillDir: skillDir, jwtKey: key, chatBusy: map[string]bool{},
// Own a cancelable child of the caller's ctx so Close() can stop every
// background goroutine below even when the caller passed a context that never
// cancels (e.g. context.Background() in tests).
ctx, cancel := context.WithCancel(ctx)
s := &Server{m: m, engine: NewEngine(m), ctx: ctx, cancel: cancel, skillDir: skillDir, jwtKey: key, chatBusy: map[string]bool{},
chatCancel: map[string]context.CancelCauseFunc{}, triggerQ: map[string][]triggeredRun{},
triggerActive: map[string]int{}, triggerCfg: map[string]triggerBehavior{},
profChatAgents: map[int64]*agent.ChatAgent{},
@@ -225,12 +235,17 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
if err := s.seedFindingRetester(); err != nil {
log.Printf("[retester] seed: %v", err)
}
go s.evidenceStore().RunGC(s.ctx)
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); s.evidenceStore().RunGC(s.ctx) }()
s.seedPythonInterpreter() // 自定义脚本工具:开机检测 python 解释器入库(仅空时)
go newScheduler(s).Run(s.ctx) // P3 触发器调度(定时/finding/目标事件),仅自定义 agent
sc := newScheduler(s)
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); sc.Run(s.ctx) }() // P3 触发器调度(定时/finding/目标事件),仅自定义 agent
// 漏洞 IM 推送投递引擎。与 Scheduler 并列但独立:推送的实时性要求(3s)
// 与触发器的业务节奏不同,且两者失败互不牵连——推送卡住不该影响 agent 触发。
go newNotifier(s).Run(s.ctx)
nt := newNotifier(s)
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); nt.Run(s.ctx) }()
// Fill the tool cache for any enabled MCP that has none yet (notably the
// seeded browser MCP on first run). Async so it never blocks startup.
go s.discoverEmptyMCPsOnStartup()
@@ -253,12 +268,34 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
log.Printf("[engine] no LLM provider configured — engine idle until set via /api/llm or env")
}
s.restoreTaskRuntimes()
go s.reconcileConcurrency()
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); s.reconcileConcurrency() }()
s.startTaskArchiveWorker()
s.wireInterceptReviewer() // LLM 兜底审批:未命中拦截规则的命令交给模型判定
return s
}
// Close stops every background goroutine started by New and waits for them to
// return, so nothing writes into the data dir afterwards. It cancels the server
// context (stopping the scheduler, notifier, evidence GC, task-archive worker and
// every task's planner/worker/deadline loops), then waits: first the server-level
// loops, then the per-task runtimes, then the archive worker. Call it before
// Manager.Close() (which closes the DB) and before the data dir is removed — in
// tests, before t.TempDir() cleanup runs, which otherwise races a late task-file or
// archive write ("TempDir RemoveAll cleanup: directory not empty"). Safe to call
// once; the engine waits are idempotent for already-exited runtimes.
func (s *Server) Close() {
if s.cancel != nil {
s.cancel()
}
if s.side != nil {
<-s.side.done // side-question snapshot flusher (final flush on ctx.Done)
}
s.bgWG.Wait() // scheduler / notifier / evidence GC / startup reconcile
s.engine.StopAll() // per-task planner / worker / deadline loops
s.archiveWG.Wait() // cold task-archive worker
}
// Restored deadline and worker loops must inherit the same context as new tasks,
// including the side-question checkpoint publisher installed during startup.
func (s *Server) restoreTaskRuntimes() {
+1
View File
@@ -22,6 +22,7 @@ func TestTaskCategoryBatchRoute(t *testing.T) {
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
+1
View File
@@ -17,6 +17,7 @@ func TestWorkerControlRoutes(t *testing.T) {
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
+2
View File
@@ -25,6 +25,7 @@ func TestTaskMetadataPatchReturnsRenameAndPin(t *testing.T) {
taskID, _ := strconv.ParseInt(task.ID, 10, 64)
defer func() { _ = m.pg.DeleteTask(taskID) }()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
@@ -67,6 +68,7 @@ func TestConversationBatchDeleteReportsMissing(t *testing.T) {
}
defer m.Close()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
first, err := m.pg.CreateConversation("mainagent", "batch-http-first", nil)
if err != nil {
t.Fatal(err)
+2
View File
@@ -21,6 +21,7 @@ func TestTaskTemplateHTTPCRUD(t *testing.T) {
}
defer m.Close()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
@@ -91,6 +92,7 @@ func TestConversationPatchReturnsPinState(t *testing.T) {
}
defer m.Close()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
conversation, err := m.pg.CreateConversation("mainagent", "pin through http", nil)
if err != nil {
t.Fatal(err)