Repository navigation
fix(matrix): journal inbound events before advancing sync token - #110568
wangmiao0668000666 wants to merge 13 commits into
Conversation
|
Codex review: found issues before merge. Reviewed August 20, 2026, 1:48 AM ET / 05:48 UTC. ClawSweeper reviewWhat this changesThis PR durably journals dispatchable Matrix events before its sync cursor is persisted, then replays unfinished events after a restart. Merge readinessKeep open, but do not merge as submitted. The Matrix crash-loss problem remains on current main, while this branch duplicates the shared ingress monitor and misses its restart-drain invariant; the shared owner must choose the narrow parked-admission capability before refactoring Matrix onto the canonical monitor. Priority: P1 Review scores
Verification
Live VerificationCommand: Result: PASS (completed) Assertions:
How this fits togetherMatrix sync emits room events while separately persisting a cursor that tells the homeserver what has been consumed. The proposed adapter places SQLite-backed ingress admission between receipt and cursor persistence, then drains queued work into Matrix agent turns. flowchart LR
A[Matrix sync batch] --> B[Matrix event listener]
B --> C[Durable admission]
C --> D[SQLite event queue]
C --> E[Persisted sync cursor]
D --> F[Ingress monitor]
F --> G[Matrix turn handler]
G --> H[Adoption or completion]
Decision needed
Why: The existing failure hook cannot preserve the required parked FIFO and cursor-gate semantics, while retaining a full Matrix lifecycle fork conflicts with the canonical owner boundary. Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +706, Tests +790. Total +1496 across 15 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Add an owner-approved, narrowly typed parked-admission recovery and health/wait capability to the shared ingress monitor, then reduce Matrix to its cursor gate, event codec, room dispatch, and Matrix-specific error classification. Do we have a high-confidence way to reproduce the issue? Unclear for an independently rerun high-confidence reproduction: current source confirms detached Matrix dispatch and the PR provides exact-head fault transcripts, but this review could not independently inspect the matrix-js-sdk cursor-ordering implementation. Is this the best way to solve the issue? No: the reliability goal is sound, but the private lifecycle is not the best fix because the shared monitor already owns the generic queue/drain behavior and lacks only a deliberate extension for Matrix's parked-admission policy. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 0a8226c3db52. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (28 earlier review cycles; latest 8 shown)
|
7afc49f to
31969b0
Compare
|
@clawsweeper re-review Addressing the [P1] real-behavior-proof finding on new head Live behavior proof for the kill -9 crash window, following the accepted #109997 (qqbot) precedent: real production components, a protocol-compatible local homeserver, a real SQLite state DB, and a cross-process kill -9/restart. No mocks of the journal, drain, client, or sync-token store. What runs in this proof
AFTER (this PR, worktree @ 31969b0436) BEFORE (origin/main @ 593423e, same harness, same kill timing, main's detached-dispatch wiring) What this demonstrates
Stub homeserver endpoints (all that matrix-js-sdk requested)
Proof mechanics: driver + stub + watcher are throwaway scripts in End-to-end probe: the proof caught a real gap, this push fixes it, and the fixed tree re-proves end-to-end While building this proof I also ran a variant where the drain dispatches into the real The drop exists for stale sync-cache replays, which may already have been handled; journaled un-adopted events are the opposite. This push now exempts lifecycle-carrying dispatches at So the kill -9 path now works end-to-end with the production handler: the journaled replay survives the pre-startup drop, reaches Scope note on the handler fix: every dispatchable event now arrives via the drain with a lifecycle, so the pre-startup drop effectively retires in favor of the journal + persistent deduper for those events; the drop still applies to the unjournaled fallback path (events without an |
|
🦞🧹 Reason: re-review requires an open issue or PR. Re-review progress:
|
|
@clawsweeper re-review Exact-head re-run of the live kill -9 proof on Tested event class: plain unencrypted Transcript 1 — monitor-level journal proof on
|
c31a2d9 to
7b85908
Compare
|
@clawsweeper re-review This PR was closed by our own account at 17:47:55 UTC with no rationale comment — an unintended automated-side close during a parallel maintenance sweep, not a maintainer or deliberate author action. Reopened now; the branch is unchanged at head The exact-head live proof requested in the last review is the comment immediately above (posted 18:06 UTC): kill -9 cross-process restart on |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
7b85908 to
41ea682
Compare
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review P1 finding addressed on new head Finding: retry exhausted admissions instead of freezing the cursorRoot cause: Fix in
Regression coverage:
Validation (remote box): full matrix suite 122 files / 1944 tests green, |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review P1 finding addressed on new head Finding (P1): later event admitted while a parked predecessor still failsRoot cause: Fix ( Regression test ( Fresh exact-head real-behavior proof (both transcripts on
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Before I start the refactor onto The Matrix branch currently has parked-admission semantics that the shared monitor does not express: when durable admission fails after retries, the event is parked (not dropped), the sync cursor is held but not permanently frozen, later events in the same room stay ordered behind the parked predecessor, and a retry loop re-attempts admission. This behavior was built up over several review rounds (retry-exhaustion cursor freeze, parked-predecessor ordering) and is covered by the exact-head kill -9 / parked-admission proofs. Should this semantics:
The answer shapes the whole refactor: option 1 changes core (and I'd scope a separate PR for it), option 2 keeps this PR plugin-only. Either way I'll keep the cursor gate, payload codec, inspection, and error classification in the Matrix adapter per the Mattermost pattern. |
|
Closing to free up contributor capacity — the core behavior here needs a maintainer decision on queue-drain semantics first. Will revisit if steipete lands on a preferred direction. |
What Problem This Solves
Matrix loses inbound user messages when the gateway crashes or restarts while an agent turn is running.
The loss window is structural: matrix-js-sdk's
doSyncsets the sync token before processing the batch's events ("set the sync token NOW before processing the events … so if something barfs on an event we can skip it" —node_modules/matrix-js-sdk/lib/sync.js:725-728). The plugin'sSqliteBackedMatrixSyncStore.setSyncDatathen persists that token (extensions/matrix/src/matrix/client/file-sync-store.ts:227-232, 250 ms debounce). Meanwhile the SDK bridge re-emits the event synchronously (extensions/matrix/src/matrix/sdk.ts:2073-2086) and the monitor dispatched it detached into a memory-onlyKeyedAsyncQueue(extensions/matrix/src/matrix/monitor/handler.ts:539) for the full agent-turn duration.So the sequence was: message arrives → token advanced in memory → next
/synctells the homeserver the batch is consumed → token persisted to SQLite — all while the message still sits in a memory-only queue. Any crash in that window (routinely minutes, the whole agent turn) permanently loses the message. The existing persistent inbound deduper only stores dedupe records, not the payload, so nothing can replay it.Why This Change Was Made
This is the same crash window the durable-ingress fleet adoption (#109657) already closed on the sibling channels — telegram (#108924), discord (#110274), whatsapp (#110418), mattermost (#110386), msteams (#110357), slack (#109910), signal (#109907), imessage (#110409), sms (#109866) — and Matrix is the remaining sync-loop channel still on detached in-memory dispatch. This PR mirrors the merged Mattermost adapter (
extensions/mattermost/src/mattermost/monitor-ingress.ts) one-for-one, mapped onto Matrix's ack equivalent (the sync-token persist instead of a websocket receive):extensions/matrix/src/matrix/monitor/ingress.ts: every dispatchable inbound event (room message, decrypted message, reaction) is journaled into the sharedchannel_ingress_eventsqueue synchronously inside the sync event listener. The queue's SQLite write is a synchronous transaction (src/state/openclaw-state-db.tsrunOpenClawStateWriteTransaction), so the journal row commits in the same macrotask cycle — before the 250 ms-debounced token persist can tell the homeserver the batch is consumed. Durable-before-ack.createChannelIngressDrain) with per-room lanes (room:<id>, matching the handler's existing per-room serialization), the canonicalturnAdoptionLifecycleseam (bindIngressLifecycleToReplyOptions→core.channel.inbound.run, so the claim tombstones at adoption when the turn's recovery state is durable), bounded retry with backoff and dead-letter (8 attempts / 24 h, shared defaults), and startup replay of journaled rows.event_idcannot be journaled and keep the previous live-dispatch path (onUnjournaledEvent), matching the handler's existing fail-open dedupe behavior for unidentifiable events.66a610d063, reviewer P1): admission retries serialize onadmissionTail, but the 250 ms-debounced sync-token persist did not wait for that tail — a persist landing mid-retry advanced the durable cursor past an event that was not journaled yet, and a crash in that gap lost the event even though the journal would have caught up.SqliteBackedMatrixSyncStorenow accepts an admission gate (setAdmissionGate, wired from the ingress monitor viaclient.setSyncAdmissionGateinmonitor/index.ts):persist()first awaitsingress.waitForAdmissions()(settle-stable on the admission tail), then refuses to advance the cursor while a sticky admission failure is recorded — a permanently un-journalable event degrades to homeserver redelivery instead of silent loss, and because the journal and the sync-token store share the same state DB, a broken DB fails the token persist too.drainPendingDecryptions(those emissions still need the journal) and awaits in-flight drain dispatches exactly where the old detached-taskwaitForIdlestood.No SQLite schema change (reuses the existing
channel_ingress_eventstable in the shared state DB), no new config or env surface, no core/SDK changes — the adapter only consumes the already-exported seams (createChannelIngressDrain,bindIngressLifecycleToReplyOptions,state.openChannelIngressQueue).Known boundary (follow-up candidate, out of scope): E2EE events are journaled when the decrypt bridge emits the decrypted event; a crash between token persist and decryption still loses the still-encrypted event. Closing that needs re-injecting raw encrypted events into the crypto pipeline on replay, which is a separate design.
User Impact
Evidence
Loss-window walkthrough (before)
/syncbatch arrivesnode_modules/matrix-js-sdk/lib/sync.js:725-728extensions/matrix/src/matrix/client/file-sync-store.ts:227-232extensions/matrix/src/matrix/sdk.ts:2073-2086extensions/matrix/src/matrix/monitor/events.ts(old)void runMonitorTask(...)into memory-only queueextensions/matrix/src/matrix/monitor/handler.ts:539Crash anywhere after the persist → message gone. After this PR, the journal row exists in SQLite before the listener returns, the drain dispatches with heartbeats + lane serialization, and rows tombstone only at adoption/completion.
Whole-module audit: all message-like paths journal before the cursor persist (head
c62cfe47)Supplied because the review environment could not materialize the changed blobs; every claim is one
git show <head>:<file> | sed -naway. Line refs below are fromc62cfe47; the gate commit changes only this listener comment inevents.ts(+1 line at :247) and adds the gate seam, leaving the routing itself untouched.All three message-like listener paths route through the durable journal:
room.message→ingress.accept(roomId, event)(extensions/matrix/src/matrix/monitor/events.ts:242-249, after verification-event routing)room.decrypted_event→ingress.accept(events.ts:258-268, RoomMessage type only, after verification routing)room.eventReaction →ingress.accept(events.ts:393)events.ts:358-397).Journal-before-cursor ordering (updated for the admission gate):
setSyncDataonly schedules the token persist:file-sync-store.tsaccumulates and callsmarkDirtyAndSchedulePersist, which defers the flush byPERSIST_DEBOUNCE_MS = 250. Listeners fire during sync processing, beforesetSyncData.admitOnceenqueues with the first attempt at 0 ms, so the journal commit lands inside the 250 ms debounce window in the normal path. A crash before the debounced flush means the token was never persisted, so the homeserver redelivers and the queue dedupes byevent_id.persist()awaitsingress.waitForAdmissions()before writing, so a mid-retry flush holds until the admission tail settles instead of committing past an un-journaled event; with a sticky admission failure recorded,persist()throws before clearingdirty, freezing the cursor so the homeserver keeps redelivering. The mid-retry window no longer exists for the cursor write — proven by the control/fixed kill-window runs below.Lane ordering / dedupe / terminal settlement:
admissionTail(ingress.ts:290-294); per-lane ordering useslaneKey(ingress.ts:276); dispatch goes throughdispatchClaimedEvent→options.dispatch(record, lifecycle)(ingress.ts:187-189).stop()awaitsadmissionTailand the drain before returning (ingress.ts:307-320), so a shutdown cannot strand an accepted-but-uncommitted event.Merged-result check: merge-base with current
mainis87d5cb9f67;mainhas zero changes underextensions/matrix/since (git diff --stat 87d5cb9f67 origin/main -- extensions/matrix/is empty) andgit merge-treereports no conflicts, so the merged result is byte-identical to this head in the touched area.Encrypted pre-decryption window: unchanged by this PR and documented as a remaining limitation — replay starts when the decrypt bridge emits
room.decrypted_event; a crash before that point is outside the adapter's guarantee, same as the reviewer noted, and not a regression of the existing path.Cursor-persist vs admission-retry race: control/fixed kill-window proof (head
66a610d063, re-run 2026-08-01 UTC after rebase ontoorigin/main@78486e2751)Same live harness as the kill-window proof above (real
MatrixClientviacreateMatrixClient, realregisterMatrixMonitorEvents, realchannel_ingress_eventsqueue on a realstate/openclaw.sqlite, realSqliteBackedMatrixSyncStorewith the 250 ms debounce, protocol-compatible stub homeserver, cross-processSIGKILL). New scenario for the reviewer P1: a transparentProxyonqueue.enqueuefails the first two journal appends transiently, so the admission tail sits in retry backoff (0/100/300 ms) across the debounce window; the watcher SIGKILLs the instant the debounced cursor persist lands.CONTROL — pre-fix head
c62cfe47(same harness, no gate seam):In this harness only the SDK's local sync-cache replay re-delivers
b1/b2after the kill; production discards exactly that replay via the pre-startup drop after an unclean shutdown (hasPersistedSyncState=false), so both events are permanently lost — the loss mechanism the accepted BEFORE run already proved end-to-end.FIXED — rebased head
66a610d063(gate wired exactly asmonitor/index.tsdoes):Same batch, same injected failures, same kill trigger — the only difference is whether the cursor write waits for the journal. The turn-in-flight scenario (A) also re-passed on the rebased head: journaled at
t=+8566ms, claimed and blocking, token persisted past it att=+8680ms,SIGKILL, and the restart replayed + adopted$evt-proof-a1exactly once (t=+7455/7458msphase-2) with the sync-cache copy deduped.Merged-result note: the branch is rebased onto current
origin/main(78486e2751), so the branch head IS the merged result. The post-merge-base Matrix drift on main is four commits (#117188/#117106 setup-contract unification, #117097 draft-composition sharing, #116990 presentation fallbacks) — none touches the ingress/event-wiring semantics this PR integrates with;git merge-treereports zero conflicts and the only changed-in-both hunk (handler.tscancelProgressDraftrename) auto-merges. Both kill-window scenarios above were re-run on this rebased head.Regression tests (real SQLite queue, temp state dir, no mocks of the journal path)
New
extensions/matrix/src/matrix/monitor/ingress.test.ts(8 tests) drives the realchannel_ingress_eventsqueue viacreateChannelIngressQueueForTestsover a real temp state DB:accept()(before any timer-based persist could fire), dispatch not started;event_idfall back to live dispatch and journal nothing;registerMatrixMonitorEventswiring: a synchronousroom.messageemission (as the SDK bridge does insidedoSync) is durable immediately after the listener returns, then replays once after a restart;waitForAdmissionsstays pending behind a retrying append and a chained later event — the exact mid-retry window from the race proof — and settles once the tail drains;waitForAdmissionsstill settles (fail-closed signal, not a hang).New
extensions/matrix/src/matrix/client/file-sync-store.test.tscoverage for the gate:persist()waits for the admission gate before writing the cursor (a reader store observes no token advance while the gate is held), andpersist()refuses to advance the cursor past a permanently failed admission (flush rejects, persisted token unchanged; clearing the failure lets the next flush commit).Plus
handler.test.ts: the handler threads the ingress lifecycle intocore.channel.inbound.runasturnAdoptionLifecycle(admission: "exclusive",onAdopted/onAbandonedpassthrough).index.test.ts: handler failures surface to the drain, and shutdown ordering is pause-sync → drain decryptions → ingress stop (awaits in-flight) → thread-binding stop → client release.Test runs
Current head
66a610d063(rebased ontoorigin/main@78486e2751, 2026-08-01 UTC):(Previous head
c62cfe473f: 218/218 focused incl.handler.test.ts, 503/503 forextensions/matrix/src/matrix/monitor/— the rebase ontoorigin/main@87d5cb9f67absorbed the monitor handler pipeline split from #113269, with the journaled-replay exemption from the pre-startup drop inhandler-ingress-prefix.tsvia anisJournaledReplayflag.)Reverse verification (control-red, pre-rebase head)
Stashed only the four production files (
events.ts,handler.ts,index.ts,ingress.ts), kept the tests:Restored the fix -> same four files green. The rebase onto the current
mainchanged only conflict mechanics (handler split intohandler-ingress-*.ts), not the journaled-before-token invariant, and the 98/517-test runs above re-prove it on the rebased head.tsgo / lint / format
(Current head
66a610d063. tsgo was clean pre-rebase with only the 3 pre-existingpackages/net-policy/src/ip.tsstale ipaddr.js type errors and zero in touched files; the post-rebase worktree cannot resolveopenclaw/plugin-sdk/*type subpaths locally, so type-level proof rides on the test runs above and PR CI on the exact head. The gate additions are narrow type surface: one exported gate type, one optional store field, one client method.)