別讓清理卡住回覆
我最怕的不是 Agent 算錯,而是答案明明做完了,最後一公里被一個「順手清理」拖到 timeout。
最近看到 OpenClaw GitHub issue #202134,情境很典型:plugin helper session 結束時,lifecycle cleanup 跑在 SQLite 的 exclusive session writer 裡,還要掃所有 orphan transcript。單次 cleanup 實測約 8.6 到 13 秒,Active Memory 其實已經在 30 秒 deadline 前產生答案,卻因為 cleanup 卡住,使用者只看到 timeout,其他 session write 也跟著排隊。更麻煩的是,不匹配的 orphan 不會被刪掉,下次又重掃同一批資料。
這不是把 timeout 從 30 秒調成 60 秒就能解的問題。它是 workflow ownership 和 critical path 切錯了。我的做法是把流程拆成三條:
使用者可見的 result path:先把 plugin result 交付出去,包含必要的 session-entry patch。這條路只做最小、可預測的寫入,不等待全域掃描。
plugin-scoped cleanup:plugin 只清理自己建立的 windows 或 key prefix,最好在建立時就留下 owner、request id 和可索引的 marker。不要每次把完整 transcript JSON 撈出來做 includes。
background maintenance:全域 orphan sweep 放到週期性維護工作,設定 batch size、時間預算和 checkpoint。掃過的 orphan 要記錄狀態,避免每一輪從頭重算。
我會把責任邊界寫成類似這樣:
request -> produce result -> commit minimal state -> return
\-> enqueue cleanup
maintenance worker -> bounded orphan sweep -> checkpoint
實作上還有幾個容易漏掉的點:
• cleanup 要有獨立的 deadline,超時只能標記 deferred,不能反過來讓主請求失敗。
• writer queue 要有 metrics,至少觀察 lock wait、queue depth、cleanup duration 和 result latency,否則你只會看到「偶發 timeout」。
• helper session 結束時寫入 owner metadata,未來才能精準回收,而不是靠全文 marker search 猜。
• 先做 bounded cleanup,再考慮全量 reconciliation。每次只處理固定筆數,讓延遲上限可估。
這個 pattern 不只適用 Active Memory。任何 webhook、通知、artifact upload 或 deployment callback 都一樣:使用者要的是結果,不是看你整理房間。把 maintenance 放在 critical path,等於讓最不重要、最不可控的工作決定產品的可靠性。
我的判斷很簡單:只要一段工作不能直接改善這次請求的結果,就應該從回覆路徑移出去,改成可重試、可觀測、可延後的 job。workflow 這樣設,偶爾清理慢只是背景噪音,不會再變成使用者眼中的 timeout。
作者:Jesse