CodeWhale icon indicating copy to clipboard operation
CodeWhale copied to clipboard

subagents.v1.json grows unbounded — worker_records has no time/state-based cleanup

Open yekern opened this issue 4 months ago • 2 comments

Summary

On a long-running session (I keep CodeWhale open for days/weeks on a PHP project), .codewhale/state/subagents.v1.json grows to ~300,000 lines and never shrinks. My only workaround is to manually empty the file and restart.

Root cause

crates/tui/src/tools/subagent/mod.rs:1992 (build_persist_payload) serializes the full in-memory state to disk as two collections:

Collection Cleanup mechanism Eviction by age?
agents (execution state) cleanup() (mod.rs:2976) Yes — COMPLETED_AGENT_RETENTION = 1h (mod.rs:117)
worker_records (run ledger) None in cleanup() No — only an LRU cap: MAX_AGENT_WORKER_RECORDS = 256 (mod.rs:118, prune_worker_records mod.rs:2244)

Every write path for worker_records was checked (mod.rs:2164, 2270, 2472, 2499): none evicts by age or completion status. cleanup() never touches them.

Each AgentWorkerRecord (mod.rs:660-695) carries a full AgentWorkerSpec (objective, instructions, profile) plus up to MAX_AGENT_WORKER_EVENTS_PER_RECORD = 128 events (mod.rs:119). At 256 saturated records, the file holds roughly 1200 lines per record = ~300k lines. This stays resident indefinitely: even records for tasks that finished days ago persist until a 257th task evicts the oldest.

Note: AgentWorkerRecord already stores absolute timestamps (completed_at_ms, updated_at_ms, mod.rs:683-684) — they just aren't consulted for eviction.

Why it's not cleaned

  • cleanup() has the structure to do per-collection retention, but the worker-records block was never implemented.
  • persist_state_best_effort() at the end of cleanup() (mod.rs:3026) only fires when agents shrinks — it does not notice worker_records changes.
  • There is no periodic cleanup timer; cleanup only fires on spawn / poll / sidebar refresh, and only when the write-lock is free.

Impact

  • Disk I/O amplification: every state change (1.5s debounce, mod.rs:147) rewrites the entire multi-MB file atomically.
  • Startup cost: load_state deserialises the whole file every launch.
  • Memory: 256 saturated records stay resident for the whole session.
  • Users on long sessions are forced to manually truncate the file.

Expected

Completed / failed / cancelled / interrupted worker records should be evicted by age (like agents already are), so the file self-bounds on long-running sessions. Running / starting records should be preserved. Ideally the retention window (and maybe the LRU cap) should be configurable, e.g. [subagents] completed_retention_secs.

Suggested fix

AgentWorkerRecord already has completed_at_ms and updated_at_ms absolute timestamps. In cleanup(max_age) (mod.rs:2976), after the existing agent-cleanup loop, iterate worker_records and remove terminal-status records whose completed_at_ms (fallback updated_at_ms) is older than now - max_age.

Also, extend the persist gate at the end of cleanup (mod.rs:3026) to fire when worker_records shrink, not only when agents change.

Environment

  • CodeWhale version: 0.8.67
  • OS: Linux
  • Usage: long-lived TUI session (days–weeks), PHP project, frequent sub-agent runs
  • State file: .codewhale/state/subagents.v1.json, ~300k lines before manual truncation

No duplicates found (searched 2026-07-08)

Searched GitHub Issues API for Hmbown/CodeWhale:

Query Hits Relevant?
subagent state cleanup 44 0 — all about checkpoint / timeout / TUI stability
worker_records retention 0 —
subagents.v1.json 5 0 — #3864/#3865 are legacy-path migration; #3882 is per-checkpoint message budget; #3885 (open, "Fleet memory hardening") mentions transcripts/budgets but not worker-record retention
state grows unbounded 2 0 — neither related

Related existing work

#3885 "Fleet memory hardening follow-up" (open, no milestone) item 4 specifically mentions subagents.v1.json: "Add a serialized-size assertion to the persistence tests and, optionally, a hard cap with oldest-record shedding." That issue covers a file-size safety net; this issue covers time-based eviction of completed records. The two are complementary and could ship together.

No other open milestones (v0.8.68–v0.9.0) currently track worker-record retention or subagent state file cleanup.

Doc update (when fix lands)

docs/SUBAGENTS.md Implementation notes (§448-462) should mention the retention policy, e.g.:

Worker records are pruned by time: completed / failed / cancelled / interrupted records are evicted after completed_retention_secs (default 1h). Running / starting records are preserved. The hard cap of 256 records acts as a safety bound.


中文版 / Chinese version

问题摘要

我在一个 PHP 项目上长期运行 CodeWhale(一天到一周不关), .codewhale/state/subagents.v1.json 增长到了约 30 万行且从未缩减。 目前唯一的解决办法是手动清空文件然后重启。

根因分析

crates/tui/src/tools/subagent/mod.rs:1992 的 build_persist_payload 将两类数据序列化到磁盘:

