Skip to content

fix(whatsapp): preserve inbound messages across restarts - #110418

Merged
steipete merged 9 commits into
mainfrom
claude/ingress-whatsapp
Jul 18, 2026
Merged

steipete merged 9 commits into
mainfrom
claude/ingress-whatsapp

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Related: #109657

What Problem This Solves

Fixes an issue where accepted WhatsApp inbound messages used a channel-private journal replay path plus a 20-minute in-memory replay guard, leaving restart recovery, duplicate rejection, and same-conversation ordering outside the shared durable-ingress contract.

Why This Change Was Made

The WhatsApp journal now drains through the shared channel ingress worker. It derives stable event IDs as sha256(remoteJid + id), uses remoteJid conversation lanes, persists receive-time skip decisions in the journal payload, and holds deferred claims until reply-lane adoption. Same-conversation work stays serialized by the core contract.

The old 20-minute/5,000-entry inbound replay guard is removed because seven-day/5,000-entry durable tombstones cover that identity window across restarts. The outbound echo cache is unchanged.

This builds on the durable-drain base authored by @obviyus. Thank you, Ayaan, for the original implementation and issue plan. AI-assisted finishing and validation were used for this PR.

User Impact

WhatsApp users get durable replay of accepted-but-not-adopted inbound messages after a restart, durable duplicate rejection, and serialized delivery per conversation through the same core path used by other migrated channels. No configuration changes are required.

Live WhatsApp login proof is not included because the QA credential is currently unlinked. That credentialed receive/restart/flush check remains part of the maintainer's manual verification round.

Evidence

  • Exact rebased head: pnpm test extensions/whatsapp on Blacksmith Testbox run 29630942093: 93 files, 1,117 tests passed.
  • extensions/whatsapp/src/inbound/durable-receive.test.ts: claim release, durable tombstones, and same-lane pending-until-adoption serialization.
  • extensions/whatsapp/src/monitor-inbox.streams-inbound-messages.test-support.ts: transient persistence retry, close-timeout disposal, prepared-map ownership/bounds, durable replay, and same-lane follow-up regressions.
  • extensions/telegram/src/polling-session.test.ts: shared same-lane serialization/adoption reference behavior.
  • node scripts/check-deadcode-exports.mjs and node scripts/check-deadcode-unused-files.mjs: zero findings.
  • git diff --check origin/main...HEAD: clean.
  • Mandatory autoreview completed. Its two findings were the already-adjudicated bounded fail-closed persistence policy and intentional same-lane serialization contract; both are explicit, tested design decisions for this landing.

obviyus and others added 7 commits July 18, 2026 05:39
Accept-before-processing stays; the private startup replay loop and inline
complete/release bookkeeping move to the core drain. Drain-owned entries keep
their durable id so downstream failures release for replay, dedupe-claim
contention stays retryable instead of tombstoning, and undeliverable claims
still send configured read receipts. Rows tombstone at dispatch return
(pre-migration timing), not at adoption (#108656).
…conversation lanes

Core durable ingress intentionally serializes claims by remote JID. Same-conversation bursts now merge as queued followups in the core reply lane after adoption; channel debouncing remains for control and retry paths, with merged fan-out and gated settlement.

Built on the durable drain branch base by @obviyus.
…inbound races

Landing autoreview caught two holes: the persistence-failure fallback
dispatched live, bypassing drain dedupe and lane serialization now that the
replay guard is deleted (duplicate replies / session races); and duplicate
pending rows could orphan or clobber preparedInboundByDurableId entries. The
append now retries transient failures with short backoff then drops loudly
(fail closed — the fallback traded a correctness race for availability
against an already-broken store); redeliveries neither clobber the first
delivery's in-flight preparation nor keep orphan entries. The old
fallback-contract test is repurposed to prove retry-then-durable-delivery.
The close timeout abandoned the graceful drain path before its finally could
dispose, so a successor monitor could pump the same account queue against a
still-live drain. The timeout wrapper now owns disposal; dispose is
idempotent so the graceful path's cleanup is unaffected.
The dead-export gate refused serializer/error exports whose only external
consumers were tests. The payload contract (Long-timestamp-preserving
serialize/deserialize + the permanent-error class) now lives in
durable-payload.ts with durable-receive as its production consumer; the dead
WhatsAppRetryableInboundError class is deleted (any non-permanent error is
retryable to the drain classifier, so test-support throws a plain Error).
A duplicate pending delivery's finishPreparation deleted the first
delivery's kept entry (ownership guard now requires the deleter to be the
installer), and queue pruning could evict pending rows whose prepared-map
entries then lingered forever on a blocked lane (map now evicts oldest-first
at a bound above the queue's pending cap; dispatch already re-normalizes the
journaled payload when its entry is gone). Regression covers the duplicate
case.
@openclaw-barnacle openclaw-barnacle Bot added channel: whatsapp-web Channel integration: whatsapp-web size: XL maintainer Maintainer-authored PR labels Jul 18, 2026
@steipete steipete self-assigned this 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: bae0c53a32

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

