Repository navigation
fix: Responses sessions compact before reaching context limit - #130993
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 29, 2026, 11:02 PM ET / August 30, 2026, 03:02 UTC. ClawSweeper reviewWhat this changesThe branch makes built-in compaction timeouts progress-aware, carries cancellation through context-engine wrappers, and hardens compaction summary and terminal-usage accounting. Merge readinessKeep open: current main lacks the branch’s compaction and usage changes, but the required direct Codex runtime-contract inspection is unavailable and the branch changes the existing timeout contract. Priority: P1 Review scores
Verification
How this fits togetherCompaction condenses an agent session when its context grows, using a context engine and then saving a checkpoint for later turns. This PR changes deadline ownership and the facts preserved through that compaction flow. flowchart LR
A[Agent session] --> B[Compaction trigger]
B --> C[Context engine]
C --> D[Progress deadline]
D --> E[Compaction checkpoint]
E --> F[Later agent turns]
Decision needed
Why: This changes an existing documented operator contract; the code and documentation are aligned, but selecting the upgrade behavior requires maintainer compatibility judgment. Before merge
Agent review detailsSecurityNone. PR surfaceSource +140, Tests +708, Docs 0, Other 0. Total +848 across 30 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Verify the exact Codex runtime contract, then explicitly accept the staged timeout semantics or retain an operation-wide deadline before merge. Do we have a high-confidence way to reproduce the issue? No: source and supplied regression evidence make the path reproducible in principle, but this read-only review did not independently establish a current-main runtime reproduction. Is this the best way to solve the issue? Unclear: the owner-boundary changes are coherent, but direct Codex contract inspection is mandatory and unavailable, and the timeout compatibility choice needs maintainer intent. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against d4ad866e5f9c. LabelsLabel justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (29 earlier review cycles; latest 8 shown)
|
f117634 to
98068df
Compare
|
Addressed the ClawSweeper P2 at head
@clawsweeper re-review |
|
🦞👀 |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Updated head
Pre-fix regressions failed with the old aggregate timeout and duplicate wrapper; the patched focused suite passes 179 tests. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Addressed both logical ClawSweeper P1s at head
The new overflow and timeout-recovery regressions both failed on @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Bound native delegated compaction from setup through post-processing while preserving progress-aware request windows. Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc
Give fallback session preparation a fresh delegated timeout window after a late provider rejection. Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc
Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc
Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc
|
@clawsweeper re-review Exact head The remaining timeout question is already explicitly decided: retain the documented per-model-request progress window for built-in staged compaction, while custom/plugin compaction keeps the operation-wide host bound. Owner decisions: #130993 (comment) and #130993 (comment). The latest split-prefix finding is addressed with the producer's real three-section format and fail-before/pass-after coverage; the audit repair is net-zero production LOC. Direct current Codex source inspection also confirms one coherent Responses usage snapshot and request-loop/replacement-history ownership: https://github.com/openai/codex/blob/b68acc4d4b56fdfa1d5b6a2c36102c66876e0c46/codex-rs/codex-api/src/sse/responses.rs#L125-L151 and https://github.com/openai/codex/blob/b68acc4d4b56fdfa1d5b6a2c36102c66876e0c46/codex-rs/core/src/compact.rs#L245-L398. This requests review only, not repair or automerge. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
Summary
High-level TLDR
This PR fixes six failures in the same long-session compaction pipeline:
## Pending user asks.latest_user_ask_not_reflected.The intentional split-turn design is unchanged: older context is summarized while the recent suffix, including tool-call/tool-result continuity, remains verbatim. Requests remain serial. The configured timeout remains 180 seconds; for built-in staged compaction it applies to each model request, while custom/plugin compaction remains bounded once at the host boundary.
Root cause and fix
A. False Responses context pressure
The Responses terminal mapper preserved billable token buckets but omitted the provider's coherent input/total snapshot from
usage.contextUsage. The pressure owner therefore fell back to estimating the mirrored transcript and could count provider-owned context again.Sanitized decision replay:
compact_then_truncate, estimated prompt390486, budget252000, sourcetranscript_estimate.{ promptTokens: 197462, totalTokens: 197764 }, routefits, estimated prompt198202, budget252000, sourceprovider_context_usage.The fix projects a terminal snapshot only when it is coherent. Output-absent snapshots require
total_tokens >= input_tokens; zero or smaller totals remain unavailable. Prompt-only recovery truncation no longer rewrites durable provider-owned transcript rows, avoiding a later idempotency collision.Direct dependency-contract check, re-verified against upstream
openai/codexmainat63d2138(2026-08-30): Codex deserializesresponse.completed.usagewithinput_tokens,output_tokens, andtotal_tokensall required and maps it into oneTokenUsage, including cached input, cache-write input, and reasoning output (codex-rs/codex-api/src/sse/responses.rs:128-150; thecache_write_input_tokensbucket is newer than the earlier citation and is already bounded by the coherence predicate here). Codex measures context astotal_tokens(codex-rs/protocol/src/protocol.rs:2365-2375) and estimates only items after the last reported usage (codex-rs/core/src/context_manager/history.rs:443), the same model this PR's pressure owner uses. Codex's local compaction keeps recent prompt history while retrying (codex-rs/core/src/compact.rs:245run_compact_task_inner_impl,:644build_compacted_history), and remote compaction installs provider-returned compacted history from the selected prompt (codex-rs/core/src/compact_remote.rs:192run_remote_compact_task_inner_impl).B. Healthy staged compaction mistaken for a hang
Sanitized runtime evidence from the newest manual failure:
Compaction timed out;The first request consumed most of one aggregate 180-second operation deadline. Although native compaction refreshed its watchdog at each serial request boundary, normal
resolveContextEngine()resolution returned a proxy closure forcompact(). Exact function identity was lost,isRuntimeCompactionDelegate()returned false, and the host silently installed a second aggregate deadline around native compaction.The fix makes watchdog ownership an explicit process-global function capability that survives registry projection proxies and duplicated dist chunks. Both normal resolution and fresh logical-turn resolution inherit it only from the canonical runtime delegate. Custom and plugin compaction functions do not inherit it and remain host-bounded.
C. Completed response confused with completed task
An isolated replay of the unchanged pre-failure transcript reproduced this after all model calls completed successfully:
## Pending user asks;stopReason="stop";completed_latest_user_ask_marked_pending;All six provider calls completed in about 143 seconds, ruling out timeout as the cause of that replay.
stopReason="stop"proves response termination, not user-task completion.The fix removes that invalid completion bit from compaction preparation, retention, and quality auditing. The summarizer still receives the full latest turn and is still instructed to put only unresolved requests under
## Pending user asks. Final budgeting now preserves the section chosen from that full transcript instead of moving an ask between completed and pending state using a structural guess.Why previous fixes did not fix these failures
latest_user_ask_not_reflectedfailures by exposing the audited ask to the summarizer. It also introduced the invalid completed-turn predicate; the newcompleted_latest_user_ask_marked_pendingfailures are distinct.new LegacyContextEngine()directly, so it missed registry proxy identity loss.Diagnostic handoff (redacted)
No private chat URL, account, session key, run ID, provider response ID, tool-call ID, transcript content, or credential is included here.
Historical signatures in the affected chat were not one bug:
latest_user_ask_not_reflectedand were addressed by fix(compaction): show the summarizer the audited latest ask #130620;completed_latest_user_ask_marked_pending;missing_identifiersin a different session.Triage signatures:
pressureSource=transcript_estimatedespite a recent coherent Responses terminal usage snapshot: inspect terminal usage projection.pressureSource=provider_context_usagewith a decision below budget: the false-pressure path is working; do not attribute a later failure to accounting without new evidence.Compaction timed outnear the configured limit while a later serial request ran only for the remaining fraction: inspect watchdog ownership/refresh.completed_latest_user_ask_marked_pendingafter a normal assistant stop while requested work remains unfinished: inspect structural response state being consumed as semantic task state.One diagnostic gap remains outside this repair: first-pass quality reason codes are logged only when retries are exhausted. If a first candidate fails quality and a later corrective attempt times out, production logs retain the timeout but not the first-pass reason. The isolated replay was needed to recover that boundary.
Evidence map
packages/ai/src/providers/openai-responses-terminal-usage.ts; consumer:src/agents/embedded-agent-runner/run/preemptive-compaction.ts; recovery projection:src/agents/embedded-agent-runner/tool-result-truncation.ts.src/agents/embedded-agent-runner/compaction-safety-timeout.ts; native request boundary:src/agents/embedded-agent-runner/compaction-session-execution.ts; registry projection:src/context-engine/registry.ts; canonical delegate:src/context-engine/delegate.ts.src/agents/agent-hooks/compaction-safeguard.ts; retention/audit:src/agents/agent-hooks/compaction-safeguard-quality.ts; split preparation:packages/agent-core/src/harness/compaction/compaction.ts.Real-behavior and regression proof
The two newly added tests failed on prior PR head
76598e92b81efor the exact defects:After the fix at
24bc0c0b2b4:Changed-surface formatting, production/test typechecks, assertion and max-line ratchets, dependency/plugin boundaries, dead-export checks, and full core lint also pass locally. Exact-head GitHub CI remains the authoritative full-suite gate.
Live deployment proof, exact head
5594d1boverlaid on a maintainer gateway from 2026-08-29 21:12Z through 2026-08-30 02:36Z: 7 automatic compactions, 7 successes, 0 failures.openai/gpt-5.6-sol×5 (46 s to 3.5 min each, three of them split-turn) andminimax/MiniMax-M3×2 (under 1.5 min). Counting the prior head9fcbe25deployed from 19:34Z, about 30 successes and 0 failures. ZeroCompaction timed out,guard_blocked,missing_identifiers, branch-fallback, or budget-exceed lines in that window; the only safeguard output is the pre-existing informationalfinalized artifact truncated; loss=...line. Earlier the same day, intermediate heads on the same gateway produced 34guard_blockedcancellations fromduplicate_section(the audit ran against the assembled artifact, whose nested split-turn section repeated every required heading) andretained_turn_ask_marked_pending(the split-prefix summarizer received no corrective feedback and was audited in the wrong format); commitsdecc184,e4146f2, and5594d1bfixed both and the failures stopped. Log lines are redacted of session identifiers.The earlier Responses transport head passed the authenticated OpenAI gateway-profile live workflow, including native OpenAI and GPT-5.6 Ultra selections: workflow run.
User impact
LOC and risk
f9b3bcc: +351/-221 (net +130) across 16 files (git diff --numstat, tests/test-support/baseline/docs excluded; ClawSweeper's +140 classifies test-support differently).openai-responses-terminal-usage.ts+27), progress-refreshable native watchdog and its abort helpers (compaction-safety-timeout.ts+26,compaction-session-execution.ts+24,context-engine/compaction-watchdog.ts+25,context-engine-abort.ts+42,with-timeout.ts+14), and audited-ask retention (compaction-safeguard-quality.ts+30). Offsets: the invalid completion oracle and retained-suffix scan (agent-core/.../compaction.ts-39,compaction-safeguard.ts-17) and registry projection cleanup (registry.ts-8). Each remaining addition is an ownership boundary (provider snapshot coherence, watchdog capability that survives registry proxies, abort-reason preservation); none is compatibility code.agents.defaults.compaction.timeoutSecondskeeps its key, default, and schema, but its meaning for built-in compaction is intentionally changed from an operation-wide cap to a per-model-request window that resets on staged progress (cause B); plugin-owned and native-harness compaction keep the operation-wide bound. Documented indocs/gateway/config-agents.mdandschema.help.agents.ts. Operators who raised the value to survive multi-stage compaction can return to the default.The remaining positive production delta establishes the provider usage/projection boundary, prompt-only truncation, a progress-refreshable native watchdog, and capability-preserving registry ownership; none is test-only compatibility code.
What was not tested
source: "provider_context_usage"from a Responses-shaped payload end to end; the mapper and transport tests join by type only.Known follow-ups (not blocking)
src/agents/embedded-agent-runner/compaction-session-execution.ts:642does not callcompactionTimeoutReset(); same outcome asmain, but it contradicts the per-request contract. One-line rearm.## Latest user request contextblock into## Decisions(seen in 2 of 7 live compactions);createSummaryQualityRetentionPlanstrips only the exact current block. Strip any such block from the body.compact.hooks.harness.ts:975-982bypasses the outer wrapper for unmarked engines in a waycompactWithSafetyTimeoutnever does, so the "no second aggregate timeout" test proves the mock; align the harness with the real owner split.delegateCompactionToRuntimealso get one operation-wide window, and that setup and post-processing get their own windows.D. Missing latest request disabled its own repair
Sanitized evidence from the newest manual failure after deployed PR head
24bc0c0b2b4:latest_user_ask_not_reflected;The quality-retention owner had two circular fast paths. First,
createSummaryQualityRetentionPlan()returnednullwhenever the generated audit artifact lacked enough token overlap with the latest request. That is exactly the state in which its boundedrequiredAskContextfallback is needed. Second, even with that precondition removed, the within-cap fast path rebuilt only for missing identifiers or oversized protected sections; it never asked whether the latest request itself was missing. A structured summary could therefore fit the cap, bypass deterministic retention, fail the final audit, consume another complete model attempt, and fail again.The canonical fix removes the obsolete whole-artifact precondition and makes missing latest-request overlap a reason to rebuild a fitting structured body. The existing bounded source context is retained in the section chosen by the summarizer when possible, or under a neutral
Latest user request context:label when no section reflects it. The final audit remains fail-closed if the required fact cannot fit. No timeout, retry count, split-turn, config, protocol, or persistence behavior changes.This is the unfinished consumer half of the earlier repair, not a recurrence of the producer bug. #130620 made the audited latest turn visible to the summarizer; it could not force a model to preserve enough literal overlap. #129423 restored omitted identifiers through the same retention owner, but the latest-request precondition and within-cap fast path remained.
Regression proof for commit
95b5526f4f8:24bc0c0b2b4in both agent test projects because compaction returnscancel: true;Updated LOC at this head:
E. Split-turn summary replaced the authoritative source ask
Sanitized evidence from the newest manual failure after deployed PR head
95b5526f4f8:reason=guard_blocked;latest_user_ask_not_reflected;The split-turn summarizer output was incorrectly assigned to
requiredAskContext. That generated, lossy text then took precedence over the authoritativelatestUserAsk. The deterministic retention planner correctly noticed that the source ask was absent, but the only protected text it was given was the generated split summary, so rebuilding could never restore the fact the final audit required.The fix keeps the split-turn summary as supplemental context while always sourcing mandatory request retention from
latestUserAsk. It deletes the generated-summary substitution instead of weakening the audit, adding retries, or adding another fallback. Split behavior, tool-call continuity, timeouts, providers, configuration, and persistence are unchanged.Regression proof at
4aca82299c0:95b5526f4f8because the final audit returns false after both generated summaries omit the source ask;src/agents/agent-hooks/compaction-safeguard.test.ts: 143/143 tests pass;This follow-up is production +1/-4 (net -3) and tests +5/-4 (net +1). No configuration, protocol, database, persisted-state, timeout, retry, provider, or channel surface changes.
F. Native watchdog bypass dropped caller cancellation
ClawSweeper exact-head review of
4aca82299c0identified a logical P1 in the earlier timeout repair. The canonical native delegate correctly bypassed the host aggregate timeout, but it also bypassed the wrapper that races the caller abort signal. Native preparation can await runtime or plugin setup before reaching its later abort-aware model call, so a cancelled manual or recovery operation could remain pending during that preparation.The fix separates those two policies: native compaction still owns its progress-aware per-model-request watchdog, while the host boundary rejects immediately on caller cancellation and removes its listener after settlement. Custom/plugin engines remain host-timeout-bounded as before.
Both regressions failed on
4aca82299c0for the intended reason:At
add844e23d5, both reject with the caller reason; the pre-aborted path never starts the delegate. The focused timeout suite passes 27/27, the adjacent compaction hook and overflow suites pass 161/161, and the full changed-file gate passes. This repair is production +41/-29 (net +12), establishing the shared cancellation race used by both host-bounded and native compaction paths; tests are +44/-0.ClawSweeper completed the first logical review and emitted the finding, but its publisher then failed on an invalid generated live-proof plan even though that review marked live proof not applicable. That publisher failure was workflow infrastructure, not a second code finding. The finding was accepted and repaired. A replacement exact-head review at
add844e23d5completed successfully, reports the patch correct with no findings and security cleared, and exact-head GitHub CI is green.Follow-up invariant fixes
Commit
6ab2b77ebd6closes the three owner-boundary gaps found in exact-head review without removing the existing accounting, watchdog, cancellation, source-ask, split-turn, or fail-closed budgeting repairs:## Pending user asks, and the audit rejects deterministic request context placed elsewhere.Focused verification passes across the changed and retained sibling paths, including context-engine resolution, Responses usage, compaction timeout/cancellation, split-turn safeguards, tool-result projection, hooks, overflow recovery, transport mapping, and node timeout behavior. The changed-surface gate passed formatting, typechecks, lint, dead-export, dependency/plugin-boundary, state/database, and import-cycle guards. Fresh structured autoreview reports no P0 findings.
G. Bound delegated native setup and post-processing
Exact-head review found that the native delegate could leave preparation before the first provider request outside any safety deadline. The repair restores a host-owned, progress-refreshable window: preparation is bounded, setup completion and each provider request refresh the window, client fallback starts with a fresh window, and successful compaction refreshes again before side effects, checkpoint persistence, and after-compaction hooks. Custom and plugin compaction remains host-bounded as before.
At fa81015, the focused timeout, overflow-recovery, and hook suites pass 382 tests across six project instances. The complete changed-surface gate passes formatting, production and test typechecks, lint, dead-export analysis, dependency and plugin boundaries, state and database guards, and import-cycle checks.
Worked on by