数据集合 清理机制 是否按时间清理?
agents(执行态) cleanup()(mod.rs:2976) 是 — COMPLETED_AGENT_RETENTION = 1h(mod.rs:117)
worker_records(运行账本) cleanup() 中完全没有 否 — 仅靠数量上限 MAX_AGENT_WORKER_RECORDS = 256(mod.rs:118,prune_worker_records mod.rs:2244)

核对了 worker_records 的全部写路径(mod.rs:2164, 2270, 2472, 2499),没有任何一处按时间或完成状态回收。cleanup() 根本不碰 worker_records。

每条 AgentWorkerRecord(mod.rs:660-695)包含完整的 AgentWorkerSpec(任务目标、指令、 profile)以及最多 MAX_AGENT_WORKER_EVENTS_PER_RECORD = 128 个事件(mod.rs:119)。 256 条满载记录 ≈ 每条约 1200 行 × 256 ≈ 约 30 万行,且永不随时间缩减—— 即使几天前已完成的任务也会一直留存,直到第 257 个新任务挤掉最旧的那条。

值得注意的是:AgentWorkerRecord 已经存储了绝对时间戳(completed_at_ms、updated_at_ms, mod.rs:683-684)——只是没用在回收逻辑上。

为什么没被清理

  • cleanup() 的代码结构本身支持按集合分别清理,但 worker_records 那一块从未实现。
  • cleanup() 末尾的 persist_state_best_effort()(mod.rs:3026)只在 agents 变化时触发, 不会因 worker_records 缩减而触发。
  • 没有定时清理器;cleanup 只在 spawn / poll / sidebar 刷新时被动触发。

影响

  • 写盘放大:每次状态变更(1.5s 防抖,mod.rs:147)全量重写整个多 MB 的 JSON 文件。
  • 启动变慢:每次启动 load_state 都要反序列化整个文件。
  • 内存常驻:256 条满载记录在内存中持续占用。
  • 用户被迫手动清空文件。

期望行为

已完成/失败/取消/中断的 worker 记录应按时间回收(就像 agents 已有的逻辑), 使文件在长期运行中能自我约束大小。Running/Starting 记录应保留。 最好暴露 [subagents] completed_retention_secs 配置项。

建议修复

AgentWorkerRecord 已有 completed_at_ms 和 updated_at_ms 绝对时间戳。 在 cleanup(max_age)(mod.rs:2976)的现有 agent 清理循环后,遍历 worker_records, 对终态且 completed_at_ms(缺失则回退到 updated_at_ms)早于 now - max_age 的记录执行移除。同时扩展 cleanup 末尾的 persist 触发条件, 在 worker_records 缩减时也触发,而不仅仅在 agents 变化时。

已检索确认无重复

通过 GitHub Issues 搜索仓库,关键词及结论见英文部分最末表格。 结论:该问题未被现有 issue/PR 覆盖。

相关已有工作

#3885 "Fleet memory hardening follow-up"(open,无里程碑)第 4 项明确提到了 subagents.v1.json:"为持久化测试增加序列化大小断言,可选地增加硬上限、 淘汰最旧记录。" 该 issue 覆盖的是文件大小安全网,本 issue 覆盖的是按时间 清理已完成记录,两者互补,可一同交付。

当前所有 open 里程碑(v0.8.68–v0.9.0)中无其他针对 worker-record 清理的工作项。

文档更新建议(修复落地后)

docs/SUBAGENTS.md 的 Implementation notes(§448-462)应补充保留策略说明,例如:

Worker 记录按时间清理:已完成 / 失败 / 取消 / 中断的记录在超过 completed_retention_secs(默认 1h)后回收。Running / Starting 记录保留。256 条硬上限作为安全边界。

yekern avatar Jul 08 '26 08:07 yekern

Thanks @yekern for the report.

This issue is staying open for maintainer triage. CodeWhale gets better because people bring us real edge cases from real machines, providers, regions, and workflows.

If you can add a reproduction, logs, version output, screenshots, or the provider/model involved, that makes it much easier for us to verify and harvest the fix. Maintainers may comment /lgtmi to mark recurring issue reporters as approved so this intake note is skipped next time.

github-actions[bot] avatar Jul 08 '26 08:07 github-actions[bot]

Fixed by #4296 (merge d79d607ab200): terminal worker records now age-evict alongside finished agents, and cleanup persists when the worker ledger shrinks.

Proof on main:

  • crates/tui/src/tools/subagent/mod.rs:525 adds terminal-status detection; lines 3055 and 3110-3121 prune stale terminal worker_records and persist the shrink.
  • crates/tui/src/tools/subagent/tests.rs:6507 adds the reload-survival regression.
  • docs/SUBAGENTS.md:497 documents the retention policy.

Verification: #4296 CI was green across lint, ubuntu/macos/windows tests, npm wrapper smoke, mobile runtime smoke, CodeQL, DCO, and security checks before merge.

Thanks @yekern for the detailed root-cause report and suggested fix shape. Please retest on a long-lived session and reopen if subagents.v1.json still grows without self-bounding.

Hmbown avatar Jul 09 '26 09:07 Hmbown