Skip to content

fix(matrix): await persistence shutdown - #129605

Merged
vincentkoc merged 5 commits into
mainfrom
fix/matrix-await-persistence-shutdown
Aug 25, 2026
Merged

vincentkoc merged 5 commits into
mainfrom
fix/matrix-await-persistence-shutdown

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Related: #120168

What Problem This Solves

Fixes Matrix shutdown races where client startup, monitor cleanup, encrypted-state persistence, SDK discard, or QA discard cleanup could outlive the generation that owned them. It also keeps caller-visible shutdown bounded when matrix-js-sdk crypto initialization never settles.

Why This Change Was Made

Generation retirement had overlapping deletion and late-drain state machines. Late lease release and forced retirement could delete a keyed generation independently of the retirement owner, persistence failure could surface before discard fallback settled, and stopWithoutPersist() could yield before claiming its shutdown flight.

beginGenerationRetirement() is now the sole generation-deletion owner:

  • a startup timeout rejects the caller after five seconds while the keyed, non-admitting generation continues to own startup settlement, monitor retirement, original leases, and SDK discard;
  • late release only resolves lease drainage;
  • repeated forced retirement rejects during late-drain, otherwise joins the active owner and never deletes directly;
  • monitor, normal discard, final-drain discard, or persistence-fallback failure retains the poisoned key;
  • strict persistence failure awaits discard fallback; successful fallback deletes and then surfaces the persistence error, while failed fallback retains and surfaces the discard error;
  • stopWithoutPersist() synchronously single-flights discard-first, persist-first, and mixed concurrent shutdown through the existing stop flight plus one private fallback promise.

The existing periodic persistence owner fix, post-abort SDK/persistence fences, and QA asynchronous discard handling remain intact.

User Impact

Matrix shutdown cannot admit a replacement over unresolved startup, monitor work, transient borrowers, or SDK discard. Failed cleanup remains visibly poisoned instead of silently replacing the client. No configuration or workflow changes.

Evidence

  • Exact head: 81fdd67f5d7d2a9ba2ef892589c1273a3a82b3d1.
  • Repair parent: 9295072c2dec01d79e8ae2c875a779abf3b53ff9; no rebase was performed.
  • Branch merge base: 5ac1b3c558f6826e636203a9b27273801d6f9fae.
  • Current origin/main: df9b7a5fbe9b94b0ab25dc404db7784797feadca.
  • Read-only merge-tree against current main succeeds. d2052167ec8088e1bed53d0162b71a149247103b / fix(matrix): let follow-ups steer active turns #128907 transfers replay-claim ownership inside already tracked Matrix handlers without changing monitor task admission, listener detachment, task waiting, cleanup registration, or this repair's write scope. The subsequent df9b7a5fbe9b commit is UI-only. No rebase is required.

Owner proof:

  • extensions/matrix/src/matrix/client/shared.ts has one authoritative retirement flow and only beginGenerationRetirement() decides whether the keyed generation can be deleted.
  • Late lease release only resolves ownership drainage. Forced retirement never deletes and rethrows while the same failed state remains keyed.
  • Startup timeout keeps the generation fenced while startup settlement, monitor retirement, lease drainage, and SDK discard are observed independently.
  • extensions/matrix/src/matrix/sdk/client-base.ts synchronously claims one stop flight and awaits any failed-persistence discard fallback.

Direct dependency proof from pinned [email protected] source and types:

  • startClient() starts sync and services without an AbortSignal;
  • initRustCrypto() exposes no cancellation or timeout;
  • stopClient() is synchronous and stops an initialized crypto backend even when startup was incomplete;
  • the SDK warns that multiple clients connected to the same IndexedDB can corrupt crypto state, which is why replacement admission must remain fenced until retirement owns a terminal outcome.

Validation:

  • Focused Matrix owner/SDK/persistence tests: 183/183 passed.
  • Focused QA lifecycle tests: 12/12 passed.
  • Seven regressions failed on parent head 9295072c2dec and now cover late-release deletion ownership, repeated forced late-drain retirement, normal discard failure retention, strict persistence fallback joining, failed fallback retention, final-drain discard failure retention, and mixed shutdown single-flight.
  • Existing regressions continue to cover live startup joining, bounded stuck startup, immediate monitor admission closure, monitor cleanup despite late discard rejection, abort while initRustCrypto() is pending, periodic persistence cancellation/awaiting, and QA deferred discard.
  • Extension production/test types, changed-file lint, formatting, package/plugin boundaries, doctor contracts, dependency pins, database-first/runtime-sidecar/import-cycle guards, and git diff --check passed.
  • Exact-head independent review and final structured P0/P1 autoreview are clean.
  • Pre-ready exact-head CI completed with 83 successful/skipped checks and no attention items.
  • Deleted-symbol scan has zero matches for late-drain-stopped, PoisonDisposition, deleteSharedClientStateAfterLateDrain, continueLateGenerationRetirement, and StopOutcome.

Live-smoke infeasibility: no authenticated Matrix credentials or accessible E2EE room are available in this execution environment, so a real homeserver/WASM shutdown-restart smoke cannot be performed. Mock lifecycle coverage plus direct [email protected] source/type contract inspection is the best available proof.

Judged LOC

  • Production: +158/-110, net +48. The growth owns bounded retirement, poison retention, and dependency-required stop fencing at the generation lifecycle owner.
  • Tests/test support: +424/-56, net +368.
  • Final repair cycle: production +72/-96, net -24; tests +106/-35, net +71.

Release Note

Fix Matrix shutdown so unresolved startup, monitor ownership, encrypted-state persistence, and asynchronous discard cleanup cannot outlive or prematurely replace their client generation.

@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@vincentkoc vincentkoc self-assigned this Aug 25, 2026
@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: M maintainer Maintainer-authored PR labels Aug 25, 2026
@vincentkoc
vincentkoc force-pushed the fix/matrix-await-persistence-shutdown branch from 6081d85 to c2af2af Compare August 25, 2026 21:23
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

The head changed from 6081d859 to c2af2af9 to address the two lifecycle findings: QA now awaits discard cleanup, and generation retirement joins the underlying startup task while abort fences crypto persistence and SDK startup. The PR body contains the refreshed proof and LOC split.

@clawsweeper

clawsweeper Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@vincentkoc
vincentkoc force-pushed the fix/matrix-await-persistence-shutdown branch from c2af2af to 251cf2f Compare August 25, 2026 21:48
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 25, 2026, 5:52 PM ET / 21:52 UTC.

ClawSweeper review

What this changes

The PR makes Matrix client retirement await startup, crypto snapshot work, and QA discard cleanup so those tasks cannot outlive a retired generation.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open. The patch addresses real owner-level Matrix shutdown races, but the current head lacks independently verified exact-head proof and direct matrix-js-sdk contract inspection; it is also a member-authored, maintainer-labeled draft.

Priority: P2
Reviewed head: 251cf2f074df0d1d0152393aef23e9f84fcea92b

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The owner-boundary patch and behavioral regressions are promising, but exact-head and dependency-contract evidence remain incomplete.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: This member-authored PR is exempt from the external-contributor proof gate; the body reports focused tests, but those results predate the current head.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This member-authored PR is exempt from the external-contributor proof gate; the body reports focused tests, but those results predate the current head.
Evidence reviewed 6 items Current-main gap: Current main starts periodic persistence without retaining its promise and invokes discard shutdown without awaiting it.
Owner-boundary repair: The PR records one periodic snapshot promise, aborts it during retirement, and awaits it before an optional final persistence.
Startup-retirement repair: The PR waits for the startup promise during retirement and keeps a timed-out generation keyed until late cleanup stops it.
Findings None None.
Security None None.

Live Verification

Command: pnpm test extensions/matrix/src/matrix/client/shared.test.ts extensions/matrix/src/matrix/sdk.test.ts extensions/matrix/src/matrix/sdk/idb-persistence.test.ts extensions/qa-lab/src/live-transports/matrix/substrate/e2ee-client.test.ts

Result: PASS (completed)

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › verifies with a provided recovery key and reports success
[MatrixClientLite] Cross-signing bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › verifies with a provided recovery key and reports success
[MatrixClientLite] Secret storage bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › accepts a staged recovery key when it establishes identity trust and bac
kup usability
[MatrixClientLite] Verification request handler registered

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › accepts a staged recovery key when it establishes identity trust and bac
kup usability
[MatrixClientLite] Secret storage bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › accepts a staged recovery key when it establishes identity trust and bac
kup usability
[MatrixClientLite] Cross-signing bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › accepts a staged recovery key when it establishes identity trust and bac
kup usability
[MatrixClientLite] Secret storage bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Verification request handler registered

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Secret storage bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Cross-signing bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Secret storage bootstrap complete

stderr | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Cross-signing/bootstrap is incomplete for an already owner-signed device; skipping automatic reset and preserving the current identity. Resto
re the recovery key or run an explicit verification bootstrap if repair is needed.

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Secret storage bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Cross-signing bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › fails recovery-key verification when the device lacks full cross-signing
 identity trust
[MatrixClientLite] Secret storage bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › keeps a usable recovery key distinct from owner device verification
[MatrixClientLite] Verification request handler registered

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › keeps a usable recovery key distinct from owner device verification
[MatrixClientLite] Secret storage bootstrap complete

stdout | extensions/matrix/src/matrix/sdk.test.ts › MatrixClient crypto bootstrapping › keeps a usable recovery key distinct from owner device verification
[MatrixClientLite] Cross-signin
… output truncated …

Assertions:

  • PASS expect_output: passed

How this fits together

Matrix client generations own SDK startup and encrypted-state persistence; leases retire a generation before another can replace it. QA Lab uses that lifecycle when exercising encrypted Matrix scenarios.

flowchart LR
A[Matrix client lease] --> B[Client generation]
B --> C[SDK startup and crypto setup]
B --> D[Periodic crypto snapshot]
A --> E[Generation retirement]
E --> F[Await owned work]
F --> G[Stop or discard client]
G --> H[Replacement or QA result]
Loading

Before merge

  • Resolve merge risk (P1) - The PR body’s focused validation names pre-current head c2af2af, while the reviewed head is 251cf2f; exact-head lifecycle proof is still needed.
  • Resolve merge risk (P1) - matrix-js-sdk startup and stop behavior is part of the changed lifecycle boundary but could not be inspected because dependencies are not materialized in this read-only checkout.
  • Resolve merge risk (P1) - Production code grows by 109 net lines; the growth is plausibly required for ownership of three asynchronous shutdown phases, but should remain bounded to those owners.
  • Complete next step (P2) - This member-authored, maintainer-labeled draft needs exact-head lifecycle and dependency-contract validation rather than automated cleanup.
Agent review details

Security

None.

PR surface

Source +100, Tests +228. Total +328 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 5 150 50 +100
Tests 4 256 28 +228
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 406 78 +328

Review metrics

Metric Value Why it matters
Production versus test delta production +149/-40 (net +109); tests/support +257/-29 (net +228) Production growth implements generation ownership and single-flight snapshot shutdown; tests exercise blocked and late-settling lifecycle paths.

Merge-risk options

Maintainer options:

  1. Refresh exact-head lifecycle proof (recommended)
    Inspect the installed Matrix SDK startup/stop contract and publish focused Matrix plus QA lifecycle results for head 251cf2f before merge.
  2. Pause until dependency proof is available
    Keep the draft open if an environment with the pinned Matrix SDK cannot verify the retirement ordering safely.

Technical review

Best possible solution:

Retain the owner-boundary repair after direct matrix-js-sdk contract inspection and exact-head focused Matrix/QA validation confirm the shutdown ordering; the production growth is justified only by those distinct asynchronous ownership boundaries.

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

No live reproduction was performed; source and focused regressions provide a medium-confidence reproduction path for pending startup, persistence, and discard cleanup.

Is this the best way to solve the issue?

Unclear: the fix is at the appropriate lifecycle owners, but direct verification of the pinned Matrix SDK contract is still missing.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded Matrix lifecycle reliability repair without evidence of an emergency core outage.
  • add merge-risk: 🚨 availability: Changed retirement ordering can affect whether Matrix clients stop, persist, and become replaceable promptly.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored PR is exempt from the external-contributor proof gate; the body reports focused tests, but those results predate the current head.

Label justifications:

  • P2: This is a bounded Matrix lifecycle reliability repair without evidence of an emergency core outage.
  • merge-risk: 🚨 availability: Changed retirement ordering can affect whether Matrix clients stop, persist, and become replaceable promptly.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored PR is exempt from the external-contributor proof gate; the body reports focused tests, but those results predate the current head.

Evidence

What I checked:

Likely related people:

  • vincentkoc: Authored the reviewed lifecycle changes and earlier shared Matrix E2EE retirement work. (role: recent area contributor; confidence: high; commits: 251cf2f074df, a3419d4a4b4c; files: extensions/matrix/src/matrix/client/shared.ts, extensions/matrix/src/matrix/sdk/client-base.ts)
  • Ben Badejo: Recent history includes a late-lease-drain repair in the same shared-client owner. (role: recent area contributor; confidence: medium; commits: 784a2287815c; files: extensions/matrix/src/matrix/client/shared.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Publish focused exact-head Matrix and QA lifecycle output.
  • Inspect the pinned matrix-js-sdk startup and stop contract before merge.

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.

@vincentkoc
vincentkoc marked this pull request as ready for review August 25, 2026 22:59
@vincentkoc
vincentkoc merged commit d7c5771 into main Aug 25, 2026
187 of 188 checks passed
@vincentkoc
vincentkoc deleted the fix/matrix-await-persistence-shutdown branch August 25, 2026 23:19
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 26, 2026
* fix(matrix): await persistence shutdown

* fix(matrix): join startup during shutdown

* fix(matrix): bound startup retirement

* fix(matrix): fence late retirement ownership

* fix(matrix): centralize generation retirement
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. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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