Skip to content

refactor(sessions): route transcript appends through the session actor - #168539

Merged
steipete merged 83 commits into
mainfrom
dbasync/actorb3
Oct 11, 2026
Merged

steipete merged 83 commits into
mainfrom
dbasync/actorb3

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

SessionManager repeatedly prepares writers and reloads transcript facts while appending messages and tool results. Cut these durable points over to the session actor without losing committed receipts, live authority, or accepted-write settlement.

User Impact

No intentional user-visible behavior change. The warmed append path removes 26 SQLite statements and one committed transaction with zero added requests. No schema, durability, retention, or permission change; no operator action required. This lane does not by itself reach the campaign's under-500 warmed-turn aim.

Why This Change Was Made

Stacked on dbasync/actorb1. The measured B1 base is b11f7c318270752376f0129528c6a589b5bd6c51; candidate is 0a5499ea1645ca4fb007ab304ccfe1fde7449351. Those measurements describe the original approved lane head. Landing subsequently incorporated main through merge commits and retained the upstream native-incognito owner.

Retain one exact physical/session actor for the attempt, including accepted descendants after a teardown timeout. Route SessionManager messages, metadata, tool-result persistence before acknowledgement, and bound transcript appends through appendToolResult / appendTranscriptEvent. Each durable append has one transaction. Capture the native receipt before fallible publication, preserve SessionTranscriptMessageCommittedError, and never repeat an unknown-outcome append.

B1 contract update 3 permits a synchronous replica snapshot and validates the optional expected preimage inside the command. The pre-append read is gone. Only a typed stale-version result, proving no mutation ran and carrying the current postimage, permits one retry; authority is checked again. The captured commit always wins over a contradictory reply. Session-scoped invalidation leaves unrelated sessions resident.

Preparation, anchors, watermarks, and context membership consume the actor's admitted metadata. Historical message payload hydration stays bounded; no full-history cache saving is claimed. After integrating #168602, native-incognito stays on its existing transcript owner and does not acquire an actor. Durable sessions use the actor append path. Released unbound SDK/native calls and explicit compaction maintenance keep named compatibility adapters; actor-bound callers have no parallel old writer path. Writer-lease types move to a leaf owner, with existing exports retained.

Deliberate compromises

The final audit against "Choose good compromises" retained the existing ownership contract rather than adding another coordination layer. This cutover removes the pre-append read and superseded actor-bound writer; it adds no fencing token, revocation generation, durable command ledger, caller-side reconciliation loop, or per-write cross-thread handshake. The existing writer-lease/navigation checks are preserved, not newly invented. Native-incognito keeps its existing owner after #168602 removed the adapter. The drain callback releases durable actors through the existing accepted-work lifecycle rather than introducing a second settlement mechanism.

Accepted edge case: a durable append can succeed while local view/receipt publication fails. The caller reports the existing committed-error contract and does not replay the append. An unknown result likewise stops this attempt. The current actor contract explicitly forbids command replay and does not make command IDs durable idempotency keys; message-level idempotency remains intact where supplied. General automatic retry is therefore not safe for every metadata/event append and is intentionally not built here. Only the typed stale-version outcome proves no mutation ran and allows the bounded retry above.

Statement and request evidence

Four required alternating B1/C pairs ran on one Hetzner runner, followed by the required fifth pair because the initial first-turn median rose. All ten complete workloads passed. The tables below include all five pairs; medians are computed separately for each side. A warmed sample is its ten-turn sum divided by ten, then the five-sample median. All-thread counts include MAIN. MAIN requests identify the sender; MAIN statements identify the executing thread. Actor commands, logical requests, transfer frames, native calls/statements, and committed transactions are distinct counters.

Comparison First-turn statements Warmed statements/turn Entire-workload statements Entire-workload worker requests
Initial four-pair medians 1148 → 1314 675.6 → 643.9 15467.5 → 14929 2936.5 → 2945
Required fifth pair alone 1542 → 1168 677.3 → 654.1 15411 → 15010 2933 → 2935
All-five medians 1171 → 1187 675.9 → 648.1 15467 → 14975 2936 → 2935

The fifth pair alone is +2 requests, not a request saving. Under the campaign's median granularity, the whole-workload comparison after that confirmation is −492 statements, −1 worker request, −2 DB requests. The remaining first-turn +16 statements / +8 worker requests is redistribution, not reported as an improvement. Recorded stacks locate the shifted work in memory-index admission/indexing and memory-workspace locks, not the append path. The affected unchanged families have equal whole-workload medians:

Family B1 requests / statements Candidate requests / statements
Memory schema.admit 1 / 130 1 / 130
cron.mutateJobs 2 / 24 2 / 24
Memory lock pluginState.compareDelete 34 / 153 34 / 153
Memory lock pluginState.compareUpdate 17 / 119 17 / 119
Memory lock pluginState.observe 17 / 68 17 / 68
Memory cache.write 8 / 98 8 / 98

All gated duration ratios are below 1.5 (maximum observed phase-median ratio 1.046). Boot/connect/first combined statements are 4665 → 4702 (+0.79%); control/cron and compaction/shutdown are also reported in retained evidence. Non-turn increases are within the campaign tolerance and come from unchanged owners. No saving is credited merely for thread movement.

Exact append attribution

Warmed append family B1 requests / statements / committed transactions Candidate requests / statements / committed transactions
Native metadata append 2 / 48 / 3 0 / 0 / 0
Actor transcript append 0 / 0 / 0 2 / 22 / 2
Actor pre-append read 0 / 0 / 0 0 / 0 / 0
Total 2 / 48 / 3 2 / 22 / 2

This attributes −26 statements, zero added requests, −1 committed transaction per warmed turn. The extra 1.8 raw warmed-statement reduction is not credited to this cutover. Across the complete workload, old metadata append/initialize is 51 requests / 1145 statements / 70 commits. Retained compatible appends plus 41 actor transcript appends and one actor tool result are 47 / 574 / 47: −4 requests, −571 statements, −23 commits in the touched families. Other-owner variation accounts for the difference from the raw workload medians. The first-turn append families themselves are 4 → 4 requests and 86 → 50 statements.

Per-phase all-thread and MAIN census: B1 → candidate, median [min–max]

Executed SQLite statements and committed outer transactions

Phase All statements MAIN statements All commits MAIN commits
Boot 3051 [3051–3081] → 3053 [3048–3081] 1944 [1944–1977] → 1949 [1944–1977] 49 [49–49] → 49 [49–49] 15 [15–15] → 15 [15–15]
Connect 435 [326–488] → 393 [323–481] 61 [61–67] → 61 [61–67] 25 [23–27] → 25 [23–26] 2 [2–2] → 2 [2–2]
First turn 1171 [1109–1542] → 1187 [1122–1579] 26 [26–53] → 26 [21–61] 95 [93–115] → 95 [93–118] 1 [1–2] → 1 [1–2]
Warmed turn 675.9 [656.9–677.3] → 648.1 [622.3–668.7] 10.2 [7.4–10.2] → 10.2 [6.6–12.4] 64.8 [63.9–65.6] → 63.8 [62.6–65.2] 0.4 [0.3–0.4] → 0.4 [0.3–0.5]
Tool/child/second session 2840 [2526–2856] → 2645 [2322–2646] 104 [73–104] → 104 [73–105] 269 [247–271] → 261 [238–263] 3 [2–3] → 3 [2–3]
Control 22 [20–209] → 22 [20–22] 0 [0–18] → 0 [0–0] 3 [3–18] → 3 [3–3] 0 [0–0] → 0 [0–0]
Cron 793 [792–795] → 722 [720–722] 17 [17–17] → 17 [17–17] 68 [68–68] → 65 [65–65] 0 [0–0] → 0 [0–0]
Compaction 267 [267–269] → 267 [267–269] 24 [24–24] → 24 [24–24] 15 [15–15] → 15 [15–15] 1 [1–1] → 1 [1–1]
Shutdown 111 [111–111] → 111 [111–115] 62 [62–62] → 62 [62–62] 9 [9–9] → 9 [9–9] 4 [4–4] → 4 [4–4]
Entire workload 15467 [15411–15545] → 14975 [14783–15028] 2340 [2336–2373] → 2345 [2341–2372] 1183 [1182–1192] → 1161 [1150–1173] 30 [30–30] → 30 [30–30]

Logical requests

Phase All worker requests MAIN worker requests All DB requests MAIN DB requests
Boot 66 [66–67] → 66 [66–66] 66 [66–67] → 66 [66–66] 64 [64–65] → 64 [64–64] 64 [64–65] → 64 [64–64]
Connect 66 [64–71] → 67 [62–70] 64 [62–69] → 64 [60–68] 60 [57–64] → 61 [55–63] 58 [55–62] → 58 [53–61]
First turn 228 [223–286] → 236 [225–308] 221 [216–279] → 229 [218–297] 200 [196–253] → 207 [197–276] 193 [189–246] → 200 [190–265]
Warmed turn 166.8 [163.6–169.2] → 166.3 [161.8–171.4] 163.8 [160.6–166.2] → 163.3 [158.8–168.4] 143.6 [140.7–146] → 143.2 [138.9–147.9] 140.6 [137.7–143] → 140.2 [135.9–144.9]
Tool/child/second session 650 [576–658] → 652 [576–654] 641 [567–649] → 643 [567–645] 571 [501–579] → 573 [501–575] 562 [492–570] → 564 [492–566]
Control 7 [5–46] → 6 [6–7] 7 [5–46] → 6 [6–7] 7 [5–46] → 6 [6–7] 7 [5–46] → 6 [6–7]
Cron 158 [157–159] → 155 [155–156] 155 [154–156] → 152 [152–153] 141 [140–142] → 138 [138–139] 138 [137–139] → 135 [135–136]
Compaction 71 [71–72] → 71 [71–72] 69 [69–70] → 69 [69–70] 58 [58–59] → 58 [58–59] 56 [56–57] → 56 [56–57]
Shutdown 15 [15–15] → 15 [15–16] 15 [15–15] → 15 [15–16] 7 [7–7] → 7 [7–8] 7 [7–7] → 7 [7–8]
Entire workload 2936 [2928–2955] → 2935 [2899–2962] 2883 [2875–2902] → 2882 [2846–2909] 2551 [2543–2568] → 2549 [2515–2574] 2498 [2490–2515] → 2496 [2462–2521]

Actor commands and native API calls (prepares included in native calls, not executed statements)

Phase All actor commands MAIN actor commands All native calls MAIN native calls
Boot 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 2738 [2737–2768] → 2740 [2735–2769] 1536 [1536–1569] → 1541 [1536–1569]
Connect 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 618 [489–712] → 581 [482–692] 98 [98–109] → 98 [98–109]
First turn 0 [0–0] → 3 [3–3] 0 [0–0] → 0 [0–0] 1614 [1523–2106] → 1632 [1569–2204] 34 [34–81] → 34 [24–91]
Warmed turn 0 [0–0] → 2 [2–2] 0 [0–0] → 0 [0–0] 778.5 [752.3–782.6] → 752.6 [714.3–781.7] 15.8 [10.9–15.8] → 15.8 [9.9–19.1]
Tool/child/second session 0 [0–0] → 14 [14–14] 0 [0–0] → 0 [0–0] 3444 [2979–3462] → 3261 [2779–3274] 147 [102–147] → 147 [102–148]
Control 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 34 [30–304] → 33 [30–34] 0 [0–23] → 0 [0–0]
Cron 0 [0–0] → 5 [5–5] 0 [0–0] → 0 [0–0] 1013 [1009–1016] → 944 [942–945] 34 [34–34] → 34 [34–34]
Compaction 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 335 [334–338] → 335 [335–338] 34 [34–34] → 34 [34–34]
Shutdown 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 168 [168–168] → 168 [168–175] 92 [92–92] → 92 [92–92]
Entire workload 0 [0–0] → 42 [42–42] 0 [0–0] → 0 [0–0] 17769 [17686–17863] → 17351 [17049–17411] 2133 [2130–2166] → 2139 [2134–2164]

Transfer frames (a received frame is not counted again as another transfer)

Phase All forward frames MAIN forward frames All reply frames MAIN reply frames
Boot 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0]
Connect 6 [6–6] → 6 [6–6] 0 [0–0] → 0 [0–0] 6 [6–6] → 6 [6–6] 0 [0–0] → 0 [0–0]
First turn 23 [23–23] → 23 [23–39] 2 [2–2] → 2 [2–3] 21 [21–21] → 21 [21–36] 0 [0–0] → 0 [0–0]
Warmed turn 9 [9–9] → 9 [9–9] 0 [0–0] → 0 [0–0] 9 [9–9] → 9 [9–9] 0 [0–0] → 0 [0–0]
Tool/child/second session 28 [28–28] → 28 [28–28] 1 [1–1] → 1 [1–1] 27 [27–27] → 27 [27–27] 0 [0–0] → 0 [0–0]
Control 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0]
Cron 9 [9–9] → 9 [9–9] 0 [0–0] → 0 [0–0] 9 [9–9] → 9 [9–9] 0 [0–0] → 0 [0–0]
Compaction 8 [8–8] → 8 [8–8] 2 [2–2] → 2 [2–2] 6 [6–6] → 6 [6–6] 0 [0–0] → 0 [0–0]
Shutdown 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0] 0 [0–0] → 0 [0–0]
Entire workload 164 [164–164] → 164 [164–180] 5 [5–5] → 5 [5–6] 159 [159–159] → 159 [159–174] 0 [0–0] → 0 [0–0]

Evidence

  • Original lane focused owner/caller proof: 210 tests, 14 files, all passed, 118.01 s wrapper. Covers durable and native-incognito FIFO/canonical ancestry, persistence before tool acknowledgement, original native owner use, replacement refusal, committed publication errors, unknown-outcome no replay, actual accepted-work drain, stale-version recovery, and unrelated-session writes. Three new no-pre-read cases fail on pre-fix d6046834d513 for the intended reason: two actor reads observed.
  • Preparation-file cost, pnpm test src/agents/embedded-agent-runner/run/attempt-transcript-lifecycle-prepare.test.ts --maxWorkers=1: B1 38 tests, 56.69 s Vitest / 81.47 s wall; candidate 47 tests, 85.16 s / 109.94 s. Peak RSS 3,408,672 → 3,424,968 KiB. Hosted CI seconds were not separately measured.
  • Original lane Madge and runtime import-cycle checks pass with zero cycles. T1 is 707 → 707 call sites across 249 files; its ratchet passes with no growth. Changed-file formatting/lint and storage/schema/runtime/pairing guards pass. The explicit continuation executes all 34 canonical selected checks: 28 pass, six inherited failures listed below.
  • SDK diff passes: 153 changed reachable declaration closures, zero direct exported-declaration changes, zero entrypoint additions/removals. Digest 6903d37cebb1758831e6b508cca5fedcc4335c0622764671742a203be89cf431. Existing exports and released synchronous/unbound behavior are retained.
  • Both exact-pin source-mapped qaRuntime builds pass. The full build/core types hit the inherited B1 error below, so this is not an all-green full-build claim.
  • Three Codex P2 review rounds were completed; the third was scoped-clean before contract update 3. Subsequent update-3 integration is covered by the regression/runtime proof above. No fourth review was run, per campaign convergence.
  • Published-driver × candidate update cell: passed from published 2026.10.1 to final head bb394679a1fb06625e633c21a03a08b7581e0afa (620 s). The service finished updating, readiness returned 200, the running version was verified, and durable plus native-incognito sessions survived.

Original lane inherited failures and gaps

Reproduced on the pinned B1 base: the assertion-safety baseline still expects two comments for session-accessor.sqlite-transcript-store.ts, whose extraction leaves one; core/build/test types encounter session-accessor.sqlite-entry-store.ts:731 using out-of-scope sessionRow (fixed later upstream by 1cbcc4aca38e); coercion guard reports session-accessor.sqlite-entry-facts.worker.ts:30 readString; deprecated-API guard reports gateway/server-methods/agents.ts:2 internal-config-api; Knip/dead exports report readSqliteDatabasePendingWriteRevision and settleFailedSqliteWorkerJobs. These paths are untouched by B3. No guard was weakened and no failure is labeled green. Later test-type graphs did not run past the inherited first-graph error; earlier pre-extraction proof passed all 27 selected graphs.

Proof ran remotely. Testbox final-head tests/static reports are at https://github.com/openclaw/openclaw/actions/runs/38062140278; subsequent sync retries timed out before executing checks. AWS quota fell back to an undersized runner, which was released without proof. The final census ran on one Hetzner lease with direct exact-commit fetch after raw sync stalled; no local Docker or heavy local proof. The shared workload is unchanged (SHA-256 1de5109a7b89eaf8c10ef943bde724a89bd44772b7d70419bd344caf18d92cd1). The lane observer avoids runtime source-map expansion, then symbolicates offline; counter calibration and exact phase/thread/SQL conservation pass. All 192 observed request kinds are source-classified; all ten workloads have zero transaction-pairing anomalies. Raw traces are deleted after compaction; compact proof is below 2 GB.

LOC versus measured B1: production +1401/−598 (net +803), tests +386/−32 (net +354), docs +22/−6 (net +16). Growth carries the receipt/admission bridge and named native/SDK compatibility owner plus durability/authority/drain regressions; superseded actor-bound writers are deleted. This is a caller cutover, not a new storage owner.

Landing integration

Merged current main with a merge commit and preserved its removal of the native-incognito actor adapter. The existing incognito transcript persistence and tool-result acknowledgement cases remain; actor-specific append assertions cover durable sessions. A subsequent CI failure exposed durable actor acquisition for detached helper attempts. The final head bb394679a1fb06625e633c21a03a08b7581e0afa skips actor/database acquisition when persistence is detached and extends the existing runtime-facts test to assert that no durable store is created. The original 31-file Bun group passes (366 tests, 88 s), focused preparation/runtime-facts proof passes (97 s), and scoped Codex P0/P1 review is clean. Final-head type-aware lint, full Knip export scans, and the export-name collision guard pass. Final-head package build/tarball integrity and the published-driver update cell also pass. CI run 38118306733 on final head stopped with two inherited failures. Both reproduce on pinned main 390f0f0acb98c577d5ccf71cd04201a6c4083c7b, independently on the same Hetzner runner:

  • test/gateway-openai-compaction-replay.e2e.test.ts — replays persisted provider state on the next embedded turn: expected continuation input to contain Continue from the compacted transcript.
  • src/gateway/server-methods/sessions-files.repository.test.ts — keeps stopped inspection limited to verified changed artifacts: expected a rejected promise, received a successful file result.

Neither test file is changed by this PR; both assertion failures match CI. No CI rerun was requested. The operator-authorized inherited-failure override applies. Native initialization repeatedly stalled during worktree allocation/checkout; its interrupted operation lock was recovered, and the explicitly authorized exact-head REST squash fallback is used. Independent dependency/security review statuses passed.

ClawSweeper follow-up: the suggested turnover-after-submission scenario is retained as a follow-up. No demonstrated data-loss, security, or money-risk finding requires new fencing or settlement machinery; the existing accepted-write lifecycle remains the owner.

…odules

Merge current main while preserving shared physical admission, cancellation, reader validation birthtime, and live deletion authority. Split worker usage, pool construction, failure settlement, and schema owner types to keep the existing line caps.
Checkpoint the single-owner cutover, cache invalidation regressions, and request-owned read transactions. Keep explicit migration verification. Paired measurement and final validation are still in progress.
Route retained existing-state writer coverage through the host-owned worker project, preserve first-admission incompatibility refusal, and match the final deletion-authority contract. Keep the gateway test under its inherited line count by moving existing pure fixture helpers. Regenerate assertion allowances without adding production assertions.
Include the thirteen transitive admission modules required by the native wrapper import-closure proof. Carry the existing birthtime through the worker validation fixture to preserve its physical-file identity.
Merge current main and preserve its optional settlement-only receipt delivery through the extracted owner. Keep the worker refusal error with the leaf contract to stay within the existing admission line cap. End the marker-free read-only fixture transaction normally; dedicated rollback and explicit revocation coverage remains unchanged.
Preserve snapshot-local reuse without freshness queries, publish dedicated archive writes, and remove Workboard polling. Retain native authority and settlement boundaries. Checkpoint reviewed corrections and focused regression repairs; final integrated proof remains in progress.
Define inactive typed durable phases, versioned hot snapshots, complete commit receipts, pure bookkeeping reducers, and unknown-outcome fencing. Share lifetime and settlement vocabulary with the existing incognito actor without changing routing or persistence.
Carry actor receipts through SessionManager and direct-note append adapters while preserving the unbound SDK path. Retain lifecycle owners until accepted descendants drain. Actor acquisition remains inactive pending the B1 runtime backend; remote proof and runtime cutover follow in this lane.
@openclaw-barnacle openclaw-barnacle Bot removed plugin: logbook Logbook automatic work journal plugin plugin: team-reports labels Oct 11, 2026
@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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Oct 11, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

