Skip to content

fix(telegram): webhook updates survive crashes and restarts via durable spooling - #98806

Merged
obviyus merged 5 commits into
mainfrom
codex/fix-telegram-webhook-durability
Jul 2, 2026
Merged

obviyus merged 5 commits into
mainfrom
codex/fix-telegram-webhook-durability

Conversation

@obviyus

@obviyus obviyus commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Closes #98777

What Problem This Solves

Fixes an issue where Telegram webhook mode silently and permanently lost updates: the handler acked 200 to Telegram before any persistence, so a gateway crash, restart, deploy, or even a transient processing failure (DB lock, provider error) during an in-flight update dropped it forever — Telegram saw the 200 and never redelivers. Three sibling webhook-mode gaps are fixed with it: a single transient network blip during startup getMe failed the whole account start (burning the supervisor's cumulative restart budget), the webhook bot's HTTP transport was never closed (leaking keep-alive sockets on every restart — the same class as #68128, fixed for polling only), and the generic 120 req/min pre-auth rate limit throttled Telegram's own authenticated delivery on busy bots, growing pending_update_count until Telegram dropped old updates.

Why This Change Was Made

Webhook mode now uses the same durability model as polling: the parsed update is written to the SQLite ingress spool before the 200 ack (a spool write failure returns non-200 so Telegram redelivers — that is the contract), and a webhook drain replays spooled updates through the bot with per-lane ordering, claim refresh, capped exponential backoff, and age-gated dead-lettering, including recovery of leftover updates on startup. Enqueue-time duplicate detection makes Telegram's own webhook retries idempotent. Rather than duplicating polling's retry policy, it is extracted into a shared spooled-update-retry-policy.ts consumed by both drains — including the age-gate semantics from 55d31be (over-limit updates keep retrying at the 3-minute cap and only tombstone once 24h old), now applied to webhook too. Startup bot.init() retries transient errors with the existing webhook retry classifier (401 stays fatal); the webhook owns its transport and closes it exactly once on shutdown and on startup failure (evicted probe-cache transports are closed as well); and the request path validates the Telegram secret first, so only failed secret guesses consume the abuse rate-limit budget — the pinned security contracts (constant-time compare, single-header enforcement, connection close on 401, body-size limits) are unchanged.

User Impact

Webhook-mode Telegram accounts no longer lose messages across restarts, deploys, or transient failures — updates survive durably and replay, matching polling-mode reliability. Accounts come up cleanly after reboots instead of dying on the first network blip, long-running gateways stop leaking sockets on webhook restarts, and busy bots no longer have their own traffic rate-limited into growing delivery backlogs.

Evidence

  • New regression tests (webhook.test.ts, +313 lines): update spooled before ack and redelivered after a transient processing failure; non-200 when the spool write fails; leftover spooled updates drained on startup; young over-limit updates stay pending while >24h-old ones dead-letter (age-gate parity); transient getMe then success starts the account while 401 stays fatal; transport closed exactly once on shutdown and startup failure (plus probe.test.ts for evicted transports); authenticated request storm passes while unauthenticated storm still 429s.
  • Extraction proof: extensions/telegram/src/polling-session.test.ts is unchanged from main and passes against the shared policy module — polling behavior is identical by its own tests, including the age-gate tests from 55d31be.
  • Validation on this branch rebased onto current main: pnpm tsgo:extensions pass; node scripts/run-vitest.mjs on webhook.test.ts, probe.test.ts, polling-session.test.ts — 114 tests pass; node scripts/run-oxlint.mjs on touched files clean; repo autoreview (branch mode vs origin/main) clean.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: XL maintainer Maintainer-authored PR labels Jul 2, 2026
@clawsweeper

clawsweeper Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 1, 2026, 8:43 PM ET / 00:43 UTC.

Summary
The PR persists Telegram webhook updates to the shared SQLite ingress spool before 200 ACK, adds webhook spool draining and retry handling, retries transient startup init, closes webhook/probe transports, and exempts authenticated Telegram delivery from the failed-secret limiter.

PR surface: Source +599, Tests +385. Total +984 across 6 files.

Reproducibility: yes. for a source-level path: current main sends 200 before durable persistence or awaiting bot.handleUpdate, while the PR moves persistence before ACK. I did not run a live Telegram crash/restart reproduction in this read-only review.

Review metrics: 2 noteworthy metrics.

  • Webhook Persistence Lifecycle: 1 durable enqueue/drain path added. Webhook mode now depends on the shared ingress queue before ACK, so maintainers should validate the delivery lifecycle before merge.
  • Webhook Rate-Limit Behavior: 1 authenticated delivery behavior changed. Valid Telegram delivery no longer shares the failed-secret limiter, which affects busy-bot throughput and abuse-boundary review.

Stored data model
Persistent data-model change detected: persistent cache schema: extensions/telegram/src/probe.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #98777
Summary: This PR is the candidate fix for the linked Telegram webhook durability issue; older webhook-loss reports cover the same ACK-before-persistence root cause, while spool and transport PRs are adjacent context.

Members:

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

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦞 diamond lobster
Result: blocked until real behavior proof is added.

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

Rank-up moves:

  • [P1] Add redacted live Telegram proof showing webhook-mode replay after restart or transient handler failure without duplicate delivery.

Proof guidance:

  • [P1] Needs real behavior proof before merge: Missing: the PR body and comments list tests and CI but no redacted live Telegram webhook restart/replay proof; add redacted video, terminal/live output, logs, or linked artifacts and update the PR body for re-review.

Mantis proof suggestion
A live Telegram proof would directly test the main merge risk: webhook delivery surviving restart without duplicate or lost chat output. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram live: verify webhook-mode Telegram update is durably replayed after a gateway restart and is not duplicated.

Risk before merge

  • [P1] No redacted live Telegram webhook restart/replay proof is attached, so source and CI do not yet prove the real transport path avoids lost, duplicated, or wedged delivery.
  • [P1] The diff changes Telegram webhook ACK timing, durable replay, retry/dead-letter behavior, startup retry, transport shutdown, and valid-traffic rate limiting, which is merge-relevant for message delivery and gateway availability.

Maintainer options:

  1. Require Live Telegram Replay Proof (recommended)
    Before merge, require redacted real Telegram webhook-mode proof that an update survives restart or transient handler failure and is not duplicated.
  2. Accept Source And CI Proof
    A maintainer can intentionally accept the delivery risk based on the shared queue design, focused tests, and green checks if live transport proof is impractical.
  3. Split The Reliability Bundle
    If the surface is too broad, pause this PR and split durable spooling, startup retry, transport close, and rate-limit behavior into narrower reviewed changes.

Next step before merge

  • [P1] Human maintainer review is needed because this protected Telegram delivery PR has merge-relevant delivery and availability risk plus a real-proof gap, with no narrow automated repair finding.

Security
Cleared: No concrete security or supply-chain regression was found; the diff adds no dependencies, workflows, lockfile changes, or broader secret exposure.

Review details

Best possible solution:

Land a maintainer-reviewed version after redacted live Telegram proof shows webhook updates persist before ACK, replay after restart or transient failure, and do not duplicate delivery in the real transport path.

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

Yes for a source-level path: current main sends 200 before durable persistence or awaiting bot.handleUpdate, while the PR moves persistence before ACK. I did not run a live Telegram crash/restart reproduction in this read-only review.

Is this the best way to solve the issue?

Yes for the fix shape: reusing the shared SQLite ingress queue and shared retry policy is narrower than an ad hoc webhook sidecar queue. It still needs maintainer review and live Telegram proof because the delivery semantics are user-visible.

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦞 diamond lobster.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P1: The PR targets a Telegram webhook message-loss path that can drop real channel updates during crash, restart, deploy, or transient processing windows.
  • merge-risk: 🚨 message-delivery: The diff changes webhook ACK, durable replay, duplicate detection, retry, and dead-letter behavior where a mistake could drop or duplicate Telegram messages.
  • merge-risk: 🚨 availability: The diff changes webhook startup retry, transport shutdown, and drain loops that can affect account startup and long-running gateway availability.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦞 diamond lobster.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Missing: the PR body and comments list tests and CI but no redacted live Telegram webhook restart/replay proof; add redacted video, terminal/live output, logs, or linked artifacts and update the PR body for re-review.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The PR changes observable Telegram webhook delivery/replay behavior that a short live Telegram proof can demonstrate.
Evidence reviewed

PR surface:

Source +599, Tests +385. Total +984 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 715 116 +599
Tests 2 398 13 +385
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 1113 129 +984

What I checked:

  • Live PR state: Live metadata shows the PR is open, mergeable, carries the protected maintainer label, and still has status: needs proof plus message-delivery and availability merge-risk labels. (17d69ebf33fb)
  • Root policy read: Root AGENTS.md was read fully; its protected-label, high-confidence review, SQLite runtime-state, and real proof guidance applies to this PR. (AGENTS.md:12, c49714f7b6d2)
  • Scoped Telegram policy read: The Telegram guide requires durable-before-ack for webhook mode, shared spool retry policy ownership, failed-secret-only rate limiting, transport close on all exits, and real Telegram proof for reliability PRs. (extensions/telegram/AGENTS.md:10, c49714f7b6d2)
  • Current main loses the durable window: Current main sends 200 before durable persistence or awaiting bot.handleUpdate, leaving the reported crash/restart loss window source-reproducible. (extensions/telegram/src/webhook.ts:353, c49714f7b6d2)
  • PR durable enqueue before ACK: The PR writes the parsed update through writeTelegramSpooledUpdate before respondText(200), so enqueue failure returns non-200 and lets Telegram retry. (extensions/telegram/src/webhook.ts:925, 17d69ebf33fb)
  • Shared queue contract checked: The PR uses the existing channel_ingress_events-backed queue, whose enqueue, claim, complete, release, fail, and tombstone paths already live in the shared SQLite state store. (src/channels/message/ingress-queue.ts:363, c49714f7b6d2)

Likely related people:

  • obviyus: Beyond authoring this PR, current-main history shows recent Telegram webhook and spool retry-policy commits that this PR builds on. (role: recent adjacent webhook and spool contributor; confidence: high; commits: 5a10a29807ab, 55d31beeef00, ce9ec4e1c3d2; files: extensions/telegram/src/webhook.ts, extensions/telegram/src/polling-session.ts, extensions/telegram/src/telegram-ingress-spool.ts)
  • Eva: git blame for the current-main webhook pre-auth limiter, 200 ACK, detached handleUpdate, and post-ACK failure log points to commit 9186125. (role: introduced current webhook path in local history; confidence: medium; commits: 918612513f7a; files: extensions/telegram/src/webhook.ts)
  • vincentkoc: Merged adjacent Telegram isolated polling spool claim recovery across polling-session, telegram-ingress-spool, and the shared ingress queue. (role: recent adjacent ingress-spool contributor; confidence: high; commits: b8e3de11608d; files: extensions/telegram/src/polling-session.ts, extensions/telegram/src/telegram-ingress-spool.ts, src/channels/message/ingress-queue.ts)
  • Diaspar4u: Opened the older webhook-loss issue and several closed unmerged durable-webhook queue PRs covering the same ACK-before-persistence failure class. (role: canonical reporter and earlier proposed-fix author; confidence: medium; commits: 31ddd254d01c; files: src/telegram/webhook.ts, src/infra/webhook-queue.ts, src/telegram/bot.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.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 2, 2026
@obviyus
obviyus force-pushed the codex/fix-telegram-webhook-durability branch from 084d339 to 17d69eb Compare July 2, 2026 00:27
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 2, 2026
@obviyus
obviyus merged commit 6a96bbc into main Jul 2, 2026
102 of 104 checks passed
@obviyus
obviyus deleted the codex/fix-telegram-webhook-durability branch July 2, 2026 03:33
@obviyus

obviyus commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Landed via rebase onto main.

  • Scoped tests: node scripts/run-vitest.mjs extensions/telegram/src/webhook.test.ts extensions/telegram/src/probe.test.ts extensions/telegram/src/polling-session.test.ts (115 tests passed); node scripts/run-oxlint.mjs extensions/telegram/src/webhook.ts extensions/telegram/src/webhook.test.ts extensions/telegram/src/probe.ts extensions/telegram/src/probe.test.ts extensions/telegram/src/polling-session.ts extensions/telegram/src/spooled-update-retry-policy.ts; pnpm tsgo:extensions; .agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main clean.
  • Changelog: not updated; release-owned.
  • Land commit: 17d69eb
  • Merge commit: 6a96bbc

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

Labels

channel: telegram Channel integration: telegram maintainer Maintainer-authored PR mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Telegram webhook mode acks 200 before persistence — updates lost forever on crash/restart

1 participant