Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7477 fix(telegram): one reply per turn across replicas, restarts and retries (#8545)
Bohan Jiang1df4e0a8bf29
diff --git a/server/cmd/migrate/channel_reply_delivery_upgrade_test.go b/server/cmd/migrate/channel_reply_delivery_upgrade_test.gonew file mode 100644index 0000000000..308f613125--- /dev/null+++ b/server/cmd/migrate/channel_reply_delivery_upgrade_test.go@@ -0,0 +1,122 @@+package main++import (+ "context"+ "os"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"+)++// A database that installed channel_reply_delivery before attempt_depth+// existed must gain the column by upgrading, not by being rebuilt.+//+// The column was first added by editing the create-table migration in place.+// Any database+// that had already recorded 500 never saw the change, so every query touching+// the column failed on exactly the deployments where the feature was already+// installed — and a fresh rebuild passing said nothing about it. This runs the+// upgrade the way a deployment does: the old table shape, then the migration.+func TestChannelReplyDeliveryAttemptDepthUpgradesAnInstalledTable(t *testing.T) {+ t.Parallel()+ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ t.Skip("integration test requires Postgres at DATABASE_URL")+ }++ ctx := context.Background()+ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ t.Fatalf("connect to Postgres: %v", err)+ }+ t.Cleanup(pool.Close)++ schema := "reply_delivery_upgrade_" + strings.ReplaceAll(uuid.NewString(), "-", "")+ quotedSchema := pgx.Identifier{schema}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {+ t.Fatalf("create schema: %v", err)+ }+ t.Cleanup(func() {+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA "+quotedSchema+" CASCADE")+ })++ conn, err := pool.Acquire(ctx)+ if err != nil {+ t.Fatalf("acquire connection: %v", err)+ }+ defer conn.Release()+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, schema); err != nil {+ t.Fatalf("set search path: %v", err)+ }++ // The table as the create-table migration made it, before the column existed.+ if _, err := conn.Exec(ctx, `+ CREATE TABLE channel_reply_delivery (+ turn_id UUID NOT NULL,+ task_id UUID NOT NULL,+ binding_id UUID NOT NULL,+ installation_id UUID NOT NULL,+ channel_type TEXT NOT NULL,+ chat_id TEXT NOT NULL,+ phase TEXT NOT NULL,+ send_state TEXT NOT NULL,+ message_id TEXT NOT NULL DEFAULT '',+ chunks_sent INTEGER NOT NULL DEFAULT 0,+ settled_reason TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ `); err != nil {+ t.Fatalf("create the pre-upgrade table: %v", err)+ }+ // A row written by the already-installed version, to prove the upgrade+ // keeps existing turns rather than requiring an empty table.+ turnID := uuid.NewString()+ if _, err := conn.Exec(ctx, `+ INSERT INTO channel_reply_delivery (+ turn_id, task_id, binding_id, installation_id, channel_type, chat_id, phase, send_state+ ) VALUES ($1, $1, $1, $1, 'telegram', '42', 'streaming', 'none')+ `, turnID); err != nil {+ t.Fatalf("seed an installed row: %v", err)+ }++ upgrade, err := os.ReadFile("../../migrations/506_channel_reply_delivery_attempt_depth.up.sql")+ if err != nil {+ t.Fatalf("read the upgrade migration: %v", err)+ }+ if _, err := conn.Exec(ctx, string(upgrade)); err != nil {+ t.Fatalf("apply the upgrade migration: %v", err)+ }++ var depth int+ if err := conn.QueryRow(ctx,+ `SELECT attempt_depth FROM channel_reply_delivery WHERE turn_id = $1`, turnID).Scan(&depth); err != nil {+ t.Fatalf("read attempt_depth after the upgrade: %v", err)+ }+ if depth != 0 {+ t.Fatalf("existing turn got attempt_depth %d, want the 0 default", depth)+ }++ // The constraint has to exist too, or an upgraded database and a fresh one+ // disagree about what the column accepts.+ var constraints int+ if err := conn.QueryRow(ctx, `+ SELECT count(*) FROM pg_constraint+ WHERE conname = 'channel_reply_delivery_attempt_depth_check'+ AND connamespace = $1::regnamespace+ `, schema).Scan(&constraints); err != nil {+ t.Fatalf("look up the depth constraint: %v", err)+ }+ if constraints != 1 {+ t.Fatalf("upgraded schema has %d attempt_depth constraints, want 1", constraints)+ }++ // Applying it twice must be a no-op: migrations are retried after a failed+ // run, and a conditionally skipped one is still recorded.+ if _, err := conn.Exec(ctx, string(upgrade)); err != nil {+ t.Fatalf("re-apply the upgrade migration: %v", err)+ }+}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex cfd5ea14c9..0623d6a1ea 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,9 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "503_channel_reply_delivery_turn_index": "idx_channel_reply_delivery_turn",+ "504_channel_reply_delivery_installation_index": "idx_channel_reply_delivery_installation",+ "505_channel_reply_delivery_binding_index": "idx_channel_reply_delivery_binding","495_issue_to_label_label_id_index": "issue_to_label_label_idx","496_chat_session_agent_id_index": "idx_chat_session_agent_id","497_agent_task_queue_delegated_failure_evidence_index": "idx_agent_task_queue_delegated_failure_evidence",diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 6c3d66cec3..39ab0ebc84 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -45,6 +45,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"channel_media_pending_object": workspaceDeleteSettle,"channel_outbound_card_message": workspaceDelete,"channel_outbound_message": workspaceDelete,+ "channel_reply_delivery": workspaceDelete,"channel_task_delivery": workspaceDelete,"channel_user_binding": workspaceDelete,"chat_draft_restore": workspaceDelete,diff --git a/server/internal/integrations/telegram/delivery.go b/server/internal/integrations/telegram/delivery.gonew file mode 100644index 0000000000..1355d6ce54--- /dev/null+++ b/server/internal/integrations/telegram/delivery.go@@ -0,0 +1,457 @@+package telegram++// delivery.go — reply-delivery ownership.+//+// A task's reply reaches Telegram through three paths: the streamed+// placeholder, the final answer, and the failure notice. In a multi-replica+// deployment they also run in three different processes — the daemon's+// transcript report and its completion callback are independent HTTP requests+// that land wherever the load balancer sends them, and the event bus is+// in-process. A process that cannot see the placeholder posts its own copy of+// the same answer, which is the duplicate users report (GH #8049, #7750).+//+// channel_reply_delivery is the shared owner, and this file is the only way to+// touch it. Three rules hold everywhere:+//+// - One user turn, one owner. A path takes the turn's lease before it calls+// Telegram and proves it still holds the lease when it records what+// happened. "The UPDATE is atomic" is not the same as "only one process+// delivers".+// - A placeholder is not progress. Having an editable message says nothing+// about how much of the final answer has been delivered; conflating the+// two silently truncates replies.+// - A send whose result was lost stays lost. Telegram's sendMessage takes no+// caller-supplied idempotency key, so a retry cannot be deduplicated by+// the provider. An unknown outcome ends delivery with the evidence kept.++import (+ "context"+ "errors"+ "fmt"+ "strconv"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const (+ deliveryPhaseStreaming = "streaming"+ deliveryPhaseTerminal = "terminal"+ deliveryPhaseSettled = "settled"++ deliverySendNone = "none"+ deliverySendInFlight = "in_flight"+ deliverySendKnown = "known"+ deliverySendUnknown = "unknown"+)++const (+ // deliveryLeaseTTL has to outlive one Telegram round trip, because the+ // lease is held across the call: a shorter lease would let a second+ // process take a turn over while the first is still talking to Telegram.+ // It is also the longest a dead process can block a turn, so it is not+ // generous.+ deliveryLeaseTTL = 30 * time.Second+ // deliveryCallTimeout bounds one provider call made while holding a turn.+ //+ // The shared Bot API client allows 65s, which getUpdates needs for long+ // polling but a delivery call must never take: a request that outlives the+ // lease can land after another process has taken the turn over and+ // finished it. The budget has to close, so one call plus recording its+ // outcome stays inside the lease — see TestDeliveryCallBudgetFitsTheLease.+ deliveryCallTimeout = 20 * time.Second+ // deliveryRecordTimeout bounds the writes that record what Telegram did.+ // They run on a context detached from the caller's: the deadline that+ // killed a send must not also stop us recording that the send happened.+ deliveryRecordTimeout = 5 * time.Second+ // deliveryBusyRetry spaces attempts on a turn another process holds.+ deliveryBusyRetry = 250 * time.Millisecond+ // maxDeliveryAcquireAttempts bounds those attempts. The lease is what+ // frees a turn held by a process that died, so this has to outlast one;+ // it bounds how long a live holder can keep the session's queue waiting.+ maxDeliveryAcquireAttempts = 240+ // maxDeliveryClaimErrorAttempts is the budget when the ownership write+ // itself fails. That is a database problem, not a busy turn: retrying it+ // for a minute holds the session's queue for a minute, and the reply is no+ // more deliverable at the end of it.+ maxDeliveryClaimErrorAttempts = 5+)++// deliveryOutcome is what Telegram did with one send.+type deliveryOutcome int++const (+ // deliveryAccepted — the provider returned a message id.+ deliveryAccepted deliveryOutcome = iota+ // deliveryRefused — the provider answered and refused. Nothing is in the+ // chat, so the send may be attempted again.+ deliveryRefused+ // deliveryUnknown — no answer came back. The message may be in the chat.+ deliveryUnknown+)++// deliveryStatus is why an acquire did not hand over the turn.+type deliveryStatus int++const (+ deliveryAcquired deliveryStatus = iota+ // deliveryBusy — another process holds a live lease. Retry.+ deliveryBusy+ // deliveryClosed — the turn is settled, or the final answer has taken over+ // a reply a streaming frame wanted. Stop.+ deliveryClosed+)++// deliveryLease is this process's hold on one turn's reply, together with the+// state it found. Every write goes through the lease, so a caller cannot+// record an outcome against a turn it no longer owns.+type deliveryLease struct {+ turnID pgtype.UUID+ token pgtype.UUID+ row db.ChannelReplyDelivery+}++// messageID is the Telegram message this turn owns, or 0 when there is none to+// edit. An in-flight or lost send has no usable id.+func (l *deliveryLease) messageID() int64 {+ if l == nil || l.row.SendState != deliverySendKnown || l.row.MessageID == "" {+ return 0+ }+ id, err := strconv.ParseInt(l.row.MessageID, 10, 64)+ if err != nil {+ return 0+ }+ return id+}++// chunksSent is how many parts of the final answer are already in the chat.+func (l *deliveryLease) chunksSent() int {+ if l == nil {+ return 0+ }+ return int(l.row.ChunksSent)+}++func (l *deliveryLease) sendState() string {+ if l == nil {+ return deliverySendNone+ }+ return l.row.SendState+}++// replyTurn is which user turn a task belongs to and how far down that turn's+// retry chain the task sits.+type replyTurn struct {+ id pgtype.UUID+ depth int32+}++// turnFor maps a task to its user turn: the root of its automatic-retry chain.+// A retry runs under a new task id and has to finish the reply its previous+// attempt started rather than answer beside it.+//+// A task with no queue row is its own turn, at depth zero — that is a fact, not+// a failure. Any other error is reported: guessing that the task is its own+// turn would open a second reply next to the one the previous attempt is still+// holding, which is the bug this lineage exists to prevent.+func (o *Outbound) turnFor(ctx context.Context, taskID pgtype.UUID) (replyTurn, error) {+ row, err := o.q.GetChannelReplyTurn(ctx, taskID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return replyTurn{id: taskID}, nil+ }+ return replyTurn{}, fmt.Errorf("resolve reply turn: %w", err)+ }+ if !row.TurnID.Valid {+ return replyTurn{id: taskID}, nil+ }+ return replyTurn{id: row.TurnID, depth: int32(row.AttemptDepth)}, nil+}++// acquireDelivery takes the turn's lease for one of the delivery phases.+func (o *Outbound) acquireDelivery(ctx context.Context, target *replyTarget, turn replyTurn, phase string) (*deliveryLease, deliveryStatus, error) {+ turnID := turn.id+ token := pgtype.UUID{Bytes: uuid.New(), Valid: true}+ row, err := o.q.AcquireChannelReplyDelivery(ctx, db.AcquireChannelReplyDeliveryParams{+ TurnID: turnID,+ TaskID: target.taskID,+ AttemptDepth: turn.depth,+ BindingID: target.bindingID,+ InstallationID: target.installationID,+ ChannelType: string(TypeTelegram),+ ChatID: target.channelChatID,+ Phase: phase,+ OwnerToken: token,+ LeaseSeconds: o.leaseSeconds(),+ })+ if err == nil {+ return &deliveryLease{turnID: turnID, token: token, row: row}, deliveryAcquired, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return nil, deliveryBusy, err+ }++ // No row means the turn was refused, and the three reasons need different+ // answers: settled and taken-over are final, a live owner is not.+ current, readErr := o.q.GetChannelReplyDelivery(ctx, turnID)+ if readErr != nil {+ if errors.Is(readErr, pgx.ErrNoRows) {+ // Raced with a concurrent close; nothing to deliver.+ return nil, deliveryClosed, nil+ }+ return nil, deliveryBusy, readErr+ }+ if current.Phase == deliveryPhaseSettled {+ return nil, deliveryClosed, nil+ }+ if phase == deliveryPhaseStreaming && current.Phase == deliveryPhaseTerminal {+ return nil, deliveryClosed, nil+ }+ if turn.depth < current.AttemptDepth {+ // A later attempt of this turn has taken over. This one is not waiting+ // for anything — it has been superseded, and its frames must not+ // rewrite what the user is now reading.+ return nil, deliveryClosed, nil+ }+ return nil, deliveryBusy, nil+}++// releaseDelivery hands the turn back so the next path does not wait out the+// lease. Best effort: an unreleased lease expires on its own.+func (o *Outbound) releaseDelivery(ctx context.Context, lease *deliveryLease) {+ if lease == nil {+ return+ }+ ctx, cancel := o.recordContext(ctx)+ defer cancel()+ if _, err := o.q.ReleaseChannelReplyDelivery(ctx, db.ReleaseChannelReplyDeliveryParams{+ TurnID: lease.turnID,+ OwnerToken: lease.token,+ }); err != nil {+ o.logger.WarnContext(ctx, "telegram outbound: releasing the delivery lease failed", "error", err)+ }+}++// claimSend publishes a send before it is made, so any other process reads+// "a send is outstanding" rather than "nothing has been sent".+func (o *Outbound) claimSend(ctx context.Context, lease *deliveryLease) bool {+ rows, err := o.q.MarkChannelReplyDeliverySending(ctx, db.MarkChannelReplyDeliverySendingParams{+ TurnID: lease.turnID,+ OwnerToken: lease.token,+ })+ if err != nil {+ o.logger.WarnContext(ctx, "telegram outbound: publishing the send failed; not sending", "error", err)+ return false+ }+ return rows == 1+}++// classifySend turns a Bot API result into what the turn now knows.+func classifySend(err error) deliveryOutcome {+ switch {+ case err == nil:+ return deliveryAccepted+ case isDefiniteRejection(err):+ return deliveryRefused+ default:+ return deliveryUnknown+ }+}++// isDefiniteRejection reports whether Telegram answered in a way that proves+// the message was not posted.+//+// A 5xx does not prove that. Telegram can accept a sendMessage and still fail+// on the way back, and treating that as "nothing was sent" is what puts the+// answer in the chat twice. Only a client error — including a 429, which is+// refused outright — is evidence of a message that never landed.+func isDefiniteRejection(err error) bool {+ var ae *apiError+ if !errors.As(err, &ae) {+ return false+ }+ return ae.Code >= 400 && ae.Code < 500+}++// recordSend writes what Telegram did. placeholder distinguishes the streamed+// message, which gives the turn something to edit, from a part of the final+// answer, which is progress. chunksSent is ignored for a placeholder.+func (o *Outbound) recordSend(ctx context.Context, lease *deliveryLease, placeholder bool, messageID int64, chunksSent int, sendErr error) deliveryOutcome {+ outcome := classifySend(sendErr)+ ctx, cancel := o.recordContext(ctx)+ defer cancel()++ var err error+ switch outcome {+ case deliveryAccepted:+ if placeholder {+ _, err = o.q.RecordChannelReplyDeliveryPlaceholder(ctx, db.RecordChannelReplyDeliveryPlaceholderParams{+ TurnID: lease.turnID,+ OwnerToken: lease.token,+ MessageID: strconv.FormatInt(messageID, 10),+ })+ } else {+ _, err = o.q.RecordChannelReplyDeliveryChunk(ctx, db.RecordChannelReplyDeliveryChunkParams{+ TurnID: lease.turnID,+ OwnerToken: lease.token,+ MessageID: strconv.FormatInt(messageID, 10),+ ChunksSent: int32(chunksSent),+ })+ }+ case deliveryRefused:+ _, err = o.q.ResetChannelReplyDeliverySend(ctx, db.ResetChannelReplyDeliverySendParams{+ TurnID: lease.turnID,+ OwnerToken: lease.token,+ })+ default:+ o.logger.WarnContext(ctx, "telegram outbound: send result unknown; delivery stops rather than risk a duplicate",+ "turn_id", uuidText(lease.turnID), "error", sendErr)+ // Deliberately not owner-checked: this write has to land even if our+ // lease expired while the request hung, because the successor reading+ // this row must not conclude that nothing was ever sent.+ _, err = o.q.MarkChannelReplyDeliverySendUnknown(ctx, lease.turnID)+ }+ if err != nil {+ // The row now disagrees with Telegram. Say so loudly: a lost progress+ // write is what makes a later delivery repeat a part, and a lost+ // unknown write is what makes it re-send.+ o.logger.ErrorContext(ctx, "telegram outbound: recording the send outcome failed; delivery state is behind Telegram",+ "turn_id", uuidText(lease.turnID), "outcome", outcome, "error", err)+ }+ return outcome+}++// settleDelivery ends the turn. Afterwards no path sends or edits for it,+// including a text frame that was still in flight when the task finished.+func (o *Outbound) settleDelivery(ctx context.Context, lease *deliveryLease, reason string) {+ ctx, cancel := o.recordContext(ctx)+ defer cancel()+ if _, err := o.q.SettleChannelReplyDelivery(ctx, db.SettleChannelReplyDeliveryParams{+ TurnID: lease.turnID,+ OwnerToken: lease.token,+ SettledReason: reason,+ }); err != nil {+ o.logger.ErrorContext(ctx, "telegram outbound: settling the reply failed; a late frame may reopen it",+ "turn_id", uuidText(lease.turnID), "reason", reason, "error", err)+ }+}++// closeTurn ends a turn with no answer to deliver — cancelled, or completed+// empty. It creates the row when the turn never reached Telegram at all:+// without that, a first text frame arriving after the cancellation would find+// nothing, open a placeholder, and leave it there with nothing to finish it.+func (o *Outbound) closeTurn(ctx context.Context, target *replyTarget, turn replyTurn, reason string) (bool, error) {+ turnID := turn.id+ _, err := o.q.CloseChannelReplyDeliveryTurn(ctx, db.CloseChannelReplyDeliveryTurnParams{+ TurnID: turnID,+ TaskID: target.taskID,+ AttemptDepth: turn.depth,+ BindingID: target.bindingID,+ InstallationID: target.installationID,+ ChannelType: string(TypeTelegram),+ ChatID: target.channelChatID,+ SettledReason: reason,+ })+ if err == nil {+ return true, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return false, err+ }+ // Settled, superseded, or held by a live owner — only the last is worth+ // waiting for.+ current, readErr := o.q.GetChannelReplyDelivery(ctx, turnID)+ if readErr != nil {+ return false, readErr+ }+ if turn.depth < current.AttemptDepth {+ // A later attempt owns this turn. Closing it is not this attempt's to+ // do, and waiting for the chance would hold the session's queue for a+ // reply that is already someone else's.+ return true, nil+ }+ return current.Phase == deliveryPhaseSettled, nil+}++// recordContext detaches a write that records what Telegram did from the+// caller's deadline. The request that timed out is exactly when recording+// matters most: dropping the write leaves the row claiming a send is still in+// flight, and that blocks the turn until the lease expires.+func (o *Outbound) recordContext(ctx context.Context) (context.Context, context.CancelFunc) {+ return context.WithTimeout(context.WithoutCancel(ctx), deliveryRecordTimeout)+}++func uuidText(id pgtype.UUID) string {+ text, err := id.Value()+ if err != nil || text == nil {+ return ""+ }+ s, _ := text.(string)+ return s+}++// renewDelivery re-proves the turn is ours and pushes the lease out. Terminal+// delivery holds a turn across several scheduler rounds, so it asks again+// before each Telegram call rather than trusting a lease taken minutes ago.+// False means another process owns the turn now and this one must stop.+func (o *Outbound) renewDelivery(ctx context.Context, lease *deliveryLease) bool {+ rows, err := o.q.RenewChannelReplyDelivery(ctx, db.RenewChannelReplyDeliveryParams{+ TurnID: lease.turnID,+ OwnerToken: lease.token,+ LeaseSeconds: o.leaseSeconds(),+ })+ if err != nil {+ o.logger.WarnContext(ctx, "telegram outbound: renewing the delivery lease failed; not sending", "error", err)+ return false+ }+ return rows == 1+}++// inheritedSend reports a send this process did not make and cannot resolve.+// Acquiring a turn whose previous owner died mid-send does not mean nothing+// was sent — it means nobody knows. Recording that is what stops the successor+// from posting a second copy, and what lets the turn finish instead of waiting+// on a lease forever.+func (o *Outbound) inheritedSend(ctx context.Context, lease *deliveryLease) bool {+ switch lease.sendState() {+ case deliverySendUnknown:+ return true+ case deliverySendInFlight:+ o.logger.WarnContext(ctx, "telegram outbound: inherited a send from a process that stopped; outcome unknown",+ "turn_id", uuidText(lease.turnID))+ recordCtx, cancel := o.recordContext(ctx)+ defer cancel()+ if _, err := o.q.MarkChannelReplyDeliverySendUnknown(recordCtx, lease.turnID); err != nil {+ o.logger.ErrorContext(ctx, "telegram outbound: recording the inherited send failed",+ "turn_id", uuidText(lease.turnID), "error", err)+ }+ return true+ }+ return false+}++// leaseSeconds is the lease length this Outbound hands out.+func (o *Outbound) leaseSeconds() float64 {+ if o.leaseTTL > 0 {+ return o.leaseTTL.Seconds()+ }+ return deliveryLeaseTTL.Seconds()+}++// callContext bounds one provider call so it cannot outlive the lease that+// authorises it. Paired with re-proving the lease immediately beforehand, this+// is what makes "the turn was taken over mid-call" a budget question rather+// than a race: the call cannot still be running when the lease lapses.+func (o *Outbound) callContext(ctx context.Context) (context.Context, context.CancelFunc) {+ budget := deliveryCallTimeout+ if o.leaseTTL > 0 && o.leaseTTL < deliveryLeaseTTL {+ // Tests shorten the lease to exercise takeover; the call budget has to+ // shrink with it or the relationship under test stops holding.+ budget = o.leaseTTL / 3+ }+ return context.WithTimeout(ctx, budget)+}diff --git a/server/internal/integrations/telegram/main_test.go b/server/internal/integrations/telegram/main_test.gonew file mode 100644index 0000000000..05d8c33e22--- /dev/null+++ b/server/internal/integrations/telegram/main_test.go@@ -0,0 +1,45 @@+package telegram++import (+ "context"+ "fmt"+ "os"+ "testing"++ "github.com/jackc/pgx/v5/pgxpool"+)++// testPool backs every test that exercises reply-delivery ownership.+//+// Those tests run the real queries rather than a hand-written stand-in on+// purpose. The first version of this feature shipped with an in-memory fake of+// the ownership table, and the fake quietly disagreed with the SQL about one+// column — enough for the whole suite to pass while the final answer never+// reached Telegram. A fake of a state machine is a second implementation of+// it, and the two drift.+//+// Without a database the suite exits green rather than red, the same contract+// the other DB-backed packages here follow.+var testPool *pgxpool.Pool++func TestMain(m *testing.M) {+ ctx := context.Background()+ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"+ }+ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ fmt.Printf("Skipping telegram delivery tests: could not connect: %v\n", err)+ os.Exit(m.Run())+ }+ if err := pool.Ping(ctx); err != nil {+ fmt.Printf("Skipping telegram delivery tests: database not reachable: %v\n", err)+ pool.Close()+ os.Exit(m.Run())+ }+ testPool = pool+ code := m.Run()+ pool.Close()+ os.Exit(code)+}diff --git a/server/internal/integrations/telegram/outbound.go b/server/internal/integrations/telegram/outbound.goindex f1a5e702c7..da44a44238 100644--- a/server/internal/integrations/telegram/outbound.go+++ b/server/internal/integrations/telegram/outbound.go@@ -40,6 +40,11 @@ type Outbound struct {apiBase stringclient *http.Client+ // leaseTTL is how long a delivery lease holds a turn. Injectable because+ // expiry is decided by database time, which a test cannot fast-forward:+ // exercising takeover after an owner dies means really waiting one out.+ leaseTTL time.Duration+mu sync.Mutexstreams map[string]*streamState // key = task_idchats map[chatScheduleKey]*chatSchedule@@ -68,6 +73,22 @@ type Outbound struct {type outboundQueries interface {GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)++ // Reply-delivery ownership. The streamed placeholder, the final answer and+ // the failure notice agree on who owns a reply through these and nothing+ // else — see delivery.go.+ GetChannelReplyTurn(ctx context.Context, taskID pgtype.UUID) (db.GetChannelReplyTurnRow, error)+ AcquireChannelReplyDelivery(ctx context.Context, arg db.AcquireChannelReplyDeliveryParams) (db.ChannelReplyDelivery, error)+ GetChannelReplyDelivery(ctx context.Context, turnID pgtype.UUID) (db.ChannelReplyDelivery, error)+ RenewChannelReplyDelivery(ctx context.Context, arg db.RenewChannelReplyDeliveryParams) (int64, error)+ ReleaseChannelReplyDelivery(ctx context.Context, arg db.ReleaseChannelReplyDeliveryParams) (int64, error)+ MarkChannelReplyDeliverySending(ctx context.Context, arg db.MarkChannelReplyDeliverySendingParams) (int64, error)+ RecordChannelReplyDeliveryPlaceholder(ctx context.Context, arg db.RecordChannelReplyDeliveryPlaceholderParams) (int64, error)+ RecordChannelReplyDeliveryChunk(ctx context.Context, arg db.RecordChannelReplyDeliveryChunkParams) (int64, error)+ ResetChannelReplyDeliverySend(ctx context.Context, arg db.ResetChannelReplyDeliverySendParams) (int64, error)+ MarkChannelReplyDeliverySendUnknown(ctx context.Context, turnID pgtype.UUID) (int64, error)+ SettleChannelReplyDelivery(ctx context.Context, arg db.SettleChannelReplyDeliveryParams) (int64, error)+ CloseChannelReplyDeliveryTurn(ctx context.Context, arg db.CloseChannelReplyDeliveryTurnParams) (db.ChannelReplyDelivery, error)}// streamState tracks one in-flight streamed reply.@@ -76,10 +97,13 @@ type streamState struct {threadID int64replyTo int64messageID int64 // placeholder message being edited; 0 until first send- // sending marks the placeholder's sendMessage as in flight: Telegram- // already has the message but its id only lands when the call returns.- // Terminal delivery waits for that instead of reading messageID as 0.- sending bool+ // turn is the user turn this stream belongs to, cached after the first+ // frame resolves it: an automatic retry's lineage cannot change mid-run.+ turn replyTurn+ // lastFrameAt is when a frame last touched this stream. A reply settled by+ // another replica leaves this one holding local state nothing will come+ // back for, so idle streams are reclaimed rather than kept forever.+ lastFrameAt time.Timeaccumulated stringschedule *chatSchedule}@@ -121,9 +145,31 @@ type terminalReply struct {placeholderEdited boolfallbackFreshSend boolplainTextFallback bool- cleanupOnce sync.Once+ plainTextEdit bool+ kind terminalKind+ settleReason string+ turn replyTurn+ turnResolved bool+ lease *deliveryLease+ acquireAttempts int+ editAttempts int+ cleanupOnce sync.Once}+// terminalKind is what a queued item delivers. All three take the turn's lease+// the same way; they differ only in what they do once they hold it.+type terminalKind int++const (+ // terminalKindAnswer delivers the agent's reply.+ terminalKindAnswer terminalKind = iota+ // terminalKindClose ends a turn with no answer — cancelled, or completed+ // empty — so a text frame still in flight cannot reopen it.+ terminalKindClose+ // terminalKindNotice posts the run-failed notice.+ terminalKindNotice+)+type terminalWork struct {sessionID stringreply *terminalReply@@ -169,6 +215,24 @@ const editInterval = 2500 * time.Millisecond// never outlast the partial's own 10s send context.const placeholderSettleRetry = 250 * time.Millisecond+// streamSweepGrace is how quiet a streamed reply must be before this process+// asks the database whether its turn is over.+//+// Time alone never decides that. A run's silence budget is hours — a task can+// sit in a tool call or a test run far longer than any timeout worth picking —+// so "no text for a while" says nothing about whether the reply is finished.+// Only the delivery row does: settled, or held by an attempt that superseded+// this one. The grace period exists to keep the sweep cheap, not to judge.+const streamSweepGrace = 2 * time.Minute++// streamSweepInterval paces the sweep. Terminal delivery hands local state back+// on its own; this exists for the turn another replica settled, which cannot+// reach into this process to tidy up. Left alone those entries and their+// chat-scheduler references are held for good, and once enough distinct chats+// accumulate the scheduler refuses new ones — streaming then stops for chats+// with nothing wrong with them.+const streamSweepInterval = time.Minute+// Idle schedules remain briefly reusable so sequential tasks and cancellation// cannot discard a chat's edit cooldown or Telegram retry_after window. The// schedule and compressed-fallback maps both have hard capacity limits.@@ -181,6 +245,16 @@ const (maxQueuedTerminalReplies = 64maxQueuedTerminalRepliesPerSession = 8maxQueuedTerminalReplyBytes = 16 << 20++ // terminalEditRetryDelay spaces retries of an edit whose outcome Telegram+ // left ambiguous; maxAmbiguousEditAttempts bounds them, because the+ // terminal queue is per session and a reply that never settles blocks+ // every later answer in the same chat.+ terminalEditRetryDelay = time.Second+ maxAmbiguousEditAttempts = 3+ // The failure notice runs on the synchronous event bus, so its retries are+ // tighter than the answer's: latency here delays realtime fanout.+ maxNoticeEditAttempts = 2)// streamPlaceholder is the first frame's text while the first tokens arrive.@@ -200,6 +274,7 @@ func NewOutbound(q outboundQueries, decrypt Decrypter, apiBase string, client *hlogger: logger,apiBase: apiBase,client: client,+ leaseTTL: deliveryLeaseTTL,streams: make(map[string]*streamState),chats: make(map[chatScheduleKey]*chatSchedule),botFallbackBackoff: make(map[string]time.Time),@@ -226,7 +301,8 @@ func (o *Outbound) Register(bus *events.Bus) {// Telegram rate limits and network latency must never delay realtime fanout.func (o *Outbound) Start(ctx context.Context) {o.workerOnce.Do(func() {- o.workerWG.Add(1)+ o.workerWG.Add(2)+ go o.runStreamSweeper(ctx)o.terminalWorkerWG.Add(terminalWorkerCount)for range terminalWorkerCount {go o.sendTerminalReplies(ctx)@@ -269,6 +345,52 @@ func (o *Outbound) handleTaskMessage(e events.Event) {o.mu.Lock()st, exists := o.streams[target.streamKey]+ turn := replyTurn{}+ if exists {+ turn = st.turn+ }+ o.mu.Unlock()+ if !turn.id.Valid {+ resolved, err := o.turnFor(ctx, target.taskID)+ if err != nil {+ // Treating the task as its own turn here would open a second reply+ // beside the one a previous attempt is still holding.+ o.logger.WarnContext(ctx, "telegram outbound: skipping stream frame; reply turn unresolved", "error", err)+ return+ }+ turn = resolved+ }++ // Hold the turn for as long as this frame is talking to Telegram. A frame+ // that checked the state and then sent would still race the final answer+ // taking over mid-request — that gap is what put a second copy of the+ // reply in the chat (GH #8049, #7750).+ lease, status, acquireErr := o.acquireDelivery(ctx, target, turn, deliveryPhaseStreaming)+ if acquireErr != nil {+ o.logger.WarnContext(ctx, "telegram outbound: reply ownership unavailable; skipping stream frame", "error", acquireErr)+ return+ }+ if status == deliveryClosed {+ // The reply is finished — possibly by another replica, which cannot+ // reach into this process to tidy up. Release the local stream and its+ // chat-scheduler reference here, or they are held for good and the+ // schedule table eventually refuses new chats.+ o.clearStream(e)+ return+ }+ if status != deliveryAcquired {+ // Another path owns the turn right now. A stream frame is decoration —+ // the answer still lands — so it steps aside.+ return+ }+ defer o.releaseDelivery(ctx, lease)+ if o.inheritedSend(ctx, lease) {+ // A send this process did not make may or may not be in the chat.+ return+ }++ o.mu.Lock()+ st, exists = o.streams[target.streamKey]if !exists {schedule := o.retainChatLocked(target.botKey, target.chatID)if schedule == nil {@@ -277,20 +399,30 @@ func (o *Outbound) handleTaskMessage(e events.Event) {}st = &streamState{chatID: target.chatID, threadID: target.threadID, replyTo: target.replyTo,- schedule: schedule,+ turn: turn, schedule: schedule,}o.streams[target.streamKey] = st}+ st.lastFrameAt = o.now()+ // A reply this process did not start — the placeholder came from another+ // replica, or from the attempt this automatic retry inherited — still+ // edits that message instead of opening a second one. Its text is whatever+ // this process has seen; the final answer overwrites it either way.+ if msgID := lease.messageID(); msgID != 0 {+ st.messageID = msgID+ }st.accumulated += payload.Contentsnapshot := st.accumulatedmsgID := st.messageIDo.mu.Unlock()- o.pushPartial(ctx, target, st, msgID, snapshot)+ o.pushPartial(ctx, target, st, lease, msgID, snapshot)}-// pushPartial sends the placeholder on the first flush and edits it after.-func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *streamState, msgID int64, snapshot string) {+// pushPartial sends the placeholder on the first flush and edits it after. It+// runs under the turn's lease, so the final answer cannot take the reply over+// between the decision made here and the call that acts on it.+func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *streamState, lease *deliveryLease, msgID int64, snapshot string) {if !st.schedule.mu.TryLock() {return}@@ -307,63 +439,67 @@ func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *str// reply is delivered in chunks by the final EventChatDone send.text = chunkMessage(text, maxMessageUnits)[0]}- // o.streams is the single owner registry for a task's reply. The caller- // released o.mu before this point and terminal delivery consumes the- // stream under that same lock, so a chat:done may have taken ownership in- // the meantime — sending on a stream this partial no longer owns is what- // puts a second copy of the reply in the chat (GH #8049).- //- // Still the owner: re-read the id under the lock that guards it (the- // caller's snapshot predates this send being serialized behind- // schedule.mu) and publish a first send while it is in flight, so terminal- // delivery can tell "no placeholder yet" from "placeholder sent, id still- // in the air" and wait for the id instead of posting its own copy.o.mu.Lock()if o.streams[target.streamKey] != st {o.mu.Unlock()return}msgID = st.messageID- st.sending = msgID == 0o.mu.Unlock()- if msgID == 0 {- defer func() {- o.mu.Lock()- st.sending = false- o.mu.Unlock()- }()- var reply *replyParameters- if st.replyTo != 0 {- reply = &replyParameters{MessageID: st.replyTo, AllowSendingWithoutReply: true}++ if msgID != 0 {+ // Re-prove the turn immediately before the edit. Acquiring it and then+ // stalling — a slow query, a descheduled goroutine — can outlive the+ // lease, and an edit made afterwards overwrites whatever the process+ // that took over has already published as the final answer.+ if !o.renewDelivery(ctx, lease) {+ return}- m, err := api.SendMessage(ctx, sendMessageParams{- ChatID: st.chatID,- Text: firstNonEmpty(formatHTML(text), streamPlaceholder),- ParseMode: "HTML",- MessageThreadID: st.threadID,- ReplyParameters: reply,+ ctx, cancel := o.callContext(ctx)+ defer cancel()+ err := api.EditMessageText(ctx, editMessageTextParams{+ ChatID: st.chatID,+ MessageID: msgID,+ Text: formatHTML(text),+ ParseMode: "HTML",})- if err != nil {+ if err != nil && !isNotModified(err) {o.noteEditFailure(st.schedule, err)return}st.schedule.lastEdit = o.now()- o.mu.Lock()- st.messageID = m.MessageID- o.mu.Unlock()return}- err := api.EditMessageText(ctx, editMessageTextParams{- ChatID: st.chatID,- MessageID: msgID,- Text: formatHTML(text),- ParseMode: "HTML",++ // Exactly one placeholder per turn, published before the call goes out so+ // that any other process reads "a send is outstanding" rather than+ // "nothing has been sent".+ if !o.claimSend(ctx, lease) {+ return+ }+ ctx, cancel := o.callContext(ctx)+ defer cancel()+ var reply *replyParameters+ if st.replyTo != 0 {+ reply = &replyParameters{MessageID: st.replyTo, AllowSendingWithoutReply: true}+ }+ m, err := api.SendMessage(ctx, sendMessageParams{+ ChatID: st.chatID,+ Text: firstNonEmpty(formatHTML(text), streamPlaceholder),+ ParseMode: "HTML",+ MessageThreadID: st.threadID,+ ReplyParameters: reply,})- if err != nil && !isNotModified(err) {- o.noteEditFailure(st.schedule, err)+ if o.recordSend(ctx, lease, true, m.MessageID, 0, err) != deliveryAccepted {+ if err != nil {+ o.noteEditFailure(st.schedule, err)+ }return}st.schedule.lastEdit = o.now()+ o.mu.Lock()+ st.messageID = m.MessageID+ o.mu.Unlock()}// noteEditFailure applies the 429-mandated backoff to the stream; other@@ -381,6 +517,23 @@ func (o *Outbound) noteEditFailure(schedule *chatSchedule, err error) {// doing Telegram I/O here would stall SubscribeAll realtime fanout behind// retry_after waits and slow network requests.func (o *Outbound) enqueueTerminalReply(e events.Event) {+ // An empty completion still closes the reply: a text frame arriving after+ // it must not reopen a stream nobody is going to finish. Local state goes+ // now — it costs nothing and frees the chat's scheduler slot — while the+ // close itself is a database write and belongs on a worker, not on the+ // synchronous bus.+ if settleOnly := chatDoneContent(e.Payload) == ""; settleOnly {+ o.clearStream(e)+ o.enqueueTerminal(e, terminalKindClose, "empty_reply")+ return+ }+ o.enqueueTerminal(e, terminalKindAnswer, "")+}++// enqueueTerminal appends to a bounded keyed FIFO. events.Bus is synchronous,+// so nothing here may touch Telegram or the database — that work belongs to+// the terminal workers.+func (o *Outbound) enqueueTerminal(e events.Event, kind terminalKind, settleReason string) {_, hasTaskID := eventTaskID(e)sessionID, sessionErr := util.ParseUUID(e.ChatSessionID)if !hasTaskID || sessionErr != nil || !sessionID.Valid {@@ -389,13 +542,8 @@ func (o *Outbound) enqueueTerminalReply(e events.Event) {o.clearStream(e)return}- content := chatDoneContent(e.Payload)- if content == "" {- o.clearStream(e)- return- }sessionKey := e.ChatSessionID- replyBytes := len(content)+ replyBytes := len(chatDoneContent(e.Payload))o.terminalMu.Lock()if o.terminalStopped {o.terminalMu.Unlock()@@ -425,7 +573,9 @@ func (o *Outbound) enqueueTerminalReply(e events.Event) {"queued_bytes", bytes, "reply_bytes", replyBytes, "queued_bytes_limit", maxQueuedTerminalReplyBytes)return}- session.queue = append(session.queue, &terminalReply{event: e, byteSize: replyBytes})+ session.queue = append(session.queue, &terminalReply{+ event: e, byteSize: replyBytes, kind: kind, settleReason: settleReason,+ })o.queuedTerminalReplyCount++o.queuedTerminalReplyBytes += replyBytesif !session.running && !session.ready && !session.retryWaiting {@@ -596,65 +746,22 @@ type terminalRequestResult struct {// fixed worker available for another session.func (o *Outbound) sendNextTerminalRequest(ctx context.Context, reply *terminalReply) terminalRequestResult {if !reply.initialized {- if reply.target == nil {- // Cached for the placeholder-settle retry only: that wait is- // bounded by the partial's own send context, and re-resolving it- // every 250ms costs two queries plus a credential decrypt. The- // capacity retry below drops the cache again, because that wait is- // unbounded and re-resolving is what re-checks the installation's- // status and picks up a rotated bot token.- target, err := o.resolveTarget(ctx, reply.event, false)- if err != nil {- return terminalRequestResult{done: true, err: err}- }- if target == nil {- return terminalRequestResult{done: true}- }- reply.target = target- }- target := reply.target-- o.mu.Lock()- st := o.streams[target.streamKey]- var schedule *chatSchedule- if st != nil {- if st.sending {- // The placeholder is mid-sendMessage: Telegram has it, but its- // id arrives only when the call returns. Reading 0 here would- // skip the edit path below and post the whole reply a second- // time while the placeholder stayed in the chat — the- // duplicate in GH #8049. Retry instead of blocking: the wait- // spans one Telegram round trip and the worker stays free for- // another session.- o.mu.Unlock()- return terminalRequestResult{retryAt: o.now().Add(placeholderSettleRetry)}- }- schedule = st.schedule- reply.streamedMessageID = st.messageID- } else {- schedule = o.retainChatLocked(target.botKey, target.chatID)- if schedule == nil {- o.mu.Unlock()- // Re-resolve on the next attempt: an installation revoked (or- // re-keyed) while this reply waited for capacity must not be- // delivered to from a target resolved before the change.- reply.target = nil- return terminalRequestResult{retryAt: o.now().Add(chatCapacityRetry)}- }- }- delete(o.streams, target.streamKey)- o.mu.Unlock()+ return o.initializeTerminalReply(ctx, reply)+ }- reply.initialized = true- reply.schedule = schedule- reply.chunks = chunkMessage(chatDoneContent(reply.event.Payload), maxMessageUnits)- if len(reply.chunks) == 0 {- return terminalRequestResult{done: true}- }- return terminalRequestResult{retryAt: o.now()}+ // Re-prove ownership before every call. A turn is held across several+ // scheduler rounds — edit pacing, a 429 backoff — and a lease taken+ // minutes ago is not evidence that this process still owns the reply.+ if !o.renewDelivery(ctx, reply.lease) {+ o.logger.WarnContext(ctx, "telegram outbound: lost the reply to another process mid-delivery",+ "turn_id", uuidText(reply.turn.id))+ return terminalRequestResult{done: true}}schedule := reply.schedule+ if reply.kind == terminalKindNotice {+ return o.deliverFailureNotice(ctx, reply)+ }schedule.mu.Lock()defer schedule.mu.Unlock()now := o.now()@@ -662,33 +769,228 @@ func (o *Outbound) sendNextTerminalRequest(ctx context.Context, reply *terminalRif available.After(now) {return terminalRequestResult{retryAt: available}}+ // Re-prove the turn here, not only at the top: waiting for schedule.mu can+ // take arbitrarily long, and the call below must be authorised by a lease+ // that is still ours at the moment it goes out.+ if !o.renewDelivery(ctx, reply.lease) {+ return terminalRequestResult{done: true}+ }+ ctx, cancel := o.callContext(ctx)+ defer cancel()api := newBotAPI(o.apiBase, reply.target.botToken, o.client)if reply.streamedMessageID != 0 && !reply.placeholderEdited && !reply.fallbackFreshSend {- err := api.EditMessageText(ctx, editMessageTextParams{- ChatID: reply.target.chatID, MessageID: reply.streamedMessageID,- Text: formatHTML(reply.chunks[0]), ParseMode: "HTML",- })- if retry, ok := retryAfter(err); ok {- retryAt := o.now().Add(retry)- schedule.setBackoffTill(retryAt)+ return o.editStreamedReply(ctx, api, reply, schedule)+ }+ return o.sendReplyChunk(ctx, api, reply, schedule)+}++// initializeTerminalReply resolves the destination, takes the turn, and works+// out what is left to deliver.+func (o *Outbound) initializeTerminalReply(ctx context.Context, reply *terminalReply) terminalRequestResult {+ if reply.target == nil {+ target, err := o.resolveTarget(ctx, reply.event, false)+ if err != nil {+ return terminalRequestResult{done: true, err: err}+ }+ if target == nil {+ return terminalRequestResult{done: true}+ }+ reply.target = target+ }+ target := reply.target+ if !reply.turnResolved {+ turn, err := o.turnFor(ctx, target.taskID)+ if err != nil {+ if retryAt, ok := o.retryDeliveryAcquire(reply, maxDeliveryClaimErrorAttempts); ok {+ return terminalRequestResult{retryAt: retryAt}+ }+ // Delivering under a guessed turn would answer beside the reply a+ // previous attempt is holding, so this stops instead.+ return terminalRequestResult{done: true, err: err}+ }+ reply.turn = turn+ reply.turnResolved = true+ }++ if reply.kind == terminalKindClose {+ // Nothing to deliver — a cancelled run, or a completion with no answer.+ // The close still has to land: it is what stops a text frame arriving+ // afterwards from opening a placeholder nothing will ever finish.+ closed, err := o.closeTurn(ctx, target, reply.turn, reply.settleReason)+ if err != nil || !closed {+ budget := maxDeliveryAcquireAttempts+ if err != nil {+ budget = maxDeliveryClaimErrorAttempts+ }+ if retryAt, ok := o.retryDeliveryAcquire(reply, budget); ok {+ return terminalRequestResult{retryAt: retryAt}+ }+ o.logger.ErrorContext(ctx, "telegram outbound: could not close the turn; a late frame may reopen it",+ "turn_id", uuidText(reply.turn.id), "reason", reply.settleReason, "error", err)+ return terminalRequestResult{done: true}+ }+ o.clearStream(reply.event)+ return terminalRequestResult{done: true}+ }++ lease, status, err := o.acquireDelivery(ctx, target, reply.turn, deliveryPhaseTerminal)+ switch {+ case err != nil:+ if retryAt, ok := o.retryDeliveryAcquire(reply, maxDeliveryClaimErrorAttempts); ok {return terminalRequestResult{retryAt: retryAt}}- if err != nil && !isNotModified(err) {- reply.fallbackFreshSend = true- reply.chunkIndex = 0- return terminalRequestResult{retryAt: o.now()}+ // Never deliver a reply this process does not own: an unowned send is+ // the duplicate this whole mechanism exists to remove. The run's+ // outcome is still in Multica, and the row shows nothing was sent.+ return terminalRequestResult{done: true, err: fmt.Errorf("claim telegram reply delivery: %w", err)}+ case status == deliveryClosed:+ // Already delivered and settled — a second completion event for this+ // turn, or a replay of one.+ o.clearStream(reply.event)+ return terminalRequestResult{done: true}+ case status == deliveryBusy:+ if retryAt, ok := o.retryDeliveryAcquire(reply, maxDeliveryAcquireAttempts); ok {+ return terminalRequestResult{retryAt: retryAt}}- reply.placeholderEdited = true- reply.chunkIndex = 1- schedule.lastEdit = o.now()- schedule.setBackoffTill(time.Time{})+ return terminalRequestResult{done: true, err: errors.New("telegram reply stayed owned by another delivery")}+ }+ reply.lease = lease++ if o.inheritedSend(ctx, lease) {+ // A send nobody can account for. Telegram offers no idempotency key,+ // so re-sending may duplicate and not re-sending may truncate; the row+ // keeps which one happened here.+ o.settleDelivery(ctx, lease, "send_result_unknown")+ o.clearStream(reply.event)+ return terminalRequestResult{done: true}+ }++ o.mu.Lock()+ st := o.streams[target.streamKey]+ var schedule *chatSchedule+ if st != nil {+ schedule = st.schedule+ } else {+ schedule = o.retainChatLocked(target.botKey, target.chatID)+ if schedule == nil {+ o.mu.Unlock()+ // Hand the turn back before waiting: holding a lease through an+ // unbounded capacity wait would block every other path on it, and+ // this reply's own next attempt as well. Re-resolve too, so an+ // installation revoked during the wait stops the delivery.+ o.releaseDelivery(ctx, lease)+ reply.lease = nil+ reply.target = nil+ return terminalRequestResult{retryAt: o.now().Add(chatCapacityRetry)}+ }+ }+ delete(o.streams, target.streamKey)+ o.mu.Unlock()++ reply.initialized = true+ reply.schedule = schedule+ reply.streamedMessageID = lease.messageID()+ if reply.kind == terminalKindNotice {+ return terminalRequestResult{retryAt: o.now()}+ }+ reply.chunks = chunkMessage(chatDoneContent(reply.event.Payload), maxMessageUnits)+ if len(reply.chunks) == 0 {+ o.settleDelivery(ctx, lease, "empty_reply")+ return terminalRequestResult{done: true}+ }+ // Resume after the last part that landed. A placeholder is not a part: it+ // gives the turn something to edit and delivers none of the final answer.+ if sent := lease.chunksSent(); sent > 0 {+ reply.placeholderEdited = reply.streamedMessageID != 0+ reply.chunkIndex = min(sent, len(reply.chunks))if reply.chunkIndex == len(reply.chunks) {+ o.settleDelivery(ctx, lease, "delivered")+ return terminalRequestResult{done: true}+ }+ }+ return terminalRequestResult{retryAt: o.now()}+}++// retryDeliveryAcquire spaces attempts on a turn this process could not take,+// and gives up rather than holding the session's queue forever. Waiting out a+// live owner is worth a lease's length; a failing ownership write is not, so+// the two have different budgets.+func (o *Outbound) retryDeliveryAcquire(reply *terminalReply, budget int) (time.Time, bool) {+ reply.acquireAttempts+++ if reply.acquireAttempts >= budget {+ return time.Time{}, false+ }+ return o.now().Add(deliveryBusyRetry), true+}++// editStreamedReply turns the placeholder into the final answer's first part.+// Every branch keeps operating on that message: posting the answer again+// beside one that may well have been edited is the duplicate (GH #8049).+func (o *Outbound) editStreamedReply(ctx context.Context, api *botAPI, reply *terminalReply, schedule *chatSchedule) terminalRequestResult {+ params := editMessageTextParams{+ ChatID: reply.target.chatID, MessageID: reply.streamedMessageID,+ Text: formatHTML(reply.chunks[0]), ParseMode: "HTML",+ }+ if reply.plainTextEdit {+ params.Text = reply.chunks[0]+ params.ParseMode = ""+ }+ err := api.EditMessageText(ctx, params)+ if retry, ok := retryAfter(err); ok {+ retryAt := o.now().Add(retry)+ schedule.setBackoffTill(retryAt)+ return terminalRequestResult{retryAt: retryAt}+ }+ switch {+ case err == nil || isNotModified(err):+ case isHTMLParseError(err) && !reply.plainTextEdit:+ // Telegram refused the markup, not the message: same target, plain.+ reply.plainTextEdit = true+ return terminalRequestResult{retryAt: o.now()}+ case isEditTargetMissing(err):+ // Confirmed gone — the only case where a fresh message is not a second+ // copy of one the user can already see.+ reply.fallbackFreshSend = true+ reply.chunkIndex = 0+ return terminalRequestResult{retryAt: o.now()}+ case isPermanentEditRejection(err):+ // Telegram will keep refusing. Stop rather than re-send or spin: the+ // queue is per session, and a reply that never settles blocks every+ // later answer in the same chat.+ o.logger.WarnContext(ctx, "telegram outbound: final edit permanently rejected; reply left as streamed",+ "turn_id", uuidText(reply.turn.id), "error", err)+ o.settleDelivery(ctx, reply.lease, "edit_rejected")+ return terminalRequestResult{done: true}+ default:+ // Ambiguous: the edit may have applied. Retry the same message on a+ // budget, then give up for the same reason as above.+ reply.editAttempts+++ if reply.editAttempts >= maxAmbiguousEditAttempts {+ o.logger.WarnContext(ctx, "telegram outbound: final edit kept failing; reply left as streamed",+ "turn_id", uuidText(reply.turn.id), "error", err)+ o.settleDelivery(ctx, reply.lease, "edit_failed")return terminalRequestResult{done: true}}- return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}+ return terminalRequestResult{retryAt: o.now().Add(terminalEditRetryDelay)}+ }+ reply.placeholderEdited = true+ reply.chunkIndex = 1+ schedule.lastEdit = o.now()+ schedule.setBackoffTill(time.Time{})+ o.recordSend(ctx, reply.lease, false, reply.streamedMessageID, reply.chunkIndex, nil)+ if reply.chunkIndex == len(reply.chunks) {+ o.settleDelivery(ctx, reply.lease, "delivered")+ return terminalRequestResult{done: true}}+ return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}+}+// sendReplyChunk posts one part of the final answer. The send is published+// before it is made and its outcome recorded after, so a delivery resumed in+// another process continues after this part rather than repeating it — and a+// part whose result was lost stops delivery instead of being sent twice.+func (o *Outbound) sendReplyChunk(ctx context.Context, api *botAPI, reply *terminalReply, schedule *chatSchedule) terminalRequestResult {chunk := reply.chunks[reply.chunkIndex]params := sendMessageParams{ChatID: reply.target.chatID, Text: formatHTML(chunk), ParseMode: "HTML",@@ -701,7 +1003,19 @@ func (o *Outbound) sendNextTerminalRequest(ctx context.Context, reply *terminalRparams.Text = chunkparams.ParseMode = ""}- _, err := api.SendMessage(ctx, params)+ if !o.claimSend(ctx, reply.lease) {+ // Either the turn moved on, or an earlier send is still unaccounted+ // for. Neither is a reason to put another message in the chat.+ return terminalRequestResult{done: true}+ }+ sent, err := api.SendMessage(ctx, params)+ if o.recordSend(ctx, reply.lease, false, sent.MessageID, reply.chunkIndex+1, err) == deliveryUnknown {+ // Report it rather than ending quietly: nobody can tell from the chat+ // whether this part arrived, so the failure has to be visible to the+ // operator as well as recorded on the row.+ o.settleDelivery(ctx, reply.lease, "send_result_unknown")+ return terminalRequestResult{done: true, err: fmt.Errorf("send final chunk: outcome unknown: %w", err)}+ }if retry, ok := retryAfter(err); ok {retryAt := o.now().Add(retry)schedule.setBackoffTill(retryAt)@@ -712,6 +1026,7 @@ func (o *Outbound) sendNextTerminalRequest(ctx context.Context, reply *terminalRreturn terminalRequestResult{retryAt: o.now()}}if err != nil {+ o.settleDelivery(ctx, reply.lease, "send_failed")return terminalRequestResult{done: true, err: fmt.Errorf("send final chunk: %w", err)}}reply.chunkIndex++@@ -719,6 +1034,7 @@ func (o *Outbound) sendNextTerminalRequest(ctx context.Context, reply *terminalRschedule.lastEdit = o.now()schedule.setBackoffTill(time.Time{})if reply.chunkIndex == len(reply.chunks) {+ o.settleDelivery(ctx, reply.lease, "delivered")return terminalRequestResult{done: true}}return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}@@ -726,6 +1042,11 @@ func (o *Outbound) sendNextTerminalRequest(ctx context.Context, reply *terminalRfunc (o *Outbound) cleanupTerminalReply(reply *terminalReply) {reply.cleanupOnce.Do(func() {+ if reply.lease != nil {+ // Settling already cleared the lease; this covers every path that+ // ended without settling, so the turn is not held until it expires.+ o.releaseDelivery(context.Background(), reply.lease)+ }if reply.initialized && reply.schedule != nil {o.releaseChat(reply.schedule, reply.target.chatID)return@@ -734,63 +1055,128 @@ func (o *Outbound) cleanupTerminalReply(reply *terminalReply) {})}-// handleTaskFailed clears any stream state and posts a failure notice.+// handleTaskFailed hands the run-failed notice to the terminal queue, which+// owns the turn's lease and its retries. Posting it inline meant a notice was+// simply dropped whenever another path — a text frame still talking to+// Telegram, often on another replica — held the turn at that instant, leaving+// the placeholder as the last thing the user ever saw.func (o *Outbound) handleTaskFailed(e events.Event) {if taskFailureRetryPending(e.Payload) {+ // The platform runs this turn again under a new task id. Nothing to+ // close and nothing to say: the turn keeps its placeholder, and the+ // retry resolves to the same turn and finishes it rather than posting+ // its answer beside an abandoned one.o.clearStream(e)return}- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ o.enqueueTerminal(e, terminalKindNotice, "failure_notice")+}++// deliverFailureNotice posts the run-failed notice, one Telegram call per+// step. Deliberately the same shape as the answer's delivery: make at most one+// request, hand back a retryAt, and let the next step re-prove the lease+// first. Looping inside a step — retrying an edit, or waiting out a+// retry_after — means the call after the wait can land well past the lease, on+// a turn another replica has since taken over and possibly finished.+func (o *Outbound) deliverFailureNotice(ctx context.Context, reply *terminalReply) terminalRequestResult {+ lease := reply.lease+ target := reply.target+ if o.inheritedSend(ctx, lease) {+ // A send nobody can account for: the user may already be looking at a+ // message about this turn.+ o.settleDelivery(ctx, lease, "send_result_unknown")+ return terminalRequestResult{done: true}+ }++ schedule := reply.schedule+ schedule.mu.Lock()+ defer schedule.mu.Unlock()+ now := o.now()+ if available := o.terminalAvailableAt(schedule, target.botKey, now); available.After(now) {+ return terminalRequestResult{retryAt: available}+ }+ if !o.renewDelivery(ctx, lease) {+ return terminalRequestResult{done: true}+ }+ ctx, cancel := o.callContext(ctx)defer cancel()- target, err := o.resolveTarget(ctx, e, false)- if err != nil || target == nil {- return+ api := newBotAPI(o.apiBase, target.botToken, o.client)++ if messageID := lease.messageID(); messageID != 0 && !reply.fallbackFreshSend {+ return o.editNoticeOntoPlaceholder(ctx, api, reply, schedule, messageID)}- o.mu.Lock()- st := o.streams[target.streamKey]- delete(o.streams, target.streamKey)- var schedule *chatSchedule- if st != nil {- schedule = st.schedule- } else {- schedule = o.retainChatLocked(target.botKey, target.chatID)+ if !o.claimSend(ctx, lease) {+ return terminalRequestResult{done: true}}- o.mu.Unlock()- if schedule == nil {- o.logger.WarnContext(ctx, "telegram outbound: failure notice skipped; chat scheduler is saturated")- return+ sent, sendErr := api.SendMessage(ctx, sendMessageParams{+ ChatID: target.chatID, Text: taskFailedText, MessageThreadID: target.threadID,+ ReplyParameters: optionalReplyParameters(target.replyTo),+ })+ if o.recordSend(ctx, lease, true, sent.MessageID, 0, sendErr) == deliveryUnknown {+ o.settleDelivery(ctx, lease, "send_result_unknown")+ return terminalRequestResult{done: true, err: fmt.Errorf("failure notice: outcome unknown: %w", sendErr)}}- defer o.releaseChat(schedule, target.chatID)- schedule.mu.Lock()- defer schedule.mu.Unlock()+ if retry, ok := retryAfter(sendErr); ok {+ retryAt := o.now().Add(retry)+ schedule.setBackoffTill(retryAt)+ return terminalRequestResult{retryAt: retryAt}+ }+ schedule.lastEdit = o.now()+ schedule.setBackoffTill(time.Time{})+ o.settleDelivery(ctx, lease, "failure_notice")+ if sendErr != nil {+ return terminalRequestResult{done: true, err: fmt.Errorf("failure notice: %w", sendErr)}+ }+ return terminalRequestResult{done: true}+}- api := newBotAPI(o.apiBase, target.botToken, o.client)- if st != nil && st.messageID != 0 {- if err := o.runScheduled(ctx, schedule, func() error {- return api.EditMessageText(ctx, editMessageTextParams{- ChatID: st.chatID, MessageID: st.messageID, Text: taskFailedText,- })- }); err == nil || isNotModified(err) {- return- }+// editNoticeOntoPlaceholder turns the streamed placeholder into the notice,+// with the same failure classification the final answer uses: only a target+// Telegram confirms is gone justifies posting a second message.+func (o *Outbound) editNoticeOntoPlaceholder(ctx context.Context, api *botAPI, reply *terminalReply, schedule *chatSchedule, messageID int64) terminalRequestResult {+ err := api.EditMessageText(ctx, editMessageTextParams{+ ChatID: reply.target.chatID, MessageID: messageID, Text: taskFailedText,+ })+ if retry, ok := retryAfter(err); ok {+ retryAt := o.now().Add(retry)+ schedule.setBackoffTill(retryAt)+ return terminalRequestResult{retryAt: retryAt}}- if err := o.runScheduled(ctx, schedule, func() error {- _, err := api.SendMessage(ctx, sendMessageParams{- ChatID: target.chatID, Text: taskFailedText, MessageThreadID: target.threadID,- ReplyParameters: optionalReplyParameters(target.replyTo),- })- return err- }); err != nil {- o.logger.WarnContext(ctx, "telegram outbound: failure notice failed", "error", err)+ switch {+ case err == nil || isNotModified(err):+ schedule.lastEdit = o.now()+ schedule.setBackoffTill(time.Time{})+ o.settleDelivery(ctx, reply.lease, "failure_notice")+ return terminalRequestResult{done: true}+ case isEditTargetMissing(err):+ reply.fallbackFreshSend = true+ return terminalRequestResult{retryAt: o.now()}+ case isPermanentEditRejection(err):+ // Keep the placeholder rather than duplicating the turn: the run's+ // outcome is still visible in Multica.+ o.logger.WarnContext(ctx, "telegram outbound: failure notice edit permanently rejected",+ "turn_id", uuidText(reply.turn.id), "error", err)+ o.settleDelivery(ctx, reply.lease, "edit_rejected")+ return terminalRequestResult{done: true}+ default:+ reply.editAttempts+++ if reply.editAttempts >= maxNoticeEditAttempts {+ o.logger.WarnContext(ctx, "telegram outbound: failure notice edit kept failing",+ "turn_id", uuidText(reply.turn.id), "error", err)+ o.settleDelivery(ctx, reply.lease, "edit_failed")+ return terminalRequestResult{done: true}+ }+ return terminalRequestResult{retryAt: o.now().Add(terminalEditRetryDelay)}}}-// handleTaskCancelled drops local stream state without changing the partial-// Telegram message already visible to the user. Cancellation has no final-// agent answer; retaining the partial avoids replacing user-visible content-// with a synthetic notice while ensuring no task state remains resident.+// handleTaskCancelled leaves the partial Telegram message the user can already+// see — cancellation has no final answer, and replacing visible content with a+// synthetic notice is worse than keeping it — but closes the reply so a text+// frame still in flight cannot open a second message beside it.func (o *Outbound) handleTaskCancelled(e events.Event) {o.clearStream(e)+ o.enqueueTerminal(e, terminalKindClose, "cancelled")}func taskFailureRetryPending(payload any) bool {@@ -856,6 +1242,69 @@ func (o *Outbound) releaseChatLocked(schedule *chatSchedule, chatID int64) {}}+// sweepSettledStreams releases local state for turns that are over, and only+// for those. A stream is a candidate once it has been quiet for a while, but+// what releases it is the delivery row saying the turn is settled or that a+// later attempt has taken it over — never the quiet itself, which is normal+// for a run that is busy rather than finished.+func (o *Outbound) sweepSettledStreams(ctx context.Context) {+ type candidate struct {+ key string+ stream *streamState+ turn replyTurn+ seenAt time.Time+ }+ now := o.now()+ var candidates []candidate+ o.mu.Lock()+ for key, st := range o.streams {+ if !st.turn.id.Valid || st.lastFrameAt.IsZero() || now.Sub(st.lastFrameAt) < streamSweepGrace {+ continue+ }+ candidates = append(candidates, candidate{key: key, stream: st, turn: st.turn, seenAt: st.lastFrameAt})+ }+ o.mu.Unlock()++ for _, c := range candidates {+ row, err := o.q.GetChannelReplyDelivery(ctx, c.turn.id)+ if err != nil {+ // No row, or the lookup failed: no evidence the turn is over, so+ // the stream stays. Reclaiming on a failed read would take a live+ // reply away from a run that is still producing text.+ continue+ }+ superseded := row.AttemptDepth > c.turn.depth+ if row.Phase != deliveryPhaseSettled && !superseded {+ continue+ }+ o.mu.Lock()+ // Re-check under the lock: a frame may have arrived while we were+ // asking, which both revives the stream and makes the answer stale.+ if current, ok := o.streams[c.key]; ok && current == c.stream && current.lastFrameAt.Equal(c.seenAt) {+ delete(o.streams, c.key)+ o.releaseChatLocked(current.schedule, current.chatID)+ o.logger.Info("telegram outbound: released local state for a turn that ended elsewhere",+ "task_id", c.key, "settled_reason", row.SettledReason, "superseded", superseded)+ }+ o.mu.Unlock()+ }+}++// runStreamSweeper reclaims local state for turns finished by another replica.+func (o *Outbound) runStreamSweeper(ctx context.Context) {+ defer o.workerWG.Done()+ ticker := time.NewTicker(streamSweepInterval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ o.sweepSettledStreams(ctx)+ }+ }+}+func (o *Outbound) pruneIdleChatsLocked(now time.Time) {o.pruneBotFallbacksLocked(now)for key, schedule := range o.chats {@@ -1021,6 +1470,12 @@ type replyTarget struct {threadID int64replyTo int64botToken string++ // Identity of the reply this target belongs to, for the ownership row.+ taskID pgtype.UUID+ bindingID pgtype.UUID+ installationID pgtype.UUID+ channelChatID string}// resolveTarget maps an event's immutable task delivery snapshot to Telegram@@ -1059,12 +1514,16 @@ func (o *Outbound) resolveTarget(ctx context.Context, e events.Event, _ bool) (*}chatID, threadID, replyTo := outboundTarget(binding)return &replyTarget{- streamKey: util.UUIDToString(taskID),- botKey: util.UUIDToString(inst.ID),- chatID: chatID,- threadID: threadID,- replyTo: replyTo,- botToken: creds.BotToken,+ streamKey: util.UUIDToString(taskID),+ botKey: util.UUIDToString(inst.ID),+ chatID: chatID,+ threadID: threadID,+ replyTo: replyTo,+ botToken: creds.BotToken,+ taskID: taskID,+ bindingID: delivery.BindingID,+ installationID: inst.ID,+ channelChatID: delivery.ChannelChatID,}, nil}@@ -1135,6 +1594,31 @@ func chatDoneContent(payload any) string {// isNotModified reports Telegram's "message is not modified" edit error, which// is benign (identical snapshot).+// isEditTargetMissing is Telegram confirming the message is gone. It is the+// only edit failure that justifies posting a fresh message: every other one+// may leave the original in the chat, and posting beside it is the duplicate.+func isEditTargetMissing(err error) bool {+ var ae *apiError+ return errors.As(err, &ae) && ae.Code == http.StatusBadRequest &&+ containsFold(ae.Description, "message to edit not found")+}++// isPermanentEditRejection reports a rejection that retrying cannot fix — the+// bot was blocked, lost its rights, or the message is no longer editable.+// Callers must have ruled out the recoverable 400s (markup, missing target)+// first, since those share the status code.+func isPermanentEditRejection(err error) bool {+ var ae *apiError+ if !errors.As(err, &ae) {+ return false+ }+ switch ae.Code {+ case http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:+ return true+ }+ return false+}+func isNotModified(err error) bool {var ae *apiErrorreturn errors.As(err, &ae) && ae.Code == http.StatusBadRequest &&diff --git a/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go b/server/internal/integrations/telegram/outbound_delivery_boundaries_test.gonew file mode 100644index 0000000000..3ef240ddd2--- /dev/null+++ b/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go@@ -0,0 +1,675 @@+package telegram++import (+ "context"+ "crypto/rand"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Boundary cases for reply delivery: concurrency, lost responses, retries and+// takeover, each one a way a reply could still arrive twice, be overwritten,+// or block the session behind it.+//+// These came out of the review of the first attempt at this fix, which passed+// its own suite while the final answer never reached Telegram — the in-memory+// stand-in for the ownership table disagreed with the SQL. So routing is the+// only thing faked here: every ownership operation runs the real generated+// query against the test database.+type review8545Queries struct {+ *db.Queries+ routing *fakeTelegramOutboundQueries+}++func (q *review8545Queries) GetChannelTaskDelivery(ctx context.Context, id pgtype.UUID) (db.ChannelTaskDelivery, error) {+ return q.routing.GetChannelTaskDelivery(ctx, id)+}++func (q *review8545Queries) GetChannelInstallation(ctx context.Context, p db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ return q.routing.GetChannelInstallation(ctx, p)+}++func review8545ID() pgtype.UUID {+ id := pgtype.UUID{Valid: true}+ _, _ = rand.Read(id.Bytes[:])+ return id+}++func review8545Setup(t *testing.T, bot *auditBot) (*Outbound, *review8545Queries, *auditClock, events.Event) {+ t.Helper()+ o, routing, c, _ := auditSetup(t, bot)+ pool := testPool+ routing.binding.ID = review8545ID()+ routing.binding.InstallationID = review8545ID()+ routing.installation.ID = routing.binding.InstallationID+ q := &review8545Queries{Queries: db.New(pool), routing: routing}+ o.q = q+ testutil.New(pool, "", "").Cleanup(t, "DELETE FROM channel_reply_delivery WHERE installation_id = $1", routing.installation.ID)+ e := telegramTestEvent()+ e.TaskID = util.UUIDToString(review8545ID())+ e.Payload = protocol.ChatDonePayload{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID, Content: "complete final answer"}+ return o, q, c, e+}++func review8545Second(o *Outbound) *Outbound {+ b := NewOutbound(o.q, nil, o.apiBase, o.client, nil)+ b.now, b.wait = o.now, o.wait+ return b+}++func review8545MessageCount(t *testing.T, bot *auditBot, want int) {+ t.Helper()+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if len(bot.messages) != want {+ t.Fatalf("visible messages=%d want=%d methods=%v content=%v", len(bot.messages), want, bot.methods, bot.messages)+ }+}++func TestReview8545PostgresFinalTextReplacesPartial(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "short prefix"))+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if got := bot.messages[1]; got != chatDoneContent(e.Payload) {+ t.Fatalf("Telegram kept %q, want final %q; methods=%v", got, chatDoneContent(e.Payload), bot.methods)+ }+}++func TestReview8545PostgresTerminalClaimIsExclusive(t *testing.T) {+ bot := &auditBot{}+ a, _, c, e := review8545Setup(t, bot)+ b := review8545Second(a)+ ra, rb := &terminalReply{event: e}, &terminalReply{event: e}+ for _, pair := range []struct {+ o *Outbound+ r *terminalReply+ }{{a, ra}, {b, rb}} {+ result := pair.o.sendNextTerminalRequest(context.Background(), pair.r)+ if result.err != nil {+ t.Fatal(result.err)+ }+ }+ for _, pair := range []struct {+ o *Outbound+ r *terminalReply+ }{{a, ra}, {b, rb}} {+ for i := 0; i < 5; i++ {+ result := pair.o.sendNextTerminalRequest(context.Background(), pair.r)+ if result.done {+ break+ }+ if d := result.retryAt.Sub(c.now()); d > 0 {+ c.advance(d)+ }+ }+ }+ review8545MessageCount(t, bot, 1)+}++func TestReview8545PostgresUnknownTerminalSendIsNotReplayed(t *testing.T) {+ bot := &auditBot{loseFirstSendResponse: true}+ a, _, c, e := review8545Setup(t, bot)+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), a, e); err == nil {+ t.Fatal("lost response did not fail")+ }+ b := review8545Second(a)+ b.enqueueTerminalReply(e)+ auditDrain(t, b, c, e.ChatSessionID)+ review8545MessageCount(t, bot, 1)+}++func TestReview8545PostgresAbandonedInFlightDoesNotBlockForever(t *testing.T) {+ bot := &auditBot{}+ o, q, c, e := review8545Setup(t, bot)+ // Expiry is decided by database time, which the test clock cannot move, so+ // the lease is shortened and really waited out.+ o.leaseTTL = 100 * time.Millisecond+ ctx := context.Background()+ target, err := o.resolveTarget(ctx, e, false)+ if err != nil {+ t.Fatal(err)+ }+ turn, err := o.turnFor(ctx, target.taskID)+ if err != nil {+ t.Fatal(err)+ }+ lease, status, err := o.acquireDelivery(ctx, target, turn, deliveryPhaseStreaming)+ if err != nil || status != deliveryAcquired {+ t.Fatalf("delivery not acquired: status=%v err=%v", status, err)+ }+ if !o.claimSend(ctx, lease) {+ t.Fatal("send not claimed")+ }+ // The owner process dies after claiming: it never records an outcome and+ // never releases the turn. Only the lease expiring can free it.+ time.Sleep(150 * time.Millisecond)+ c.advance(24 * time.Hour)+ _ = q+ reply := &terminalReply{event: e}+ for i := 0; i < 25; i++ {+ result := o.sendNextTerminalRequest(context.Background(), reply)+ if result.done {+ return+ }+ if d := result.retryAt.Sub(c.now()); d > 0 {+ c.advance(d)+ }+ }+ t.Fatal("orphaned in_flight still waits after 24 hours and 25 attempts; later replies in the session remain blocked")+}++func TestReview8545PostgresCloseBeforeFirstFrame(t *testing.T) {+ for _, reason := range []string{"cancelled", "empty"} {+ t.Run(reason, func(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ if reason == "cancelled" {+ o.handleTaskCancelled(e)+ } else {+ empty := e+ empty.Payload = protocol.ChatDonePayload{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID}+ o.enqueueTerminalReply(empty)+ }+ auditDrain(t, o, c, e.ChatSessionID)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "late text after closed task"))+ review8545MessageCount(t, bot, 0)+ })+ }+}++func TestReview8545PostgresRetryDoesNotAdoptUnrelatedTurn(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first request"))+ o.handleTaskFailed(events.Event{TaskID: e.TaskID, Payload: map[string]any{"retry_pending": true}})+ c.advance(editInterval + time.Millisecond)+ // Different ordinary task on the same binding; no retry relationship.+ otherID := util.UUIDToString(review8545ID())+ o.handleTaskMessage(telegramPartialEvent(otherID, "unrelated second request"))+ review8545MessageCount(t, bot, 2)+}++func TestReview8545PostgresOldAttemptCannotReopenAfterAdoption(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first attempt"))+ o.handleTaskFailed(events.Event{TaskID: e.TaskID, Payload: map[string]any{"retry_pending": true}})+ c.advance(editInterval + time.Millisecond)+ retryTask := util.UUIDToString(review8545ID())+ seedRetryChain(t, e.TaskID, retryTask)+ o.handleTaskMessage(telegramPartialEvent(retryTask, "retry attempt"))+ c.advance(editInterval + time.Millisecond)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "late old attempt"))+ review8545MessageCount(t, bot, 1)+}++func TestReview8545PostgresRetryWithoutStreamKeepsExistingReply(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first attempt"))+ o.handleTaskFailed(events.Event{TaskID: e.TaskID, Payload: map[string]any{"retry_pending": true}})+ retryTask := util.UUIDToString(review8545ID())+ seedRetryChain(t, e.TaskID, retryTask)+ e.TaskID = retryTask+ e.Payload = protocol.ChatDonePayload{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID, Content: "retry complete answer"}+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ review8545MessageCount(t, bot, 1)+}++func TestReview8545PostgresFailureNoticeRespectsUnknownSend(t *testing.T) {+ bot := &auditBot{loseFirstSendResponse: true}+ a, _, c, e := review8545Setup(t, bot)+ a.handleTaskMessage(telegramPartialEvent(e.TaskID, "accepted before response loss"))+ b := review8545Second(a)+ b.handleTaskFailed(events.Event{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID,+ Payload: map[string]any{"retry_pending": false}})+ auditDrain(t, b, c, e.ChatSessionID)+ review8545MessageCount(t, bot, 1)+}++type review8545FailClaim struct{ *review8545Queries }++func (q *review8545FailClaim) AcquireChannelReplyDelivery(context.Context, db.AcquireChannelReplyDeliveryParams) (db.ChannelReplyDelivery, error) {+ return db.ChannelReplyDelivery{}, errors.New("injected ownership write failure")+}++func TestReview8545PostgresClaimFailureMustNotSendUnowned(t *testing.T) {+ bot := &auditBot{}+ o, q, c, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "original visible reply"))+ o.q = &review8545FailClaim{q}+ o.enqueueTerminalReply(e)++ // Delivery must end on a bounded budget and report the failure rather than+ // send without owning the reply, so this drives it directly: auditDrain+ // treats any reported failure as fatal, and here the report is the point.+ reply := o.terminalSessions[e.ChatSessionID].queue[0]+ var result terminalRequestResult+ settled := false+ for i := 0; i < 25; i++ {+ result = o.sendNextTerminalRequest(context.Background(), reply)+ if result.done {+ settled = true+ break+ }+ if d := result.retryAt.Sub(c.now()); d > 0 {+ c.advance(d)+ }+ }+ if !settled {+ t.Fatal("delivery never gave up; the session's queue stays blocked")+ }+ if result.err == nil {+ t.Fatal("delivery reported success without ever owning the reply")+ }+ review8545MessageCount(t, bot, 1)+}++type review8545PauseStreamRead struct {+ *review8545Queries+ pause atomic.Bool+ entered chan struct{}+ release chan struct{}+}++func (q *review8545PauseStreamRead) AcquireChannelReplyDelivery(ctx context.Context, p db.AcquireChannelReplyDeliveryParams) (db.ChannelReplyDelivery, error) {+ row, err := q.Queries.AcquireChannelReplyDelivery(ctx, p)+ if p.Phase == deliveryPhaseStreaming && q.pause.CompareAndSwap(true, false) {+ close(q.entered)+ select {+ case <-q.release:+ case <-ctx.Done():+ return row, ctx.Err()+ }+ }+ return row, err+}++func TestReview8545PostgresStaleStreamCannotOverwriteSettledAnswer(t *testing.T) {+ bot := &auditBot{}+ a, base, c, e := review8545Setup(t, bot)+ a.handleTaskMessage(telegramPartialEvent(e.TaskID, chatDoneContent(e.Payload)))+ c.advance(editInterval + time.Millisecond)+ q := &review8545PauseStreamRead{review8545Queries: base, entered: make(chan struct{}), release: make(chan struct{})}+ q.pause.Store(true)+ a.q = q+ a.leaseTTL = 100 * time.Millisecond+ b := review8545Second(a)+ b.leaseTTL = 100 * time.Millisecond+ done := make(chan struct{})+ go func() { defer close(done); a.handleTaskMessage(telegramPartialEvent(e.TaskID, " stale tail")) }()+ defer func() { close(q.release); <-done }()+ <-q.entered+ // The paused frame still owns the turn; the final answer takes over only+ // once that lease expires.+ time.Sleep(150 * time.Millisecond)+ b.enqueueTerminalReply(e)+ auditDrain(t, b, c, e.ChatSessionID)+ q.release <- struct{}{}+ <-done+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.messages[1] != chatDoneContent(e.Payload) {+ t.Fatalf("settled final answer was overwritten: %q; methods=%v", bot.messages[1], bot.methods)+ }+}++// A 5xx is not proof that nothing was posted. Telegram can accept a+// sendMessage and still fail on the way back, so treating it as a definite+// rejection puts the same answer in the chat twice.+func TestReview8545PostgresServerErrorAfterAcceptIsNotResent(t *testing.T) {+ bot := &auditBot{serverErrorAfterAccept: true}+ o, _, c, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "accepted then 500"))+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ review8545MessageCount(t, bot, 1)+}++type review8545FailTurnLookup struct {+ *review8545Queries+ fail atomic.Bool+}++func (q *review8545FailTurnLookup) GetChannelReplyTurn(ctx context.Context, id pgtype.UUID) (db.GetChannelReplyTurnRow, error) {+ if q.fail.Load() {+ return db.GetChannelReplyTurnRow{}, errors.New("injected lineage lookup failure")+ }+ return q.review8545Queries.GetChannelReplyTurn(ctx, id)+}++// A lineage lookup that fails must not fall back to "this task is its own+// turn": that opens a second reply beside the one the previous attempt holds.+func TestReview8545PostgresTurnLookupFailureDoesNotOpenSecondReply(t *testing.T) {+ bot := &auditBot{}+ o, base, c, e := review8545Setup(t, bot)+ retryTask := util.UUIDToString(review8545ID())+ seedRetryChain(t, e.TaskID, retryTask)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first attempt"))++ q := &review8545FailTurnLookup{review8545Queries: base}+ q.fail.Store(true)+ o.q = q+ o.handleTaskMessage(telegramPartialEvent(retryTask, "retry attempt"))+ review8545MessageCount(t, bot, 1)++ // Once the lookup recovers the retry finishes the reply it inherited.+ q.fail.Store(false)+ retry := e+ retry.TaskID = retryTask+ retry.Payload = protocol.ChatDonePayload{TaskID: retryTask, ChatSessionID: e.ChatSessionID, Content: "retry complete answer"}+ o.enqueueTerminalReply(retry)+ auditDrain(t, o, c, retry.ChatSessionID)+ review8545MessageCount(t, bot, 1)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.messages[1] != "retry complete answer" {+ t.Fatalf("inherited reply not finished by the retry: %q; methods=%v", bot.messages[1], bot.methods)+ }+}++// Once a retry has taken the turn, a late frame from the attempt it superseded+// must not take it back and rewrite what the user is reading.+func TestReview8545PostgresSupersededAttemptCannotRewriteReply(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ retryTask := util.UUIDToString(review8545ID())+ seedRetryChain(t, e.TaskID, retryTask)++ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first attempt"))+ c.advance(editInterval + time.Millisecond)+ o.handleTaskMessage(telegramPartialEvent(retryTask, "retry attempt"))+ c.advance(editInterval + time.Millisecond)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, " stale tail from the old attempt"))++ review8545MessageCount(t, bot, 1)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if strings.Contains(bot.messages[1], "stale tail") {+ t.Fatalf("superseded attempt rewrote the reply: %q; methods=%v", bot.messages[1], bot.methods)+ }+}++// A reply settled by another replica leaves this one holding a stream and a+// chat-scheduler reference. Nothing else can release them, so the next frame+// for that turn must.+func TestReview8545PostgresSettledElsewhereReleasesLocalState(t *testing.T) {+ bot := &auditBot{}+ a, _, c, e := review8545Setup(t, bot)+ a.handleTaskMessage(telegramPartialEvent(e.TaskID, "streamed on this replica"))+ b := review8545Second(a)+ b.enqueueTerminalReply(e)+ auditDrain(t, b, c, e.ChatSessionID)++ a.mu.Lock()+ held := len(a.streams)+ a.mu.Unlock()+ if held != 1 {+ t.Fatalf("setup expected one local stream, found %d", held)+ }+ c.advance(editInterval + time.Millisecond)+ a.handleTaskMessage(telegramPartialEvent(e.TaskID, " late tail"))++ a.mu.Lock()+ defer a.mu.Unlock()+ if len(a.streams) != 0 {+ t.Fatal("local stream survived a reply another replica settled")+ }+ for key, schedule := range a.chats {+ if schedule.refs != 0 {+ t.Fatalf("chat schedule %v still referenced after the reply settled", key)+ }+ }+}++// A failure notice must wait for the turn like any other terminal work. Losing+// it because a text frame held the turn at that instant leaves the placeholder+// as the last thing the user ever sees.+func TestReview8545PostgresFailureNoticeWaitsForALiveLease(t *testing.T) {+ bot := &auditBot{}+ a, _, c, e := review8545Setup(t, bot)+ a.leaseTTL = 100 * time.Millisecond+ a.handleTaskMessage(telegramPartialEvent(e.TaskID, "streamed reply"))++ ctx := context.Background()+ target, err := a.resolveTarget(ctx, e, false)+ if err != nil {+ t.Fatal(err)+ }+ turn, err := a.turnFor(ctx, target.taskID)+ if err != nil {+ t.Fatal(err)+ }+ // Hold the turn the way a frame mid-request would.+ if _, status, err := a.acquireDelivery(ctx, target, turn, deliveryPhaseStreaming); err != nil || status != deliveryAcquired {+ t.Fatalf("could not hold the turn: status=%v err=%v", status, err)+ }++ b := review8545Second(a)+ b.leaseTTL = 100 * time.Millisecond+ b.handleTaskFailed(events.Event{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID,+ Payload: map[string]any{"retry_pending": false}})+ time.Sleep(150 * time.Millisecond)+ auditDrain(t, b, c, e.ChatSessionID)++ review8545MessageCount(t, bot, 1)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.messages[1] != taskFailedText {+ t.Fatalf("failure notice was lost: reply still reads %q; methods=%v", bot.messages[1], bot.methods)+ }+}++// A cancellation or empty completion belonging to an attempt the retry chain+// has moved past must not end the turn: the attempt that superseded it is+// still delivering, and its answer would be dropped as already settled.+func TestReview8545PostgresSupersededAttemptCannotCloseTheTurn(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ oldTask := e.TaskID+ retryTask := util.UUIDToString(review8545ID())+ seedRetryChain(t, oldTask, retryTask)++ // The retry takes the turn and starts streaming.+ o.handleTaskMessage(telegramPartialEvent(retryTask, "retry streaming"))++ // The attempt it superseded completes empty, late.+ stale := e+ stale.TaskID = oldTask+ stale.Payload = protocol.ChatDonePayload{TaskID: oldTask, ChatSessionID: e.ChatSessionID}+ o.enqueueTerminalReply(stale)+ auditDrain(t, o, c, stale.ChatSessionID)++ // The retry's answer must still be delivered.+ retry := e+ retry.TaskID = retryTask+ retry.Payload = protocol.ChatDonePayload{TaskID: retryTask, ChatSessionID: e.ChatSessionID, Content: "retry complete answer"}+ o.enqueueTerminalReply(retry)+ auditDrain(t, o, c, retry.ChatSessionID)++ review8545MessageCount(t, bot, 1)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.messages[1] != "retry complete answer" {+ t.Fatalf("superseded attempt closed the turn; reply reads %q, methods=%v", bot.messages[1], bot.methods)+ }+}++// Losing the lease mid-notice must stop the notice, not merely change what it+// does next. One provider call per step, and the next step re-proves the turn.+func TestReview8545PostgresFailureNoticeStopsAfterLosingTheLease(t *testing.T) {+ bot := &auditBot{failFirstEdit: true}+ o, _, c, e := review8545Setup(t, bot)+ o.leaseTTL = 100 * time.Millisecond+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "streamed reply"))+ o.handleTaskFailed(events.Event{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID,+ Payload: map[string]any{"retry_pending": false}})++ o.terminalMu.Lock()+ reply := o.terminalSessions[e.ChatSessionID].queue[0]+ o.terminalMu.Unlock()++ // First step: initialize and take the turn.+ if result := o.sendNextTerminalRequest(context.Background(), reply); result.done {+ t.Fatalf("notice finished before making a request: %+v", result)+ }+ // Second step: the ambiguous edit. It must come back for another step+ // rather than retrying inside this one.+ result := o.sendNextTerminalRequest(context.Background(), reply)+ if result.done {+ t.Fatalf("ambiguous edit settled inside one step: %+v", result)+ }+ callsBefore, _ := func() (int, bool) {+ bot.mu.Lock()+ defer bot.mu.Unlock()+ return len(bot.methods), true+ }()++ // Another replica takes the turn over while this one waits.+ other := review8545Second(o)+ other.leaseTTL = 100 * time.Millisecond+ time.Sleep(150 * time.Millisecond)+ target, err := other.resolveTarget(context.Background(), e, false)+ if err != nil {+ t.Fatal(err)+ }+ turn, err := other.turnFor(context.Background(), target.taskID)+ if err != nil {+ t.Fatal(err)+ }+ if _, status, err := other.acquireDelivery(context.Background(), target, turn, deliveryPhaseTerminal); err != nil || status != deliveryAcquired {+ t.Fatalf("second replica could not take the turn: status=%v err=%v", status, err)+ }++ c.advance(time.Minute)+ if result := o.sendNextTerminalRequest(context.Background(), reply); !result.done {+ t.Fatalf("delivery continued without the turn: %+v", result)+ }+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if len(bot.methods) != callsBefore {+ t.Fatalf("called Telegram after losing the turn: %v", bot.methods)+ }+}++// Quiet is not abandoned. A run can sit in a tool call far longer than any+// sweep interval, and reclaiming its stream would restart the reply's text+// from whatever arrives next.+func TestReview8545PostgresQuietStreamSurvivesTheSweep(t *testing.T) {+ bot := &auditBot{}+ o, _, c, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first half"))++ // Hours of silence, the shape of a long tool call.+ c.advance(3 * time.Hour)+ o.sweepSettledStreams(context.Background())++ o.mu.Lock()+ _, held := o.streams[e.TaskID]+ o.mu.Unlock()+ if !held {+ t.Fatal("sweep reclaimed a live reply that was merely quiet")+ }++ o.handleTaskMessage(telegramPartialEvent(e.TaskID, " second half"))+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.messages[1] != "first half second half" {+ t.Fatalf("quiet stream lost its prefix: %q; methods=%v", bot.messages[1], bot.methods)+ }+}++// The other half of the same rule: once the turn really is over, the sweep+// does release the local state nothing else can.+func TestReview8545PostgresSweepReleasesTurnsSettledElsewhere(t *testing.T) {+ bot := &auditBot{}+ a, _, c, e := review8545Setup(t, bot)+ a.handleTaskMessage(telegramPartialEvent(e.TaskID, "streamed on this replica"))+ b := review8545Second(a)+ b.enqueueTerminalReply(e)+ auditDrain(t, b, c, e.ChatSessionID)++ c.advance(streamSweepGrace + time.Second)+ a.sweepSettledStreams(context.Background())++ a.mu.Lock()+ defer a.mu.Unlock()+ if len(a.streams) != 0 {+ t.Fatal("sweep left local state for a turn another replica settled")+ }+ for key, schedule := range a.chats {+ if schedule.refs != 0 {+ t.Fatalf("chat schedule %v still referenced after the sweep", key)+ }+ }+}++// The lease only means anything if a call made under it cannot outlive it.+// The shared Bot API client allows 65s — fine for getUpdates long polling,+// fatal for a delivery call, because a request that outlives its lease can+// land after another process has taken the turn over and finished it.+func TestDeliveryCallBudgetFitsTheLease(t *testing.T) {+ if deliveryCallTimeout+deliveryRecordTimeout >= deliveryLeaseTTL {+ t.Fatalf("one call (%s) plus recording its outcome (%s) does not fit inside the lease (%s): "++ "a delivery can still be talking to Telegram after losing the turn",+ deliveryCallTimeout, deliveryRecordTimeout, deliveryLeaseTTL)+ }+}++// A call that hangs must be cut off by its own budget rather than by the+// client's, so the turn is released close to the lease instead of minutes past+// it. Exercised with a short lease and a bot that never answers.+func TestReview8545PostgresSlowCallIsCutOffInsideTheLease(t *testing.T) {+ block := make(chan struct{})+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ select {+ case <-block:+ case <-r.Context().Done():+ }+ }))+ // Release the handler before closing the server: Close waits for handlers+ // to return, and deferred calls run in reverse.+ defer srv.Close()+ defer close(block)++ bot := &auditBot{}+ o, _, _, e := review8545Setup(t, bot)+ o.apiBase = srv.URL+ o.client = srv.Client()+ o.leaseTTL = 600 * time.Millisecond++ done := make(chan time.Duration, 1)+ go func() {+ started := time.Now()+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "a send that never comes back"))+ done <- time.Since(started)+ }()++ select {+ case took := <-done:+ // The call budget is a third of the lease, so the frame has to give up+ // well before the lease lapses — never at the client's 65s.+ if took >= o.leaseTTL {+ t.Fatalf("send held the turn for %s, past its %s lease", took, o.leaseTTL)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("send was still running long after its lease; the call budget is not bounding it")+ }+}diff --git a/server/internal/integrations/telegram/outbound_delivery_contract_test.go b/server/internal/integrations/telegram/outbound_delivery_contract_test.gonew file mode 100644index 0000000000..86fdfe5af0--- /dev/null+++ b/server/internal/integrations/telegram/outbound_delivery_contract_test.go@@ -0,0 +1,446 @@+package telegram++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// The delivery contract for a task's reply, probe by probe: one user turn+// gets one answer, whichever path, process or failure mode produces it.+//+// These cases were written as an audit of the duplicate reports (GH #8049,+// #7750) and failed on main; they run by default now that they pass, because+// each one is a way the reply used to arrive twice. Everything here uses a+// local fake Bot API, a controllable clock and a shared fake database — two+// Outbound values sharing one of those stand in for two backend replicas.+type auditBot struct {+ mu sync.Mutex+ messages map[int64]string+ methods []string+ loseFirstSendResponse bool+ serverErrorAfterAccept bool+ failFirstEdit bool+ forbidEdits bool+ sends int64+ edits int+}++func (a *auditBot) serve(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ method := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]+ a.mu.Lock()+ defer a.mu.Unlock()+ a.methods = append(a.methods, method)+ w.Header().Set("Content-Type", "application/json")+ switch method {+ case "sendMessage":+ a.sends+++ a.messages[a.sends] = body["text"].(string)+ if a.serverErrorAfterAccept && a.sends == 1 {+ // Accepted, then failed on the way back. The message is in the+ // chat; the caller has no way to know that.+ w.WriteHeader(500)+ _, _ = w.Write([]byte(`{"ok":false,"error_code":500,"description":"Internal Server Error"}`))+ return+ }+ if a.loseFirstSendResponse && a.sends == 1 {+ // The provider accepted the message, but the caller gets no ID.+ conn, _, err := w.(http.Hijacker).Hijack()+ if err == nil {+ _ = conn.Close()+ }+ return+ }+ _, _ = fmt.Fprintf(w, `{"ok":true,"result":{"message_id":%d}}`, a.sends)+ case "editMessageText":+ a.edits+++ if a.forbidEdits {+ _, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"Bad Request: message can't be edited"}`))+ return+ }+ a.messages[int64(body["message_id"].(float64))] = body["text"].(string)+ if a.failFirstEdit && a.edits == 1 {+ _, _ = w.Write([]byte(`{"ok":false,"error_code":500,"description":"Internal Server Error"}`))+ return+ }+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))+ }+}++func (a *auditBot) wantOne(t *testing.T) {+ t.Helper()+ a.mu.Lock()+ defer a.mu.Unlock()+ if len(a.messages) != 1 {+ t.Fatalf("visible replies = %d, want 1; methods=%v messages=%v", len(a.messages), a.methods, a.messages)+ }+}++type auditClock struct{ nanos atomic.Int64 }++func (c *auditClock) now() time.Time { return time.Unix(0, c.nanos.Load()) }+func (c *auditClock) advance(d time.Duration) { c.nanos.Add(int64(d)) }++func auditSetup(t *testing.T, bot *auditBot) (*Outbound, *fakeTelegramOutboundQueries, *auditClock, *httptest.Server) {+ t.Helper()+ bot.messages = make(map[int64]string)+ srv := httptest.NewServer(http.HandlerFunc(bot.serve))+ t.Cleanup(srv.Close)+ q := newTelegramOutboundQueries(t)+ q.channelOrigin = true+ o := NewOutbound(q, nil, srv.URL, srv.Client(), nil)+ c := &auditClock{}+ c.nanos.Store(time.Date(2026, 9, 18, 0, 0, 0, 0, time.UTC).UnixNano())+ o.now = c.now+ o.wait = func(_ context.Context, d time.Duration) error { c.advance(d); return nil }+ return o, q, c, srv+}++func auditPartial(e events.Event) events.Event {+ return events.Event{Type: protocol.EventTaskMessage, TaskID: e.TaskID,+ Payload: protocol.TaskMessagePayload{TaskID: e.TaskID, Type: "text", Content: chatDoneContent(e.Payload)}}+}++// Drive the real terminal queue without wall-clock sleeps or worker races.+func auditDrain(t *testing.T, o *Outbound, c *auditClock, sessionID string) {+ t.Helper()+ for {+ o.terminalMu.Lock()+ s := o.terminalSessions[sessionID]+ if s == nil || len(s.queue) == 0 {+ o.terminalMu.Unlock()+ return+ }+ reply := s.queue[0]+ s.running = true+ s.ready = false+ o.terminalInFlight+++ o.terminalMu.Unlock()+ finished := false+ for i := 0; i < 25; i++ {+ result := o.sendNextTerminalRequest(context.Background(), reply)+ if result.done {+ o.cleanupTerminalReply(reply)+ o.updateQueueAfterTerminalRequest(terminalResult{+ terminalWork: terminalWork{sessionID: sessionID, reply: reply}, done: true, err: result.err})+ if result.err != nil {+ t.Fatalf("terminal delivery failed: %v", result.err)+ }+ finished = true+ break+ }+ if d := result.retryAt.Sub(c.now()); d > 0 {+ c.advance(d)+ }+ }+ if !finished {+ t.Fatal("terminal reply did not settle after 25 requests")+ }+ }+}++// seedRetryChain records that retryTask is an automatic retry of firstTask.+// Delivery ownership keys on that lineage rather than guessing which pending+// reply looked closest, so the relationship has to be real for the retry to+// inherit anything — which is the whole point of the case below.+func seedRetryChain(t *testing.T, firstTask, retryTask string) {+ t.Helper()+ unique := time.Now().UnixNano()+ fx := testutil.New(testPool, "", "")+ fx.UserID = fx.User(t, "telegram-delivery", fmt.Sprintf("telegram-delivery-%[email protected]", unique))+ fx.WorkspaceID = fx.Workspace(t, "telegram-delivery", fmt.Sprintf("telegram-delivery-%d", unique))+ agentID := fx.Agent(t, "telegram-delivery", "")+ finished := testutil.Cols{"status": "completed", "completed_at": testutil.Raw("now()")}+ fx.Task(t, agentID, merged(finished, testutil.Cols{"id": firstTask}))+ fx.Task(t, agentID, merged(finished, testutil.Cols{"id": retryTask, "retry_of_task_id": firstTask}))+}++func merged(base, extra testutil.Cols) testutil.Cols {+ out := testutil.Cols{}+ for k, v := range base {+ out[k] = v+ }+ for k, v := range extra {+ out[k] = v+ }+ return out+}++func TestAuditLatePartialAfterCompletion(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ c.advance(editInterval + time.Millisecond)+ o.handleTaskMessage(auditPartial(e))+ bot.wantOne(t)+}++func TestAuditDistinctReplicasForPartialAndCompletion(t *testing.T) {+ bot := &auditBot{}+ a, q, c, srv := auditSetup(t, bot)+ b := NewOutbound(q, nil, srv.URL, srv.Client(), nil)+ b.now = c.now+ e := telegramTestEvent()+ a.handleTaskMessage(auditPartial(e))+ b.enqueueTerminalReply(e)+ auditDrain(t, b, c, e.ChatSessionID)+ bot.wantOne(t)+}++func TestAuditAcceptedPlaceholderWithLostResponse(t *testing.T) {+ bot := &auditBot{loseFirstSendResponse: true}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.handleTaskMessage(auditPartial(e))+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ bot.wantOne(t)+}++func TestAuditAmbiguousFinalEdit(t *testing.T) {+ bot := &auditBot{failFirstEdit: true}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.handleTaskMessage(auditPartial(e))+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ bot.wantOne(t)+}++func TestAuditAmbiguousFailureNoticeEdit(t *testing.T) {+ bot := &auditBot{failFirstEdit: true}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.handleTaskMessage(auditPartial(e))+ o.handleTaskFailed(events.Event{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID,+ Type: protocol.EventTaskFailed, Payload: map[string]any{"retry_pending": false}})+ auditDrain(t, o, c, e.ChatSessionID)+ bot.wantOne(t)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.messages[1] != taskFailedText {+ t.Fatalf("placeholder was not turned into the failure notice: %q; methods=%v", bot.messages[1], bot.methods)+ }+}++func TestAuditDuplicateTerminalEvent(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.enqueueTerminalReply(e)+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ bot.wantOne(t)+}++func TestAuditLatePartialAfterCancellationOrEmptyCompletion(t *testing.T) {+ for _, terminal := range []string{"cancelled", "empty"} {+ t.Run(terminal, func(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.handleTaskMessage(auditPartial(e))+ if terminal == "cancelled" {+ o.handleTaskCancelled(e)+ } else {+ empty := e+ empty.Payload = protocol.ChatDonePayload{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID}+ o.enqueueTerminalReply(empty)+ }+ c.advance(editInterval + time.Millisecond)+ o.handleTaskMessage(auditPartial(e))+ bot.wantOne(t)+ })+ }+}++type auditGatedQueries struct {+ *fakeTelegramOutboundQueries+ first atomic.Bool+ entered chan struct{}+ release chan struct{}+}++func (q *auditGatedQueries) GetChannelTaskDelivery(ctx context.Context, id pgtype.UUID) (db.ChannelTaskDelivery, error) {+ if q.first.CompareAndSwap(false, true) {+ close(q.entered)+ select {+ case <-q.release:+ case <-ctx.Done():+ return db.ChannelTaskDelivery{}, ctx.Err()+ }+ }+ return q.fakeTelegramOutboundQueries.GetChannelTaskDelivery(ctx, id)+}++func TestAuditPartialResolutionOverlapsCompletion(t *testing.T) {+ bot := &auditBot{}+ o, base, c, _ := auditSetup(t, bot)+ q := &auditGatedQueries{fakeTelegramOutboundQueries: base, entered: make(chan struct{}), release: make(chan struct{})}+ o.q = q+ e := telegramTestEvent()+ finished := make(chan struct{})+ go func() { defer close(finished); o.handleTaskMessage(auditPartial(e)) }()+ defer func() { close(q.release); <-finished }()+ <-q.entered+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ c.advance(editInterval + time.Millisecond)+ q.release <- struct{}{}+ <-finished+ bot.wantOne(t)+}++func TestAuditAutomaticRetryPreservesSingleReply(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ first := telegramTestEvent()+ retryTask := telegramTestEventFor(3, 5, "").TaskID+ seedRetryChain(t, first.TaskID, retryTask)+ o.handleTaskMessage(auditPartial(first))+ o.handleTaskFailed(events.Event{TaskID: first.TaskID, Type: protocol.EventTaskFailed,+ Payload: map[string]any{"retry_pending": true}})+ c.advance(editInterval + time.Millisecond)+ retry := telegramTestEventFor(3, 5, chatDoneContent(first.Payload))+ _ = retryTask+ o.handleTaskMessage(auditPartial(retry))+ o.enqueueTerminalReply(retry)+ auditDrain(t, o, c, retry.ChatSessionID)+ bot.wantOne(t)+}++func TestAuditPermanentEditFailureDoesNotBlockSession(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.handleTaskMessage(auditPartial(e))+ bot.mu.Lock()+ bot.forbidEdits = true+ bot.mu.Unlock()+ o.enqueueTerminalReply(e)+ reply := o.terminalSessions[e.ChatSessionID].queue[0]+ for i := 0; i < 25; i++ {+ result := o.sendNextTerminalRequest(context.Background(), reply)+ if result.done {+ bot.wantOne(t)+ return+ }+ if d := result.retryAt.Sub(c.now()); d > 0 {+ c.advance(d)+ }+ }+ t.Fatal("25 terminal steps did not settle a permanent edit rejection; the same session's next reply remains blocked")+}++func TestAuditLatePartialAfterDedupTTL(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ c.advance(11 * time.Minute)+ o.handleTaskMessage(auditPartial(e))+ bot.wantOne(t)+}++type auditLedgerQueries struct {+ *fakeTelegramOutboundQueries+ row db.ChatMessage+}++func (q *auditLedgerQueries) GetChatMessageByTaskAssistant(context.Context, pgtype.UUID) (db.ChatMessage, error) {+ return q.row, nil+}++func (q *auditLedgerQueries) SetChatMessageChannelOutboundProvenanceByTask(_ context.Context, p db.SetChatMessageChannelOutboundProvenanceByTaskParams) (int64, error) {+ q.row.ChannelOutboundType = p.ChannelType+ q.row.ChannelOutboundInstallationID = p.InstallationID+ q.row.ChannelOutboundChatID = p.ChannelChatID+ q.row.ChannelOutboundMessageIds = append([]string(nil), p.MessageIds...)+ return 1, nil+}++func (q *auditLedgerQueries) RecordChannelOutboundMessage(context.Context, db.RecordChannelOutboundMessageParams) error {+ return nil+}++func TestAuditReplayAfterInterruptionBetweenChunks(t *testing.T) {+ bot := &auditBot{}+ a, base, c, srv := auditSetup(t, bot)+ q := &auditLedgerQueries{fakeTelegramOutboundQueries: base, row: db.ChatMessage{ID: telegramTestUUID(9)}}+ a.q = q+ // The interrupted process never releases its lease — it stops existing.+ // Expiry is what frees the turn, and expiry is database time, so the test+ // shortens the lease and really waits for it.+ a.leaseTTL = 100 * time.Millisecond+ e := telegramTestEventFor(3, 2, strings.Repeat("A", maxMessageUnits)+"tail")+ a.enqueueTerminalReply(e)+ reply := a.terminalSessions[e.ChatSessionID].queue[0]+ for i := 0; reply.chunkIndex < 1 && i < 10; i++ {+ result := a.sendNextTerminalRequest(context.Background(), reply)+ if result.done {+ t.Fatalf("unexpected completion before first chunk: %+v", result)+ }+ if d := result.retryAt.Sub(c.now()); d > 0 {+ c.advance(d)+ }+ }+ if reply.chunkIndex != 1 {+ t.Fatal("first chunk was never sent")+ }+ // Simulate losing process memory before the next chunk. A replay-capable+ // caller delivers the same completion against the same durable database.+ time.Sleep(150 * time.Millisecond)+ b := NewOutbound(q, nil, srv.URL, srv.Client(), nil)+ b.now = c.now+ b.leaseTTL = 100 * time.Millisecond+ b.enqueueTerminalReply(e)+ auditDrain(t, b, c, e.ChatSessionID)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if len(bot.messages) != 2 {+ t.Fatalf("2-chunk reply produced %d visible messages after interruption; methods=%v", len(bot.messages), bot.methods)+ }+}++func TestAuditControlNormalStreamAndFinalEdit(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ e := telegramTestEvent()+ o.handleTaskMessage(auditPartial(e))+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ bot.wantOne(t)+}++func TestAuditControlSeparateTurnsWithIdenticalText(t *testing.T) {+ bot := &auditBot{}+ o, _, c, _ := auditSetup(t, bot)+ for _, id := range []byte{2, 5} {+ e := telegramTestEventFor(3, id, "same legitimate answer")+ o.enqueueTerminalReply(e)+ auditDrain(t, o, c, e.ChatSessionID)+ }+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if len(bot.messages) != 2 {+ t.Fatalf("distinct turns produced %d replies, want 2", len(bot.messages))+ }+}diff --git a/server/internal/integrations/telegram/outbound_stream_race_test.go b/server/internal/integrations/telegram/outbound_stream_race_test.goindex 724cf5a1d1..255fe8ee9a 100644--- a/server/internal/integrations/telegram/outbound_stream_race_test.go+++ b/server/internal/integrations/telegram/outbound_stream_race_test.go@@ -75,7 +75,7 @@ func TestOutboundChatDoneWaitsForInFlightPlaceholderSend(t *testing.T) {api, calls, sendStarted, release := gatedTelegramAPI(t)defer release()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)taskID := telegramTestEvent().TaskID@@ -147,35 +147,19 @@ func TestOutboundChatDoneWaitsForInFlightPlaceholderSend(t *testing.T) {}}-// The mirror case: terminal delivery gets the stream first, between the-// partial registering it and that partial claiming the send. The partial no-// longer owns the reply and must not post its placeholder on top of the-// terminal one.+// The mirror case: the final answer takes the reply over while a streaming+// frame is on its way to sending. The frame no longer owns the turn and must+// not put its placeholder on top of the answer.func TestOutboundPartialSkipsSendAfterTerminalConsumedTheStream(t *testing.T) {api, calls, _, release := gatedTelegramAPI(t)release() // no gating needed herectx := context.Background()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)taskID := telegramTestEvent().TaskID- target, err := o.resolveTarget(ctx, telegramPartialEvent(taskID, "hello world"), true)- if err != nil || target == nil {- t.Fatalf("resolve target: %v (target %v)", err, target)- }- // Register the stream exactly as handleTaskMessage does, and stop there:- // this is the state a partial is in when it is about to claim the send.- o.mu.Lock()- st := &streamState{- chatID: target.chatID, threadID: target.threadID, replyTo: target.replyTo,- accumulated: "hello world",- schedule: o.retainChatLocked(target.botKey, target.chatID),- }- o.streams[target.streamKey] = st- o.mu.Unlock()-done := telegramTestEvent()done.Payload = protocol.ChatDonePayload{TaskID: taskID, ChatSessionID: done.ChatSessionID, Content: "hello world",@@ -188,16 +172,24 @@ func TestOutboundPartialSkipsSendAfterTerminalConsumedTheStream(t *testing.T) {}// Clear the cooldown the terminal send just set, so the only thing that- // can hold this partial back is the ownership check under test.- st.schedule.mu.Lock()- st.schedule.lastEdit = time.Time{}- st.schedule.setBackoffTill(time.Time{})- st.schedule.mu.Unlock()+ // can hold this frame back is the ownership it no longer has.+ o.mu.Lock()+ schedules := make([]*chatSchedule, 0, len(o.chats))+ for _, schedule := range o.chats {+ schedules = append(schedules, schedule)+ }+ o.mu.Unlock()+ for _, schedule := range schedules {+ schedule.mu.Lock()+ schedule.lastEdit = time.Time{}+ schedule.setBackoffTill(time.Time{})+ schedule.mu.Unlock()+ }- o.pushPartial(ctx, target, st, 0, "hello world")+ o.handleTaskMessage(telegramPartialEvent(taskID, "hello world"))if methods, _ := calls(); len(methods) != 1 {- t.Fatalf("partial posted a placeholder for a reply it no longer owned: %v", methods)+ t.Fatalf("frame touched Telegram for a reply it no longer owned: %v", methods)}}@@ -210,7 +202,7 @@ func TestOutboundCapacityRetryRechecksInstallation(t *testing.T) {release() // nothing to gate herectx := context.Background()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)diff --git a/server/internal/integrations/telegram/outbound_test.go b/server/internal/integrations/telegram/outbound_test.goindex d46efabbd2..2e70054d05 100644--- a/server/internal/integrations/telegram/outbound_test.go+++ b/server/internal/integrations/telegram/outbound_test.go@@ -25,6 +25,14 @@ import ()type fakeTelegramOutboundQueries struct {+ // Routing is faked; reply-delivery ownership is not. Every query the+ // ownership state machine runs is the real generated one, against the test+ // database. An in-memory stand-in for that state machine is a second+ // implementation of it: the first version of this feature had one, it+ // disagreed with the SQL about a single column, and the whole suite passed+ // while the final answer never reached Telegram.+ *db.Queries+deliveryErr errorchannelOrigin boolbinding db.ChannelChatSessionBinding@@ -104,6 +112,7 @@ func sendTerminalReplySynchronouslyForTest(ctx context.Context, o *Outbound, e efunc telegramTestBinding(chatID int64) db.ChannelChatSessionBinding {return db.ChannelChatSessionBinding{+ ID: telegramTestUUID(byte(chatID)),InstallationID: telegramTestUUID(1),ChannelChatID: strconv.FormatInt(chatID, 10),Config: []byte(fmt.Sprintf(`{"chat_id":"%d"}`, chatID)),@@ -111,9 +120,23 @@ func telegramTestBinding(chatID int64) db.ChannelChatSessionBinding {}}-func newTelegramOutboundQueries() *fakeTelegramOutboundQueries {+func newTelegramOutboundQueries(t *testing.T) *fakeTelegramOutboundQueries {+ t.Helper()+ if testPool == nil {+ t.Skip("reply-delivery ownership runs real SQL; start this checkout's environment and run via make test")+ }+ // Cases in this package reuse fixed task ids, and a turn id is a task id,+ // so rows left by an earlier case would collide. Scoped to this+ // installation rather than the whole table: other packages run alongside+ // this one against the same database.+ if _, err := testPool.Exec(context.Background(),+ `DELETE FROM channel_reply_delivery WHERE installation_id = $1`, telegramTestUUID(1)); err != nil {+ t.Fatalf("reset channel_reply_delivery: %v", err)+ }return &fakeTelegramOutboundQueries{+ Queries: db.New(testPool),binding: db.ChannelChatSessionBinding{+ ID: telegramTestUUID(7),InstallationID: telegramTestUUID(1),ChannelChatID: "42",Config: []byte(`{"chat_id":"42"}`),@@ -128,7 +151,7 @@ func newTelegramOutboundQueries() *fakeTelegramOutboundQueries {}func TestResolveTargetFailsClosedWhenDeliveryLookupFails(t *testing.T) {- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.deliveryErr = errors.New("database unavailable")o := NewOutbound(q, nil, "", nil, nil)@@ -138,7 +161,7 @@ func TestResolveTargetFailsClosedWhenDeliveryLookupFails(t *testing.T) {}func TestResolveTargetSkipsDirectTaskOnBoundTelegramSession(t *testing.T) {- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)o := NewOutbound(q, nil, "", nil, nil)target, err := o.resolveTarget(context.Background(), telegramTestEvent(), false)@@ -151,7 +174,7 @@ func TestResolveTargetSkipsDirectTaskOnBoundTelegramSession(t *testing.T) {}func TestResolveTargetDeliversChannelTaskReply(t *testing.T) {- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, "", nil, nil)@@ -165,7 +188,7 @@ func TestResolveTargetDeliversChannelTaskReply(t *testing.T) {}func TestResolveTargetIsolatesConcurrentTasksInOneSession(t *testing.T) {- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, "", nil, nil)@@ -222,7 +245,7 @@ func TestOutboundStreamsBySendingThenEditingTheSameQuotedMessage(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)taskID := telegramTestEvent().TaskID@@ -296,7 +319,7 @@ func TestOutboundThrottlesConcurrentTasksPerChat(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)first := telegramTestEvent().TaskID@@ -319,7 +342,7 @@ func TestOutboundThrottlesConcurrentTasksPerChat(t *testing.T) {}func TestOutboundCancellationClearsStateAndKeepsPartialMessage(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)taskID := telegramTestEvent().TaskIDo.mu.Lock()schedule := o.retainChatLocked("bot-a", 42)@@ -341,7 +364,7 @@ func TestOutboundCancellationClearsStateAndKeepsPartialMessage(t *testing.T) {}func TestOutboundRetainsScheduleAcrossSequentialTasks(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }@@ -357,7 +380,7 @@ func TestOutboundRetainsScheduleAcrossSequentialTasks(t *testing.T) {}func TestOutboundExpiresIdleScheduleAfterTTL(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }@@ -374,7 +397,7 @@ func TestOutboundExpiresIdleScheduleAfterTTL(t *testing.T) {}func TestOutboundCancellationPreservesActiveRetryAfter(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }taskID := telegramTestEvent().TaskID@@ -401,7 +424,7 @@ func TestOutboundCancellationPreservesActiveRetryAfter(t *testing.T) {}func TestOutboundChatScheduleCacheIsBounded(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }@@ -418,7 +441,7 @@ func TestOutboundChatScheduleCacheIsBounded(t *testing.T) {}func TestOutboundIdleSchedulePreservesBackoffBeyondTTL(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }@@ -440,7 +463,7 @@ func TestOutboundIdleSchedulePreservesBackoffBeyondTTL(t *testing.T) {}func TestOutboundCapacityPruningPreservesActiveBackoff(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }@@ -497,7 +520,7 @@ func TestOutboundCapacityEvictionPreservesRecentChatCooldown(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)candidateKey := chatScheduleKey{botKey: "bot-a", chatID: 1}candidate := &chatSchedule{key: candidateKey, idleSince: current.Add(-tt.idleFor)}if tt.backoffFor > 0 {@@ -526,7 +549,7 @@ func TestOutboundCapacityEvictionPreservesRecentChatCooldown(t *testing.T) {}func TestOutboundManyActiveBackoffsKeepTotalScheduleCacheBounded(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }@@ -559,7 +582,7 @@ func TestOutboundManyActiveBackoffsKeepTotalScheduleCacheBounded(t *testing.T) {}func TestOutboundCompressedChatInheritsBotFallback(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.now = func() time.Time { return current }backoffTill := current.Add(time.Hour)@@ -601,7 +624,7 @@ func TestOutboundCompressedChatInheritsBotFallback(t *testing.T) {}func TestOutboundExpiredBotFallbackIsRemoved(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.mu.Lock()o.botFallbackBackoff["bot-a"] = current.Add(time.Minute)@@ -620,7 +643,7 @@ func TestOutboundExpiredBotFallbackIsRemoved(t *testing.T) {}func TestOutboundBotFallbackDoesNotThrottleAnotherInstallation(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)o.mu.Lock()o.botFallbackBackoff["bot-a"] = current.Add(time.Hour)@@ -652,7 +675,7 @@ func TestOutboundCompletionWaitsForRetryAfterBackoff(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)@@ -697,7 +720,7 @@ func TestOutboundTerminalWorkerDeliversLongMultiChunkReply(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)@@ -740,7 +763,7 @@ func TestOutboundTerminalDeliveryHasNoFixedRetryAfterBudget(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)@@ -779,7 +802,7 @@ func TestOutboundChatDoneDoesNotBlockRealtimeFanout(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)ctx, cancel := context.WithCancel(context.Background())@@ -857,7 +880,7 @@ func TestOutboundLegacyLaneCollisionDoesNotBlockAnotherSession(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueq.bindings = map[[16]byte]db.ChannelChatSessionBinding{{15: 2}: telegramTestBinding(42),@@ -909,7 +932,7 @@ func TestOutboundSameSessionSecondReplyCannotOvertakeFirst(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)ctx, cancel := context.WithCancel(context.Background())@@ -963,7 +986,7 @@ func TestOutboundBackoffSessionsDoNotExhaustWorkers(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueq.bindings = make(map[[16]byte]db.ChannelChatSessionBinding)for i := byte(1); i <= terminalWorkerCount+2; i++ {@@ -1022,7 +1045,7 @@ func TestOutboundShutdownAbandonsQueuedRetryWaitingAndInflightJobs(t *testing.T)}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueq.bindings = map[[16]byte]db.ChannelChatSessionBinding{{15: 2}: telegramTestBinding(42),@@ -1080,7 +1103,7 @@ func TestOutboundRetryResumesAtFailedChunkWithoutRepeatingSuccess(t *testing.T)}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)@@ -1103,7 +1126,7 @@ func TestOutboundRetryResumesAtFailedChunkWithoutRepeatingSuccess(t *testing.T)}func TestOutboundTerminalSchedulerPreservesSessionFIFO(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)first := telegramTestEvent()second := telegramTestEvent()second.TaskID = "00000000-0000-0000-0000-000000000005"@@ -1126,7 +1149,7 @@ func TestOutboundTerminalSchedulerPreservesSessionFIFO(t *testing.T) {}func TestOutboundRejectsSixtyFifthQueuedTerminalReply(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)for i := byte(0); i < maxQueuedTerminalReplies; i++ {sessionByte := i/byte(maxQueuedTerminalRepliesPerSession) + 1o.enqueueTerminalReply(telegramTestEventFor(sessionByte, i+20, "queued"))@@ -1144,7 +1167,7 @@ func TestOutboundRejectsSixtyFifthQueuedTerminalReply(t *testing.T) {}func TestOutboundRejectsNinthQueuedTerminalReplyInSession(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)for i := byte(0); i < maxQueuedTerminalRepliesPerSession; i++ {o.enqueueTerminalReply(telegramTestEventFor(3, i+20, "queued"))}@@ -1160,7 +1183,7 @@ func TestOutboundRejectsNinthQueuedTerminalReplyInSession(t *testing.T) {}func TestOutboundRejectsTerminalReplyBeyondByteLimit(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)e := telegramTestEventFor(3, 2, strings.Repeat("x", maxQueuedTerminalReplyBytes+1))o.enqueueTerminalReply(e)@@ -1174,7 +1197,7 @@ func TestOutboundRejectsTerminalReplyBeyondByteLimit(t *testing.T) {}func TestOutboundCompletedTerminalReplyReleasesCapacityImmediately(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)e := telegramTestEventFor(3, 2, "reply")o.enqueueTerminalReply(e)@@ -1200,7 +1223,7 @@ func TestOutboundCompletedTerminalReplyReleasesCapacityImmediately(t *testing.T)}func TestOutboundShutdownClearsTerminalReplyCapacity(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)o.enqueueTerminalReply(telegramTestEventFor(3, 2, "first"))o.enqueueTerminalReply(telegramTestEventFor(7, 5, "second"))o.stopTerminalScheduler()@@ -1218,7 +1241,7 @@ func TestOutboundShutdownClearsTerminalReplyCapacity(t *testing.T) {func TestOutboundRejectedTerminalReplyReleasesStreamSchedule(t *testing.T) {var logs bytes.Bufferlogger := slog.New(slog.NewTextHandler(&logs, nil))- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, logger)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, logger)e := telegramTestEventFor(3, 2, "rejected")schedule := &chatSchedule{key: chatScheduleKey{botKey: "bot", chatID: 42}, refs: 1}o.streams[e.TaskID] = &streamState{chatID: 42, schedule: schedule}@@ -1239,30 +1262,50 @@ func TestOutboundRejectedTerminalReplyReleasesStreamSchedule(t *testing.T) {}}-func TestOutboundEmptyTerminalReplySkipsQueueAndClearsStream(t *testing.T) {- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)+// An empty completion has no answer to deliver, but it still ends the turn: it+// releases local state at once and queues the close that stops a late text+// frame from reopening the reply. The close is a database write, so it runs on+// a worker rather than on the synchronous bus.+func TestOutboundEmptyTerminalReplyClearsStreamAndQueuesTheClose(t *testing.T) {+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, nil)e := telegramTestEventFor(3, 2, "")schedule := &chatSchedule{key: chatScheduleKey{botKey: "bot", chatID: 42}, refs: 1}o.streams[e.TaskID] = &streamState{chatID: 42, schedule: schedule}o.chats[schedule.key] = scheduleo.enqueueTerminalReply(e)- o.terminalMu.Lock()- count := o.queuedTerminalReplyCount- o.terminalMu.Unlock()o.mu.Lock()_, streamExists := o.streams[e.TaskID]refs := schedule.refso.mu.Unlock()- if count != 0 || streamExists || refs != 0 {- t.Fatalf("empty reply count=%d stream=%v schedule refs=%d", count, streamExists, refs)+ if streamExists || refs != 0 {+ t.Fatalf("empty reply left local state behind: stream=%v schedule refs=%d", streamExists, refs)+ }++ o.terminalMu.Lock()+ queued := o.terminalSessions[e.ChatSessionID]+ o.terminalMu.Unlock()+ if queued == nil || len(queued.queue) != 1 {+ t.Fatalf("empty reply did not queue its close: %+v", queued)+ }+ reply := queued.queue[0]+ if reply.kind != terminalKindClose || reply.settleReason != "empty_reply" {+ t.Fatalf("queued reply is not a close: kind=%v reason=%q", reply.kind, reply.settleReason)+ }+ if reply.byteSize != 0 {+ t.Fatalf("empty reply charged %d bytes to the queue budget", reply.byteSize)+ }++ // The close must settle the reply without asking Telegram for anything.+ if result := o.sendNextTerminalRequest(context.Background(), reply); !result.done || result.err != nil {+ t.Fatalf("close did not settle: %+v", result)}}func TestOutboundInvalidTerminalReplyIdentityFailsFast(t *testing.T) {var logs bytes.Bufferlogger := slog.New(slog.NewTextHandler(&logs, nil))- o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, logger)+ o := NewOutbound(newTelegramOutboundQueries(t), nil, "", nil, logger)e := telegramTestEvent()e.TaskID = "invalid-task"e.ChatSessionID = "invalid-session"@@ -1288,7 +1331,7 @@ func TestOutboundTerminalReplyUsesPayloadTaskIDFromProductionEvent(t *testing.T)}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)ctx, cancel := context.WithCancel(context.Background())@@ -1319,7 +1362,7 @@ func TestOutboundRetryPendingFailureCleansStreamWithoutNotice(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)taskID := telegramTestEvent().TaskID@@ -1353,14 +1396,45 @@ func TestOutboundTerminalFailureSendsNotice(t *testing.T) {}))defer api.Close()- q := newTelegramOutboundQueries()+ q := newTelegramOutboundQueries(t)q.channelOrigin = trueo := NewOutbound(q, nil, api.URL, api.Client(), nil)e := telegramTestEvent()e.Type = protocol.EventTaskFailede.Payload = map[string]any{"retry_pending": false}o.handleTaskFailed(e)+ // The notice is terminal work now: it waits for the turn's lease like the+ // answer does, so it is delivered by the queue rather than inline.+ drainTerminalQueueForTest(t, o, e.ChatSessionID)if requests != 1 {t.Fatalf("terminal failure requests = %d, want 1", requests)}}++// drainTerminalQueueForTest runs one session's queued terminal work to+// completion, the way the workers would.+func drainTerminalQueueForTest(t *testing.T, o *Outbound, sessionID string) {+ t.Helper()+ ctx := context.Background()+ for {+ o.terminalMu.Lock()+ session := o.terminalSessions[sessionID]+ if session == nil || len(session.queue) == 0 {+ o.terminalMu.Unlock()+ return+ }+ reply := session.queue[0]+ session.queue = session.queue[1:]+ o.terminalMu.Unlock()+ for i := 0; i < 25; i++ {+ result := o.sendNextTerminalRequest(ctx, reply)+ if result.done {+ o.cleanupTerminalReply(reply)+ break+ }+ if d := result.retryAt.Sub(o.now()); d > 0 {+ _ = o.wait(ctx, d)+ }+ }+ }+}diff --git a/server/migrations/502_channel_reply_delivery.down.sql b/server/migrations/502_channel_reply_delivery.down.sqlnew file mode 100644index 0000000000..7dc23219e4--- /dev/null+++ b/server/migrations/502_channel_reply_delivery.down.sql@@ -0,0 +1,3 @@+-- Keep delivery ownership on application rollback: dropping it would let an+-- older binary re-send replies the provider has already accepted.+SELECT 1;diff --git a/server/migrations/502_channel_reply_delivery.up.sql b/server/migrations/502_channel_reply_delivery.up.sqlnew file mode 100644index 0000000000..1a46fd7e11--- /dev/null+++ b/server/migrations/502_channel_reply_delivery.up.sql@@ -0,0 +1,55 @@+-- One row per user turn: who is currently delivering that turn's reply into a+-- chat channel, what the provider has already accepted, and how far it got.+--+-- The streamed placeholder, the final answer and the failure notice are three+-- code paths, and across replicas three processes — the daemon's transcript+-- report and its completion callback are independent HTTP requests that land+-- wherever the load balancer sends them, and the event bus is in-process. A+-- process that cannot see the placeholder posts its own copy of the same+-- answer (GH #8049, #7750). This row is where they agree.+--+-- Keyed by turn, not by task: an automatic retry runs under a new task id and+-- must finish the reply its previous attempt started rather than answer beside+-- it. turn_id is the root of the agent_task_queue retry_of_task_id chain, so+-- the relationship is the real lineage and never a guess about which pending+-- reply looked closest.+CREATE TABLE IF NOT EXISTS channel_reply_delivery (+ turn_id UUID NOT NULL,+ -- The attempt holding the turn most recently; diagnostics, never identity.+ -- How far down the retry chain that attempt sits is added by migration 506,+ -- which is also where a database created by this file gets it.+ task_id UUID NOT NULL,+ binding_id UUID NOT NULL,+ installation_id UUID NOT NULL,+ channel_type TEXT NOT NULL,+ chat_id TEXT NOT NULL,+ -- streaming: the placeholder is the live reply and may still be edited.+ -- terminal: the final answer has taken over; no placeholder may reopen.+ -- settled: delivery is over; nothing may send or edit for this turn.+ phase TEXT NOT NULL CHECK (phase IN ('streaming', 'terminal', 'settled')),+ -- The state of the one send that may be outstanding, placeholder or chunk.+ -- none: nothing is out.+ -- in_flight: a send is out; the provider may already have accepted it.+ -- known: accepted, and message_id identifies the editable message.+ -- unknown: accepted or not — the response was lost. Telegram's+ -- sendMessage has no caller-supplied idempotency key, so+ -- re-sending here cannot be deduplicated by the provider.+ -- Delivery stops and this row keeps the evidence.+ send_state TEXT NOT NULL CHECK (send_state IN ('none', 'in_flight', 'known', 'unknown')),+ -- The message later paths edit. Independent of chunks_sent: a placeholder+ -- exists long before any part of the final answer has been delivered, and+ -- conflating the two silently truncates the reply.+ message_id TEXT NOT NULL DEFAULT '',+ -- Parts of the FINAL answer already in the chat. Never set by the+ -- placeholder.+ chunks_sent INTEGER NOT NULL DEFAULT 0 CHECK (chunks_sent >= 0),+ -- The delivery lease. Exactly one process may act on a turn at a time;+ -- every state write proves it still holds the token. A lease that expires+ -- is a process that died mid-delivery — the successor may take the turn+ -- over, but an outstanding send stays unknown rather than being retried.+ owner_token UUID,+ owner_expires_at TIMESTAMPTZ,+ settled_reason TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/503_channel_reply_delivery_turn_index.down.sql b/server/migrations/503_channel_reply_delivery_turn_index.down.sqlnew file mode 100644index 0000000000..db2440277a--- /dev/null+++ b/server/migrations/503_channel_reply_delivery_turn_index.down.sql@@ -0,0 +1,2 @@+-- Retain the uniqueness guard the delivery claim infers on.+SELECT 1;diff --git a/server/migrations/503_channel_reply_delivery_turn_index.up.sql b/server/migrations/503_channel_reply_delivery_turn_index.up.sqlnew file mode 100644index 0000000000..c6d9f8e7da--- /dev/null+++ b/server/migrations/503_channel_reply_delivery_turn_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_channel_reply_delivery_turn ON channel_reply_delivery (turn_id);diff --git a/server/migrations/504_channel_reply_delivery_installation_index.down.sql b/server/migrations/504_channel_reply_delivery_installation_index.down.sqlnew file mode 100644index 0000000000..c43f0deb1f--- /dev/null+++ b/server/migrations/504_channel_reply_delivery_installation_index.down.sql@@ -0,0 +1,3 @@+-- Retain the index the workspace, installation and binding teardown paths+-- delete through; without it each of those becomes a full table scan.+SELECT 1;diff --git a/server/migrations/504_channel_reply_delivery_installation_index.up.sql b/server/migrations/504_channel_reply_delivery_installation_index.up.sqlnew file mode 100644index 0000000000..0155431c50--- /dev/null+++ b/server/migrations/504_channel_reply_delivery_installation_index.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_channel_reply_delivery_installation ON channel_reply_delivery (installation_id);diff --git a/server/migrations/505_channel_reply_delivery_binding_index.down.sql b/server/migrations/505_channel_reply_delivery_binding_index.down.sqlnew file mode 100644index 0000000000..6c45a01267--- /dev/null+++ b/server/migrations/505_channel_reply_delivery_binding_index.down.sql@@ -0,0 +1,2 @@+-- Retain the index the binding teardown paths delete through.+SELECT 1;diff --git a/server/migrations/505_channel_reply_delivery_binding_index.up.sql b/server/migrations/505_channel_reply_delivery_binding_index.up.sqlnew file mode 100644index 0000000000..9775b9a513--- /dev/null+++ b/server/migrations/505_channel_reply_delivery_binding_index.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_channel_reply_delivery_binding ON channel_reply_delivery (binding_id);diff --git a/server/migrations/506_channel_reply_delivery_attempt_depth.down.sql b/server/migrations/506_channel_reply_delivery_attempt_depth.down.sqlnew file mode 100644index 0000000000..e166698e16--- /dev/null+++ b/server/migrations/506_channel_reply_delivery_attempt_depth.down.sql@@ -0,0 +1,3 @@+-- Keep the column: an older binary ignores it, and dropping it would lose the+-- ordering that stops a superseded attempt from rewriting a live reply.+SELECT 1;diff --git a/server/migrations/506_channel_reply_delivery_attempt_depth.up.sql b/server/migrations/506_channel_reply_delivery_attempt_depth.up.sqlnew file mode 100644index 0000000000..d58df650df--- /dev/null+++ b/server/migrations/506_channel_reply_delivery_attempt_depth.up.sql@@ -0,0 +1,17 @@+-- How far down the retry chain the attempt holding a turn sits. Depth only+-- ever moves forward: once a retry has taken a turn over, a late frame from an+-- earlier attempt must not take it back and rewrite what the user is reading.+--+-- Its own migration rather than an edit to 500: a database that already+-- recorded 500 would never see a change made there, and every query touching+-- the column would fail on exactly the deployments this feature has already+-- been installed on. Written so a database created by 500 and one upgraded+-- through this file end up with the same schema.+ALTER TABLE channel_reply_delivery+ ADD COLUMN IF NOT EXISTS attempt_depth INTEGER NOT NULL DEFAULT 0;++ALTER TABLE channel_reply_delivery+ DROP CONSTRAINT IF EXISTS channel_reply_delivery_attempt_depth_check;++ALTER TABLE channel_reply_delivery+ ADD CONSTRAINT channel_reply_delivery_attempt_depth_check CHECK (attempt_depth >= 0);diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.goindex b4827224fa..df7204eb65 100644--- a/server/pkg/db/generated/channel.sql.go+++ b/server/pkg/db/generated/channel.sql.go@@ -11,6 +11,87 @@ import ("github.com/jackc/pgx/v5/pgtype")+const acquireChannelReplyDelivery = `-- name: AcquireChannelReplyDelivery :one+INSERT INTO channel_reply_delivery (+ turn_id, task_id, attempt_depth, binding_id, installation_id, channel_type, chat_id,+ phase, send_state, owner_token, owner_expires_at+) VALUES (+ $1, $2, $3, $4, $5, $6, $7,+ $8, 'none', $9, now() + make_interval(secs => $10::double precision)+)+ON CONFLICT (turn_id) DO UPDATE+SET task_id = EXCLUDED.task_id,+ attempt_depth = EXCLUDED.attempt_depth,+ phase = CASE WHEN EXCLUDED.phase = 'terminal' THEN 'terminal' ELSE channel_reply_delivery.phase END,+ owner_token = EXCLUDED.owner_token,+ owner_expires_at = EXCLUDED.owner_expires_at,+ updated_at = now()+WHERE channel_reply_delivery.phase <> 'settled'+ AND (channel_reply_delivery.owner_token IS NULL OR channel_reply_delivery.owner_expires_at <= now())+ AND NOT (EXCLUDED.phase = 'streaming' AND channel_reply_delivery.phase = 'terminal')+ -- An attempt the retry chain has already moved past may not take the turn+ -- back: its late frames would rewrite what the user is reading with content+ -- from a run that was superseded.+ AND EXCLUDED.attempt_depth >= channel_reply_delivery.attempt_depth+RETURNING turn_id, task_id, binding_id, installation_id, channel_type, chat_id, phase, send_state, message_id, chunks_sent, owner_token, owner_expires_at, settled_reason, created_at, updated_at, attempt_depth+`++type AcquireChannelReplyDeliveryParams struct {+ TurnID pgtype.UUID `json:"turn_id"`+ TaskID pgtype.UUID `json:"task_id"`+ AttemptDepth int32 `json:"attempt_depth"`+ BindingID pgtype.UUID `json:"binding_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ChannelType string `json:"channel_type"`+ ChatID string `json:"chat_id"`+ Phase string `json:"phase"`+ OwnerToken pgtype.UUID `json:"owner_token"`+ LeaseSeconds float64 `json:"lease_seconds"`+}++// Take the turn's delivery lease, creating the row on first use. Returns no+// row when the turn is settled, when a live owner holds it, or when a+// streaming path asks for a reply the final answer has taken over — the three+// cases where this caller must not touch the provider.+//+// An expired lease is a process that died mid-delivery. Its successor gets the+// turn, but never a clean slate: send_state survives, so an outstanding send+// stays outstanding rather than being silently retried.+func (q *Queries) AcquireChannelReplyDelivery(ctx context.Context, arg AcquireChannelReplyDeliveryParams) (ChannelReplyDelivery, error) {+ row := q.db.QueryRow(ctx, acquireChannelReplyDelivery,+ arg.TurnID,+ arg.TaskID,+ arg.AttemptDepth,+ arg.BindingID,+ arg.InstallationID,+ arg.ChannelType,+ arg.ChatID,+ arg.Phase,+ arg.OwnerToken,+ arg.LeaseSeconds,+ )+ var i ChannelReplyDelivery+ err := row.Scan(+ &i.TurnID,+ &i.TaskID,+ &i.BindingID,+ &i.InstallationID,+ &i.ChannelType,+ &i.ChatID,+ &i.Phase,+ &i.SendState,+ &i.MessageID,+ &i.ChunksSent,+ &i.OwnerToken,+ &i.OwnerExpiresAt,+ &i.SettledReason,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.AttemptDepth,+ )+ return i, err+}+const acquireChannelWSLease = `-- name: AcquireChannelWSLease :oneUPDATE channel_installationSET ws_lease_token = $1,@@ -460,6 +541,78 @@ func (q *Queries) ClearChannelInstallationBotScopedRows(ctx context.Context, insreturn i, err}+const closeChannelReplyDeliveryTurn = `-- name: CloseChannelReplyDeliveryTurn :one+INSERT INTO channel_reply_delivery (+ turn_id, task_id, attempt_depth, binding_id, installation_id, channel_type, chat_id,+ phase, send_state, settled_reason+) VALUES (+ $1, $2, $3, $4, $5, $6, $7,+ 'settled', 'none', $8+)+ON CONFLICT (turn_id) DO UPDATE+SET phase = 'settled',+ settled_reason = $8,+ owner_token = NULL,+ owner_expires_at = NULL,+ updated_at = now()+WHERE channel_reply_delivery.phase <> 'settled'+ AND (channel_reply_delivery.owner_token IS NULL OR channel_reply_delivery.owner_expires_at <= now())+ -- Same one-way rule the claim follows. A cancellation or empty completion+ -- belonging to an attempt the retry chain has moved past must not end the+ -- turn: the attempt that superseded it is still delivering, and its answer+ -- would be dropped as "already settled".+ AND EXCLUDED.attempt_depth >= channel_reply_delivery.attempt_depth+RETURNING turn_id, task_id, binding_id, installation_id, channel_type, chat_id, phase, send_state, message_id, chunks_sent, owner_token, owner_expires_at, settled_reason, created_at, updated_at, attempt_depth+`++type CloseChannelReplyDeliveryTurnParams struct {+ TurnID pgtype.UUID `json:"turn_id"`+ TaskID pgtype.UUID `json:"task_id"`+ AttemptDepth int32 `json:"attempt_depth"`+ BindingID pgtype.UUID `json:"binding_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ChannelType string `json:"channel_type"`+ ChatID string `json:"chat_id"`+ SettledReason string `json:"settled_reason"`+}++// End a turn that has no answer to deliver — cancelled, or completed empty —+// creating the row when the turn never reached the provider at all. Without+// the insert, a first text frame arriving after the cancellation would find+// nothing, open a placeholder, and leave it there forever.+func (q *Queries) CloseChannelReplyDeliveryTurn(ctx context.Context, arg CloseChannelReplyDeliveryTurnParams) (ChannelReplyDelivery, error) {+ row := q.db.QueryRow(ctx, closeChannelReplyDeliveryTurn,+ arg.TurnID,+ arg.TaskID,+ arg.AttemptDepth,+ arg.BindingID,+ arg.InstallationID,+ arg.ChannelType,+ arg.ChatID,+ arg.SettledReason,+ )+ var i ChannelReplyDelivery+ err := row.Scan(+ &i.TurnID,+ &i.TaskID,+ &i.BindingID,+ &i.InstallationID,+ &i.ChannelType,+ &i.ChatID,+ &i.Phase,+ &i.SendState,+ &i.MessageID,+ &i.ChunksSent,+ &i.OwnerToken,+ &i.OwnerExpiresAt,+ &i.SettledReason,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.AttemptDepth,+ )+ return i, err+}+const consumeChannelBindingToken = `-- name: ConsumeChannelBindingToken :oneUPDATE channel_binding_tokenSET consumed_at = now()@@ -975,6 +1128,8 @@ WITH target AS (DELETE FROM channel_task_delivery AS delivery WHERE delivery.binding_id IN (SELECT id FROM target)), cleared_outbound AS (DELETE FROM channel_outbound_message AS outbound WHERE outbound.binding_id IN (SELECT id FROM target)+), cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery AS reply WHERE reply.binding_id IN (SELECT id FROM target)), deleted_binding AS (DELETE FROM channel_chat_session_binding AS binding WHERE binding.id IN (SELECT id FROM target))@@ -999,6 +1154,10 @@ WITH cleared_deliveries AS (DELETE FROM channel_outbound_message AS outboundWHERE outbound.installation_id = $1AND outbound.channel_type = $2+), cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery AS reply+ WHERE reply.installation_id = $1+ AND reply.channel_type = $2)DELETE FROM channel_chat_session_binding AS bindingWHERE binding.installation_id = $1@@ -1046,6 +1205,9 @@ cleared_dingtalk_bot_identity AS (cleared_dingtalk_group_routes AS (DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)),+cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery WHERE installation_id IN (SELECT id FROM doomed)+),cleared_task_deliveries AS (DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM doomed)),@@ -1701,6 +1863,76 @@ func (q *Queries) GetChannelOutboundCardByTask(ctx context.Context, arg GetChannreturn i, err}+const getChannelReplyDelivery = `-- name: GetChannelReplyDelivery :one+SELECT turn_id, task_id, binding_id, installation_id, channel_type, chat_id, phase, send_state, message_id, chunks_sent, owner_token, owner_expires_at, settled_reason, created_at, updated_at, attempt_depth FROM channel_reply_delivery WHERE turn_id = $1+`++// Read without taking the lease, so a caller that lost the race can tell+// "someone else is working on it" from "this turn is finished".+func (q *Queries) GetChannelReplyDelivery(ctx context.Context, turnID pgtype.UUID) (ChannelReplyDelivery, error) {+ row := q.db.QueryRow(ctx, getChannelReplyDelivery, turnID)+ var i ChannelReplyDelivery+ err := row.Scan(+ &i.TurnID,+ &i.TaskID,+ &i.BindingID,+ &i.InstallationID,+ &i.ChannelType,+ &i.ChatID,+ &i.Phase,+ &i.SendState,+ &i.MessageID,+ &i.ChunksSent,+ &i.OwnerToken,+ &i.OwnerExpiresAt,+ &i.SettledReason,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.AttemptDepth,+ )+ return i, err+}++const getChannelReplyTurn = `-- name: GetChannelReplyTurn :one++WITH RECURSIVE chain(task_id, parent_task_id, depth) AS (+ SELECT attempt.id, attempt.retry_of_task_id, 0+ FROM agent_task_queue attempt+ WHERE attempt.id = $1+ UNION ALL+ SELECT parent.id, parent.retry_of_task_id, chain.depth + 1+ FROM agent_task_queue parent+ JOIN chain ON parent.id = chain.parent_task_id+)+SELECT+ (SELECT root.task_id FROM chain root WHERE root.parent_task_id IS NULL LIMIT 1) AS turn_id,+ (SELECT COALESCE(MAX(step.depth), 0) FROM chain step)::int AS attempt_depth+`++type GetChannelReplyTurnRow struct {+ TurnID pgtype.UUID `json:"turn_id"`+ AttemptDepth int32 `json:"attempt_depth"`+}++// ---------------------------------------------------------------------------+// Reply delivery ownership (channel_reply_delivery).+//+// One user turn, one owner, one reply. Every path that can put a message in a+// chat proves it holds the turn's lease before it calls the provider, and+// proves it still holds the lease when it records what happened.+// ---------------------------------------------------------------------------+// The root of a task's automatic-retry chain — the user turn all its attempts+// belong to — and how far down the chain this attempt sits. A retry runs under+// a new task id and must finish the reply its previous attempt started, so+// ownership is keyed by the root; depth is what stops an earlier attempt's late+// frame from taking the turn back off the retry that superseded it.+func (q *Queries) GetChannelReplyTurn(ctx context.Context, id pgtype.UUID) (GetChannelReplyTurnRow, error) {+ row := q.db.QueryRow(ctx, getChannelReplyTurn, id)+ var i GetChannelReplyTurnRow+ err := row.Scan(&i.TurnID, &i.AttemptDepth)+ return i, err+}+const getChannelTaskDelivery = `-- name: GetChannelTaskDelivery :oneSELECT task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, channel_message_id, channel_thread_id, route_revision, config, created_at, channel_sender_id FROM channel_task_delivery WHERE task_id = $1`@@ -2286,6 +2518,46 @@ func (q *Queries) MarkChannelInboundDedupProcessed(ctx context.Context, arg Markreturn result.RowsAffected(), nil}+const markChannelReplyDeliverySendUnknown = `-- name: MarkChannelReplyDeliverySendUnknown :execrows+UPDATE channel_reply_delivery+SET send_state = 'unknown', updated_at = now()+WHERE turn_id = $1 AND send_state = 'in_flight'+`++// The response was lost. Recorded without the owner check: this is the write+// that must survive a caller whose lease expired while its own request hung,+// because the alternative is a successor assuming nothing was ever sent.+func (q *Queries) MarkChannelReplyDeliverySendUnknown(ctx context.Context, turnID pgtype.UUID) (int64, error) {+ result, err := q.db.Exec(ctx, markChannelReplyDeliverySendUnknown, turnID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const markChannelReplyDeliverySending = `-- name: MarkChannelReplyDeliverySending :execrows+UPDATE channel_reply_delivery+SET send_state = 'in_flight', updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND send_state NOT IN ('in_flight', 'unknown')+`++type MarkChannelReplyDeliverySendingParams struct {+ TurnID pgtype.UUID `json:"turn_id"`+ OwnerToken pgtype.UUID `json:"owner_token"`+}++// Publish a send before making it, so any other process reads "a send is+// outstanding" rather than "nothing has been sent". A resolved earlier send+// does not block the next part of a multi-part answer; an unresolved one does,+// because that is the case where nobody knows what is already in the chat.+func (q *Queries) MarkChannelReplyDeliverySending(ctx context.Context, arg MarkChannelReplyDeliverySendingParams) (int64, error) {+ result, err := q.db.Exec(ctx, markChannelReplyDeliverySending, arg.TurnID, arg.OwnerToken)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const nullChannelInboundAuditInstallationID = `-- name: NullChannelInboundAuditInstallationID :execUPDATE channel_inbound_auditSET installation_id = NULL@@ -2353,6 +2625,9 @@ cleared_task_deliveries AS (cleared_outbound_messages AS (DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM dead)),+cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery WHERE installation_id IN (SELECT id FROM dead)+),cleared_chat_sessions AS (DELETE FROM channel_chat_session_bindingWHERE installation_id IN (SELECT id FROM dead)@@ -2584,6 +2859,59 @@ func (q *Queries) RecordChannelOutboundMessage(ctx context.Context, arg RecordChreturn err}+const recordChannelReplyDeliveryChunk = `-- name: RecordChannelReplyDeliveryChunk :execrows+UPDATE channel_reply_delivery+SET send_state = 'known',+ message_id = CASE WHEN message_id = '' THEN $1::text ELSE message_id END,+ chunks_sent = GREATEST(chunks_sent, $2::int),+ updated_at = now()+WHERE turn_id = $3 AND owner_token = $4+`++type RecordChannelReplyDeliveryChunkParams struct {+ MessageID string `json:"message_id"`+ ChunksSent int32 `json:"chunks_sent"`+ TurnID pgtype.UUID `json:"turn_id"`+ OwnerToken pgtype.UUID `json:"owner_token"`+}++// A part of the final answer landed. message_id is only adopted when the turn+// has no editable message yet, so later parts never retarget the first one.+func (q *Queries) RecordChannelReplyDeliveryChunk(ctx context.Context, arg RecordChannelReplyDeliveryChunkParams) (int64, error) {+ result, err := q.db.Exec(ctx, recordChannelReplyDeliveryChunk,+ arg.MessageID,+ arg.ChunksSent,+ arg.TurnID,+ arg.OwnerToken,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const recordChannelReplyDeliveryPlaceholder = `-- name: RecordChannelReplyDeliveryPlaceholder :execrows+UPDATE channel_reply_delivery+SET send_state = 'known', message_id = $3, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND send_state = 'in_flight'+`++type RecordChannelReplyDeliveryPlaceholderParams struct {+ TurnID pgtype.UUID `json:"turn_id"`+ OwnerToken pgtype.UUID `json:"owner_token"`+ MessageID string `json:"message_id"`+}++// The placeholder landed. It gives the turn an editable message; it delivers+// no part of the final answer, so chunks_sent stays where it is.+func (q *Queries) RecordChannelReplyDeliveryPlaceholder(ctx context.Context, arg RecordChannelReplyDeliveryPlaceholderParams) (int64, error) {+ result, err := q.db.Exec(ctx, recordChannelReplyDeliveryPlaceholder, arg.TurnID, arg.OwnerToken, arg.MessageID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const releaseChannelInboundDedup = `-- name: ReleaseChannelInboundDedup :execrowsDELETE FROM channel_inbound_message_dedupWHERE installation_id = $1@@ -2644,6 +2972,26 @@ func (q *Queries) ReleaseChannelMediaPendingObject(ctx context.Context, arg Relereturn err}+const releaseChannelReplyDelivery = `-- name: ReleaseChannelReplyDelivery :execrows+UPDATE channel_reply_delivery+SET owner_token = NULL, owner_expires_at = NULL, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2+`++type ReleaseChannelReplyDeliveryParams struct {+ TurnID pgtype.UUID `json:"turn_id"`+ OwnerToken pgtype.UUID `json:"owner_token"`+}++// Hand the turn back so the next path does not wait out the lease.+func (q *Queries) ReleaseChannelReplyDelivery(ctx context.Context, arg ReleaseChannelReplyDeliveryParams) (int64, error) {+ result, err := q.db.Exec(ctx, releaseChannelReplyDelivery, arg.TurnID, arg.OwnerToken)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const releaseChannelWSLease = `-- name: ReleaseChannelWSLease :execUPDATE channel_installationSET ws_lease_token = NULL,@@ -2664,6 +3012,52 @@ func (q *Queries) ReleaseChannelWSLease(ctx context.Context, arg ReleaseChannelWreturn err}+const renewChannelReplyDelivery = `-- name: RenewChannelReplyDelivery :execrows+UPDATE channel_reply_delivery+SET owner_expires_at = now() + make_interval(secs => $1::double precision), updated_at = now()+WHERE turn_id = $2 AND owner_token = $3 AND phase <> 'settled'+`++type RenewChannelReplyDeliveryParams struct {+ LeaseSeconds float64 `json:"lease_seconds"`+ TurnID pgtype.UUID `json:"turn_id"`+ OwnerToken pgtype.UUID `json:"owner_token"`+}++// Prove the turn is still ours and push the lease out. Terminal delivery holds+// a turn across several scheduler rounds — edit pacing, a 429 backoff — so it+// re-proves ownership before each Telegram call rather than trusting a lease+// taken minutes earlier. No rows means another process took the turn over, and+// this one must stop.+func (q *Queries) RenewChannelReplyDelivery(ctx context.Context, arg RenewChannelReplyDeliveryParams) (int64, error) {+ result, err := q.db.Exec(ctx, renewChannelReplyDelivery, arg.LeaseSeconds, arg.TurnID, arg.OwnerToken)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const resetChannelReplyDeliverySend = `-- name: ResetChannelReplyDeliverySend :execrows+UPDATE channel_reply_delivery+SET send_state = CASE WHEN message_id = '' THEN 'none' ELSE 'known' END, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND send_state = 'in_flight'+`++type ResetChannelReplyDeliverySendParams struct {+ TurnID pgtype.UUID `json:"turn_id"`+ OwnerToken pgtype.UUID `json:"owner_token"`+}++// The provider answered and refused: nothing is in the chat, so the turn may+// be attempted again.+func (q *Queries) ResetChannelReplyDeliverySend(ctx context.Context, arg ResetChannelReplyDeliverySendParams) (int64, error) {+ result, err := q.db.Exec(ctx, resetChannelReplyDeliverySend, arg.TurnID, arg.OwnerToken)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const resolveChannelChatContextHistoryStart = `-- name: ResolveChannelChatContextHistoryStart :execUPDATE channel_chat_context_generationSET history_start_message_id = $1,@@ -2819,6 +3213,27 @@ func (q *Queries) SetChannelInstallationStatus(ctx context.Context, arg SetChannreturn err}+const settleChannelReplyDelivery = `-- name: SettleChannelReplyDelivery :execrows+UPDATE channel_reply_delivery+SET phase = 'settled', settled_reason = $3, owner_token = NULL, owner_expires_at = NULL, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND phase <> 'settled'+`++type SettleChannelReplyDeliveryParams struct {+ TurnID pgtype.UUID `json:"turn_id"`+ OwnerToken pgtype.UUID `json:"owner_token"`+ SettledReason string `json:"settled_reason"`+}++// Delivery is over. Nothing sends or edits for this turn afterwards.+func (q *Queries) SettleChannelReplyDelivery(ctx context.Context, arg SettleChannelReplyDeliveryParams) (int64, error) {+ result, err := q.db.Exec(ctx, settleChannelReplyDelivery, arg.TurnID, arg.OwnerToken, arg.SettledReason)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const tombstoneChannelMediaPendingObject = `-- name: TombstoneChannelMediaPendingObject :execrowsUPDATE channel_media_pending_objectSET state = 'tombstoned',diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 54b24b4377..067434ef0a 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -440,6 +440,25 @@ type ChannelOutboundMessage struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type ChannelReplyDelivery struct {+ TurnID pgtype.UUID `json:"turn_id"`+ TaskID pgtype.UUID `json:"task_id"`+ BindingID pgtype.UUID `json:"binding_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ChannelType string `json:"channel_type"`+ ChatID string `json:"chat_id"`+ Phase string `json:"phase"`+ SendState string `json:"send_state"`+ MessageID string `json:"message_id"`+ ChunksSent int32 `json:"chunks_sent"`+ OwnerToken pgtype.UUID `json:"owner_token"`+ OwnerExpiresAt pgtype.Timestamptz `json:"owner_expires_at"`+ SettledReason string `json:"settled_reason"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ AttemptDepth int32 `json:"attempt_depth"`+}+type ChannelTaskDelivery struct {TaskID pgtype.UUID `json:"task_id"`BindingID pgtype.UUID `json:"binding_id"`diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex e011c8f882..224775b994 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -77,6 +77,9 @@ cleared_channel_task_deliveries AS (cleared_channel_outbound_messages AS (DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM ws_installations)),+cleared_channel_reply_deliveries AS (+ DELETE FROM channel_reply_delivery WHERE installation_id IN (SELECT id FROM ws_installations)+),cleared_chat_sessions AS (DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)RETURNING chat_session_iddiff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 203fcd7d3a..90db014839 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -418,6 +418,10 @@ deleted_channel_outbound_messages AS (DELETE FROM channel_outbound_messageWHERE installation_id IN (SELECT id FROM ws_channel_installations)),+deleted_channel_reply_deliveries AS (+ DELETE FROM channel_reply_delivery+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)+),deleted_channel_chat_contexts AS (DELETE FROM channel_chat_context_generationWHERE chat_session_id IN (SELECT id FROM ws_sessions)diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sqlindex a8be4a31d5..775844130a 100644--- a/server/pkg/db/queries/channel.sql+++ b/server/pkg/db/queries/channel.sql@@ -219,6 +219,9 @@ cleared_task_deliveries AS (cleared_outbound_messages AS (DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM dead)),+cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery WHERE installation_id IN (SELECT id FROM dead)+),cleared_chat_sessions AS (DELETE FROM channel_chat_session_bindingWHERE installation_id IN (SELECT id FROM dead)@@ -373,6 +376,9 @@ cleared_dingtalk_bot_identity AS (cleared_dingtalk_group_routes AS (DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)),+cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery WHERE installation_id IN (SELECT id FROM doomed)+),cleared_task_deliveries AS (DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM doomed)),@@ -882,6 +888,8 @@ WITH target AS (DELETE FROM channel_task_delivery AS delivery WHERE delivery.binding_id IN (SELECT id FROM target)), cleared_outbound AS (DELETE FROM channel_outbound_message AS outbound WHERE outbound.binding_id IN (SELECT id FROM target)+), cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery AS reply WHERE reply.binding_id IN (SELECT id FROM target)), deleted_binding AS (DELETE FROM channel_chat_session_binding AS binding WHERE binding.id IN (SELECT id FROM target))@@ -906,6 +914,10 @@ WITH cleared_deliveries AS (DELETE FROM channel_outbound_message AS outboundWHERE outbound.installation_id = sqlc.arg('installation_id')AND outbound.channel_type = sqlc.arg('channel_type')+), cleared_reply_deliveries AS (+ DELETE FROM channel_reply_delivery AS reply+ WHERE reply.installation_id = sqlc.arg('installation_id')+ AND reply.channel_type = sqlc.arg('channel_type'))DELETE FROM channel_chat_session_binding AS bindingWHERE binding.installation_id = sqlc.arg('installation_id')@@ -1352,3 +1364,157 @@ SELECT EXISTS (AND workspace_id = @workspace_idAND url = @storage_url) AS referenced;++-- ---------------------------------------------------------------------------+-- Reply delivery ownership (channel_reply_delivery).+--+-- One user turn, one owner, one reply. Every path that can put a message in a+-- chat proves it holds the turn's lease before it calls the provider, and+-- proves it still holds the lease when it records what happened.+-- ---------------------------------------------------------------------------++-- name: GetChannelReplyTurn :one+-- The root of a task's automatic-retry chain — the user turn all its attempts+-- belong to — and how far down the chain this attempt sits. A retry runs under+-- a new task id and must finish the reply its previous attempt started, so+-- ownership is keyed by the root; depth is what stops an earlier attempt's late+-- frame from taking the turn back off the retry that superseded it.+WITH RECURSIVE chain(task_id, parent_task_id, depth) AS (+ SELECT attempt.id, attempt.retry_of_task_id, 0+ FROM agent_task_queue attempt+ WHERE attempt.id = $1+ UNION ALL+ SELECT parent.id, parent.retry_of_task_id, chain.depth + 1+ FROM agent_task_queue parent+ JOIN chain ON parent.id = chain.parent_task_id+)+SELECT+ (SELECT root.task_id FROM chain root WHERE root.parent_task_id IS NULL LIMIT 1) AS turn_id,+ (SELECT COALESCE(MAX(step.depth), 0) FROM chain step)::int AS attempt_depth;++-- name: AcquireChannelReplyDelivery :one+-- Take the turn's delivery lease, creating the row on first use. Returns no+-- row when the turn is settled, when a live owner holds it, or when a+-- streaming path asks for a reply the final answer has taken over — the three+-- cases where this caller must not touch the provider.+--+-- An expired lease is a process that died mid-delivery. Its successor gets the+-- turn, but never a clean slate: send_state survives, so an outstanding send+-- stays outstanding rather than being silently retried.+INSERT INTO channel_reply_delivery (+ turn_id, task_id, attempt_depth, binding_id, installation_id, channel_type, chat_id,+ phase, send_state, owner_token, owner_expires_at+) VALUES (+ @turn_id, @task_id, @attempt_depth, @binding_id, @installation_id, @channel_type, @chat_id,+ @phase, 'none', @owner_token, now() + make_interval(secs => @lease_seconds::double precision)+)+ON CONFLICT (turn_id) DO UPDATE+SET task_id = EXCLUDED.task_id,+ attempt_depth = EXCLUDED.attempt_depth,+ phase = CASE WHEN EXCLUDED.phase = 'terminal' THEN 'terminal' ELSE channel_reply_delivery.phase END,+ owner_token = EXCLUDED.owner_token,+ owner_expires_at = EXCLUDED.owner_expires_at,+ updated_at = now()+WHERE channel_reply_delivery.phase <> 'settled'+ AND (channel_reply_delivery.owner_token IS NULL OR channel_reply_delivery.owner_expires_at <= now())+ AND NOT (EXCLUDED.phase = 'streaming' AND channel_reply_delivery.phase = 'terminal')+ -- An attempt the retry chain has already moved past may not take the turn+ -- back: its late frames would rewrite what the user is reading with content+ -- from a run that was superseded.+ AND EXCLUDED.attempt_depth >= channel_reply_delivery.attempt_depth+RETURNING *;++-- name: GetChannelReplyDelivery :one+-- Read without taking the lease, so a caller that lost the race can tell+-- "someone else is working on it" from "this turn is finished".+SELECT * FROM channel_reply_delivery WHERE turn_id = $1;++-- name: ReleaseChannelReplyDelivery :execrows+-- Hand the turn back so the next path does not wait out the lease.+UPDATE channel_reply_delivery+SET owner_token = NULL, owner_expires_at = NULL, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2;++-- name: RenewChannelReplyDelivery :execrows+-- Prove the turn is still ours and push the lease out. Terminal delivery holds+-- a turn across several scheduler rounds — edit pacing, a 429 backoff — so it+-- re-proves ownership before each Telegram call rather than trusting a lease+-- taken minutes earlier. No rows means another process took the turn over, and+-- this one must stop.+UPDATE channel_reply_delivery+SET owner_expires_at = now() + make_interval(secs => sqlc.arg(lease_seconds)::double precision), updated_at = now()+WHERE turn_id = sqlc.arg(turn_id) AND owner_token = sqlc.arg(owner_token) AND phase <> 'settled';++-- name: MarkChannelReplyDeliverySending :execrows+-- Publish a send before making it, so any other process reads "a send is+-- outstanding" rather than "nothing has been sent". A resolved earlier send+-- does not block the next part of a multi-part answer; an unresolved one does,+-- because that is the case where nobody knows what is already in the chat.+UPDATE channel_reply_delivery+SET send_state = 'in_flight', updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND send_state NOT IN ('in_flight', 'unknown');++-- name: RecordChannelReplyDeliveryPlaceholder :execrows+-- The placeholder landed. It gives the turn an editable message; it delivers+-- no part of the final answer, so chunks_sent stays where it is.+UPDATE channel_reply_delivery+SET send_state = 'known', message_id = $3, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND send_state = 'in_flight';++-- name: RecordChannelReplyDeliveryChunk :execrows+-- A part of the final answer landed. message_id is only adopted when the turn+-- has no editable message yet, so later parts never retarget the first one.+UPDATE channel_reply_delivery+SET send_state = 'known',+ message_id = CASE WHEN message_id = '' THEN sqlc.arg(message_id)::text ELSE message_id END,+ chunks_sent = GREATEST(chunks_sent, sqlc.arg(chunks_sent)::int),+ updated_at = now()+WHERE turn_id = sqlc.arg(turn_id) AND owner_token = sqlc.arg(owner_token);++-- name: ResetChannelReplyDeliverySend :execrows+-- The provider answered and refused: nothing is in the chat, so the turn may+-- be attempted again.+UPDATE channel_reply_delivery+SET send_state = CASE WHEN message_id = '' THEN 'none' ELSE 'known' END, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND send_state = 'in_flight';++-- name: MarkChannelReplyDeliverySendUnknown :execrows+-- The response was lost. Recorded without the owner check: this is the write+-- that must survive a caller whose lease expired while its own request hung,+-- because the alternative is a successor assuming nothing was ever sent.+UPDATE channel_reply_delivery+SET send_state = 'unknown', updated_at = now()+WHERE turn_id = $1 AND send_state = 'in_flight';++-- name: SettleChannelReplyDelivery :execrows+-- Delivery is over. Nothing sends or edits for this turn afterwards.+UPDATE channel_reply_delivery+SET phase = 'settled', settled_reason = $3, owner_token = NULL, owner_expires_at = NULL, updated_at = now()+WHERE turn_id = $1 AND owner_token = $2 AND phase <> 'settled';++-- name: CloseChannelReplyDeliveryTurn :one+-- End a turn that has no answer to deliver — cancelled, or completed empty —+-- creating the row when the turn never reached the provider at all. Without+-- the insert, a first text frame arriving after the cancellation would find+-- nothing, open a placeholder, and leave it there forever.+INSERT INTO channel_reply_delivery (+ turn_id, task_id, attempt_depth, binding_id, installation_id, channel_type, chat_id,+ phase, send_state, settled_reason+) VALUES (+ @turn_id, @task_id, @attempt_depth, @binding_id, @installation_id, @channel_type, @chat_id,+ 'settled', 'none', @settled_reason+)+ON CONFLICT (turn_id) DO UPDATE+SET phase = 'settled',+ settled_reason = @settled_reason,+ owner_token = NULL,+ owner_expires_at = NULL,+ updated_at = now()+WHERE channel_reply_delivery.phase <> 'settled'+ AND (channel_reply_delivery.owner_token IS NULL OR channel_reply_delivery.owner_expires_at <= now())+ -- Same one-way rule the claim follows. A cancellation or empty completion+ -- belonging to an attempt the retry chain has moved past must not end the+ -- turn: the attempt that superseded it is still delivering, and its answer+ -- would be dropped as "already settled".+ AND EXCLUDED.attempt_depth >= channel_reply_delivery.attempt_depth+RETURNING *;diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex 5922db914e..d86ac43f1a 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -120,6 +120,9 @@ cleared_channel_task_deliveries AS (cleared_channel_outbound_messages AS (DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM ws_installations)),+cleared_channel_reply_deliveries AS (+ DELETE FROM channel_reply_delivery WHERE installation_id IN (SELECT id FROM ws_installations)+),cleared_chat_sessions AS (DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)RETURNING chat_session_iddiff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex fad5152cc4..49d8876ff0 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -438,6 +438,10 @@ deleted_channel_outbound_messages AS (DELETE FROM channel_outbound_messageWHERE installation_id IN (SELECT id FROM ws_channel_installations)),+deleted_channel_reply_deliveries AS (+ DELETE FROM channel_reply_delivery+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)+),deleted_channel_chat_contexts AS (DELETE FROM channel_chat_context_generationWHERE chat_session_id IN (SELECT id FROM ws_sessions)