Skip to content

refactor(gateway): move worker transcript replay off the main thread - #163594

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

steipete merged 4 commits into
mainfrom
dbasync/ledger

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Worker transcript replay-ledger begin, terminal completion, and exact discard still ran SQLite on the Gateway main thread. This moves the eight ledger SQL sites into the existing shared-state worker broker.

User Impact

Internal execution change: ledger SQL leaves the Gateway thread while transcript replay, ordering, and live revocation retain their existing behavior. No schema, stored format, retention, durability, released SDK, or update contract changes. No operator action is required.

Why This Change Was Made

Typed placementTranscript.begin, .complete, and .discard operations use the existing placement mutation owner and registry. The committer awaits pending persistence before transcript effects and terminal persistence before replying. Captured inputs preserve the original environment, epoch, sequence, request hash, and store identity. Lost replies use acknowledged native receipts; unknown outcomes keep pending recovery. Only a fresh claim may be discarded after a known rollback, and database close joins accepted work.

The pre-existing short authority reads remain live at transaction and commit admission. The overbroad landing-only assertion against all host SQL was removed; the PR's regression still proves that ledger SQL runs off the caller thread. No authority check was weakened.

Released SDK audit against v2026.9.7: the changed ledger factory and methods are internal-only. Current and released src/plugin-sdk exports, src/plugins/runtime, and documented SDK subpaths do not expose them. No compatibility boundary or public type test is needed.

Evidence

  • Coordinator approval and clean independent Codex autoreview through P2 cover the production change at d3d7dcb05290d087ccdd2d37eb87f1323e757bab. Later authored changes are test fixtures and mechanical main integration; no production redesign was introduced.
  • All 100 focused ledger, lazy-loading, committer, RPC, claim-closure, and launcher-recovery tests passed on the first integrated source tree, 241.03s wrapper wall. They cover replay/sequence/hash/epoch checks, captured inputs, live revocation, lost replies, rollback cleanup, receipt ordering, and close settlement.
  • Full pnpm build passed at 5ce2d2d6573dfc79b52f777c0f1251a901b6421c in 18m39.09s, including runtime bundles, runtime/public SDK declarations, export checks, and Control UI production bundling. This completed the full-build request from that head's ClawSweeper review. It is prior-head evidence.
  • After integrating main d20ba7392c1de16a0eb9dab79336ade5ebf996a3, the scoped qaRuntime build passed in 14m30.76s. It covers the changed worker admission and registration inputs.
  • Core/test/script typechecks, all 27 core-test typecheck groups, type-aware fixture lint, formatting, three unused-export scans, and the planned storage/runtime/guard checks passed before the latest main integration. git diff --check passes on the resolved merge.
  • Environment-name comparison against integrated main d20ba7392c1de16a0eb9dab79336ade5ebf996a3: 477 → 477, no added or removed names. Main carries the owner-approved 477 budget; this PR does not change it. The standalone env-count gate passes 477/477 on the final merge commit. The earlier 478/476 failure is historical.
  • Current integrated proof: 123/123 tests passed across the six ledger/Gateway files and two worker fixture files, using node scripts/run-vitest.mjs <eight focused files> --maxWorkers=1. Test wrapper wall: 207.89s; Vitest shard durations: 136.07s + 55.27s = 191.34s. Provider blacksmith-testbox, lease tbx_01m3yx0mjxfbpq45sc1ez2drb4, run 37045755991. The receiver verified staged tree bae33c2bc2135f253aab2725f26aed34312efd08 plus key ledger/runtime/fixture/native-registration blob hashes. Provider result: exit 0, lease stopped and independently confirmed completed. The local wrapper was subsequently killed with signal 9 during local capsule cleanup (exit 137); all its children are gone. This does not change the completed remote test result, and no test rerun was performed. Exact-head PR CI remains a separate landing gate.

The suites use real agent/shared-state workers for their integration contracts. No test timeout or assertion was weakened. The existing lazy-loading suite resets module generations to exercise admission before runtime loading.

CI fixture repair and main integration

Final merge-resolution commit: efdd370171149b9fc4faed3f1b480d8972c8b320; its tree exactly matches the 123-test remote proof. This is a merge commit with main, not a rebase.

CI run 37025678680 tested head 5ce2d2d6573dfc79b52f777c0f1251a901b6421c and failed in the chat-abort and fault-injection fixtures. The in-process worker changes OPENCLAW_STATE_DIR after the Gateway creates its agent owner; an unbound transcript target then selects the worker namespace and correctly fails ownership admission. The same error reproduced on exact CI main parent b1c09f1088e0fba7b91c661d3b20b945c96ab141. The full ordered fault suite on that baseline produced 10 failures and 5 passes, so that evidence was not used to waive all 15 CI failures.

Main independently fixed the storage binding in #163637 (d20ba7392c1de16a0eb9dab79336ade5ebf996a3). This merge takes main's gatewayStorageEnvironment implementation and removes the duplicate fixture fix from 5ab3c24ce009a2fbe7aa1ea0c8f3931c1475f72b. The remaining fixture delta is the ledger import and removal of an artificial two-second RPC deadline, retaining the existing production 30-second deadline. Diagnostics observed unintended timeouts at 2000.8, 2002.0, and 2001.9 ms in addition to the deliberately injected socket close. Exact replay counts, immutable payloads, single provider invocation, and durable transcript uniqueness remain asserted.

Before this final main merge, all 15 fault-injection cases and 7 chat-abort cases passed together. One first-use chat startup exceeded its unchanged 10-second budget under concurrent typechecking before any ledger request; the same case passed unchanged after typechecking settled, and all 8 chat cases had passed in the earlier binding-fix run. This is evidence of startup timing sensitivity, not a claimed repair of it. No inherited-failure admin exception has been used.

Authority-read follow-up debt

The eight observed SQL events below remain follow-up debt. The recorder logs both prepare and execution, so the two ownership observations at each grant are one query, not two independent reads: eight observations represent six executions.

Grant Observation Source Owner
Transaction PRAGMA data_version execution src/infra/sqlite-schema-facts.ts:296 Native SQLite schema/cache freshness
Transaction Ownership row SELECT preparation src/state/openclaw-state-ownership.ts:126 Shared-state external supervision/ownership
Transaction Ownership row SELECT execution, state_key = ? LIMIT 1 src/state/openclaw-state-ownership.ts:126 Shared-state external supervision/ownership
Transaction Placement SELECT execution, session_id = ? src/gateway/worker-environments/placement-row-codec.ts:122 via placement-turn-claims.ts:463 Live placement/turn-claim authority
Commit PRAGMA data_version execution src/infra/sqlite-schema-facts.ts:296 Native SQLite schema/cache freshness
Commit Ownership row SELECT preparation src/state/openclaw-state-ownership.ts:126 Shared-state external supervision/ownership
Commit Ownership row SELECT execution, state_key = ? LIMIT 1 src/state/openclaw-state-ownership.ts:126 Shared-state external supervision/ownership
Commit Placement SELECT execution, session_id = ? src/gateway/worker-environments/placement-row-codec.ts:122 via placement-turn-claims.ts:463 Live placement/turn-claim authority

These calls use the existing warm native handle (placement-store.ts:105, openclaw-state-db.ts:274). config_machine_state.state_key and worker_session_placements.session_id are primary keys; both SELECTs are indexed point lookups, and the pragma is constant-size. The ownership reader calls inspectOpenClawStateOwnershipFromDatabase directly with admitted schema facts, not the path-based/read-only inspection helpers. None of the eight observations enters maintenance-scoped current/read-only state admission, creates a snapshot subprocess, scans a table, or waits for writer admission. Existing lifecycle/maintenance and external-ownership revocation checks remain intentional live authority gates. WAL allows these reads while the worker holds its write transaction.

Separately retained source-authority debt: worker-turn-transcript-target.ts:28 checks the bound session through its existing session owner; placement-turn-claim-events.ts:211 rechecks the live run/claim/operator capability. These are not additional ledger SQL sites.

Route ledger begin, terminal completion, and exact discard through the existing shared-state broker and placement mutation owner. Preserve live grants, native receipt settlement, ordered replay, and fresh-claim rollback cleanup. Await pending and terminal persistence around the existing transcript application.

Also repair the inherited async session-manager fixture in worker claim recovery. Validation covers 100 focused tests, zero caller-thread ledger SQL, Gateway runtime build, type/lint guards, zero cycles, and P2 review. The inherited env-name budget remains unchanged.
@clawsweeper

clawsweeper Bot commented Oct 2, 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: L labels Oct 2, 2026
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 2:30 PM ET / 18:30 UTC (Revision 5).

ClawSweeper review

What this changes

Moves worker transcript replay bookkeeping into the existing SQLite worker broker and updates callers and recovery fixtures to await persistence.

Merge readiness

✅ Ready for maintainer review

The central refactor remains necessary, and no actionable introduced defect was found. The resolved head addresses the previous conflict blocker while preserving live authority checks and durable receipt ordering.

Priority: P2
Reviewed head: efdd370171149b9fc4faed3f1b480d8972c8b320

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, coherent worker cutover with meaningful production-boundary recovery coverage and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (linked_artifact): The reported exact-tree run exercises the production ledger through real SQLite workers, injected broker reply loss, durable recovery, and service-level revoked/replaced claims with no transcript or acknowledgment effects. Source inspection confirms those boundaries; raw remote logs were inaccessible to this reviewer. Stored row formats and predicates are unchanged.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The reported exact-tree run exercises the production ledger through real SQLite workers, injected broker reply loss, durable recovery, and service-level revoked/replaced claims with no transcript or acknowledgment effects. Source inspection confirms those boundaries; raw remote logs were inaccessible to this reviewer. Stored row formats and predicates are unchanged.
Evidence reviewed 8 items Pinned introduction and resolved composition: Reviewed the introduced delta from d20ba73 to efdd370. The raw head records the previous reviewed head and integrated main as parents; its tree is bae33c2bc2135f253aab2725f26aed34312efd08, matching the tree identified in the supplied proof. The stale GitHub test merge was not used as merge-result evidence.
Existing worker owner and captured inputs: The ledger captures the physical database context and clones submitted commands before yielding, then uses the existing placement mutation owner for begin, completion, and exact discard.
Authority and receipt ordering: The worker kernel requests transaction and immediate commit admission and records a native commit receipt. The runtime awaits begin before transcript effects and completion before returning; the RPC owner separately revalidates live authority before acknowledgment. Revoked and replaced claims are exercised through the real service and transcript owners, asserting no persisted transcript, publication, or acknowledgment.
Findings None None.
Security None None.

How this fits together

Workers submit ordered transcript batches to the Gateway. Its replay ledger prevents duplicate application and records durable outcomes before acknowledgments return to workers.

flowchart TD
 A[Worker transcript batch] --> B[Gateway session queue]
 B --> C[Live authority checks]
 C --> D[Shared state worker ledger]
 D --> E[Agent transcript writer]
 E --> F[Durable terminal receipt]
 F --> G[Worker acknowledgment]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +167, Tests +301, Docs +13, Other 0. Total +481 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 7 260 93 +167
Tests 10 401 100 +301
Docs 1 13 0 +13
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 19 675 194 +481

Review metrics

Metric Value Why it matters
Net code growth Production +167 lines; tests, test support, and routing +301 lines Production growth supplies the typed worker adapter and receipt contract; added coverage targets ordering, revocation, reply loss, and close settlement.

Technical review

Best possible solution:

Keep one worker-backed replay ledger with captured store identity, live commit admission, and durable receipts governing transcript application and acknowledgment.

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

Not applicable to a new product bug: current main and the latest release visibly execute replay-ledger SQL synchronously, establishing the refactor's starting condition.

Is this the best way to solve the issue?

Yes. Reusing the existing shared-state broker and placement mutation owner preserves a single persistence authority and avoids a competing writer or new storage contract.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The reported exact-tree run exercises the production ledger through real SQLite workers, injected broker reply loss, durable recovery, and service-level revoked/replaced claims with no transcript or acknowledgment effects. Source inspection confirms those boundaries; raw remote logs were inaccessible to this reviewer. Stored row formats and predicates are unchanged.

Label justifications:

  • P2: This is a bounded internal runtime improvement without a demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The reported exact-tree run exercises the production ledger through real SQLite workers, injected broker reply loss, durable recovery, and service-level revoked/replaced claims with no transcript or acknowledgment effects. Source inspection confirms those boundaries; raw remote logs were inaccessible to this reviewer. Stored row formats and predicates are unchanged.
  • proof: sufficient: Contributor real behavior proof is sufficient. The reported exact-tree run exercises the production ledger through real SQLite workers, injected broker reply loss, durable recovery, and service-level revoked/replaced claims with no transcript or acknowledgment effects. Source inspection confirms those boundaries; raw remote logs were inaccessible to this reviewer. Stored row formats and predicates are unchanged.

Evidence

What I checked:

  • Pinned introduction and resolved composition: Reviewed the introduced delta from d20ba73 to efdd370. The raw head records the previous reviewed head and integrated main as parents; its tree is bae33c2bc2135f253aab2725f26aed34312efd08, matching the tree identified in the supplied proof. The stale GitHub test merge was not used as merge-result evidence. (efdd37017114)
  • Existing worker owner and captured inputs: The ledger captures the physical database context and clones submitted commands before yielding, then uses the existing placement mutation owner for begin, completion, and exact discard. (src/gateway/worker-environments/transcript-commit-ledger.ts:20, efdd37017114)
  • Authority and receipt ordering: The worker kernel requests transaction and immediate commit admission and records a native commit receipt. The runtime awaits begin before transcript effects and completion before returning; the RPC owner separately revalidates live authority before acknowledgment. Revoked and replaced claims are exercised through the real service and transcript owners, asserting no persisted transcript, publication, or acknowledgment. (src/gateway/worker-environments/transcript-commit-store.worker.ts:182, efdd37017114)
  • Stored contract preserved: Read the original ledger and replacement kernel. Existing table names, row fields, sequence/hash/environment predicates, pending recovery, terminal JSON interpretation, and exact discard predicates are preserved. No schema, migration, retention, configuration, or released plugin API change was introduced. (src/gateway/worker-environments/transcript-commit-store.worker.ts:192, efdd37017114)
  • Still necessary on main and latest release: Fetched main 0bf122d still implements ledger operations with synchronous runOpenClawStateWriteTransaction. The latest release v2026.9.7 contains the same synchronous factory. Neither establishes the requested worker cutover. (src/gateway/worker-environments/transcript-commit-store.ts:232, c074824a27c9)
  • Production-boundary recovery proof: The supplied body reports 123/123 passing tests on the exact resolved tree, with 207.89 seconds wrapper wall time and 191.34 seconds summed Vitest durations. Inspected scenarios use real shared-state workers, corrupt actual broker replies, verify durable recovery, and join accepted work during close. The enclosing Testbox workflow https://github.com/openclaw/openclaw/actions/runs/37045755991 is cancelled, so its workflow conclusion is not a passing test verdict. Raw-log inspection was blocked by the network allowlist; this reviewer limitation does not negate the separately reported completed provider result. (src/gateway/worker-environments/transcript-commit-store.test.ts:253, efdd37017114)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: 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-02T15:07:48.201Z sha d3d7dcb :: needs changes before merge. :: none
  • reviewed 2026-10-02T15:22:11.443Z sha 5ce2d2d :: needs changes before merge. :: none
  • reviewed 2026-10-02T15:41:06.741Z sha 5ce2d2d :: needs changes before merge. :: none
  • reviewed 2026-10-02T16:56:10.175Z sha 5ab3c24 :: blocked before merge. :: none

Preserve both launcher fixture fixes: await session-manager opening and asynchronous transcript append. The integrated candidate passed all 100 focused tests. Production conflict resolution is mechanical; reuse the approved P2 review.
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 2, 2026
Capture the Gateway transcript storage environment before the in-process worker changes process.env. Keep the production RPC deadline so cold worker admission does not inject extra timeout faults into exact replay-count tests. Production code, test deadlines, and assertions are unchanged.
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Keep main’s Gateway storage-environment binding in the shared worker fixture. Retain the ledger worker import and the production RPC deadline. Verified the resolved tree with 123 focused tests on Blacksmith Testbox.
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 2, 2026
@steipete
steipete merged commit 5e69827 into main Oct 2, 2026
142 of 144 checks passed
@steipete
steipete deleted the dbasync/ledger branch October 2, 2026 20:27
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 3, 2026
…penclaw#163594)

* refactor(gateway): move transcript replay ledger off thread

Route ledger begin, terminal completion, and exact discard through the existing shared-state broker and placement mutation owner. Preserve live grants, native receipt settlement, ordered replay, and fresh-claim rollback cleanup. Await pending and terminal persistence around the existing transcript application.

Also repair the inherited async session-manager fixture in worker claim recovery. Validation covers 100 focused tests, zero caller-thread ledger SQL, Gateway runtime build, type/lint guards, zero cycles, and P2 review. The inherited env-name budget remains unchanged.

* test(worker): retain harness storage identity across worker startup

Capture the Gateway transcript storage environment before the in-process worker changes process.env. Keep the production RPC deadline so cold worker admission does not inject extra timeout faults into exact replay-count tests. Production code, test deadlines, and assertions are unchanged.
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: L 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