Skip to content

[Fix] Persist WhatsApp inbound delivery - #85257

Closed
samzong wants to merge 1 commit into
openclaw:mainfrom
samzong:fix/whatsapp-durable-inbound
Closed

samzong wants to merge 1 commit into
openclaw:mainfrom
samzong:fix/whatsapp-durable-inbound

Conversation

@samzong

@samzong samzong commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fixes WhatsApp inbound message loss by adding an authDir-local durable inbound queue before handler dispatch.
  • Serializes every durable queue store operation per inbound-queue.json file so accept/complete/retry read-modify-write cycles cannot overwrite each other inside one process.
  • Replays pending durable inbound records on monitor startup, completes them only after successful/non-retryable finalization, and delays read receipts until finalization.

Closes #50563.

Scope

  • WhatsApp plugin inbound monitor and durable inbound queue only.
  • No WhatsApp auth, outbound delivery, provider, gateway protocol, or public plugin API changes.

Real behavior proof

  • Behavior addressed: A WhatsApp inbound message accepted by the monitor is durably queued before processing, remains pending after a retryable handler failure, replays through the monitor on the next attach, completes after successful replay, and only then sends a read receipt.
  • Real environment tested: macOS local OpenClaw checkout, Node v24.14.0, production extensions/whatsapp/src/inbound/monitor.ts, production extensions/whatsapp/src/inbound/durable-queue.ts, a fake WASocket event emitter, and a real temporary authDir on disk.
  • Exact steps or command run after this patch: AUTH_DIR=$(mktemp -d) node --import tsx --input-type=module <<'EOF' ... EOF; the script imported production attachWebInboxToSocket, WhatsAppRetryableInboundError, and loadPendingDurableInboundMessages, emitted a real messages.upsert event into the monitor, forced a retryable handler failure, closed the monitor, attached a second monitor against the same authDir, and waited for durable replay completion.
  • Evidence after fix:
[whatsapp] Failed handling inbound web message: WhatsAppRetryableInboundError: proof retry
{
  "firstRun": {
    "handlerCalls": 1,
    "pendingAfterRetry": 1,
    "readReceiptsBeforeSuccess": 0
  },
  "replayRun": {
    "handlerCalls": 1,
    "pendingAfterReplayComplete": 0,
    "readReceiptsAfterReplayComplete": 1
  },
  "store": {
    "exists": true,
    "pending": 0,
    "completed": 1,
    "file": "inbound-queue.json"
  }
}
  • Observed result after fix: The first monitor run retained the message in inbound-queue.json after retryable failure and did not mark it read. The second monitor attach replayed that pending record through the monitor, completed it, drained pending to 0, recorded one completed ID, and sent one read receipt after successful replay.
  • What was not tested: Live WhatsApp Web crash/restart with real account traffic was not run.
  • Before evidence: Source-level issue Message loss on gateway crash (ack-before-process) #50563 documents the ack-before-process message-loss mode; ClawSweeper also confirmed current main marks WhatsApp messages read before handler completion.

Root Cause

  • The old monitor path used in-memory processing state around messages.upsert; a crash after receipt but before handler completion left no authDir-backed pending record to replay.
  • The first durable queue patch still depended on re-entrant withFileLock for same-process read-modify-write serialization, so overlapping accept/complete/retry operations could lose updates.

Regression Test Plan

  • Target test files:
    • extensions/whatsapp/src/inbound/durable-queue.test.ts
    • extensions/whatsapp/src/monitor-inbox.behavior.test.ts
  • Scenario locked in: overlapping durable accept and complete writes against one inbound-queue.json store serialize correctly, and the monitor still dispatches/retries/replays inbound messages through the existing behavior harness.

Verification

  • node scripts/run-vitest.mjs extensions/whatsapp/src/inbound/durable-queue.test.ts extensions/whatsapp/src/monitor-inbox.behavior.test.ts
    • Result: 2 files passed, 59 tests passed.
  • AUTH_DIR=$(mktemp -d) node --import tsx --input-type=module <<'EOF' ... EOF
    • Result: monitor-level durable retry/replay proof shown above.

Security Impact

  • New permissions/capabilities? No.
  • Secrets/tokens handling changed? No.
  • New/changed network calls? No.
  • Command/tool execution surface changed? No.
  • Data access scope changed? Yes.
  • Risk and mitigation: WhatsApp inbound payloads are now persisted under the existing local WhatsApp auth/session directory. The queue is account-scoped, file-locked, same-process serialized, and prunes completed IDs.

