Skip to content

fix(telegram): stop durable-ingress message loss after restart (PID/TID claim liveness + global update-id watermark) - #107288

Merged
obviyus merged 3 commits into
mainfrom
fix/telegram-ingress-pid-reuse-watermark
Jul 14, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/telegram-ingress-pid-reuse-watermark

Conversation

@obviyus

@obviyus obviyus commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes #107246 — two independent Telegram durable-ingress bugs that combined into silent inbound message loss after a gateway restart:

A. PID reused as a Linux thread ID fakes a live claim owner. Spool claim liveness was process.kill(pid, 0) (processExists). On Linux, that succeeds for thread IDs of any process, and after a restart the dead owner's PID can reappear as a TID of the new gateway (observed in production: old owner PID 9, new gateway PID 8, /proc/9/status → Tgid: 8). Stale-claim recovery (polling-session.ts and the webhook drain both gate on isTelegramSpooledUpdateClaimOwnedByOtherLiveProcess) then refuses the claim for the full 30-minute lease, wedging every later update in that chat's lane (pending, attempts=0).

B. Global update-ID watermark drops delayed cross-lane replays. Telegram update_ids are global across chats. While one lane is delayed, other lanes complete newer IDs and advance the tracker's single highestAcceptedUpdateId. When the delayed updates finally replay from the durable spool, beginUpdate rejects them as accepted-watermark, bot middleware returns before any handler, and the drain tombstones the rows as completed — zero model dispatch, permanent loss. The old floor-replay exception only covered IDs at or below the persistence floor captured at Bot creation, not mid-process cross-lane delays.

Why This Change Was Made

Production incident on 2026-07-14 (details and DB evidence in #107246): a restart during a held claim wedged one group's lane; after the lane was unwedged, the two queued user messages replayed and were watermark-rejected into completed tombstones. Both mechanisms are generic — any restart-during-claim can trigger A, and any cross-lane delay can trigger B independently.

Fix A — process-instance identity, not PID liveness. Claim owner IDs now encode pid:startToken:uuid, where the start token is the OS process start time (Linux: /proc/<pid>/stat field 22; macOS: ps -o lstart= pinned to UTC — same contract as core src/shared/pid-alive.ts, implemented plugin-local because plugins cannot import core src/** and no SDK barrel exports it). A claim is live-owned only if the PID exists and its start time matches the token, so TIDs and recycled PIDs can no longer impersonate a dead owner, while a genuinely live peer process keeps its lease. Explicit x tokens (platforms that cannot read start time, e.g. win32) and well-formed legacy two-part pid:uuid owner IDs keep the previous existence-only contract — reclaiming a fresh claim from a live old-version worker during a rolling upgrade would double-dispatch its update; malformed owner IDs are not live-provable and recover, which re-queues (never drops). Both the normal and corrupt-claim variants share the check, which also covers the webhook drain (same helper).

Fix B — per-ID acceptance instead of a global high-water mark. beginUpdate now rejects only (1) IDs at or below the restored Bot API offset (initialUpdateId, i.e. redelivery of already-persisted updates after restart) and (2) exact IDs already accepted by this process. Never-seen lower IDs — cross-lane delayed spool replays — dispatch normally. The accepted-ID set is bounded by one prune rule (at/below max(persisted offset, highestAccepted − 10_000), never pruning pending/failed IDs): IDs below the persisted offset cannot be redelivered by getUpdates, and the retention window covers realistic in-process redelivery where no persist callback exists; semantic-key dedupe and durable spool tombstones (enqueue is ON CONFLICT DO NOTHING) cover everything older. The floor-replay special case is deleted — startup replays now flow through the same single path.

Why this is the best fix (alternatives rejected): detecting only Linux TIDs (Tgid != Pid) misses general PID reuse; dropping the liveness probe entirely would let a booting process steal claims from a live peer mid-run; lease/timeout tuning leaves up to 30 minutes of wedge and was explicitly out of scope; per-lane watermarks add a concept where the actual problem is per-ID acceptance. The watermark's real contract (suppress Bot API redelivery of already-processed updates) is preserved by the restored-offset gate + exact-ID set + spool tombstones.

User Impact

  • A gateway restart while a Telegram update is being processed can no longer freeze that chat for up to 30 minutes.
  • Updates that were delayed in one chat while other chats advanced are dispatched exactly once instead of being silently discarded.
  • No config, protocol, or API surface changes. Claim owner IDs are transient (30-minute lease); pre-upgrade claims keep their old existence-based lease semantics for the one process generation that can still hold them.

Evidence

RCA / incident: #107246 (queue rows, /proc evidence, timeline).

Regression tests (all new tests fail on the old code):

  • telegram-ingress-spool.test.ts: fresh foreign claim whose PID is now a thread of this process → not live-owned; unrelated PID reuse → not live-owned; matching start-time peer → live-owned; fresh live legacy two-part owner ID → still lease-protected (rolling upgrade); malformed owner ID → not live-owned; explicit x token → existence-only.
  • bot-update-tracker.test.ts: delayed lower ID after newer cross-lane completions dispatches exactly once; duplicate replay of a completed ID stays rejected; delayed group mention passes the gate for normal user_request routing; accepted-ID set bounded (retention + persisted floor, pending/failed retained).
  • polling-session.test.ts: TID-reuse claim recovered and same-lane backlog drains through the real spool harness; post-adoption crash window — reclaimed claim replays, tombstones, and drains the lane without a deferred model turn.

Validation:

  • Blacksmith Testbox (tbx_01kxfqm9d17pd2s1bj0r03gvxk, synced from this branch): pnpm check:changed all lanes green (conflict markers, TypeScript LOC ratchet, changelog attributions, wildcard re-export guards, dependency pin guard, format, Plugin SDK API baseline, package patch guard, tsgo typecheck of extensions + extension tests), then the full telegram extension suite: 143 test files / 2751 tests passed.
  • Structured second-model review (codex gpt-5.6-sol, high reasoning) over the change bundle: one P1 finding in an intermediate revision (legacy fresh claims could be stolen during rolling upgrades — fixed by the existence-only legacy fallback above); final pass clean, "no actionable defects".

Scope note / follow-up: restart recovery cannot tombstone a recovered turn's spool claim directly — DeliveryContext carries no update_id, and dispatch dedupe keys on (provider, message_id). Post-adoption crash replay therefore relies on the same at-least-once + inbound-dedupe + session-ordering contract that shipped floor-replay startup recovery already uses; adding durable update-ID linkage to adoption identity is a possible follow-up, not attempted here.

Sibling surfaces checked: webhook drain shares the fixed liveness helper and the fixed tracker; WhatsApp durable ingress uses enqueue/complete only (no claims, no liveness gate) and is unaffected.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: L maintainer Maintainer-authored PR labels Jul 14, 2026
obviyus added 3 commits July 14, 2026 14:20
Spool claim owners now encode pid:starttime:uuid, and live-owner detection
requires the pid to exist with a matching process start time. Bare
process.kill(pid, 0) treated Linux thread IDs and recycled PIDs of the new
gateway as a live foreign owner, wedging a chat lane behind a dead claim for
the full 30-minute lease after a restart. Legacy pid:uuid and explicit-x
owners keep existence-only lease protection so rolling upgrades and
no-starttime platforms cannot double-dispatch a live worker's claim.

Refs #107246
Telegram update ids are global across chats, but the update tracker rejected
any id at or below its single high-water mark. When one lane was delayed
while other lanes completed newer ids, the delayed durable-spool replay was
rejected as accepted-watermark and tombstoned without dispatch - silent
message loss. The tracker now rejects only restored-offset ids and exact ids
it already accepted, with the accepted-id set pruned at the persisted offset
plus a bounded retention window; the startup-only floor-replay special case
is deleted.

Refs #107246
The retention bound, claim lease default, and liveness options type were
exported only for tests, which fails the dead-export gate. Tests pin the
policy literals locally instead.

Refs #107246
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 size: L

Projects

None yet

1 participant