Repository navigation
fix(telegram): stop durable-ingress message loss after restart (PID/TID claim liveness + global update-id watermark) - #107288
Merged
Conversation
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
obviyus
force-pushed
the
fix/telegram-ingress-pid-reuse-watermark
branch
from
July 14, 2026 08:50
3780fba to
1389cab
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.tsand the webhook drain both gate onisTelegramSpooledUpdateClaimOwnedByOtherLiveProcess) 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 singlehighestAcceptedUpdateId. When the delayed updates finally replay from the durable spool,beginUpdaterejects them asaccepted-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>/statfield 22; macOS:ps -o lstart=pinned to UTC — same contract as coresrc/shared/pid-alive.ts, implemented plugin-local because plugins cannot import coresrc/**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. Explicitxtokens (platforms that cannot read start time, e.g. win32) and well-formed legacy two-partpid:uuidowner 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.
beginUpdatenow 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/belowmax(persisted offset, highestAccepted − 10_000), never pruning pending/failed IDs): IDs below the persisted offset cannot be redelivered bygetUpdates, and the retention window covers realistic in-process redelivery where no persist callback exists; semantic-key dedupe and durable spool tombstones (enqueueisON 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
Evidence
RCA / incident: #107246 (queue rows,
/procevidence, 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; explicitxtoken → 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 normaluser_requestrouting; 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:
tbx_01kxfqm9d17pd2s1bj0r03gvxk, synced from this branch):pnpm check:changedall lanes green (conflict markers, TypeScript LOC ratchet, changelog attributions, wildcard re-export guards, dependency pin guard, format, Plugin SDK API baseline, package patch guard,tsgotypecheck of extensions + extension tests), then the full telegram extension suite: 143 test files / 2751 tests passed.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 —
DeliveryContextcarries noupdate_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.