Comment on lines +123 to +126
receivedAt,
...(params.receiveOrder === undefined ? {} : { receiveOrder: params.receiveOrder }),
},
{ receivedAt, laneKey: facts.laneKey },

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.

P1 Badge Preserve durable ordering for same-millisecond messages

When two messages for the same chat are appended in one Baileys upsert, or before the drain runs, they can share the same millisecond receivedAt here. The shared ingress queue claims by received_at and then event_id (src/channels/message/ingress-queue.ts:692-695), while WhatsApp only stores receiveOrder inside the payload, so the same-lane drain can claim SHA-sorted later messages before earlier ones. That can reverse user turns after restart/backlog replay and corrupt the conversation transcript; make the durable queue ordering monotonic or include receiveOrder in the claim order before enqueueing.

Useful? React with 👍 / 👎.

steipete added 2 commits July 18, 2026 06:03
Closed verdict shape for the retry result (queue enqueue's metadata generic
leaks any into the union), Promise.resolve-wrapped abandonment aggregators,
braced timeout executor, and the drain merged to a single const (lazy
closures above only run post-start, so const-after-use is TDZ-safe).
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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

@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: c3b9e6759f

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

receiveOrder: context.receiveOrder ?? context.receivedAt,
turnAdoptionLifecycle: context.lifecycle,
});
return "deferred";

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 configured WhatsApp debounce batching

When debounceMs is non-zero and a user sends two text messages in the same WhatsApp chat within the debounce window, this path enqueues the first item into the debouncer and then returns deferred; the ingress drain keeps that remoteJid lane claimed until the single item adopts, so the second row cannot reach createInboundDebouncer in time to be batched. This regresses the documented/configured WhatsApp debounce behavior for rapid same-sender texts into multiple agent turns/replies.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 1855f35 into main Jul 18, 2026
137 of 141 checks passed
@steipete
steipete deleted the claude/ingress-whatsapp branch July 18, 2026 05:14
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 18, 2026
…0418)

* refactor(whatsapp): replay durable inbound through the shared drain

Accept-before-processing stays; the private startup replay loop and inline
complete/release bookkeeping move to the core drain. Drain-owned entries keep
their durable id so downstream failures release for replay, dedupe-claim
contention stays retryable instead of tombstoning, and undeliverable claims
still send configured read receipts. Rows tombstone at dispatch return
(pre-migration timing), not at adoption (openclaw#108656).

* fix(whatsapp): finish durable ingress drain adoption with serialized conversation lanes

Core durable ingress intentionally serializes claims by remote JID. Same-conversation bursts now merge as queued followups in the core reply lane after adoption; channel debouncing remains for control and retry paths, with merged fan-out and gated settlement.

Built on the durable drain branch base by @obviyus.

* fix(whatsapp): fail closed on persistence failure and guard prepared-inbound races

Landing autoreview caught two holes: the persistence-failure fallback
dispatched live, bypassing drain dedupe and lane serialization now that the
replay guard is deleted (duplicate replies / session races); and duplicate
pending rows could orphan or clobber preparedInboundByDurableId entries. The
append now retries transient failures with short backoff then drops loudly
(fail closed — the fallback traded a correctness race for availability
against an already-broken store); redeliveries neither clobber the first
delivery's in-flight preparation nor keep orphan entries. The old
fallback-contract test is repurposed to prove retry-then-durable-delivery.

* fix(whatsapp): dispose the durable drain when the close drain times out

The close timeout abandoned the graceful drain path before its finally could
dispose, so a successor monitor could pump the same account queue against a
still-live drain. The timeout wrapper now owns disposal; dispose is
idempotent so the graceful path's cleanup is unaffected.

* style(whatsapp): keep ingress internals unexported and drop a dead harness helper

* refactor(whatsapp): move durable payload serialization to its own module

The dead-export gate refused serializer/error exports whose only external
consumers were tests. The payload contract (Long-timestamp-preserving
serialize/deserialize + the permanent-error class) now lives in
durable-payload.ts with durable-receive as its production consumer; the dead
WhatsAppRetryableInboundError class is deleted (any non-permanent error is
retryable to the drain classifier, so test-support throws a plain Error).

* fix(whatsapp): guard prepared-map ownership and bound its growth

A duplicate pending delivery's finishPreparation deleted the first
delivery's kept entry (ownership guard now requires the deleter to be the
installer), and queue pruning could evict pending rows whose prepared-map
entries then lingered forever on a blocked lane (map now evicts oldest-first
at a bound above the queue's pending cap; dispatch already re-normalizes the
journaled payload when its entry is gone). Regression covers the duplicate
case.

* style(whatsapp): prune split leftovers and satisfy consistent-return lint

* style(whatsapp): satisfy type-aware lint across the drain monitor

Closed verdict shape for the retry result (queue enqueue's metadata generic
leaks any into the union), Promise.resolve-wrapped abandonment aggregators,
braced timeout executor, and the drain merged to a single const (lazy
closures above only run post-start, so const-after-use is TDZ-safe).

---------

Co-authored-by: Ayaan Zaidi <[email protected]>
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]>
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
…0418)

* refactor(whatsapp): replay durable inbound through the shared drain

Accept-before-processing stays; the private startup replay loop and inline
complete/release bookkeeping move to the core drain. Drain-owned entries keep
their durable id so downstream failures release for replay, dedupe-claim
contention stays retryable instead of tombstoning, and undeliverable claims
still send configured read receipts. Rows tombstone at dispatch return
(pre-migration timing), not at adoption (openclaw#108656).

* fix(whatsapp): finish durable ingress drain adoption with serialized conversation lanes

Core durable ingress intentionally serializes claims by remote JID. Same-conversation bursts now merge as queued followups in the core reply lane after adoption; channel debouncing remains for control and retry paths, with merged fan-out and gated settlement.

Built on the durable drain branch base by @obviyus.

* fix(whatsapp): fail closed on persistence failure and guard prepared-inbound races

Landing autoreview caught two holes: the persistence-failure fallback
dispatched live, bypassing drain dedupe and lane serialization now that the
replay guard is deleted (duplicate replies / session races); and duplicate
pending rows could orphan or clobber preparedInboundByDurableId entries. The
append now retries transient failures with short backoff then drops loudly
(fail closed — the fallback traded a correctness race for availability
against an already-broken store); redeliveries neither clobber the first
delivery's in-flight preparation nor keep orphan entries. The old
fallback-contract test is repurposed to prove retry-then-durable-delivery.

* fix(whatsapp): dispose the durable drain when the close drain times out

The close timeout abandoned the graceful drain path before its finally could
dispose, so a successor monitor could pump the same account queue against a
still-live drain. The timeout wrapper now owns disposal; dispose is
idempotent so the graceful path's cleanup is unaffected.

* style(whatsapp): keep ingress internals unexported and drop a dead harness helper

* refactor(whatsapp): move durable payload serialization to its own module

The dead-export gate refused serializer/error exports whose only external
consumers were tests. The payload contract (Long-timestamp-preserving
serialize/deserialize + the permanent-error class) now lives in
durable-payload.ts with durable-receive as its production consumer; the dead
WhatsAppRetryableInboundError class is deleted (any non-permanent error is
retryable to the drain classifier, so test-support throws a plain Error).

* fix(whatsapp): guard prepared-map ownership and bound its growth

A duplicate pending delivery's finishPreparation deleted the first
delivery's kept entry (ownership guard now requires the deleter to be the
installer), and queue pruning could evict pending rows whose prepared-map
entries then lingered forever on a blocked lane (map now evicts oldest-first
at a bound above the queue's pending cap; dispatch already re-normalizes the
journaled payload when its entry is gone). Regression covers the duplicate
case.

* style(whatsapp): prune split leftovers and satisfy consistent-return lint

* style(whatsapp): satisfy type-aware lint across the drain monitor

Closed verdict shape for the retry result (queue enqueue's metadata generic
leaks any into the union), Promise.resolve-wrapped abandonment aggregators,
braced timeout executor, and the drain merged to a single const (lazy
closures above only run post-start, so const-after-use is TDZ-safe).

---------

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: whatsapp-web Channel integration: whatsapp-web 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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.

2 participants