Repository navigation
fix(discord): /codex detach and rebind revert after a Gateway restart - #178333
Satoshi-Kusumoto wants to merge 1 commit into
Conversation
Discord opened its thread-binding store with the runtime of whichever plugin instance was running at write time. `/codex` commands run in the Codex plugin instance, where Discord's runtime slot is empty, so the write failed. The failure was caught, the change stayed in memory, persistence was turned off for the whole process, and the command still reported success, so the earlier binding came back after a Gateway restart. Keep the runtime of the Discord instance that created the thread-binding manager and use it for the manager's own loads and writes. The module-level session-wide idle, max-age, and unbind writes look up the account's manager and read the same owner holder through `ownersByManager`, falling back to the call-time lookup when there is none. When a provider reuses a live manager after a timed-out stop, a non-empty runtime from the new provider replaces the old one. No core production code or public SDK contract changes.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR makes Discord binding persistence use the thread-binding manager’s retained runtime across plugin calls. Example: Send /codex detach in a bound Discord DM, then restart the Gateway.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 6 items remain Keep this PR open: it repairs a demonstrated Discord persistence bug, but the retained runtime introduces actionable retirement and reload defects. Priority: P1 Before merge
Findings
Tests
Agent review detailsHow this fits togetherDiscord’s thread-binding manager translates conversation-binding operations from plugins and session commands into in-memory routing records and durable plugin-state writes. flowchart TD
A[Codex and session commands] --> B[Conversation binding service]
B --> C[Discord binding manager]
D[Session lifecycle helpers] --> C
C --> E[Retained Discord runtime]
E --> F[Plugin state store]
F --> G[SQLite binding records]
Technical reviewBest possible solution: Retain Discord-owned persistence while fencing retired writers, separating replacement lifecycle authority, and preserving persistence after refused writes. Do we have a high-confidence way to reproduce the issue? The linked report supplies a real Discord reproduction, and current-main source explains it: Codex’s instance lacks Discord’s runtime slot, and the resulting storage failure is swallowed; this review executed no target code. Is this the best way to solve the issue? Capturing the channel owner’s runtime addresses the root cause and follows the merged Telegram repair, but mutable reassignment and unchecked compatibility writes do not preserve runtime lifetime authority. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 1ff58cefbe8d. Provenance checked
TestingProof path: shipped entry point. SecurityNeeds attention: Runtime retention and reassignment bypass the originating lifecycle’s authority for reachable binding writes. EvidenceSecurity concerns:
What I checked:
Likely related people:
PR surfaceSource +58, Tests +424. Total +482 across 9 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 20, 2026, 6:34 AM ET / 10:34 UTC. |
Closes #178330
Related: #175379
Alternative to #177691
What Problem This Solves
Fixes: in Discord,
/codex detachand re-running/codex bindreply with success but are not saved, so the earlier binding is back after a Gateway restart.User Impact
User impact: detaching or re-binding a Discord conversation with
/codexnow survives a Gateway restart, and one such command no longer leaves Discord's binding storage memory-only for the rest of the Gateway process.runtime-apikeep their signatures./session unbindalso removes it, as on main.Why This Change Was Made
Discord opened its binding store with the runtime of whichever plugin instance was running at write time.
/codexcommands run in the Codex plugin instance, where Discord's runtime slot is empty, so the write failed.commitBindingRecordcaught the failure, kept the change in memory, turned persistence off for the whole process, and the command reported success. #178330 has the reproduction.The thread-binding manager now keeps the runtime of the Discord instance that created it. Its load, bind, unbind, touch, deprecated synchronous touch, and save-interrupted reporter use that runtime. This is the runtime ownership of the Telegram repair merged in #175379 (
2a30b52). Discord needs two more pieces:WeakMapin Discord's existing shared binding state. On main, the same calls from another plugin instance did not reach the store either: the runtime lookup failed and switched Discord to memory-only for the rest of the process. Without a manager, or with a manager that has no runtime, the helpers fall back to the call-time lookup, as on main.createThreadBindingManager. That manager now adopts the replacement provider's runtime when the provider has one. A caller without a Discord runtime, such as the Codex instance, does not replace it.No core production code or public SDK contract changes; the tests extend one existing core test file.
This is an alternative to #177691, which fixes the same bug; thanks to its author for the careful work there. The original #175379 description already noted that Discord opens its binding store the same way, and I started on Discord after a maintainer took that PR over on 2026-10-18. Reproducing the bug and proving the fix on a real Discord bot took a few more days, so this PR arrives after #177691; apologies for the overlap. For the session-wide helpers, this PR follows #177691, whose first commit already covered them through the manager's retained runtime. This PR keeps the repair inside Discord's binding owner: it does not change core implementation or the public SDK contract, its runtime ownership has the same shape as the Telegram repair merged in #175379 (
2a30b52), and it has real Discord runs before and after the fix. #177691 goes further: it fences runtime-owned plugin-state stores after their owning runtime retires, and makes refused async binding changes (other than best-effort activity touches) reject without publishing the change or disabling persistence. This PR leaves both cases as accepted limits below. Both rely on core plugin-state changes in #177691 (refusing retired runtimes when stores open and on synchronous writes, with a typed refusal error) that change behavior for every plugin using runtime-owned stores, and the async case also changes how Discord binding commands report failures; these are maintainer decisions beyond this Discord-local fix. I am happy to follow whichever direction maintainers prefer; the live reproduction in #178330 applies to either PR.Accepted limits (plugin reload windows only; named here rather than coded around):
2a30b52). No bundled code calls these deprecated writes; only external SDK callers can.createThreadBindingManageris exported. A caller that gets an existing manager back while holding a different Discord runtime also replaces that manager's runtime. In bundled code only the Discord provider calls it with a Discord runtime.TypeErroruntil restart, as refactor(channels): consolidate private transport paths #173128 decided for such shape changes.SessionBindingService.touch.Design notes
WeakMapis keyed by manager, next to the existingaccountOperationTailsmap in the same shared state. Unlike the default runtime slot, which resolves from the calling plugin instance, the stored value does not follow the caller.getOptionalDiscordRuntime(), because existing tests create managers without one. Such a manager cannot open the store, so Discord stays memory-only, as it did before when the first load found no runtime.Evidence
On a real Discord bot and the same
d8e54eccheckout,/codex detachleft the binding stored before the fix (1 row, and the binding was back after a restart) and removed it with this PR (0 rows, no binding after a restart, and nopersistence unavailableline).Real Discord, before and after. Both runs used the same
d8e54eccheckout and a dedicated test bot in a paired DM, with the commands sent as plain-text messages from a Discord client (commands.native: false). The Codex plugin was enabled and the Gateway had no model credentials; no ordinary message was sent, so there was no model turn. The Gateway was built withpnpm buildand started withnode openclaw.mjs --dev gateway --bind loopback --tailscale off --verbose, which loads Discord fromdist/. Stored rows were counted read-only with the Gateway stopped (plugin_id = 'discord',namespace = 'thread-bindings'). The pre-fix run used unpatchedd8e54ec; the post-fix run used this PR's diff on the same checkout./codex bind, Allow once: 1 row./codex bind --cwd <dir>,/codex detach,/codex binding: all success replies, but still 1 row. The console loggeddiscord thread binding persistence unavailable; keeping bindings in memoryonce, 1 ms before the re-bind'splugin binding auto-refreshline./codex bindingshowed the binding again, withWorkspace: <worktree>from the first bind; the re-bind's<dir>was lost./session unbindthen removed it (0 rows)./codex bind --cwd <dir>, Allow once, then/session idle 2h: 1 row, withidleTimeoutMs=7200000./codex bind --cwd <dir>,/codex detach,/codex binding: 0 rows./codex binding,/session unbind,/codex bindingrepliedNo Codex conversation binding is attached., thenℹ️ This conversation is not currently bound., thenNo Codex conversation binding is attached.0 rows at the end.persistence unavailablelines over the whole run (4 Gateway starts; the first was stopped to approve the DM pairing): 0.--cwd(left out by mistake), and the post-fix run added/session idle 2h. That command reaches the changed session-wide async helper (source reading). The run shows that the helper still stores on a real Gateway; the focused tests below cover the cross-instance calls.Focused tests.
src/plugins/conversation-binding.cross-instance.test.tsgets a newdescribe("Discord thread bindings across plugin instances"): 5itblocks, one of them anit.eachover 3 writers, so 7 executed cases. Each case uses the real plugin registry lifecycle, the real plugin-state store, and Discord's real thread-binding manager started inside a Discord plugin instance, as channel startup does. Writes come from a Codex plugin instance, throughrequestPluginConversationBinding/detachPluginConversationBindingor Discord's public session-wide exports; in the reuse case they come from a replacement Discord instance. Every case except the retired-runtime control reads the stored row and then checks that a later write from Discord's own instance is still stored, which catches the process-wide switch to memory-only.d8e54ecand pass with this change. A sixth case has a replacement provider, running in a replacement Discord instance, reuse a live manager (the reload-timeout path). It passes ond8e54ec, which looks the runtime up at call time, and fails if only the manager keeps the runtime; it guards against that regression.d8e54ecthe case fails before it reaches the paused store write, because the request settles first, so it is not red/green proof for this change.DEP_PLUGIN_SDKdeprecation warnings are expected.Test cost (
pnpm test <file> --maxWorkers=1, Linux x86_64, Node 24.21.0, Vitest on Node):src/plugins/conversation-binding.cross-instance.test.ts: wall 19.17 s, Vitest Duration 16.59 s. Each Discord case takes 446–602 ms (about 3.4 s for the 7), and the 3 existing Telegram cases about 1.9 s. This is above the 5 s target and under 30 s: each case builds a real registry, a real SQLite-backed plugin-state store, and Discord's real manager, because the bug is which plugin instance opens that store, and a fake adapter would not open it. The per-case cost matches the Telegram cases already in this file.extensions/discord/src/monitor/thread-bindings.state.test.ts(two existing calls now pass the runtime resolver; no cases added): wall 13.82 s, Vitest Duration 11.33 s.Checks (same environment, tree
d8e54ecplus this diff):git diff --check, format check, core and Discord lint, core and extension type checks, and the existing Discord thread-binding tests: pass.pnpm test:extension discord: passed (252 files, 2496 tests).pnpm check:changed: exited 1. The lanes covering this diff pass (core-test and extension type checks, lint on the changed files, import cycles). Three checks fail identically on a cleand8e54ec: the max-lines suppression ratchet (files underui/), the core tsgo test-root budget per shard (724 and 725 against 720), and the dead-export scan (untouched google-meet and gateway talk files).autoreviewagainstd8e54ec: scoped-clean, no actionable findings.pnpm test:contracts:channels, since no shared plugin or channel interface changed.Not covered:
Focused tests on
d8e54ec, a manager-only variant, and this changeThe middle column is a variant of this fix, not submitted, in which only the manager keeps the runtime: the session-wide helpers still look it up at call time, and a reused manager keeps its old runtime. It shows that each of the last four Discord cases fails without the part of this change it covers. Same environment and test file in all three runs; only the production files differ.
Discord thread bindings across plugin instances > …)d8e54ecThe 3 existing Telegram cases pass in all three runs. Failures on
d8e54ec:The manager-only variant fails the three session-wide cases with the same assertions, and the reuse case with:
Post-fix run: build pinning and transcript (redacted)
The pre-fix working tree had an empty diff against
d8e54ec. For the post-fix run, the freshly built Discord chunks contain this change's identifiers (ownersByManager×4 andresolveThreadBindingsOwnerRuntime×6, all in files built after this run's build started; 0 of each before the build), each of the 4 Gateway starts logged[plugins] loading discord from <worktree>/dist/extensions/discord/index.js, and the working-tree diff (sha256b7bddf1b49d00fe979febf11ef28da00b4abc80978d15fa81feff31f83b82757) is byte-identical togit diff --binary d8e54ec 74d9a81348e6. The working tree matched this diff right after the build and again after the last Gateway stop.Maintainer edits are enabled ("Allow edits and access to secrets by maintainers"); this fork has no Actions secrets configured.