Skip to content

fix(matrix): journal inbound events before advancing sync token - #110568

Closed
wangmiao0668000666 wants to merge 13 commits into
openclaw:mainfrom
wangmiao0668000666:fix/matrix-ingress-durability
Closed

wangmiao0668000666 wants to merge 13 commits into
openclaw:mainfrom
wangmiao0668000666:fix/matrix-ingress-durability

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

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 doSync sets 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's SqliteBackedMatrixSyncStore.setSyncData then 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-only KeyedAsyncQueue (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 /sync tells 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):

  • New extensions/matrix/src/matrix/monitor/ingress.ts: every dispatchable inbound event (room message, decrypted message, reaction) is journaled into the shared channel_ingress_events queue synchronously inside the sync event listener. The queue's SQLite write is a synchronous transaction (src/state/openclaw-state-db.ts runOpenClawStateWriteTransaction), 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.
  • Dispatch now runs through the core durable ingress drain (createChannelIngressDrain) with per-room lanes (room:<id>, matching the handler's existing per-room serialization), the canonical turnAdoptionLifecycle seam (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.
  • Handler failures now propagate to the drain when journaled (the detached path swallowed them) so the retry/dead-letter policy owns them; terminal non-turn outcomes (policy gates, dedupe skips) tombstone on dispatch return. The pre-existing persistent deduper keeps homeserver redeliveries exactly-once on top of the drain's tombstones.
  • Events without an event_id cannot be journaled and keep the previous live-dispatch path (onUnjournaledEvent), matching the handler's existing fail-open dedupe behavior for unidentifiable events.
  • Journal-append failure retries (0/100/300 ms) on the serialized admission tail; a permanently failed append is recorded as a sticky admission failure (fail closed), mirroring the whatsapp landing decision.
  • The durable cursor write is gated on journal admission (head 66a610d063, reviewer P1): admission retries serialize on admissionTail, 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. SqliteBackedMatrixSyncStore now accepts an admission gate (setAdmissionGate, wired from the ingress monitor via client.setSyncAdmissionGate in monitor/index.ts): persist() first awaits ingress.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.
  • Shutdown stops ingress after drainPendingDecryptions (those emissions still need the journal) and awaits in-flight drain dispatches exactly where the old detached-task waitForIdle stood.

No SQLite schema change (reuses the existing channel_ingress_events table 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

  • A gateway crash/restart during (or before) an agent turn no longer permanently loses Matrix room messages, decrypted messages, or reactions: journaled events replay once on startup and are deduped against already-handled ones.
  • Handler failures retry with bounded backoff and dead-letter loudly instead of vanishing into a detached-task log line.
  • No operator action, config change, or migration required; behavior on the happy path is unchanged (same per-room serialization, same reply pipeline).

Evidence

Loss-window walkthrough (before)

Step Where Effect
/sync batch arrives node_modules/matrix-js-sdk/lib/sync.js:725-728 token set before event processing
token persisted extensions/matrix/src/matrix/client/file-sync-store.ts:227-232 homeserver may consider batch consumed after 250 ms debounce
event re-emitted extensions/matrix/src/matrix/sdk.ts:2073-2086 sync, during batch processing
dispatch extensions/matrix/src/matrix/monitor/events.ts (old) detached void runMonitorTask(...) into memory-only queue
agent turn extensions/matrix/src/matrix/monitor/handler.ts:539 message lives only in process memory for minutes

Crash 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 -n away. Line refs below are from c62cfe47; the gate commit changes only this listener comment in events.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.event Reaction → ingress.accept (events.ts:393)
  • Non-message events (member, encrypted-raw, invite, join, verification) are intentionally not journaled: they create no delivery turn, only state invalidation/warnings (events.ts:358-397).

Journal-before-cursor ordering (updated for the admission gate):

  • setSyncData only schedules the token persist: file-sync-store.ts accumulates and calls markDirtyAndSchedulePersist, which defers the flush by PERSIST_DEBOUNCE_MS = 250. Listeners fire during sync processing, before setSyncData.
  • admitOnce enqueues 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 by event_id.
  • Retry-window race (reviewer P1) is now closed structurally: persist() awaits ingress.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 clearing dirty, 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.
  • The journal shares the state DB with the sync-token store: a dropped journal append correlates with token-persist failure, so the failure mode degrades to redelivery, not loss. After retries (0/100/300 ms) a failed append is logged loudly and the event is not dispatched live around the drain's dedupe.

Lane ordering / dedupe / terminal settlement:

  • Admission is serialized through admissionTail (ingress.ts:290-294); per-lane ordering uses laneKey (ingress.ts:276); dispatch goes through dispatchClaimedEvent → options.dispatch(record, lifecycle) (ingress.ts:187-189).
  • stop() awaits admissionTail and 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 main is 87d5cb9f67; main has zero changes under extensions/matrix/ since (git diff --stat 87d5cb9f67 origin/main -- extensions/matrix/ is empty) and git merge-tree reports 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 onto origin/main @ 78486e2751)

Same live harness as the kill-window proof above (real MatrixClient via createMatrixClient, real registerMatrixMonitorEvents, real channel_ingress_events queue on a real state/openclaw.sqlite, real SqliteBackedMatrixSyncStore with the 250 ms debounce, protocol-compatible stub homeserver, cross-process SIGKILL). New scenario for the reviewer P1: a transparent Proxy on queue.enqueue fails 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):

[journal] enqueue id=$evt-proof-b1 attempt=1 -> TRANSIENT FAIL (t=+7581ms)
[journal] enqueue id=$evt-proof-b1 attempt=2 -> TRANSIENT FAIL (t=+7681ms)
[cursor] persisted token advanced: null -> s2 (t=+7713ms)   <-- 250 ms debounce fired mid-retry
[watcher] journal rows at SIGKILL: []                       <-- token past BOTH events, nothing durable
[watcher] stub /sync since-token sequence: ["<initial>","s1","s2","s2"]  <-- restart resumes at s2; homeserver never re-serves

In this harness only the SDK's local sync-cache replay re-delivers b1/b2 after 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 as monitor/index.ts does):

[journal] enqueue id=$evt-proof-b1 attempt=1 -> TRANSIENT FAIL (t=+8290ms)
[journal] enqueue id=$evt-proof-b1 attempt=2 -> TRANSIENT FAIL (t=+8391ms)
[journal] enqueue id=$evt-proof-b1 attempt=3 -> ok (t=+8693ms)
[journal] enqueue id=$evt-proof-b2 attempt=4 -> ok (t=+8695ms)   <-- b2 chained behind the retrying tail
[cursor] persisted token advanced: null -> s2 (t=+8710ms)        <-- gate held the persist until the tail settled
[watcher] journal rows at SIGKILL: [$evt-proof-b1 claimed, $evt-proof-b2 pending]  <-- both durable before the ack
=== PHASE 2: fresh process on the same state dir (kill -9 restart) ===
[dispatch] replayed id=$evt-proof-b1 body="first: append fails twice"; adopted (t=+7821/7824ms)
[dispatch] replayed id=$evt-proof-b2 body="second: chained behind the retrying tail"; adopted (t=+7827/7829ms)  <-- journal replay, exactly once
[journal] enqueue id=$evt-proof-b1/b2 -> ok (t=+8023/8027ms)  <-- sync-cache replay copies deduped against the tombstones

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 at t=+8680ms, SIGKILL, and the restart replayed + adopted $evt-proof-a1 exactly once (t=+7455/7458ms phase-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-tree reports zero conflicts and the only changed-in-both hunk (handler.ts cancelProgressDraft rename) 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 real channel_ingress_events queue via createChannelIngressQueueForTests over a real temp state DB:

  • journal row commits in the same macrotask cycle as accept() (before any timer-based persist could fire), dispatch not started;
  • restart replay: accept → simulated crash (no stop) → fresh monitor over the same state dir dispatches the journaled event exactly once and tombstones it;
  • completed events are not redispatched across a restart;
  • a throwing dispatch is not tombstoned — a later process redelivers it (retry budget), then completes;
  • events without an event_id fall back to live dispatch and journal nothing;
  • end-to-end through the real registerMatrixMonitorEvents wiring: a synchronous room.message emission (as the SDK bridge does inside doSync) is durable immediately after the listener returns, then replays once after a restart;
  • waitForAdmissions stays 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;
  • a journal append that exhausts its retries records a sticky admission failure while waitForAdmissions still settles (fail-closed signal, not a hang).

New extensions/matrix/src/matrix/client/file-sync-store.test.ts coverage 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), and persist() 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 into core.channel.inbound.run as turnAdoptionLifecycle (admission: "exclusive", onAdopted/onAbandoned passthrough). 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 onto origin/main @ 78486e2751, 2026-08-01 UTC):

$ node scripts/run-vitest.mjs extensions/matrix/src/matrix/monitor/ingress.test.ts \
    extensions/matrix/src/matrix/client/file-sync-store.test.ts \
    extensions/matrix/src/matrix/monitor/index.test.ts \
    extensions/matrix/src/matrix/monitor/events.test.ts
Test Files  4 passed (4)
Tests  98 passed (98)

$ node scripts/run-vitest.mjs extensions/matrix/src/matrix/monitor/ \
    extensions/matrix/src/matrix/client/file-sync-store.test.ts
Tests  517 passed (517)

(Previous head c62cfe473f: 218/218 focused incl. handler.test.ts, 503/503 for extensions/matrix/src/matrix/monitor/ — the rebase onto origin/main @ 87d5cb9f67 absorbed the monitor handler pipeline split from #113269, with the journaled-replay exemption from the pre-startup drop in handler-ingress-prefix.ts via an isJournaledReplay flag.)

Reverse verification (control-red, pre-rebase head)

Stashed only the four production files (events.ts, handler.ts, index.ts, ingress.ts), kept the tests:

Test Files  4 failed (4)   <- ingress import gone, wiring assertions red
Tests  6 failed | 199 passed (205)

Restored the fix -> same four files green. The rebase onto the current main changed only conflict mechanics (handler split into handler-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

$ oxlint extensions/matrix/src/matrix/monitor/   -> clean (exit 0)
$ oxfmt --check extensions/matrix/src/matrix/monitor/ -> clean (85 files)

(Current head 66a610d063. tsgo was clean pre-rebase with only the 3 pre-existing packages/net-policy/src/ip.ts stale ipaddr.js type errors and zero in touched files; the post-rebase worktree cannot resolve openclaw/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.)

@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: L labels Jul 18, 2026
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 20, 2026, 1:48 AM ET / 05:48 UTC.

ClawSweeper review

What this changes

This PR durably journals dispatchable Matrix events before its sync cursor is persisted, then replays unfinished events after a restart.

Merge readiness

⚠️ Needs maintainer review before merge - 5 items remain

Keep 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
Reviewed head: 39a4a194927952f784d3c539b5c1a90e07168aff
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The crash-recovery proof is strong, but the unresolved duplicated lifecycle is a merge-blocking architectural defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The contributor supplied exact-head redacted terminal evidence of SIGKILL/restart recovery and SQLite-lock parked-admission recovery through production Matrix components.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The contributor supplied exact-head redacted terminal evidence of SIGKILL/restart recovery and SQLite-lock parked-admission recovery through production Matrix components.
Evidence reviewed 6 items Current main still has the loss-prone route: Current main dispatches Matrix room, decrypted, and reaction events through detached tasks, while its sync store has no admission gate.
Canonical lifecycle owner: The public ingress monitor owns queue/drain construction, retry, idle wake, restart fencing, retention, and shutdown; its contract leaves channel code with transport inspection, payload, and delivery policy.
Concrete branch divergence: The new Matrix monitor reimplements the generic lifecycle and lacks the shared monitor's gateway-restart drain fence, so it can evolve differently from the canonical owner.
Findings 1 actionable finding [P1] Move Matrix onto the shared ingress monitor
Security None None.

Live Verification

Command: pnpm openclaw --help

Result: PASS (completed)

pnpm openclaw --help
runner@runnervmzvulz:/tmp/clawsweeper-live-proof-110568-xO7xER/target$ pnpm openclaw --help
$ node scripts/run-node.mjs --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
pnpm openclaw --help
[browser] build: node scripts/build-copilot-runtime.mjs
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.88 kB
[log]
[success] rolldown v1.2.0 Finished in 47.81 ms
[diffs] build: node ../../scripts/build-diffs-viewer-runtime.mjs curated
[diffs-language-pack] build: node ../../scripts/build-diffs-viewer-runtime.mjs full
[discord] build: node ../../scripts/build-discord-activity-sdk.mjs
[tsdown-build] invocation 1/2 finished in 0.7s
[tsdown-build] invocation 2/2 finished in 8.0s
runtime-postbuild: 9 phases completed in 779ms (slowest: stable root runtime imports 265ms)

OpenClaw 2026.7.2 (39a4a19) — All your chats, one OpenClaw.

Usage: openclaw [options] [command]

Options:
  --container ‹name›   Run the CLI inside a running Podman/Docker container named ‹name› (default: env OPENCLAW_CONTAINER)
  --dev                Dev profile: isolate state under ~/.openclaw-dev, default gateway port 19001, and shift derived ports (browser/canvas)
  -h, --help           Display help for command
  --log-level ‹level›  Global log level override for file + console (silent|fatal|error|warn|info|debug|trace)
  --no-color           Disable ANSI colors
  --profile ‹name›     Use a named profile (isolates OPENCLAW_STATE_DIR/OPENCLAW_CONFIG_PATH under ~/.openclaw-‹name›)
  -V, --version        output the version number

Commands:
  Hint: commands suffixed with * have subcommands. Run ‹command› --help for details.
  acp *                Run an ACP bridge backed by the Gateway
  agent *              Run an agent turn via the Gateway (use --local for embedded)
  agents *             Manage isolated agents (workspaces + auth + routing)
  approvals *          Manage approval policy and pending requests
  attach               Attach Claude Code to a gateway session with scoped MCP tools
  audit                Inspect activity records and exact-run identity context
  automations *        Manage automations (alias for cron)
  backup *             Create and verify backup archives and SQLite snapshots
  capability *         Run provider capability commands (fallback alias: infer)
  channels *           Manage connected chat channels and accounts
  chat                 Open a local terminal UI (alias for tui --local)
  clawbot *            Legacy clawbot command aliases
  commitments *        List and manage inferred follow-up commitments
  completion           Generate shell completion script
  config *             Non-interactive config helpers (get/set/patch/unset/file/schema/validate). Run without subcommand for guided setup.
  configure            Interactive configuration for credentials, channels, gateway, and agent defaults
  cron *               Manage automations (via Gateway)
  daemon *             Manage the Gateway service (launchd/systemd/schtasks)
  dashboard            Open the Control UI with your current token
  devices *            Device pairing and auth tokens
  directory *          Lookup contact and group IDs (self, peers, groups) for supported chat channels
  dns *                DNS helpers for wide-area discovery (Tailscale + CoreDNS)
  docs                 Search the live OpenClaw docs
  doctor               Health checks + quick fixes for the gateway and channels
  exec-approvals *     Manage exec approvals (alias for approvals)
  exec-policy *        Show or synchronize requested exec policy with host approvals
  fleet *              Provision and manage isolated tenant cells (experimental)
  gateway *            Run, inspect, and query the WebSocket Gateway
  health               Fetch health from the running gateway
  help                 Display help for command
  ho
… output truncated …

Assertions:

  • PASS expect_output: Usage:

How this fits together

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

Decision needed

Question Recommendation
Should the shared ingress monitor own a narrow opt-in parked-admission recovery mode for cursor-gated channels, or should Matrix retain that exceptional policy behind a new shared extension hook? Add a shared recovery capability: Make ordered parked admission and its health/wait observation a small shared monitor option, then refactor Matrix onto the canonical monitor.

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

  • Move Matrix onto the shared ingress monitor (P1) - This private monitor duplicates queue admission, pumping, retention, and shutdown, but its requestDrain path lacks the shared monitor's restart-drain fence. A Matrix process can therefore dispatch while gateway restart recovery is active and will keep drifting from shared lifecycle fixes. Add the needed parked-admission capability to the shared monitor, then make this a thin Matrix adapter.
  • Resolve merge risk (P1) - The private Matrix pump lacks the shared monitor's restart-drain fence, so it can dispatch while restart recovery is still active.
  • Resolve merge risk (P1) - Merging a second lifecycle owner risks future divergence in retry, cancellation, retention, and shutdown behavior.
  • Resolve merge risk (P1) - GitHub reports this branch as conflicting with current main; exact-head proof must be refreshed after the architectural refactor and conflict resolution.

Findings

  • [P1] Move Matrix onto the shared ingress monitor — extensions/matrix/src/matrix/monitor/ingress.ts:309-316
Agent review details

Security

None.

PR surface

Source +706, Tests +790. Total +1496 across 15 files.

View PR surface stats
Area Files Added Removed Net
Source 10 760 54 +706
Tests 5 815 25 +790
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 1575 79 +1496

Review metrics

Metric Value Why it matters
Production versus test LOC production +691/-47, tests +884/-32 Most production growth is a second queue/drain lifecycle, which needs a named shared-owner justification before merge.

Stored data model

Persistent data-model change detected: serialized state: extensions/matrix/src/matrix/client/file-sync-store.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refactor onto the canonical monitor (recommended)
    Approve the narrow shared recovery contract, remove the private Matrix queue/drain/pump lifecycle, and refresh exact-head proof before merge.
  2. Pause the proposal
    Hold this branch if maintainers do not want to expand the shared monitor contract for Matrix's cursor-gated recovery semantics.

Technical review

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

  • [P1] Move Matrix onto the shared ingress monitor — extensions/matrix/src/matrix/monitor/ingress.ts:309-316
    This private monitor duplicates queue admission, pumping, retention, and shutdown, but its requestDrain path lacks the shared monitor's restart-drain fence. A Matrix process can therefore dispatch while gateway restart recovery is active and will keep drifting from shared lifecycle fixes. Add the needed parked-admission capability to the shared monitor, then make this a thin Matrix adapter.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The patch targets silent loss of inbound Matrix messages after a gateway crash before turn adoption.
  • merge-risk: 🚨 message-delivery: Admission ordering and cursor persistence directly control Matrix replay, ordering, and duplicate suppression.
  • merge-risk: 🚨 availability: The admission gate can intentionally stop cursor persistence while durable admission remains unhealthy.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The contributor supplied exact-head redacted terminal evidence of SIGKILL/restart recovery and SQLite-lock parked-admission recovery through production Matrix components.
  • proof: sufficient: Contributor real behavior proof is sufficient. The contributor supplied exact-head redacted terminal evidence of SIGKILL/restart recovery and SQLite-lock parked-admission recovery through production Matrix components.

Evidence

What I checked:

  • Current main still has the loss-prone route: Current main dispatches Matrix room, decrypted, and reaction events through detached tasks, while its sync store has no admission gate. (extensions/matrix/src/matrix/monitor/events.ts:242, 0a8226c3db52)
  • Canonical lifecycle owner: The public ingress monitor owns queue/drain construction, retry, idle wake, restart fencing, retention, and shutdown; its contract leaves channel code with transport inspection, payload, and delivery policy. (src/channels/message/ingress-monitor.ts:182, 0a8226c3db52)
  • Concrete branch divergence: The new Matrix monitor reimplements the generic lifecycle and lacks the shared monitor's gateway-restart drain fence, so it can evolve differently from the canonical owner. (extensions/matrix/src/matrix/monitor/ingress.ts:309, 39a4a1949279)
  • Existing hook is insufficient: The shared monitor retries an admission, calls its failure hook, rethrows, and clears its admission tail; it cannot retain a failed raw event, preserve parked FIFO order, or expose Matrix's settle-stable cursor gate. (src/channels/message/ingress-monitor.ts:578, 0a8226c3db52)
  • Shared-monitor provenance: History shows deliberate shared-monitor consolidation, including the channel refactor commit and subsequent monitor consolidation. (src/channels/message/ingress-monitor.ts:186, c163daa4ed02)
  • After-fix behavior proof: The PR discussion supplies exact-head terminal transcripts using production Matrix client/event registration, SQLite queue and sync store, a local protocol-compatible homeserver, cross-process SIGKILL restart, and SQLite-lock recovery; it covers unencrypted events, not the separate pre-decryption boundary. (39a4a1949279)

Likely related people:

  • steipete: History credits repeated shared-monitor consolidation to this author, and the contributor explicitly requested this person's decision on the missing recovery capability. (role: shared ingress monitor author and recent area contributor; confidence: high; commits: c163daa4ed02, f7ddcdbf26e3; files: src/channels/message/ingress-monitor.ts, src/plugin-sdk/channel-outbound.ts)
  • joshavant: Recent ingress history includes post-branch retry-exhaustion work in the shared monitor area. (role: recent shared-ingress contributor; confidence: medium; commits: 06600e2c; files: src/channels/message/ingress-monitor.ts)
  • obviyus: The merged durable-ingress foundation was authored through the related core adoption work. (role: adjacent durable-ingress contributor; confidence: medium; commits: 19b5e564d7e3; files: src/channels/message/ingress-drain.ts)

Rank-up moves

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

  • Obtain the shared-monitor owner decision.
  • Refactor Matrix to the selected shared seam.
  • Re-run the supplied recovery proof on the conflict-resolved head.

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 (28 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-07T06:45:34.775Z sha a81a3b7 :: needs changes before merge. :: [P1] Retry exhausted admissions instead of freezing the cursor
  • reviewed 2026-08-07T07:45:30.403Z sha 92da25f :: needs real behavior proof before merge. :: [P1] Do not admit a later event while a parked predecessor still fails
  • reviewed 2026-08-07T07:53:59.633Z sha 92da25f :: needs real behavior proof before merge. :: [P1] Keep later events behind a parked predecessor
  • reviewed 2026-08-07T08:47:40.007Z sha 39a4a19 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-07T09:40:47.397Z sha 39a4a19 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-14T10:28:23.319Z sha 39a4a19 :: found issues before merge. :: [P1] Use the shared ingress monitor instead of a Matrix lifecycle fork
  • reviewed 2026-08-15T07:49:19.094Z sha 39a4a19 :: needs changes before merge. :: [P1] Use the shared ingress monitor instead of a Matrix lifecycle fork
  • reviewed August 16, 2026, 5:31 AM ET / 09:31 UTC sha unknown :: found issues before merge. :: [P1] Reuse the shared ingress monitor

@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/matrix-ingress-durability branch from 7afc49f to 31969b0 Compare July 18, 2026 14:41
@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. labels Jul 18, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressing the [P1] real-behavior-proof finding on new head c31a2d953d (CI-fix rebase 31969b0436 + the handler drop-exemption this proof itself surfaced).

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

  • Real MatrixClient (extensions/matrix/src/matrix/sdk.ts) over matrix-js-sdk 41.9.0-rc.0, built through the production factory createMatrixClient (extensions/matrix/src/matrix/client/create-client.ts) with the documented operator opt-in for a loopback homeserver (dangerouslyAllowPrivateNetwork, the same flag channels.matrix.dangerouslyAllowPrivateNetwork maps to).
  • Real registerMatrixMonitorEvents (monitor/events.ts) — the exact listener wiring this PR changes.
  • Real createMatrixIngressMonitor (monitor/ingress.ts) over the real shared channel_ingress_events queue (createChannelIngressQueue, src/channels/message/ingress-queue.ts) on a real state/openclaw.sqlite.
  • Real SqliteBackedMatrixSyncStore (250 ms-debounced token persist) — the "ack" the journal must beat.
  • A ~120-line Node http stub homeserver on 127.0.0.1 speaking just enough client-server API for matrix-js-sdk startup and long-poll sync (endpoints below).
  • A parent watcher that polls the SQLite DB / driver log and sends real SIGKILL to the gateway process, then starts a brand-new process on the same state dir.
  • Tested event class: plain unencrypted m.room.message (E2EE off, matching the default config). The E2EE boundary is unchanged by this PR and already documented in the PR body: encrypted events are journaled when the decrypt bridge emits the decrypted event, so a crash between token persist and decryption still loses the still-encrypted event — that pre-decrypt window is the stated follow-up, out of scope here. The BEFORE/AFTER contrast below therefore covers only already-decrypted/plain room events.

AFTER (this PR, worktree @ 31969b0436)

=== PHASE 1: fresh gateway process; agent turn in flight; kill -9 AFTER the 250ms-debounced sync-token persist ===
[driver] client created; hasPersistedSyncState=false
[journal] enqueue id=$create-1 -> kind=accepted duplicate=false
[journal] enqueue id=$mem-bot -> kind=accepted duplicate=false
[dispatch] claimed id=$create-1 ts=1784391696827 — agent turn in flight, blocking until kill -9
[journal] enqueue id=$mem-alice -> kind=accepted duplicate=false
[journal] enqueue id=$name-1 -> kind=accepted duplicate=false
[journal] enqueue id=$evt-proof-1 -> kind=accepted duplicate=false
[driver] sync ready; hasPersistedSyncState=false dispatchCount=1
[watcher] journal row visible; waiting 1200ms so the debounced sync-token persist lands before the kill
[watcher] sent SIGKILL to pid 933024
-- sqlite channel_ingress_events immediately after kill -9 (queue ["matrix","default"]):
$create-1    claimed  attempts=0  claim_owner=933024:... (owner pid is dead)
$mem-bot     pending  attempts=0
$mem-alice   pending  attempts=0
$name-1      pending  attempts=0
$evt-proof-1 pending  attempts=0   <-- the inbound user message, durable before the kill

=== PHASE 2: new gateway process, same state dir (cross-process kill -9 restart) ===
[driver] client created; hasPersistedSyncState=false
[dispatch] replayed id=$evt-proof-1 ts=1784391696827 body="prove ingress durability" preStartup=true — adopting turn
[dispatch] adopted id=$evt-proof-1; journal row completed
[journal] enqueue id=$evt-proof-1 -> kind=completed duplicate=true   <-- sync-cache replay of the same event deduped
[driver] final summary: dispatchCount=5
(... the 4 room-state events replay+adopt the same way, in room-lane order ...)
-- stub homeserver view (phase 1 consumed batches through since=s5; after kill -9 the new process'
-- FIRST request is since=s4 = the persisted token; no second INITIAL /sync, batch never re-served):
[stub] /sync since=s4 -> empty batch next_batch=s5   (phase 1, before kill)
[stub] /sync since=s5 -> empty batch next_batch=s6   (phase 1, last before kill -9)
[stub] /sync since=s4 -> empty batch next_batch=s7   (phase 2 first request: resumed from persisted token s4)
-- sqlite channel_ingress_events after restart replay:
$create-1    completed  attempts=1  (stale claim from dead pid recovered, then adopted)
$mem-bot     completed  attempts=0
$mem-alice   completed  attempts=0
$name-1      completed  attempts=0
$evt-proof-1 completed  attempts=0  <-- exactly-once: replayed once, adopted once, tombstoned

BEFORE (origin/main @ 593423e, same harness, same kill timing, main's detached-dispatch wiring)

=== PHASE 1: fresh gateway process; detached dispatch in flight; kill -9 AFTER the debounced sync-token persist ===
[driver] client created; hasPersistedSyncState=false
[dispatch] delivered id=$evt-proof-1 ts=1784391833378 body="prove ingress durability" — detached in-memory dispatch, agent turn in flight, blocking
[driver] sync ready; hasPersistedSyncState=false dispatchCount=5
(all 5 batch events were delivered into memory-only detached dispatches; nothing was journaled)
[watcher] log pattern seen: blocking; waiting 1200ms so the debounced sync-token persist lands
[watcher] sent SIGKILL to pid 955006
-- sqlite channel_ingress_events immediately after kill -9:
(state DB missing: nothing durable was ever written for this event)

=== PHASE 2: new gateway process, same state dir ===
[driver] client created; hasPersistedSyncState=false
[dispatch] re-delivered id=$evt-proof-1 ts=1784391833378 body="prove ingress durability" preStartup=true processStartupMs=1784391835113
[driver] final summary: dispatchCount=5
-- stub homeserver view (phase 1 consumed batches through since=s5; after kill -9 the new process'
-- FIRST request is since=s4 = the persisted token; no second INITIAL /sync, batch never re-served):
[stub] /sync since=s4 -> empty batch next_batch=s5   (phase 1, before kill)
[stub] /sync since=s5 -> empty batch next_batch=s6   (phase 1, last before kill -9)
[stub] /sync since=s4 -> empty batch next_batch=s7   (phase 2 first request: resumed from persisted token s4)
-- sqlite channel_ingress_events after restart:
(state DB missing: still 0 durable rows anywhere)

=> the ONLY post-restart delivery is the local sync-cache replay (preStartup=true).
=> production main computes dropPreStartupMessages=true here (hasPersistedSyncState=false after
   kill -9, monitor/index.ts:344) and the handler discards pre-startup events (handler.ts:639-647),
   so no agent turn ever runs again for $evt-proof-1; the homeserver will not redeliver (token
   advanced past it). No journal exists to replay. The message is permanently lost.

What this demonstrates

  • Durable-before-ack: on the PR branch the journal rows commit inside the sync event listener (enqueue -> kind=accepted), before the 250 ms-debounced sync-token persist can tell the homeserver the batch is consumed; on main nothing durable exists at the same point (no state DB at all).
  • Stale-claim recovery: the kill -9'd owner's claimed row (claim_owner=933024:...) is recovered by the new process and redispatched (attempts=1 on $create-1), then adopted and tombstoned.
  • Exactly-once completion: each journaled event is dispatched once and lands exactly one completed tombstone; the sync-cache replay of the same event after restart enqueues as kind=completed duplicate=true and never dispatches a second time.
  • The homeserver side never re-serves the batch in either run (restart syncs resume at the persisted token, since=s4), so on main the loss is permanent: the only re-delivery there is the local sync-cache replay, which the pre-startup drop discards.

Stub homeserver endpoints (all that matrix-js-sdk requested)

GET /_matrix/client/versions, GET /_matrix/client/v3/pushrules/, POST /_matrix/client/v3/user/{id}/filter, GET /_matrix/client/v3/sync (first no-since sync serves one m.room.message in !room:example.org + room state; incremental syncs return empty batches), GET /_matrix/client/v3/account/whoami, plus a GET /_matrix/client/v3/capabilities the SDK also issues (answered by the catch-all 200 {}); account-data/state endpoints return realistic 404 M_NOT_FOUND.

Proof mechanics: driver + stub + watcher are throwaway scripts in /tmp (not in the PR). The driver plays the gateway host: it injects the matrix plugin runtime with the same real core helpers the host uses (resolveStateDir, createPluginStateKeyedStore/createPluginStateSyncKeyedStore, state.openChannelIngressQueue), and registers the real monitor event wiring. The dispatch callback stands exactly where production injects handleRoomMessage (monitor/index.ts:467-469); in PHASE 1 it blocks like an in-flight agent turn, in PHASE 2 it calls lifecycle.onAdopted(), the same adoption seam the handler threads into core.channel.inbound.run via bindIngressLifecycleToReplyOptions. The queue is wrapped in a transparent Proxy that only logs enqueue results.


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 createMatrixRoomMessageHandler (with dropPreStartupMessages computed exactly as monitor/index.ts:350 does, startupGraceMs=0 as in index.ts:307). The first probe run exposed a real gap in the original diff: after an unclean shutdown hasPersistedSyncState() is false, so dropPreStartupMessages=true, and the pre-existing pre-startup drop (handler.ts:645) also caught journaled replays — events that by construction were never adopted — tombstoning them without an agent turn:

=== PROBE BEFORE the handler fix (kill -9 restart; drain replays into the REAL handler) ===
[probe] dropPreStartupMessages=true (from hasPersistedSyncState=false) startupMs=1784392513141
[probe] real handler invoked for id=$evt-proof-1 ts=1784392511301 body="prove ingress durability" preStartup=true
[probe] handler returned WITHOUT reaching the agent turn for id=$evt-proof-1 (dropped by a pre-turn policy gate)
-- sqlite afterwards: $evt-proof-1 status=completed  (tombstoned WITHOUT an agent turn)
(directTracker.isDirectMessage — the first seam past the pre-startup drop — was never reached)

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 handler.ts:645 (if (dropPreStartupMessages && !ingressLifecycle)), and the same probe against the fixed tree shows the full end-to-end recovery with the real handler:

=== PROBE AFTER the handler fix (same kill -9 scenario, real handler, fixed working tree) ===
[probe] dropPreStartupMessages=true (from hasPersistedSyncState=false) startupMs=1784394936960
[probe] real handler invoked for id=$evt-proof-1 ts=1784394934901 body="prove ingress durability" preStartup=true
[probe] event SURVIVED the pre-startup drop (reached directTracker.isDirectMessage)
[probe] core.channel.inbound.run reached — turnAdoptionLifecycle present=true admission=exclusive
[probe] agent turn for text="prove ingress durability"; adopting via turnAdoptionLifecycle.onAdopted()
[probe] turn adopted; agent turn complete
[probe] handler returned for id=$evt-proof-1
[journal] enqueue id=$create-1 -> kind=completed duplicate=true
[journal] enqueue id=$mem-bot -> kind=completed duplicate=true
[journal] enqueue id=$mem-alice -> kind=completed duplicate=true
[journal] enqueue id=$name-1 -> kind=completed duplicate=true
[journal] enqueue id=$evt-proof-1 -> kind=completed duplicate=true   <-- sync-cache replay copy deduped
-- sqlite afterwards: all 5 rows status=completed
-- $evt-proof-1 completed attempts=0  (adopted exactly once on first replay)
-- $create-1    completed attempts=1  (stale claim from the kill -9'd owner recovered, then adopted)

So the kill -9 path now works end-to-end with the production handler: the journaled replay survives the pre-startup drop, reaches core.channel.inbound.run with turnAdoptionLifecycle (admission: "exclusive"), is adopted exactly once, the row tombstones, and the sync-cache replay of the same event enqueues as duplicate=true without a second dispatch. The probe's core facade implements only the host seams the real handler calls on a plain DM text path (mirroring monitor/handler.test-helpers.ts); the drop decision, the lifecycle threading, the drain, and the queue are all the production code in this PR.

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 event_id, dispatched via onUnjournaledEvent without a lifecycle). Cold-start backlog dropping for unidentifiable events is unchanged.

@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper could not start a re-review for this item.

Reason: re-review requires an open issue or PR.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 18, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Exact-head re-run of the live kill -9 proof on 7b85908dc9 (the current head: 2eaedcddd0 journal + c5fc971e4e handler drop-exemption + 7b85908dc9 test-shape fix), addressing the [P1] "proof must cover the replay-drop behavior on the exact head" finding. Same harness as the previous comment (real MatrixClient via the production factory, real registerMatrixMonitorEvents, real createMatrixIngressMonitor over the real shared channel_ingress_events queue on a real SQLite state DB, real SqliteBackedMatrixSyncStore, ~120-line stub homeserver, parent watcher sending real SIGKILL). The CI red on the prior head was a test-only TypeScript shape error ({ onAdopted } stub missing the other lifecycle fields, handler.test.ts); fixed in 7b85908dc9, check-test-types lane green locally, 123/123 handler.test.ts pass. The iOS scan failure was a runner toolchain error (expected Xcode 26.x) unrelated to this diff.

Tested event class: plain unencrypted m.room.message (E2EE boundary unchanged, as documented in the PR body).

Transcript 1 — monitor-level journal proof on 7b85908dc9

=== PHASE 1: fresh gateway process; agent turn in flight; kill -9 AFTER the 250ms-debounced sync-token persist ===
[driver] client created; hasPersistedSyncState=false
[journal] enqueue id=$create-1 -> kind=accepted duplicate=false
[journal] enqueue id=$mem-bot -> kind=accepted duplicate=false
[dispatch] claimed id=$create-1 — agent turn in flight, blocking until kill -9
[journal] enqueue id=$mem-alice / $name-1 / $evt-proof-1 -> kind=accepted duplicate=false
[watcher] journal row visible; waiting 1200ms so the debounced sync-token persist lands before the kill
[watcher] sent SIGKILL to pid 1785446
-- sqlite channel_ingress_events immediately after kill -9:
$create-1    claimed  attempts=0  claim_owner=1785446:... (owner pid is dead)
$mem-bot     pending
$mem-alice   pending
$name-1      pending
$evt-proof-1 pending   <-- the inbound user message, durable before the kill

=== PHASE 2: new gateway process, same state dir (cross-process kill -9 restart) ===
[dispatch] replayed id=$create-1 preStartup=true — adopting turn
[dispatch] adopted id=$create-1; journal row completed
(... all 5 events replay+adopt the same way, in order ...)
[journal] enqueue id=$evt-proof-1 -> kind=completed duplicate=true   <-- sync-cache replay deduped
[driver] final summary: dispatchCount=5
-- sqlite channel_ingress_events after restart replay:
$create-1    completed  attempts=1  (stale claim from dead pid recovered, then adopted)
$mem-bot     completed  attempts=0
$mem-alice   completed  attempts=0
$name-1      completed  attempts=0
$evt-proof-1 completed  attempts=0  <-- exactly-once: replayed once, adopted once, tombstoned

Transcript 2 — the replay-drop path with the REAL production handler on 7b85908dc9

Same kill -9 scenario, but phase 2 drains into the real createMatrixRoomMessageHandler with dropPreStartupMessages computed exactly as monitor/index.ts does (hasPersistedSyncState=false after the unclean shutdown → true). This is the path head commit c5fc971e4e changes (handler.ts: if (dropPreStartupMessages && !ingressLifecycle)):

=== PROBE PHASE 1: journal + blocked dispatch + kill -9 (identical shape to Transcript 1) ===
[watcher] sent SIGKILL to pid 1792368
-- sqlite after kill -9: $create-1 claimed by dead pid; 4 rows pending incl. $evt-proof-1

=== PROBE PHASE 2: restart; drain replays into the REAL handler ===
[probe] dropPreStartupMessages=true (from hasPersistedSyncState=false) startupMs=1784397821016
[probe] real handler invoked for id=$evt-proof-1 body="prove ingress durability" preStartup=true
[probe] event SURVIVED the pre-startup drop (reached directTracker.isDirectMessage)
[probe] core.channel.inbound.run reached — turnAdoptionLifecycle present=true admission=exclusive
[probe] agent turn for text="prove ingress durability"; adopting via turnAdoptionLifecycle.onAdopted()
[probe] turn adopted; agent turn complete
[journal] enqueue id=$evt-proof-1 -> kind=completed duplicate=true   <-- sync-cache replay copy deduped
-- sqlite afterwards: all 5 rows status=completed
-- $evt-proof-1 completed attempts=0  (adopted exactly once on first replay)
-- $create-1    completed attempts=1  (stale claim from the kill -9'd owner recovered, then adopted)

So on the exact head 7b85908dc9: the journaled replay survives the pre-startup drop (the behavior c5fc971e4e adds), reaches core.channel.inbound.run with turnAdoptionLifecycle (admission: "exclusive"), is adopted exactly once, tombstones, and the sync-cache replay of the same event enqueues as duplicate=true without a second dispatch. The BEFORE (origin/main) transcript from the previous comment is unchanged: nothing journaled, the only post-restart delivery is the pre-startup-dropped sync-cache replay, message permanently lost.

Stub homeserver endpoints (all that matrix-js-sdk requested): GET /_matrix/client/versions, GET /_matrix/client/v3/pushrules/, POST /_matrix/client/v3/user/{id}/filter, GET /_matrix/client/v3/sync (first no-since sync serves one m.room.message + room state; incrementals return empty batches), GET /_matrix/client/v3/account/whoami, plus GET /_matrix/client/v3/capabilities (catch-all 200 {}); account-data/state endpoints return realistic 404 M_NOT_FOUND. Driver/stub/watcher are throwaway scripts in /tmp, not in the PR.

@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/matrix-ingress-durability branch from c31a2d9 to 7b85908 Compare July 18, 2026 18:49
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@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 7b85908dc9.

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 7b85908dc9, covering both the monitor-level journal path and the real-handler replay-drop path (dropPreStartupMessages && !ingressLifecycle) with the production handler.

@clawsweeper

clawsweeper Bot commented Jul 18, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 18, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/matrix-ingress-durability branch from 7b85908 to 41ea682 Compare July 21, 2026 16:20
@clawsweeper

clawsweeper Bot commented Jul 21, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 7, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. labels Aug 7, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

P1 finding addressed on new head 92da25f84e.

Finding: retry exhausted admissions instead of freezing the cursor

Root cause: admitOnce dropped the event after its three live retries and set a sticky admissionFailure that nothing could clear, so the sync store rejected every later cursor flush until restart — and the dropped event was neither journaled nor dispatched.

Fix in extensions/matrix/src/matrix/monitor/ingress.ts:

  • Exhausted admissions are now parked (parkedAdmissions) instead of dropped, keeping the event, its facts, and its original receivedAt.
  • Parked admissions are retried on every drain poll (single attempt each, driven by the existing 1s poll timer via requestDrain → scheduleAdmissionRetry) and at the head of every later accept, so a recovered queue can never append a later event ahead of an earlier parked one.
  • The failure gate stays non-null while anything remains parked, so the cursor stays frozen behind the event exactly as before; it clears automatically once the parked append lands — a transient SQLite lock now recovers with no restart, while a genuinely dead journal still freezes the cursor for restart redelivery.

Regression coverage:

  • New ingress.test.ts case: exhaust retries with a rejecting enqueue, recover the queue, start() the monitor — the parked event is journaled on a later poll, dispatched exactly once, and getAdmissionFailure() clears.
  • Existing store-side test already proves the freeze lifts when the gate reports healthy again (file-sync-store.test.ts "refuses to advance the cursor past a permanently failed admission").

Validation (remote box): full matrix suite 122 files / 1944 tests green, tsgo extensions test types clean for matrix.

@clawsweeper

clawsweeper Bot commented Aug 7, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 7, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

P1 finding addressed on new head 39a4a19492, with fresh exact-head real-behavior proof for both the crash/replay path and the parked-admission recovery path.

Finding (P1): later event admitted while a parked predecessor still fails

Root cause: accept chained retryParkedAdmissions() but then ran admitOnce unconditionally. If the parked retry failed, the newer event still attempted its own journal append; a successful append would land in the queue while the older same-room event had no row, and the drain (which can only order persisted rows) would dispatch the room out of order.

Fix (39a4a19492, extensions/matrix/src/matrix/monitor/ingress.ts): admitOnce now checks the parked tail before touching the journal — while any admission is parked, the newer event queues behind it in parkedAdmissions without a journal attempt, and the poll-driven retry lands both in accept order. The admission flow is now a strict single chain: journal rows always appear in accept order, even while the queue keeps failing.

Regression test (ingress.test.ts): queues a later same-room event behind a still-failing parked predecessor — the older event's appends fail and it parks; while the queue stays unhealthy the newer event must produce zero journal attempts for itself and no queue rows; after recovery the drain dispatches [older, newer] in order and the failure gate clears. Verified red against the pre-fix head (the newer event reached enqueue while the predecessor was parked) and green with the fix.

Fresh exact-head real-behavior proof (both transcripts on 39a4a19492)

Same production-component harness as the accepted earlier proof: real MatrixClient via the production factory, real registerMatrixMonitorEvents, real createMatrixIngressMonitor over the real shared channel_ingress_events queue on a real SQLite state DB, real SqliteBackedMatrixSyncStore with the admission gate wired, stub homeserver on 127.0.0.1, tsx so every touched file executes from current source.

Proof 1 (new): parked-admission recovery under a real SQLite write lock

A second process holds BEGIN IMMEDIATE on the state DB while the homeserver serves two same-room events; the lock releases only after the first event parks.

=== PHASE P2: second process holds a real SQLite write lock; stub serves $evt-park-a then $evt-park-b ===
[watcher] DB write lock held (BEGIN IMMEDIATE on .../state/state/openclaw.sqlite)
[watcher] persisted sync token at lock time: s15
matrix ingress: failed to durably journal inbound event room=!room:example.org id=$evt-park-a: database is locked
[watcher] $evt-park-a parked (live retries exhausted)
-- sqlite channel_ingress_events while the lock is still held:
(0 rows)                                          <-- $evt-park-b never reached the journal behind its parked predecessor
-- persisted sync token while locked: s15         <-- cursor frozen by the admission gate
=== PHASE P3: lock released; the drain poll must land both rows in accept order ===
[watcher] lock released (COMMIT)
[journal] enqueue id=$evt-park-a -> kind=accepted duplicate=false
[journal] enqueue id=$evt-park-b -> kind=accepted duplicate=false
[dispatch] delivered id=$evt-park-a body="first: parked predecessor" — adopting turn
[dispatch] adopted id=$evt-park-a; journal row completed
[dispatch] delivered id=$evt-park-b body="second: must not overtake" — adopting turn
[dispatch] adopted id=$evt-park-b; journal row completed
[proof] driver exited code=0
-- sqlite channel_ingress_events after recovery:
$evt-park-a    completed
$evt-park-b    completed                          <-- journal and dispatch order both match accept order
-- persisted sync token after recovery: s22       <-- cursor unfreezes without a restart

Proof 2 (rerun): cross-process SIGKILL crash/replay on the exact head

=== PHASE 1: fresh gateway process; agent turn in flight; kill -9 AFTER the 250ms-debounced sync-token persist ===
[journal] enqueue id=$evt-proof-1 -> kind=accepted duplicate=false
[dispatch] claimed id=$evt-proof-1 — agent turn in flight, blocking until kill -9
[watcher] sent SIGKILL to pid 8360
-- sqlite channel_ingress_events immediately after kill -9:
$evt-proof-1   claimed    attempts=0  claim_owner=8360:... (owner pid is dead)
=== PHASE 2: new gateway process, same state dir (cross-process kill -9 restart) ===
[dispatch] delivered id=$evt-proof-1 body="prove ingress durability" — adopting turn
[dispatch] adopted id=$evt-proof-1; journal row completed
[journal] enqueue id=$evt-proof-1 -> kind=completed duplicate=true   <-- sync-cache replay deduped
[driver] final summary: dispatchCount=1
-- sqlite channel_ingress_events after restart replay:
$evt-proof-1   completed  attempts=1   <-- stale claim recovered, adopted once, tombstoned
-- stub homeserver view: phase 2's first /sync is since=s14 (the persisted token); the batch is never re-served

Validation

All on head 39a4a19492 (node scripts/run-vitest.mjs):

  • extensions/matrix full suite — 122 files / 1945 tests green (includes ingress.test.ts 12/12 with the new ordering regression)
  • New regression test red-checked against the pre-fix ingress.ts (fails: newer event reaches the journal while parked) and green with the fix
  • tsgo extensions prod + test-types: no matrix errors (the 6 rejectSymlinks/ansi.ts errors in terminal-core/fs-bridge/includes/control-ui/workspace/local-loader are pre-existing main drift, unrelated to this PR)

@clawsweeper

clawsweeper Bot commented Aug 7, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 7, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 15, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Before I start the refactor onto createChannelIngressMonitor requested in the latest review, one design question for @steipete (author of the shared monitor):

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:

  1. move into createChannelIngressMonitor as an opt-in capability (e.g. an admission-failure mode), so other channels with cursor-like gates can share it, or
  2. stay channel-side, rebuilt on top of the shared monitor's onAdmissionFailure hook, with Matrix keeping its own parked queue and ordering?

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.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

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.

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: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL 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