Skip to content

fix(zalo): journal polled updates before dispatch - #110803

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

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

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

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: getUpdates has 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 current main, the polling loop calls processUpdate directly after getUpdates with no durable journal (extensions/zalo/src/monitor.ts poll()). 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 (createZaloWebhookIngress in extensions/zalo/src/webhook-spool.ts, backed by the shared channel_ingress_events SQLite queue), before the drain dispatches it. The polling branch reuses steipete's spool for journal admission — the same dedupe key (Bot API message.message_id), the same chat:<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 getUpdates response and journal admission), the ingress now sets admissionMode: "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 after ingress.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 second getUpdates in-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 shouldJournal predicate, so sticker/unsupported events are skipped consistently regardless of shutdown timing.

Delivery concurrency. On main the loop awaited processUpdate inline, so polling was back-pressured by agent turn duration (one update at a time). After this change, acceptUpdate returns once the row is appended and the shared ingress drain runs at ZALO_WEBHOOK_MAX_CONCURRENT_DELIVERIES = 8. Per-chat ordering is preserved by the chat:<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 SQLite channel_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_URL override (extensions/zalo/src/api.ts:11), with the state DB under a throwaway OPENCLAW_STATE_DIR. The stub serves one message.text.received update, 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.

--- [before] phase 1: dispatch in flight, then kill -9
[driver] dispatch #1 started for MessageSid=proof-msg-1 SessionKey=agent:main:zalo:direct:proof-chat-1
[driver] dispatch is now in flight; process will be killed before it settles
--- [before] sqlite rows before kill (queue_name='["zalo","default"]'):
[]
--- [before] killed driver with SIGKILL; sqlite rows after kill -9:
[]
--- [before] phase 2: restart (stub serves nothing — update was consumed on response)
[stub] getUpdates -> holding long-poll open (no updates)
[driver] PROOF-FAIL: journaled update was never replayed after restart   (phase2 exit=1)
--- [before] final sqlite rows:
[]

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.

--- [after] phase 1: dispatch in flight, then kill -9
[driver] dispatch #1 started for MessageSid=proof-msg-1 SessionKey=agent:main:zalo:direct:proof-chat-1
--- [after] sqlite rows before kill:
[{"event_id":"proof-msg-1","status":"claimed","attempts":0}]
--- [after] killed driver with SIGKILL; sqlite rows after kill -9:
[{"event_id":"proof-msg-1","status":"claimed","attempts":0}]
--- [after] phase 2: restart; stub re-serves the identical update once (dedupe probe)
[driver] dispatch #1 started for MessageSid=proof-msg-1   <- journal replay, before first poll answer
[driver] turn adopted; durable claim tombstoned
[driver] visible reply delivered
[stub] sendMessage -> visible reply #1: {"chat_id":"proof-chat-1","text":"pong from proof driver"}
[stub] getUpdates -> serving proof-msg-1 (1/1)            <- redelivery; no second dispatch
[driver] PROOF-PHASE2-OK dispatchCount=1 (replay exactly once, duplicate deduped)
--- [after] final sqlite rows:
[{"event_id":"proof-msg-1","status":"completed","attempts":1}]

Tests

  • New 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-flight getUpdates.
  • Reverse verification: with monitor.ts stashed, all 5 new tests fail; restored, all pass.
  • Two pre-existing polling test suites now install the real ingress queue fixture (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.
  • oxlint on all 7 changed files — clean; oxfmt --check — clean; git diff --check — clean.
  • Diff: monitor.ts +69/−39 (net +30 prod LOC), webhook-spool.ts +1/−0 (admissionMode), plus tests; no files outside extensions/zalo.

Fixes #130566

@openclaw-barnacle openclaw-barnacle Bot added channel: zalo Channel integration: zalo size: M labels Jul 18, 2026
@clawsweeper clawsweeper Bot added 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. 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 maintainer review before merge. Reviewed August 26, 2026, 9:31 PM ET / August 27, 2026, 01:31 UTC.

ClawSweeper review

What this changes

The 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 readiness

⚠️ Ready for maintainer review - 3 items remain

Keep 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
Reviewed head: f7fb4903b2640e3715e0a5e4fb2567228d38651d
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The branch has strong owner-boundary coverage and credible runtime output, with the remaining blocker being an explicit delivery-policy decision rather than a demonstrated patch defect.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body contains after-fix copied live output from the production polling monitor, a real SQLite queue, and a protocol-compatible local Bot API showing restart replay, one visible reply, and duplicate suppression.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body contains after-fix copied live output from the production polling monitor, a real SQLite queue, and a protocol-compatible local Bot API showing restart replay, one visible reply, and duplicate suppression.
Evidence reviewed 7 items Current-main loss window: Current main awaits direct processing after each successful poll response; no durable queue is created on the polling path.
Branch durable boundary: The branch creates the existing Zalo ingress for polling, starts it, and passes its admission function into the polling loop; the loop journals eligible updates before the next poll.
Shutdown admission contract: The shared monitor expressly permits append-only admission after stop with durable-after-stop, and this branch enables that mode on the Zalo ingress.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs run --config test/vitest/vitest.extension-zalo.config.ts --configLoader runner extensions/zalo/src/monitor.polling-ingress.test.ts

Result: PASS (completed)

RUN  v4.1.10 /tmp/clawsweeper-live-proof-110803-j0hhBO/target

 ✓  extension-zalo  extensions/zalo/src/monitor.polling-ingress.test.ts (5 tests) 14241ms
     ✓ journals a polled update durably before dispatch and tombstones it after adoption  731ms
     ✓ replays a journaled update exactly once after a crash between poll and dispatch  1170ms

 Test Files  1 passed (1)
      Tests  5 passed (5)
   Start at  01:31:50
   Duration  25.03s (transform 18.47s, setup 907ms, import 9.59s, tests 14.24s, environment 0ms)
RUN  v4.1.10 /tmp/clawsweeper-live-proof-110803-j0hhBO/target

 ✓  extension-zalo  extensions/zalo/src/monitor.polling-ingress.test.ts (5 tests) 6333ms
     ✓ journals a polled update durably before dispatch and tombstones it after adoption  465ms
     ✓ replays a journaled update exactly once after a crash between poll and dispatch  1178ms

 Test Files  1 passed (1)
      Tests  5 passed (5)
   Start at  01:32:17
   Duration  11.00s (transform 4.77s, setup 439ms, import 4.01s, tests 6.33s, environment 0ms)

Assertions:

  • PASS expect_output: 5 passed

How this fits together

The 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]
Loading

Decision needed

Question Recommendation
Should Zalo polling adopt the shared ingress drain's limit of eight concurrent cross-chat deliveries in exchange for durable pre-dispatch journaling, while retaining per-chat lane ordering? Accept shared ingress delivery: Rebase or validate the merge ref, retain the shared eight-delivery limit, and record that per-chat ordering is the preserved compatibility contract.

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

  • Resolve merge risk (P1) - Polling currently back-pressures on one direct dispatch; this branch instead admits the next update once persistence completes and permits up to eight concurrent cross-chat deliveries. Chat lanes preserve per-chat order, but downstream load, rate-limit behavior, and failure timing change.
  • Resolve merge risk (P1) - The head is behind current main. GitHub reports a clean merge, but the final merge ref should rerun the focused ingress proof because current main has since changed surrounding Zalo validation code.
Agent review details

Security

None.

PR surface

Source +35, Tests +358. Total +393 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 5 76 41 +35
Tests 2 359 1 +358
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 435 42 +393

Review metrics

Metric Value Why it matters
Production versus test LOC production +70/-39; tests and test support +365/-3 The net production growth is concentrated in replacing direct polling dispatch with the durable owner; the larger test delta covers the crash and shutdown boundary.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #130566
Summary: This PR is the explicit candidate repair for the open Zalo polling crash-window report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Accept and verify the shared delivery policy (recommended)
    Rebase or validate GitHub's merge ref, rerun the polling-ingress proof, and have the channel owner explicitly accept eight concurrent cross-chat deliveries with per-chat lanes.
  2. Keep polling serial
    Pause this branch and redesign the ingress boundary only if the established polling backpressure must remain one delivery at a time.

Technical review

Best 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.

Labels

Label justifications:

  • P1: The branch addresses a silent-loss path for inbound Zalo messages during crash or restart.
  • merge-risk: 🚨 compatibility: Existing polling changes from serial dispatch to concurrent cross-chat delivery.
  • merge-risk: 🚨 message-delivery: The patch changes when inbound updates are persisted, deduplicated, retried, and delivered.
  • merge-risk: 🚨 availability: The new shared drain can start up to eight cross-chat agent deliveries instead of one polling delivery.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body contains after-fix copied live output from the production polling monitor, a real SQLite queue, and a protocol-compatible local Bot API showing restart replay, one visible reply, and duplicate suppression.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body contains after-fix copied live output from the production polling monitor, a real SQLite queue, and a protocol-compatible local Bot API showing restart replay, one visible reply, and duplicate suppression.

Evidence

What I checked:

Likely related people:

  • steipete: Introduced the merged Zalo webhook durable-ingress path that this branch reuses, and authored the later Zalo delivery and lifecycle work. (role: durable-ingress feature owner; confidence: high; commits: 0ac69b9fe807, 7c6c512759f3, f9d9d1225a1c; files: extensions/zalo/src/webhook-spool.ts, extensions/zalo/src/monitor.ts)
  • joshavant: Added the current context-bound pre-dispatch authorization behavior traversed by queued Zalo deliveries. (role: recent adjacent contributor; confidence: medium; commits: 97a53a9b35a8; files: extensions/zalo/src/monitor.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain an owner decision on cross-chat concurrency, then rerun the focused polling-ingress proof on the exact merge ref.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

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

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-31T10:45:46.779Z sha f30c1498da20766fc3e0ba1e7c8e6a2c663a6fd6 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-31T13:13:39.681Z sha cea05826fe5678e4e60865156ec7cd425cc2994c :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T09:49:16.472Z sha cea05826fe5678e4e60865156ec7cd425cc2994c :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T10:08:52.311Z sha cea05826fe5678e4e60865156ec7cd425cc2994c :: found issues before merge. :: [P1] Preserve the current channel status lifecycle | [P1] Do not restore swallowed Zalo text-send failures
  • reviewed August 5, 2026, 12:06 PM ET / 16:06 UTC sha unknown :: needs changes before merge. :: [P1] Preserve the current channel status lifecycle | [P1] Propagate failed Zalo text sends to the ingress drain
  • reviewed 2026-08-05T16:23:34.146Z sha ad4513a87e1af17a4396081464fffab3cea115ab :: needs maintainer review before merge. :: none
  • reviewed 2026-08-16T00:23:35.939Z sha f7fb490 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-19T20:50:54.474Z sha f7fb490 :: needs maintainer review before merge. :: none

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

CI lint fix pushed (3060f9caf7): oxlint typescript(no-unnecessary-type-parameters) — dropped the unused <_T> type parameter on the openChannelIngressQueue test stub in monitor.polling-ingress.test.ts:104. Verified locally: oxlint clean on the file, node scripts/run-vitest.mjs extensions/zalo/src/monitor.polling-ingress.test.ts green.

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

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));

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

Comment thread extensions/zalo/src/monitor.ts Outdated
});
// 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.

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.

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.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/zalo-polling-durability branch from 3060f9c to f2fe3da Compare July 21, 2026 16:17
@clawsweeper

clawsweeper Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

if (isStopped() || abortSignal.aborted) {
if (response.ok && response.result) {
await acceptUpdate(JSON.stringify(response.result)).catch((err: unknown) =>

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.

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.

Comment thread extensions/zalo/src/monitor.ts Outdated
@@ -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

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

@Yigtwxx

Yigtwxx commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Separate from the two inline notes: the description now describes a version of the branch that 1a6a117 changed, and it is the part a reviewer leans on most.

"Non-message events remain no-ops and skip journaling" is no longer true on both paths. Measured on 1a6a117, with the normal path as the control:

envelope path journaled
sticker normal []
sticker abort ["probe-sticker-1"]

"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 failed to journal consumed update before shutdown — loud, but about an update that was never eligible for the journal and where nothing was lost.

More generally, 1a6a117 adds a new SQLite write on the shutdown path and the description does not mention it. On a PR carrying merge-risk: 🚨 message-delivery, that is the one behavior a maintainer would want stated explicitly rather than discovered from the diff — especially since the labels (proof: sufficient, rating: 🐚) were assigned on July 18 and predate both of today's commits.

Still unaddressed from my first pass, and cheap to fold into the same edit: polling delivery concurrency changes with this patch. On main the loop awaited processUpdate inline, so polling was back-pressured by agent turn duration; after this it returns once the row is appended and the drain runs at ZALO_WEBHOOK_MAX_CONCURRENT_DELIVERIES = 8. Per-chat ordering still holds via the chat:<chatId> lane, so this reads as intentional — it just means "reuses steipete's spool unchanged" is true of the spool but not of the polling side's delivery shape.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@wangmiao0668000666

wangmiao0668000666 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@Yigtwxx
Thanks for catching both issues on 1a6a117. Fixed in 4dcb611:

  1. Abort filter mismatch — extracted shouldJournal as a single predicate (same message + no-op exclusion) shared by both the abort and normal paths, so sticker/unsupported events are consistently skipped regardless of shutdown timing.

  2. Else-branch comment — corrected to "getUpdates network error during shutdown": .catch on the abort-path acceptUpdate already consumes that rejection, so only getUpdates network failures reach here.

shouldJournal also addresses the no-op gate from the first review pass.

Let me know if this aligns with what you had in mind.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@Yigtwxx

Yigtwxx commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@wangmiao0668000666 Confirmed on 4dcb611 — I re-ran the probe I used for 1a6a117, driving the production monitorZaloProvider against the real SQLite ingress queue, with the normal path as the control. Both inline findings are closed:

case envelope path journaled errors
A sticker normal [] []
B sticker abort [] []
C no message normal [] []
D no message abort [] []

B and D were the two mismatches; the shared shouldJournal removes both.

The same run carries a control case I should have included the first time, and it does not pass: the abort-path journal that 1a6a117 added does not journal anything under realistic shutdown timing. Same probe, a real text update — the case the branch exists to save:

case envelope path abort → response gap journaled errors
E text normal — ["probe-text-1"] []
F text abort one settle of pending async work [] failed to journal consumed update before shutdown: Error: Zalo ingress stopped.
G text abort same tick ["probe-text-1"] []
H text abort real 50 ms [] failed to journal consumed update before shutdown: Error: Zalo ingress stopped.

E is the control — the fixture can write. G shows the append succeeds only when the poll response lands in the same tick as abort(). F and H are the shape that actually occurs.

The refusal comes from assertAdmissionOpen:

// 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();
}

createZaloWebhookIngress passes no admissionMode, so admission closes on stop. The abort branch calls acceptUpdate precisely when the monitor is stopping, so on the timeline that matters admit is refused at the door and the .catch converts a lost message into a log line.

The gap is not narrow, either. 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 timeout while finally → stop() → ingress.stop() completes. G's window is a tick; the real one is seconds.

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 ingress.stop() already awaits admissionTail, calling acceptUpdate here after abort should be safe." admissionTail is not the guard that fires — admit never gets scheduled onto it.

The mode this needs already exists in-tree, and two channels set it: extensions/line/src/webhook-spool.ts:307 and extensions/sms/src/ingress-spool.ts:134 both use admissionMode: "durable-after-stop". Adding the same line to the Zalo ingress, beside waitForDeliveryIdleBeforeRepump:

admissionMode: "durable-after-stop",

measured with the same probe, back-to-back runs:

case 4dcb611 as shipped 4dcb611 + the line
F text / abort [] + stopped-error ["probe-text-1"]
H text / abort, 50 ms [] + stopped-error ["probe-text-1"]
A–D (the filter) [] [] — unchanged
E text / normal (control) ["probe-text-1"] unchanged

The full Zalo suite is indifferent to that line: 120 passed | 18 failed on both sides here, identical counts, and all 18 failures are Windows EBUSY SQLite-unlink noise present with and without the change. The delta is zero — I am reporting the difference, not the absolute, since my box does not reproduce your 131/132.

Two things I am explicitly not asserting. I have not checked whether durable-after-stop interacts with the drain's own shutdown path in a way LINE and SMS tolerate but Zalo would not — that deserves your own pass before adopting it. And monitor.polling-ingress.test.ts is still untouched across all three commits, so nothing pins the abort branch; that is why its behavior has been able to change twice now without a test moving.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@Yigtwxx Thanks for the detailed probe — the admission-mode gap is exactly right.

Applied in 344d39d:

  1. admissionMode: "durable-after-stop" added to createZaloWebhookIngress in webhook-spool.ts — same pattern LINE (extensions/line/src/webhook-spool.ts:307) and SMS (extensions/sms/src/ingress-spool.ts:134) already use. Without it admit is refused at the door once stopped is true; with it the abort-path acceptUpdate survives the stop window.

  2. Test added in monitor.polling-ingress.test.ts — hangs the second getUpdates in-flight, aborts, shuts down the monitor, then releases the late poll response and asserts the consumed update lands in the durable queue.

The Zalo drain shutdown path is structurally the same as LINE and SMS (single createChannelIngressMonitor, same runDetachedWebhookWork pump, same stop → admissionTail → waitForPumpIdle sequence). durable-after-stop only widens the admission window — it doesn't change drain/shutdown ordering — so the interaction with waitForDeliveryIdleBeforeRepump: false and the deferred-claims settlement in stop() should be neutral.

@Yigtwxx

Yigtwxx commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@wangmiao0668000666 Measured 344d39d. The line does what it was added for, the new test pins it, and both items I left open last round are now closed. One claim in the branch is still wider than what I can measure.

1. The fix is real, and the test is load-bearing. Mutation: delete only the added line in extensions/zalo/src/webhook-spool.ts, nothing else.

monitor.polling-ingress.test.ts
344d39d 5/5 pass
344d39d minus admissionMode 1 fail — journals a polled update on the abort path…, AssertionError: expected [] to include 'poll-abort-b'

Exactly one test flips, and it is the new one.

Harness note: on Windows every test in this file fails on the fs.rm(stateDir) teardown with EBUSY: resource busy or locked … openclaw-agent.sqlite, which masks the body verdict. I made that unlink non-fatal locally — teardown only — to read pass/fail. That is my box, not the branch.

2. My open item from last round is clean — durable-after-stop does not disturb the drain. Full extensions/zalo suite, with and without the line, back to back on the same box:

both sides 19 failed | 120 passed (139), and the failing test names are identical — diff of the two × lists is empty. All 19 are the same EBUSY teardown noise. Delta zero.

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 getUpdates parked so nothing new arrives:

PROBE_AFTER_STOP    {"claims":[],"pending":["probe-abort-b"],"dispatches":1}
PROBE_AFTER_RESTART {"replayed":true,"dispatches":2,"claims":[],"pending":[]}

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 server-close.ts stops channels (:859-864) and then closes the state store (:882). Measured both ways with the shutdown order modelled explicitly:

PROBE closeDb=false journaled=true errors=[]
PROBE closeDb=true  journaled=true errors=[]

closeOpenClawStateDatabase() clears the cache and the next write reopens lazily, so the DB close is not the hazard. Process exit is — see below.

5. What is still overstated: monitor.ts:254-256.

// The Bot API consumes each polled update on response. When shutdown
// lands between getUpdates and journal, still accept the update so
// the ingress stop drains it before the DB handle closes.

The ingress stop does not drain it. By the time the late poll returns, ingress.stop() has already completed — that is precisely why admissionMode was needed — and requestDrain() no-ops on a stopped monitor. Measured in §3: the row sits pending, dispatches stays at 1, and it is delivered only after a restart. Journaled-and-deferred, not drained.

The wider point is that nothing holds the process open for that append:

  • the poll loop is detached — void poll() (monitor.ts:304), startPollingLoop(...) is called without await (:1050-1059), and the finally awaits only cleanupWebhook and asyncStopHandlers (:1067-1075). So monitorZaloProvider resolves with the poll still in flight; your own test depends on that, resolving latePoll after await run.
  • getUpdates takes no abort signal and carries its own 35s deadline (api.ts:254-255, with pollTimeout = 30 at monitor.ts:243), so abort does not shorten it.
  • the gateway waits at most CHANNEL_STOP_ABORT_TIMEOUT_MS = 5_000 for the channel task and then logs channel stop exceeded …; continuing shutdown and proceeds (server-channels.ts:52, :981-987).

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:

  • reword the comment to what it does: a best-effort append that, when it lands, is recovered on the next start — not drained by this stop.
  • if you want it drained in-process, keep the handle startPollingLoop currently discards and await it in the finally before asyncStopHandlers. That buys real delivery, but it trades against the same 5s bound.

One thing worth ruling out explicitly: making getUpdates abort-aware is not the fix, and would be strictly worse. The Bot API has already consumed the update by the time it responds; discarding that response guarantees exactly the loss this branch exists to prevent.

None of this argues against the change — every measured state here is better than 4dcb611. It is the description of the guarantee I would tighten before a maintainer reads merge-risk: 🚨 message-delivery and takes the comment at face value.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@Yigtwxx Thanks for the thorough measurement — §5 is well taken. Fixed in a6981ff:

Reworded monitor.ts:254-262: the comment now says what the code actually does — best-effort append, durable-after-stop admission, recovered on next restart — instead of "the ingress stop drains it."

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.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 5, 2026
@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/zalo-polling-durability branch from cea0582 to ad4513a Compare August 5, 2026 16:16
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Rebased onto current main (113af2fcbd) as ad4513a87e. The branch is now a single commit, +435/−42 — identical scope to the reviewed head, conflict-free.

How the two P1 findings were resolved:

  1. Status lifecycle preserved — the rebase keeps every current-main status path: channelReadyPatch() after a successful poll (monitor.ts:300), recovering on polling errors (monitor.ts:316) and on startup failure (monitor.ts:1124). The polling change now only swaps the direct processUpdate call for ingress.accept(...).
  2. Partial-delivery behavior preserved — processUpdate's failure path is untouched: rethrow when no visible reply was sent, receipts + createChannelPartialDeliveryError for partial sends (monitor.ts:846-859). No swallowed send failures.

Conflict resolution notes:

  • webhook-spool.ts keeps both deferredClaims: "wait-on-stop" (from refactor(channels): deduplicate ingress monitor shells #115792) and admissionMode: "durable-after-stop" — the two shutdown policies are independent fields. Everything else in that file is main's side; the old hand-rolled deferred-claim machinery was not resurrected.
  • Only other conflict was an import block in monitor.polling.media-reply.test-support.ts; merged both sides.

Focused proof on the rebased head (Node 24.18, node scripts/run-vitest.mjs run --config test/vitest/vitest.extension-zalo.config.ts --configLoader runner):

  • monitor.polling-ingress.test.ts — 5/5 (durable journal before dispatch, crash replay exactly-once, abort-path durable-after-stop admission, dedupe, dead-letter)
  • webhook-spool.test.ts — 11/11 (including deferred-claim-through-shutdown)
  • monitor.lifecycle.test.ts — 10/10 (ready after first successful poll, recovering on poll failure, timer cleanup)
  • monitor.webhook.test.ts — 12/12
  • monitor.polling-lifecycle.test.ts — 26/26 (media replies, replay-after-failure dedupe through the real reply dispatcher)

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 5, 2026
@Yigtwxx

Yigtwxx commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@wangmiao0668000666 Measured ad4513a. The resolution is the one this thread asked for, and both P1s from the pre-rebase head are closed by the new base. One Windows observation at the end, which is not a finding against the fix.

Resolution. webhook-spool.ts against current main is a one-line diff, so both shutdown policies survive and nothing else in the file drifted off main's side:

     runPumpTask: runDetachedWebhookWork,
     deferredClaims: "wait-on-stop",
+    admissionMode: "durable-after-stop",

The hand-rolled deferred-claim machinery #115792 deleted stayed deleted.

"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:

head base ± lines sha256 (first 16)
f30c1498 14da8a25 477 f0f8b2a85c5714c2
cea05826 d81465f7 477 f0f8b2a85c5714c2
ad4513a8 113af2fc 477 f0f8b2a85c5714c2

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. git diff origin/main ad4513a -- extensions/zalo/src/monitor.ts produces hunks only inside startPollingLoop and the polling branch of monitorZaloProvider. Everything the lifecycle waves and #117864 added is context, not diff: channelReadyPatch() at monitor.ts:300, recovering at :316, and the partial-delivery block at :846-860 are main's bytes on this head.

Worth stating positively, because it is the part that got stronger with the rebase: now that #117864 is in the base, polling inherits the error contract the webhook transport already ships. Both transports call processUpdate inside createZaloWebhookIngress({ deliver }) — :967 for webhook, :1086 for polling — so a partial send raises one createChannelPartialDeliveryError into one drain, with the accepted messageIds carried on it, instead of two different failure behaviors per transport. That is a better position than the pre-rebase head had.

Base. 27 commits behind main at the time of writing, but none of the 7 files in this PR moved in those 27 commits (git log 113af2fcbd0..origin/main -- <the 7 paths> is empty), so a refresh is mechanical. No failing checks on ad4513a — 45 pass, 39 skipped.

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, node scripts/run-vitest.mjs run --config test/vitest/vitest.extension-zalo.config.ts --configLoader runner <file>, run in two clean worktrees:

file at base 113af2fc at ad4513a your number
webhook-spool.test.ts — 11 passed 11
monitor.lifecycle.test.ts — 10 passed 10
monitor.webhook.test.ts — 12 passed 12
monitor.polling-lifecycle.test.ts 17 passed / 9 failed 1 passed / 25 failed 26
monitor.polling-ingress.test.ts (absent) 0 passed / 5 failed 5

Every failure is the same one, in teardown, never in an assertion:

Error: EBUSY: resource busy or locked, unlink
  '...\openclaw-zalo-poll-ingress-1rzSdm\agents\main\agent\openclaw-agent.sqlite'

At the base 9 of the 26 already fail this way — the three Zalo pairing lifecycle cases, the two Zalo reply-once lifecycle cases, and four Zalo polling image handling cases. After the change it is 25 of 26: every eligible polled update now journals, so nearly every case in that file writes the state database whose directory removal is what breaks.

It is a live handle, not a slow release: raising both cleanup paths to fs.rm(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }) turns none of them green — the run stalls on the retries until vitest kills the process group, so the file is still locked two seconds after closeOpenClawStateDatabaseForTest().

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.

@wangmiao0668000666

wangmiao0668000666 commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor Author

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 #117864 is exactly right.

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 EBUSY (the agent state DB file is still locked well after closeOpenClawStateDatabaseForTest() returns), and I plan to dig into the root cause and propose a fix there, so it stays out of this PR's merge path.


Tracking issue: #119796

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

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 (readSessionUpdatedAt → openOpenClawAgentDatabase), which caches the handle process-wide; the Zalo lifecycle teardown only closed the shared state DB before fs.rm. The fix mirrors the #113316 fixture ordering — closeOpenClawAgentDatabasesForTest() before the shared close, plus the same fs.rm retry budget — and adds a regression test that observes the handle release on any OS (fails before, passes after). Your base-column analysis was exactly right: the leak pre-exists on main, and #110803 only amplifies exposure.

@Yigtwxx

Yigtwxx commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

@wangmiao0668000666 Not a review finding — a staleness measurement, since the head has been at ad4513a for ten days while monitor.ts moved underneath it.

What moved. Three commits landed on main touching files this PR owns:

commit file(s)
978f9b15eb8 (#119809, 06.08) monitor.lifecycle.test.ts, test-support/monitor-mocks-test-support.ts
3ee6c6a3e1a (#120988, 09.08) monitor.ts, monitor.image.polling.test-support.ts
97a53a9b35a (#122863, 14.08) monitor.ts (+53/−26)

#122863 is the one worth knowing about: it split authorizeZaloMessage into a first resolve plus a second, context-bound resolve immediately before dispatch, with a bail on !channelIngress.senderAccess.allowed (zalo: authorization changed before dispatch). Everything this PR journals lands in exactly that path, via ingress.accept → deliver → processUpdate.

Merge measured locally — current main 8f59226bc93 merged into ad4513a: clean, no conflicts, 7 files.

tsgo -p extensions/zalo/tsconfig.json → exit 0. Control arm: appending a deliberate const x: number = "s" → exit 1 with TS2322, so the checker was live.

Suite, test/vitest/vitest.extension-zalo.config.ts, Windows, Node 24.18.1:

arm test files tests
main 8f59226bc93 3 failed / 50 passed (53) 16 failed / 437 passed (453)
main + this PR 3 failed / 51 passed (54) 16 failed / 442 passed (458)

Identical three red files on both arms — zalouser/doctor-contract-api, zalouser/src/zalo-js.credentials, zalouser/src/zalo-quote-metadata, every failure an EBUSY … unlink openclaw.sqlite teardown, Windows-only and inherited, not reachable from this diff. Your five new tests pass on the new base.

Two one-line mutations on the merge head, to check the suite still measures something there:

mutation monitor.polling-ingress.test.ts
baseline 5 passed
const shouldJournal = false && … 5 failed
#122863's if (!channelIngress.senderAccess.allowed) → if (true) 5 failed

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 main changes the surface this thread already verified, and the rebase does not need a second review pass over the journal logic.

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
@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/zalo-polling-durability branch from ad4513a to f7fb490 Compare August 16, 2026 00:18
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Rebased onto current main (38e0ae6ec8) as f7fb4903b26 — clean, conflict-free, identical scope (7 files, +435/−42). Local verification on Node 24.19.0: monitor.polling-ingress.test.ts 5/5 green, monitor.lifecycle.test.ts 10/10 green.

@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

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 (startLimit=1), which reproduces current main's exact user-visible delivery semantics — in-order, one at a time — so no delivery-policy decision is needed.

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 main (ce5d04fac71): PROOF-FAIL (main, never replayed) vs. PROOF-REPLAY-OK (fix, zero redelivery).

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.

@wangmiao0668000666
wangmiao0668000666 deleted the fix/zalo-polling-durability branch October 28, 2026 07:42
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: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

[Bug]: zalo: polled updates are lost permanently on crash between poll and dispatch

2 participants