Skip to content

feat(agents): compact ChatGPT sign-in sessions server-side (remote compaction V2) - #168401

Merged
obviyus merged 33 commits into
mainfrom
openclaw/comparing-server-side-compaction-approaches
Oct 12, 2026
Merged

obviyus merged 33 commits into
mainfrom
openclaw/comparing-server-side-compaction-approaches

Conversation

@obviyus

@obviyus obviyus commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

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 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 (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).
  • 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 ce5b795128e with no PR code. Checking out commits around one change shows that both start at 5843d60 (#168539, "route transcript appends through the session actor"):

Test 5843d60c^ 5843d60c origin/main ce5b795128e
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

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 ff6f58a8c32)

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):
  2. extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts (checks-node-changed-extensions-bundle-3, 180s hook timeout):

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.

Current State (2026-10-12)

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: XL labels Oct 10, 2026
@github-actions

github-actions Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 8bef14f9ec73f425c7bdc819ad0ab95d3645acc7
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/transcript-redact-replay.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: Client-side summarization makes separate requests and replaces context with a text summary.
  • After: The reported preflight run compacted 90,999 input tokens into a checkpoint, and the next user turn used 22,439 input tokens while recalling all three seeded facts.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Approved, useful behavior with live entry-point evidence, focused failure coverage, and no actionable finding; this read-only review ran no tests.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied real ChatGPT OAuth Gateway results exercise the changed native transport at preflight and mid-turn boundaries, show matching request surfaces, smaller later turns, consecutive checkpoints, and correct recall; the accepted upgrade run covers restart and a stored opt-out, and the latest revision changes only a test expectation.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: ChatGPT sign-in conversations pay for separate client summaries and lose conversational detail during automatic compaction.
Reason: Maintainer-authored direction and live cache, context-size, and recall results justify the implementation; manual compaction intentionally retains its existing path.

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
Reviewed head: 8bef14f9ec73f425c7bdc819ad0ab95d3645acc7

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

  • Native ChatGPT request construction keeps the original intent (89c01cd: Consolidate provider streaming while preserving transport-specific behavior; the extraction retains normal request construction and adds the V2 control item.)
  • Measured request-pressure accounting keeps the original intent (45c7bc9: Avoid premature recovery during tool-heavy turns using a matching provider-usage anchor; V2 shares that accounting and keeps conservative unanchored preflight.)
  • Retained provider windows and persistence keeps the original intent (3b3372b: Preserve canonical provider windows while honoring history ownership; the patch reuses their representation and adds optional usage accounting.)
  • Empty assistant replay filtering changes intended behavior with a stated reason (24bd0b2: Drop empty stream-error placeholders before provider replay; the explained exception keeps successful checkpoint carriers while continuing to drop errors and suppression markers.)
  • Automatic compaction ownership keeps the original intent (942d3d7: Resolve the effective runtime before maintenance so native owners retain their transcripts; V2 adds a narrow ChatGPT token-maintenance deferral without removing memory or byte maintenance.)
  • Gateway replay fixture expectation keeps the original intent (6461c18: Replay the recorded model-facing user projection; the latest test correction expects consumed directives to remain absent on replay.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 47f78a3 adds packages/ai/src/transports/openai-responses-compaction-replay.ts:103 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 47f78a32eb9e; files: packages/ai/src/transports/openai-responses-compaction-replay.ts)
  • Ayaan Gazali: Raw commit 3b3372b adds packages/ai/src/transports/openai-responses-compaction-window.ts:133 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 3b3372bd762e; files: packages/ai/src/transports/openai-responses-compaction-window.ts)

PR surface

