Skip to content

fix(agent): compact and continue after a context overflow with partial output - #7055

Merged
M4n5ter merged 1 commit into
rust-previewfrom
fix/overflow-after-output-compacts
Nov 20, 2026
Merged

M4n5ter merged 1 commit into
rust-previewfrom
fix/overflow-after-output-compacts

Conversation

@UncertaintyDeterminesYou4ndMe

@UncertaintyDeterminesYou4ndMe UncertaintyDeterminesYou4ndMe commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

#7083 made a Main context overflow always interrupt the attempt. This PR compacts and continues after a mid-response context overflow whenever it is safe:

  • Attempt::compactable_overflow() checks that the attempt was interrupted by ContextOverflow, made no tool calls, and persisted no semantic output to the canonical log — replacing scattered inline checks across state, engine, and native.
  • Both on-demand overflow summaries and adopted ready background summaries (Action::AdoptCandidate) append the Host cut-off note so the model knows its previous partial text was not delivered.
  • On OpenAI Responses, if an attempt already persisted semantic output or a tool call before overflowing, the turn still ends as failed — and reconcile.rs now waits for recovery assessment before dispatching tools on an interrupted attempt and rejects unadmitted tool calls on ContextOverflow attempts without executing them.
  • Anthropic streams ending with model_context_window_exceeded now emit Event::ProviderError so they enter ModelError::ContextOverflow compaction recovery instead of output-length continuation.

Verification

  • cargo fmt --check
  • cargo test -p maka-provider-protocol --lib (32/32 passed, including a_stop_at_a_full_context_window_is_a_provider_error)
  • cargo test -p maka-agent-state --lib (51/51 passed)
  • cargo test -p maka-agent-engine --lib (32/32 passed, including a_tool_call_from_an_overflowed_attempt_is_rejected_without_execution)
  • cargo test -p maka-agent-native --lib context_overflow_after_partial_output_compacts_and_continues (1/1 passed: both background-summary adoption and on-demand overflow summary paths)

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: 3 live-reproduced bugs on OpenAI Responses (item_acceptance == true) and proactive compaction adoption

English

Consolidating the 6 scattered inline overflow checks into Attempt::compactable_overflow() / overflow_ended() is a very clean simplification (net -9 production lines). However, dropping !attempt.semantic broke the implicit invariant that overflowed attempts leave no Fact::ModelObserved rows in the canonical log, causing three live-reproduced regressions on OpenAI Responses and proactive compaction paths:

1. [Blocker] On OpenAI Responses (supports_item_acceptance() == true), the "dropped" partial output leaks back into subsequent history replays (same-Run ToolContinuation or Turn 3) (live-reproduced)

  • Locations: summary_repair.rs#L101, compacted.rs#L431-L439, replay.rs#L262-L264.
  • Root cause & Repro: With supports_item_acceptance() == true, receive() persists Fact::ModelObserved as soon as an output_item.done arrives. When the stream then fails with context_length_exceeded, prepare_frozen_summary reuses source_capture.through_sequence from before the overflowed attempt M1 as ContextCompacted's covered watermark. While the immediate AfterCompaction request excludes M1, any subsequent ToolContinuation in the same Run or Turn 3 replays semantic_tail after through_sequence, where replay.rs:262 includes M1 and re-injects its ModelObserved(Text) right before M2's real reply (and service/history/projection.rs:497 also renders the supposedly undelivered draft).
  • Reproduction: Real Rig + OpenAI Responses fixture emitting DROPPED_PARTIAL_OUTPUT_LEAK_PROBE then response.failed(context_length_exceeded): summary_has_leak=false, m2_has_leak=false, m2_has_note=true, then on Turn 3: t3_has_leak=true, t3_has_second=true.
  • Suggested fix: Skip attempts that have compactable_overflow() (and were superseded by compaction) in driver_model/replay.rs (and align service/history/projection.rs if the cut-off draft should not appear as delivered).

2. [Major] Adopting a ready background proactive summary (Action::AdoptCandidate) silently drops the [Host] Your previous response was cut off... note (live-reproduced)

  • Location: compacted.rs#L294-L302.
  • Root cause & Repro: compacted.rs:294 checks only summary_request.compaction_recovery. When a session is near the window limit (the most common situation for mid-response overflow), a background proactive summary is often already ready and reconcile.rs:1545 takes Action::AdoptCandidate. Proactive summaries always have compaction_recovery == None (sql_compaction.rs:69) and may also come from a prior Run (producer != view.run), so cut_off evaluates to false.
  • Reproduction: Real Rig with compactionThreshold: 5000 where Turn 2 triggered proactive summary completion before Main overflowed with partial text: has_summary=true, has_cutoff_note=false, has_partial=false, final_state={"kind":"completed"}.
  • Suggested fix: When summary_request.compaction_recovery.filter(|_| producer == view.run) is None and current_request.accounting.purpose == ModelPurpose::Main, inspect view.current_attempt's recovery directly.

3. [Major] On OpenAI Responses, a tool call emitted before overflow is actually executed (with side effects) before the Run fails (live-reproduced)

  • Location: reconcile.rs#L1099-L1231.
  • Root cause & Repro: Allowing AttemptRecovery::ContextOverflow on ModelClosed(Outcome::Error) lets any already-persisted ModelObserved(ToolCall) hit the tool-scheduling loop in reconcile.rs:1099-1231 before line 1531's overflow branch. Because tool_incomplete only checks Outcome::Success + FinishReason::Length, the driver approves and executes the tool (ToolDecided(Approved) -> ToolAdmitted -> LocalToolReturned -> ToolResultAccepted(Succeeded)) and then terminates the Run as Failed discarding the result.
  • Suggested fix: Reject unadmitted tool calls in reconcile.rs whenever their attempt closed with Outcome::Error + AttemptRecovery::ContextOverflow (or any non-recoverable Outcome::Error) instead of executing them before failing the turn.

4. Tests

  • The new preset_acceptance.rs test (+84 lines) is a solid end-to-end behavioral test (no full rewrite needed); just reuse existing quiescent_message helpers and add regressions for the three cases above (Responses Turn 3 non-leak, AdoptCandidate cut-off note, Responses tool-call-before-overflow non-execution).
简体中文

把分散在 state / engine / native 6 处的内联判断收敛成 Attempt::compactable_overflow() / overflow_ended()(生产代码净删 9 行)非常干净。但去掉 !attempt.semantic 后打破了“overflow attempt 不会在 canonical log 留 Fact::ModelObserved”的隐含前提,在 OpenAI Responses 与后台 proactive summary 路径实跑复现出 3 个回归:

1. [Blocker] OpenAI Responses(supports_item_acceptance() == true)上被宣称“丢弃”的 partial output 会在下一次历史重放(同 Run ToolContinuation 或 Turn 3)重新泄漏进 prompt(实跑复现)

  • 位置:summary_repair.rs#L101、compacted.rs#L431-L439、replay.rs#L262-L264。
  • 根因与复现:Responses 模式下收到 output_item.done 就会立即落盘 Fact::ModelObserved。随后触发 context_length_exceeded 时,prepare_frozen_summary 复用了溢出 attempt M1 之前的 through_sequence 作为压缩覆盖水位线。紧接着的 AfterCompaction 虽不含 M1,但同 Run 内任意 ToolContinuation 或用户发 Turn 3 从 through_sequence 之后重放 semantic_tail 时,replay.rs:262 会把 M1 的 ModelObserved(Text) 原封不动重新插回 prompt(service/history/projection.rs:497 也会渲染出来)。实跑复现:summary_has_leak=false, m2_has_leak=false, m2_has_note=true,随后 Turn 3 测得 t3_has_leak=true, t3_has_second=true。
  • 最小修法:在 driver_model/replay.rs 跳过已记录 compactable_overflow() 且被后续压缩取代的失败 attempt(若不希望未送达草稿展示在历史里,同步对齐 projection.rs)。

2. [Major] 命中后台 proactive summary 采纳路径(Action::AdoptCandidate)时静默丢失 [Host] Your previous response was cut off... 提示(实跑复现)

  • 位置:compacted.rs#L294-L302。
  • 根因与复现:长会话逼近窗口上限时后台 proactive summary 往往已就绪并走 Action::AdoptCandidate,其 compaction_recovery 恒为 None(且跨 Run 复用时 producer != view.run),导致 cut_off 恒为 false。实跑 compactionThreshold: 5000 测得 has_summary=true, has_cutoff_note=false, has_partial=false, final_state={"kind":"completed"}。
  • 最小修法:summary_request.compaction_recovery.filter(|_| producer == view.run) 为 None 且当前主请求为 ModelPurpose::Main 时,直接检查 view.current_attempt 的 recovery。

3. [Major] OpenAI Responses 上在 overflow 前已发出的 tool call 会先被真实执行(产生副作用),再把 Run 判 Failed 扔掉结果(实跑复现)

  • 位置:reconcile.rs#L1099-L1231。
  • 根因与复现:放宽 ModelClosed(Outcome::Error) 写 ContextOverflow 后,已落盘的 ModelObserved(ToolCall) 先落入 reconcile.rs:1099-1231 的工具调度循环(排在 line 1531 之前),而 tool_incomplete 只拦截 Outcome::Success + FinishReason::Length。实跑 OpenAI Responses 先发 function_call 再发 context_length_exceeded,事实序列实锤先执行了 ToolDecided(Approved) -> ToolAdmitted -> LocalToolReturned -> ToolResultAccepted(Succeeded),随后才 RunTerminated(Failed)。
  • 最小修法:在 reconcile.rs 工具调度入口对已以 Outcome::Error + ContextOverflow(或任意不可恢复 Outcome::Error)关闭的 attempt 拒绝未 admit 的 tool call,而非先执行再丢弃结果。

4. 测试建议

  • 新增的 preset_acceptance.rs 测试本身是扎实的行为测试(无需整套重写),建议复用已有 quiescent_message 辅助精简样板,并补上上述 3 个场景的回归断言/用例。

@UncertaintyDeterminesYou4ndMe
UncertaintyDeterminesYou4ndMe force-pushed the fix/overflow-after-output-compacts branch from 6bc471d to 86d633b Compare November 20, 2026 11:50
@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor Author

Thanks — rebased onto current rust-preview, which includes #7083. A main overflow now always interrupts the attempt, so the "closed with error" handling from this branch is gone; the PR now only adds compaction after partial output.

  • (1) Leak on Responses: an overflow is compacted only when the attempt left no model output in the canonical log (Attempt::compactable_overflow(): interrupted, not semantic, no tools). On Responses, an overflow after an accepted output item still ends the turn, so nothing dropped can be replayed later. The fold enforces this when the recovery step starts.
  • (2) Adopted candidate drops the note: the cut-off note is now decided from the overflowed Main attempt itself, looked up through the store (the current attempt for an adopted candidate, the recovery link for the overflow's own Summary), so it is added on both paths.
  • (3) Tool executed before the Run fails: attempts with tool calls are never compacted, and the relaxed ModelClosed(Error) path is removed. Whether upstream still executes a persisted Responses tool call of the interrupted current attempt before failing is outside this PR; happy to file it separately.
  • Tests: one Host API test covers both the adopted background summary and the overflow's own summary, including that the partial text does not return in the next turn.

…l output

Since #7083 a main-model context overflow interrupts the attempt. When the
attempt's partial output never reached the canonical log (no semantic
output, no tool calls), compact and continue instead of failing the turn:

- Consolidate the safe-overflow check in Attempt::compactable_overflow()
  across state, engine, and native; OpenAI Responses attempts that already
  persisted semantic output or tool calls still end the turn.
- Reject unadmitted tool calls from ContextOverflow attempts (and wait for
  Assess while an interrupted attempt has no recovery yet) so doomed
  overflowed attempts never execute side-effecting tools before failing.
- Emit the Host cut-off note on both on-demand overflow summaries and
  adopted background proactive summaries (Action::AdoptCandidate).
- Route Anthropic stream model_context_window_exceeded to ProviderError so
  it takes the ContextOverflow compaction path instead of output-length
  continuation.
@M4n5ter
M4n5ter force-pushed the fix/overflow-after-output-compacts branch from 86d633b to 31c991a Compare November 20, 2026 12:07
@M4n5ter
M4n5ter merged commit b00c82a into rust-preview Nov 20, 2026
@M4n5ter
M4n5ter deleted the fix/overflow-after-output-compacts branch November 20, 2026 12:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/M Under 500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants