Skip to content

refactor(sessions): run rewind and branch transactions in the agent executor (compound 2b) - #164753

Merged
steipete merged 2 commits into
mainfrom
dbasync/compound2b
Oct 4, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/compound2b

Conversation

@steipete

@steipete steipete commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Rewind and branch switching synchronously scan and clone transcript graphs, rebuild indexes, and rotate session entries on the Gateway thread.

Why This Change Was Made

Run the complete durable rewind/switch transaction through the existing agent database executor. Capture the physical source and selected lifecycle before yielding, prepare cold history and native-generation custody outside the transaction, and reread authoritative source/model-lock/branch predicates inside the synchronous worker transaction. Publish entry, identity, branch-cache, and subscription changes through the existing receipt owner.

Reuse the reversible native-binding settlement from #164391: the shared-state veto still precedes agent COMMIT; confirmed agent rollback conditionally restores the removed binding; unknown outcomes retain custody and block reuse without replay. The reusable extension points are SessionNativeBindingParticipants, runSessionNativeBindingWorkerOperation, and runSessionNativeBindingTransaction.

User Impact

No new product behavior, schema, persistent cache, retention, durability, configuration, or update migration. This converts rewind and branch switching only. Fork-at-message belongs to #158030; the fork family remains C6/compound 3. This does not adopt the new native fork command in #162287. Per coordinator direction, overlap with retained-history authority #163592 and the inactive #162433 design draft is intentional; hunks stay within this lane.

Production: 12 files, +602 / −158 / net +444 (760 changed lines). Static T1: 915 → 915 against e25a98150544d4848f4296e79b1d5384ed8f6ab6; mixed native/worker kernels retain their conservative classification. No new OPENCLAW_* names.

Evidence

  • Real sessions.rewind and sessions.branches.switch handler tests prove zero caller-thread SQL for the moved operations, preserve transcript history, and refresh branch identity/cache state. The same boundary tests failed on the original implementation.
  • Model-lock and both caller-authority forms refuse at the transaction boundary. Physical-store replacement and implicit selected-generation races refuse; an acknowledged mutation survives retirement of its old authority.
  • Real native storage proves precommit veto/error identity, exact-payload compensation, successor preservation, actual worker-loss blocking, delayed receipt, and lost-reply settlement.
  • Real server close holds accepted persistence before worker SQL, aborts the scheduler, rejects new requests, joins the accepted rewind, closes the database, and verifies persisted history through a reopened handle.
  • Shared-registry import rule: runtime-process build graph, get-reply imports, shared-state worker imports, worker runtime imports, wrapper source closure, and the targeted PR wrapper inventory test all passed.
  • Original functional-patch Codex review through P2: scoped-clean. Madge: 0 cycles (135.87 s). Worker ratchet: passed (34.98 s).

The synthetic real-Gateway C3 workload passed four turns, rewind/divergence/switch history assertions, and clean shutdown, with no SQL errors. Measurement baseline is clean 2df2d8455db0bec1488ccfe8790b093f90362a4b; candidate uses the built production bytes committed in da930b8ae63c757672c6157421ded154af17b6b0 (only mechanical test lint edits followed the build). The original C3 kernel/handler/native settlement sources were unchanged between that baseline and the pinned merge base.

Measurement Rewind before → after Branch switch before → after
C3 preparation + transaction caller SQL 221 → 0 260 → 0
C3 statements off main 0 → 222 0 → 262
Whole RPC-window caller SQL 250 → 35 335 → 35
Main native SQL execution 111.37 → 0.78 ms 53.28 → 0.43 ms
RPC latency 265.79 → 602.28 ms 274.29 → 239.01 ms

The remaining 35 caller statements are outside C3: 12 session preflight, 6 upstream-link preflight, 17 placement read/reconciliation. Original kernel-only attribution remains 217/256 before and 0/0 after. These instrumented single runs on a loaded host establish execution placement, not an overall latency improvement. Candidate workload wall time was 352.44 s, including 282.67 s startup; all owned processes exited.

All focused commands used pnpm test <files> --maxWorkers=1. Local wall times include the heavily loaded host and compilation:

Proof Result Wall time
Native binding owner + settlement + C3 suites 28 passed 554.26 s
Final close-prelude + six native C3 cases 7 passed 415.84 s; close assertion 15.12 s
PR wrapper inventory 1 passed 29.76 s
Core message-cut accessor 11 passed 218.20 s file time; 1,014.69 s combined command with the earlier native-fixture timeout
Real-handler boundary/model-lock 8 passed 488.41 s combined command, including an earlier close-fixture timeout
Real-handler transaction authority 6 passed 462.69 s combined command, including an earlier close-fixture scope failure
Required import/closure batch 20 passed 243.56 s shard time; 700.88 s combined command, including an earlier close setup timeout

Earlier failures were investigated, not counted as clean commands: worker read scopes initially carried a function and were narrowed to data; implicit preparation initially adopted a newer lifecycle and now retains the initial acquisition; native test injection now waits for lease quiescence and distinguishes known-not-entered readiness retries; the close fixture now uses suite setup, synchronous seeding, and an admin-scoped synthetic client. The final native/close run passes without timeout overrides. Per-file CI seconds were not recoverable from the published artifacts or bounded log inspection; the local wall times remain the measured per-file evidence.

The node scripts/check-changed.mjs --base e25a98150544d4848f4296e79b1d5384ed8f6ab6 run verified its prefix of guards, production/test type graphs, formatting, and dead exports in 2,835.79 s, then reported four test-only lint issues. The shadowed parameter, unbound helper reference, and redundant type arguments were corrected; the exact planner-selected lint step then passed in 89.85 s. Earlier unused type export was removed. The original planner's remaining script/schema/legacy-store/media/sidecar/import/webhook/auth checks were then run in order and all passed in 982.42 s, including 0 runtime value cycles. No gate was skipped. The final P2 review covers the functional patch; only these mechanical test lint corrections followed it.

qaRuntime build passed: 583.3 s build phases, 1,032.53 s including artifact-ownership wait. The committed-ref SDK diff completed locally: 151 public entrypoints and 3,644 direct exports are unchanged, with no additions/removals or direct signature changes. Its 131 reachable-closure changes (digest 415a211f) arise from internal executor/kernel declarations, equivalent participant factoring, and worker error registration retained by conservative declaration closure traversal. A source-semantic audit of all 131 affected public export types, repeated against the patch base, found no newly exposed operation or error union case; both traversals exhausted the same 23,104 types without unresolved types. The v2026.9.8 private-local inventory and package exclusions confirm that the SQLite executor facades are not released third-party type contracts. Public ModelSelectionLockedError and harness mutation callback signatures are preserved. Existing exhaustive switches over released SDK unions need no additional cases for this change. SDK diff wall time, including isolated-worktree cleanup: 1,850.74 s; semantic audit: 8.07 s head / 10.01 s base.

Retained contracts and follow-up debt

Opaque released SDK mutation hooks retain synchronous transaction visibility (v2026.9.8, src/agents/harness/types.ts:490,508, publicly reachable through src/plugin-sdk/agent-harness-runtime.ts:113). Incognito keeps its process-owned native database; maintenance/Doctor and excluded fork paths retain their existing owners.

The pre-existing operator-role fallback can read indexed shared-state profile metadata during a live caller grant: src/gateway/operator-role-policy.ts:240 (cache miss at :48) → src/state/user-profiles.ts:128 → src/state/user-profiles-internal.ts:231. Prepared-profile grants are memory-only. This other-owner authority read remains follow-up debt and is outside the moved-transaction SQL claim.

Codex subscription behavior was personally checked against sibling ../codex HEAD ade0ccacf9182e665cf784de041c51a79e35bc31, codex-rs/app-server/src/request_processors/thread_processor.rs:1011–1037: unsubscribe is connection-scoped and distinguishes not-loaded, unsubscribed, and not-subscribed. Existing subscription cleanup remains after acknowledged settlement.

The cross-database crash window is unchanged; unknown outcomes are blocked, not replayed. Testbox was not leased because of the stated organization cost cap. Full repository/release suites were not part of this focused local proof; normal PR CI remains required before merge. This PR is ready for review; it has not been landed.

Landing update

Head 9a3deb4fc1771c7871d55f052a49e7b344596ed7 merges main dac9277a4126b87f2c0b6e0fcca1de9565dc66d7 without rebasing or conflicts. The PR remains exactly 19 files, +1,450 / -192, and its stable patch ID is unchanged: 5790ce7952b894a3a2302c58649b863c41b280f6. Main's independent auth-profile error registration from #164588 composes with the model-lock registration; its behavior is preserved.

The original CI run 37175895301 had two independently inherited failures: the global-session preview fixture omitted lastMessagePreview (also observed in scheduled main run 37173736148), and the declaration fixture's native Node import could not resolve format-duration-internal.js (reproduced 5/5 on main). Main subsequently fixed them in 217efe0ad5974a and 3c0f7e4c5cdade; both fixes are included in this merge. The old admin-attribution evidence is historical and is not being used to waive fresh-head CI. The earlier PR-context heading failure was corrected and its check passed.

Fresh merged-tree proof passed 27 tests across seven files / five Vitest shards in 1,254.43 s, using node scripts/run-vitest.mjs <files> --maxWorkers=1: runtime-process build graph, get-reply imports, shared-state worker imports, worker-runtime imports, PR wrapper source closure, the real close-prelude regression, and all six native message-cut settlement cases. The close assertion itself took 5.57 s. The local run used supported Node 26.10.0; slow collection completed without timeout overrides or retries.

The canonical SDK diff at the original head (digest 415a211f) is retained for the identical PR patch; it is not relabeled as a new-head render. A fresh semantic comparison of merged tree 3dfb414803aa83f1803f659ed7bec01b96858f5a against integrated main checked all 151 public entrypoints / 3,644 exports, including constructor/value and instance types. Both traversals exhausted 39,951 types / 49,515 nodes, with no unresolved types, cuts, or newly exposed operation/error union member. Existing exhaustive consumers need no additional cases.

Fresh P2 review completed. Its single rejected finding conflated registration of the native deletion callback with invoking it: withSqliteSessionDeletionWorkerParticipant only installs the callback (session-accessor.sqlite-deletion.ts:73), and the kernel's non-created outcomes return before commitSqliteSessionDeletion (session-accessor.sqlite-message-cut.ts:281–317). Pending participants settle as rolled back. No code was changed to suppress the finding, and no accepted/actionable findings remain.

The original preview case passed five local observations; passing replays were not treated as a fix. The main declaration reproduction additionally hit one unrelated local fixture timeout, recorded separately from the PR CI roots. A planned remote baseline comparison was superseded once both main fixes landed; no Testbox lease or remote test ran. Fresh CI and a completed ClawSweeper review of this new head remain required before merge.

@clawsweeper

clawsweeper Bot commented Oct 4, 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 gateway Gateway runtime scripts Repository scripts size: XL labels Oct 4, 2026
@steipete

steipete commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 4, 2026, 2:24 AM ET / 06:24 UTC (Revision 5).

ClawSweeper review

What this changes

Moves durable conversation rewind and branch-switch transactions into the existing agent database worker while preserving history, identity publication, and native-session cleanup.

Merge readiness

✅ Ready for maintainer review

This remains useful, distinct work that current main does not implement. The reviewed patch has no supported blocking correctness or security finding, and the supplied production-boundary evidence supports the execution cutover.

Priority: P2
Reviewed head: 9a3deb4fc1771c7871d55f052a49e7b344596ed7

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent executor cutover with strong scoped runtime evidence and no supported blocking defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied built-production Gateway run exercises rewind and branch switching with preserved history and zero moved-operation caller SQL; actual worker/storage fault cases cover final-grant revocation, compensation, lost replies, and shutdown settlement. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied built-production Gateway run exercises rewind and branch switching with preserved history and zero moved-operation caller SQL; actual worker/storage fault cases cover final-grant revocation, compensation, lost replies, and shutdown settlement. No stored-data contract changes require migration proof.
Evidence reviewed 8 items Pinned introduction and review continuity: Reviewed the introduced delta from dac9277 to 9a3deb4. Raw head records confirm the original implementation and integrated main as its two parents. The previous completed review contained no findings or published rank-up moves; the central worker modules are unchanged since that reviewed head. The supplied stale test merge was not used to infer removal of main behavior.
Current main still needs the cutover: At fetched main, history navigation still reads the source and runs the complete message-cut transaction through the caller-side exclusive SQLite writer. The new message-cut worker modules are absent. The merged deletion predecessor explicitly excluded rewind and branch transactions, so it does not supersede this PR. No shipped fixing PR for this cutover is established.
Authority and final transaction boundary: The host retains physical source identity, caller guards, and native custody through preparation. Existing worker admission invokes live assertions at transaction and commit grants. The kernel rereads lifecycle and model-lock predicates before mutation. The changed handler tests inject revocation at the final commit grant for both caller-authority forms and compare all stored transcript generations against the unchanged pre-mutation state.
Findings None None.
Security None None.

How this fits together

Gateway session requests select conversation history and authorize changes. The agent database executor applies those changes, then acknowledged receipts refresh session identity, branch summaries, and native subscriptions.

flowchart TD
  A[Rewind or branch request] --> B[Capture source and authority]
  B --> C[Prepare history and native custody]
  C --> D[Agent database worker]
  D --> E[Recheck authority and transact]
  E --> F[Acknowledged commit receipt]
  F --> G[Publish identity and refresh branches]
  G --> H[Settle native subscription cleanup]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +444, Tests +800, Docs +13, Other +1. Total +1258 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 12 602 158 +444
Tests 5 831 31 +800
Docs 1 16 3 +13
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 19 1450 192 +1258

Review metrics

Metric Value Why it matters
Production and test growth production net +444 lines; tests/support net +800 lines Production growth implements preparation, worker transfer, and reusable settlement while tests protect distinct authority, storage, and shutdown boundaries.
Measured SQL placement rewind 221 → 0; branch switch 260 → 0 caller statements The supplied real Gateway measurement directly demonstrates the intended worker placement without claiming an overall latency improvement.

Technical review

Best possible solution:

Use the existing executor and receipt owners for durable history navigation, preserving synchronous SDK hooks and the established transcript format.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a functional bug report; current-main source establishes caller-thread transaction execution, and the supplied before/after Gateway measurement demonstrates the placement change.

Is this the best way to solve the issue?

Yes. Reusing the existing executor, transcript kernel, and native settlement owner is a focused approach that preserves established storage and SDK contracts.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against f0af328d2475.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded runtime responsiveness and ownership improvement with no demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied built-production Gateway run exercises rewind and branch switching with preserved history and zero moved-operation caller SQL; actual worker/storage fault cases cover final-grant revocation, compensation, lost replies, and shutdown settlement. No stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied built-production Gateway run exercises rewind and branch switching with preserved history and zero moved-operation caller SQL; actual worker/storage fault cases cover final-grant revocation, compensation, lost replies, and shutdown settlement. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction and review continuity: Reviewed the introduced delta from dac9277 to 9a3deb4. Raw head records confirm the original implementation and integrated main as its two parents. The previous completed review contained no findings or published rank-up moves; the central worker modules are unchanged since that reviewed head. The supplied stale test merge was not used to infer removal of main behavior. (src/config/sessions/session-message-cut.ts:26, 9a3deb4fc177)
  • Current main still needs the cutover: At fetched main, history navigation still reads the source and runs the complete message-cut transaction through the caller-side exclusive SQLite writer. The new message-cut worker modules are absent. The merged deletion predecessor explicitly excluded rewind and branch transactions, so it does not supersede this PR. No shipped fixing PR for this cutover is established. (src/config/sessions/session-accessor.sqlite-message-cut.ts:122, f0af328d2475)
  • Authority and final transaction boundary: The host retains physical source identity, caller guards, and native custody through preparation. Existing worker admission invokes live assertions at transaction and commit grants. The kernel rereads lifecycle and model-lock predicates before mutation. The changed handler tests inject revocation at the final commit grant for both caller-authority forms and compare all stored transcript generations against the unchanged pre-mutation state. (src/gateway/server-methods/sessions-rewind.storage.test.ts:702, 9a3deb4fc177)
  • Native settlement and rejected finding: The worker participant installs a callback; it does not immediately delete a binding. Missing, conflicting, invalid-target, and already-active outcomes return before the kernel invokes deletion. The shared settlement owner preserves precommit veto, conditional exact-payload compensation, successor preservation, and unknown-outcome custody. The six added native cases exercise actual database workers, including termination and lost result delivery. (src/config/sessions/session-native-binding.message-cut.test.ts:137, 9a3deb4fc177)
  • Real Gateway proof and source identity: The captured body reports a built-production Gateway workload completing four turns, rewind, divergence, branch switch, history assertions, and clean shutdown. Moved-operation caller SQL fell from 221/260 statements to zero; these measurements establish placement, not a general latency improvement. Fresh merged-tree proof reports 27 passing boundary/import/native/shutdown tests. The omitted body tail was inspected through GitHub, and the complete body's SHA-256 matched the captured c52441d339b8c78ef653ccac1a6195d936926d68826235baac3b665636be3957 identity. These are supplied execution results, not tests run by this reviewer. (9a3deb4fc177)
  • Stored and SDK contracts: The existing graph-cloning, entry serialization, retained-history behavior, and model-lock error interface remain intact. Added worker messages and receipts are internal runtime transfer contracts; no schema or persisted representation changes were introduced. Opaque synchronous SDK callbacks, incognito, and fork paths retain their existing routes. The body records a semantic comparison of 151 public entrypoints and 3,644 exports with no newly exposed operation or error-union case. (src/config/sessions/session-message-cut.ts:114, 9a3deb4fc177)

Likely related people:

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

Rating scale

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

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

Workflow

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

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-04T04:07:55.315Z sha da930b8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-04T04:15:37.376Z sha da930b8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-04T04:23:29.630Z sha da930b8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-04T04:36:11.945Z sha da930b8 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 4, 2026
Integrate main dac9277, including the preview fixture publication-order fix and native duration formatter import fix. The compound2b patch remains unchanged relative to main.

Validation: 27 focused close, native settlement, build-graph, and import-boundary tests passed. All 3,644 public SDK exports retain the same reachable union surface against main. Fresh P2 review completed; the callback-registration/deletion claim was rejected by tracing the existing deletion owner.
@steipete

steipete commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 40a6c07 into main Oct 4, 2026
185 checks passed
@steipete
steipete deleted the dbasync/compound2b branch October 4, 2026 07:08
@steipete

steipete commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts 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.

1 participant