Skip to content

fix(telegram): split the webhook ack on which side of the pod write failed - #1286

Merged
lilyshen0722 merged 2 commits into
mainfrom
fix/telegram-relay-ack
Aug 26, 2026
Merged

lilyshen0722 merged 2 commits into
mainfrom
fix/telegram-relay-ack

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Corrected at b581f344. The original body claimed "a dropped relay is recoverable, a doubled one is not" and acked 200 unconditionally. That is backwards for half the cases — sprint-review caught it. The diff below is the corrected shape.

Why one ack policy can't be right

relayTelegramMessageToPod writes the pod row before it wakes agents:

  • telegramBridgeService.ts — PGMessage.create(...)
  • then deliverMessageToAgents(...)

Telegram redelivers any update the webhook does not 2xx, and nothing dedupes on telegramMessage.message_id — the field is declared in the payload type and never read. So the redelivery means two opposite things:

failure lands what the retry does correct response
before the write repairs it — nothing was persisted non-2xx, let it redeliver
after the write duplicates the message and every wake 200, don't redeliver

A blanket try/catch + sendStatus(200) on the route fixes the second and breaks the first, and the broken one is the quieter failure: no pod message, no wake, one console.error, and the sender has to retype with no signal that anything went wrong.

The shape

Guard only the post-write step, and put the guard where that step is:

  • deliverMessageToAgents is wrapped inside the bridge — the row already exists, so swallowing keeps the record and costs only the wake.
  • Everything earlier propagates to the route's outer handler and 500s.
  • The route keeps a bare await plus a comment stating the bareness is deliberate, because re-adding a blanket catch there is precisely the next edit someone makes.

The split now falls out of where the code sits rather than a runtime decision about which side failed.

Proof

__tests__/unit/services/telegramBridgeService.inboundRetry.test.js — three cases: relays normally; propagates when PGMessage.create rejects (and never reaches delivery); resolves when deliverMessageToAgents rejects (with the create still counted once). Route test inverted to assert the non-ack.

Two mutations, each producing exactly one red, and a different one:

remove the post-write guard   -> 1 failed / 16 passed
   ✕ swallows a failure AFTER the write, so the retry cannot duplicate it

re-add a blanket catch on the route -> 1 failed / 16 passed
   ✕ does not ack when the relay throws, so Telegram redelivers

Not done

Dedupe on message_id is the better fix — it gives retry safety without depending on where the throw landed — and it wants somewhere to keep seen ids. Deliberately not added hours before a live demo. This change is free and removes the duplication path either way.

Correction credit: sprint-review.

lilyshen0722 and others added 2 commits August 26, 2026 13:24
Telegram redelivers any update the webhook does not 2xx, and
relayTelegramMessageToPod is not idempotent: it writes the pod row
(PGMessage.create) before it wakes agents (deliverMessageToAgents), and
nothing dedupes on message_id. A throw in delivery therefore reached the
route's outer catch, returned 500, and the retry duplicated both the pod
message and every agent wake it triggered.

Wrap the relay call and sendStatus(200) regardless. A dropped relay is
recoverable; a doubled one is not.

Two route tests: the live-relay branch bypasses the buffer provider, and
a throwing relay still acks 200. Reverting the route change turns the
second red and leaves the other four green.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous shape acked 200 unconditionally, which is right for only half
the cases. relayTelegramMessageToPod writes the pod row (PGMessage.create)
before it wakes agents (deliverMessageToAgents), so a redelivery means two
different things:

  before the write - nothing persisted; Telegram's retry is the only thing
    that saves the update. A blanket 200 drops it silently: no pod message,
    no wake, one console line, and the sender has to retype.
  after the write - the row exists and nothing dedupes on message_id, so the
    retry duplicates both the message and every wake it triggers.

So guard only the post-write step, inside the bridge, and let anything
earlier propagate to the route's outer handler and 500. The route now
carries an explicit comment that its bare await is deliberate.

Three service tests pin the split (propagates before, swallows after,
succeeds normally) and the route test inverts to assert the non-ack.
Mutation controls, one red each and unique: removing the post-write guard
fails only 'swallows a failure AFTER the write'; re-adding a blanket catch
in the route fails only 'does not ack when the relay throws'.

Correction credit: sprint-review, who caught that the original PR body had
it exactly backwards - the dropped relay is the unrecoverable one.

Co-Authored-By: Claude Opus 5 <[email protected]>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Approving at afd569ed. Correct fix, and the mutation reproduces: reverting only the route change and leaving the test file in place gives 1 failed / 4 passed, and the red is the ack-on-throw case — nothing else in that suite notices. 5/5 green at the head.

The reasoning in the comment is the right one. A duplicate wake is unrecoverable and a dropped relay is not, so unconditional ack is the correct trade even before idempotency exists.

One residual the comment overstates

"A dropped relay is recoverable" holds only when the throw lands before the pod write. In telegramBridgeService.ts on main the order is:

:239  const created = await PGMessage.create(podId, String(linkedUserId), ...)
:248  await deliverMessageToAgents({ ... })      // unguarded

and deliverMessageToAgents awaits enqueueDmEvent / enqueueMentions with no internal try — so a throw there is reachable, and after this PR it produces a half delivery: the message is in the pod, no agent was woken, and we acked so Telegram will not retry. From the pod side that is indistinguishable from every agent choosing to ignore the human, which is a worse failure than a duplicate for an attention surface, and it is now silent by construction.

Not an argument against the ack — retrying would still duplicate. It is an argument that the catch is swallowing two different failures under one log line. Cheapest split, no new machinery:

} catch (relayErr) {
  console.error('[tg-bridge] inbound relay failed:', (relayErr as Error).message);
}

→ have relayTelegramMessageToPod report whether the pod row was written (it already returns { relayed, routedAgent }), and log the post-write failure at a distinguishable key. Then "message landed, wake lost" is greppable instead of looking like "nothing happened."

Second, smaller

The Telegram sender gets no signal either way. The bridge already holds telegramService.sendMessage and a botToken/chatId for the outbound direction, so a one-line failure notice back into the chat is available and would close the loop for the human whose message vanished. Worth a follow-up issue rather than this PR.

Not verified

I did not exercise the retry itself — no test here proves Telegram's redelivery behaviour, and I am taking "non-2xx ⇒ redeliver" from the Bot API contract, not from an observed retry against this endpoint. The mutation proves the ack, not the consequence of failing to ack. Also unverified: that deliverMessageToAgents actually throws in production for any realistic cause. I confirmed the await is unguarded and the path is reachable; I did not induce a failure.

@lilyshen0722 lilyshen0722 changed the title fix(telegram): ack the webhook even when the inbound relay throws fix(telegram): split the webhook ack on which side of the pod write failed Aug 26, 2026
@lilyshen0722
lilyshen0722 merged commit 994a963 into main Aug 26, 2026
13 checks passed
@lilyshen0722
lilyshen0722 deleted the fix/telegram-relay-ack branch August 26, 2026 20:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant