Skip to content

fix(matrix): spawns from Gateway chat.send turns break thread bindings until restart - #177372

Merged
obviyus merged 1 commit into
openclaw:mainfrom
MarMarLabs:fix/matrix-thread-binding-owner-runtime
Oct 29, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
MarMarLabs:fix/matrix-thread-binding-owner-runtime

Conversation

@MarMarLabs

@MarMarLabs MarMarLabs commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Related: #175379.

What Problem This Solves

Fixes: a thread-bound subagent spawn requested through Gateway chat.send fails to persist its Matrix binding and can leave the account's binding manager unusable until restart.

User Impact

Users can create persistent Matrix thread-bound children through Gateway-originated turns, receive their replies in the intended Matrix thread, and continue that same child after a Gateway restart. Ordinary inbound replies and unbound-session delivery remain unchanged.

Why This Change Was Made

The Matrix binding manager now retains its owning plugin runtime when it starts instead of looking up a runtime from whichever caller later invokes a storage callback. Initial loading, persistence, reconciliation and activity writes use that same owner. Existing worker serialization, registry-retirement and manager-authority checks remain intact; there is no new storage format, configuration or public API.

Evidence

Built Gateway + real local Synapse differential proof, native Matrix events, controls and actual process-exit receipts.

  • Frozen main c8a27378eecac4f7cb82110f682ca0284d0493a9: two independent spawns return the native Matrix persistence/reconciliation error, including after a graceful Gateway restart.
  • Candidate ca70b506831a951154279cb3a1301aa3ad98b142: two spawns are accepted on the same account, and Synapse records both automatic child replies and subsequent operator sends in their respective native Matrix threads.
  • After a graceful candidate restart, an ordinary Matrix thread follow-up reaches the original child session and receives a reply in that thread. Unbound sends do not leak into Matrix; ordinary room messages reply on both refs.
  • All four final Gateway processes are awaited through SIGTERM to actual exit code 0. Synapse also exits 0 after SIGTERM. No Gateway or homeserver process is force-killed.
  • The agent runtime and tools are real; a deterministic local provider supplies tokens. The homeserver is real Synapse, with synthetic accounts and encryption off. This does not claim public Matrix service, E2EE, client UI or external-model quality coverage.
  • The contributor's existing regressions cover core-caller persistence across restart, recovery after a rejected write, and registry retirement. No additional product or test changes were needed during this proof.

Contributor: @MarMarLabs. The separate contributor provider supplement is attributed head-only evidence, distinct from the differential and graceful-exit run above.

Merge Danger

Two-way code change with no schema migration: existing-format bindings remain readable after a revert, and already-created child sessions/bindings are not automatically removed. A bad runtime capture could disrupt Matrix binding persistence or lifecycle cleanup; other channel adapters and the core binding service are unchanged.

@clawsweeper

clawsweeper Bot commented Oct 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.

@MarMarLabs
MarMarLabs marked this pull request as ready for review October 19, 2026 14:07
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T14:13:49.388585Z ca70b50 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: M labels Oct 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. P1 High-priority user-facing bug, regression, or broken workflow. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Retain Matrix’s owning plugin runtime so Gateway-originated subagent spawns can persist thread bindings.

Example: A Gateway chat.send turn requests sessions_spawn with thread:true and mode:"session" in an existing Matrix room session.

  • Before: Binding persistence fails and retires the account’s binding manager until restart.
  • After: Two children bind successfully, and an inbound thread follow-up reaches the original child after restart.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-local repair with shipped-entry-point differential evidence, distinct regression coverage, successful exact-head CI gating, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The exact candidate is exercised through shipped Gateway chat.send and the real agent runtime: the real-model supplement covers provider execution, while the real-Synapse differential proves accepted spawns, native threaded replies, restored inbound routing after restart, negative delivery controls, and graceful process exits.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Creating a thread-bound child from a Gateway turn fails and can leave Matrix binding operations unavailable until restart.
Reason: Restores existing thread-binding behavior with a focused internal ownership repair and preserves configuration, delivery policy, and storage contracts.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a current Matrix binding failure with a small, owner-local change; no actionable correctness or security findings remain.

Priority: P1
Reviewed head: ca70b506831a951154279cb3a1301aa3ad98b142

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Base-red/head-green execution of the added automated regressions is not documented; the supplied shipped-Gateway differential run establishes the user-visible failure and repair.
Agent review details

How this fits together

Gateway agent turns call the shared binding service, which delegates to Matrix’s account manager to persist bindings in SQLite and route Matrix threads to child sessions.

flowchart LR
  A[Gateway chat.send] --> B[Agent sessions_spawn]
  B --> C[Session binding service]
  C --> D[Matrix binding manager]
  D --> E[Owning plugin runtime]
  E --> F[SQLite worker]
  D --> G[Matrix thread]
Loading

Technical review

Best possible solution:

Use the manager’s startup runtime for every binding-storage operation while preserving existing worker serialization and lifecycle checks.

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

The supplied differential built-Gateway run reproduces the failure twice on frozen main, and current-main source retains the same caller-dependent lookup; this review executed no target code.

Is this the best way to solve the issue?

This is the smallest complete repair: bind storage access to the existing Matrix manager’s runtime rather than changing shared adapter semantics or introducing another state owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Matrix binding persistence and activity writes keeps the original intent (refactor(matrix): move thread bindings to workers #168485: The worker migration established async persistence, committed-state reconciliation, and retirement checks; subsequent simplification retained one serialized binding-write owner.)
  • Matrix runtime instance selection keeps the original intent (unknown: Runtime-store documents invocation-scoped slots to prevent a reload candidate from replacing the live instance’s runtime; deeper git log -S history encountered unavailable promisor blobs, so exact introduction remains unknown.)
  • Manager shutdown and replacement keeps the original intent (fix(matrix): preserve thread binding activity on shutdown #125039: Shutdown must await accepted binding writes before retiring the manager; this PR preserves that durability barrier.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 76a282c adds extensions/matrix/src/matrix/thread-bindings.ts:44 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 76a282c7a1c6; files: extensions/matrix/src/matrix/thread-bindings.ts)

PR surface

Source +10, Tests +215. Total +225 across 2 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 11 1 +10
Tests 1 215 0 +215
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 226 1 +225

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Gateway-originated Matrix spawns fail and can disable further binding mutations for the account until restart.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-19T14:23:38.546Z sha ca70b50 :: needs real behavior proof before merge. :: none

Reviewed October 29, 2026, 6:52 AM ET / 10:52 UTC (Revision 2).

@MarMarLabs

Copy link
Copy Markdown
Contributor Author

I ran the spawn and follow-up scenario on head ca70b506831a951154279cb3a1301aa3ad98b142 in an isolated built Gateway with the shipped agent/runtime and fresh state. The configured provider model was openai/gpt-5.6-luna, reached through a counting relay. Matrix used a loopback stub homeserver, not an external service. No source patch, seeded binding row or mocked model reply was used.

The records below select fields from projected artifacts. Times are UTC. Credentials, endpoints, process identities, upstream identifiers and the CLI idempotency value are omitted.

Run timeline

10:47:31  Empty initial Matrix sync.
10:47:37  Qualification turn starts, returns exactly QUALIFICATION-OK.
10:47:40  Primer enqueued, bot reply $root-1 at 10:47:42.
10:47:44  Existing room session and delivery metadata confirmed, bindings=0.
10:47:45  CLI chat.send turn starts into that session with deliver=true.
10:47:48  Actual Matrix send $root-2, binding recorded at 10:47:48.673.
10:47:50  Child reply MATRIX-CHILD-OK sent as $root-3 under $root-2.
10:47:55  Bindings=1.
10:48:02  Room message asks for the second spawn on the same Gateway.
10:48:04  Actual Matrix send $root-5, second binding recorded.
10:48:05  Second child replies under $root-5.
10:48:10  Bindings=2. Parent and both children later observed idle twice.
10:48:20  Binding snapshot, then SIGTERM.
10:48:20.792  shutdown completed cleanly in 180ms
10:49:20.813  Process still required killing after 60 seconds, exit=-9.
10:49:33  Fresh Gateway, before new traffic, both binding records equal.
10:49:35  Follow-up enqueued in the original $root-2 thread.
10:49:39  MATRIX-FOLLOWUP-OK sent as $root-8 under $root-2.
10:49:41  Second Gateway receives SIGTERM.
10:49:41.772  shutdown completed cleanly in 84ms
10:50:41.912  Second Gateway also killed after the wait, exit=-9.

CLI receipt and actual spawn

The shipped gateway call chat.send used an existing room session, deliver:true and no origin or target override. Selected receipt fields and the correlated call/result follow.

{"params":{"sessionKey":"agent:main:matrix:channel:!room:localhost",
 "message":"Use sessions_spawn exactly once with runtime=subagent, task=\"Reply MATRIX-CHILD-OK\", thread=true, mode=session, label=proof-core. Report the actual tool result.",
 "deliver":true,"timeoutMs":90000},"response":{"status":"started"}}
{"name":"sessions_spawn","transport_tool":"dispatch_action",
 "arguments":{"runtime":"subagent","task":"Reply MATRIX-CHILD-OK","thread":true,"mode":"session","label":"proof-core"},
 "result":{"status":"accepted","childSessionKey":"agent:main:subagent:1685a51b-a137-4363-b10c-540b02a82311","mode":"session","modelApplied":true}}

The inbound room-message spawn was also accepted and created the second binding. These are actual calls and results, not prompt instructions treated as execution.

Binding and retained child

Both retained records matched before stop, after kill and after fresh startup before traffic. Selected fields of the original binding follow.

{"conversationId":"$root-2","parentConversationId":"!room:localhost",
 "targetKind":"subagent","targetSessionKey":"agent:main:subagent:1685a51b-a137-4363-b10c-540b02a82311",
 "label":"proof-core","boundBy":"system","boundAt":1793098068673,
 "lastActivityAt":1793098068673,"idleTimeoutMs":86400000,"maxAgeMs":0}

The other root was $root-5. After the follow-up only the original binding's lastActivityAt changed, to 1793098175676, its enqueue time. The original child retained that key and session ID a016cba2-7227-437e-9b1f-8e3f3cf4e1f6 in the idle query, after restart and after the follow-up.

Selected event fields show the incoming message and delivered reply under the same root.

{"at":"2026-10-27T10:49:35.676Z","kind":"enqueue","event_id":"$fixture-7",
 "m.relates_to":{"rel_type":"m.thread","event_id":"$root-2","m.in_reply_to":{"event_id":"$root-2"}}}
{"at":"2026-10-27T10:49:39.049Z","kind":"send","event_id":"$root-8",
 "m.relates_to":{"rel_type":"m.thread","event_id":"$root-2","m.in_reply_to":{"event_id":"$root-2"}},
 "markers":["MATRIX-FOLLOWUP-OK"]}

The final answer matched exactly and added one provider request.

Counted attempts and usage estimates

All 27 requests returned HTTP 200. Input totals include cached and cache-write tokens.

Attempt Requests With usage Input Cached Cache write Output Usage estimate
Observer-stopped first attempt 11 10 32,715 10,418 20,976 648 $0.00649416
Completed fresh-state run 16 16 53,879 19,336 32,154 1,173 $0.01031062
Combined 27 26 86,594 29,754 53,130 1,821 $0.01680478

These estimates use the run's assumed per-million rates of $0.20 uncached input, $0.02 cached input, $0.25 cache writes and $1.20 output. Cached and write tokens are subtracted before charging uncached input. I have not verified these as published prices. The first attempt's request 11 has no usage, so its cost is unknown. Billing is unsettled.

The first observer missed a spawn nested in dispatch_action. Four saved-transcript checks then recognized the accepted result without another model request. No retained post-spawn binding snapshot proves a row for that attempt. I reran the whole case in fresh state and counted both attempts.

This is head only. The earlier base failure used a mock model. The forced restart proves persistence, not graceful exit. Config watching fell back to polling in the sandbox, so there was no hot reload.

@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Differential built Gateway + local Synapse proof

Candidate: ca70b506831a951154279cb3a1301aa3ad98b142 (contributor commit unchanged).
Frozen main: c8a27378eecac4f7cb82110f682ca0284d0493a9.

Both sources were staged from those Git archives and built with Node 24.22.1 inside secretless Docker. Each normal built Gateway loaded the bundled Matrix plugin. Matrix traffic went to a real, task-owned Synapse homeserver (matrixdotorg/synapse, image digest sha256:3c2900775df229b91ae0f21f2c98070e0da48d4e135a9c5b567b029be57fdb56), not a Matrix wire stub. All accounts, rooms and messages were synthetic. Encryption was off; this does not claim public-homeserver, Element UI or E2EE validation.

A deterministic local OpenAI-compatible provider supplied tokens to the real agent runtime. It used the advertised tool_describe / dispatch_action surface to execute the real sessions_spawn tool with thread:true, mode:"session". No Matrix adapter, runtime getter, binding manager, SQLite store or tool result was mocked, patched or seeded.

Observed user path

  1. Register the bot and two local users on Synapse; create a three-member room and let the Gateway bot join normally.
  2. Send an ordinary Matrix message. Both versions deliver PRIMER_ACK, establishing the room session and its native delivery context.
  3. Use the shipped Gateway chat.send RPC with deliver:true against that existing room session to request a thread-bound child.
  4. Repeat twice. Main is gracefully restarted between its two reproductions; candidate creates both children on the same account without an intervening restart.
main #1: sessions_spawn -> status:error
  Thread bind failed: Matrix thread binding persistence could not be reconciled; restart the account
main #2: sessions_spawn -> status:error
  Thread bind failed: Matrix thread binding persistence could not be reconciled; restart the account

candidate #1: sessions_spawn -> status:accepted, mode:session
  child: agent:main:subagent:08ba1c8c-d06d-418e-b8c5-fa40cab6949d
  root:  $T1jKZVVAhDdlPul_7xGwIvd_DsfHq2-iv9NkBfPJEcM
  automatic CHILD_READY event:
    $fJnr6auJ3kBdfo5SOVXQkK5nw498Fb5sTotjv-unV9Q
    m.relates_to = {rel_type:"m.thread", event_id:<root #1>}

candidate #2: sessions_spawn -> status:accepted, mode:session
  child: agent:main:subagent:a7c845f6-da55-4edb-aac5-ba4e08b0310b
  root:  $jG2Z1JRkrTUBJkOu-gSofSGjNu-vXvddV1VpUV86zSQ
  automatic CHILD_READY event:
    $akybhmHlDiPOv0YH3fnIN1pi5gr97l91IcDTiqVrSLM
    m.relates_to = {rel_type:"m.thread", event_id:<root #2>}

Synapse accepted a top-level “session active” banner on both failed main attempts, but the native spawn results report failed persistence. A returned child ID alone is therefore not treated as a successful binding.

Child chat.send, persistence and negative controls

For subsequent operator chat.send calls into the two bound children, the public Gateway client negotiated operator.admin, operator.read and operator.write and supplied the existing originatingChannel, originatingTo, originatingAccountId and originatingThreadId fields. This is normal explicit operator routing: channel-agnostic subagent keys intentionally do not automatically inherit an external delivery route. It is not the persistence oracle.

Synapse recorded these actual follow-up deliveries:

child #1 -> FOLLOWUP_ACK
  event: $6W5dp6SJIzFwMD8FlqsAcKOIqquJfEn19FIXKWwFPAw
  m.relates_to = {rel_type:"m.thread", event_id:<root #1>}
child #2 -> FOLLOWUP_ACK
  event: $fjhB5sx_U3OYKMSEqRF9-f19ZKJTCBGeISjm0Ps3LbA
  m.relates_to = {rel_type:"m.thread", event_id:<root #2>}

Then the candidate Gateway was stopped and restarted with the same state. A local Matrix user sent an ordinary follow-up into root #1, with no Gateway origin override. That input appeared in the original child #1 history as P177372_FOLLOWUP after restart; Synapse recorded FOLLOWUP_ACK event $kKYynxnhDakHUHW8WSFVB7XzYikshJOZ1NF4kQKgEk0 in root #1's m.thread. This independently proves the durable binding was restored and routed the inbound message to the original spawned session.

An unbound-session chat.send without an external origin returned UNBOUND_ACK internally and produced no Matrix delivery on either ref. Ordinary inbound room replies remained working on both refs.

Graceful shutdown evidence

All four final Gateway processes received SIGTERM and were awaited until their actual process exit, each with code 0, signal null. Each also logged shutdown completed cleanly. The wait continued after the shutdown log while remaining handles drained. No Gateway or Synapse process was force-killed; no source patch or clock change was used. Synapse was separately sent SIGTERM and docker wait returned 0.

Only final completed turns and real spawn-tool result objects are counted here. Earlier fixture preparation failures and a rejected broad collector oracle are retained privately and excluded from this differential proof. No unit tests were added or run in this repair pass.

Simplification pass: retain the existing owner runtime and all existing worker/reconciliation/retirement checks. Production +11/-1 (net +10), tests +215/-0; this worker changes neither. The contributor's separate provider supplement remains attributed head-only evidence, not this before/after or shutdown receipt.

@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 29, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 29, 2026
@obviyus
obviyus merged commit a1c3e81 into openclaw:main Oct 29, 2026
242 of 245 checks passed
@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Landed in a1c3e81. Thanks @MarMarLabs. Sessions spawned into Matrix threads now keep their thread binding.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 30, 2026
…s until restart (openclaw#177372)

fix(matrix): keep the Matrix thread binding for sessions spawned through chat.send

When chat.send spawned a child session in a Matrix room, the plugin read its runtime before the binding was ready, so the Matrix thread binding wasn't stored. Replies didn't reach the thread, and later messages in it didn't reach the child. The binding is now taken from the runtime captured at spawn time.

Evidence: built Gateway with the bundled Matrix plugin against a real local Synapse. On main the binding wasn't stored (twice); with this change two spawned sessions were bound and delivered native threaded replies (twice). After a graceful Gateway restart, a normal inbound message in the thread reached the original child and got a threaded reply. Unbound-session controls sent nothing to Matrix. Details: openclaw#177372 (comment).

Thanks @MarMarLabs.

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

channel: matrix Channel integration: matrix P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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