Skip to content

feat(core): auto-dump memory diagnostics to disk on pressure detection #4651

@yiliang114

Description

@yiliang114

Parent

Part of #3000 (Memory Diagnostics roadmap). Supersedes #4181 + #4182 + #4183 for the "崩溃后可定位" 场景。

问题场景

当前用户遇到 OOM 崩溃后,maintainer 唯一能拿到的信息是用户手动跑 /doctor memory 的输出——但进程都崩了根本跑不了

实际用户报 bug 的流程:

  1. 长 session 跑着跑着突然 FATAL ERROR: Reached heap limit
  2. 进程死了,终端只剩一段 V8 native stack trace
  3. 用户贴 stack trace 到 issue,maintainer 无法判断是 history 太大、tool result 泄漏、还是 clone 峰值

期望行为

当运行时检测到内存压力达到 hard/critical 级别时,自动将一份诊断快照写入磁盘,即使后续进程崩溃,用户也能在 bug report 中提交这个文件。

设计参考

参考 Claude Code 的 heapDumpService.ts 设计:

检测层 (memory pressure monitor, 已有 #4403)
  ├─ soft  → 清理 cache(已实现)
  ├─ hard  → 清理 cache + 自动写 diagnostics JSON ← 新增
  └─ critical → 清理 + 写 diagnostics + 可选 heap snapshot ← 新增

写入顺序(关键):
  1. 先写轻量 diagnostics JSON(不会 OOM)
  2. 再可选写 .heapsnapshot(可能触发 OOM,但 JSON 已经安全落盘)

具体方案

1. 自动落盘 diagnostics(核心)

#4403MemoryPressureMonitor 检测到 hard/critical 压力时:

  • 调用已有的 collectMemoryDiagnostics() 收集数据
  • 追加 session 维度信息(history 条目数、估算大小、最大 tool result)
  • 写入 .qwen/diagnostics/memory-{sessionId}-{timestamp}.json
  • 每个 session 最多写 3 次(避免磁盘轰炸)

输出示例:

{
  "timestamp": "2026-05-31T12:00:00Z",
  "sessionId": "abc-123",
  "trigger": "hard",
  "memory": { "rss": 3200000000, "heapUsed": 2800000000, "heapLimit": 4096000000 },
  "session": { "historyEntries": 6401, "estimatedHistoryBytes": 157000000 },
  "risks": ["heap_used_ratio_high", "large_session_history"],
  "suggestion": "Consider running /compress or restarting with a fresh session"
}

2. TUI 内存告警(辅助)

在状态栏/通知区域显示内存警告:

  • heapUsed > 1.5 GB → 黄色提示 "内存偏高 (1.8GB),建议 /compress"
  • heapUsed > 2.5 GB → 红色提示 "内存严重不足 (2.8GB)"

让用户在崩溃前有机会主动处理。

3. 可选 heap snapshot(高级)

critical 压力时,如果 Node 启动带了 --expose-gc,可选触发 v8.writeHeapSnapshot()。但这是在 diagnostics JSON 之后执行——即使 snapshot 过程中 OOM 了,JSON 已经在磁盘上。

工作量评估

核心原因:重活已做完(collectMemoryDiagnostics 450 行、#4403 MemoryPressureMonitor 605 行),只需串联 + 加输出。

验收标准

  • hard/critical 压力时自动写 diagnostics JSON 到 .qwen/diagnostics/
  • JSON 包含 memory stats + session scale + risk assessment + suggestion
  • 每 session 限制最多 3 次 dump(cooldown)
  • TUI 在 high memory 时显示黄色/红色告警
  • 即使后续进程崩溃,diagnostics 文件完整可读

关联

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions