Skip to content

fix(discord): preserve gateway messages across dispatch crashes - #110274

Merged
steipete merged 4 commits into
mainfrom
claude/ingress-discord
Jul 18, 2026
Merged

steipete merged 4 commits into
mainfrom
claude/ingress-discord

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Related: #109657

What Problem This Solves

Fixes an issue where Discord gateway messages could be lost when the gateway crashed after receiving an event but before dispatch adopted the turn. The old path detached dispatch behind a five-minute persistent replay guard. Discord RESUME can cover brief live-session interruptions, but session state is memory-only; a cold restart re-IDENTIFYs and cannot recover downtime from the platform. This change closes the receive-to-dispatch crash window without claiming to solve that platform limitation.

Why This Change Was Made

Discord now writes the raw APIMessage payload to the shared durable ingress drain before dispatch, using the message snowflake as the event id and channel/thread-derived lanes for ordering. Debounced turns keep claims deferred and fan adoption out to every constituent message; terminal outcomes settle through the shared drain. The old replay guard is removed after a RESUME duplicate-delivery parity test, with completed tombstones retained for 30 days and capped at 5,000 entries.

The transport boundary remains narrow: only MessageCreateListener is registered. Message updates still do not dispatch, so snowflake tombstones cannot suppress edit turns. The feature commit records this boundary explicitly; any future edit dispatcher must namespace its event ids.

User Impact

Discord messages received before an in-process gateway crash now replay after restart instead of disappearing between receive and turn adoption. Duplicate gateway deliveries remain suppressed after completion. Cold-restart downtime remains subject to Discord's re-IDENTIFY behavior and is not recovered by this change.

Evidence

  • Full extensions/discord suite after rebase: 2,266 tests green.
  • Focused ingress, listener, dispatcher, queue, and restart set: 240 tests green.
  • Post-rebase hard-zero guards: node scripts/check-deadcode-exports.mjs and node scripts/check-deadcode-unused-files.mjs, both green with 0 entries.
  • Post-rebase git diff --check and changed-file conflict-marker scan: clean.
  • Rebase range-diff preserved all four branch commits exactly; no conflict resolution or code changes were needed.
  • Autoreview sandbox fallback: the Codex sandbox could not access the network during the review build stage; a full manual review was performed, and a later landing review found and fixed the shutdown/aborted-dispatch loss race now covered by regression tests.

AI-assisted implementation and review; maintainer understands and owns the change.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: XL maintainer Maintainer-authored PR labels Jul 18, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4fc9954874

ℹ️ 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".

if (!channelId) {
throw new DiscordIngressPayloadError("Discord MESSAGE_CREATE payload is missing channel_id");
}
return { eventId, laneKey: `channel:${channelId}` };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve Discord debounce across durable ingress

When messages.inbound.debounceMs (or the Discord override) is nonzero, using the channel id as the durable ingress lane keeps the first claimed message active until its debounce flush reaches adoption; createChannelIngressDrain blocks later pending rows with the same lane while that claim is deferred, so a second same-channel/same-author message arriving inside the debounce window cannot be claimed and added to the same debounce buffer. The new dispatcher has logic to fan adoption across merged entries, but the gateway durable path never lets those entries reach the debouncer together, regressing configured Discord batching into one turn per message.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the claude/ingress-discord branch from 4fc9954 to 39d7f85 Compare July 18, 2026 00:43

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 39d7f85271

ℹ️ 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".

await adoptAll();
}
},
abandon: async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve deferred flush failures for ingress disposition

When inbound debounce is enabled, dispatchMessage returns deferred before the later debounce flush runs; if that later preflight/flush fails, the catch path calls ingress.abandon(error), but this implementation drops the error and only calls onAbandoned(). That means permanent failures the drain can classify via resolveNonRetryableFailure (for example a Discord 401 raised during preflight) are recorded as generic turn-abandoned retries until the retry limit instead of being dead-lettered immediately.

Useful? React with 👍 / 👎.

steipete added 4 commits July 18, 2026 01:51
Gateway MESSAGE_CREATE events dispatched with only an in-memory/persistent
5-minute dedupe; a crash between receive and dispatch lost the message (live
sessions replay via RESUME, but session state is memory-only so a cold
restart re-IDENTIFYs — stated platform limitation: the drain closes the
receive->dispatch window, not cold downtime). Raw API messages now journal
durably (event_id = message snowflake, lane per channel/thread) before
normalization; dispatch runs through the core drain with deferred claims,
fan-out adoption, gated settlement, and 30d/5k tombstones. The persistent
guard is deleted after its RESUME duplicate-delivery parity test. Edits stay
outside the queue: only MessageCreateListener is registered, MESSAGE_UPDATE
never dispatches, so snowflake tombstones cannot swallow edit turns; a future
edit dispatcher must namespace its event ids.

Autoreview blocked by codex sandbox network in the build stage; full manual
review performed. Part of the #109657 fleet adoption program (wave 2).
Landing autoreview reproduced a real loss race: a dispatch entering after
dispatcher shutdown (or with an aborted signal) returned completed, so the
drain tombstoned a message that never ran and a restarted gateway skipped it
forever. Aborted-before-dispatch now returns failed-retryable so the claim
releases for replay. Test type imports of drain-internal types converted to
factory-derived types so the dead-export gate and typecheck agree.
@steipete
steipete force-pushed the claude/ingress-discord branch from 39d7f85 to 347dfb6 Compare July 18, 2026 00:52
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 18, 2026
@steipete
steipete merged commit 6f0f6af into main Jul 18, 2026
119 of 122 checks passed
@steipete
steipete deleted the claude/ingress-discord branch July 18, 2026 00:58
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 17, 2026, 8:55 PM ET / July 18, 2026, 00:55 UTC.

Summary
The branch replaces Discord’s replay guard with a durable ingress drain that persists raw MESSAGE_CREATE payloads before dispatch and settles them through turn adoption.

PR surface: Source +413, Tests +350. Total +763 across 26 files.

Reproducibility: yes. source review provides a high-confidence path for the two regressions: enable Discord inbound debounce and send two eligible messages in one channel, then force a non-retryable failure during the later debounce flush. A real Discord restart replay was not demonstrated in the supplied PR evidence.

Review metrics: none identified.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦪 silver shellfish
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Repair the debounce lane/adoption interaction and add a focused regression test for two messages joining one configured batch.
  • Pass deferred-flush errors into ingress classification and cover a non-retryable error disposition.
  • [P1] Add redacted real Discord crash/restart replay proof that shows the message replays once and completed duplicates remain suppressed.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR reports unit-suite and static-check results, but it does not include after-fix proof from a real Discord receive/crash/restart replay setup. Add a redacted live transcript, terminal output, recording, or runtime logs showing durable replay and duplicate suppression; after updating the PR body, request @clawsweeper re-review if a fresh review does not start automatically. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Configured Discord inbound debounce can regress from batched turns to one turn per message because deferred ingress claims serialize later same-lane arrivals before they enter the debouncer.
  • [P1] A permanent deferred-flush failure can be retried until the generic limit instead of being dead-lettered immediately when the error is not passed to ingress disposition.
  • [P1] The supplied evidence reports suites and static checks but does not show an after-fix Discord receive/crash/restart replay in a real setup; private identifiers and endpoints should be redacted in any proof.

Maintainer options:

  1. Preserve batching and failure classification (recommended)
    Update the adapter so debounce-eligible messages are admitted into the same batch and deferred errors reach the shared drain’s retryability classifier before merging.
  2. Pause the durable-ingress migration
    Defer this Discord adapter until its lane and deferred-settlement behavior can be validated against the shared ingress contract.

Next step before merge

  • [P1] The protected maintainer label and the required Discord/shared-ingress lane decision make this unsuitable for autonomous repair promotion, despite the concrete findings.

Maintainer decision needed

  • Question: Should the Discord owner keep the durable-ingress design and repair the debounce-lane and deferred-error disposition paths before merge?
  • Rationale: The intended reliability improvement aligns with the linked channel-ingress program, but choosing the correct lane/adoption coordination requires confirmation against Discord’s established batching semantics and the shared drain contract.
  • Likely owner: steipete — They authored the current ingress adapter and its shutdown-race follow-up.
  • Options:
    • Repair the adapter before merge (recommended): Keep the durable drain, but add a lane/adoption design that preserves configured debounce batching and forwards deferred failure errors to ingress classification.
    • Pause for an owner design check: Hold the PR until the Discord and shared-ingress owners confirm the intended lane and deferred-settlement contract.

Security
Cleared: The reviewed diff is confined to Discord ingress, queue, and test behavior; no dependency, workflow, secret, permission, or supply-chain change is evident.

Review findings

  • [P2] Preserve Discord debounce batching across ingress claims — extensions/discord/src/monitor/message-dispatcher.ts:1
  • [P2] Forward deferred flush errors to ingress disposition — extensions/discord/src/monitor/ingress.ts:27
Review details

Best possible solution:

Preserve durable-before-dispatch admission while allowing messages eligible for the same Discord debounce batch to reach the debouncer together, and propagate the actual deferred-flush error into the drain so retryability and dead-letter policy remain canonical.

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

Yes, source review provides a high-confidence path for the two regressions: enable Discord inbound debounce and send two eligible messages in one channel, then force a non-retryable failure during the later debounce flush. A real Discord restart replay was not demonstrated in the supplied PR evidence.

Is this the best way to solve the issue?

No. Durable admission is the appropriate direction, but the patch must preserve existing debounce batching and carry deferred errors into the shared drain’s existing failure classifier rather than introducing Discord-specific weaker outcomes.

Full review comments:

  • [P2] Preserve Discord debounce batching across ingress claims — extensions/discord/src/monitor/message-dispatcher.ts:1
    With inbound debounce enabled, a deferred claim holds the channel lane until flush adoption, so later eligible messages in that channel cannot enter the same debounce buffer. This regresses configured batching to one turn per message; choose a lane/adoption arrangement that permits batch formation while retaining durable replay.
    Confidence: 0.88
  • [P2] Forward deferred flush errors to ingress disposition — extensions/discord/src/monitor/ingress.ts:27
    When the later debounce flush fails, the ingress abandonment path drops the original error before the drain classifies it. Non-retryable failures can therefore consume generic retries instead of dead-lettering immediately; preserve and pass the error through the lifecycle settlement path.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.82

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model internal, reasoning high; reviewed against 3a4e2ef65f41.

Label changes

Label changes:

  • add P1: The PR targets real inbound Discord message loss, but the remaining concerns can still alter message delivery behavior for configured users.
  • add merge-risk: 🚨 message-delivery: The changed ingress lane and settlement paths can suppress debounce batching or mishandle terminal delivery failures after merge.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR reports unit-suite and static-check results, but it does not include after-fix proof from a real Discord receive/crash/restart replay setup. Add a redacted live transcript, terminal output, recording, or runtime logs showing durable replay and duplicate suppression; after updating the PR body, request @clawsweeper re-review if a fresh review does not start automatically. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P1: The PR targets real inbound Discord message loss, but the remaining concerns can still alter message delivery behavior for configured users.
  • merge-risk: 🚨 message-delivery: The changed ingress lane and settlement paths can suppress debounce batching or mishandle terminal delivery failures after merge.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR reports unit-suite and static-check results, but it does not include after-fix proof from a real Discord receive/crash/restart replay setup. Add a redacted live transcript, terminal output, recording, or runtime logs showing durable replay and duplicate suppression; after updating the PR body, request @clawsweeper re-review if a fresh review does not start automatically. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +413, Tests +350. Total +763 across 26 files.

View PR surface stats
Area Files Added Removed Net
Source 19 778 365 +413
Tests 7 463 113 +350
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 26 1241 478 +763

