Skip to content

fix: keep queued channel recovery replies alive - #201554

Merged
tideclaw-bot merged 9 commits into
mainfrom
openclaw/crisp-claw
Nov 22, 2026
Merged

tideclaw-bot merged 9 commits into
mainfrom
openclaw/crisp-claw

Conversation

@RomneyDa

@RomneyDa RomneyDa commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Related: #191476

What Problem This Solves

Matrix recovery can lose a reply when the original turn releases its channel consumer before a queued follow-up invokes retained callbacks. A real Matrix/live-model reproduction failed with Plugin matrix consumer is closed during recovery.

User Impact

Queued recovery replies remain deliverable after the original turn ends. Closed-consumer and operator-authority checks remain strict. No configuration or schema changes are required.

Why This Change Was Made

Give queued callbacks their own consumer lifetime, independent of one-shot ingress adoption. Release that lifetime through queue-source settlement, retain all contributing consumers when collecting follow-ups, and preserve custody through overflow compaction. Recovery acquires fresh custody rather than reusing the original ingress cancellation identity. Restore same-owner values before copying prewrapped reply options so native cancellation signals retain their identity.

Evidence

  • Real baseline Matrix/live-model recovery reproduced the closed-consumer error; the first failing callback was onModelSelected.
  • The fixed real-model scenario triggered private-final recovery, delivered the visible marker exactly once, and produced no repeat during the following eight seconds.
  • Initial proof: 134 focused tests and 28 sibling tests passed; after test-file extraction, 90 affected tests passed. Core typecheck, targeted lint, formatting, build, docs checks, line-cap ratchet, and diff checks passed.
  • Independent and canonical local review found no remaining actionable P0–P2 issues after collection/overflow propagation fixes.
  • CI exposed a type-import cycle. Moving the callback contract into a dependency-free leaf produced zero Madge cycles and 47 passing focused tests. The subsequent CI architecture gate passed at 09e9c9d5c5ba1b2456c54a0811abb55c91f9a259.
  • CI also caught three import-order formatting errors; repository formatting fixed them. Both docs and lint failures in that run originated from these same import blocks; all docs content checks passed.
  • CI job 135274685539 exposed an introduced prewrapped-options regression: AbortSignal.any rejected a proxied signal. The existing delivery-custody suite passed 14/14 on frozen base, failed 1/14 on the candidate, and passed after restoring native option values before copying. Expanded the focused identity test to include prewrapped options; both files now pass 31/31 tests (59.36s wrapper wall time including compiler preparation; 57.37s Vitest duration). Targeted lint and formatting pass. Fresh independent review found no P0–P2 findings and confirmed callback fencing remains intact.
  • At head 333f2682172dd9ee3f2fa1a461cfa854d7287448, CI passes architecture, docs, lint, production/test types, and the delivery-custody test shard. ClawSweeper reviewed this exact head and reported no actionable findings.
  • November 22 maintainer review: a fresh independent review of all 14 changed files found no actionable P0–P2 issues, including retention/release, collected and overflow sources, native signal identity, and authority boundaries.

Retained real Matrix proof — sanitized excerpts

The isolated official Matrix plugin/live-model run used frozen base d6f628897ad7830e7cd54063c18de41c9c4cc73e. Baseline occurrence 70079534-2004-4f61-a67f-37c0d9ec1314 timed out after recovery hit the released consumer. IDs, local paths and model/provider details are omitted below; no message content or credentials are included.

2026-11-19T00:55:19.460+00:00 [source-reply/private-final]
agent produced a private final reply without calling the configured delivery tool
(message_tool_only); response kept private and not delivered to the source channel
channel=matrix chars=2924
2026-11-19T00:55:19.621+00:00 [turn/execution]
visible channel turn dispatched with no queued reply payloads: channel=matrix cause=completed
2026-11-19T00:55:19.900+00:00 Error: Plugin matrix consumer is closed

Fixed occurrence 40d72565-7593-4cce-b9bf-823e4be426c1, from the reviewed original production repair before subsequent CI-driven corrections:

2026-11-19T01:17:33.913+00:00 [source-reply/private-final]
agent produced a private final reply without calling the configured delivery tool
(message_tool_only); response kept private and not delivered to the source channel
channel=matrix chars=2671
scenario: Matrix custody real-model diagnostic — pass
Prepare Matrix live — pass
recovers a substantive private final through one message tool retry — pass
recovered=1; WARN logged=true
scenario counts: passed=1 failed=0 skipped=0 total=1
QA scenarios passed, but cleanup failed

The scenario requires the private-final warning, asserts exactly one matching outbound marker, waits 8000ms, and asserts the count remains one. A direct first-answer send cannot satisfy this proof. Live provider-request counters were unavailable and are not evidence of request counts. The cleanup limitation is detailed below; the live scenario was not rerun on the later CI-correction head.

CI Failure Classification

CI run 44440362497, attempt 1, completed with four failed runtime jobs. These three signatures reproduce on frozen base d6f628897ad7830e7cd54063c18de41c9c4cc73e; none of their test files was changed:

  • src/gateway/operator-run-cancellation.test.ts:265: two accepted-turn cases expect device revocation to throw, but it does not. Base and candidate each report 2 failed / 16 passed; repeated in current-run job 135280128892.
  • src/gateway/server-plugins.user-profile.test.ts:143: role-lifetime case expects rejection, but resolves undefined. Base reproduces 1 failed / 3 passed; repeated in current-run job 135280128930.
  • test/cron-message-read.integration.test.ts:727: the claude-cli/channel-edit/native, disabled before undefined case lacks toolsAllowProvenance.channelRequester. Frozen-base targeted run reproduces the exact missing-field assertion: 1 failed / 8 skipped, 33.07s Vitest duration (37.79s wrapper). Current-run job 135280128752 has the same signature. This is not introduced by the Matrix patch.

Job 135280128915 fails test/gateway-restart-resume.e2e.test.ts because the yielded parent receives a child shutdown-completion input instead of RESUMED_0_parent. CI tested merge eb1e725093ef48832a1a6e36f0b771b16c4fbadb, with ordered parents 053fb62c6141c801fdd0f9bb2dfc3060a6fed912 and this PR head. That base includes #201544 (82e52b648cf0), which intentionally replaces quiet child shutdown with retained error completion, while the unchanged fixture expects a generic parent resume.

November 22 attribution update: upstream #201757 (cb04fefe4f3a6db0bdf60faf421af93f91b21636), already on main, explicitly corrects this same fixture to require HANDLED_NEW_INPUT, exactly one child-identifying status: error: Gateway stopped completion, and zero generic parent resumes. Inspection confirms all four failing test inputs are unchanged between the CI baseline and tested merge. The restart failure is therefore attributed to the upstream stale expectation, not this callback-lifetime repair. This is source-based attribution, not a claim that the Matrix patch fixed restart recovery.

A fresh exact-baseline local replay built successfully, but its first selected case timed out after 180 seconds with loopback AI-fixture connection failures. The remaining replay was stopped; this attempt does not corroborate the restart signature or establish passing integration proof. The earlier frozen-base setup failure is likewise not runtime evidence.

No assertions, baselines, or authority checks were weakened. CI remains red; passing gates are not a claim that all checks passed. Native inherited-failure admission must independently verify exact-head CI, security, required reviews, source inputs, and current writer authority.

Limits and Cleanup

The real Matrix scenario passed, but its QA process exited 1 during rootless Podman cleanup. Task-owned containers and networks were subsequently removed and the private service stopped; this is not reported as a wholly green QA command.

The original image/completion-plus-inbound overlap and encrypted Matrix transport were not separately exercised. This PR addresses the reproduced shared callback-lifetime failure, rather than claiming every report in #191476 is resolved.

OpenClaw-Publication: ab2da49a-e2b9-421a-973c-7b93a3b14108
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

RomneyDa and others added 2 commits November 19, 2026 01:24
OpenClaw-Publication: 901a8578-1d72-433e-985b-4687c184be00
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation plugin: file-transfer size: M and removed size: XS labels Nov 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 19, 2026
RomneyDa and others added 4 commits November 19, 2026 01:38
Move the unchanged callback symbol and type to a dependency-free leaf to remove the CI-reported type import cycle.

Co-authored-by: RomneyDa <[email protected]>
OpenClaw-Publication: bd55977b-001c-4a92-b2ba-7421ff48b959
Apply the repository formatter to the three import blocks reported by CI.

Co-authored-by: RomneyDa <[email protected]>
OpenClaw-Publication: 34fcdd84-be75-4f78-be29-1b5159e995fe
RomneyDa and others added 2 commits November 19, 2026 01:53
Restore same-owner option values before copying callback custody metadata. This preserves native AbortSignal identity while keeping callbacks consumer-bound.

CI delivery-custody regression reproduced on the candidate (1/14 failed), passed on frozen base, and now passes with the fix. Expanded the focused identity test for prewrapped options; all 31 tests pass. Independent review found no P0-P2 issues.

Co-authored-by: RomneyDa <[email protected]>
OpenClaw-Publication: eb6ba022-f466-439f-8fe0-28260e56ff91
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR retains channel callbacks independently of ingress adoption until queued work settles.

Example: A Matrix message-tool-only turn produces “The answer is ready.” without sending it, triggering native delivery recovery.

  • Before: The parent consumer closes and the recovery callback throws “Plugin matrix consumer is closed.”
  • After: The recovery retains its own callback hold until settlement.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is coherent, but the supplied evidence does not yet support a merge-ready verdict.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Queued recovery can fail before sending an otherwise available channel reply.
Reason: The maintainer-authored direction repairs a reported shared lifecycle defect and appropriately uses Related rather than claiming the broader linked issue is resolved.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a concrete callback-lifetime failure still present on main; source review found no actionable introduced bug, while current-head CI remains unresolved.

Priority: P1
Reviewed head: 333f2682172dd9ee3f2fa1a461cfa854d7287448

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Attach the retained Matrix recovery logs or terminal capture showing parent completion followed by successful recovery delivery, with IPs, credentials, phone numbers, and non-public endpoints redacted, and identify the recovery regression's base-red/head-green result.
Agent review details

How this fits together

The plugin runtime binds channel callbacks, reply preparation carries them into queued runs, and session-controller source settlement releases their consumer holds.

flowchart TD
  A[Channel inbound dispatch] --> B[Plugin consumer]
  B --> C[Reply preparation]
  C --> D[Queued source]
  D --> E[Recovery or collected execution]
  E --> F[Source settlement]
  F --> B
Loading

Technical review

Best possible solution:

Keep callback retention on the existing queue-source lifecycle while preserving separate ingress cancellation identity and strict closed-consumer guards.

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

Source exposes the recovery lifetime mismatch and the linked discussion supplies a concrete reproduction, but this read-only review performed no runtime reproduction.

Is this the best way to solve the issue?

The patch repairs the shared lifetime owner, preserves collection and overflow contributors, and removes the superseded adoption-coupled release path without weakening consumer guards.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 60ab51294944.

Provenance checked

  • Channel callback consumer retention changes intended behavior with a stated reason (b9f1750: Queued A2A replies needed their original task callbacks alive through settlement, while immediate dispatch retained its consumer until return.)
  • Top-level ingress adoption binding changes intended behavior with a stated reason (1f161cf: Matrix's selected top-level lifecycle bypassed the resolved-turn custody wrapper; the earlier repair bound retention at that selection point.)
  • Queue-source settlement ownership keeps the original intent (36e277d: The session-controller refactor established one owner for source custody and settlement; the patch adds callback release to that existing owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Wesley: Raw commit b9f1750 adds src/plugins/runtime/runtime-channel.ts:184 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b9f17505b630; files: src/plugins/runtime/runtime-channel.ts)

PR surface

Source +26, Tests +90, Docs +4. Total +120 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 9 66 40 +26
Tests 4 188 98 +90
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 258 138 +120

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test changes Production +66/-40; tests +188/-98 The production growth carries independent callback holds through existing owners; test growth covers recovery, collection, rejected enqueue cleanup, and native signal identity.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Closed channel consumers can prevent queued recovery replies from reaching users, with related failures reported on the current stable release.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

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

Workflow

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

Reviewed November 18, 2026, 9:10 PM ET / November 19, 2026, 02:10 UTC.

@tideclaw-bot
tideclaw-bot merged commit 3a4f6b7 into main Nov 22, 2026
168 of 174 checks passed
@tideclaw-bot
tideclaw-bot deleted the openclaw/crisp-claw branch November 22, 2026 06:24
@tideclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
* fix: keep queued channel recovery replies alive

OpenClaw-Publication: ab2da49a-e2b9-421a-973c-7b93a3b14108

* fix: keep queued channel recovery replies alive

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: 901a8578-1d72-433e-985b-4687c184be00

* fix: isolate queued callback custody contract

Move the unchanged callback symbol and type to a dependency-free leaf to remove the CI-reported type import cycle.

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: bd55977b-001c-4a92-b2ba-7421ff48b959

* style: normalize callback custody imports

Apply the repository formatter to the three import blocks reported by CI.

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: 34fcdd84-be75-4f78-be29-1b5159e995fe

* fix: preserve native signals in prewrapped channel options

Restore same-owner option values before copying callback custody metadata. This preserves native AbortSignal identity while keeping callbacks consumer-bound.

CI delivery-custody regression reproduced on the candidate (1/14 failed), passed on frozen base, and now passes with the fix. Expanded the focused identity test for prewrapped options; all 31 tests pass. Independent review found no P0-P2 issues.

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: eb6ba022-f466-439f-8fe0-28260e56ff91

---------

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
* fix: keep queued channel recovery replies alive

OpenClaw-Publication: ab2da49a-e2b9-421a-973c-7b93a3b14108

* fix: keep queued channel recovery replies alive

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: 901a8578-1d72-433e-985b-4687c184be00

* fix: isolate queued callback custody contract

Move the unchanged callback symbol and type to a dependency-free leaf to remove the CI-reported type import cycle.

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: bd55977b-001c-4a92-b2ba-7421ff48b959

* style: normalize callback custody imports

Apply the repository formatter to the three import blocks reported by CI.

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: 34fcdd84-be75-4f78-be29-1b5159e995fe

* fix: preserve native signals in prewrapped channel options

Restore same-owner option values before copying callback custody metadata. This preserves native AbortSignal identity while keeping callbacks consumer-bound.

CI delivery-custody regression reproduced on the candidate (1/14 failed), passed on frozen base, and now passes with the fix. Expanded the focused identity test for prewrapped options; all 31 tests pass. Independent review found no P0-P2 issues.

Co-authored-by: RomneyDa <[email protected]>

* Publish openclaw/crisp-claw

OpenClaw-Publication: eb6ba022-f466-439f-8fe0-28260e56ff91

---------

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 3a4f6b7)

Operator-requested 2026.11.10 stable backport (Dallin, 2026-11-24 04:15). Clean apply. Later main mentions: none.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Plugin session forks (`runForkedTurn`, `forkSession`; for example Better Prompt and Skill Workshop reviews) always ran on the built-in runtime. On a Claude CLI chat signed in with a Claude subscription:

- With only the CLI's own `claude` login, `runForkedTurn` failed with `No API key found for provider "claude-cli"`.
- With a Claude subscription token stored in OpenClaw, `runForkedTurn` sent the token to the Anthropic API directly, which bills metered extra usage instead of the plan (`cliBackendDispatch` notes in `run/params.ts`).
- `forkSession` refused every CLI runtime: `Session forks are not supported for CLI runtime claude-cli.`

OpenClaw already has one owner for "run this embedded run on the subscription CLI": `cliBackendDispatch: "subscription-auth"` (Active Memory's recall uses it). The fork owner opts into it; no new path:

- `runSessionFork` sets `cliBackendDispatch: "subscription-auth"`. Eligibility is unchanged: subscription (oauth/token) or unresolvable credentials go to the CLI; API keys keep the request replay and its prompt cache.
- Dispatch accepts the fork's in-memory conversation (`sessionManager`), and sends the CLI only the tools that may execute (`toolExecutionAllow`; an empty list is a tool-free run).
- Dispatch now picks the CLI account the way a new CLI session does. Before, it passed only an explicit pin, so a stored Claude token never reached the CLI (`Not logged in · Please run /login`); Active Memory recalls had the same gap.
- Runs that grant the plugin's own tools or set `maxTokens` keep the direct route: neither reaches a CLI process.
- Dispatch carries the run's policy facts to the CLI: a run under another session's policy (a fork's `sandboxSessionKey`) passes that session's entry, the requester fields and `internal_system` provenance into the CLI's Gateway tool grant, so restricted-sender limits apply to the fork as to the chat's own turns.

Accepted: a CLI fork starts a fresh CLI session with the conversation as context, so it does not reuse the chat's cache, and each fork leaves one Claude session file under `~/.claude/projects`, as Active Memory's CLI recalls already do. The source chat's native session is never resumed or written.

Permission modes (maintainer decision, now in `docs/gateway/permission-modes.md`): the `sessionRoot` boundary is enforced on the built-in runtime; CLI-backed chats use the CLI's own controls, and owner turns' Gateway tools are not limited to `sessionRoot`. Live, on a Claude CLI chat in `workspace` mode, an ordinary turn and a fork both read a file outside the workspace through `mcp__openclaw__read`, and the same chat on the built-in runtime refuses both with `Path escapes sandbox root`. A CLI fork therefore has the same file access as the chat's own CLI turns.

Not covered: Gemini CLI on a Google login (OpenClaw cannot limit its tools under OAuth), and harnesses that own their login with no limited one-shot turn (Copilot, Muse, `acp-*`).

Real product, tier source (`ocx src`), isolated foreground Gateway, no API key in the environment or auth store; profiles: Claude subscription setup token, ChatGPT OAuth, Grok OAuth. Each chat: one turn ("Remember PELICAN-42"), then forks through a probe plugin.

| Route | `runForkedTurn` `[read, ls]` | `forkSession` | `runForkedTurn` cache read |
|---|---|---|---|
| `claude-cli`, Claude token | `PELICAN-42 \| FORK-READ-OK 7f3a` (dispatched to Claude CLI) | `PELICAN-42` | 6,985 |
| ChatGPT OAuth, built-in | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (cache read 9,856) | 10,112 |
| Codex app-server | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (19,584) | 8,704 |
| Grok OAuth | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (1,152) | 1,152 |

- `main` on the same Claude chat: `runForkedTurn` ran on the Anthropic API with the token (cache read 0, cache write 23,872), `forkSession` refused.
- Every route: source transcript hash, message count and native binding unchanged; the Claude source session file holds only the chat's own turn.
- Better Prompt 0.2.2 (`start` → `take` through `plugins.sessionAction`) produced an improved prompt on the Claude CLI chat and on the ChatGPT chat.
- Dispatch tests: a fork runs on the CLI with only its own tools from its in-memory session; plugin tool grants and output caps keep the passthrough.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit b7bf937)

Release adaptation: retain staged Gateway permission-mode documentation and enforcement; omit the superseded upstream documentation exception.

Companions: #202941 and #202646 are present-equivalent (9ec8d08 and 087c816); #201554 is staged as 5647120. #202957 is not applicable (reverts a separate native-tools path). #204219, #203999, #203901, #203919, #203601 and #203271 are independent prewarm, lifecycle, recovery, review or default-routing changes; not required for the selected fork path.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 8a592a33b7866a1306c60468e4aaf2c9fb23a93f)
obviyus added a commit that referenced this pull request Nov 29, 2026
… handled (#208571)

Root cause: `extensions/matrix/src/matrix/client/file-sync-store.ts:118-120` replays the whole saved Matrix sync cache into ingress on every client start (Gateway restart, or the Matrix channel restart that a room join's config write triggers); `extensions/matrix/src/matrix/monitor/ingress.ts:136-142` only marks first-login events as history, so cached events are admitted as deliverable; their only guard is the event-ID replay tombstone (`src/channels/message/ingress-queue.ts:358-376`), which shared retention prunes after 30 days (`src/channels/message/ingress-monitor-owner.ts:16-17`), so the next restart answers month-old messages as new turns.

Fixes #191476 (the replay of old inbound reported on 2026.11.12). The closed-consumer failure from the original report was fixed by #201554.

## What Problem This Solves

After a Gateway restart or a Matrix room join, OpenClaw answered Matrix messages that were 30 to 60 days old as if they had just arrived. It only happened in quiet rooms whose last message was at least 30 days old. In the report, 32 replies went to stale messages over two days, the same two images were answered four times over two months, and a month-old instruction rewrote a spreadsheet.

## User Impact

Restarts and room joins no longer revive Matrix messages that were already handled. Messages that arrived but were not yet answered when the Gateway stopped are still answered once after restart, and messages that arrive while the Gateway is down are still answered. No action or migration is needed.

## Why This Change Was Made

Matrix stores each sync batch in durable ingress before saving its cursor, so everything in the saved sync cache was already admitted. Replaying the cache on startup is meant to find those existing rows (pending ones keep their delivery). Once a completed row's 30-day replay guard is pruned, the replay was creating a brand-new deliverable row instead. The plugin now classifies cached replay the way it already classifies first-login history: an existing row is left as is, and an event without a row is recorded as intentionally not delivered. Shared retention, storage and the ingress queue are unchanged.

## Evidence

Isolated Gateway from a built checkout, local tuwunel homeserver, deterministic OpenAI-compatible model fixture. The Gateway answers a message in two rooms, then restarts with only its own clock moved forward 31 days (so the hourly prune removes the replay guards), then gets a `channels.matrix.groups` config change, which restarts the Matrix channel like a room join does.

| Run | After the channel restart |
|---|---|
| main, +31 days | both 31-day-old events dispatched again (`message processed ... messageId=<old event>`), and the bot posted a new message in each quiet room |
| main, no clock change | nothing dispatched |
| this PR, +31 days | channel restarted, nothing dispatched, no new bot messages |

On main the replayed turn in this setup ends with `Input completion retry conflicts with the committed input`, because the same session still holds the original input, and the room gets "⚠️ OpenClaw couldn't finish this request". The reporter's month-old sessions produced full fresh replies instead.

Safety checks, same result on main and this PR:
- A message queued behind a running turn when the Gateway was killed with SIGKILL (its ingress row was `claimed`) is answered exactly once after restart.
- A message sent while the Gateway was down is answered exactly once after restart.

Regression test `handler.restart.test.ts` "does not answer a cached message again after its replay tombstone expires" (real sync store, SQLite ingress queue) fails on main with `$unadopted` dispatched twice and passes here.

Thanks @hartmark for the report, and @7s9ffcyjq5-lgtm for the detailed 2026.11.12 replay timeline.

Merge danger: two-way door. A revert restores the old classification; no stored state, schema or config changes. Blast radius: Matrix inbound only, at client start.

Observed proof lines: #208571 (comment)

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
… handled (#208571)

Root cause: `extensions/matrix/src/matrix/client/file-sync-store.ts:118-120` replays the whole saved Matrix sync cache into ingress on every client start (Gateway restart, or the Matrix channel restart that a room join's config write triggers); `extensions/matrix/src/matrix/monitor/ingress.ts:136-142` only marks first-login events as history, so cached events are admitted as deliverable; their only guard is the event-ID replay tombstone (`src/channels/message/ingress-queue.ts:358-376`), which shared retention prunes after 30 days (`src/channels/message/ingress-monitor-owner.ts:16-17`), so the next restart answers month-old messages as new turns.

Fixes #191476 (the replay of old inbound reported on 2026.11.12). The closed-consumer failure from the original report was fixed by #201554.

## What Problem This Solves

After a Gateway restart or a Matrix room join, OpenClaw answered Matrix messages that were 30 to 60 days old as if they had just arrived. It only happened in quiet rooms whose last message was at least 30 days old. In the report, 32 replies went to stale messages over two days, the same two images were answered four times over two months, and a month-old instruction rewrote a spreadsheet.

## User Impact

Restarts and room joins no longer revive Matrix messages that were already handled. Messages that arrived but were not yet answered when the Gateway stopped are still answered once after restart, and messages that arrive while the Gateway is down are still answered. No action or migration is needed.

## Why This Change Was Made

Matrix stores each sync batch in durable ingress before saving its cursor, so everything in the saved sync cache was already admitted. Replaying the cache on startup is meant to find those existing rows (pending ones keep their delivery). Once a completed row's 30-day replay guard is pruned, the replay was creating a brand-new deliverable row instead. The plugin now classifies cached replay the way it already classifies first-login history: an existing row is left as is, and an event without a row is recorded as intentionally not delivered. Shared retention, storage and the ingress queue are unchanged.

## Evidence

Isolated Gateway from a built checkout, local tuwunel homeserver, deterministic OpenAI-compatible model fixture. The Gateway answers a message in two rooms, then restarts with only its own clock moved forward 31 days (so the hourly prune removes the replay guards), then gets a `channels.matrix.groups` config change, which restarts the Matrix channel like a room join does.

| Run | After the channel restart |
|---|---|
| main, +31 days | both 31-day-old events dispatched again (`message processed ... messageId=<old event>`), and the bot posted a new message in each quiet room |
| main, no clock change | nothing dispatched |
| this PR, +31 days | channel restarted, nothing dispatched, no new bot messages |

On main the replayed turn in this setup ends with `Input completion retry conflicts with the committed input`, because the same session still holds the original input, and the room gets "⚠️ OpenClaw couldn't finish this request". The reporter's month-old sessions produced full fresh replies instead.

Safety checks, same result on main and this PR:
- A message queued behind a running turn when the Gateway was killed with SIGKILL (its ingress row was `claimed`) is answered exactly once after restart.
- A message sent while the Gateway was down is answered exactly once after restart.

Regression test `handler.restart.test.ts` "does not answer a cached message again after its replay tombstone expires" (real sync store, SQLite ingress queue) fails on main with `$unadopted` dispatched twice and passes here.

Thanks @hartmark for the report, and @7s9ffcyjq5-lgtm for the detailed 2026.11.12 replay timeline.

Merge danger: two-way door. A revert restores the old classification; no stored state, schema or config changes. Blast radius: Matrix inbound only, at client start.

Observed proof lines: #208571 (comment)

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit d692ddc)

Follow-up audit: No later same-path, PR-number or SHA references through be407a4.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
… handled (#208571)

Root cause: `extensions/matrix/src/matrix/client/file-sync-store.ts:118-120` replays the whole saved Matrix sync cache into ingress on every client start (Gateway restart, or the Matrix channel restart that a room join's config write triggers); `extensions/matrix/src/matrix/monitor/ingress.ts:136-142` only marks first-login events as history, so cached events are admitted as deliverable; their only guard is the event-ID replay tombstone (`src/channels/message/ingress-queue.ts:358-376`), which shared retention prunes after 30 days (`src/channels/message/ingress-monitor-owner.ts:16-17`), so the next restart answers month-old messages as new turns.

Fixes #191476 (the replay of old inbound reported on 2026.11.12). The closed-consumer failure from the original report was fixed by #201554.

## What Problem This Solves

After a Gateway restart or a Matrix room join, OpenClaw answered Matrix messages that were 30 to 60 days old as if they had just arrived. It only happened in quiet rooms whose last message was at least 30 days old. In the report, 32 replies went to stale messages over two days, the same two images were answered four times over two months, and a month-old instruction rewrote a spreadsheet.

## User Impact

Restarts and room joins no longer revive Matrix messages that were already handled. Messages that arrived but were not yet answered when the Gateway stopped are still answered once after restart, and messages that arrive while the Gateway is down are still answered. No action or migration is needed.

## Why This Change Was Made

Matrix stores each sync batch in durable ingress before saving its cursor, so everything in the saved sync cache was already admitted. Replaying the cache on startup is meant to find those existing rows (pending ones keep their delivery). Once a completed row's 30-day replay guard is pruned, the replay was creating a brand-new deliverable row instead. The plugin now classifies cached replay the way it already classifies first-login history: an existing row is left as is, and an event without a row is recorded as intentionally not delivered. Shared retention, storage and the ingress queue are unchanged.

## Evidence

Isolated Gateway from a built checkout, local tuwunel homeserver, deterministic OpenAI-compatible model fixture. The Gateway answers a message in two rooms, then restarts with only its own clock moved forward 31 days (so the hourly prune removes the replay guards), then gets a `channels.matrix.groups` config change, which restarts the Matrix channel like a room join does.

| Run | After the channel restart |
|---|---|
| main, +31 days | both 31-day-old events dispatched again (`message processed ... messageId=<old event>`), and the bot posted a new message in each quiet room |
| main, no clock change | nothing dispatched |
| this PR, +31 days | channel restarted, nothing dispatched, no new bot messages |

On main the replayed turn in this setup ends with `Input completion retry conflicts with the committed input`, because the same session still holds the original input, and the room gets "⚠️ OpenClaw couldn't finish this request". The reporter's month-old sessions produced full fresh replies instead.

Safety checks, same result on main and this PR:
- A message queued behind a running turn when the Gateway was killed with SIGKILL (its ingress row was `claimed`) is answered exactly once after restart.
- A message sent while the Gateway was down is answered exactly once after restart.

Regression test `handler.restart.test.ts` "does not answer a cached message again after its replay tombstone expires" (real sync store, SQLite ingress queue) fails on main with `$unadopted` dispatched twice and passes here.

Thanks @hartmark for the report, and @7s9ffcyjq5-lgtm for the detailed 2026.11.12 replay timeline.

Merge danger: two-way door. A revert restores the old classification; no stored state, schema or config changes. Blast radius: Matrix inbound only, at client start.

Observed proof lines: #208571 (comment)

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit d692ddc)

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 30, 2026
… handled (openclaw#208571)

Root cause: `extensions/matrix/src/matrix/client/file-sync-store.ts:118-120` replays the whole saved Matrix sync cache into ingress on every client start (Gateway restart, or the Matrix channel restart that a room join's config write triggers); `extensions/matrix/src/matrix/monitor/ingress.ts:136-142` only marks first-login events as history, so cached events are admitted as deliverable; their only guard is the event-ID replay tombstone (`src/channels/message/ingress-queue.ts:358-376`), which shared retention prunes after 30 days (`src/channels/message/ingress-monitor-owner.ts:16-17`), so the next restart answers month-old messages as new turns.

Fixes openclaw#191476 (the replay of old inbound reported on 2026.11.12). The closed-consumer failure from the original report was fixed by openclaw#201554.

## What Problem This Solves

After a Gateway restart or a Matrix room join, OpenClaw answered Matrix messages that were 30 to 60 days old as if they had just arrived. It only happened in quiet rooms whose last message was at least 30 days old. In the report, 32 replies went to stale messages over two days, the same two images were answered four times over two months, and a month-old instruction rewrote a spreadsheet.

## User Impact

Restarts and room joins no longer revive Matrix messages that were already handled. Messages that arrived but were not yet answered when the Gateway stopped are still answered once after restart, and messages that arrive while the Gateway is down are still answered. No action or migration is needed.

## Why This Change Was Made

Matrix stores each sync batch in durable ingress before saving its cursor, so everything in the saved sync cache was already admitted. Replaying the cache on startup is meant to find those existing rows (pending ones keep their delivery). Once a completed row's 30-day replay guard is pruned, the replay was creating a brand-new deliverable row instead. The plugin now classifies cached replay the way it already classifies first-login history: an existing row is left as is, and an event without a row is recorded as intentionally not delivered. Shared retention, storage and the ingress queue are unchanged.

## Evidence

Isolated Gateway from a built checkout, local tuwunel homeserver, deterministic OpenAI-compatible model fixture. The Gateway answers a message in two rooms, then restarts with only its own clock moved forward 31 days (so the hourly prune removes the replay guards), then gets a `channels.matrix.groups` config change, which restarts the Matrix channel like a room join does.

| Run | After the channel restart |
|---|---|
| main, +31 days | both 31-day-old events dispatched again (`message processed ... messageId=<old event>`), and the bot posted a new message in each quiet room |
| main, no clock change | nothing dispatched |
| this PR, +31 days | channel restarted, nothing dispatched, no new bot messages |

On main the replayed turn in this setup ends with `Input completion retry conflicts with the committed input`, because the same session still holds the original input, and the room gets "⚠️ OpenClaw couldn't finish this request". The reporter's month-old sessions produced full fresh replies instead.

Safety checks, same result on main and this PR:
- A message queued behind a running turn when the Gateway was killed with SIGKILL (its ingress row was `claimed`) is answered exactly once after restart.
- A message sent while the Gateway was down is answered exactly once after restart.

Regression test `handler.restart.test.ts` "does not answer a cached message again after its replay tombstone expires" (real sync store, SQLite ingress queue) fails on main with `$unadopted` dispatched twice and passes here.

Thanks @hartmark for the report, and @7s9ffcyjq5-lgtm for the detailed 2026.11.12 replay timeline.

Merge danger: two-way door. A revert restores the old classification; no stored state, schema or config changes. Blast radius: Matrix inbound only, at client start.

Observed proof lines: openclaw#208571 (comment)

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. plugin: file-transfer rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M 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.

2 participants