Source +1432, Tests +974, Docs +26, Other -3. Total +2429 across 50 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 29 1678 246 +1432
Tests 17 1069 95 +974
Docs 2 33 7 +26
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 4 -3
Total 50 2781 352 +2429

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Useful provider-specific context and cache improvement with existing recovery paths.
  • merge-risk: 🚨 compatibility: Automatic ChatGPT compaction changes by default and persists optional checkpoint accounting; maintainer direction, accepted upgrade evidence, stable-reader inspection, and existing opt-outs address the tradeoff.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (18 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-11T07:46:36.547Z sha 018c9bc :: blocked before merge. :: [P2] Use the matching request anchor when deciding to compact with V2
  • reviewed 2026-10-11T09:42:58.978Z sha 018c9bc :: blocked before merge. :: [P2] Use the matching request anchor when deciding to compact with V2
  • reviewed 2026-10-11T11:00:24.343Z sha e902124 :: blocked before merge. :: none
  • reviewed 2026-10-11T11:35:24.108Z sha b3a7405 :: blocked before merge. :: none
  • reviewed 2026-10-11T12:25:21.761Z sha b3a7405 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T13:18:20.400Z sha 08d73bc :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T15:51:44.540Z sha dcbcf62 :: needs changes before merge. :: none
  • reviewed 2026-10-12T00:40:19.354Z sha 6cf0fae :: needs maintainer review before merge. :: none

Reviewed October 11, 2026, 9:32 PM ET / October 12, 2026, 01:32 UTC (Revision 19).

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 10, 2026
@obviyus

obviyus commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator Author

Upgrade proof from latest stable to this branch, live with a real ChatGPT OAuth test login, isolated state. Stable is [email protected] (npm latest); the candidate is 0bf5ce06d40.

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 (openclaw doctor --fix). Session IDs survived the migration. Every Gateway stop was graceful.

A — default (server compaction on):

  • The session created on stable loaded unchanged.
  • Automatic compaction sent compaction_trigger at 91,479 input tokens and got back an opaque checkpoint. The next request dropped to 14,017 input tokens.
  • Seven later requests and a candidate restart all replayed the checkpoint; the restart recall used 23,500 tokens.
  • All four recalls of facts seeded on stable were correct.

B — stored opt-out (responsesCompactEndpoint: false, set on stable):

  • The opt-out survived the upgrade: zero compaction_trigger requests.
  • Client compaction ran normally: 118,241 tokens before, two summary calls (8,626 and 1,233 input tokens), no WARN in either request window. The next recall used 32,404 tokens; after restart, 32,783.
  • All four recalls were correct.
  • The Gateway logged one stream-terminated/fallback warning, from an internal memory-flush session the foreground turn aborted. It is not the foreground request or compaction.

Also fixed since the last review:

  • The settings fixtures gained getCompactionEnabled. The 12 previously failing files now pass (69 tests).
  • Main merged. V2's mid-turn deferral now uses main's redesigned mid-turn precheck from fix(compaction): avoid premature recovery during tool-heavy turns #168338 (it returns early while V2 owns the request boundary), and onModelRequest sees both the V2 request and the normal request.
  • tsgo core and src pass, and 344 focused tests pass.
  • Local check-changed fails one main-owned gate (ui-e2e graph roots, 722 against a limit of 720). This PR's UI and test config inputs are identical to main's.

@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
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

@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 (dcbcf62 and the merges). Next I'll merge main once, after #169434 and #168961 land, then freeze that head, run one live ChatGPT smoke on it (V2 before a turn and mid-turn: cache parity, later-turn size, recall), and land it if CI is green and ClawSweeper is ready. If you have any unpushed changes, please send them to me instead of pushing.

# 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
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
#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.
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Red-job attribution for head 6cf0fae6eb6 (Dallin's main merge; my local merge of the same conflicts resolved them identically, so I adopted it):

ClawSweeper is ready on this exact head. A final live V2 smoke on this frozen head is running; I will post its numbers before landing.

@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override (Ayaan approved landing; we own this change). ClawSweeper is ready on 8bef14f9ec7; the only red job is inherited from main.

@obviyus
obviyus merged commit 52200cf into main Oct 12, 2026
130 of 133 checks passed
@obviyus
obviyus deleted the openclaw/comparing-server-side-compaction-approaches branch October 12, 2026 02:07
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Final live smoke on head 6cf0fae6eb6 (ChatGPT sign-in, isolated Gateway, openai/gpt-6-astra): pass. 8bef14f changes only a test fixture, so this covers the landed product code.

Compaction Cache share on compaction Next-turn input tokens Recall
Preflight (route=compact_only, est. 100,835 > 100,000 budget) 99.86% 22,221 3/3
Mid-turn #1 (same run) 99.88% 14,515 3/3 after both
Mid-turn #2 (same run) 99.80% 15,015 3/3 after both
  • This exercises the newer budget commits (406b134 retained-window preflight, dcbcf62 unanchored estimate), which were previously tested only. The numbers match the earlier proofs (87–100% cache, ~14–22k next turn, recall 3/3).
  • No client-compaction fallbacks and no provider compaction errors. The Gateway stopped cleanly with exit code 0.
  • Other log lines are unrelated: an embeddings quota 429, a memory reindex conflict, and isolated-state skill symlink warnings.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…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]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
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]>
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Default ChatGPT-login compaction to Codex-style remote compaction V2, built as the next normal turn

3 participants