Skip to content

fix(updates): preserve delivery during shutdown - #317

Merged
negasus merged 3 commits into
go-telegram:mainfrom
INKCR0W:fix-shutdown-update-delivery
Nov 19, 2026
Merged

negasus merged 3 commits into
go-telegram:mainfrom
INKCR0W:fix-shutdown-update-delivery

Conversation

@INKCR0W

@INKCR0W INKCR0W commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Polling and webhook mode can both lose updates when the bot is stopped.

In polling mode, getUpdates advances lastUpdateID as soon as it reads an update, so the next request confirms it with Telegram before any handler has run. Updates still in b.updates when the context is canceled are never handled.

In webhook mode, WebhookHandler answers 200 for every valid update and puts it into b.updates. Updates still in that buffer at shutdown are lost, and Telegram doesn't retry them because it already got 200.

This change:

  • Polling. A worker claims each update before running any user code (matchers, middlewares, handler). A batch is confirmed once all its updates are claimed. If the context is canceled first, only the updates before the first unclaimed one are confirmed, and polling resumes there. Updates after it may be delivered again, but none are lost. After a request with a negative offset, the cursor moves to the first update of the batch, so the same rule applies.
  • Webhook. WebhookHandler returns 200 once a worker takes the update through an unbuffered handoff. It returns 503 if StartWebhook isn't running, or if the run stops or the request is canceled before a worker takes it, and 400 if the request body can't be read. Such an update is never handled, so Telegram's retry doesn't duplicate it.
  • Lifecycle. Each run has its own context and queue. Start and StartWebhook wait for running handlers before returning, and for a previous run on the same bot before starting. If every worker exits (e.g. runtime.Goexit in a matcher), the run stops. With zero workers they report an error and return.

Behavior changes:

  • A handler that ignores context cancellation keeps Start or StartWebhook from returning. Calling either from a handler of the same running bot blocks until that call's context is canceled.
  • With WithNotAsyncHandlers, a webhook request waits for a free worker, and polling fetches the next batch only after the current one is dispatched.
  • WithUpdatesChannelCap now only bounds how many updates wait for a worker. A negative capacity makes New return an error instead of panicking.
  • If a matcher or middleware constructor exits through runtime.Goexit, the update still counts as dispatched in both modes (200 for webhook, confirmed for polling), so a bad update isn't redelivered forever.
  • The some updates lost, ctx done and failed to send update, ctx done errors are gone. 503s aren't logged since Telegram retries them. A request while StartWebhook isn't running logs webhook update rejected: StartWebhook is not running, and starting without workers logs cannot start bot without update workers.

Known limitations (same as before this change):

  • Telegram only learns the new offset from the next getUpdates call, so after a process restart the last batch may be delivered again. Delivery is at least once.
  • WithInitialOffset(k) sends k+1.

@codecov-commenter

codecov-commenter commented Nov 17, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 92.30769% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.21%. Comparing base (7ce11c6) to head (9d7a554).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
wait_updates.go 90.78% 5 Missing and 2 partials ⚠️
get_updates.go 93.93% 1 Missing and 1 partial ⚠️
webhook_handler.go 92.85% 2 Missing ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #317      +/-   ##
==========================================
+ Coverage   61.28%   63.21%   +1.93%     
==========================================
  Files          39       40       +1     
  Lines        3278     3404     +126     
==========================================
+ Hits         2009     2152     +143     
+ Misses       1216     1194      -22     
- Partials       53       58       +5     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@negasus negasus 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.

Thanks for addressing shutdown handling. I found a reproducible logical race in webhook admission during shutdown that can acknowledge and then drop an update. Please address the inline comment before merging. The full go test -race -count=1 ./... suite passed locally, but repeated execution of the existing shutdown test exposed the race.

Comment thread webhook_handler.go
case <-stopping:
return false
case run.queue <- queuedUpdate{update: update}:
return true

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.

A webhook request blocked on a full queue can still receive 200 after shutdown begins. Once the run context is canceled, workers drain/discard queued updates, which can make both stopping and the queue-send case ready. Go's select can choose the send, so this returns true even though the update will be discarded. Telegram sees 200 and will not retry it.

Reproduced on this commit using the existing test:

go test -run TestWebhookHandler_StopsDispatchingOnShutdown -count=10000 .

Two iterations failed with:

status for blocked update = 200, want 503
reported webhook stopped before dispatching accepted updates, dropped 2, want the dropped queued update

Please coordinate admission with shutdown so a request unblocked during shutdown does not acknowledge an update that will be dropped, and add a deterministic regression test for this interleaving. The context check before this select does not prevent cancellation between that check and the send.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the repro. Checking the context before the select can't close that window, and 1990946 still had the same problem through an external cancel and with a zero-capacity queue. So I reworked the webhook path instead of patching the select.

Each run now has its own queue, which is never closed or drained. The request hands the update to a worker through an unbuffered channel and returns 200 only if the worker takes it. If the run stops or the request is canceled first, it returns 503 and the worker skips the update. Since the handoff is unbuffered, the request and the worker always agree on whether the update was taken, so nothing is left to drop at shutdown.

TestWebhookHandler_StopsDispatchingOnShutdown now checks that a request blocked on a full queue gets 503 when the run stops, and your command passes 10000/10000 here. TestWebhookHandler_SkipsUpdatesOfCanceledRequests covers a request canceled while its update is still queued.

The polling side changed too, see the updated description.

A request waiting for queue space could be acknowledged after StartWebhook's
ctx was canceled: dropping a queued update freed space, and select could pick
the send over the stop case. Admission now checks the run and sends under
updatesMx with a reserved slot, and dropped updates do not free slots.
Polling: a worker claims each update before running any user code, and
on cancellation only the updates before the first unclaimed one are
confirmed. After a negative-offset request the cursor moves to the first
update of the batch.

Webhook: WebhookHandler returns 200 once a worker takes the update
through an unbuffered handoff, 503 if StartWebhook is not running or the
run stops or the request is canceled first, and 400 for an unreadable
body.

Each run has its own context and queue. Start and StartWebhook wait for
running handlers and for a previous run on the same bot.
@INKCR0W
INKCR0W requested a review from negasus November 18, 2026 19:58

@negasus negasus 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.

Re-reviewed commit 9d7a554. The unbuffered webhook handoff addresses the previously reported acknowledgment/drop race during shutdown. No blocking issues found in the updated polling confirmation and run lifecycle handling. Validation passed locally: go test -race -count=1 ./... and go test -run TestWebhookHandler_StopsDispatchingOnShutdown -count=10000 . Thanks for the rework!

@negasus
negasus merged commit 57414ed into go-telegram:main Nov 19, 2026
3 checks passed
@INKCR0W
INKCR0W deleted the fix-shutdown-update-delivery branch November 19, 2026 09:23
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.

3 participants