Repository navigation
feat(agents): compact ChatGPT sign-in sessions server-side (remote compaction V2) - #168401
Conversation
Related: #168088 Co-authored-by: obviyus <[email protected]>
Plugin provider streams return before dispatching, so the V2 request was rejected as never reaching the Responses transport and every live compaction fell back to client summaries. Log every V2 fallback reason at WARN.
…rver-side-compaction-approaches
…rver-side-compaction-approaches
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: needs maintainer review before merge. What this changesThis PR makes automatic ChatGPT sign-in compaction use the normal provider request and saves an opaque checkpoint for subsequent turns. Example: An openai/gpt-6-astra conversation reaches automatic compaction.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it delivers approved ChatGPT compaction behavior absent from main, with relevant live evidence and no actionable finding; final landing remains author-owned. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe embedded agent prepares conversation context and tools, the ChatGPT transport requests provider compaction, and the existing session writer persists the checkpoint for later request serialization. flowchart LR
A[Conversation and tools] --> B[Embedded request boundary]
B --> C[ChatGPT Responses transport]
C --> D[Completed compaction checkpoint]
D --> E[Session transcript writer]
E --> F[Later request replay]
Technical reviewBest possible solution: Land the approved request-boundary implementation through the author’s existing landing plan, preserving opt-outs, durable checkpoints, and client recovery. Do we have a high-confidence way to reproduce the issue? This is an approved feature rather than a newly established bug; current-main source still uses the prior behavior, and supplied live Gateway results demonstrate the requested improvement. Is this the best way to solve the issue? Building compaction through the normal request pipeline preserves prompt parity without retaining a second warm-request cache, while the existing session owner handles persistence and recovery. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 992410c17ab7. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +1432, Tests +974, Docs +26, Other -3. Total +2429 across 50 files. Added test files: 2. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (18 earlier review cycles; latest 8 shown)
Reviewed October 11, 2026, 9:32 PM ET / October 12, 2026, 01:32 UTC (Revision 19). |
|
Upgrade proof from latest stable to this branch, live with a real ChatGPT OAuth test login, isolated state. Stable is Method: stable initialized fresh state and created both sessions. The candidate then opened that same state. Main's storage is a newer schema than 2026.9.9, so the candidate first asked for its usual migration ( A — default (server compaction on):
B — stored opt-out (
Also fixed since the last review:
@clawsweeper re-review |
# Conflicts: # src/agents/embedded-agent-runner/run/attempt-prompt-phase.ts # src/agents/embedded-agent-runner/run/attempt-prompt-preflight.test.ts # src/agents/embedded-agent-runner/run/attempt-prompt-preflight.ts # src/agents/embedded-agent-runner/run/attempt-setup.ts # src/agents/embedded-agent-runner/run/attempt-stream.ts
|
@RomneyDa thanks for the budget-anchor fix and the merges. I own the final landing of this PR, by agreement with Ayaan. Please make no further pushes to this branch. I'll keep your commits ( |
# Conflicts: # config/assertion-safety-baseline.txt # packages/ai/src/providers/openai-chatgpt-responses.ts # src/agents/embedded-agent-runner/run/attempt-context-guards.test.ts
#167938 replays the recorded model-prompt projection, so the consumed /think directive is absent from the second turn's replay of the first, as it was from the original request.
|
Red-job attribution for head
ClawSweeper is |
|
Maintainer override (Ayaan approved landing; we own this change). ClawSweeper is
|
|
Final live smoke on head
|
…mpaction V2) (openclaw#168401) Closes openclaw#168088. Related: openclaw#168164. ## What Problem This Solves With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing `{"type":"compaction_trigger"}` item, and the provider returns one opaque `compaction` item that stands in for the history. ## Fix - **Request:** automatic compaction on the ChatGPT route (preflight before a turn, and mid-turn between tool rounds) sends V2 as the next normal request, through the same attempt pipeline and native ChatGPT stream, with `compaction_trigger` appended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache. - **Result:** exactly one non-empty `compaction` item is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt. - **Checkpoint:** real user messages are retained newest-first within 64k tokens, plus the item, matching Codex `compact_remote_v2.rs`. Users retained from an earlier window stay eligible, so repeated compactions keep them. - **Fallback:** every fallback to client compaction logs a WARN with its reason. Overflow recovery, `/compact <focus>` and manual `/compact` stay client-side; manual V2 needs session-writer ownership work and is a follow-up. - **Fixed during live testing** (each with a regression that fails on the defect): 1. V2 never ran: the compact request was checked before the async provider adapter dispatched it. 2. V2 ran only in the managed client; real ChatGPT turns use the native stream. V2 now runs there. 3. Replay normalization dropped the checkpoint turn as an empty failed turn, so the next request grew back to full history. It now keeps successful compaction checkpoints; error turns and suppression markers are still dropped. ## User Impact ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k. `params.responsesCompactEndpoint: false` turns it off. ## Evidence Live, real ChatGPT OAuth login, `openai/gpt-6-astra`, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds. | Compaction | Compaction input / cached / output | Wall | Input before → after | Next user turn input / cached | Recall | |---|---:|---:|---:|---:|---:| | Preflight | 90,999 / 73,856 / 885 | 20.2 s | 90,999 → 22,308 | 22,439 / 22,144 | 3/3 | | Mid-turn, first | 91,075 / 82,560 / 575 | 12.3 s | 91,075 → 13,904 | 14,121 / 12,928 | 3/3 | | Mid-turn, second | 76,486 / 58,880 / 716 | 17.4 s | 76,486 → 14,476 | 14,709 / 14,336 | 3/3 | Request parity, compaction request vs the preceding normal turn: | Compaction | Tools | Instruction chars | Input prefix | Cached vs previous input | |---|---|---|---|---:| | Preflight | 6 → 6 | 35,857 → 35,857 | 26/26 items identical | 89.3% | | Mid-turn, first | 6 → 6 | 35,855 → 35,855 | 26/26 items identical | 99.8% | | Mid-turn, second | 6 → 6 | 35,855 → 35,855 | 39/39 items identical | 86.7% | The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3 `compaction_trigger` requests, all HTTP 200, and no client-summary requests. **Client comparison (same route, before this change):** one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark. **Tests:** fetch-boundary regressions across the managed and native ChatGPT streams cover: - request parity; - failed, cancelled and incomplete terminal responses; - aborts; - duplicate or empty items; - multilingual retention; - two consecutive persisted compactions; - the async-dispatch case and replay normalization through the real `SessionManager`. Negative controls fail on each defect. tsgo core/src/packages pass; `check-changed` passes. ## Release-landing follow-ups (2026.10.2) - **ClawSweeper P2 fix (budget anchor), commit e902124:** V2 used to price the outgoing request with the conservative preflight estimator. That estimator counts unchanged instructions twice, because measured usage already includes them. The V2 boundary now uses the same accounting as the mid-turn precheck it replaces: - The shared code is `resolveProjectedRequestPressure`, split out of `checkMidTurnPrecheck`. - The stream guard's request observation now returns the matching measured predecessor. The foreground request is observed before V2 decides, so both price the same anchor. A checkpoint request is then observed again as its own request. - Requests with no anchor keep the conservative estimate. - Regression test: `chatgpt-v2-compaction.test.ts` "prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers from `attempt-midturn-precheck.test.ts`. It fails on the previous head (the boundary throws `MidTurnPrecheckSignal`) and passes now. - Production LOC: +45/-27. Most of that is the function split plus contract comments. - **Test-only fixture fix, commit 018c9bc:** three Gateway e2e fixtures counted the labeled `OpenClaw runtime context:` carrier as a user turn: `gateway-rpc-chat`, `gateway-provider-review-product-proof` and `gateway-completion-replay`. These fail the same way on `main` (openclaw#168843; same fix as openclaw#168961). - **Rollback to v2026.10.1:** that release's replay normalization drops the empty, zero-usage V2 checkpoint carrier. The raw transcript is never rewritten, so v2026.10.1 replays the full raw history, and its own client compaction applies if that history is too large. Rollback loses no data; it just loses the provider checkpoint. The stored checkpoint format already shipped in v2026.10.1, and its reader ignores the added optional `outputTokens` (details in the compatibility comment). ### Unrelated failures that also happen on `main` (proof scoped to the tests involved) Both failures reproduce on a clean `origin/main` checkout at `02040ecbc92` with no PR code. Checking out commits around one change shows that both start at 9657a374 (openclaw#168539, "route transcript appends through the session actor"): | Test | `9657a374^` | `9657a374` | `origin/main` `02040ecbc92` | |---|---|---|---| | `src/agents/embedded-agent-runner.prompt-cache.test.ts` | 4/4 pass | 2 fail (`SqliteTranscriptMutationConflictError` from `appendSessionManagerActor`) | 2 fail | | `test/gateway-steer-fifo.e2e.test.ts` | 7/7 pass | 3 fail (1 model request where 2 are expected) | 3 fail | - openclaw#168981 independently reports the prompt-cache failure on clean main. - openclaw#169006 (steering diagnostics) landed and did not fix the steer-fifo failures. - CI selects these tests for this PR only through the shared embedded-runner files. Neither failing path is touched here. ### Local proof on the current head All runs below were local and focused on the touched files: - `chatgpt-v2-compaction`: 13/13. - The other affected `src/agents/embedded-agent-runner/run/` unit files: 208/208. These are `attempt-midturn-precheck`, `attempt-prompt-submit.*`, `attempt-stream-*`, `preemptive-compaction*`, `attempt-execution-phase`, `attempt-prompt-preflight` and `attempt-context-guards`. - `agent-runner.runreplyagent.e2e`: 231/231. - The 3 repaired Gateway e2e files: all passed. - `node scripts/check-changed.mjs -- <touched files>` exited 0. That run includes `tsgo` for core and core tests. - Codex protocol check (read directly in `../codex`): `codex-rs/core/src/compact_remote_v2_attempt.rs:70-84` and `compact_remote_v2.rs:65,398-450`. ### Unrelated failures on the current head (b3a7405, which merges `origin/main` at `3dc543d9ee8`) The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain: 1. **`src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts`** (5 tests, `checks-node-changed-compact-large-4`): - Fails the same way on a clean `origin/main` checkout at `3dc543d9ee8`, and passes at `596e31d1764` (10/10). - `git bisect` names `70e895e21606` as the first bad commit: openclaw#168992, "perf(agents): reduce repeated SQLite work during agent preparation". - This PR does not touch native harness auth. 2. **`extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts`** (`checks-node-changed-extensions-bundle-3`, 180s hook timeout): - Also fails on the unrelated PR openclaw#169026 (CI run 38137511377). - Passes locally (2/2) on this head, on clean `origin/main` `3dc543d9ee8`, and on this branch merged with that main. - This PR touches no `extensions/codex` files. Two other failures were flaky: `build-artifacts` (`sqlite-sessions-transcripts-flip-proof.built-cli`) and `gateway-completion-replay`. Each passed on rerun, and each passes locally after `pnpm build` on this head. Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Dallin Romney <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
First-parent upstream 84a834e..2b9aa2e (112 commits, including openclaw#169327 actor memory storage for incognito consumers, openclaw#169458 session bookkeeping/transcript workers, openclaw#169449 gateway read paths, openclaw#169364 cron worker queue, openclaw#168401 remote compaction V2, openclaw#169467 transcript backlog). Conflicts: - session-reset-service.ts: upstream moved ensureSessionRuntimeCleanup into session-reset-runtime-cleanup.ts. Took upstream's form and ported our delta into the new module: the `reason` parameter and the awaited clearSessionScopeRuntimeState (continuation cancellation that cannot persist returns UNAVAILABLE). Callers keep passing `reason`. - attempt-execution.ts: upstream made the Claude CLI fallback prelude async; ported the await into our extracted resolveClaudeCliFallbackPrelude. - session-accessor.sqlite-lifecycle.ts: upstream's two actor-storage imports; the eviction kick import stays where the fork moved its caller. - status-message.ts: upstream threads preparedTtsPreferences into the voice line; ported into our status-session-lines.ts helper. - plugin-sdk-surface-report.mts budgets; worker inventory regenerated. Also: session-actor-memory-collaboration-contract.ts (new upstream file) excludes the fork's sharing `authority.capture` op from actor memory commands (it runs only on the sharing writer's owner), as at step 26. Refs #1475 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes #168088. Related: #168164.
What Problem This Solves
With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing
{"type":"compaction_trigger"}item, and the provider returns one opaquecompactionitem that stands in for the history.Fix
compaction_triggerappended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache.compactionitem is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt.compact_remote_v2.rs. Users retained from an earlier window stay eligible, so repeated compactions keep them./compact <focus>and manual/compactstay client-side; manual V2 needs session-writer ownership work and is a follow-up.User Impact
ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k.
params.responsesCompactEndpoint: falseturns it off.Evidence
Live, real ChatGPT OAuth login,
openai/gpt-6-astra, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds.Request parity, compaction request vs the preceding normal turn:
The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3
compaction_triggerrequests, all HTTP 200, and no client-summary requests.Client comparison (same route, before this change): one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark.
Tests: fetch-boundary regressions across the managed and native ChatGPT streams cover:
SessionManager.Negative controls fail on each defect. tsgo core/src/packages pass;
check-changedpasses.Release-landing follow-ups (2026.10.2)
resolveProjectedRequestPressure, split out ofcheckMidTurnPrecheck.chatgpt-v2-compaction.test.ts"prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers fromattempt-midturn-precheck.test.ts. It fails on the previous head (the boundary throwsMidTurnPrecheckSignal) and passes now.OpenClaw runtime context:carrier as a user turn:gateway-rpc-chat,gateway-provider-review-product-proofandgateway-completion-replay. These fail the same way onmain(Three Gateway e2e tests fail on main: fixtures still match the old runtime-context envelope #168843; same fix as fix: Gateway regression tests fail after runtime context labeling changes #168961).outputTokens(details in the compatibility comment).Unrelated failures that also happen on
main(proof scoped to the tests involved)Both failures reproduce on a clean
origin/maincheckout atce5b795128ewith no PR code. Checking out commits around one change shows that both start at 5843d60 (#168539, "route transcript appends through the session actor"):5843d60c^5843d60corigin/maince5b795128esrc/agents/embedded-agent-runner.prompt-cache.test.tsSqliteTranscriptMutationConflictErrorfromappendSessionManagerActor)test/gateway-steer-fifo.e2e.test.tsLocal proof on the current head
All runs below were local and focused on the touched files:
chatgpt-v2-compaction: 13/13.src/agents/embedded-agent-runner/run/unit files: 208/208. These areattempt-midturn-precheck,attempt-prompt-submit.*,attempt-stream-*,preemptive-compaction*,attempt-execution-phase,attempt-prompt-preflightandattempt-context-guards.agent-runner.runreplyagent.e2e: 231/231.node scripts/check-changed.mjs -- <touched files>exited 0. That run includestsgofor core and core tests.../codex):codex-rs/core/src/compact_remote_v2_attempt.rs:70-84andcompact_remote_v2.rs:65,398-450.Unrelated failures on the current head (b3a7405, which merges
origin/mainatff6f58a8c32)The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain:
src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts(5 tests,checks-node-changed-compact-large-4):origin/maincheckout atff6f58a8c32, and passes atbdcbb2d8870(10/10).git bisectnamese63b5a01cf26as the first bad commit: perf(agents): reduce repeated SQLite work during agent preparation #168992, "perf(agents): reduce repeated SQLite work during agent preparation".extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts(checks-node-changed-extensions-bundle-3, 180s hook timeout):origin/mainff6f58a8c32, and on this branch merged with that main.extensions/codexfiles.Two other failures were flaky:
build-artifacts(sqlite-sessions-transcripts-flip-proof.built-cli) andgateway-completion-replay. Each passed on rerun, and each passes locally afterpnpm buildon this head.Current State (2026-10-12)
8bef14f9. ClawSweeper: diamond lobster, no findings.extensions/codex/src/app-server/settled-turn-finalizer.native.test.ts. That is a main regression from fix(codex): prepare mirror write authority before reserving the transcript writer #169343, fixed by fix(plugin-sdk): install the mirror write assertion on the resolved transcript target #169498, which is not yet landed.scripts/pr. Not part of 2026.10.2.