What I checked:

  • PR intent and boundary: The PR body states that only raw MESSAGE_CREATE events enter durable ingress, using message snowflakes for event IDs and channel/thread-derived lanes; it explicitly ties the work to crash-window replay rather than cold-restart downtime. (extensions/discord/src/monitor/ingress.ts:1, 347dfb64accc)
  • Existing review: debounce regression: The prior review identifies that a shared channel ingress lane holds a deferred claim until debounce flush adoption, preventing later same-channel messages from reaching the debounce buffer; the final commit message addresses shutdown abort handling, not this lane/debounce interaction. (extensions/discord/src/monitor/message-dispatcher.ts:1, 347dfb64accc)
  • Existing review: deferred permanent-failure classification: The prior review identifies that deferred-flush abandonment drops the underlying error, preventing the ingress drain from immediately dead-lettering failures it can classify as non-retryable; the shown lifecycle type has an error-less onAbandoned callback. (extensions/discord/src/monitor/ingress.ts:27, 347dfb64accc)
  • Related canonical program: The linked umbrella issue explicitly calls for a separate Discord durable-ingress adapter and requires channel-specific crash-window/restart-replay proof, so this PR is a candidate implementation of that Discord slice rather than a duplicate. (src/channels/message/ingress-drain.test.ts:1, 3a4e2ef65f41)
  • Repository-policy inspection status: The target AGENTS.md guidance was supplied but could not be fully verified from the read-only checkout because the command sandbox failed before it could read the file; its visible policy nonetheless reinforces careful channel/queue sibling-surface review. (AGENTS.md:1, 3a4e2ef65f41)

Likely related people:

  • steipete: Authored the four-commit durable-ingress implementation and the follow-up shutdown-race fix, making them the clearest available routing contact for this specific Discord adaptation. (role: recent area contributor; confidence: medium; commits: 868a48de8f6e, 347dfb64accc; files: extensions/discord/src/monitor/ingress.ts, extensions/discord/src/monitor/message-dispatcher.ts, extensions/discord/src/monitor/message-run-queue.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 18, 2026
…claw#110274)

* fix(discord): adopt durable ingress drain for gateway messages

Gateway MESSAGE_CREATE events dispatched with only an in-memory/persistent
5-minute dedupe; a crash between receive and dispatch lost the message (live
sessions replay via RESUME, but session state is memory-only so a cold
restart re-IDENTIFYs — stated platform limitation: the drain closes the
receive->dispatch window, not cold downtime). Raw API messages now journal
durably (event_id = message snowflake, lane per channel/thread) before
normalization; dispatch runs through the core drain with deferred claims,
fan-out adoption, gated settlement, and 30d/5k tombstones. The persistent
guard is deleted after its RESUME duplicate-delivery parity test. Edits stay
outside the queue: only MessageCreateListener is registered, MESSAGE_UPDATE
never dispatches, so snowflake tombstones cannot swallow edit turns; a future
edit dispatcher must namespace its event ids.

Autoreview blocked by codex sandbox network in the build stage; full manual
review performed. Part of the openclaw#109657 fleet adoption program (wave 2).

* style(discord): keep drain-internal types and dispatcher unexported

* refactor(discord): move message dispatcher to its own module for the dead-export gate

* fix(discord): shutdown dispatch releases claims instead of tombstoning

Landing autoreview reproduced a real loss race: a dispatch entering after
dispatcher shutdown (or with an aborted signal) returned completed, so the
drain tombstoned a message that never ran and a restarted gateway skipped it
forever. Aborted-before-dispatch now returns failed-retryable so the claim
releases for replay. Test type imports of drain-internal types converted to
factory-derived types so the dead-export gate and typecheck agree.
wangmiao0668000666 added a commit to wangmiao0668000666/openclaw that referenced this pull request Aug 6, 2026
Matrix advances the /sync token before inbound events finish dispatching
(matrix-js-sdk doSync sets the token first, then the plugin's SQLite sync
store persists it), while room messages were dispatched into a memory-only
detached queue for the full agent-turn duration. A gateway crash or restart
in that window permanently lost the user message: the next /sync told the
homeserver the batch was consumed.

Journal every dispatchable inbound event into the shared channel ingress
queue (channel_ingress_events, no schema change) synchronously inside the
sync event listener — before the debounced token persist can land — and
dispatch through the core durable ingress drain with per-room lanes,
complete-at-adoption via the canonical turnAdoptionLifecycle reply-options
seam, bounded retry/dead-letter, and restart replay. The existing
persistent inbound deduper keeps redelivered events exactly-once. Events
without an event id keep the previous live-dispatch path.

Mirrors the durable-ingress fleet adoption (openclaw#109657): telegram openclaw#108924,
discord openclaw#110274, whatsapp openclaw#110418, mattermost openclaw#110386, msteams openclaw#110357.

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord maintainer Maintainer-authored PR merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant