压缩替换 History 后,旧 World State baseline 默认失效。是否立即安装新基线取决于压缩发生位置:Pre-turn/手动压缩不在替代历史中注入初始上下文,下一正常 Turn 完整重建;Mid-turn 为了继续同一 Turn,必须把 canonical 初始上下文和对应 Snapshot 一起安装。
InitialContextInjection 是显式策略
枚举只有 DoNotInject 和 BeforeLastUserMessage。前者返回空 initial context 与空 baseline;后者调用 build_initial_context_with_world_state,同时返回与这些消息一致的 WorldState Snapshot。
async def build_compaction_context(session, injection):
if injection == DO_NOT_INJECT:
return [], None, None
world = await session.build_world_state_for_step(injection.step)
items = await session.build_initial_context(injection.turn, world)
return items, world.snapshot(), injection.turn.to_context_item()
插入位置必须保护最后摘要
Mid-turn replacement 从后向前寻找最后一个“真实用户消息”,跳过带 Summary prefix 的合成 user message。找不到真实 user 时,插到最后 summary/compaction item 之前;都没有才追加。这样模型训练要求的 compaction item 或 summary 仍保持最后。
def insert_initial_context(history, context):
index = find_last_real_user(history)
if index is None:
index = find_last_summary_or_compaction(history)
if index is None:
return history + context
return history[:index] + context + history[index:]
replace_compacted_history 还安装 reference_context_item、window metadata 和 baseline。仅插消息而不设 baseline,会让下一 Step 重复完整注入;仅设 baseline 而不插消息,则会让 Runtime 以为模型知道从未看过的状态,后者更危险。
源码与测试锚点
codex-rs/core/src/compact.rs::InitialContextInjection。build_compaction_initial_context与insert_initial_context_before_last_real_user_or_summary。codex-rs/core/src/session/session.rs::replace_compacted_history。codex-rs/core/src/compact_tests.rs:各种替代历史形状。
评论
登录后即可评论