Repository navigation
Conversation
…napshots The cursor fence and the encrypted to-device fence both await a strict crypto snapshot on behalf of a caller that the transport or the sync store has already admitted. If the generation is stopped while that caller is still parked (recovery-key persistence drain, in-flight cursor write), the snapshot was written before the caller got rejected. Check the generation before the snapshot, pass its abort signal into the dump, and check again afterwards. Move the request matcher into its own module and cover both fences at unit level.
…ehind fence snapshots The sync store called its crypto durability fence through an optional call. Once the stop path had detached the fence, a cursor that consumed to-device events was written without any crypto snapshot. The store now remembers that a fence was registered and refuses such a cursor while the fence is detached. A store that never had a fence belongs to a client without crypto state and keeps writing its cursor unconditionally. The stop path keeps the generation fence registered until it is done, so a stray cursor write is rejected instead of skipped. A clean stop hands the store its final strict snapshot as the fence for the last cursor write; a stop without persist leaves the store detached. A fence snapshot receives the generation abort signal, so a generation that stops while the snapshot waits for the lock or dumps publishes nothing. A snapshot that is already publishing finishes its write; the stop path now waits for it, so no snapshot of a retired generation lands after its stop has settled. The fence moves into its own module.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR saves Matrix crypto state before persisting affected sync cursors and dispatching encrypted to-device messages. Example: The Gateway receives a room key, replies, and is killed with SIGKILL four seconds later.
Review scores
ProductKind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 3 items remain Keep open: this PR addresses a concrete Matrix crash-persistence defect still present on main, but its storage-failure policy needs an owner decision. Priority: P1 Decision needed
Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe Matrix plugin connects SDK crypto processing and sync responses to account-scoped SQLite snapshots, durable cursors, and homeserver HTTP dispatch. flowchart TD
A[Homeserver sync response] --> B[SDK crypto processing]
B --> C[Sync cursor owner]
C --> D[Crypto durability fence]
E[Encrypted to-device request] --> D
D --> F[Account SQLite snapshot]
F --> G[Cursor write or HTTP dispatch]
Technical reviewBest possible solution: Keep both durability boundaries in the existing Matrix owners with an accepted storage-failure recovery policy. Do we have a high-confidence way to reproduce the issue? Independent cursor and crypto persistence schedules expose the reported crash window, supported by controlled stable-release and main reports; this review executed no target code. Is this the best way to solve the issue? The two fences address the actual inbound and outbound durability boundaries, and the pinned SDK ordering supports the design. Full review comments:
Overall correctness: patch is correct AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 50792af5c154. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +128, Tests +480. Total +608 across 7 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (3 earlier review cycles)
Reviewed October 12, 2026, 12:45 AM ET / 04:45 UTC (Revision 4). |
|
Looking forward to this fix! OpenClaw regularly crashes (out of memory) and Matirx plugin doesn't come back. This used to work some weeks/months ago. It's a pain to see in which state the Matrix plugin is currently in. |
Related: #165636, #158784. See also #147450 / #147457 (same idea for
keys/upload, independent of this change).What Problem This Solves
Fixes: a Matrix bot in encrypted rooms can no longer decrypt incoming messages, and peers can no longer decrypt its replies, after the gateway process is killed hard between two crypto snapshots.
The Matrix crypto store is snapshotted once after init, every 60 s, and on clean stop. A hard exit in between restores state that is older than what the homeserver and the peers have seen:
User Impact
User impact: a Matrix bot in encrypted rooms keeps reading and answering after a hard exit of the gateway (crash, OOM kill,
SIGKILL, power loss), instead of staying unable to decrypt, or unable to be decrypted, until the device is reset. No configuration change, no migration and no action required. Cost: one additional crypto snapshot per sync response that carried to-device events and per encrypted to-device send (measured below). Behaviour change to be aware of: if that snapshot cannot be written, the sync cursor is held back and the encrypted to-device send is rejected (fail closed), see Risk and open questions.Why This Change Was Made
Four commits on main
bc1d2b9b.client/file-sync-store.ts). When a sync response contained to-device events, the next cursor write first awaits a strict crypto snapshot (setCryptoDurabilityFence). The cursor payload is captured before the snapshot, so the snapshot is at least as new as the cursor. If the snapshot fails, the cursor write fails and is retried with the fence still pending.sdk/client-base.ts,sdk/encrypted-to-device.ts). A strict crypto snapshot in the existing guarded-fetchbeforeRequesthook beforePUT .../sendToDevice/m.room.encrypted/...is dispatched. Other requests are untouched.sdk/crypto-durability-fence.ts). Both fences go through one helper that checks the client generation before the snapshot and again afterwards, and passes the generation's abort signal into the dump. A generation that is stopped before the snapshot starts, or while it waits for the snapshot lock or dumps, publishes nothing and its caller is rejected.The periodic timer is unchanged. No stored format changes, no migration, nothing is reset or deleted.
Evidence
Unit tests, final commit.
sdk.test.tsandclient/file-sync-store.test.tsthrough the repository runner (scripts/test-projects.mts, one worker): 2 files, 125 of 125 tests passed. The whole extension (scripts/test-projects.mts extensions/matrix): 159 files, 1678 of 1678 tests passed in 5 shards. 15 tests are new:PUTtriggers a snapshot, no dispatch when the snapshot fails;Mutation checks, final commit. Each protection was removed once and both files re-run; the tests written for it failed and all other tests passed: cursor fence (5 failed of 125), to-device fence (4), generation pre-check (2), final-snapshot hand-over on clean stop (1), the "never registered" distinction (2). The fail-closed check, the wait for in-flight snapshots on stop and the abort signal into the dump were removed together in one run (4 failed, one or two per protection, no overlap).
Static checks. Typecheck (
tsgo) of the Matrix extension passed on the final commit for production sources (227 files of the extension in the program, the four changed production files among them) and for test sources, using the repository's extension and test compiler settings narrowed toextensions/matrix(all 159 test files of the extension were in the test program).oxfmt --checkandoxlintpass on the seven changed files.Real-homeserver lab (local tuwunel 1.9.3, OpenClaw 2026.10.1 in an isolated state dir, scripted matrix-js-sdk peer, fresh bot account and empty crypto store per run,
SIGKILLas the crash). Two generations of the fix were measured and are kept apart here.First lab version (fences 1 and 2 only). The logic of commits 1 and 2 was edited by hand into the built 2026.10.1 plugin. These runs do not exercise commits 3 and 4:
Fence 1 alone fixes the first row's inbound half only (bot decrypts, its answer is undecryptable for the peer, 3/3), which is why both fences are in one change.
This change (all four commits). The production hunks of this branch were applied at source level to the 2026.10.1 tag (they apply without conflicts; the two new modules are byte-identical to the branch) and the plugin was built with the repository's plugin runtime build. An unmodified rebuild of the tag reproduced all 90 files of the published plugin's
distbyte for byte, so the only difference to the published plugin is this change plus two lab-only log lines that time the fence snapshots. The branch itself could not be loaded by the 2026.10.1 host (it imports oneopenclaw/plugin-sdksubpath that 2026.10.1 does not export), so main's own code base was not run against a homeserver.SIGKILL3.8-4.1 s after the first messageSIGKILLafter a snapshot tick plus a second roomSIGTERM) instead of the killSIGKILLSIGKILLAcross the 20 gateway boots with this change the bot log shows no decryption error after a restart, and the "fence is detached" refusal never fired.
Measured cost, this change, same lab runs. Cursor fence: 29-224 ms, median 104 ms (20 snapshots). To-device fence: 27-119 ms, median 50 ms (23 snapshots). The serialized snapshot was about 49 KB.
CI on the current head (
276e8332, merge of maine5bf0728). The red Matrix tests inchecks-node-changed-extensions-bundle-1are not caused by this change; they fail identically on main without it. Same test selection as the CI shard (vitest projectextension-database-workers), run locally:doctor-contract-api.test.ts"remaining TTL" +file-sync-store.test.ts"rejects a bad digest" (bulk, legacy)idb-persistence.test.ts"beyond chunk 9"e5bf0728without this changee5bf0728merged with this branchsdk.test.tsamong them)841272e2(#168999)5ed6a305(parent of #168999)All four failing tests are existing tests that this PR does not modify; they write to SQLite directly behind the plugin-state store and then expect
lookupto see the change. Since #168999,lookup/lookupManycan be answered from the in-process observation cache (src/plugin-state/plugin-state-worker-client.ts), which returns the value from before the raw write. That mechanism was traced for the three tests of the first column; for theidb-persistencetest only the identical before/after result was established. The fourth test does not show up in the CI log because the job stops after the first failing group. Local runs used Node 24.21 (CI: 24.19).The two red
QA Smoke CIprofiles fail insubagent-completion-direct-fallback/subagent-empty-completion-recoverywith a "config restart readiness" timeout; the same scenarios fail with the same message on unrelated PRs (#169089, #163765, #168767).Risk and open questions
resolveOpenSharedMatrixClientStateinsrc/matrix/client/shared.tsawaits the predecessor's retirement before it creates a successor for the same auth. A successor built outside that path (direct, unshared construction) that reuses the in-process IndexedDB without restoring from disk was not tested.pnpm check,tsgo:extensions,tsgo:extensions:test, thelint:extensionswrapper), tests outsideextensions/matrix, Synapse, federation, verified devices, key backup.written by an AI agent (kumo) on behalf of @nissl24