Repository navigation
fix(discord): codex detach and rebind are lost after a Gateway restart - #177691
MarMarLabs wants to merge 14 commits into
Conversation
|
🦞👀 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 SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: de7639b875
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Codex review: blocked before merge. What this changesDiscord binding managers retain their creating runtime, refuse retired-owner mutations, and hand persistence to active replacement managers. Example: Send
Review scores
ProductKind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 2 items remain This PR fixes a current Discord persistence bug and has sufficient behavior proof; the public SDK behavior change still needs owner approval. Priority: P1 Decision needed
Before merge
FindingsNone. Agent review detailsHow this fits togetherDiscord binding managers translate conversation commands and lifecycle updates into plugin-state writes; SQLite stores the records that startup restores into routing state. flowchart LR
A[Discord conversation command] --> B[Conversation binding service]
B --> C[Discord binding manager]
C --> D[Captured runtime authority]
D --> E[Plugin state worker]
E --> F[SQLite binding records]
F --> G[Startup routing state]
Technical reviewBest possible solution: Keep the runtime-bound persistence repair and obtain SDK-owner acceptance of retired-runtime refusal during the synchronous compatibility window. Do we have a high-confidence way to reproduce the issue? Current-main store lookup and fallback code explain the reporter's real Discord reproduction; no target code was executed during this review. Is this the best way to solve the issue? Retaining the creating runtime fixes the ownership error at the existing manager and store boundaries, while typed refusal preserves the distinction between lost authority and unavailable storage. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 2bc19eb1e725. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +171, Tests +1097, Docs +2. Total +1270 across 19 files. Added test files: 2. View PR surface stats
LabelsLabel changes: No label 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 HistoryReview history (3 earlier review cycles)
Reviewed October 29, 2026, 5:07 PM ET / 21:07 UTC (Revision 4). |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d1980ede38
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d5f8321b44
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Live Discord persistence at
|
| Snapshot | Rows |
|---|---|
| Before detach | 1 |
| After detach | 0 |
| After full stop | 0 |
| After fresh start, before traffic | 0 |
| After final query | 0 |
/codex binding returned No Codex conversation binding is attached. before the stop and again after restart.
B2, rebind
In a fresh case an approved A bind and real file read returned WORKSPACE-A-OK. I sent /codex bind naming workspace B. No new approval prompt appeared. Exactly one row remained, with the same Discord conversation, webhook, target key and binding ID, now naming B. /codex binding named B and a real file read returned WORKSPACE-B-OK.
The retained binding record was equal before and after the full stop, and after a fresh start before traffic. The query then named B again, and a final real file read returned WORKSPACE-B-OK.
The native Thread value in the two binding queries changed across restart. The Discord conversation, binding ID and workspace persisted. I do not claim the native thread survived or infer a recovery mechanism from that changed value alone.
Requests and limits
These completed B1 and B2 runs used 2 and 6 model requests respectively, two per file read. Detach, rebind and binding queries added none. The earlier blocked attempt is separate.
- Head only, with no real Discord base run. The failing side remains the earlier local evidence in the body.
- Initial approval cards stayed visible after commit. Retained projections establish approved binds, not the exact initial native interaction or which approval button was clicked.
- Callback HTTP statuses, approval click IDs, direct
MESSAGE_CREATEframes and internal caller-instance traces were unavailable. Typed messages, replies and durable outcomes were measured, not the writer's internal instance identity. - No artifacts are attached. Screenshots remain private pending export review. This comment is text only.
Retirement coverage
Retirement and late-stop handover retain test-only evidence. I read these tests at the tested head and did not rerun them.
src/plugins/conversation-binding.discord.test.tscovers sync and async touch, idle timeout, max age and unbind, plus async rebind and detach. All run through a foreign caller against active, retired-before-stop and stopped owners. Non-active cases require unchanged durable rows.src/plugin-state/plugin-state-store.runtime.test.tschecks all seven sync mutators after revocation, plus update and deleteIf when their own callback revokes the owner.src/plugins/conversation-binding.discord-handoff.test.tschecks explicit retirement handoff and that the old manager's late stop leaves its replacement registered.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Retirement and replacement proof at
|
| Call after retirement | Result |
|---|---|
| sync touch | null |
| sync idle timeout, max age, unbind | [] each |
| async touch | null |
| async idle timeout, max age, unbind | PLUGIN_STATE_RUNTIME_INACTIVE each |
retained sync store update, V2 store register |
PLUGIN_STATE_RUNTIME_INACTIVE each |
After every call the whole plugin_state_entries table had the same SHA-256 as before retirement, and the in-memory routing projection was unchanged.
The replacement then acquired a distinct manager. A separate read-only SQLite connection read back each write. Bind set proofPhase to replacement, idle timeout became 90000 ms and max age 180000 ms. Awaiting the old manager's stop at that point left the replacement registered. After another real 15 s wait, touch set lastActivityAt to the requested value. Unbind left 0 rows.
Wrong-version control
The wrong version points one built Discord file at a copy where the two store-open helpers call getDiscordRuntime() instead of (runtime ?? getDiscordRuntime()). That is main's lookup. It borrows the calling instance's runtime, and no other module changes.
- My control covers the four synchronous operations. After retirement each changed the rows. Touch advanced
lastActivityAt, idle timeout became 60000, max age 120000 and unbind deleted the row. Later operations in that run found no row and prove nothing more. Acquisition then reused the retired manager, which fails the driver's own distinct-manager check. - An independent checker reran the control with the four asynchronous operations first, which covers them as separate evidence. Touch advanced
lastActivityAt, idle timeout became 65000, max age 130000 and unbind deleted the row. The paired head run in that order passed. - The checker's revoke run used
revokePluginRecordat head. The ten refusals, unchanged rows and replacement writes were the same, with the registry not retired and the old instance still accepting calls. That mode has no wrong-version run. - The two store-handle refusals have no wrong-version control.
The checker also reran the head and the control in fresh roots. With timestamps set aside, all 22 head snapshots and 16 operation results matched my run, and all 16 control snapshots and 11 operation results matched.
Terminal output
Selected driver stdout lines from my head run.
{"utc":"2026-10-29T19:16:40.381Z","attempt":"attempt5","event":"owner_deactivated","method":"markPluginRegistryRetired","ownerActive":false,"registryRetired":true,"ownerAcceptingCalls":false,"managerStillRegistered":true,"managerStopping":false,"candidateActive":true}
{"utc":"2026-10-29T19:16:40.383Z","attempt":"attempt5","event":"operation","label":"retained.sync_touch","returned":null}
{"utc":"2026-10-29T19:16:40.386Z","attempt":"attempt5","event":"refusal_check","label":"retained.sync_touch","byteIdenticalRows":true,"unchangedRoutingProjection":true,"isRefusal":true}
{"utc":"2026-10-29T19:16:40.396Z","attempt":"attempt5","event":"operation","label":"retained.async_unbind","error":{"name":"PluginStateRuntimeInactiveError","code":"PLUGIN_STATE_RUNTIME_INACTIVE","message":"Plugin \"discord\" runtime is no longer active."}}
{"utc":"2026-10-29T19:16:40.397Z","attempt":"attempt5","event":"refusal_check","label":"retained.async_unbind","byteIdenticalRows":true,"unchangedRoutingProjection":true,"isRefusal":true}
Limits
- All ten refusals came within about 20 ms of retirement, in one process.
- I set up the retired state directly and did not reach it through a real reload. The plugin record is synthetic and the driver activates each registry itself.
- The driver activates the replacement registry while the original is still live and no old-provider stop has started. A reload stops the old provider, or times out on it, and disposes its instances before loading the replacement. Both then mark the new registry active before retiring the old one.
- No sweeper, webhook, REST, farewell, plugin loader or command handler path ran. The conversation is a direct
user:one and onlyplugin_state_entrieswas snapshotted. - The old manager was not stopping during the refusals, so a stop held part-way is not modeled. Only the calls listed above ran, not every synchronous mutator.
No artifacts are attached. This comment is text only.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Closing this to keep my open queue small. Happy to reopen or redo it if it's still useful. |
Fixes #178330. Related to #175379.
What Problem This Solves
A Discord thread detached with a typed
/codex detachcan become bound again after the Gateway restarts. A typed/codex bindthat moves a bound thread to a new workspace can also be undone by a restart.User impact
Detached threads stay detached, rebinds keep their new workspace, and later binding changes remain durable. A write refused by a retired runtime or a closing Gateway no longer disables persistence, and a refused binding change reports a failure, not success. A replacement Discord provider that starts after its predecessor retires gets its own thread binding manager, so its bind, idle timeout and detach writes persist. No config change or migration is needed.
A row left behind by an earlier detach is still loaded at startup. That thread needs one more
/codex detachon this build.The repair reaches core runtime-owned state stores, so the Telegram, ClickClack and
/codexcaller suites are included below. Matrix's separate no-instance repair is #177372.Cause and repair
Discord looked up its plugin runtime in the slot of the plugin instance currently running, and a typed detach starts in the
/codexinstance, where the Discord slot is empty. The write threwDiscord runtime not initialized, the manager changed memory and disabled persistence for the process, and the command appeared to succeed until restart.Each Discord manager now retains its creating runtime and passes it into async and synchronous store opens, and session-wide idle timeout, max age and unbind helpers read the same runtime from a private WeakMap through the account registry. Core now checks a runtime-owned synchronous store at open and before all seven mutators, update and deleteIf also after their callback. Already-open handle reads are unchanged.
The state runtime marks its authority refusal with
PLUGIN_STATE_RUNTIME_INACTIVE, and the worker client preserves it. Discord tells it from a storage failure through the SDK facade it already imports, drops the uncommitted write and leaves persistence on. For a retired runtime, async unbind, bind, detach and the session-wide idle timeout, max age and unbind updates reject with it, send no unbound notification and publish no record. The check runs before every shared-memory publication, including a touch inside the 15 s persist interval and a manager with persistence off or latched off. It opens a data-only V2 handle with no store operation before the operation module source is captured. Synchronous compatibility calls still return null or an empty array, a retired owner's touches resolve null, and a deleted thread still closes its sessions after a refused unbind. Real storage failures still disable persistence and apply the change in memory.createThreadBindingManagerused to return the account's cached manager even after its owner retired, so a replacement provider's own bind, idle timeout and detach were refused, and after the old stop removed the adapter nothing recovered until a later acquisition. Now, when the cached manager's runtime is inactive, acquisition checks that the caller's runtime is active, starts the old stop without waiting for it, and registers a new manager that retains the caller's runtime. The old manager's runtime is never reassigned, and its late stop clears the slot and adapter only while it owns them. A live owner's manager is still reused, an inactive caller still gets the typed refusal, and a reference taken while its owner was live stays refused after retirement.Reviewed through
5388ada4c289, manager method signatures, account queues and the runtime lookup for managers without a retained runtime are unchanged.Public SDK semantics change for retired runtimes. Typed and plain runtime refusals now count as closed admission for SDK retries and tool outcomes. New synchronous opens and writes through retained synchronous handles now refuse work, and async binding changes through a retired Discord manager now reject. An October 19 usage query found no resolved references to this member but covered only 2,047 of 2,432 eligible artifacts, so third-party impact is unknown.
createThreadBindingManager, exported from the Discord runtime API, now also replaces the cached manager of a retired owner, and in that case it throws the typed refusal if the caller's runtime is inactive or missing.Evidence
At
857edb7316cf, six PR test files passed 218 tests, 15 plugin-state files passed 193 with one skipped, and ten baseline checks passed. My real Discord/model checks atd1e4495644c5are in #177691 (comment). The checks passed, but the full runbook evidence remains inconclusive. Typed detach and rebind persisted across restart. These runs cover only the first half of the authority-chain item. Retirement and replacement writes ran in #177691 (comment), a scripted driver over the built production modules atd1e4495644c5and not a Gateway reload. A checker's revoke run there covers revocation. Other results below ran at earlier heads.Tests at
22ea62dHead
857edb7316cfmerges5388ada4c289, uses upstream'spublicationEffecthelper and adds six cases. Commit22ea62daddssrc/plugins/conversation-binding.discord-handoff.test.tswith three cases. A live owner's retained manager refuses a candidate's writes after retirement until an explicit acquisition hands off. A replacement started after retirement gets a distinct manager whose bind, idle timeout, touch and detach persist, and the old manager's late stop leaves it registered. An inactive candidate cannot replace a retired owner. All three fail with the two production files from56cd59fand pass at22ea62d. Wrong versions that borrow the caller's runtime at call time, fall back to memory on the typed refusal, hand off over a live owner, or skip the candidate's activity check each fail one of them.On a mocked clock, an uncommitted diagnostic found that at
56cd59f, after the owner retired, the candidate's idle timeout write was refused at five points from +1 s to +1 h. At maine2da41fthe idle writes, bind, touch and detach all succeeded before the old stop. A probe then stopped the old instance from accepting calls, started the replacement with the old manager unstopped, and ran each operation in the replacement.56cd59fproduction files22ea62d/session idle/codex detachBINDING_ADAPTER_UNAVAILABLEAt
22ea62dthe 14 Discord binding, listener and manager caller files passed 206 tests and the 7 conversation binding and contract files passed 128. The extensions type check, the core plugin-platform test type check, formatting and typed lint on the three files it changes, and the mock-exports and line-cap ratchets also passed. At22ea62d, max-lines, the other ratchets, the SDK exports check, plugin inventory and config documentation were not rerun. At the56cd59fproduction code they passed except max-lines, which flagged three unchanged UI files, and 17 Telegram, ClickClack and/codexcaller files passed 310 tests.The 19 retired Discord cases fail at
d5f8321, and the bound-source and core open cases fail ated59bdf. Real SQLite trigger failures verify the memory fallback. The/codex detachcommand file checks the failure reply and the restored native binding. A 30-cell guard matrix from95d9afethroughed59bdf, a 45-cell probe and an uncommitted 153-cell probe of earlier heads found no durable difference and were not rerun.Prior-head Gateway evidence, not rerun
The earlier local Gateway record used a Discord stand-in and mock model. It compares main
89e77376ccbwith local merge3a4095bc93d, the earlierde7639brepair. It was not rerun on a later head, and its typed detach reply predates the refusal path above. After detach, stop and a fresh start, main held 1, 1, 1 rows and the old binding returned after restart, while the merge held 0, 0, 0. A typed rebind run kept the new workspace through restart on the merge, not on main.Remaining limits
The live runs did not cover a base build, a DM, Always allow or registry retirement, which the scripted driver ran. The full Discord extension project passed at
67b59f2ef60eand was not rerun after main changed 96 Discord extension files through5388ada4c289. #178330 holds its author's pre-fix reproduction on a real Discord bot, which was not rerun on this branch.The typed detach failure reply and the real store's refusal were measured separately, not together in a Gateway. The reload ordering, with the old instance's calls stopped before the replacement provider starts, was read from source and modeled with an instance that no longer accepts calls. The time from retirement to the replacement's acquisition was not measured, and writes in it are still refused. The handoff for a caller with no runtime has no test. A channel restart inside the same plugin instance after a timed-out stop still shares one manager, so the old task's late stop removes its adapter until the next provider start, as on main. A session-wide call while no manager is registered still uses the ambient runtime lookup, whose failure still turns persistence off, as on main. A session-wide update across two accounts stops at the first refused row without rolling back earlier rows, startup reconciliation does not catch a refused stale unbind, and a refused thread-delete unbind leaves its row for the replacement owner's sweeper.