长任务的 context compaction:
什么时候压,压什么,对 cache 有什么影响?
先弄清楚:每个概念是什么
- Context window
- model 一次能看的 token 上限。长任务里 messages 越积越多,早晚会满。
- Context compaction
- 把旧的历史换成一段摘要,腾出空间。
- Prefix cache
- 两次请求的前缀完全相同时,这段前缀算过的结果可以复用。前缀里改了一处,它后面的部分都要重算。
- 规则文件
- 不参与 compaction 的固定内容,每次原样放进 context。硬约束写在这里。
看图:compaction 前后的 context
30 秒回答
The harness, not the model, watches token usage and compacts when it crosses a threshold, say eighty percent of the window. Large tool results never stay inline: they go to files, and the context keeps a path and a short preview. The summary keeps the goal, the constraints, the decisions made and the open steps. The raw history stays on disk, so anything the summary dropped can be fetched back. Compaction rewrites the prefix, so the prompt cache misses once afterwards. That's why I compact rarely and keep the system prompt and tool definitions fixed at the front. Hard constraints live in a rules file that is never summarized.
什么时候压,压什么
| 问题 | 做法 |
|---|---|
| 谁触发 | harness 每轮数 token,过了阈值就压,比如 window 的 80%。不靠 model 自己想起来 |
| 大 tool result | 写进文件,context 里只留路径和开头几行 |
| 摘要里留什么 | 目标、约束、已做的决定、未完成的步骤 |
| 摘要丢了细节 (字节原题) | 原始记录留在磁盘,摘要里带路径,要用时 model 用 read tool 取回 |
| 不能丢的约束 (蚂蚁原题) | 放进规则文件,逐字保留。写进长期 memory 之前,再拿规则文件核对一遍 |
单个文件放不进 context 是另一道题,见 文件放不进 context。
对 prefix cache 的影响
Compaction 改写了历史,所以从摘要开始往后的部分会 miss 一次(原理见 KV cache 和 inference cost)。对策是少压,一次压到位,并把 system prompt 和 tool 定义放在最前面不动。
数字都是举例。window 是 200K,阈值 80% 就是 160K。压之前有固定前缀 10K、旧的历史 135K、最近几轮 20K,合计 165K,过了阈值。把旧的历史压成 5K 的摘要,合计变成 35K。压完后的第一次请求里,10K 的固定前缀命中 cache,后面的 25K 重算,再往后每轮只算新增的部分。
必答点
- 由 harness 按 token 用量触发,不靠 model 自觉
- 大 tool result 落盘,context 里只留路径和开头几行
- 摘要保留目标、约束、已做的决定、未完成的步骤
- 原始记录留在磁盘,丢了的细节按路径取回
- Compaction 让 prefix cache miss 一次,所以少压,固定前缀不动
- 硬约束放规则文件,不参与 compaction
追问
被问到 Claude Code 或 Codex 的 compaction 是怎么实现的,怎么答?
没读过实现就直说,然后讲自己会怎么设计,也就是上面那张表的五行。
FlashVector 怎么控制 context 的大小?
它的 Refine 在 run 结束后 in-place 更新 knowledge base,不往后追加,所以 agent 要带的 memory 有上限(见 knowledge base 和 memory)。
来源面经原帖:科大讯飞 AI 应用一面、蚂蚁 AI 应用方向、字节 Agent 开发日常实习一面、上海某中厂 Agent 开发一面(触发点是 model 主动还是 harness 实现) · PracHub:Mercor SWE 电面 · FlashVector §4.2 Refine · ml-八股 08 第 34 题 · 中文平台调研笔记 1.4 节