Skip to content

fix(matrix): bind E2EE readiness to client generations - #120168

Closed
vincentkoc wants to merge 2 commits into
mainfrom
fix/matrix-e2ee-generation-lifecycle-20260807
Closed

vincentkoc wants to merge 2 commits into
mainfrom
fix/matrix-e2ee-generation-lifecycle-20260807

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Related: #119920

What Problem This Solves

Fixes four Matrix E2EE lifecycle races in the split from #119920:

  • readiness probes could outlive terminal sync/generation changes, lose a wake, or hang past timeout;
  • Rust crypto could finish initializing after terminal stop and leave its newly assigned backend running;
  • QA image timeout cancellation did not reach matrix-js-sdk's active upload;
  • shutdown could return at its deadline while IndexedDB persistence later committed a snapshot.

This remains limited to Matrix generation/readiness, upload cancellation, persistence shutdown, and the QA E2EE lifecycle that owns those operations. It does not add scenario configuration, room setup, CLI/gateway, Docker, recording, release, or live evidence changes.

Why This Change Was Made

The canonical owners now enforce the lifecycle:

  • extensions/matrix/src/matrix/sdk/client-base.ts:381-432 races each async readiness probe against sync/error/abort changes and rechecks captured generation ownership before accepting success.
  • extensions/matrix/src/matrix/sdk/client-base.ts:680-718 re-stops matrix-js-sdk if delayed Rust crypto initialization settles after the OpenClaw generation stopped.
  • extensions/matrix/src/matrix/sdk/client-core.ts:445-457 passes the QA operation's AbortController into matrix-js-sdk's upload contract; extensions/qa-lab/src/live-transports/matrix/substrate/e2ee-client.ts:491-522 keeps readiness, encryption, upload, and dispatch in one tracked operation. Cancellation can abort an active upload; once message dispatch starts, its send promise remains authoritative and timeout reports unknown completion rather than a false aborted-send result.
  • extensions/matrix/src/matrix/sdk/client-base.ts:577-612 propagates one absolute shutdown deadline and abort signal to persistence; extensions/matrix/src/matrix/sdk/idb-persistence.ts:305-344 checks cancellation again immediately before the snapshot write, preventing a late commit after shutdown returns.

The repair also removes duplicate lifecycle policy: failed shared generations are deleted at the startup producer, QA uses the plugin SDK timeout primitive, and one generation-aware readiness loop owns both startup and encrypted-room readiness.

Direct Dependency Evidence

Personally inspected installed matrix-js-sdk 41.9.0 source and declarations:

  • matrix-js-sdk/src/sync.ts:80-97,821-855,887-929: ERROR may recover, cached PREPARED is marked fromCache, live sync emits readiness after processing, and sync persistence occurs before/after those transitions.
  • matrix-js-sdk/src/client.ts:1470-1542,1564-1576: startup is async; stopClient() stops the current crypto backend and is idempotent once client polling is stopped.
  • matrix-js-sdk/src/client.ts:1993-2048: Rust crypto assigns cryptoBackend only after asynchronous import/initialization, so an earlier stop cannot clean the late backend.
  • matrix-js-sdk/src/http-api/interface.ts:192-215, src/http-api/index.ts:55-165, src/http-api/fetch.ts:257-305: upload cancellation is owned by UploadOpts.abortController, which drives both XHR and fetch cancellation.
  • matrix-js-sdk/lib/client.d.ts:949-958,1160-1176,2763-2769: declarations confirm async start/init, synchronous stop, and the upload options contract.

Provenance

User Impact

Matrix E2EE QA sends now wait on the current live generation, active image uploads are actually abortable, terminal stop cleans crypto even when initialization completes late, and shutdown cannot produce a post-deadline snapshot commit.

Evidence

  • Exact pushed head: 089056737bd173a02afe129b9b27142fbf587c38.
  • Focused Matrix shared/SDK/persistence tests: 3 files, 174 passed.
  • Focused QA E2EE lifecycle tests: 1 file, 14 passed.
  • Added regressions for a never-settling readiness probe, terminal failure during a pending probe, late crypto init after stop, abort during active upload, and persistence resolving after deadline cancellation without a late snapshot commit.
  • Targeted oxfmt: clean on all 9 repair files.
  • git diff --check: clean.
  • Autoreview: clean; no accepted/actionable findings, patch-correct score 0.98, TruffleHog clean.
  • Whole non-test production delta from the PR parent: +272/-192, net +80.
  • Whole test delta from the PR parent: +369/-8, net +361.
  • Targeted oxlint could not start because the package-boundary declaration preflight fails outside this diff at packages/terminal-core/src/ansi.ts:194 with TS2554.
  • The changed classifier was stopped because its automatic AWS Crabbox route conflicted with the explicit no-Crabbox boundary; the owned lease was released and no remote result is claimed.

Remaining proof: independent exact-head re-review, hosted CI, and any parent-assigned live Matrix/Crabbox evidence. This PR remains draft.

Punchcard-Session: calm-orchard-workshop-fw

Punchcard-Session: cobalt-valley-meadow-mg
@vincentkoc vincentkoc self-assigned this Aug 7, 2026
Punchcard-Session: calm-orchard-workshop-fw
@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix extensions: qa-lab size: L maintainer Maintainer-authored PR labels Aug 7, 2026
@clawsweeper

clawsweeper Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 27, 2026, 4:04 AM ET / 08:04 UTC (Revision 8).

ClawSweeper review

What this changes

The branch makes Matrix encrypted-room QA sends wait for client-generation readiness, forwards cancellation to image uploads, and adds shutdown deadlines for encrypted-state persistence.

Merge readiness

⛔ Blocked before merge - 9 items remain

Keep this protected, MEMBER-authored PR open. Current main has merged part of the shutdown repair, but the branch retains distinct QA readiness and upload cancellation work. Three previously reported correctness blockers remain at the unchanged head, and GitHub reports merge conflicts.

Priority: P1
Reviewed head: 089056737bd173a02afe129b9b27142fbf587c38

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The branch contains useful lifecycle work and focused tests, but three concrete ordering defects and an unresolved main-branch integration prevent a merge-ready rating.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: The changed Matrix client and QA send path has focused mock-based tests, but no exact-head real Matrix scenario result; the contributor proof gate does not apply to this MEMBER-authored PR. The patch changes snapshot cancellation, not the stored snapshot format, so data-model compatibility is not applicable.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The changed Matrix client and QA send path has focused mock-based tests, but no exact-head real Matrix scenario result; the contributor proof gate does not apply to this MEMBER-authored PR. The patch changes snapshot cancellation, not the stored snapshot format, so data-model compatibility is not applicable.
Evidence reviewed 14 items Introduced startup fence gap: The new catch removes the keyed generation when an abort rejects the wrapper, although the underlying SDK startup may still be pending.
Abort wrapper contract: The wrapper rejects on caller abort without waiting for its input promise to settle, establishing the immediate-reacquire ordering behind the startup finding.
Pinned SDK startup contract: At the verified v41.9.0 commit, Rust crypto initialization awaits work before assigning the crypto backend; stopping an earlier backend cannot settle that outstanding initialization.
Findings 3 actionable findings [P1] Keep an aborted startup generation keyed until SDK settlement
[P1] Cancel and await periodic persistence during shutdown
[P2] Reject STOPPED while waiting for encrypted-room readiness
Security None None.

How this fits together

The Matrix plugin wraps matrix-js-sdk for account sync, encrypted sends, and crypto-state storage. QA Lab drives that client through send and shutdown scenarios, while shared client generations control when a replacement may start.

flowchart LR
A[Matrix account and QA action] --> B[Shared client generation]
B --> C[SDK sync and crypto]
C --> D{Room ready and generation live?}
D -->|Yes| E[Encrypted send or upload]
D -->|No| F[Wait or report failure]
B --> G[Shutdown and snapshot persistence]
Loading

Before merge

  • Keep an aborted startup generation keyed until SDK settlement (P1) - The new catch deletes the keyed state when awaitMatrixStartupWithAbort rejects on abort, but that wrapper does not stop or await client.start(). A subsequent acquire can create another client against the same crypto storage while the first Rust initialization is still running. Retain the non-admitting generation until its retirement owner observes startup and cleanup settlement.
  • Cancel and await periodic persistence during shutdown (P1) - The new deadline races only the final persistIdbToDisk call. The interval still starts untracked snapshot writes, so an in-flight periodic write can finish after shutdown returns or contend with the final snapshot. Track, abort, and join that write in the client lifecycle before reporting shutdown complete.
  • Reject STOPPED while waiting for encrypted-room readiness (P2) - The new room check returns false when sync reaches STOPPED, leaving the waiter pending until its full timeout even though this client cannot become ready. Treat the terminal sync state as an immediate failure, as initial-sync readiness already does.
  • Resolve merge risk (P1) - GitHub reports a dirty merge, and current main has newer generation-retirement and periodic-persistence owners; the combined lifecycle behavior needs review after conflict resolution.
  • Resolve merge risk (P1) - No real Matrix E2EE run on this exact head demonstrates readiness, active-upload cancellation, and shutdown recovery together.
  • Complete next step (P2) - Resolve the current-main conflicts, retain aborted startup generations until retirement settles, cancel and await periodic persistence, reject STOPPED readiness promptly, and add the three ordering regressions.
  • Improve patch quality - Integrate the unique changes with current main's generation-retirement and periodic-persistence owners.
  • Improve patch quality - Add the aborted-first-starter then immediate-reacquire ordering regression.
  • Improve patch quality - Add regressions for in-flight periodic persistence at shutdown and STOPPED encrypted-room readiness.

Findings

  • [P1] Keep an aborted startup generation keyed until SDK settlement — extensions/matrix/src/matrix/client/shared.ts:148-156
  • [P1] Cancel and await periodic persistence during shutdown — extensions/matrix/src/matrix/sdk/client-base.ts:599-606
  • [P2] Reject STOPPED while waiting for encrypted-room readiness — extensions/matrix/src/matrix/sdk/client-core.ts:42-49
Agent review details

Security

None.

PR surface

Source +80, Tests +361. Total +441 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 7 272 192 +80
Tests 4 369 8 +361
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 641 200 +441

Review metrics

Metric Value Why it matters
Production and test LOC production +272/-192 (net +80); tests +369/-8 (net +361) Production growth serves the generation, readiness, and SDK cancellation boundaries; the larger test delta covers lifecycle ordering.

Merge-risk options

Maintainer options:

  1. Integrate with current Matrix owners (recommended)
    Resolve the conflicts, repair the three lifecycle findings, and verify the resulting generation and persistence ordering before merge.
  2. Pause this branch
    Keep the protected draft open while the owner decides whether its remaining QA behavior belongs in the related readiness PR.

Technical review

Best possible solution:

Integrate the remaining QA readiness and upload behavior into current main's Matrix lifecycle owners, keeping a generation keyed through startup retirement and joining periodic persistence before shutdown completes.

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

Yes, source inspection gives three concrete ordering cases at this PR head: abort while SDK startup remains pending, stop during an active periodic snapshot, and STOPPED while encrypted-room readiness waits. They were not executed in this read-only review.

Is this the best way to solve the issue?

No. The owner boundaries are appropriate, but this implementation needs to preserve current main's startup-retirement and periodic-persistence fences and reject terminal readiness promptly.

Full review comments:

  • [P1] Keep an aborted startup generation keyed until SDK settlement — extensions/matrix/src/matrix/client/shared.ts:148-156
    The new catch deletes the keyed state when awaitMatrixStartupWithAbort rejects on abort, but that wrapper does not stop or await client.start(). A subsequent acquire can create another client against the same crypto storage while the first Rust initialization is still running. Retain the non-admitting generation until its retirement owner observes startup and cleanup settlement.
    Confidence: 0.96
  • [P1] Cancel and await periodic persistence during shutdown — extensions/matrix/src/matrix/sdk/client-base.ts:599-606
    The new deadline races only the final persistIdbToDisk call. The interval still starts untracked snapshot writes, so an in-flight periodic write can finish after shutdown returns or contend with the final snapshot. Track, abort, and join that write in the client lifecycle before reporting shutdown complete.
    Confidence: 0.94
  • [P2] Reject STOPPED while waiting for encrypted-room readiness — extensions/matrix/src/matrix/sdk/client-core.ts:42-49
    The new room check returns false when sync reaches STOPPED, leaving the waiter pending until its full timeout even though this client cannot become ready. Treat the terminal sync state as an immediate failure, as initial-sync readiness already does.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 9ae6e1853062.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The branch affects Matrix encrypted-client availability and can admit overlapping crypto generations during aborted startup.
  • merge-risk: 🚨 session-state: An early replacement generation or late snapshot write could leave Matrix crypto state associated with the wrong lifecycle.
  • merge-risk: 🚨 availability: Terminal sync can leave encrypted-room readiness waiting until timeout, and shutdown ordering remains unresolved on this head.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The changed Matrix client and QA send path has focused mock-based tests, but no exact-head real Matrix scenario result; the contributor proof gate does not apply to this MEMBER-authored PR. The patch changes snapshot cancellation, not the stored snapshot format, so data-model compatibility is not applicable.

Evidence

What I checked:

Likely related people:

  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • RomneyDa: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • 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 (7 earlier review cycles)
  • reviewed 2026-08-07T07:50:35.616Z sha 0890567 :: needs changes before merge. :: [P1] Cancel periodic persistence when shutdown times out | [P2] Reject terminal sync state during encrypted readiness
  • reviewed 2026-08-18T22:14:23.236Z sha 0890567 :: found issues before merge. :: [P1] Cancel in-flight periodic persistence at shutdown | [P2] Reject terminal sync state during encrypted readiness
  • reviewed 2026-08-24T22:08:52.413Z sha 0890567 :: found issues before merge. :: [P1] Cancel and await in-flight periodic persistence | [P2] Reject terminal sync states during encrypted readiness
  • reviewed 2026-08-24T22:50:26.189Z sha 0890567 :: needs historical verification review before merge. :: [P1] Cancel and await in-flight periodic persistence | [P2] Reject terminal sync states during encrypted readiness
  • reviewed 2026-09-01T10:00:32.430Z sha 0890567 :: found issues before merge. :: [P1] Abort and await periodic persistence before shutdown | [P2] Reject terminal sync states during encrypted readiness
  • reviewed 2026-09-02T16:28:21.733Z sha 0890567 :: found issues before merge. :: [P1] Fence a startup generation until the SDK start settles | [P1] Abort and await interval persistence before shutdown returns | [P2] Reject terminal sync states during encrypted readiness
  • reviewed 2026-09-02T16:46:43.335Z sha 0890567 :: found issues before merge. :: [P1] Fence the first startup generation before deleting it | [P1] Abort and await in-flight periodic persistence | [P2] Reject terminal sync states during encrypted readiness

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 7, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. clawsweeper-recovery-stuck labels Aug 18, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 29, 2026
@vincentkoc

Copy link
Copy Markdown
Member Author

Closing as superseded by the verified current-main reconstruction in #163012, squash commit 37a8f34.

The replacement landed through the native workflow with green exact-head CI and Security Review, a completed clean ClawSweeper review, and remote causal/runtime proof: 55 unique candidate tests, affected readiness follow-ups, encrypted text/notice/image round trips, and all 28 selected checks. All eight landed source hashes match that proof. Current-main snapshot 800847145caaa5d939eb1d68d7a24786472de56a contains the squash with no intervening Matrix or Matrix QA source changes.

The remaining historical behavior is already owned on main:

Those canonical commits and the existing QA simplification in #160460 were verified ancestors of the landed replacement. This is source-backed supersession plus the replacement's actual proof, not a reuse of the historical 188-pass claim.

The separate QA cleanup in #119920 remains open. This closure does not delete the historical branch or revive its unidentified session.

@vincentkoc vincentkoc closed this Oct 1, 2026
@RomneyDa
RomneyDa deleted the fix/matrix-e2ee-generation-lifecycle-20260807 branch October 22, 2026 03:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: matrix Channel integration: matrix extensions: qa-lab maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L 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