CHAPTER 12 · CONTEXT BUDGET
Compaction:85% 阈值与可选 two-pass
默认策略在上下文使用率达到 85% 时允许自动压缩。memory flush 和 two-pass 默认均关闭,启用后才进入对应流程。
课程目标
记住
记住
CompactionPolicy 的五个真实字段与默认值,并能追到 Agent::should_auto_compact 和 xai-token-estimation 的阈值判断。核心视觉 · 自动压缩阈值
0% · 可用空间充足100% · 上下文上限
used × 100 >= context_window × threshold_percent。比较使用饱和乘法,context window 为 0 时返回 false。
CompactionPolicy 默认值
auto_compact_threshold_percent: u3285自动压缩阈值百分比。
compact_model: Option<String>None未指定时使用当前 Session 模型。
memory_flush_enabled: boolfalse启用后,压缩前才运行 memory flush turn。
wall_clock_budget_secs: u64300单次压缩的墙钟预算,单位秒。
two_pass_enabled: boolfalse由配置解析后写入;默认走 single-pass 路径。
Two-pass 何时成立
PASS 1 · PREFIRE
预先摘要历史前缀
仅在 two_pass_enabled 为 true 时,接近阈值可投机地在后台总结历史前缀,得到 NOTE₁。
→
PASS 2 · COMPACT
总结 NOTE₁ 与近期尾部
正式压缩时把 NOTE₁ 与 recent tail 组合后再次总结。配置为 false 时保留原有 single-pass 路径。
真实源码证据
crates/codegen/xai-grok-agent/src/compaction.rs
impl Default for CompactionPolicy {
fn default() -> Self {
Self {
auto_compact_threshold_percent: 85,
compact_model: None,
memory_flush_enabled: false,
wall_clock_budget_secs: 300,
two_pass_enabled: false,
}
}
}
fn default() -> Self {
Self {
auto_compact_threshold_percent: 85,
compact_model: None,
memory_flush_enabled: false,
wall_clock_budget_secs: 300,
two_pass_enabled: false,
}
}
}
crates/codegen/xai-token-estimation/src/lib.rs
pub fn exceeds_threshold(
used: u64,
context_window: u64,
threshold_percent: u8,
) -> bool {
if context_window == 0 { return false; }
used.saturating_mul(100) >=
context_window.saturating_mul(
threshold_percent as u64
)
}
used: u64,
context_window: u64,
threshold_percent: u8,
) -> bool {
if context_window == 0 { return false; }
used.saturating_mul(100) >=
context_window.saturating_mul(
threshold_percent as u64
)
}
调用位置:
Agent::should_auto_compact 接收 total_tokens 与 NonZeroU64 context_window,再调用 xai_token_estimation::exceeds_threshold。策略结构体本身没有虚构的 should_compact(&self, usage: f64) 方法。源码快照说明:本页依据本地同步副本核对。该副本没有
.git 元数据,因此不声称对应某个 commit 版本。课堂练习
手算边界
context window 为 100,000,阈值 85。判断 84,999、85,000、90,000 tokens 是否触发。再说明开启 two_pass_enabled 会改变压缩路径,但不会把默认值改成 true。
Takeaway:默认阈值是 85,wall clock 是 300 秒,memory flush 与 two-pass 均为 false。Two-pass 是显式配置能力,自动触发判断落在 Agent 与 token estimation 中。