ClawSweeper follow-up: retain the suggested turnover-after-submission proof as follow-up work. This review did not demonstrate user-data loss, a security hole, or money risk; the accepted-write lifecycle remains the owner, without adding speculative fencing. The native-incognito persistence issue is addressed in a552cdb: native-incognito keeps its existing transcript owner, while durable sessions use actor-backed appends.

@openclaw-barnacle openclaw-barnacle Bot removed the scripts Repository scripts label Oct 11, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 11, 2026
Detached helper attempts retain caller-owned transcript state. Skip durable actor acquisition for them so preparation does not create a database or route later reads through an unintended owner. Extend the existing runtime-facts test to verify that the attempt creates no durable database.
@steipete
steipete merged commit 5843d60 into main Oct 11, 2026
119 of 136 checks passed
@steipete
steipete deleted the dbasync/actorb3 branch October 11, 2026 07:17
obviyus added a commit that referenced this pull request Oct 12, 2026
…mpaction V2) (#168401)

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` (#168843; same fix as #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 |

- #168981 independently reports the prompt-cache failure on clean main.
- #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 `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`):
   - Fails the same way on a clean `origin/main` checkout at `ff6f58a8c32`, and passes at `bdcbb2d8870` (10/10).
   - `git bisect` names `e63b5a01cf26` as the first bad commit: #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 #169026 (CI run 38137511377).
   - Passes locally (2/2) on this head, on clean `origin/main` `ff6f58a8c32`, 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
openclaw#168539)

* perf(sqlite): checkpoint shared admission across workers (WIP)

* test(sqlite): align worker fixtures with shared admission

* perf(sqlite): avoid repeated quarantine reads in retained scopes

* docs(sqlite): define single-owner database freshness

* perf(sqlite): replace runtime probes with writer publications

Checkpoint the single-owner cutover, cache invalidation regressions, and request-owned read transactions. Keep explicit migration verification. Paired measurement and final validation are still in progress.

* test(sqlite): align first-admission coverage and deletion fixtures

Route retained existing-state writer coverage through the host-owned worker project, preserve first-admission incompatibility refusal, and match the final deletion-authority contract. Keep the gateway test under its inherited line count by moving existing pure fixture helpers. Regenerate assertion allowances without adding production assertions.

* build(sqlite): include shared admission in compiled wrappers

Include the thirteen transitive admission modules required by the native wrapper import-closure proof. Carry the existing birthtime through the worker validation fixture to preserve its physical-file identity.

* test(sqlite): use the canonical settlement owner in publication proof

* fix(sqlite): complete writer custody and snapshot cache lifetimes

Preserve snapshot-local reuse without freshness queries, publish dedicated archive writes, and remove Workboard polling. Retain native authority and settlement boundaries. Checkpoint reviewed corrections and focused regression repairs; final integrated proof remains in progress.

* fix(sqlite): retain integrity and worker admission through cleanup

* test(sqlite): preserve reader coverage in existing fixture owners

* fix(sqlite): preserve cache receipts across sibling writers and temp DDL

* fix(workboard): type the replacement card-list promise

* fix(sessions): integrate receipt-based list revision reads

* perf(sessions): reuse committed entry facts across ordered reads

* refactor(sessions): identify fused query as worker-only

* fix(sessions): preserve receipt facts across read phases

* docs(sessions): clarify retained listing and alias guards

* refactor(sessions): define shared session actor contract

Define inactive typed durable phases, versioned hot snapshots, complete commit receipts, pure bookkeeping reducers, and unknown-outcome fencing. Share lifetime and settlement vocabulary with the existing incognito actor without changing routing or persistence.

* refactor(sessions): update actor cutover contract

* refactor(sessions): prepare actor-backed transcript appends

Carry actor receipts through SessionManager and direct-note append adapters while preserving the unbound SDK path. Retain lifecycle owners until accepted descendants drain. Actor acquisition remains inactive pending the B1 runtime backend; remote proof and runtime cutover follow in this lane.

* refactor(sessions): add inactive phase actor backend

* refactor(sessions): preserve actor append outcomes through callers

* fix(sessions): preserve actor projection readiness and held facts

* perf(sessions): reuse retained transcript initialization facts

* refactor(sessions): bind attempt appends to the session actor

* test(sessions): service actor fixture admission synchronously

* feat(sessions): contract update 2 for existing incognito owners

* fix(agents): retain native incognito actor for transcript appends

* perf(agents): defer native actor adapter loading

* fix(sessions): reacquire incognito projection claims after actor commits

* test(sessions): distinguish model metadata from context messages

* refactor(sessions): separate actor contracts and share mutation executors

* docs(sessions): explain actor assertion invariants

* fix(sessions): borrow active native actor admission

* fix(sessions): publish committed actor initialization identity

* refactor(sessions): share native transcript presence query

* test(sessions): assert atomic metadata cancellation receipts

* docs(sessions): describe actor append cutover

* test(sessions): explain actor eviction mock isolation

* test(sessions): observe actor context fallback boundary

* refactor(sessions): separate native persistence compatibility

* refactor(sessions): retain private writer claim storage

* fix(sessions): preserve typed actor append failure and scope

* refactor(sessions): keep writer lease types below actor contracts

* fix(sessions): retain optional actor writer fence fields

* test(sessions): align actor fixtures with typed owner contracts

* fix(sessions): preserve actor callback bindings and audit inactive APIs

* fix(sessions): preserve actor callback bindings and lint contracts

* fix(sessions): keep host config out of worker transport bundles

* feat(sessions): contract update 3 for scoped receipts and command preimages

* fix(sessions): reject mutations during actor authority admission

* perf(sessions): append with actor command-local preimages

* fix(sessions): retain actor state across unrelated pending writes

* fix(sessions): preserve incognito transaction settlement contract

* test(sessions): keep scoped receipt fixtures within storage contracts

* refactor(sessions): separate receipt and transcript helper responsibilities

* test(sessions): pass the logical scope to sibling writes

* fix: retain native incognito transcript ownership

* fix(sessions): keep detached attempts out of durable actors

Detached helper attempts retain caller-owned transcript state. Skip durable actor acquisition for them so preparation does not create a database or route later reads through an unintended owner. Extend the existing runtime-facts test to verify that the attempt creates no durable database.
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 16, 2026
Step 29 absorbed upstream openclaw#168539, whose session actor replica trusts the
scoped write token of its own session keys. Our recipient-authority epoch
write ran outside any write scope, so it counted as unscoped and advanced
every session's token: an owner change on one session revoked every
unrelated replica on the database. Upstream's
session-actor-replica.test.ts ("retains unrelated session postimages but
invalidates a shared physical session window") failed on the absorb and
passes on plain upstream 5843d60; with the advance disabled it passed,
which isolates the cause.

Scope the epoch write to its own session key inside
advanceSessionRecipientAuthorityInTransaction, so every caller (owner,
visibility narrowing, membership removal, lifecycle delete, capture) is
covered.

Also keep session-accessor.sqlite-entry-read.ts under its line cap (our
raw-row reader pushed it 700 -> 704 after upstream growth): the owner
path reads the exact-row query cache directly, and its call site already
explains why it skips participant projection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
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 P2 Normal backlog priority with limited blast radius. 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.

1 participant