Risks

  • Persisting inbound WhatsApp payloads increases local authDir storage sensitivity; this stays inside the existing WhatsApp authDir boundary.
  • Live WhatsApp Web crash/restart with a real account remains untested in this PR.

@openclaw-barnacle openclaw-barnacle Bot added channel: whatsapp-web Channel integration: whatsapp-web size: L triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels May 22, 2026
@clawsweeper

clawsweeper Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

Latest ClawSweeper review: 2026-05-22 17:11 UTC / May 22, 2026, 1:11 PM ET.

Workflow note: Future ClawSweeper reviews update this same comment in place.

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.

Summary
The branch adds an authDir-local durable WhatsApp inbound queue with replay-on-attach, serialized store updates, delayed read receipts, duplicate read-receipt retry handling, and focused monitor/queue tests.

Reproducibility: yes. at source level: current main sends WhatsApp read receipts before enrichment, dedupe claim, activity recording, and enqueueInboundMessage. I did not run a live crash path in this read-only review.

PR rating
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🐚 platinum hermit
Summary: Good normal PR quality: focused implementation, useful terminal proof, and no blocking findings, with confidence limited by live-transport and retention-policy risk.

Rank-up moves:

  • none
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.

Real behavior proof
Sufficient (terminal): The PR body includes terminal output from production monitor and durable queue code showing retry retention, replay completion, and delayed read receipt after the fix; live WhatsApp account crash/restart is explicitly untested.

Risk before merge

  • Live WhatsApp Web crash/restart with real account traffic remains untested; the supplied proof uses production monitor/queue code with a fake WASocket emitter and real temporary authDir.
  • Persisting inbound WhatsApp payloads under authDir increases local data-at-rest sensitivity within the existing WhatsApp session directory boundary.
  • If the durable queue cannot be written or locked, the new path fails before handler dispatch; that protects against silent loss but is an upgrade-visible message-delivery behavior change.
  • The new inboundProcessingChain intentionally serializes replay, live accept, and finalization, which can change burst-concurrency behavior for WhatsApp inbound traffic.

Maintainer options:

  1. Merge after delivery-policy acceptance (recommended)
    If targeted WhatsApp tests and required checks are green, maintainers can merge while explicitly owning authDir payload retention, fail-closed queue writes, and sequential inbound processing.
  2. Require live crash/restart proof
    Ask for redacted real-account WhatsApp Web crash/restart proof if maintainers want transport-level replay and read-receipt timing validated before merge.
  3. Pause for retention or throughput policy
    Pause this PR if full inbound payload retention or serialized burst processing needs a narrower cleanup, encryption, retention, or concurrency design first.

Next step before merge
No narrow automated repair remains; maintainers should review CI and explicitly accept the WhatsApp delivery, local-retention, and non-live-proof tradeoffs before merge.

Security
Cleared: No supply-chain, permission, credential, or new execution-surface regression was found; the security-relevant change is intentional local WhatsApp payload persistence under authDir.

Review details

Best possible solution:

Land the WhatsApp-plugin durable handoff if targeted tests and required checks are green and maintainers accept authDir retention, fail-closed queue writes, and sequential inbound ordering.

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

Yes, at source level: current main sends WhatsApp read receipts before enrichment, dedupe claim, activity recording, and enqueueInboundMessage. I did not run a live crash path in this read-only review.

Is this the best way to solve the issue?

Yes, mostly: durable queueing before handler dispatch with replay and delayed read receipts is the right WhatsApp-owned boundary, and the current head addresses earlier serialization and duplicate read-receipt review notes. The remaining question is maintainer acceptance of storage and delivery-ordering policy, not a narrow code defect.

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes terminal output from production monitor and durable queue code showing retry retention, replay completion, and delayed read receipt after the fix; live WhatsApp account crash/restart is explicitly untested.

Label justifications:

  • P1: This PR targets a broken WhatsApp inbound workflow where a crash can silently lose a user message after acknowledgment state.
  • merge-risk: 🚨 message-delivery: Merging changes WhatsApp delivery semantics through durable queue writes, delayed read receipts, duplicate retry behavior, and serialized inbound processing.
  • rating: 🐚 platinum hermit: Current PR rating is 🐚 platinum hermit because proof is 🐚 platinum hermit, patch quality is 🐚 platinum hermit, and Good normal PR quality: focused implementation, useful terminal proof, and no blocking findings, with confidence limited by live-transport and retention-policy risk.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes terminal output from production monitor and durable queue code showing retry retention, replay completion, and delayed read receipt after the fix; live WhatsApp account crash/restart is explicitly untested.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes terminal output from production monitor and durable queue code showing retry retention, replay completion, and delayed read receipt after the fix; live WhatsApp account crash/restart is explicitly untested.

Acceptance criteria:

  • node scripts/run-vitest.mjs extensions/whatsapp/src/inbound/durable-queue.test.ts extensions/whatsapp/src/monitor-inbox.behavior.test.ts
  • Required PR checks for the exact head SHA
  • Optional redacted real-account WhatsApp Web crash/restart proof if maintainers require transport-level validation

What I checked:

  • Current main has the ack-before-process path: Current main calls maybeMarkInboundAsRead(inbound) before append filtering, enrichment, dedupe claim, activity recording, and enqueueInboundMessage, matching the linked message-loss report. (extensions/whatsapp/src/inbound/monitor.ts:841, 718cc1b9b666)
  • PR adds per-file durable queue serialization: The PR's durable queue uses a process-local storeOperationQueues chain before withFileLock, matching the earlier review concern that the SDK file lock is re-entrant in one process. (extensions/whatsapp/src/inbound/durable-queue.ts:13, fb6c5a5e2f63)
  • SDK file-lock contract supports the serialization concern: The local SDK explicitly documents acquireFileLock as a re-entrant process-local file lock, so same-process read-modify-write cycles need their own queueing when writes target one file. (src/plugin-sdk/file-lock.ts:77, 718cc1b9b666)
  • PR delays durable finalization and read receipts until handler outcome: finalizeInboundEntries now completes durable records, commits dedupe, and only then sends read receipts; retryable handler errors release dedupe and keep durable records pending. (extensions/whatsapp/src/inbound/monitor.ts:286, fb6c5a5e2f63)
  • PR replays pending durable messages and retries duplicate read receipts: The PR loads pending durable records on attach, processes them before live work via inboundProcessingChain, and retries read receipts for completed duplicate deliveries with stored receipt targets. (extensions/whatsapp/src/inbound/monitor.ts:1041, fb6c5a5e2f63)
  • PR includes focused concurrency and replay-related tests: The new durable queue test covers overlapping accept/complete writes against one store, and the monitor behavior tests cover duplicate read-receipt retry and retryable inbound redelivery. (extensions/whatsapp/src/inbound/durable-queue.test.ts:53, fb6c5a5e2f63)

Likely related people:

  • steipete: GitHub commit history for web: send read receipts for inbound messages shows the original Baileys sock.readMessages behavior that this PR reorders. (role: introduced read-receipt behavior / adjacent owner; confidence: high; commits: a331bd5ea14c; files: src/provider-web.ts, extensions/whatsapp/src/inbound/monitor.ts)
  • vincentkoc: Feature history shows Vincent Koc added the claimable dedupe helper and then wired WhatsApp inbound retry/dedupe sequencing around claimRecentInboundMessage, commitRecentInboundMessage, and releaseRecentInboundMessage. (role: inbound dedupe and retry contributor; confidence: high; commits: 028434a00ffd, d70e6b13d7e1; files: src/plugin-sdk/persistent-dedupe.ts, extensions/whatsapp/src/inbound/dedupe.ts, extensions/whatsapp/src/inbound/monitor.ts)
  • mcaxtr: Recent merged WhatsApp multi-account inbound-state work touched monitor-adjacent account policy and defaults, making this a useful routing candidate for review context. (role: recent adjacent WhatsApp inbound contributor; confidence: medium; commits: 458a52610a4d; files: extensions/whatsapp/src/account-config.ts, extensions/whatsapp/src/accounts.ts, extensions/whatsapp/src/inbound/monitor.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 718cc1b9b666.

@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: 2f74c685b5

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

@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels May 22, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels May 22, 2026
@clawsweeper

clawsweeper Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

✨ Hatched: 🌱 uncommon Gilded Branchling

Hatch command

Comment @clawsweeper hatch when this PR is hatchable.

Hatchability rules:

  • Merged PRs are hatchable.
  • Open PRs are hatchable when they are status: 👀 ready for maintainer look, status: 🚀 automerge armed, or labeled clawsweeper:automerge.
  • Closed unmerged PRs are hatchable only when one of those hatchable labels is still present in the durable record.

Rarity: 🌱 uncommon.
Trait: purrs at green checks.
Image traits: location green-check meadow; accessory rollback rope; palette sunrise gold and clean white; mood calm; pose holding its accessory up for inspection; shell smooth pearl shell; lighting clean product lighting; background small green status lights.
Share on X: post this hatch
Copy: My PR egg hatched a 🌱 uncommon Gilded Branchling in ClawSweeper.

What is this egg doing here?
  • Eggs appear after the PR passes real-behavior proof. It is here for vibes, not verdicts: it does not change labels, ratings, merge decisions, or automation.
  • The shell reacts to review momentum: open follow-up work warms it up, re-review makes it wobble, and a clean final review lets it hatch.
  • Hatchability usually comes from sufficient real-behavior proof, no blocking P0/P1/P2 findings, no security attention needed, and clean correctness. A merged PR is already final, so merge makes the egg hatchable independently.
  • The hatch is seeded from this repository and PR number, so the same PR keeps the same creature; the reviewed head SHA can only change safe visual details.
  • Rarity is just collectible sparkle: 🥚 common, 🌱 uncommon, 💎 rare, ✨ glimmer, and 🌈 legendary.

@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 22, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 May 22, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 22, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 22, 2026
@samzong

samzong commented May 22, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

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

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

@martingarramon martingarramon 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.

The durable queue has the expected pieces: process-local serialization via the per-file enqueueStoreOperation promise chain; cross-process safety via withFileLock + writeJsonFileAtomically; and prepareMessage/reviveMessage round-tripping through BufferJSON.replacer/reviver for protobuf Long fields that don't serialize cleanly. The replay-on-startup path feeds into inboundProcessingChain, so pending records are processed before new live messages arrive. The SHA-256 dedup key on accountId + remoteJid + messageId + participantJid covers the resumed-session duplicate case.

Two things to confirm:

Sequential processing: enqueueInboundProcessing now chains all handleMessagesUpsert calls behind a single inboundProcessingChain. Previously each call was an independent fire-and-forget task. That means burst traffic will queue instead of overlap. Intentional? If yes, a brief comment in the function noting the sequential constraint would help future readers understand the tradeoff.

Read receipt timing + getCurrentSock(): read receipts now fire after handler finalization rather than on message receipt; getCurrentSock() ?? sock in maybeMarkInboundAsRead covers the post-reconnect case. The test changes to vi.waitFor on sock.readMessages assertions confirm the async ordering is working. No ask here, just confirming that's the intended semantic change.

LGTM pending confirmation on sequential processing.

@samzong
samzong force-pushed the fix/whatsapp-durable-inbound branch from 086506d to d74cde7 Compare May 22, 2026 17:00
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 22, 2026
@samzong

samzong commented May 22, 2026

Copy link
Copy Markdown
Contributor Author

@martingarramon Thanks, yes, the sequential processing is intentional.
I added a short comment to make that explicit.

@samzong
samzong force-pushed the fix/whatsapp-durable-inbound branch from d74cde7 to fb6c5a5 Compare May 22, 2026 17:05
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 22, 2026
@steipete steipete self-assigned this May 22, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thanks for digging into the inbound-loss path here. I agree with the problem, but we decided not to land a WhatsApp-local JSON disk cache because this is a shared channel delivery concern and we already have the plugin-state keyed store that can move onto the SQLite/runtime DB path cleanly.

I opened a replacement PR at #85506. It adds a generic channel-message durable receive journal backed by plugin state, wires WhatsApp through that pending/completed journal, delays read receipts until handler completion, releases retryable failures for redelivery, and falls back to live delivery if persistence rejects an oversized payload.

Closing this PR in favor of that narrower shared-core/API shape. Thank you again for surfacing the issue and for the first pass on the failure mode.

@steipete steipete closed this May 22, 2026
@martingarramon

Copy link
Copy Markdown
Contributor

Concern resolved. The new comment makes the serialization intent explicit: withFileLock is process-local re-entrant, so same-file store cycles are intentionally sequenced through storeOperationQueues. LGTM.

@samzong

samzong commented May 23, 2026

Copy link
Copy Markdown
Contributor Author

@steipete Thanks for the clarification, I will check it.

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 merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

Message loss on gateway crash (ack-before-process)

3 participants