Skip to content

fix: Responses sessions compact before reaching context limit - #130993

Merged
VACInc merged 26 commits into
mainfrom
fix/managed-context-pressure
Aug 30, 2026
Merged

VACInc merged 26 commits into
mainfrom
fix/managed-context-pressure

Conversation

@VACInc

@VACInc VACInc commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Summary

High-level TLDR

This PR fixes six failures in the same long-session compaction pipeline:

  1. OpenAI Responses terminal usage could lose its coherent context boundary, causing replay estimation to nearly double-count context and trigger compaction too early.
  2. A legitimate multi-stage compaction could be aborted by an outer aggregate deadline even though each serial model request was still making healthy progress.
  3. The summary quality gate treated a normally ended assistant response as proof that the user task was complete, then rejected a correct summary that kept unfinished work under ## Pending user asks.
  4. A second latest-request retention gate disabled its own deterministic repair precisely when a generated summary omitted or over-paraphrased that request, then spent a corrective attempt and failed with latest_user_ask_not_reflected.
  5. On split turns, a lossy model-generated prefix summary replaced the authoritative source ask as required retention context, so deterministic repair could not restore the fact the final audit required.
  6. The native-watchdog exception also skipped the caller-abort race, so cancellation could leave runtime or plugin preparation pending before the next abort-aware model request.

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:

  • Before: route compact_then_truncate, estimated prompt 390486, budget 252000, source transcript_estimate.
  • After: coherent provider snapshot { promptTokens: 197462, totalTokens: 197764 }, route fits, estimated prompt 198202, budget 252000, source provider_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/codex main at 63d2138 (2026-08-30): Codex deserializes response.completed.usage with input_tokens, output_tokens, and total_tokens all required and maps it into one TokenUsage, including cached input, cache-write input, and reasoning output (codex-rs/codex-api/src/sse/responses.rs:128-150; the cache_write_input_tokens bucket is newer than the earlier citation and is already bounded by the coherence predicate here). Codex measures context as total_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:245 run_compact_task_inner_impl, :644 build_compacted_history), and remote compaction installs provider-returned compacted history from the selected prompt (codex-rs/core/src/compact_remote.rs:192 run_remote_compact_task_inner_impl).

B. Healthy staged compaction mistaken for a hang

Sanitized runtime evidence from the newest manual failure:

  • compaction failed at about 178.852 seconds with Compaction timed out;
  • the final provider request was aborted about 25.6 seconds after it started;
  • the deterministic plan required two serial summary chunks (about 64k and 83k estimated tokens) followed by a merge.

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 for compact(). 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:

  • two chunk summaries and the merge completed;
  • the merged summary retained every required section and correctly listed the still-unfinished request under ## Pending user asks;
  • a structural oracle marked the request complete solely because the retained assistant tail had non-empty text and stopReason="stop";
  • the audit rejected the summary as completed_latest_user_ask_marked_pending;
  • a corrective three-call retry made the same semantic classification and failed the same sole check.

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

  • The older identifier-retention repair (fix(compaction): summarize the prepared window and always restore audited identifiers #129423) validates summary retention after compaction is selected. It cannot provide missing provider usage, alter pressure routing, or change watchdog ownership.
  • fix(compaction): show the summarizer the audited latest ask #130620 fixed four earlier latest_user_ask_not_reflected failures by exposing the audited ask to the summarizer. It also introduced the invalid completed-turn predicate; the new completed_latest_user_ask_marked_pending failures are distinct.
  • The first timeout follow-up refreshed the native watchdog but did not test the normally resolved default engine. Its regression constructed new LegacyContextEngine() directly, so it missed registry proxy identity loss.
  • A broader attempted timeout exception for every non-owning engine was unsafe: a synthetic custom CLI engine could then hang without a host deadline. This PR keeps the exception capability-bound to the canonical native delegate and proves both default resolution paths preserve that capability.

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:

Triage signatures:

  • pressureSource=transcript_estimate despite a recent coherent Responses terminal usage snapshot: inspect terminal usage projection.
  • pressureSource=provider_context_usage with a decision below budget: the false-pressure path is working; do not attribute a later failure to accounting without new evidence.
  • Compaction timed out near the configured limit while a later serial request ran only for the remaining fraction: inspect watchdog ownership/refresh.
  • one model request itself exceeding the configured limit: expected safety timeout, not this bug.
  • custom/plugin compaction exceeding its aggregate host deadline: expected host ownership.
  • completed_latest_user_ask_marked_pending after 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

  • Responses usage producer: 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.
  • Timeout owner: 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.
  • Summary semantic owner: 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.
  • Timeout siblings covered: normal default resolution, logical-turn projection, manual/queued compaction, CLI, overflow, timeout recovery, and custom-engine host bounds.
  • Quality siblings covered: ordinary latest turns, split turns, preserved recent turns, final artifact budgeting, identifier retention, and corrective generation.

Real-behavior and regression proof

The two newly added tests failed on prior PR head 76598e92b81e for the exact defects:

preserves native compaction watchdog ownership through default resolution
AssertionError: expected false to be true

does not treat a terminal assistant response as proof that the latest task is complete
AssertionError: compaction result was cancel=true

After the fix at 24bc0c0b2b4:

pnpm exec vitest run \
  src/context-engine/context-engine.test.ts \
  src/context-engine/host-param-projection.test.ts \
  src/agents/embedded-agent-runner.compaction-safety-timeout.test.ts \
  src/agents/agent-hooks/compaction-safeguard.test.ts \
  packages/agent-core/src/harness/compaction/compaction.test.ts

Test Files  7 passed (7)
Tests       451 passed (451)

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 5594d1b overlaid 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) and minimax/MiniMax-M3 ×2 (under 1.5 min). Counting the prior head 9fcbe25 deployed from 19:34Z, about 30 successes and 0 failures. Zero Compaction timed out, guard_blocked, missing_identifiers, branch-fallback, or budget-exceed lines in that window; the only safeguard output is the pre-existing informational finalized artifact truncated; loss=... line. Earlier the same day, intermediate heads on the same gateway produced 34 guard_blocked cancellations from duplicate_section (the audit ran against the assembled artifact, whose nested split-turn section repeated every required heading) and retained_turn_ask_marked_pending (the split-prefix summarizer received no corrective feedback and was audited in the wrong format); commits decc184, e4146f2, and 5594d1b fixed 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

  • Responses sessions no longer compact because replay estimation double-counted a coherent provider usage snapshot.
  • Prompt-only recovery does not mutate durable provider-owned transcript rows.
  • Legitimate built-in split compaction can span several healthy serial requests without an outer aggregate deadline cutting off later stages.
  • A normally ended assistant response no longer makes the quality gate declare unfinished user work complete.
  • Tool-call and recent-turn detail remain protected by the existing intentional split design.

LOC and risk

  • Production versus merge-base f9b3bcc: +351/-221 (net +130) across 16 files (git diff --numstat, tests/test-support/baseline/docs excluded; ClawSweeper's +140 classifies test-support differently).
  • Tests/test support/baseline: +1006/-288 (net +718).
  • Docs: +1/-1.
  • Runtime growth by owner: Responses usage coherence boundary (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.
  • No configuration, protocol, database, persisted-state, or timeout-default surface changes. agents.defaults.compaction.timeoutSeconds keeps 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 in docs/gateway/config-agents.md and schema.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

  • The original large session was not re-run wall-clock end to end; the live proof above covers automatic compactions on a maintainer gateway running this exact head, and the original transcript was replayed only in isolated state for RCA. Deterministic regressions cover both repaired owner boundaries.
  • No runner-level test asserts 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)

  • After a per-request timeout, the compaction model fallback inherits a nearly expired host watchdog because the failure exit at src/agents/embedded-agent-runner/compaction-session-execution.ts:642 does not call compactionTimeoutReset(); same outcome as main, but it contradicts the per-request contract. One-line rearm.
  • On re-distill the model can copy the previous artifact's ## Latest user request context block into ## Decisions (seen in 2 of 7 live compactions); createSummaryQualityRetentionPlan strips only the exact current block. Strip any such block from the body.
  • compact.hooks.harness.ts:975-982 bypasses the outer wrapper for unmarked engines in a way compactWithSafetyTimeout never does, so the "no second aggregate timeout" test proves the mock; align the harness with the real owner split.
  • Docs could add that native harness compaction (Codex, Copilot) and plugin engines wrapping delegateCompactionToRuntime also 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:

  • all four provider requests succeeded in about 38.990, 24.163, 56.499, and 24.232 seconds;
  • two candidate summaries finalized;
  • the operation ended after about 154.746 seconds with only latest_user_ask_not_reflected;
  • the source latest request was a short approval/continuation request; no private text or identifier is retained here;
  • there was no provider, transport, timeout, or split-turn failure in this occurrence.

The quality-retention owner had two circular fast paths. First, createSummaryQualityRetentionPlan() returned null whenever the generated audit artifact lacked enough token overlap with the latest request. That is exactly the state in which its bounded requiredAskContext fallback 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:

  • the new owner-boundary scenario fails on deployed head 24bc0c0b2b4 in both agent test projects because compaction returns cancel: true;
  • after the fix it succeeds in both projects, restores the bounded source request context, passes the final source audit, calls the summarizer once, and records no cancellation;
  • the complete safeguard file passes 286/286 assertions across both projects;
  • the full changed-file gate passes formatting, production and test typechecks, lint, dead-export analysis, import-cycle checks, and database/state policy guards;
  • isolated structured Autoreview reports no P0 finding.

Updated LOC at this head:

  • Production: +183/-132 (net +51).
  • Tests/test support: +323/-104 (net +219).
  • Docs: +1/-1.
  • This latest repair alone is +5/-10 production (net -5) and +44/-4 tests.

E. Split-turn summary replaced the authoritative source ask

Sanitized evidence from the newest manual failure after deployed PR head 95b5526f4f8:

  • the operation used the intentional split-turn path and completed two finalization passes;
  • it ended after about 142.592 seconds with reason=guard_blocked;
  • the sole quality reason was latest_user_ask_not_reflected;
  • the source request was a short approval/continuation ask; no private text, session identifier, response identifier, or transcript content is retained here;
  • the deployed files matched the PR head, and there was no timeout or transport failure in this occurrence.

The split-turn summarizer output was incorrectly assigned to requiredAskContext. That generated, lossy text then took precedence over the authoritative latestUserAsk. 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:

  • the focused split-turn scenario fails on prior head 95b5526f4f8 because the final audit returns false after both generated summaries omit the source ask;
  • after the fix, the final artifact contains the exact source ask and identifier and passes the source audit in the same two model calls;
  • src/agents/agent-hooks/compaction-safeguard.test.ts: 143/143 tests pass;
  • the complete changed-file gate passes formatting, production/test typechecks, lint, dependency and plugin boundaries, dead-export analysis, import-cycle checks, and database/state policy guards.

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 4aca82299c0 identified 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 4aca82299c0 for the intended reason:

  • a pre-aborted invocation still called and resolved the native delegate;
  • an in-flight native preparation remained pending after the caller aborted.

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 add844e23d5 completed successfully, reports the patch correct with no findings and security cleared, and exact-head GitHub CI is green.

Follow-up invariant fixes

Commit 6ab2b77ebd6 closes 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:

  • quarantined custom context engines now expose native watchdog ownership when their actual compaction dispatch is the built-in fallback;
  • frozen tool-result projections report progress only when the next provider projection changes, avoiding a no-op retry;
  • source requests omitted by the generated summary are conservatively restored under ## 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

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 27, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 29, 2026, 11:02 PM ET / August 30, 2026, 03:02 UTC.

ClawSweeper review

What this changes

The branch makes built-in compaction timeouts progress-aware, carries cancellation through context-engine wrappers, and hardens compaction summary and terminal-usage accounting.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep 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
Reviewed head: 5594d1ba8b0bb5d6e02e396098c2177f27f721a8
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch and supplied evidence are substantial, but Codex-source verification and a timeout compatibility decision remain unresolved.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The author is a repository member, so external-contributor proof is not mandatory; supplied live Gateway evidence is supplemental and was not independently verified in this offline review.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The author is a repository member, so external-contributor proof is not mandatory; supplied live Gateway evidence is supplemental and was not independently verified in this offline review.
Evidence reviewed 6 items Changed timeout ownership: The branch identifies the built-in delegate and passes a resettable watchdog through its runtime context; model-call start resets the window for staged compaction.
Callers and wrapper preservation: Queued and recovery compaction callers enter the shared timeout wrapper, while registry proxies preserve the native-delegate marker across wrapping.
Documented compatibility change: The branch changes timeoutSeconds from a maximum duration for one compaction operation to a per-model-request safety window that can permit a longer total operation.
Findings None None.
Security None None.

How this fits together

Compaction 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]
Loading

Decision needed

Question Recommendation
Should timeoutSeconds intentionally become a per-model-request progress window for built-in staged compaction, even when a complete compaction exceeds the configured duration? Accept staged timeout semantics: Keep the progress-aware window once direct Codex contract verification confirms the cancellation behavior.

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

  • Resolve merge risk (P1) - Existing timeoutSeconds configurations can now allow total built-in compaction time to exceed the configured value.
  • Resolve merge risk (P1) - The bug-fix branch has a net production increase of 130 lines; the review evidence does not establish that this complexity cannot be absorbed at the existing owner boundary.
  • Resolve merge risk (P1) - Codex cancellation and progress behavior could not be checked because the mandatory sibling source checkout is unavailable.
  • Complete next step (P2) - Manual review is required because the Codex contract gate cannot be completed locally and the PR changes an existing timeout contract.
Agent review details

Security

None.

PR surface

Source +140, Tests +708, Docs 0, Other 0. Total +848 across 30 files.

View PR surface stats
Area Files Added Removed Net
Source 17 367 227 +140
Tests 11 988 280 +708
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 30 1357 509 +848

Review metrics

Metric Value Why it matters
Production versus test delta production +351/-221; tests/test support +1004/-286; docs/baseline +2/-2 The branch materially expands compaction behavior and its regression coverage.
Configuration contract 1 changed: agents.defaults.compaction.timeoutSeconds The setting changes from an operation-wide cap to a per-request progress window.

Merge-risk options

Maintainer options:

  1. Verify and accept the new timeout contract (recommended)
    Inspect the required Codex source and record acceptance of the documented per-request timeout semantics before merging.
  2. Preserve the current deadline guarantee
    Keep timeoutSeconds operation-wide if existing configurations must remain a strict total-duration cap.

Technical review

Best 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.

Labels

Label justifications:

  • P1: This changes a core agent-session compaction path that can affect active long-running sessions.
  • merge-risk: 🚨 compatibility: Existing timeoutSeconds users can observe longer total compaction duration after merge.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The author is a repository member, so external-contributor proof is not mandatory; supplied live Gateway evidence is supplemental and was not independently verified in this offline review.

Evidence

Acceptance criteria:

  • [P1] Inspect the exact Codex source governing cancellation and compaction progress.
  • [P1] Run the changed compaction path against the exact merge head after resolving the contract gate.

What I checked:

Likely related people:

  • Vito Cappello: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Inspect the Codex runtime source governing cancellation and progress behavior.
  • Record maintainer acceptance of the per-request timeout semantics or retain an operation-wide deadline.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (29 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-28T22:39:29.279Z sha 9246819 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-29T18:49:23.820Z sha e383bfd :: needs changes before merge. :: [P1] Keep retained-ask checks scoped to the split-prefix summary
  • reviewed 2026-08-29T18:58:44.227Z sha 58246f0 :: found issues before merge. :: [P1] Scope retained-ask checks to the split-prefix summary
  • reviewed 2026-08-29T19:30:50.010Z sha 9fcbe25 :: found issues before merge. :: [P1] Feed corrective feedback to split-prefix retries
  • reviewed 2026-08-29T20:17:53.455Z sha b09b57c :: needs changes before merge. :: [P1] Parse the split-prefix format before auditing pending asks
  • reviewed 2026-08-29T20:27:52.953Z sha 3bd7431817cf7553358c26f89fe3f94e3628ab1b :: needs changes before merge. :: [P1] Audit the split-prefix format before rejecting pending asks
  • reviewed 2026-08-29T20:46:20.196Z sha 5594d1b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-29T20:58:13.071Z sha 5594d1b :: needs maintainer review before merge. :: none

@VACInc
VACInc force-pushed the fix/managed-context-pressure branch from f117634 to 98068df Compare August 27, 2026 15:53
@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Addressed the ClawSweeper P2 at head 98068df9b22:

  • output-absent usage is authoritative only when total_tokens >= input_tokens;
  • added regressions for zero, smaller, and equal totals;
  • reran focused owner tests (60 passed), pnpm test:changed (130 passed), node scripts/check-changed.mjs, and autoreview (clean).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 27, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: M and removed size: S labels Aug 27, 2026
@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Updated head 93e68afbe33 with the second compaction failure found in the same pipeline:

  • delegated native compaction no longer receives a duplicate aggregate context-engine timeout;
  • built-in serial compaction refreshes its watchdog when each model request starts, while each hung request remains bounded by the configured timeout;
  • split/serial behavior and the 180-second default are unchanged.

Pre-fix regressions failed with the old aggregate timeout and duplicate wrapper; the patched focused suite passes 179 tests. node scripts/check-changed.mjs and autoreview are clean. The PR body includes the sanitized RCA, local full-suite worker limitation, and production/test LOC split.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 27, 2026
@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Addressed both logical ClawSweeper P1s at head d4a980c781a:

  • recorded the maintainer decision to adopt per-model-request timeoutSeconds semantics for built-in staged compaction; docs now state explicitly that a complete staged compaction may exceed the value, while each request remains bounded and plugin-owned compaction keeps one aggregate deadline;
  • centralized timeout ownership in compactContextEngineWithSafetyTimeout, so queued/manual, overflow, and timeout-recovery paths all bypass the duplicate outer timer for the default delegating engine.

The new overflow and timeout-recovery regressions both failed on 93e68afbe33 with Error: Compaction timed out. The final focused suite passes 187 tests; node scripts/check-changed.mjs and review-driven autoreview are clean.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

Exact head 5594d1ba8b0bb5d6e02e396098c2177f27f721a8 is mergeable and exact-head CI is green after rerunning one isolated Codex startup-fixture EPIPE: https://github.com/openclaw/openclaw/actions/runs/33274025977

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.

@clawsweeper

clawsweeper Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@VACInc

VACInc commented Aug 30, 2026

Copy link
Copy Markdown
Member Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants