fix(telegram): drop pending updates before long polling

After the daemon was down ~9 hours it booted and answered every message
sent while it was gone -- 8 stale messages, 8 LLM turns, one burst.

Telegram holds undelivered updates for 24h and replays them on the first
getUpdates. launch()'s webhook branch already passes DropPendingUpdates;
the long-polling fallback had no equivalent, and polling is what this
deployment uses. deleteWebhook carries the flag even when no webhook is
registered -- the same call python-telegram-bot makes when it starts
polling -- and it doubles as a guard against a stale webhook, which
would otherwise fail getUpdates with 409.

Bounded by a 10s deadline so an unreachable Telegram cannot hold up
gateway startup.
This commit is contained in:
sam committed 2026-07-31 01:33:02 +10:00
1 parent f4bf755727
commit 75e30cb18a
2 files changed
+129

No files matched your search

+35
View File
@@ -81,6 +81,11 @@ type Gateway struct {
bot *bot.Bot
webhookCancel context.CancelFunc
running bool
// serverURL redirects the Bot API at a test server. Empty in production,
// where the library's default endpoint is used. It exists so launch's
// wiring can be tested without reaching api.telegram.org.
serverURL string
}
type UpdateService interface {
@@ -186,6 +191,9 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
if g.WebhookSecret != "" {
opts = append(opts, bot.WithWebhookSecretToken(g.WebhookSecret))
}
if g.serverURL != "" {
opts = append(opts, bot.WithServerURL(g.serverURL), bot.WithSkipGetMe())
}
b, err := bot.New(g.Token, opts...)
if err != nil {
@@ -247,6 +255,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
g.running = true
go b.StartWebhook(webhookCtx)
} else {
g.dropPendingUpdates(ctx, b)
g.running = true
go b.Start(ctx)
}
@@ -772,3 +781,29 @@ func (g *Gateway) ValidateConfig(cfg map[string]any) error {
// Compile-time guard.
var _ channels.Channel = (*Gateway)(nil)
// dropPendingUpdates clears Telegram's queue of undelivered updates before
// long polling starts.
//
// Telegram holds updates for 24h and replays them on the first getUpdates,
// so without this a daemon that was down overnight boots and answers every
// message sent while it was gone -- one LLM turn each, in a burst. The
// webhook path already passes DropPendingUpdates when it registers; polling
// has no equivalent, so it has to be asked for explicitly. deleteWebhook is
// the call that carries the flag, and it doubles as a guard against a stale
// webhook registration, which would make getUpdates fail with 409.
//
// This also runs on /restart, so a message sent during the restart window is
// discarded rather than answered late. That matches the webhook branch, which
// passes the same flag on every launch.
//
// Best-effort: a failure here is logged, not fatal. Chat availability matters
// more than a clean queue, and the deadline keeps an unreachable Telegram
// from holding up gateway startup.
func (g *Gateway) dropPendingUpdates(ctx context.Context, b *bot.Bot) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if _, err := b.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil {
g.log.Warn("could not drop pending telegram updates, backlog may be replayed", "error", err)
}
}
@@ -8,6 +8,7 @@ import (
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
@@ -542,3 +543,96 @@ func TestThreadIDString(t *testing.T) {
})
}
}
// A restart must not answer messages that arrived while the daemon was
// down. Telegram holds undelivered updates for 24h and replays them on the
// first getUpdates, so a boot after an outage answers hours-old chatter.
// The webhook path already passes DropPendingUpdates; long polling has to
// clear the backlog explicitly.
func TestDropPendingUpdatesClearsTheBacklog(t *testing.T) {
var gotPath string
var gotDrop bool
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
// The client sends multipart/form-data, not JSON.
if err := r.ParseMultipartForm(1 << 20); err != nil {
t.Errorf("parse Telegram request: %v", err)
}
gotDrop = r.FormValue("drop_pending_updates") == "true"
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
}))
defer api.Close()
b, err := bot.New("1:test", bot.WithServerURL(api.URL), bot.WithSkipGetMe())
if err != nil {
t.Fatalf("new test bot: %v", err)
}
g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler))
g.dropPendingUpdates(context.Background(), b)
if !strings.Contains(gotPath, "deleteWebhook") {
t.Errorf("called %q, want deleteWebhook", gotPath)
}
if !gotDrop {
t.Error("drop_pending_updates was not set; the backlog would be replayed on boot")
}
}
// Clearing the backlog is best-effort. A Telegram error here must not stop
// the gateway coming up -- chat availability matters more than a clean queue --
// but it must say so, or a silently replayed backlog looks like a bot bug.
func TestDropPendingUpdatesSurvivesAPIFailure(t *testing.T) {
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"ok":false,"description":"boom"}`))
}))
defer api.Close()
b, err := bot.New("1:test", bot.WithServerURL(api.URL), bot.WithSkipGetMe())
if err != nil {
t.Fatalf("new test bot: %v", err)
}
var logged strings.Builder
g := New("1:test", "", "", []int64{42}, slog.New(slog.NewTextHandler(&logged, nil)))
g.dropPendingUpdates(context.Background(), b) // must not panic or block
if !strings.Contains(logged.String(), "could not drop pending telegram updates") {
t.Errorf("failure was swallowed silently; log = %q", logged.String())
}
}
// The helper working is not the fix; launch calling it is. Without this,
// deleting the call from the polling branch leaves the suite green.
func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) {
var mu sync.Mutex
var dropped bool
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "deleteWebhook") {
if err := r.ParseMultipartForm(1 << 20); err == nil {
mu.Lock()
dropped = r.FormValue("drop_pending_updates") == "true"
mu.Unlock()
}
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
}))
defer api.Close()
g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler))
g.serverURL = api.URL
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if _, err := g.launch(ctx, nil); err != nil {
t.Fatalf("launch() error = %v", err)
}
cancel()
mu.Lock()
defer mu.Unlock()
if !dropped {
t.Error("launch() started long polling without dropping pending updates")
}
}