Skip to content

fix(qqbot): queued and in-flight messages are lost when the gateway resumes after reconnect or restart - #109997

Closed
YangManBOBO wants to merge 1 commit into
openclaw:mainfrom
YangManBOBO:fix/qqbot-resume-seq-watermark
Closed

YangManBOBO wants to merge 1 commit into
openclaw:mainfrom
YangManBOBO:fix/qqbot-resume-seq-watermark

Conversation

@YangManBOBO

@YangManBOBO YangManBOBO commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #109996

What Problem This Solves

Fixes an issue where QQ Bot users' messages would silently vanish — no reply, no error — whenever the gateway connection dropped, the server requested a reconnect, or the gateway process restarted while their message was still queued or being processed.

The QQ gateway replays only events with seq greater than the RESUME seq, but the channel committed (and persisted to the SQLite session store) each frame's seq at receipt, before the queued handler ran. Any message in flight or in the in-memory per-peer queue at disconnect/restart time was skipped by the resume replay and permanently lost. Handler failures had the same outcome: the message was logged-and-dropped locally while the already-advanced seq defeated the protocol's replay. This is the same defect family as the ClickClack reconnect-cursor race fixed in #108577, with the added severity that the premature cursor is persisted across process restarts (5-minute resume window).

Why This Change Was Made

Message-frame seqs now commit to the RESUME watermark only when the message settles. A new SeqWatermark tracks in-flight message seqs: the resumable value stays just below the oldest unsettled message, so RESUME replays anything still queued, in flight, or failed; frames without queued work (READY, RESUMED, interactions, acks) commit immediately, exactly as before. Settling covers every terminal state: handler completed, handler failed with a logged drop (the existing failure contract), or intentional discard (queue-full eviction, urgent queue clear). Failed handlers settle deliberately: the watermark is connection-wide and the queue keeps processing later messages after a failure, so holding the cursor behind one poison message would replay already-successful traffic for unrelated peers on every reconnect. The watermark therefore stays behind only messages that are genuinely still queued or in flight — exactly the restart/reconnect loss window this PR closes. The previously fire-and-forget message dispatch also gets a rejection handler so routing failures are logged and left pending for replay. Heartbeats intentionally do NOT use the watermark: they report the latest received frame seq (receive cursor) so the client never looks behind while a handler is running; only RESUME and persisted session state use the settlement watermark.

Delivery semantics move from at-most-once (silent loss) to at-least-once across reconnects: a crash after a handler completes but before the throttled session save can redeliver an already-handled message. That matches the durable-before-ack convention used by the Telegram/WhatsApp/Slack/Signal channels.

User Impact

QQ Bot messages received while an agent turn is running — or queued behind one — now survive reconnects, server-driven RECONNECTs, and gateway restarts within the resume window: the gateway replays them and the bot answers. Previously they disappeared with no trace. No config, protocol, or persisted-state shape changes.

Evidence

Live behavior proof (real GatewayConnection, real ws client, protocol-compatible local gateway)

Driver: the production GatewayConnection (real websocket client, real reconnect/backoff, real event dispatcher and per-peer message queue) connected to a local WebSocket server implementing the QQ gateway protocol: HELLO → IDENTIFY → READY(s=1), and RESUME → replay events with seq > resume seq. A message event s=2 is delivered while its handler is still running, then the server drops the socket.

Before (current main) — the client resumes at the already-committed seq and the message is lost:

[server] IDENTIFY received — sending READY (s=1)
[proof] delivering message event seq=2 (handler will hang in flight)
[client] handler invoked for m-inflight (call #1)
[server] dropping the client connection (transient network failure)
[client] WebSocket closed: 1006
[server] RESUME received with seq=2 — replaying 0 event(s) with seq>2
[proof] FINAL: resumeSeq=2 handledAfterReplay=(none)

After (this patch) — the client resumes below the unprocessed message, the server replays it, and it is handled:

[server] RESUME received with seq=1 — replaying 1 event(s) with seq>1
[client] handler invoked for m-inflight (call #2)
[client] handler COMPLETED for m-inflight
[proof] FINAL: resumeSeq=1 handledAfterReplay=m-inflight

Regression coverage

  • seq-watermark.test.ts (new): commit/register/settle semantics, out-of-order settles, replay boundary, session reset.
  • gateway-connection.test.ts (4 new integration tests): message seq is not committed until the handler completes; with a message in flight, heartbeats report the latest received seq (2) while reconnect RESUME asks for replay below the unprocessed message (1); a failed handler settles and a failure-then-later-success reconnect resumes past both (no cross-peer replay amplification); queue-full eviction settles so the watermark cannot wedge.
  • Against unfixed main, all 4 new integration tests fail (RESUME seq advances past the in-flight message); the 7 pre-existing disconnect-status tests pass unchanged in both states.
  • node scripts/run-vitest.mjs on seq-watermark.test.ts + gateway-connection.test.ts + message-queue.test.ts → 26 passed.
  • Pre-existing outbound-dispatch.test.ts failures on this machine reproduce identically without this change (unrelated outbound media-path surface).
  • Scoped oxlint, oxfmt, and git diff --check pass on the five changed files.

Sibling-surface context

The receive-path audit that found this also checked the other channels for the same premature-cursor family: Telegram's default isolated ingress advances its offset only after durable spooling, WhatsApp journals inbound before ack, Slack and Signal are durable-before-ack, and iMessage clamps its catchup cursor below failed rows — qqbot was the remaining gateway-resume surface committing before processing.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. 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 17, 2026
@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed July 19, 2026, 10:13 PM ET / July 20, 2026, 02:13 UTC.

Summary
The PR replaces immediate QQ Bot gateway sequence persistence with a settlement-aware resume watermark, adds queue settlement callbacks, and adds watermark and reconnect regression coverage.

PR surface: Source -64, Tests +188. Total +124 across 5 files.

Reproducibility: yes. at source level: a protocol-compatible gateway can send a message frame, keep its handler queued or in flight, drop the socket, and compare the subsequent RESUME sequence with the replay boundary. The PR body supplies this exact real-connection scenario and before/after output.

Review metrics: none identified.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #109996
Summary: This PR is the candidate implementation for the open QQ Bot reconnect/restart message-loss report.

Members:

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

Merge readiness
Overall: 🧂 unranked krab
Proof: 🦞 diamond lobster
Patch quality: 🧂 unranked krab
Result: blocked by patch quality or review findings.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Rebase the implementation onto current main without removing ingress monitor, lifecycle, or shutdown behavior.
  • [P2] Add a focused regression that exercises the preserved ingress lifecycle together with an in-flight reconnect and replay.

Risk before merge

  • [P1] Merging the branch could remove QQ Bot ingress/admission lifecycle behavior that is independent of the resume sequence, reintroducing message-loss or recovery regressions outside the newly tested reconnect scenario.
  • [P1] The branch is behind main; refresh the merge result after preserving ingress ownership rather than treating the older base diff as an isolated watermark-only change.

Maintainer options:

  1. Preserve ingress while applying the watermark (recommended)
    Rework the branch so SeqWatermark is attached to terminal queue outcomes without removing QQ Bot ingress monitoring, admission, lifecycle propagation, or shutdown handling, then rerun focused gateway and queue coverage.
  2. Pause the branch
    Pause or close this implementation if the intended permanent QQ Bot delivery boundary is to replace ingress ownership rather than preserve it, because that requires an explicit owner design review.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Rebase onto current main, retain the QQ Bot ingress lifecycle and shutdown path, and add focused regression coverage proving both ingress lifecycle preservation and replay of queued or in-flight messages.

Next step before merge

  • [P2] The blocker is a concrete mechanical repair: retain current QQ Bot ingress ownership while integrating the settlement watermark and prove the combined lifecycle.

Security
Cleared: The diff is limited to QQ Bot gateway and queue behavior plus tests; it adds no dependency, workflow, secret, permission, package-resolution, or external-code-execution surface.

Review findings

  • [P1] Keep the QQ Bot ingress lifecycle wired — extensions/qqbot/src/engine/gateway/gateway-connection.ts:20-31
Review details

Best possible solution:

Rebase the narrow settlement-aware sequence change onto current main, preserve the existing QQ Bot ingress and turn-adoption lifecycle end to end, and extend the reconnect tests to cover that combined path before merge.

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

Yes, at source level: a protocol-compatible gateway can send a message frame, keep its handler queued or in flight, drop the socket, and compare the subsequent RESUME sequence with the replay boundary. The PR body supplies this exact real-connection scenario and before/after output.

Is this the best way to solve the issue?

No. A settlement-aware RESUME cursor is the right repair direction, but this branch is not the best implementation while it removes the QQ Bot ingress lifecycle instead of composing with it.

Full review comments:

  • [P1] Keep the QQ Bot ingress lifecycle wired — extensions/qqbot/src/engine/gateway/gateway-connection.ts:20-31
    Restore the removed ingress monitor and turn-adoption lifecycle rather than replacing them with direct queue dispatch. The watermark only changes when the server may replay a frame; removing createQQBotIngressMonitor/lifecycle propagation changes the separate admission, recovery, and shutdown contract and can reintroduce message loss outside the covered RESUME window.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.82

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body provides after-fix live output from the production GatewayConnection with a real ws client against a protocol-compatible local gateway, showing a reconnect resumes below the in-flight message and replays it.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: The patch addresses and can affect silent loss of real inbound QQ Bot messages during reconnects and restarts.
  • merge-risk: 🚨 message-delivery: The changed receive cursor and removed ingress lifecycle both determine whether inbound events are retained, replayed, or dropped.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body provides after-fix live output from the production GatewayConnection with a real ws client against a protocol-compatible local gateway, showing a reconnect resumes below the in-flight message and replays it.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix live output from the production GatewayConnection with a real ws client against a protocol-compatible local gateway, showing a reconnect resumes below the in-flight message and replays it.
Evidence reviewed

PR surface:

Source -64, Tests +188. Total +124 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 255 319 -64
Tests 2 309 121 +188
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 564 440 +124

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs extensions/qqbot/src/engine/gateway/seq-watermark.test.ts extensions/qqbot/src/engine/gateway/gateway-connection.test.ts extensions/qqbot/src/engine/gateway/message-queue.test.ts.
  • [P1] git diff --check.

What I checked:

  • Gateway lifecycle deletion in the patch: The PR removes the gateway imports and context plumbing for createQQBotIngressMonitor, QQBotIngressLifecycle, and ingress dispatch handling while adding SeqWatermark; this is a broader behavioral change than delaying the RESUME cursor. (extensions/qqbot/src/engine/gateway/gateway-connection.ts:20, 64d627c66334)
  • Queue lifecycle deletion in the patch: The queue diff removes turnAdoptionLifecycle, ingress-lifecycle merging, and queue stop behavior while adding onMessageSettled; the watermark callback must be integrated without discarding the existing durable/admission lifecycle. (extensions/qqbot/src/engine/gateway/message-queue.ts:45, 64d627c66334)
  • Focused cursor coverage: The branch adds unit coverage for watermark ordering and gateway reconnect cases, including separate heartbeat and replay cursors. This supports the narrow resume-cursor portion of the repair but does not prove the removed ingress lifecycle remains preserved. (extensions/qqbot/src/engine/gateway/seq-watermark.test.ts:1, 64d627c66334)
  • Related cursor-recovery precedent: The linked ClickClack repair was merged as commit 5810de21b9844d318ffc4f9a903195ba9ea9a123; it is useful semantic precedent for reconnect cursor timing, but it does not justify removing QQ Bot-specific ingress ownership. (extensions/clickclack/src/gateway.ts, 5810de21b984)
  • Prior review continuity: The earlier heartbeat-cursor and terminal-failure concerns were addressed before the reviewed e74c2d88aac3b01e07cda3b846c37afe6f8cfeb1 head. The remaining blocker is the later branch’s wider ingress-lifecycle removal, not a re-raised prior finding. (extensions/qqbot/src/engine/gateway/gateway-connection.ts:20, 64d627c66334)

Likely related people:

  • zhanxingxin1998: Authored the merged ClickClack reconnect-cursor repair cited by this PR, which establishes closely related replay-cursor semantics but on a different channel. (role: adjacent owner; confidence: medium; commits: 5810de21b984; files: extensions/clickclack/src/gateway.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.
Review history (4 earlier review cycles)
  • reviewed 2026-07-17T13:09:11.131Z sha 1f65b8b2aed9257b6bf82945eafe6e3a25641e94 :: needs changes before merge. :: [P1] Keep the heartbeat receive cursor separate
  • reviewed 2026-07-17T13:39:50.274Z sha 1c1923a13ce8b17537eafd4916cf6156ec7c1fa2 :: found issues before merge. :: [P1] Prevent failed handlers from pinning the global replay cursor
  • reviewed 2026-07-17T14:28:01.799Z sha e74c2d88aac3b01e07cda3b846c37afe6f8cfeb1 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-17T15:07:05.646Z sha e74c2d88aac3b01e07cda3b846c37afe6f8cfeb1 :: needs maintainer review before merge. :: none

@YangManBOBO

Copy link
Copy Markdown
Contributor Author

Addressed the P1 review finding in 1c1923a13c: heartbeat and replay cursors are now separate. SeqWatermark.latest() exposes the receive cursor (highest received frame seq) and the OP 1 heartbeat payload uses it, so heartbeats never lag while a handler is running; RESUME and persisted session state keep using the settlement watermark. The reconnect regression test now pins both payloads with a message in flight: heartbeat d = 2 (latest received) while RESUME seq = 1 (below the unsettled message). Focused runs: seq-watermark.test.ts + gateway-connection.test.ts + message-queue.test.ts → 27 passed.

@YangManBOBO

Copy link
Copy Markdown
Contributor Author

Both round-2 items addressed in e74c2d88aa:

Handler-failure cursor policy — adopted the recommended option (preserve terminal failure semantics): a logged handler failure now settles in a finally, so the connection-wide watermark can never wedge behind a poison message and replay later already-successful traffic for unrelated peers. Delayed settlement remains only for messages genuinely queued or in flight — the restart/reconnect loss window this PR closes. executeImmediate follows the same terminal-settle contract. Added the requested failure-then-later-success reconnect regression: seq 2 fails terminally, seq 3 succeeds, reconnect RESUMEs at seq 3 (neither replayed).

check-test-types — the failure was this head's own (msg: never) cast in the new test helper; replaced with the proper QueuedMessage handler type. pnpm tsgo:test (core+extensions+root test lanes) passes locally on the new head; focused runs seq-watermark.test.ts + gateway-connection.test.ts + message-queue.test.ts → 27 passed.

@YangManBOBO

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Jul 17, 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:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor 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 Jul 17, 2026
@YangManBOBO
YangManBOBO force-pushed the fix/qqbot-resume-seq-watermark branch from e74c2d8 to 64d627c Compare July 20, 2026 01:54
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 20, 2026
@YangManBOBO

Copy link
Copy Markdown
Contributor Author

Closing in favor of #111859 which applies the same SeqWatermark fix while preserving the QQ Bot ingress lifecycle, turn-adoption lifecycle, shutdown handling, and admission control intact.

This replacement branch:

  • Keeps createQQBotIngressMonitor / QQBotIngressLifecycle wired end to end
  • Preserves dispatchIngressMessage unchanged
  • Preserves shutdown() with all cleanup ordering preserved
  • Adds SeqWatermark composed with (not replacing) the ingress
  • Uses a FIFO pendingTurnSeqs queue for seq tracking through the ingress chain
  • All existing gateway tests pass

See #111859 for the full implementation.

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

Labels

channel: qqbot 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: qqbot commits RESUME seq before handlers finish — queued/in-flight messages permanently lost on reconnect or restart

1 participant