长任务的 context compaction:
什么时候压,压什么,对 cache 有什么影响?

英文问法How would you handle context limit exceeded in an LLM application? · When do you trigger compaction, and what do you keep? · Does summarizing the history hurt prompt cache hits?

考过别家面经原题:科大讯飞 AI 应用一面(校招,面试 2026-09-15)「什么时候检测并触发压缩,大 Tool Result 的阈值是什么?」「摘要会影响 KV / Prefix Cache 命中吗,怎样降低影响?」(牛客)、蚂蚁 AI 应用方向技术面(校招,发帖 2026-11-08)「如果压缩把“不能修改生产配置”变成了“修改生产配置”,并写入长期记忆,怎么发现和避免?」(牛客)、字节 Agent 开发日常实习一面(发帖 2026-10-20,作者按回忆转述)「如果旧信息已经被摘要掉了,后面还要用怎么办」(牛客) · 英文侧:Mercor SWE 电面 2026-09 的快问快答 "How would you handle context limit exceeded in an LLM application?"(PracHub,站方编辑过的面经页) · 中文面经样本里有 24 帖问 context 和 memory 管理 · 没有 Unity 自己的面经原题

先弄清楚:每个概念是什么

Context window
model 一次能看的 token 上限。长任务里 messages 越积越多,早晚会满。
Context compaction
把旧的历史换成一段摘要,腾出空间。
Prefix cache
两次请求的前缀完全相同时,这段前缀算过的结果可以复用。前缀里改了一处,它后面的部分都要重算。
规则文件
不参与 compaction 的固定内容,每次原样放进 context。硬约束写在这里。

看图:compaction 前后的 context

压之前 固定前缀 旧的历史(含大 tool result) 最近几轮 空余 阈值,比如 80% 换成摘要 文件:大 tool result 的全文 压之后 固定前缀 摘要 最近几轮 空余 cache 命中 重算一次
图 1:横条的总长是 context window,各段的长度只作示意。固定前缀是 system prompt 和 tool 定义,compaction 不动它,所以它的 cache 还能命中。

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 重算,再往后每轮只算新增的部分。

必答点

追问

被问到 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 节