Skip to content

fix(zalo): journal polled inbound updates across restarts - #110559

Closed
wangmiao0668000666 wants to merge 1 commit into
openclaw:mainfrom
wangmiao0668000666:fix/zalo-ingress-durability
Closed

wangmiao0668000666 wants to merge 1 commit into
openclaw:mainfrom
wangmiao0668000666:fix/zalo-ingress-durability

Conversation

@wangmiao0668000666

Copy link
Copy Markdown
Contributor

What Problem This Solves

Zalo long-polling — the default inbound mode when no webhook is configured — loses messages permanently in two windows:

  1. Crash window. getUpdates (extensions/zalo/src/api.ts:249-258) sends only {timeout}; no offset parameter exists and ZaloUpdate (api.ts:51-58) carries no update id, so the client can never confirm or replay — the server consumes each update on response. In the poll loop (monitor.ts), a crash between the getUpdates response and processUpdate completion destroys the only copy of the message. It is never redelivered.
  2. Dispatch-error window. Before this change the poll loop called await processUpdate(...) directly and the surrounding catch only logged Zalo polling error and polled on — any handler failure silently dropped the consumed update.

The webhook sibling had the weaker form of the same bug: detached processing with an immediate 200 and a memory-only replay guard (5 min TTL), so a restart forgot recent deliveries and a post-ack handler failure was committed-and-dropped.

Why This Change Was Made

This mirrors the maintainer-blessed "inbound durability across restart" wave that landed on main in the last 24h — #110418 whatsapp, #110409 imessage, #110386 mattermost, #110357 msteams, #110274 discord, #109910 slack, #109866 sms, #109907 signal, line webhook-spool (#109655/#109819) — all built on the core durable ingress drain (src/channels/message/ingress-drain.ts, #108656 lineage). Zalo adopts the same mechanism through the same SDK seam (openclaw/plugin-sdk/channel-outbound: createChannelIngressDrain, bindIngressLifecycleToReplyOptions), storing rows in the existing channel_ingress_events table of the shared state DB — no schema change.

Design (closest template: extensions/sms/src/ingress-spool.ts, mapped to Zalo's polling chokepoint):

  • New extensions/zalo/src/monitor-ingress.ts: createZaloIngressSpool journals each inbound update before it can be lost. Event id = JSON.stringify([chatId, senderId, messageId]) (JSON encoding keeps ids unambiguous; message_id is contract-required per api.ts:31), lane = one per chat for per-conversation serialization.
  • Polling loop: enqueue first, then drainOnce() + waitForIdle() each cycle (preserves the old one-at-a-time backpressure), pumping retries even on empty polls. Dispatch errors are now drain-owned: retry with backoff (8 attempts / 24h dead-letter gate) instead of silent drop.
  • Webhook: 200 only after the journal append (durable-before-ack); an append failure answers 500 so Zalo redelivers. The retired memory-only replay guard is deleted; 30d/20k tombstones dominate its 5min/5k window.
  • Adoption lifecycle is threaded into core.channel.inbound.dispatch (turnAdoptionLifecycle) so claims tombstone when recovery-relevant turn state is durable; events dropped pre-dispatch (unauthorized, sticker/unsupported, empty text) complete at dispatch return.
  • Fail closed: the append retries transient SQLite errors (250/750ms) then throws loudly — no unjournaled live dispatch fallback (the whatsapp landed-autoreview lesson).

Honest note: Zalo's server-side consume-on-response semantics are code-inferred — no offset/id field exists in the client contract, so the journal is correct under any server semantics (worst case it dedupes a redelivery).

User Impact

  • Polling mode (default): a gateway crash/restart no longer loses the in-flight Zalo message; it replays on startup. Handler failures retry with backoff instead of vanishing.
  • Webhook mode: deliveries survive restarts; replays dedupe durably (30d) instead of 5 minutes in memory; failed appends get a 500 so Zalo redelivers.
  • No config/schema changes; journal rows live in the existing shared state DB table already used by telegram/sms/signal/whatsapp.
  • Updates without a message (no-ops downstream) and malformed messages missing the contract-required message_id are acknowledged without journaling (logged), since they can be neither deduped nor replayed.

Evidence

  • New extensions/zalo/src/monitor-ingress.test.ts (8 tests, real SQLite queues in temp dirs via createChannelIngressQueueForTests): crash-window replay (journal → dispose without dispatch → fresh spool replays exactly once), tombstone dedupe, complete-at-dispatch-return, retryable-failure retry, permanent-failure dead-letter, ignore-without-message, per-chat event-id scoping, per-chat lane.
  • monitor.webhook.test.ts (14 tests): real-spool journal-before-ack + detached drain over HTTP, durable replay dedupe, 500-on-append-failure redelivery contract, plus retained rate-limit/auth guards.
  • Reverse verification: with the durable append in enqueue removed, 6/8 spool tests go red (crash replay, dedupe, complete-at-return, retry, scoping, lane); restored, all 8 pass.
  • Full zalo suite: 126/127 pass. The single failure (setup-surface.test.ts wizard prompt, locale-dependent) fails identically on an untouched main checkout — pre-existing, unrelated.
  • node scripts/run-tsgo.mjs -p tsconfig.extensions.json: zero errors in touched files (only the 3 pre-existing packages/net-policy/src/ip.ts errors from stale worktree ipaddr.js types).
  • Existing end-to-end lifecycle tests (polling image, pairing, reply-once) run the real monitor through the journal and stay green, proving no regression in the happy path.

@openclaw-barnacle openclaw-barnacle Bot added channel: zalo Channel integration: zalo size: L labels Jul 18, 2026
@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
@clawsweeper

clawsweeper Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 18, 2026, 4:11 AM ET / 08:11 UTC.

Summary
The branch routes Zalo polling and webhook updates through the shared durable ingress queue, replacing in-memory replay handling with persisted enqueue, replay, retry, and lifecycle settlement.

PR surface: Source +151, Tests +195. Total +346 across 9 files.

Reproducibility: unclear. for a live reproduction. The PR describes a source-level crash/dispatch-loss path, but the current-main Zalo implementation could not be inspected in this environment.

Review metrics: none identified.

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🦐 gold shrimp
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] Add redacted proof from a real Zalo polling or webhook restart/retry path.
  • Re-run full source and ingress-contract review once read-only repository access is available.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The body describes SQLite-backed tests and CI, but no inspectable real Zalo polling or webhook after-fix run demonstrates restart recovery or retry behavior; provide redacted live output, logs, or a terminal recording. 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] Merging changes to enqueue-before-ack, retry, replay, and claim settlement without a complete source/contract comparison could drop, duplicate, or indefinitely retain inbound Zalo messages.
  • [P1] The PR body provides test assertions but no inspectable after-fix live Zalo polling or webhook restart/retry evidence.

Maintainer options:

  1. Validate the adapter before merge (recommended)
    Confirm durable admission, replay, lifecycle completion, shutdown, and webhook response behavior against the shared drain contract and capture real Zalo behavior proof.
  2. Pause for a narrower review
    Pause the PR if the Zalo transport’s redelivery or polling-consumption contract cannot be established from source and provider evidence.

Next step before merge

  • [P1] The remaining work is maintainer validation of a delivery-sensitive adapter and contributor-supplied real behavior proof, not a defined mechanical repair.

Security
Cleared: The supplied diff adds no dependency, workflow, secret, permission, package-resolution, or external-code-execution change; the principal concern is message-delivery correctness.

Review details

Best possible solution:

Compare the Zalo adapter with the current shared ingress-drain contract and a merged channel reference, then obtain a redacted real Zalo polling or webhook restart/retry transcript before merge.

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

Unclear for a live reproduction. The PR describes a source-level crash/dispatch-loss path, but the current-main Zalo implementation could not be inspected in this environment.

Is this the best way to solve the issue?

Unclear. Using the shared durable ingress drain is consistent with the supplied adjacent-channel context, but the Zalo-specific lifecycle and transport assumptions still need direct contract review.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 34440523cd03.

Label changes

Label changes:

  • add P1: The PR addresses a plausible silent-loss path for accepted inbound Zalo messages.
  • add merge-risk: 🚨 message-delivery: It changes acknowledgement timing, persistent replay, retry, and completion semantics for inbound messages.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The body describes SQLite-backed tests and CI, but no inspectable real Zalo polling or webhook after-fix run demonstrates restart recovery or retry behavior; provide redacted live output, logs, or a terminal recording. 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 addresses a plausible silent-loss path for accepted inbound Zalo messages.
  • merge-risk: 🚨 message-delivery: It changes acknowledgement timing, persistent replay, retry, and completion semantics for inbound messages.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The body describes SQLite-backed tests and CI, but no inspectable real Zalo polling or webhook after-fix run demonstrates restart recovery or retry behavior; provide redacted live output, logs, or a terminal recording. 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 +151, Tests +195. Total +346 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 6 281 130 +151
Tests 3 391 196 +195
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 672 326 +346

What I checked:

  • PR scope: The supplied PR diff adds a Zalo ingress spool and changes both polling and webhook admission to journal inbound updates before asynchronous dispatch. (extensions/zalo/src/monitor-ingress.ts:1, 492881926c19)
  • Shared-pattern context: The supplied related-item context shows that the core durable ingress drain was recently introduced and adopted by several channel implementations; this PR is a Zalo-specific application of that seam. (src/channels/message/ingress-drain.ts:1, 34440523cd03)
  • Inspection blocker: The required read-only local inspection command failed before producing repository output because the sandbox could not create its loopback address; the available web fetches also failed on cache misses.

Likely related people:

  • obviyus: The supplied related context credits the core durable ingress drain lineage to this contributor, whose core seam the Zalo adapter consumes. (role: shared-ingress feature author; confidence: medium; files: src/channels/message/ingress-drain.ts)
  • steipete: The supplied related merged PRs show repeated recent ownership of comparable durable-inbound integrations across channels. (role: recent adjacent channel contributor; confidence: medium; commits: 1855f35d7d9b, 4e0cc187a21c; files: extensions/whatsapp/src/inbound/durable-receive.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.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing: the webhook half of this PR is superseded by steipete's #110630 (fix(zalo): prevent webhook message loss after acknowledgment, merged 2026-07-18), which landed the same durable-append-before-200 design on the webhook path — dedupe by Bot API message ID, chat-ID lane serialization, shared ingress drain with bounded retries / dead-letter / restart recovery (extensions/zalo/src/webhook-spool.ts). Verifying against current main (monitor.ts + webhook-spool.ts): the webhook loss window this PR targeted is closed.

The polling half remains a live gap on main: the Bot API consumes each polled update on response (no offset/confirm parameter — api.ts getUpdates sends only { timeout }), and the polling loop still calls processUpdate directly after getUpdates with no durable journal (monitor.ts polling poll()). A crash between poll response and dispatch completion still loses that update. I will re-propose that narrower fix as a focused follow-up PR built on the post-#110630 world.

Branch stays on the fork for reference. Thanks for the reviews!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: zalo Channel integration: zalo 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: L 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