Repository navigation
fix(zalo): journal polled updates before dispatch - #110803
wangmiao0668000666 wants to merge 1 commit into
Conversation
|
Codex review: needs maintainer review before merge. Reviewed August 26, 2026, 9:31 PM ET / August 27, 2026, 01:31 UTC. ClawSweeper reviewWhat this changesThe branch routes Zalo polling updates through the existing SQLite-backed ingress queue before agent dispatch and adds replay, deduplication, shutdown, and failure-path coverage. Merge readinessKeep open for channel-owner review: current main still has the loss window, and the shared-ingress repair is coherent, but it deliberately changes polling from serial dispatch to up to eight concurrent cross-chat deliveries. Priority: P1 Review scores
Verification
Live VerificationCommand: Result: PASS (completed) Assertions:
How this fits togetherThe Zalo polling monitor receives one Bot API update at a time and dispatches it into an agent run. The ingress monitor is the durable boundary that stores an update, serializes each chat lane, retries delivery, and recovers unfinished work after restart. flowchart LR
A[Zalo Bot API] --> B[Polling monitor]
B --> C[Durable ingress queue]
C --> D[Per-chat delivery lane]
D --> E[Agent dispatch]
E --> F[Zalo reply]
Decision needed
Why: The implementation correctly reuses the canonical queue, but its concurrency change is a user-visible channel-delivery policy choice rather than a mechanical consequence of persistence. Before merge
Agent review detailsSecurityNone. PR surfaceSource +35, Tests +358. Total +393 across 7 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain the single shared durable ingress owner and land it only after the channel owner explicitly accepts the cross-chat concurrency policy and verifies the exact merge result. Do we have a high-confidence way to reproduce the issue? Yes, at source level: current main receives an update and awaits direct dispatch without journaling it. The PR body also supplies before/after production-monitor output using real SQLite and a protocol-compatible local Bot API stub, though this read-only review did not rerun it. Is this the best way to solve the issue? Yes, conditionally: reusing the existing Zalo durable ingress is the canonical repair rather than creating a second journal, but the resulting concurrency policy requires owner acceptance. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against c6fa27aea68b. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (12 earlier review cycles; latest 8 shown)
|
|
CI lint fix pushed ( |
Yigtwxx
left a comment
There was a problem hiding this comment.
Design looks right to me — routing polling into the same durable ingress Telegram already uses (telegram-ingress-worker.runtime.ts) reuses the canonical path rather than inventing a second one, and I checked that all four added tests genuinely fail on main. Two loss windows the patch leaves open, both siblings of the one it closes.
One behavioral note for the description while you're in here: the delivery concurrency changes with this patch. On main the loop awaited processUpdate inline, so polling ran one update at a time and was back-pressured by agent turn duration; after this, acceptUpdate returns once the row is appended and the drain runs at ZALO_WEBHOOK_MAX_CONCURRENT_DELIVERIES = 8. Per-chat ordering is still preserved by the chat:<chatId> lane key, so this looks intentional and fine — just not quite "reuses the spool unchanged" from the polling side.
| // journal is the only crash recovery. Non-message events are no-ops | ||
| // downstream, so they skip journaling. | ||
| if (response.result.message) { | ||
| await acceptUpdate(JSON.stringify(response.result)); |
There was a problem hiding this comment.
The comment right above this is the strongest argument against the guard four lines up: if the Bot API consumes each update on response, then the abort check after getUpdates returns is itself a loss window —
const response = await getUpdates(token, { timeout: pollTimeout }, fetcher);
if (isStopped() || abortSignal.aborted) { return undefined; }the update is already consumed and there is no offset to re-fetch it with, so a normal abort() drops it permanently. That is the same loss class this PR closes for kill -9, but on the far more common path. Since ingress.stop() already awaits admissionTail, calling acceptUpdate here after abort should be safe — the append completes before shutdown returns, and it replays on restart.
Second window, same line: if acceptUpdate throws (inspectZaloWebhookEvent rejects a missing message_id/chat.id, or the ZALO_WEBHOOK_APPEND_RETRY_DELAYS_MS ladder is exhausted against a locked DB), the catch below routes it to else if (!isStopped() && !abortSignal.aborted) — so during abort it is dropped with no log at all, and otherwise it surfaces as a polling error when the transport was fine.
Worth noting the description's framing here — "malformed envelopes fail admission loudly instead of being dispatched unjournaled, mirroring the webhook 400/500 semantics" — doesn't quite transfer: a webhook 400 is safe because the sender retries, but in polling there is no sender and the update is already gone, so "fail loudly" means "lose the message". Neither path has test coverage.
| }); | ||
| // The Bot API consumes each polled update on response, so the durable | ||
| // journal is the only crash recovery. Non-message events are no-ops | ||
| // downstream, so they skip journaling. |
There was a problem hiding this comment.
Comment and gate disagree: this says non-message events skip journaling, but the gate is if (response.result.message). message.sticker.received and message.unsupported.received both carry message and are pure logVerbose no-ops in processUpdate, so they take the full journal → claim → dispatch → tombstone round trip. Harmless, but gating on event_name would make the comment true and keep the journal free of no-op rows.
|
@clawsweeper re-review |
3060f9c to
f2fe3da
Compare
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
| if (isStopped() || abortSignal.aborted) { | ||
| if (response.ok && response.result) { | ||
| await acceptUpdate(JSON.stringify(response.result)).catch((err: unknown) => |
There was a problem hiding this comment.
This branch skips the filter the same commit adds ten lines below, so the two paths disagree about what belongs in the journal.
Normal path (:270) gates on message and excludes the two no-op events. This branch gates on response.result alone. I ran both paths against the same envelopes on 1a6a117, with the normal path as the control:
| case | envelope | path | result |
|---|---|---|---|
| A | sticker | normal | journaled: [] |
| B | sticker | abort | journaled: ["probe-sticker-1"] |
| C | no message |
normal | errors: [] |
| D | no message |
abort | errors: [ "failed to journal consumed update before shutdown: ZaloWebhookPayloadError: Zalo webhook message is missing message.message_id." ] |
B is the mismatch your own comment rules out — a sticker takes the full journal → claim → dispatch → tombstone round trip only when shutdown happens to land on it. parseClaimedUpdate accepts all four event_name values, so it drains rather than dead-letters; it is wasted work and a row that the normal path would never have written.
D is the one I would not ship. message is optional on ZaloUpdate, so a message-less envelope is in contract; inspectZaloWebhookEvent rejects it at webhook-spool.ts:84, the .catch fires, and the operator gets failed to journal consumed update before shutdown — a message-loss warning for an update that was never eligible for the journal and where nothing was lost. That is a false positive in exactly the alarm this PR exists to make trustworthy.
Both go away by reusing the same predicate on both sides rather than restating it, e.g. hoisting shouldJournal(update) above the abort check and calling it in both places.
Worth noting the reason this needed a run to see: the fix commit is monitor.ts-only. My earlier review flagged that neither of these two paths had coverage, and after the fix they still don't — monitor.polling-ingress.test.ts is unchanged, so nothing pins the abort branch's admission behavior against the normal path's.
| @@ -288,6 +284,12 @@ function startPollingLoop(params: ZaloPollingLoopParams) { | |||
| runtime.error?.(`[${account.accountId}] Zalo polling error: ${formatZaloError(err)}`); | |||
| // Abort-aware backoff; bottom poll reschedule already checks stopped/aborted. | |||
| await sleepWithAbort(5000, abortSignal).catch(() => undefined); | |||
| } else { | |||
| // acceptUpdate or getUpdates failure during abort: log instead of | |||
There was a problem hiding this comment.
The comment says acceptUpdate ... failure during abort, but an acceptUpdate failure can never reach this branch: the call at :259 has its own .catch that consumes the rejection and already logs it, so await there never throws.
Case D from my run above shows it — the message-less envelope produced exactly one error, from the .catch:
failed to journal consumed update before shutdown: ZaloWebhookPayloadError: ...
and none from this branch. So what actually lands here is a getUpdates failure that happened to coincide with shutdown. getUpdates takes no abort signal (api.ts:249 — only timeoutMs and fetcher), so an in-flight long poll is not cancelled by abort(); it runs to its own 35s timeout. Its rejection then arrives with abortSignal.aborted already true and gets logged as Zalo ingress error during shutdown, which reads like a durable-store problem when it is an ordinary poll timeout during a normal stop.
Not asking for a behavior change here — dropping acceptUpdate from the comment, and saying getUpdates rather than "ingress" in the message, would make it match what the branch can actually observe.
|
Separate from the two inline notes: the description now describes a version of the branch that "Non-message events remain no-ops and skip journaling" is no longer true on both paths. Measured on
"Malformed envelopes fail admission loudly ... mirroring the webhook 400/500 semantics" now has a second reading it did not have in July 18's tree. On the abort path a message-less envelope produces More generally, Still unaddressed from my first pass, and cheap to fold into the same edit: polling delivery concurrency changes with this patch. On |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@Yigtwxx
Let me know if this aligns with what you had in mind. |
|
@clawsweeper re-review |
|
@wangmiao0668000666 Confirmed on
B and D were the two mismatches; the shared The same run carries a control case I should have included the first time, and it does not pass: the abort-path journal that
E is the control — the fixture can write. G shows the append succeeds only when the poll response lands in the same tick as The refusal comes from // src/channels/message/ingress-monitor.ts:499
if (
(stopped && options.admissionMode !== "durable-after-stop") ||
(options.admissionMode === "while-running" && !running) ||
(options.abortSignal?.aborted && options.admissionMode !== "durable-after-stop")
) {
throw createStoppedError();
}
The gap is not narrow, either. That also means my own first-pass assumption was wrong, and it is worth stating plainly rather than leaving it in the thread: I wrote "since The mode this needs already exists in-tree, and two channels set it: admissionMode: "durable-after-stop",measured with the same probe, back-to-back runs:
The full Zalo suite is indifferent to that line: Two things I am explicitly not asserting. I have not checked whether |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@Yigtwxx Thanks for the detailed probe — the admission-mode gap is exactly right. Applied in
The Zalo drain shutdown path is structurally the same as LINE and SMS (single |
|
@wangmiao0668000666 Measured 1. The fix is real, and the test is load-bearing. Mutation: delete only the added line in
Exactly one test flips, and it is the new one. Harness note: on Windows every test in this file fails on the 2. My open item from last round is clean — both sides 3. A control your test does not carry: the saved row is actually delivered. The test asserts the row lands in the queue. I extended it — after the abort journal, start a second monitor for the same account with Replayed exactly once on restart, queue drained. That is the property the branch exists for, and it holds end to end. 4. A hypothesis of mine that died — recording it so nobody re-chases it. I expected the late append to fail against a closed database, since
5. What is still overstated:
The ingress stop does not drain it. By the time the late poll returns, The wider point is that nothing holds the process open for that append:
A 35s poll against a 5s bound means that on a real shutdown the process is usually well past the channel step — and often gone — before the response arrives. I have not measured a full gateway shutdown, so I am not putting a number on how often the append actually lands; I am only saying it is best-effort, and the comment reads as a guarantee. Two ways to square it, and I think the first is the honest one:
One thing worth ruling out explicitly: making None of this argues against the change — every measured state here is better than |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@Yigtwxx Thanks for the thorough measurement — §5 is well taken. Fixed in Reworded The async lifecycle analysis (35 s getUpdates vs 5 s channel-stop deadline) matches my read. The row lands when it lands; the important property is that when it does, it is not lost. |
cea0582 to
ad4513a
Compare
|
@clawsweeper re-review Rebased onto current How the two P1 findings were resolved:
Conflict resolution notes:
Focused proof on the rebased head (Node 24.18,
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@wangmiao0668000666 Measured Resolution. runPumpTask: runDetachedWebhookWork,
deferredClaims: "wait-on-stop",
+ admissionMode: "durable-after-stop",The hand-rolled deferred-claim machinery "Identical scope" claim. Checked mechanically rather than by eye — I took the added/removed lines of the branch diff at each head and hashed them:
Byte-for-byte the same delta at all three. What changed is not the patch, it is what the patch sits on. The two P1s. Worth stating positively, because it is the part that got stronger with the rebase: now that Base. 27 commits behind Windows note — not a review finding. Three of your five numbers reproduce here; two do not, and the control says the difference is inherited, not yours. Node 24.18.1,
Every failure is the same one, in teardown, never in an assertion: At the base 9 of the 26 already fail this way — the three It is a live handle, not a slow release: raising both cleanup paths to CI is Linux, where unlinking an open file succeeds, so none of this is visible there and the merge decision does not depend on it. The reason I am writing it down: the file carrying this PR's headline proof cannot be run to green on a Windows checkout, and if someone hits that later, the base column above says where it came from. |
|
Thanks for the thorough verification — the three-head hash comparison is a much stronger confirmation of "identical scope" than my eyeball claim, and the positive note about polling inheriting the webhook partial-delivery contract via On the Windows note: agreed it is inherited, not introduced here — the base column makes that clear. But the fact that this PR's headline proof file cannot run green on a Windows checkout deserves its own tracking rather than living in a PR comment. I will file a standalone issue for the teardown Tracking issue: #119796 |
|
Follow-up on the Windows note: filed as #119796, fix PR open at #119809. Root cause confirmed against source: a fully processed update opens the per-agent DB through the real session accessor inside the envelope builder ( |
|
@wangmiao0668000666 Not a review finding — a staleness measurement, since the head has been at What moved. Three commits landed on
#122863 is the one worth knowing about: it split Merge measured locally — current
Suite,
Identical three red files on both arms — Two one-line mutations on the merge head, to check the suite still measures something there:
The second one is the informative half: that guard is #122863's, not yours, and flipping it takes the whole polling-ingress suite down — so the journaled update really runs through the new pre-dispatch re-authorization rather than around it. So the refresh is deterministic here: nothing in the last ten days of |
The Zalo Bot API consumes each polled update on response (getUpdates has no offset or confirm parameter), so a crash or restart between the poll response and dispatch completion permanently loses the message. Route polling through the same durable ingress the webhook transport uses (openclaw#110630), including durable-after-stop admission for the shutdown race, while keeping current ready/recovering status and partial-delivery recovery behavior. PR openclaw#110803
ad4513a to
f7fb490
Compare
|
@clawsweeper re-review Rebased onto current |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Superseded by #136330 — closing in favor of the behavior-preserving re-slice. Why the re-slice: this branch routed polling through the shared ingress at the webhook fan-out limit (8 concurrent cross-chat deliveries). The final review correctly flagged that as a channel-owner delivery-policy decision, and six weeks without an owner answer says the decision won't come from more patch iterations. The new PR keeps this branch's journal/replay/dedupe core (including the test suites hardened by @Yigtwxx's multi-round review) but drains the polling ingress serially ( Quantified on the same driver (details in the new PR body): the 8-concurrent shape started the second cross-chat delivery 3493 ms before the first settled and visibly reordered replies (B before A); the serial drain matches main (+8 ms, A then B). Before/after kill -9 replay proof rerun on current Branch retained as reference. Thanks again @Yigtwxx for the depth of the review here — it is what made the carried-over core safe to re-slice. |
What Problem This Solves
Follow-up to #110630, which made Zalo webhook ingress durable but left the polling transport with the same message-loss window.
The Zalo Bot API consumes each polled update on response:
getUpdateshas no offset or confirm parameter (extensions/zalo/src/api.ts), so once the poll response is returned, the server will never serve that update again. On currentmain, the polling loop callsprocessUpdatedirectly aftergetUpdateswith no durable journal (extensions/zalo/src/monitor.tspoll()). A crash or restart between the poll response and dispatch completion permanently loses the already-consumed update — no replay, no error, the sender's message just vanishes.Why This Change Was Made
Polling now admits each polled update into the same durable ingress that #110630 built for webhooks (
createZaloWebhookIngressinextensions/zalo/src/webhook-spool.ts, backed by the sharedchannel_ingress_eventsSQLite queue), before the drain dispatches it. The polling branch reuses steipete's spool for journal admission — the same dedupe key (Bot APImessage.message_id), the samechat:<chatId>lane, the same bounded retry/dead-letter policy, and the same turn-adoption lifecycle — so both transports share one canonical durability path and one per-account queue. No schema bump, no new config or env surface, no new dependency; polling and webhook stay mutually exclusive per monitor.Shutdown-path coverage. On the abort path (shutdown lands between
getUpdatesresponse and journal admission), the ingress now setsadmissionMode: "durable-after-stop"(webhook-spool.ts:235, the same pattern LINE and SMS already use) so the late poll response is still admitted into the queue afteringress.stop()has completed. The append is best-effort — the poll's 35 s deadline can outlive the 5 s channel-stop deadline — but when it lands, the row is recovered on the next restart rather than lost. A new regression test (monitor.polling-ingress.test.ts, the 5th test) pins this behavior: hangs the secondgetUpdatesin-flight, aborts, releases the late response, and asserts the consumed update is durably journaled.Consistent no-op filtering. Both the normal and abort journal paths share a single
shouldJournalpredicate, so sticker/unsupported events are skipped consistently regardless of shutdown timing.Delivery concurrency. On
mainthe loopawaitedprocessUpdateinline, so polling was back-pressured by agent turn duration (one update at a time). After this change,acceptUpdatereturns once the row is appended and the shared ingress drain runs atZALO_WEBHOOK_MAX_CONCURRENT_DELIVERIES = 8. Per-chat ordering is preserved by thechat:<chatId>lane key, so cross-chat concurrency increases without reordering messages within a conversation.This replaces the approach in our earlier (now closed) #110559 with one that harmonizes with the merged webhook design instead of adding a second journal.
User Impact
Zalo polling users no longer lose messages when the gateway crashes or restarts while a polled update is in flight: the update is journaled before dispatch, replays exactly once after restart, and duplicate Bot API redeliveries are deduped against the durable tombstone. Abort-path updates that arrive after
ingress.stop()are best-effort — journaled when the late response lands, recovered on restart. Permanent dispatch failures (e.g. revoked token → 401/403) dead-letter with an operator-visible log line instead of hot-looping.Evidence
Live behavior proof (real production
monitorZaloProvider, real SQLitechannel_ingress_events, protocol-compatible local Bot API stub)Driver: the production polling monitor, pointed at a local stub Bot API server via the existing
ZALO_API_URLoverride (extensions/zalo/src/api.ts:11), with the state DB under a throwawayOPENCLAW_STATE_DIR. The stub serves onemessage.text.receivedupdate, then holds the long-poll open (no further updates — the Bot API consumed it). Same protocol-compatible-local-server pattern as the accepted #109997 proof; #110630's Evidence notes no real Zalo account is available even to maintainers.Before (main @ 5143d90) — dispatch in flight,
kill -9, restart with the API serving nothing (update already consumed): the message is gone.After (this PR) — identical scenario: the update is journaled before dispatch, survives
kill -9, replays exactly once, the visible reply is sent once, and a re-served identical update is deduped.Tests
extensions/zalo/src/monitor.polling-ingress.test.ts(5 tests, real SQLite queue): journaled durably before dispatch + tombstoned after adoption; re-polled duplicate deduped after completion; crash between poll and dispatch replays exactly once after restart (abandoned-claim recovery); 401 dispatch failure dead-letters without retry; abort-path journaling with in-flightgetUpdates.monitor.tsstashed, all 5 new tests fail; restored, all pass.installLifecycleIngressState, renamed from the webhook-only helper); the fake-timer lifecycle test closes the state DB before asserting zero timers because the shared DB's WAL maintenance interval is process-level.Checks
node scripts/run-tsgo.mjs -p tsconfig.extensions.json— 0 errors.oxlinton all 7 changed files — clean;oxfmt --check— clean;git diff --check— clean.monitor.ts+69/−39 (net +30 prod LOC),webhook-spool.ts+1/−0 (admissionMode), plus tests; no files outsideextensions/zalo.Fixes #130566