Skip to content

fix(matrix): encrypted rooms stay undecryptable after a hard gateway exit - #169116

Open
bitfroest wants to merge 5 commits into
openclaw:mainfrom
bitfroest:fix/matrix-crypto-durability-fences
Open

bitfroest wants to merge 5 commits into
openclaw:mainfrom
bitfroest:fix/matrix-crypto-durability-fences

Conversation

@bitfroest

@bitfroest bitfroest commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

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.

  1. Cursor fence (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.
  2. To-device fence (sdk/client-base.ts, sdk/encrypted-to-device.ts). A strict crypto snapshot in the existing guarded-fetch beforeRequest hook before PUT .../sendToDevice/m.room.encrypted/... is dispatched. Other requests are untouched.
  3. Generation check (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.
  4. Fail closed, and ordered retirement.
    • The store remembers that a fence was registered. With the fence detached, a cursor that consumed to-device events is refused instead of written without a snapshot. A store that never had a fence (client without encryption, or crypto init failed) writes its cursor unconditionally, as before.
    • The stop path no longer detaches the fence up front. A clean stop takes its final strict snapshot as before and hands exactly that snapshot to the store as the fence for the last cursor write, so a cursor still pending at shutdown is written after it and without a second dump. A stop without persist, and a clean stop that fails, leave the store detached: they must not advance the cursor past crypto state they did not persist.
    • A fence snapshot that is already publishing when the generation stops finishes its write (publication is not interruptible by design). The stop path now waits for in-flight fence snapshots before it settles, so no snapshot of a retired generation lands after its stop.

The periodic timer is unchanged. No stored format changes, no migration, nothing is reset or deleted.

Evidence

Unit tests, final commit. sdk.test.ts and client/file-sync-store.test.ts through 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:

  • cursor fence: ordering, cursor held back on snapshot failure, no fence ever registered, fence detached (refused, then written after re-attach), cursor without to-device events while detached;
  • to-device fence: only the encrypted PUT triggers a snapshot, no dispatch when the snapshot fails;
  • generation: request on an already stopped generation, generation stopped while the request is parked in the hook, generation stopped during the dump (nothing published), generation stopped during publication (write completes, stop settles only afterwards, request rejected), cursor write after the generation stopped;
  • stop paths: pending to-device cursor on a clean stop (one final snapshot, taken before the cursor), refused after a stop without persist, client without encryption is not held back.

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 to extensions/matrix (all 159 test files of the extension were in the test program). oxfmt --check and oxlint pass 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, SIGKILL as 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:

Scenario Unmodified Fences 1 and 2
A: kill 3-7 s after the first decrypted message, then next message in the same Megolm session bot cannot decrypt, 3/3 bot decrypts and answers, peer decrypts the answer, 3/3
D: kill after a snapshot tick plus one more key exchange over the existing Olm session; then same session and two fresh rooms bot answers nothing, 3/3 all answered and decryptable on both sides, 3/3

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 dist byte 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 one openclaw/plugin-sdk subpath that 2026.10.1 does not export), so main's own code base was not run against a homeserver.

Run Result
A, SIGKILL 3.8-4.1 s after the first message bot decrypts the next message in the same Megolm session and answers, peer decrypts the answer, 3/3
D, SIGKILL after a snapshot tick plus a second room same-session message and two fresh rooms answered, every reply decryptable at the peer, 3/3
Control: A with a clean stop (SIGTERM) instead of the kill 1/1: exit code 0 after 1.7 s, final snapshot and clean-shutdown cursor written, next message decrypted and answered after restart
Control: two encrypted rooms, then a clean stop (D without waiting for the tick) 1/1: exit code 0 after 1.7 s, same-session message and two fresh rooms answered and decryptable
Control: encryption disabled in the channel config, unencrypted room, SIGKILL 1/1: answered before and after the kill, sync cursor persisted with no fence call, clean stop exit code 0
Control: encryption enabled, unencrypted room, SIGKILL 1/1: answered before and after the kill
Counter-run, unmodified 2026.10.1, scenario D, same day 1/1: no answer in the old session or in two fresh rooms, 45 decryption errors in the bot log

Across 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 main e5bf0728). The red Matrix tests in checks-node-changed-extensions-bundle-1 are not caused by this change; they fail identically on main without it. Same test selection as the CI shard (vitest project extension-database-workers), run locally:

Tree 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"
main e5bf0728 without this change 3 tests fail, full shard 3/3 runs, the two files alone 2/2 runs fails, 1/1
main e5bf0728 merged with this branch the same 3 tests fail, full shard 3/3 runs, the two files alone 1/1 fails, 1/1 (all other 166 tests of that group pass, sdk.test.ts among them)
main at 841272e2 (#168999) the same 3 tests fail, 1/1 not run
main at 5ed6a305 (parent of #168999) 25 of 25 pass, 1/1 not run

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 lookup to see the change. Since #168999, lookup/lookupMany can 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 the idb-persistence test 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 CI profiles fail in subagent-completion-direct-fallback / subagent-empty-completion-recovery with a "config restart readiness" timeout; the same scenarios fail with the same message on unrelated PRs (#169089, #163765, #168767).

Risk and open questions

  • Cost: every fence is a full snapshot dump. Measured 27-224 ms on a fresh store (snapshot about 49 KB) in the lab, see above; not measured on large, long-lived stores.
  • Fail-closed behaviour: if the snapshot cannot be written, the cursor is held back and encrypted to-device sends are rejected. That is the same policy question as in fix(matrix): persist private crypto state before key uploads #147457 and needs an owner decision.
  • Retired generation, remaining window: a snapshot whose publication has started when the generation stops still completes. It is serialized with a successor's restore by the snapshot file lock and the stop waits for it, but the commit itself carries no generation identity. In the shared-client path this window is closed by the existing lifecycle: resolveOpenSharedMatrixClientState in src/matrix/client/shared.ts awaits 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.
  • Clean stop and the fence: the final cursor write relies on sync and crypto being stopped before the final snapshot, which is the existing stop order. A change to that order would need the hand-over revisited.
  • Not covered: keys imported from backup or forwarded keys, state changes with no to-device traffic in either direction.
  • Not tested: main's own code base against a real homeserver (the lab ran this change on the 2026.10.1 tag), a persistently failing snapshot and a detached fence on a real homeserver (unit tests only), more than one run per control, the repository-wide check lanes (pnpm check, tsgo:extensions, tsgo:extensions:test, the lint:extensions wrapper), tests outside extensions/matrix, Synapse, federation, verified devices, key backup.

written by an AI agent (kumo) on behalf of @nissl24

…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.
@clawsweeper

clawsweeper Bot commented Oct 11, 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 channel: matrix Channel integration: matrix size: L labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

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

  • Before: Restart can restore stale crypto state, leaving subsequent messages or replies undecryptable.
  • After: The proposed fences persist the corresponding crypto state before advancing the durable cursor or sending encrypted to-device messages.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The production design is coherent and has useful persistence coverage, but supplied runtime evidence is insufficient and product acceptance remains outstanding.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Encrypted Matrix conversations can remain unreadable after a hard Gateway exit despite retaining the same device identity.
Reason: Preventing recurrence has clear value, but strict snapshot persistence changes the existing storage-failure policy.

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
Reviewed head: 276e8332beaee5e3dd6c5dd5c3372e2bbc44538f
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should Matrix hold affected sync cursors and reject encrypted to-device sends whenever its crypto snapshot cannot be saved?
  • Recommendation: Accept strict durability with actionable recovery: Preserve the fences and require a clear storage-failure diagnosis and retry path that retains device identity.
  • Why: This changes runtime persistence from best effort to a prerequisite for encrypted to-device dispatch, and no owner acceptance appears in this PR or the related upload-fence discussion.

Before merge

  • Add real behavior proof - The tuwunel lab reports useful crash controls after porting the production hunks onto v2026.10.1, but supplies result tables without runtime traces and excludes the reviewed main-based Gateway; attach logs or terminal evidence for the changed crash and storage-failure paths, redacting keys, IPs, phone numbers, and non-public endpoints. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Replace lifecycle polling with explicit completion gates (P3) - The retirement test polls stopClient and then waits ten event-loop turns before asserting that shutdown remains pending. That fixed delay does not establish that shutdown reached fence settlement, so the negative assertion can pass prematurely; polling also violates the repository's explicit test policy. Use fixture admission/completion gates here and for the dump-entry wait. This previously reported concern remains unchanged; its late discovery was acknowledged in the earlier review.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P3] Replace lifecycle polling with explicit completion gates — extensions/matrix/src/matrix/sdk.test.ts:1004-1009

Tests

  • Missing end-to-end proof: Provide redacted runtime traces from the reviewed main-based Gateway showing persisted-cursor crash continuity, peer decryption of replies, storage-failure recovery, and continuity of an existing v2026.10.1 device.
Agent review details

How this fits together

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

Technical review

Best 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:

  • [P3] Replace lifecycle polling with explicit completion gates — extensions/matrix/src/matrix/sdk.test.ts:1004-1009
    The retirement test polls stopClient and then waits ten event-loop turns before asserting that shutdown remains pending. That fixed delay does not establish that shutdown reached fence settlement, so the negative assertion can pass prematurely; polling also violates the repository's explicit test policy. Use fixture admission/completion gates here and for the dump-entry wait. This previously reported concern remains unchanged; its late discovery was acknowledged in the earlier review.
    Confidence: 0.93
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is correct
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Sync cursor persistence changes intended behavior with a stated reason (3a2dbb6: Move sync-cache operations into workers while preserving restart replay, clean-shutdown markers, and failure reporting.)
  • Final crypto snapshot and clean cursor ordering keeps the original intent (c3267e7: Serialize recovery persistence and settle accepted work during shutdown without changing stored keys or migration behavior.)
  • Shared-generation retirement keeps the original intent (d7c5771: Keep replacement admission behind completion of startup, monitor work, persistence, and SDK discard.)
  • Guarded HTTP dispatch keeps the original intent (9a5af1b: Preserve live request authority through Matrix reads and crypto-owned work.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +128, Tests +480. Total +608 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 129 1 +128
Tests 3 481 1 +480
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 610 2 +608

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +129/-1 lines; tests and test support +481/-1 lines Most growth covers distinct cursor-ordering, persistence-failure, and generation-retirement contracts.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: A hard Gateway exit can leave existing encrypted Matrix conversations unable to receive messages or produce decryptable replies.
  • merge-risk: 🚨 compatibility: Encrypted setups with snapshot-storage failures would reject to-device sends that previously proceeded under best-effort persistence.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

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

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-11T13:14:48.266Z sha e24ef09 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T13:25:45.975Z sha 276e833 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T14:32:51.024Z sha 276e833 :: needs real behavior proof before merge. :: [P3] Replace lifecycle polling with explicit completion gates

Reviewed October 12, 2026, 12:45 AM ET / 04:45 UTC (Revision 4).

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Oct 11, 2026
@sibbl

sibbl commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

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.

This branch has not been deployed

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

Labels

channel: matrix Channel integration: matrix merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants