Skip to content

feat(telegram): persist inbound webhooks to survive restarts - #42185

Closed
Diaspar4u wants to merge 1 commit into
openclaw:mainfrom
Diaspar4u:feat/webhook-queue
Closed

Diaspar4u wants to merge 1 commit into
openclaw:mainfrom
Diaspar4u:feat/webhook-queue

Conversation

@Diaspar4u

Copy link
Copy Markdown
Contributor

Summary

  • Problem: When the gateway restarts (crash, update, manual restart), any Telegram webhook payloads received but not yet fully processed are lost. Telegram does not retry webhook deliveries reliably, so these messages silently disappear.
  • Why it matters: Users send messages that never reach their agent. On busy gateways with frequent restarts this causes visible message loss.
  • What changed: Inbound Telegram webhook payloads are persisted to disk (one JSON file per update) before processing begins. After the update is fully handled (including deferred work like media groups, text fragment assembly, and inbound debouncing), the file is removed. On startup, any files still on disk are replayed through the bot middleware in enqueue-time order.
  • What did NOT change: Normal webhook processing flow, Grammy middleware ordering, Telegram webhook secret validation. The queue is purely additive -- if disk writes fail, processing continues as before.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

Messages received during a gateway restart window are now replayed on next startup instead of being silently dropped. No new config required -- the queue directory (webhook-queue/ inside the state dir) is created automatically.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: macOS / Linux
  • Runtime/container: Node 22+
  • Model/provider: N/A (transport layer)
  • Integration/channel: Telegram (webhook mode)
  • Relevant config: default Telegram webhook config

Steps

  1. Start gateway with Telegram webhook channel
  2. Send a message via Telegram
  3. Immediately restart the gateway (kill -9 or openclaw gateway restart)
  4. Wait for gateway to come back up

Expected

  • Message is replayed on startup and reaches the agent

Actual (before this PR)

  • Message is lost

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

New test suites:

  • src/infra/webhook-queue.test.ts (13 tests): enqueue/dequeue lifecycle, replay ordering, deduplication, TTL cleanup, malformed file handling, orphaned tmp cleanup, idempotent dequeue, timestamp tie-breaking
  • src/telegram/webhook.test.ts (1 new test): verifies dequeue fires when onUpdateProcessed callback triggers

Human Verification (required)

  • Verified scenarios: Sent messages, restarted gateway, confirmed replay on startup via log output. Verified dequeue removes files after successful processing.
  • Edge cases checked: Media groups (multiple updates for one logical message), text fragment assembly (Telegram splits long pastes), inbound debouncing -- all wire deferred-work promises so the queue file is not removed until the full logical operation completes.
  • What I did not verify: Behavior under disk-full conditions (queue write failure is caught and does not block processing). Behavior with very large payloads (files are small -- one JSON per update).

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: Revert this commit. The queue directory can be safely deleted -- it only contains transient data.
  • Files/config to restore: None
  • Known bad symptoms reviewers should watch for: Duplicate message processing on startup (dedup by update_id prevents this, but worth watching). Stale files accumulating (1-hour TTL cleanup prevents this).

Risks and Mitigations

  • Risk: Disk I/O added to the hot webhook path (one write + one rename per update)
    • Mitigation: Writes are small (~1KB JSON), use atomic tmp+rename, and failures are caught silently -- they never block normal processing.
  • Risk: Replayed updates could be processed out of order relative to new incoming updates
    • Mitigation: Replay happens before the webhook HTTP server starts accepting new requests. Entries are sorted by enqueue time.
  • Risk: Orphaned queue files from interrupted writes
    • Mitigation: .tmp files are cleaned up during replay. Entries older than 1 hour are deleted during replay.

Architecture

Three layers:

  1. Queue module (src/infra/webhook-queue.ts): Generic channel-agnostic enqueue/dequeue/replay with atomic writes, TTL cleanup, dedup, and deterministic ordering.

  2. Webhook integration (src/telegram/webhook.ts): Validates secret before enqueuing. Enqueues before Grammy handler. Dequeues via onUpdateProcessed callback. Replays pending entries on startup before accepting new webhooks.

  3. Deferred-work tracking (src/telegram/bot.ts, bot-handlers.ts): The onUpdateProcessed callback only fires after all deferred work (media group assembly, text fragment concatenation, inbound debounce flush) has settled. Handlers register promises via registerDeferredWork(updateId, promise). The bot middleware awaits all registered promises for an update_id before calling onUpdateProcessed.

AI Disclosure

AI-assisted (Claude). Fully tested and reviewed.

Resubmission of #40056 (closed for clean commit history).

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ffb13392d3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/telegram/webhook.ts Resolved
@greptile-apps

greptile-apps Bot commented Mar 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a disk-backed webhook queue to survive Telegram gateway restarts — a well-scoped solution to a real message-loss problem. Payloads are persisted atomically before processing, deferred work (media groups, text fragments, inbound debounce) delays dequeue until the full logical operation completes, and replay on startup is ordered and deduplicated.

Verified findings:

  1. At-least-once delivery with no shutdown drain — dequeueWebhook is fire-and-forget, and the shutdown path does not drain pending unlink operations. A SIGKILL between onUpdateProcessed firing and the filesystem delete completing leaves the entry on disk for replay. The in-memory dedup cache does not survive process restarts, so the same update can be processed twice across restart boundaries.

  2. Missing channelId validation — Entries lacking a valid channelId field pass the validation gate and are silently skipped by the channel filter without being cleaned up, accumulating on disk until the 1-hour TTL expires. Adding channelId to the validation check hardens the API against malformed or corrupted files.

  3. Cross-channel dedup bug in public API — The dedup set is keyed on deduplicationId alone, not including channelId. If replayPendingWebhooks is called without a channel filter, entries from different channels sharing a numeric ID will have duplicates silently discarded. Current Telegram usage always filters by channel, avoiding the issue, but the optional channelId parameter invites the mistake in future callers.

The core persistence and replay logic is solid — atomic writes, TTL cleanup, correct deferred-work tracking, and replay-before-listen ordering are all well-implemented. The three findings above are edge-case issues: one is a restart-window race condition, two are API design improvements that would prevent latent bugs if the code is reused across multiple channels.

Confidence Score: 3/5

  • Mostly safe to merge with awareness that at-least-once delivery is the actual guarantee and duplicate replay is possible after an abrupt SIGKILL.
  • The core persistence and replay logic is solid — atomic writes, TTL cleanup, deferred-work tracking, and ordering are all well-implemented. The three findings are legitimate but are edge-case issues: (1) a SIGKILL window for cross-restart duplicate delivery, which may be acceptable given it's caught by update_id in the same logical flow; (2) missing validation for malformed files, a latent resource issue; (3) cross-channel dedup not accounting for channelId, a latent API design flaw that doesn't currently manifest since all calls filter by channel. Recommend fixing the validation and dedup issues before merge if multi-channel use is planned, otherwise acceptable with documented understanding of at-least-once semantics.
  • src/telegram/webhook.ts (dequeue shutdown handling) and src/infra/webhook-queue.ts (channelId validation and dedup key)

Last reviewed commit: ffb1339

Comment thread src/telegram/webhook.ts Resolved
Comment thread src/infra/webhook-queue.ts Resolved
Comment thread src/infra/webhook-queue.ts Resolved
@Diaspar4u

Copy link
Copy Markdown
Contributor Author

Closing for rework. Will resubmit with fixes.

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

Labels

channel: telegram Channel integration: telegram size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inbound Telegram webhook payloads lost on gateway restart

1 participant