Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
79.1 KB
Raw Blame
package wecom

// Relay completions to the replica holding the bot's WebSocket lease.
// Redis claims keyed by turn deduplicate replay across restarts and replicas.
//
// Relay consumers run on the shard reader, so enqueue bounded work and return
// without waiting for platform acknowledgements. Register before readers start;
// Attach supplies the eventual handler while early frames wait in the queue.
//
// Preserve per-installation order across re-offers by retrying at the queue head.
// Hashed shards bound concurrency, not isolation: colliding installations can
// still wait behind each other.

import (
	"context"
	"encoding/json"
	"errors"
	"hash/fnv"
	"log/slog"
	"sync"
	"sync/atomic"
	"time"

	"github.com/jackc/pgx/v5/pgtype"

	"github.com/multica-ai/multica/server/internal/events"
	"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
	"github.com/multica-ai/multica/server/internal/realtime"
	"github.com/multica-ai/multica/server/internal/util"
)

// relayPublisher is the slice of the realtime relay this package needs.
// *realtime.ShardedStreamRelay and *realtime.RedisRelay both satisfy it.
type relayPublisher interface {
	PublishWithID(scopeType, scopeID, exclude string, frame []byte, id string) error
}

// DedupeStore is the at-most-once claim that spans a restart and two replicas.
// Backed by Redis in production (see NewRedisDedupe); nil leaves only the
// in-process gate, which is correct for a single-replica deployment because
// there the relay is never used at all.
type DedupeStore interface {
	// Claim takes key for token, or re-takes it when key already holds
	// token — the same owner coming back after a Release whose result was
	// unknown. Atomic across processes. The token is what makes every other
	// operation here safe to retry: a re-sent command can never act on a
	// claim that a later owner has since taken.
	Claim(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
	// Release gives back the claim held under token, for a delivery that
	// provably did not happen: a compare-and-delete. false with a nil error
	// means the key no longer holds token — the delete already landed, the
	// claim expired, or somebody else holds it now — and is not a failure.
	// A non-nil error means the OUTCOME IS UNKNOWN: the delete may or may
	// not have landed. The caller must not read it as either.
	Release(ctx context.Context, key, token string) (bool, error)
	// Settle marks the claim held under token as settled: its holder is about
	// to record the delivery's outcome. false means the key no longer holds
	// token — the publisher already resolved it as lost, or it expired — and
	// the holder must then record nothing, so the reply ends with one record.
	// Settling an already-settled claim reports true (a retry is safe).
	Settle(ctx context.Context, key, token string) (bool, error)
	// Resolve is the publisher's end-of-grace read, and its fence: a claim
	// still held by a token at that point is turned into claimLost in the
	// same operation, so a holder that comes back later finds its Settle
	// refused and records nothing. See RelayOutbound.settle.
	Resolve(ctx context.Context, key string) (claimState, error)
	// ClaimState is Resolve WITHOUT the fence: it reports what the key holds
	// right now and changes nothing. It is what an inbox publish polls while it
	// waits to see whether a replica took the delivery; Resolve would fence a
	// holder that is merely mid-delivery. See RelayOutbound.confirmInbox.
	ClaimState(ctx context.Context, key string) (claimState, error)
	// ClaimBudget is the longest ONE round trip above may take. The store
	// states it because the store enforces it: outcomeGrace pays this budget
	// once per offer, and a copy of the number kept by the dispatcher would be
	// free to drift from the timeout actually applied.
	ClaimBudget() time.Duration
}

// minDedupeTTL floors the claim lifetime. The invariant the claim upholds is
// that it outlives the relay's replay window — a claim that expires while the
// frame is still replayable is not a claim — and that window is an OPERATOR
// KNOB (REALTIME_RELAY_REPLAY_GRACE), not a constant, so the TTL cannot be one
// either: a 2h grace against a fixed 1h TTL would re-send an answer the user
// already read on any restart between the two. dedupeTTLFor derives it.
const minDedupeTTL = time.Hour

// dedupeTTLFor is max(minDedupeTTL, 2×replayGrace): twice the grace so a claim
// comfortably outlives the window it guards, floored so a tiny grace does not
// produce a claim shorter than the hour the default always had.
func dedupeTTLFor(replayGrace time.Duration) time.Duration {
	if ttl := 2 * replayGrace; ttl > minDedupeTTL {
		return ttl
	}
	return minDedupeTTL
}

// RelayConfig sizes the dispatcher. None of these is a taste: each one has an
// operational bound behind it, named in its comment, and the two whose bound
// lives OUTSIDE this package are passed in rather than guessed — the relay's
// replay window and the supervisor's lease poll interval.
//
// A zero field takes its documented default.
type RelayConfig struct {
	// DeliveryBudget is the longest one delivery attempt may take once it
	// holds the claim, and it bounds the WHOLE logical delivery: the wait for
	// the target chat's turn, and every piece a long answer is split into with
	// its own ack wait. Zero means ackTimeout.
	//
	// One budget for all of it, because that is what the publisher's outcome
	// grace reserves for one offer (outcomeGrace) — a grace sized for one ack
	// while the delivery waits for several is a Resolve that fences a reply
	// its holder is still writing.
	//
	// The grace charges it PER OFFER, not once for the chain: an offer that
	// fails provably-unsent hands the claim back, so the next offer starts
	// with a budget of its own. Lowering it therefore shortens the grace
	// twelve-fold on the defaults, which is why tests that wait a grace out
	// shrink it along with the claim budget and the lease settle.
	DeliveryBudget time.Duration

	// Shards is how many independent queues carry frames, and it is a
	// concurrency bound rather than an ordering one: ordering comes from the
	// hash putting one installation on one queue, and installations that
	// collide on a shard DO wait behind each other. The number to size against
	// is therefore how many bots may be slow at once before a healthy one
	// queues behind them. Eight covers a deployment's worth of bots against
	// the one thing that makes a delivery slow — ackTimeout, 5s — while
	// keeping eight idle goroutines rather than one per installation.
	Shards int

	// QueueDepth is per shard, and the burst it must absorb is a restart's
	// replay: the shard reader opens at (now - ReplayGrace) and hands over
	// everything published in that window at once. 256 per shard is 2048
	// frames in flight across the default eight — more than a replay window
	// of WeCom answers can hold for one deployment, and small enough that a
	// wedged bot sheds instead of growing the heap without bound.
	QueueDepth int

	// DrainBudget bounds the WHOLE post-shutdown drain, not one delivery.
	// Its bound is external: the drain runs inside the process's own
	// shutdown, so it must fit under the channel supervisor's ShutdownTimeout
	// (engine.Config, 15s by default) with room for the supervisor's own
	// join. Ten seconds is that fit; whatever misses it is left to the claim
	// TTL and the next replica's replay window.
	DrainBudget time.Duration

	// ReplayGrace is the relay's configured startup lookback. It sizes the
	// claim TTL (dedupeTTLFor) and it is an operator knob
	// (REALTIME_RELAY_REPLAY_GRACE), which is exactly why it is a parameter.
	ReplayGrace time.Duration

	// LeaseSettle is how long a WebSocket lease takes to finish moving to
	// another replica, and it sizes the retry chain. Its bound is the channel
	// supervisor's PollInterval (CHANNEL_WS_LEASE_POLL_INTERVAL, 30s by
	// default): a replica learns it should hold an installation on its next
	// sweep, so a frame that arrives mid-move has to be re-offered for at
	// least that long or it is given up on while the holder is still on its
	// way. The previous fixed five attempts at 200ms covered three seconds —
	// a tenth of one poll — and expired long before the move it existed for.
	LeaseSettle time.Duration

	// AcceptanceWindow is how long an inbox publish waits to see a replica take
	// the delivery claim before it concludes that nobody holds that bot's
	// socket. Its bound is the frame's trip to every replica's dispatcher plus
	// one claim round trip (DedupeStore.ClaimBudget), NOT the re-offer chain
	// the reply path's outcomeGrace outlasts: an inbox frame nobody claimed has
	// no chain behind it, so waiting the chain out would only delay the
	// fallback. Zero takes defaultRelayAcceptanceWindow.
	AcceptanceWindow time.Duration

	// RetryBackoff is the FIRST wait between re-offers; the chain doubles from
	// there, capped at a quarter of LeaseSettle so a lease that lands early is
	// not sat out. Small on purpose: the common reason a re-offer succeeds is
	// that the move has already finished.
	RetryBackoff time.Duration
}

const (
	defaultRelayShards      = 8
	defaultRelayQueueDepth  = 256
	defaultRelayDrainBudget = 10 * time.Second
	// defaultRelayLeaseSettle is the supervisor's own default poll interval,
	// referenced rather than repeated: it is the same quantity, and a copy
	// here would be free to drift from the thing it is meant to outlast.
	defaultRelayLeaseSettle  = engine.DefaultPollInterval
	defaultRelayRetryBackoff = 200 * time.Millisecond
	// defaultRelayAcceptanceWindow matches defaultClaimBudget: one claim round
	// trip plus room for the bus fan-out and a dispatcher's turn. The two live
	// in different files on purpose — this is the relay's bound on how long it
	// will wait, that is the store's bound on how long one call may take.
	defaultRelayAcceptanceWindow = 2 * time.Second
)

// withDefaults fills the zero fields and returns the completed config.
// deliveryBudget is DeliveryBudget with its default applied.
func (c RelayConfig) deliveryBudget() time.Duration {
	if c.DeliveryBudget > 0 {
		return c.DeliveryBudget
	}
	return ackTimeout
}

func (c RelayConfig) withDefaults() RelayConfig {
	if c.Shards <= 0 {
		c.Shards = defaultRelayShards
	}
	if c.QueueDepth <= 0 {
		c.QueueDepth = defaultRelayQueueDepth
	}
	if c.DrainBudget <= 0 {
		c.DrainBudget = defaultRelayDrainBudget
	}
	if c.LeaseSettle <= 0 {
		c.LeaseSettle = defaultRelayLeaseSettle
	}
	if c.RetryBackoff <= 0 {
		c.RetryBackoff = defaultRelayRetryBackoff
	}
	if c.AcceptanceWindow <= 0 {
		c.AcceptanceWindow = defaultRelayAcceptanceWindow
	}
	return c
}

// retryPlan is the re-offer chain, computed once from the settle window rather
// than written down: delays double from RetryBackoff, each capped at a quarter
// of LeaseSettle, and the chain is long enough that its TOTAL covers one and a
// half settle windows — the move itself, plus half of one for the reconnect
// and subscribe that follow it.
//
// Bounded twice over so a pathological config cannot produce an unbounded
// chain: at most relayRetryChainCap entries.
const relayRetryChainCap = 24

func (c RelayConfig) retryPlan() []time.Duration {
	target := c.LeaseSettle + c.LeaseSettle/2
	cap := c.LeaseSettle / 4
	if cap < c.RetryBackoff {
		cap = c.RetryBackoff
	}
	var (
		plan  []time.Duration
		total time.Duration
		delay = c.RetryBackoff
	)
	for total < target && len(plan) < relayRetryChainCap {
		if delay > cap {
			delay = cap
		}
		plan = append(plan, delay)
		total += delay
		delay *= 2
	}
	return plan
}

// relayFrame is one delivery in transit between replicas. It carries
// identifiers rather than rendered payloads for anything the lease holder can
// read for itself, so an attachment is fetched by the replica that will send
// it rather than shipped through Redis.
type relayFrame struct {
	Kind           string `json:"kind"` // relayKindReply | relayKindInbox | relayKindSeal | relayKindProgress
	InstallationID string `json:"installation_id"`
	ChatID         string `json:"chat_id"`
	ChatType       int    `json:"chat_type"`
	Content        string `json:"content"`
	// SealReason names the ending a relayKindSeal frame carries, instead of the
	// words for it. The words are the ROUND's, and the round is on the holder:
	// its locale was captured when its bubble was opened, so the holder is the
	// only replica that can say the sentence in the language the asker reads.
	SealReason   string `json:"seal_reason,omitempty"`
	TaskID       string `json:"task_id,omitempty"`
	MessageID    string `json:"message_id,omitempty"`
	WorkspaceID  string `json:"workspace_id,omitempty"`
	SessionID    string `json:"session_id,omitempty"`
	CarriesFiles bool   `json:"carries_files,omitempty"`

	// RoundID, Seq and Milestone are a relayKindProgress frame's whole
	// content: which round (chat_input_task_id, for an auto-retry clone), how
	// far the reporting run's transcript had got (task_message.seq), and
	// whether this is the "starting the agent" milestone instead. No text: the
	// round's holder reads the rows itself (see relayKindProgress).
	RoundID   string `json:"round_id,omitempty"`
	Seq       int32  `json:"seq,omitempty"`
	Milestone bool   `json:"milestone,omitempty"`
}

const (
	relayKindReply = "reply"
	relayKindInbox = "inbox"
	// relayKindSeal ENDS A ROUND WITHOUT CARRYING WORDS, which is the one thing
	// a reply frame cannot express: every wordless ending — a cancellation, a
	// completion with nothing to say, an answer that is only files — had no way
	// to reach the replica holding the bubble, so off-lease it left a spinner
	// claiming work was still in progress for the rest of the protocol's
	// window. Nothing else ends it: the sweep writes no frame, OnSettled needs
	// an unbound round, and the next question opens its own bubble.
	//
	// It is NOT a reply with an empty body, and the difference is the point. A
	// reply whose round is gone falls through to an ordinary push; one
	// cancel-all click would then put 这次处理已取消 into every chat in the
	// deployment. A seal frame with no round does NOTHING AT ALL.
	//
	// And it is for whoever holds the ROUND, which is not a question the
	// socket or the claim can answer, so it takes neither: it is published
	// under its task id, since it carries no installation and the stream
	// reader drops a frame with no scope id, and perform hands it to every
	// replica's deliverRelayed without the ownership gate or the claim. Gated
	// on the socket it reached nobody; claimed once for the deployment, the
	// replica that won could be one without the round, and the holder would
	// lose the race and never close the bubble. Every replica but the holder
	// finds no round and returns, and a copy that reaches the holder twice
	// finds the round already taken.
	relayKindSeal = "seal"

	// relayKindProgress says a run has new progress — a tool call, reasoning,
	// the starting milestone — to the replica holding that run's bubble. It
	// is a nudge, not a delivery, and none of the machinery above applies to
	// it:
	//
	//   - It never enters the dispatcher's shard queues. DeliverWecomOutbound
	//     hands it straight to the progress sink, so a burst of progress takes
	//     no queue space from an answer and never waits in line ahead of one.
	//   - It takes no claim. Its dedupe is the round's own record of how far
	//     the run's transcript is already shown (roundEntry.folded), on the
	//     one replica that holds the round, so a copy, a replay or an
	//     out-of-order frame is a no-op there, and the terminal claim key is
	//     never touched.
	//   - It carries no text. The holder reads the rows the daemon's request
	//     already committed to task_message, and redacts them itself; reasoning
	//     cannot be redacted before it is joined (safeThinking), and this
	//     relay keeps every frame in a Redis stream for its replay window.
	//   - Like a seal it is for whoever holds the ROUND, not the socket: a
	//     replica with no round for it does nothing.
	relayKindProgress = "progress"
)

// progressSink is the half of the typing indicator the relay hands progress
// frames to. It must not block: it is called on the shard read loop.
type progressSink interface {
	acceptRelayedProgress(f relayFrame)
}

// progressAttacher is how the typing indicator registers as that sink.
// *RelayOutbound satisfies it; a test relay that does not is simply never
// handed progress.
type progressAttacher interface {
	attachProgress(s progressSink)
}

// relayHandler performs a delivery on the replica that holds the socket.
// *Outbound implements it; the indirection is what lets this object be
// registered with the relay before the subscriber exists.
type relayHandler interface {
	deliverRelayed(ctx context.Context, f relayFrame) relayResult
	// ownsSocket answers "does this process hold that installation's live
	// connection right now". It gates the global claim — see perform.
	ownsSocket(installationID string) bool
}

// claimState is what Resolve reads off one claim key.
type claimState int

const (
	// claimAbsent — nobody holds it: never claimed, released, or expired.
	claimAbsent claimState = iota
	// claimHeld — a replica took it and has not recorded an outcome. Resolve
	// turns this into claimLost as it reports it.
	claimHeld
	// claimSettled — its holder recorded the outcome.
	claimSettled
	// claimLost — the publisher recorded it as lost.
	claimLost
)

// claimSettledValue and claimLostValue are what a key holds once it is no
// longer a token. A token never collides with them: it is hex and a slash.
const (
	claimSettledValue = "settled"
	claimLostValue    = "lost"
)

// relayResult is what one delivery attempt reports: whether the frame is
// finished, and — for a finished one — the record its holder owes. The record
// is separated from the delivery so it can be made AFTER the claim is settled:
// a holder whose Settle is refused (the publisher already counted the reply
// as lost) must record nothing, or the reply ends with two records.
type relayResult struct {
	outcome deliveryOutcome
	record  func()
}

// deliveryOutcome tells the dispatcher whether the claim may be released.
type deliveryOutcome int

const (
	// outcomeNotOurs — this replica holds no socket for that installation.
	// Another one will take the frame; the claim must go back.
	outcomeNotOurs deliveryOutcome = iota
	// outcomeDone — delivered, or failed in a way that must not be retried.
	outcomeDone
	// outcomeProvablyNotSent — nothing reached the wire, so the claim goes
	// back and a replay or another replica may try again. Deliberately NOT
	// used for an ack timeout: errAckTimeout means the frame may well have
	// arrived, and this adapter's standing rule is that a caller retries such
	// a send at its own risk.
	outcomeProvablyNotSent
)

// relayPublish is what one trip through the cross-replica router produced.
//
// The bool it replaces could not tell "the bus took it" from "a replica took
// the delivery" from "the publish call itself failed", and an inbox push needs
// all three: only an accepted-and-claimed frame is a delivery it may stop
// making, and only a failed publish forbids it from trying another bot.
type relayPublish int

const (
	// relayNotWired — nothing reached the bus: no relay is attached, or the
	// frame could not even be built. A caller may treat it as a delivery that
	// certainly did not happen.
	relayNotWired relayPublish = iota
	// relayAccepted — the bus took the frame. For a reply or a seal that is the
	// whole answer. For an inbox push it means a replica that owns the target
	// bot's socket took the delivery claim, so somebody is carrying it.
	relayAccepted
	// relayNoHolder — the bus took the frame, but across the acceptance window
	// no replica took the delivery claim: nobody holds that installation's
	// socket, so every dispatcher discards the frame. Only an inbox push can
	// report this (see confirmInbox). The delivery provably did not happen.
	relayNoHolder
	// relayUncertain — the publish call failed, or the claim store could not
	// answer. The frame may or may not have been accepted, so nothing may be
	// concluded and nothing may be re-routed on this evidence.
	relayUncertain
)

// routed reports whether the bus took the frame, which is the whole question
// the reply and seal callers ask. They have no second route to fall back to,
// and a frame that may have been accepted is treated as not carried, so they
// keep their old local-send behaviour.
func (p relayPublish) routed() bool { return p == relayAccepted }

// seenEvents is a bounded, per-process set of relay event ids already acted on.
// It is a cheap first gate in front of the Redis claim — the publisher's own
// copy of its own frame is the common case and never needs a round trip. It is
// NOT the idempotency mechanism; DedupeStore is.
type seenEvents struct {
	mu    sync.Mutex
	ids   map[string]struct{}
	order []string
	limit int
}

func newSeenEvents(limit int) *seenEvents {
	return &seenEvents{ids: make(map[string]struct{}, limit), limit: limit}
}

func (s *seenEvents) claim(id string) bool {
	if id == "" {
		return true
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if _, dup := s.ids[id]; dup {
		return false
	}
	s.ids[id] = struct{}{}
	s.order = append(s.order, id)
	if len(s.order) > s.limit {
		delete(s.ids, s.order[0])
		s.order = s.order[1:]
	}
	return true
}

func (s *seenEvents) forget(id string) {
	if id == "" {
		return
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.ids, id)
}

// queued is one frame waiting for a worker, with the id its claims are under
// and how many times a worker has already picked it up.
type queued struct {
	frame    relayFrame
	eventID  string
	attempts int
}

// A released claim has nobody to retry it EXCEPT this process: each replica
// reads a given stream frame exactly once and replays only on restart, so
// "release so the holder can take it" strands the reply whenever the holder
// already processed its copy — it lost the claim race, returned, and nothing
// will ever wake it again. The party that released is therefore the party
// that re-offers it, on RelayConfig.retryPlan, until the lease settles.

// hold is one installation's line while its head is waiting out a re-offer.
// items[0] is the frame being retried; everything after it arrived later and
// must not overtake it. Owned by exactly one worker goroutine, so unlocked.
type hold struct {
	items   []queued
	readyAt time.Time
}

// RelayOutbound publishes a delivery to the replica holding the bot's socket,
// and performs the ones other replicas publish. One per process.
type RelayOutbound struct {
	publisher relayPublisher
	dedupe    DedupeStore
	dedupeTTL time.Duration
	cfg       RelayConfig
	retryPlan []time.Duration

	// owner is this process's half of every claim token (tokenFor). Minted
	// once per RelayOutbound so a claim can tell its own re-offers from
	// another replica's, and nothing else.
	owner  string
	logger *slog.Logger
	seen   *seenEvents

	// verify carries a routed reply's id to the outcome watcher — the one
	// owner of "did anybody end up delivering this". Buffered and shed rather
	// than blocking: the publisher is on a bus subscriber's goroutine.
	verify chan pendingOutcome

	// metrics arrives after construction: this object is built before the
	// metrics registry exists, because the relay's shard readers start before
	// both. Atomic because DeliverWecomOutbound runs on the shard reader while
	// boot is still wiring.
	metrics atomic.Value // Metrics

	ready   chan struct{}
	handler relayHandler

	// progress is where relayKindProgress frames go. Set during boot by the
	// typing indicator (attachProgress) while the shard readers may already
	// be running, hence atomic. Without one, a progress frame is dropped and
	// that is said once (warnNoProgress).
	progress       atomic.Value // progressSink
	warnNoProgress sync.Once

	queues []chan queued
	wg     sync.WaitGroup
}

// NewRelayOutbound builds the cross-replica router. replayGrace is the relay's
// configured startup replay window, which sizes the claim TTL (dedupeTTLFor).
// Call Attach with the subscriber and Start with the process context;
// registering it on the relay is safe before either.
func NewRelayOutbound(publisher relayPublisher, dedupe DedupeStore, cfg RelayConfig, logger *slog.Logger) *RelayOutbound {
	if logger == nil {
		logger = slog.Default()
	}
	cfg = cfg.withDefaults()
	r := &RelayOutbound{
		publisher: publisher,
		dedupe:    dedupe,
		dedupeTTL: dedupeTTLFor(cfg.ReplayGrace),
		cfg:       cfg,
		retryPlan: cfg.retryPlan(),
		owner:     newReqID(),
		logger:    logger,
		seen:      newSeenEvents(4096),
		verify:    make(chan pendingOutcome, cfg.QueueDepth),
		ready:     make(chan struct{}),
		queues:    make([]chan queued, cfg.Shards),
	}
	for i := range r.queues {
		r.queues[i] = make(chan queued, cfg.QueueDepth)
	}
	return r
}

// SetMetrics installs the health sink. Called once during boot, before any
// delivery can run (the workers wait on Attach), so the only concurrent reader
// is the shed counter on the shard reader — which is why it is atomic.
func (r *RelayOutbound) SetMetrics(m Metrics) {
	if r != nil && m != nil {
		r.metrics.Store(m)
	}
}

func (r *RelayOutbound) mx() Metrics {
	if v := r.metrics.Load(); v != nil {
		return v.(Metrics)
	}
	return nopMetrics{}
}

// attachProgress makes s the receiver of progress frames.
func (r *RelayOutbound) attachProgress(s progressSink) {
	if r != nil && s != nil {
		r.progress.Store(s)
	}
}

// deliverProgress hands a progress frame to the sink, on the shard reader's
// goroutine, and never to the dispatcher's queues (see relayKindProgress).
func (r *RelayOutbound) deliverProgress(f relayFrame) {
	if s, ok := r.progress.Load().(progressSink); ok {
		s.acceptRelayedProgress(f)
		return
	}
	r.warnNoProgress.Do(func() {
		r.logger.Warn("wecom relay: progress frames are arriving and nothing here shows them; " +
			"a run whose reports reach another replica shows no steps in its bubble, and a long run's " +
			"bubble is not handed over before the stream window ends")
	})
}

// Attach supplies the handler that performs deliveries. Called once, after the
// subscriber exists. Frames received before this wait in their queue.
func (r *RelayOutbound) Attach(h relayHandler) {
	if r == nil {
		return
	}
	r.handler = h
	close(r.ready)
}

// Start runs the workers until ctx is done, then drains what is already
// queued so a graceful shutdown does not strand a reply somebody is waiting
// for.
func (r *RelayOutbound) Start(ctx context.Context) {
	if r == nil {
		return
	}
	for i := range r.queues {
		r.wg.Add(1)
		go r.work(ctx, r.queues[i])
	}
	r.wg.Add(1)
	go r.watchOutcomes(ctx)
}

// handlerReady blocks until Attach has run, and reports whether there is a
// handler to deliver with at all.
func (r *RelayOutbound) handlerReady(ctx context.Context) bool {
	select {
	case <-r.ready:
		return true
	case <-ctx.Done():
		// Cancelled before (or while) the handler arrived. If it IS already
		// attached — the select picks between two ready channels arbitrarily —
		// what is queued can still be drained; without it there is nothing a
		// drain could deliver with.
		select {
		case <-r.ready:
			return true
		default:
			return false
		}
	}
}

// work is one shard's whole life.
//
// Everything it touches belongs to this goroutine alone: the per-installation
// lines and the one timer that wakes them. That is deliberate on both counts.
// The lines are what keep a re-offered frame AT THE HEAD of its installation
// rather than at the back of the queue, so a later reply for the same bot
// cannot overtake it. The timer being the worker's own is what makes a pending
// re-offer part of the worker — a timer scheduled outside it could fire after
// the worker had drained and exited, and put a frame into a queue nobody is
// reading.
func (r *RelayOutbound) work(ctx context.Context, q chan queued) {
	defer r.wg.Done()
	if !r.handlerReady(ctx) {
		return
	}
	lines := map[string]*hold{}
	timer := time.NewTimer(time.Hour)
	defer timer.Stop()
	for {
		wait := time.Hour
		if next, ok := earliestDue(lines); ok {
			if wait = time.Until(next); wait < 0 {
				wait = 0
			}
		}
		if !timer.Stop() {
			select {
			case <-timer.C:
			default:
			}
		}
		timer.Reset(wait)

		select {
		case item := <-q:
			// The select is fair, so an item can win against an already-fired
			// ctx.Done. Performing it on the cancelled context would misfile it
			// as a dedupe outage; it belongs to the drain.
			if ctx.Err() != nil {
				r.drainRemaining(ctx, q, lines, &item)
				return
			}
			r.offer(ctx, lines, item)
		case <-timer.C:
			if ctx.Err() != nil {
				r.drainRemaining(ctx, q, lines, nil)
				return
			}
			r.fireDue(ctx, lines)
		case <-ctx.Done():
			r.drainRemaining(ctx, q, lines, nil)
			return
		}
	}
}

// earliestDue is the soonest moment any line's head may be offered again.
func earliestDue(lines map[string]*hold) (time.Time, bool) {
	var soonest time.Time
	found := false
	for _, h := range lines {
		if len(h.items) == 0 {
			continue
		}
		if !found || h.readyAt.Before(soonest) {
			soonest, found = h.readyAt, true
		}
	}
	return soonest, found
}

// offer takes one frame off the shard queue. If its installation already has a
// line waiting out a re-offer, it joins the BACK of that line: overtaking the
// frame in front of it is exactly the reordering this exists to prevent.
func (r *RelayOutbound) offer(ctx context.Context, lines map[string]*hold, item queued) {
	if h := lines[item.frame.InstallationID]; h != nil {
		if len(h.items) >= r.cfg.QueueDepth {
			r.shed(item, "the installation's line is full behind a retry")
			return
		}
		h.items = append(h.items, item)
		return
	}
	r.step(ctx, lines, item)
}

// step runs one delivery and files what it means for the line. A frame that
// needs another offer stays at the head of its installation's line with the
// next delay on it; a finished one lets whatever queued behind it move up.
func (r *RelayOutbound) step(ctx context.Context, lines map[string]*hold, item queued) {
	inst := item.frame.InstallationID
	if r.perform(ctx, item) {
		r.advance(lines, inst)
		return
	}
	delay, more := r.delayFor(item.attempts)
	if !more {
		// By far the likeliest reason to exhaust the chain is a claim held
		// because another replica already delivered, so this is not counted as
		// a drop. The publisher's outcome watch is what names a reply nobody
		// delivered, and it names it once.
		r.logger.Warn("wecom relay: giving up on a routed delivery after retries",
			"installation_id", inst, "task_id", item.frame.TaskID,
			"attempts", item.attempts+1)
		r.advance(lines, inst)
		return
	}
	item.attempts++
	h := lines[inst]
	if h == nil {
		h = &hold{items: []queued{item}}
		lines[inst] = h
	} else {
		h.items[0] = item // it is the head; step is only ever called on one
	}
	h.readyAt = time.Now().Add(delay)
}

// advance retires a finished head and lets the next frame for that
// installation become due immediately.
func (r *RelayOutbound) advance(lines map[string]*hold, inst string) {
	h := lines[inst]
	if h == nil {
		return // it came straight off the queue and never joined a line
	}
	h.items = h.items[1:]
	if len(h.items) == 0 {
		delete(lines, inst)
		return
	}
	h.readyAt = time.Time{} // due now; the next loop turn picks it up
}

// fireDue offers every line whose head has waited out its backoff.
func (r *RelayOutbound) fireDue(ctx context.Context, lines map[string]*hold) {
	now := time.Now()
	for inst, h := range lines {
		if len(h.items) == 0 {
			delete(lines, inst)
			continue
		}
		if h.readyAt.After(now) {
			continue
		}
		r.step(ctx, lines, h.items[0])
	}
}

// delayFor is how long the next offer waits, and whether there is one.
func (r *RelayOutbound) delayFor(attempts int) (time.Duration, bool) {
	if attempts < 0 || attempts >= len(r.retryPlan) {
		return 0, false
	}
	return r.retryPlan[attempts], true
}

// shed records a frame refused for want of queue space. It is an ADMISSION
// decision and nothing more: relay_shed, labelled by kind, on whichever
// replica refused it.
//
// It deliberately does not touch the reply counters. Every replica reads every
// frame, so no replica can tell from here whether a shed cost the user
// anything — the one that sheds may not be the one that would have sent it,
// and during a lease handoff two replicas can hold a sender at once, so even
// "do I hold the socket" is not proof of being the only one who could. Each
// replica answering that question for itself is what produced one reply
// counted as delivered and dropped at the same time.
//
// So the reply outcome stays with the single owner that can settle it after
// the fact: the publisher's watchOutcomes, which asks whether ANY replica ever
// claimed the delivery and counts the loss once if none did. A shed that
// really did cost the user the reply reaches that owner as an unclaimed
// delivery, and is counted there.
func (r *RelayOutbound) shed(item queued, why string) {
	r.mx().RecordRelayShed(item.frame.Kind)
	r.logger.Warn("wecom relay: shedding a routed delivery, "+why,
		"kind", item.frame.Kind,
		"installation_id", item.frame.InstallationID, "task_id", item.frame.TaskID)
}

// drainRemaining performs what is already queued so a graceful shutdown does
// not strand a reply — under ONE bounded budget for the whole drain, so a full
// shard cannot stack sequential ack waits. Deliveries started near the edge
// inherit the deadline and abort with it. first is an item a worker had
// already taken off the queue when the cancel won the race.
// Frames parked in a line waiting out a re-offer go first and without their
// backoff: the wait existed to give a lease time to move, and shutdown has
// overtaken that.
func (r *RelayOutbound) drainRemaining(ctx context.Context, q chan queued, lines map[string]*hold, first *queued) {
	drainCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), r.cfg.DrainBudget)
	defer cancel()
	if first != nil {
		// Join the back of its installation's line rather than jump it. This
		// frame was taken off the queue AFTER whatever is parked at that
		// line's head, and sending it first would invert two answers in the
		// user's chat — the exact reordering offer() exists to prevent, undone
		// on the way out. With no line for that installation there is nothing
		// to overtake.
		if h := lines[first.frame.InstallationID]; h != nil {
			h.items = append(h.items, *first)
		} else {
			r.perform(drainCtx, *first)
		}
	}
	for inst, h := range lines {
		for _, item := range h.items {
			if drainCtx.Err() != nil {
				return
			}
			r.perform(drainCtx, item)
		}
		delete(lines, inst)
	}
	for {
		if drainCtx.Err() != nil {
			return
		}
		select {
		case item := <-q:
			r.perform(drainCtx, item)
		default:
			return
		}
	}
}

// Wait blocks until every worker has stopped. For tests and shutdown.
func (r *RelayOutbound) Wait() {
	if r != nil {
		r.wg.Wait()
	}
}

// publish hands a delivery to the other replicas and reports what the bus did
// with it. See relayPublish for why the answer is not a bool.
//
// It NEVER waits: every caller of this one either has no second route to take
// when nobody holds the target bot, or is not in a position to take one. The
// single caller that is (an inbox push with the recipient-wide bot behind it)
// asks through publishAwaitingHolder instead, and pays the wait only there.
func (r *RelayOutbound) publish(f relayFrame, eventID string) relayPublish {
	return r.publishFrame(context.Background(), f, eventID, false)
}

// publishAwaitingHolder is publish plus the acceptance wait: it answers whether
// a replica owning the target bot's socket actually took the delivery, which is
// what an inbox push needs before it may put a second card in the member's chat
// through another bot. The wait is bounded by ctx, and by the acceptance window
// it configures -- see confirmInbox.
//
// WHY IT IS A SEPARATE ENTRY POINT. Bus delivery is synchronous on the caller's
// goroutine, and the publisher of an inbox:new is the HTTP request that created
// the comment; only one replica holds a given bot's socket, so this wait is the
// common path in a multi-replica deployment. Spending it where the answer is
// then discarded -- a member-authored push, which has no second route to try,
// or the fallback attempt itself, which has nothing behind it -- holds the
// request open for a verdict nobody can act on. Those callers keep publish.
func (r *RelayOutbound) publishAwaitingHolder(ctx context.Context, f relayFrame, eventID string) relayPublish {
	return r.publishFrame(ctx, f, eventID, true)
}

// publishFrame is the one implementation behind the two entry points.
func (r *RelayOutbound) publishFrame(ctx context.Context, f relayFrame, eventID string, awaitHolder bool) relayPublish {
	if r == nil || r.publisher == nil {
		return relayNotWired
	}
	body, err := json.Marshal(f)
	if err != nil {
		r.logger.Warn("wecom relay: marshal outbound frame", "error", err)
		return relayNotWired
	}
	scope := f.InstallationID
	if f.Kind == relayKindSeal {
		scope = f.TaskID // see relayKindSeal
	}
	if err := r.publisher.PublishWithID(realtime.ScopeWecomOutbound, scope, "", body, eventID); err != nil {
		r.logger.Warn("wecom relay: publish failed",
			"error", err, "installation_id", f.InstallationID, "task_id", f.TaskID)
		// The bus call failed, but a publish whose RESPONSE was lost may still
		// have been accepted. Nothing may be concluded from it.
		return relayUncertain
	}
	// A published reply is now owed an outcome by somebody. watchOutcomes is
	// that somebody — see its comment for why it cannot be anyone else.
	if f.Kind == relayKindReply {
		r.awaitOutcome(f, eventID)
	}
	// Reply and seal frames are fire-and-forget: their callers read only "did
	// the bus take it", and counting a routed reply twice is what the outcome
	// watch exists to prevent. Only the inbox push asks whether a replica
	// actually took the delivery, because only it has a second route to fall
	// back to -- and only when the caller asked to wait.
	if !awaitHolder || f.Kind != relayKindInbox {
		return relayAccepted
	}
	if r.dedupe == nil {
		// No claim store means no relay in production (see DedupeStore); the
		// bus call is the only signal available, so take it.
		return relayAccepted
	}
	return r.confirmInbox(ctx, eventID)
}

// confirmInbox answers whether a replica took the delivery claim for an inbox
// frame the bus accepted, so the publisher can tell "somebody is carrying this"
// from "nobody holds that bot's socket" without waiting out a re-offer chain
// that will never exist.
//
// It reads the claim key for up to RelayConfig.AcceptanceWindow. A claim that
// appears means a replica owning the installation's socket engaged the
// delivery, and the relay's own guarantees (re-offers, the outcome record) take
// over from there. A key still absent at the end of the window means no replica
// even took it — the frame is handed to each replica exactly once and only a
// socket holder claims — so none ever will. The publisher then FENCES the key
// under a token no delivery worker presents (fenceTokenFor) and reports
// relayNoHolder, which is what lets the caller
// route the notification somewhere else. The fence is what keeps that safe: a
// dispatcher that is late, or a replica replaying the frame across a restart,
// finds the claim taken and delivers nothing -- on the publishing replica too,
// which is the one a fence under its own delivery token would NOT have stopped.
// See fenceTokenFor.
//
// A claim store that cannot answer is relayUncertain: the delivery might be
// happening, and the caller must not route a second copy on that. So is a
// caller whose own budget ran out mid-wait -- the wait is bounded by ctx as
// well as by the window, because this runs on a request's goroutine.
func (r *RelayOutbound) confirmInbox(ctx context.Context, eventID string) relayPublish {
	window := r.cfg.AcceptanceWindow
	// THE CALLER'S BUDGET IS THE OUTER BOUND. This wait runs on the goroutine
	// that is serving an HTTP request (see publishAwaitingHolder), so a caller
	// that runs out of time must take the wait with it rather than be held for
	// a window it configured elsewhere. A tighter caller deadline shortens the
	// window; with no deadline the window stands.
	deadline := time.Now().Add(window)
	callerDeadline, hasCallerDeadline := ctx.Deadline()
	if hasCallerDeadline && callerDeadline.Before(deadline) {
		deadline = callerDeadline
	}
	// The poll's OWN deadline ends the wait; the context is the backstop that
	// keeps a claim store which ignores its deadline from outlasting it, so it
	// gets a little more room than the loop. Were the two equal, the context
	// could fire in the same instant the last poll lands and the verdict would
	// rest on which select case won: reporting "uncertain" for a bot nobody
	// holds, and silently giving up the fallback.
	pollCtx, cancel := context.WithTimeout(ctx, time.Until(deadline)+window/8+time.Millisecond)
	defer cancel()
	key := dedupeKey(eventID)
	// Eight polls over whatever window actually applies, so a caller that
	// shortened the wait still samples it evenly rather than once at the start
	// and once past its own deadline.
	step := window / 8
	if effective := time.Until(deadline); effective < window {
		step = effective / 8
	}
	if step < time.Millisecond {
		step = time.Millisecond
	}
	for {
		state, err := r.dedupe.ClaimState(pollCtx, key)
		if err != nil {
			r.logger.WarnContext(pollCtx, "wecom relay: inbox claim state unreadable; the push is not re-routed",
				"error", err, "event_id", eventID)
			return relayUncertain
		}
		if state != claimAbsent {
			return relayAccepted
		}
		if !time.Now().Before(deadline) {
			break
		}
		timer := time.NewTimer(step)
		select {
		case <-timer.C:
		case <-pollCtx.Done():
			timer.Stop()
			return relayUncertain
		}
	}
	// A deadline can pass before its cancellation callback updates Err. An
	// expired caller must not fence the unconfirmed delivery or start a fallback.
	callerErr := ctx.Err()
	if callerErr == nil && hasCallerDeadline && !time.Now().Before(callerDeadline) {
		callerErr = context.DeadlineExceeded
	}
	if callerErr != nil {
		r.logger.WarnContext(ctx, "wecom relay: the caller's budget ran out before an inbox push's bot could be confirmed; not re-routing",
			"error", callerErr, "event_id", eventID)
		return relayUncertain
	}
	won, err := r.dedupe.Claim(pollCtx, key, r.fenceTokenFor(eventID), r.dedupeTTL)
	if err != nil {
		r.logger.WarnContext(pollCtx, "wecom relay: could not fence an unclaimed inbox delivery; the push is not re-routed",
			"error", err, "event_id", eventID)
		return relayUncertain
	}
	if !won {
		// A replica took the claim between the last read and the fence.
		return relayAccepted
	}
	r.logger.InfoContext(pollCtx, "wecom relay: no replica holds the inbox push's bot; its sender may route it elsewhere",
		"event_id", eventID)
	return relayNoHolder
}

// DeliverWecomOutbound is realtime.WecomOutboundDeliverer. It must not block:
// the caller is the shared shard read loop, and everything else on that shard
// waits behind it.
func (r *RelayOutbound) DeliverWecomOutbound(scopeID string, frame []byte, eventID string) {
	if r == nil {
		return
	}
	var f relayFrame
	if err := json.Unmarshal(frame, &f); err != nil {
		r.logger.Warn("wecom relay: undecodable frame", "error", err, "installation_id", scopeID)
		return
	}
	if f.Kind == relayKindProgress {
		r.deliverProgress(f)
		return
	}
	select {
	case r.queues[r.shardFor(dispatchKey(f))] <- queued{frame: f, eventID: eventID}:
	default:
		// Shed rather than stall the shard. Counted, because a reply nobody
		// gets is exactly what this whole path exists to stop being silent.
		r.shed(queued{frame: f, eventID: eventID}, "dispatch queue full")
	}
}

// dispatchKey picks the shard queue a frame waits on. Replies and inbox pushes
// go by installation, which is what keeps one bot's frames in order. A seal
// carries no installation, so keying it the same way would put every seal in
// the deployment on one queue behind one worker, and a cancel-all burst past
// QueueDepth would be shed: those bubbles would keep spinning. A seal needs no
// ordering against anything but its own round, so it goes by task id.
func dispatchKey(f relayFrame) string {
	if f.Kind == relayKindSeal {
		return f.TaskID
	}
	return f.InstallationID
}

func (r *RelayOutbound) shardFor(installationID string) int {
	h := fnv.New32a()
	_, _ = h.Write([]byte(installationID))
	return int(h.Sum32() % uint32(len(r.queues)))
}

// perform runs one delivery under an at-most-once claim, and reports whether
// this frame is FINISHED — delivered, refused, or not this replica's business.
// False means it is owed another offer, which the caller schedules at the head
// of the installation's line.
func (r *RelayOutbound) perform(ctx context.Context, item queued) bool {
	if item.frame.Kind == relayKindSeal {
		// Neither gate below applies: see relayKindSeal.
		dctx, cancel := context.WithTimeout(ctx, r.cfg.deliveryBudget())
		r.handler.deliverRelayed(dctx, item.frame)
		cancel()
		return true
	}
	// Ownership FIRST, the global claim second. The claim is a cross-replica
	// SET NX: every replica reads every frame, and if one that cannot send
	// were allowed to win it, the replica that can send would lose the race,
	// conclude somebody else has it, and return — while the winner discovers
	// it holds no socket, releases the key, and nothing ever wakes the loser
	// again. Every party behaves correctly and the reply is still lost. So a
	// replica competes for the claim only after establishing it could honour
	// it. The socket can still vanish between this check and the send; that
	// window is why deliverRelayed re-checks and why a not-ours outcome
	// releases the claim.
	if !r.handler.ownsSocket(item.frame.InstallationID) {
		return true
	}
	if !r.seen.claim(item.eventID) {
		return true
	}
	key := dedupeKey(item.eventID)
	token := r.tokenFor(item.eventID)
	if r.dedupe != nil {
		won, err := r.dedupe.Claim(ctx, key, token, r.dedupeTTL)
		if err != nil {
			// A dedupe store that cannot answer must not silently become an
			// at-least-once path: a duplicate answer in a room is worse than a
			// late one. But nothing external retries a running process either
			// — replay happens only on restart — so the retry is ours.
			r.seen.forget(item.eventID)
			r.logger.WarnContext(ctx, "wecom relay: dedupe unavailable, retrying locally",
				"error", err, "installation_id", item.frame.InstallationID)
			return false
		}
		if !won {
			// Losing the claim does NOT mean somebody else will deliver. In a
			// mid-flight lease move the loser here can be the replica that
			// NOW holds the socket, while the winner is about to discover it
			// no longer does and release — and each replica reads a stream
			// frame exactly once, so nothing external ever hands it back.
			// The loser therefore checks again, bounded and backed off; the
			// common case (the claim is held because the reply was
			// delivered) burns the chain out and stops.
			r.seen.forget(item.eventID)
			return false
		}
	}
	// DeliveryBudget is what the publisher's outcomeGrace charges per offer
	// (outcomeGrace, below), so it has to be what this delivery actually
	// gets. It was documented as the bound and never applied: the send's only
	// limit was ackTimeout, the constant, whatever the config said. An
	// operator who lowered the budget shrank the grace without shortening the
	// delivery, and a Resolve landing inside an ack wait fences a reply that
	// is on its way.
	//
	// A budget PER OFFER and not one for the chain, because this is where the
	// claim is taken and given back: an offer that ends provably-unsent
	// releases the claim a few lines down, and the next offer arrives here
	// and opens a fresh one.
	//
	// The default is ackTimeout, so a deployment that sets nothing sees no
	// change. A delivery cut here ends in a context error, which
	// unconfirmedReason reads as unknown rather than failed — correct when
	// the cut lands after the write, and marked as certain when it lands
	// before one (errNotAttempted, ws_sender.go).
	dctx, cancelDelivery := context.WithTimeout(ctx, r.cfg.deliveryBudget())
	res := r.handler.deliverRelayed(dctx, item.frame)
	cancelDelivery()
	if res.outcome == outcomeDone {
		// FINISHED. The holder's record is made only once the claim says
		// so: Settle is a compare-and-set on this replica's token, and a
		// refusal means the publisher already resolved the reply as lost
		// at the end of its grace — it has a record, so this one must not
		// be made. That is the whole reason record is a closure rather than
		// a counter moved inside deliverRelayed.
		if r.dedupe != nil && !r.settleClaim(ctx, key, token, item.frame) {
			return true
		}
		if res.record != nil {
			res.record()
		}
		return true
	}
	// Not ours, or provably never written: give the claim back — and offer it
	// again locally too, because release alone wakes nobody (see !won above).
	//
	// Release is a compare-and-delete on this replica's token, so it is safe
	// to retry and can never take a claim a later owner holds. Its three
	// answers are all "offer it again":
	//   - released: the next offer's Claim starts from an empty key;
	//   - not ours any more: the delete already landed, or another replica
	//     holds it now — the next Claim decides which;
	//   - error: UNKNOWN whether the delete landed. Nothing is recorded on
	//     that word. If the key still holds this token the next Claim
	//     re-takes it (same owner) and the delivery runs again; if the delete
	//     did land the next Claim takes it fresh, or loses it to a replica
	//     that got there first — which then delivers and records, once.
	// A claim that stays stranded under this token — every release erroring,
	// every re-offer failing — is what the publisher's Resolve finds at the
	// end of the grace: held, by nobody who recorded anything, and it
	// records the loss there, once.
	if r.dedupe != nil {
		if released, err := r.dedupe.Release(ctx, key, token); err != nil {
			r.logger.WarnContext(ctx, "wecom relay: claim release outcome unknown; the next offer re-claims",
				"error", err, "kind", item.frame.Kind,
				"installation_id", item.frame.InstallationID, "task_id", item.frame.TaskID)
		} else if !released {
			r.logger.DebugContext(ctx, "wecom relay: claim no longer ours at release",
				"kind", item.frame.Kind, "installation_id", item.frame.InstallationID, "task_id", item.frame.TaskID)
		}
	}
	r.seen.forget(item.eventID)
	return false
}

// claimSettleAttempts is how many times the holder asks the store to settle
// its claim before giving up. An error from Settle means UNKNOWN, exactly as
// it does for Release — and unlike Release there is no later offer to resolve
// it, because a settled delivery is finished. So the retry is what resolves
// it, and the operation is built to be retried: redisSettleSource is
// idempotent and token-fenced, so a retry after a settle that DID land
// matches the settled value and reports success, while one after a settle
// that never landed finds either the token (settles it now) or the
// publisher's fence (refused, and the holder correctly records nothing).
const claimSettleAttempts = 3

// settleRetryBackoff paces those attempts. The claim layer's own knob rather
// than a new one: it is the same "how long before asking the store again"
// question the re-offer chain asks.
func (r *RelayOutbound) settleRetryBackoff() time.Duration {
	if r.cfg.RetryBackoff > 0 {
		return r.cfg.RetryBackoff
	}
	return defaultRelayRetryBackoff
}

// settleClaim marks a delivered frame's claim as settled and reports whether
// its holder may record the outcome.
//
// False has two meanings, and only one of them is covered elsewhere.
//
// Covered: the publisher already resolved the reply as lost. Its record
// stands, and a second one here would double it.
//
// NOT always covered: every attempt came back unknown. The holder cannot tell
// which state the store is in. If the settles never landed the claim is still
// held by this token, and the publisher's Resolve ends the reply once — the
// common case, and the reason not to count here. But if a settle DID land and
// only its response was lost, the key already reads settled, so that Resolve
// stays quiet too and the reply ends with NO record at all. Recording here
// instead would turn the common case into the double count this whole path
// exists to prevent, so the miss is the side deliberately taken: a monitoring
// gap under a store that keeps failing, not a reply the user did not get. The
// warning below is what makes it visible.
func (r *RelayOutbound) settleClaim(ctx context.Context, key, token string, f relayFrame) bool {
	var (
		lastErr error
		made    int
	)
	for attempt := 0; attempt < claimSettleAttempts; attempt++ {
		if attempt > 0 {
			timer := time.NewTimer(r.settleRetryBackoff())
			select {
			case <-timer.C:
			case <-ctx.Done():
				// Shutdown does not excuse the settle: the frame is already
				// in the user's chat, and the store call itself runs on a
				// context of its own (dedupe_redis.go). Skip the pause, not
				// the attempt.
				timer.Stop()
			}
			if settleBudgetSpent(ctx) {
				break
			}
		}
		made++
		settled, err := r.dedupe.Settle(ctx, key, token)
		switch {
		case err != nil:
			lastErr = err
		case settled:
			return true
		default:
			r.logger.WarnContext(ctx, "wecom relay: delivered after the publisher resolved the reply as lost; not counted again",
				"kind", f.Kind, "installation_id", f.InstallationID, "task_id", f.TaskID)
			return false
		}
	}
	// Still unknown after every attempt this was allowed to make. See the
	// doc comment: the publisher ends the reply when the settles never
	// landed, and nothing ends it when one landed and only its answer was
	// lost. Which of the two happened is exactly what is not knowable here,
	// so the outcome is left unrecorded rather than double-recorded.
	r.logger.WarnContext(ctx, "wecom relay: delivered, but the claim could not be settled; this reply's outcome may go unrecorded",
		"error", lastErr, "attempts", made, "kind", f.Kind,
		"installation_id", f.InstallationID, "task_id", f.TaskID,
		"detail", "the delivery itself reached the chat; if the settle landed and only its "+
			"response was lost, the publisher's Resolve reads the claim as settled and stays "+
			"quiet as well, so no delivered/dropped/unconfirmed is counted for this reply")
	return false
}

// settleBudgetSpent reports whether a bounding DEADLINE on ctx has passed.
//
// A bare cancellation is not one. Shutdown interrupts the work, but the frame
// is already in the user's chat and its claim still has to be settled — which
// is why the store call drops cancellation (dedupe_redis.go). A deadline is
// the opposite case: drainRemaining bounds the WHOLE drain with one, and a
// retry chain that keeps opening attempts past it spends time the shutdown
// already promised away. Attempts already made stand; no new one begins.
func settleBudgetSpent(ctx context.Context) bool {
	deadline, ok := ctx.Deadline()
	return ok && !time.Now().Before(deadline)
}

// tokenFor is the owner token one claim is held under: this process, and the
// delivery. Stable across re-offers on this process, unique across replicas.
func (r *RelayOutbound) tokenFor(eventID string) string { return r.owner + "/" + eventID }

// fenceTokenFor is the token a no-holder fence is planted under, and it is
// deliberately NOT tokenFor. Claim answers "won" when the stored value equals
// the caller's token, so a fence planted under the publisher's own delivery
// token would be reclaimable by that replica's dispatcher the moment its
// socket came back -- the ordinary reconnect, not an exotic one -- and the
// frame it then delivered would be the second card the fallback had already
// replaced. The suffix makes the fenced value one no delivery worker ever
// presents, so the fence holds against every worker on every replica, the
// publishing one included. It is never released; the claim TTL retires it.
func (r *RelayOutbound) fenceTokenFor(eventID string) string {
	return r.tokenFor(eventID) + "/fence"
}

func dedupeKey(eventID string) string { return "wecom:outbound:claim:" + eventID }

// pendingOutcome is one routed reply whose end-to-end fate is not known yet.
type pendingOutcome struct {
	key       string
	sessionID string
	instID    string
	taskID    string
	dueAt     time.Time
}

// outcomeGrace is how long a routed reply is given to find a holder before the
// publisher concludes nobody had one. It has to outlast the WHOLE re-offer
// chain — a reply still being retried is in flight, not lost — plus the claim
// round trip each of those offers pays for.
func (r *RelayOutbound) outcomeGrace() time.Duration {
	// One claim round trip per OFFER, not one for the chain. Every re-offer
	// makes its own Claim call and each can burn the store's full claim budget, so a
	// grace built from the backoffs plus a single round trip expires while the
	// chain is still running against a slow store — and the watcher then
	// records a loss that the next attempt contradicts by delivering. Sizing
	// it for the worst case costs a later settle on a healthy store, which is
	// the harmless direction.
	budget := defaultClaimBudget
	if r.dedupe != nil {
		budget = r.dedupe.ClaimBudget()
	}
	// TWO round trips per offer, not one. Every offer makes its own Claim,
	// and every offer ends in a second call on the same budget: a Release
	// when it is owed another offer, a Settle when it is finished. Counting
	// only the Claim leaves half the store time out of the arithmetic, and
	// the absent state is deliberately NOT fenced by Resolve — a premature
	// expiry there would be recorded as a loss while a later offer could
	// still claim, deliver and settle, which is the contradiction this whole
	// path exists to remove. (Fencing absent would trade that miscount for a
	// claim no offer can take, i.e. a reply the user never gets: worse.)
	offers := len(r.retryPlan) + 1
	total := budget * time.Duration(2*offers)
	for _, d := range r.retryPlan {
		total += d
	}
	// The settle retry on the finished offer: its extra attempts and the
	// pauses between them (settleClaim).
	total += time.Duration(claimSettleAttempts-1) * (budget + r.settleRetryBackoff())
	// Plus a DELIVERY PER OFFER, not one for the chain. perform gives every
	// claimed delivery a budget of its own, and the failure that spends the
	// whole of one is also the failure that hands the claim back: an offer
	// whose chat is busy waits for the chat's turn until its budget runs out
	// and comes back errChatBusy, which is provablyNotSent, so the claim is
	// released and the frame is offered again with a fresh budget. Charging
	// one delivery to the chain therefore sized the grace for a chain that
	// cannot happen — every offer's backoff plus one offer's delivery — and
	// on the defaults that is 5s of grace against 60s the chain can spend.
	//
	// The Resolve that lands inside a live offer is the whole cost: it fences
	// the key as lost in the same operation, so the holder that comes back
	// records nothing while the counter already says the reply was dropped.
	// One reply, counted lost and delivered at once.
	//
	// The other direction — a delivery that outlives the budget perform gave
	// it — cannot happen: it IS the budget, applied to the context the
	// delivery runs on, so an answer split into several frames spends it
	// across all of them rather than taking an ack wait per piece.
	total += r.cfg.deliveryBudget() * time.Duration(offers)
	return total
}

// watchOutcomes is the ONE owner of a routed reply's final outcome.
//
// Nobody else can be. The publisher hands the frame to Redis and returns; every
// replica that reads it and holds no socket returns silently, correctly, and
// counts nothing; the replica that does deliver counts the delivery. So when
// NO replica holds the socket — all of them mid-reconnect — the reply is lost
// with every party behaving properly and no counter moving. That is the window
// SELF_HOSTING.md describes and that nothing could previously size.
//
// The claim key is what makes it observable after the fact. It is taken by
// whoever delivers, under that replica's token; released — compare-and-delete
// on the token — only by a replica that proved it sent nothing; and settled by
// the holder once it has recorded the outcome. So once the re-offer chain can
// no longer be running, Resolve reads one of four things: absent (the reply
// reached nobody), settled (its holder counted it), lost (already resolved by
// an earlier pass over the same key), or still held by a token — a holder that
// never managed to record anything, which Resolve fences as lost in the same
// operation so the holder, should it come back, records nothing. One Lua call
// per routed reply, and routed replies are the off-lease minority.
func (r *RelayOutbound) watchOutcomes(ctx context.Context) {
	defer r.wg.Done()
	if r.dedupe == nil {
		// No claim store means no relay either (see DedupeStore), so there is
		// no routed reply whose outcome could be in question.
		for {
			select {
			case <-r.verify:
			case <-ctx.Done():
				return
			}
		}
	}
	var pending []pendingOutcome
	timer := time.NewTimer(time.Hour)
	defer timer.Stop()
	for {
		wait := time.Hour
		if len(pending) > 0 {
			if wait = time.Until(pending[0].dueAt); wait < 0 {
				wait = 0
			}
		}
		if !timer.Stop() {
			select {
			case <-timer.C:
			default:
			}
		}
		timer.Reset(wait)

		select {
		case p := <-r.verify:
			pending = append(pending, p) // the grace is constant, so this stays sorted
		case <-timer.C:
			now := time.Now()
			for len(pending) > 0 && !pending[0].dueAt.After(now) {
				r.settle(ctx, pending[0])
				pending = pending[1:]
			}
		case <-ctx.Done():
			// Shutdown is not evidence. A reply still inside its grace may yet
			// be delivered by the replica that has it, and this process is
			// leaving; counting it here would report a loss that did not
			// happen.
			if len(pending) > 0 {
				r.logger.Info("wecom relay: shutting down with routed replies still unresolved",
					"count", len(pending))
			}
			return
		}
	}
}

// settle asks whether anybody ever claimed one routed reply, and records the
// loss if nobody did.
func (r *RelayOutbound) settle(ctx context.Context, p pendingOutcome) {
	state, err := r.dedupe.Resolve(ctx, p.key)
	if err != nil {
		// An unreadable claim store proves nothing either way. Saying "lost"
		// here would turn a Redis blip into a fleet of phantom drops.
		r.logger.WarnContext(ctx, "wecom relay: could not settle a routed reply's outcome",
			"error", err, "installation_id", p.instID, "task_id", p.taskID)
		return
	}
	switch state {
	case claimSettled:
		return // its holder recorded the outcome
	case claimLost:
		return // already resolved — a republished completion meets the same key
	case claimHeld:
		// A replica took it and never settled it: its release or its settle
		// was lost on the wire, or the process went with it. Resolve has
		// just fenced the key as lost, so a holder that comes back finds its
		// Settle refused and records nothing; this is the reply's one record.
		r.mx().RecordOutboundDropped(string(dropTransport))
		r.logger.WarnContext(ctx, "wecom outbound: reply not delivered",
			"reason", string(dropTransport),
			"chat_session_id", p.sessionID,
			"installation_id", p.instID,
			"task_id", p.taskID,
			"detail", "a replica claimed the delivery and never recorded an outcome: "+
				"its claim could not be released or settled, and nothing reached the chat")
		return
	}
	r.mx().RecordOutboundDropped(string(dropNoConnection))
	r.logger.WarnContext(ctx, "wecom outbound: reply not delivered",
		"reason", string(dropNoConnection),
		"chat_session_id", p.sessionID,
		"installation_id", p.instID,
		"task_id", p.taskID,
		"detail", "routed to the replicas and none took the delivery: either no replica "+
			"held a live connection, or the one that did could not admit the frame "+
			"(see outbound_relay_shed_total)")
}

// awaitOutcome enrolls a routed reply for the check above. Never blocks: the
// caller is a bus subscriber's goroutine.
func (r *RelayOutbound) awaitOutcome(f relayFrame, eventID string) {
	if r.dedupe == nil {
		return
	}
	select {
	case r.verify <- pendingOutcome{
		key:       dedupeKey(eventID),
		sessionID: f.SessionID,
		instID:    f.InstallationID,
		taskID:    f.TaskID,
		dueAt:     time.Now().Add(r.outcomeGrace()),
	}:
	default:
		r.logger.Warn("wecom relay: outcome watch full, a routed reply's fate will go unrecorded",
			"installation_id", f.InstallationID, "task_id", f.TaskID)
	}
}

// WithRelay attaches the cross-replica router to the subscriber. Without it the
// subscriber keeps the behaviour it had: a reply produced off-lease is dropped
// where it stands.
func WithRelay(r noticeRouter) OutboundOption {
	return func(o *Outbound) { o.relay = r }
}

// relayEventID is the id every claim is keyed on. Derived from the turn rather
// than minted, so a republish of the same completion — a retry of the publish,
// a replayed stream entry, a second subscriber — is the same claim and cannot
// become a second message in the chat.
func relayEventID(e events.Event, taskID pgtype.UUID) string {
	return "wecom:" + e.Type + ":" + util.UUIDToString(taskID)
}

// relayInboxEventID is the same rule for an inbox push, which has no task. The
// installation is part of the id because one push is offered to two bots: the
// acting agent's, then the recipient-wide one. The publisher FENCES the claim
// of a bot nobody holds before it tries the other, and distinct ids are what
// keep that fence from also swallowing the route around it.
func relayInboxEventID(itemID, recipientID, installationID string) string {
	return "wecom:inbox:" + itemID + ":" + recipientID + ":" + installationID
}

// deliverRelayed performs a delivery published by another replica. It is the
// relayHandler half, and it runs on a dispatcher worker — never on the shard
// read loop.
//
// The frame carries identifiers, not payloads, for anything readable here: the
// attachment rows are fetched by this replica, which is the one that can send
// them, and are never shipped through Redis.
func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResult {
	// A SEAL FRAME IS ANSWERED BEFORE ANY OF THIS, and it is filtered by who
	// holds the ROUND rather than by who holds a socket. That is why it needs
	// no installation id: a cancellation deliberately does not chase an address
	// (typing_indicator.go), and a bubble is writable only on the replica that
	// painted it — so "do I have this round" asks the same question without a
	// database read.
	//
	// It writes no message, so none of the reply machinery below applies: no
	// counters move, no fallback push, and a round that is not here means the
	// frame did its whole job by doing nothing.
	if f.Kind == relayKindSeal {
		o.sealRelayedRound(ctx, f)
		return relayResult{outcome: outcomeDone}
	}
	instID, err := util.ParseUUID(f.InstallationID)
	if err != nil || !instID.Valid {
		return relayResult{outcome: outcomeDone} // unaddressable; a retry cannot make it addressable
	}
	if o.senders == nil {
		return relayResult{outcome: outcomeNotOurs}
	}
	sender := o.senders.get(instID)
	if sender == nil {
		return relayResult{outcome: outcomeNotOurs} // the replica holding the lease will take it
	}
	// record is the holder's one record for a finished reply, made by the
	// dispatcher after the claim is settled (perform). It moves the reply
	// counters only for AGENT REPLIES — their documented unit. An inbox push
	// routed here must not move them: the same push would otherwise count as
	// a delivered reply, a dropped reply, or nothing at all depending on
	// which replica happened to hold the socket.
	var record func()
	// hasVisibleChar, not `!= ""`, and the same predicate the local path uses
	// (outbound.go). A completion of "\n" carrying a file is words to neither
	// of them: the local path sends nothing and lets the file carry the
	// reply's outcome, and a frame routed here has to reach the same two
	// conclusions or which replica held the socket decides whether the user
	// sees a blank message and whether the text or the file is what the reply
	// counter is counting.
	// THE BUBBLE THIS REPLY BELONGS TO IS ON THIS REPLICA, so seal it rather
	// than pushing a second message underneath it. The replica that takes a
	// relayed reply is by definition the one holding the socket, and a bubble
	// is writable only where it was painted — which is that same replica. The
	// frame carries the task id for exactly this lookup.
	//
	// Replies only: an inbox push is not an answer to a round and must never
	// close one.
	// NOT GATED ON HAVING WORDS. An answer that is only files still ends the
	// round, and gating the take on hasVisibleChar left that round open: the
	// file arrived and the spinner above it kept turning. What the words should
	// be is decided AFTER the round is in hand, because the copy has to be in
	// the round's own locale and that was captured when its bubble was opened.
	spoke := false
	text := f.Content
	if f.Kind == relayKindReply && f.TaskID != "" {
		if sessionID, err := util.ParseUUID(f.SessionID); err == nil && sessionID.Valid {
			if t, _ := o.rounds().take(ctx, sessionID, byTask(f.TaskID)); t.HasBubble {
				if !hasVisibleChar(text) {
					text = wordlessSealCopy(t.Handle.Locale, f.CarriesFiles)
				}
				// The same split the local path makes (outbound.go): a closing
				// frame is clipped to 20480 bytes, so the rest follows as
				// messages under the bubble.
				head, rest := splitForBubble(text)
				sealErr := o.finishStream(ctx, t.Handle, head)
				switch classifySeal(sealErr) {
				case sealOnScreen:
					o.sendRest(ctx, t.Handle, rest)
					record, spoke = o.delivered, true
				case sealUnknown:
					o.sendRest(ctx, t.Handle, rest)
					se := sealErr
					record = func() {
						o.unconfirmedFor(ctx, f.SessionID, f.Kind, unconfirmedSealReason(se), se)
					}
					spoke = true
				default:
					// Proof the words are not in the bubble. They still have to
					// reach the room, on a budget the seal cannot have spent.
					var cancel context.CancelFunc
					ctx, cancel = fallbackBudget(ctx)
					defer cancel()
				}
			}
		}
	}
	// text, not f.Content: when a wordless ending's seal was refused, the copy
	// that was going to close the bubble is what the room gets instead — the
	// same substitution the local path makes (outbound.go).
	if hasVisibleChar(text) && !spoke {
		if err := sender.sendTextCtx(guardReply(ctx, o.q, instID), f.ChatID, f.ChatType, text); err != nil {
			if f.Kind == relayKindReply && errors.Is(err, errInstallationGone) && !errors.Is(err, errPartiallySent) {
				// Revoked while the reply waited. Final, unlike the other
				// refusals that precede the write: no replica may write it, so
				// another offer would only walk the retry chain and come back
				// as no_live_connection. An inbox push takes the ordinary
				// route below — the publisher offers a proven miss to the
				// member's other bot, which is still the right place for it.
				return relayResult{outcome: outcomeDone, record: func() {
					o.skippedFor(ctx, f.SessionID, skipInstallationInactive)
				}}
			}
			// WHETHER THIS FRAME IS FINISHED IS SETTLED BEFORE ANY COUNTER
			// MOVES. A frame that is owed another offer is still in flight,
			// and counting it here counts it once per attempt: the dispatcher
			// re-offers a provably-unsent frame across the whole retry chain
			// (RelayConfig.retryPlan is eleven entries on the production
			// defaults) and the publisher's watchOutcomes settles it once
			// more afterwards, so one reply lands on outbound_dropped twelve
			// or thirteen times — and if a later offer succeeds, on
			// outbound_delivered as well. That is precisely the "one reply
			// counted as delivered and dropped at the same time" defect shed's
			// comment above says this package no longer has.
			//
			// So the counters below record an outcome only for a frame that
			// will not be offered again; a frame still in flight is owed its
			// outcome by the single owner that can settle it after the fact —
			// the publisher's watchOutcomes, which counts a delivery nobody
			// took exactly once.
			//
			// Only a failure PROVEN to precede the write releases the claim.
			// Everything past that point — an attempted write, a verdict that
			// never came, a context that expired while waiting — may have
			// reached the peer, and releasing the claim there turns a retry
			// into a duplicate answer in the user's chat.
			if provablyNotSent(err) {
				o.logger.DebugContext(ctx, "wecom relay: nothing reached the wire, the frame is owed another offer",
					"error", err, "kind", f.Kind,
					"installation_id", f.InstallationID, "task_id", f.TaskID)
				return relayResult{outcome: outcomeProvablyNotSent}
			}
			sendErr := err
			if f.Kind == relayKindReply {
				// The same mapping the direct path uses. A partial send in
				// particular has to agree across the two, or one reply counts
				// as delivered or dropped depending on which replica held the
				// socket — see recordSend.
				record = func() { o.recordSend(ctx, f.SessionID, f.Kind, sendErr) }
			} else {
				record = func() {
					o.logger.WarnContext(ctx, "wecom relay: inbox push failed on the lease holder",
						"error", sendErr, "installation_id", f.InstallationID)
				}
			}
			return relayResult{outcome: outcomeDone, record: record}
		}
		if f.Kind == relayKindReply {
			record = o.delivered
		}
	}
	if f.Kind == relayKindInbox {
		return relayResult{outcome: outcomeDone}
	}
	if f.CarriesFiles {
		o.deliverAttachmentsByID(f.MessageID, f.WorkspaceID, attachmentTarget{
			InstallationID: instID,
			ChatID:         f.ChatID,
			ChatType:       f.ChatType,
			SessionID:      f.SessionID,
			// Same reason as the direct path in outbound.go: the failure runs
			// on a detached goroutine with no context left to read a profile
			// with, so the reader's language is resolved here. A relayed reply
			// is the one a multi-replica deployment takes most of the time —
			// without this, an English reader's file-failure notice arrives in
			// the deployment's language and nothing else differs.
			Locale: localeFor(ctx, o.q, instID, f.ChatType, f.ChatID),
		}, !hasVisibleChar(f.Content))
	}
	return relayResult{outcome: outcomeDone, record: record}
}

// wordlessSealCopy is what closes a bubble for an ending that has no words of
// its own. One place, so a relayed round and a local one cannot say different
// sentences about the same outcome.
func wordlessSealCopy(locale Locale, carriesFiles bool) string {
	c := copyFor(locale)
	if carriesFiles {
		return c.StreamNoReplyWithFiles
	}
	return c.StreamNoReply
}

// sealReason names the ending a seal frame carries. The words are not shipped:
// they are the round's, and the round's locale is on the holder.
const (
	sealReasonCancelled = "cancelled"
	sealReasonNoReply   = "no_reply"
)

// sealRelayedRound closes a round on behalf of a replica that could not reach
// it, and does NOTHING when the round is not here — which is the reason this is
// its own frame kind rather than a reply with an empty body.
func (o *Outbound) sealRelayedRound(ctx context.Context, f relayFrame) {
	if f.TaskID == "" {
		return
	}
	sessionID, err := util.ParseUUID(f.SessionID)
	if err != nil || !sessionID.Valid {
		return
	}
	t, _ := o.rounds().take(ctx, sessionID, byTask(f.TaskID))
	if !t.HasBubble {
		// No bubble here. Nothing to close and nothing to say: this ending was
		// silent before the frame existed and stays silent.
		return
	}
	text := wordlessSealCopy(t.Handle.Locale, f.CarriesFiles)
	if f.SealReason == sealReasonCancelled {
		text = copyFor(t.Handle.Locale).StreamCancelled
	}
	if err := o.finishStream(ctx, t.Handle, text); err != nil {
		// A seal that cannot land leaves the bubble where it was. Saying the
		// words as a message instead is the local path's move for an ANSWER,
		// which the asker is waiting for; nobody is waiting on this one, and a
		// push here is the plain message this frame kind exists to avoid.
		o.logger.WarnContext(ctx, "wecom relay: could not seal a routed round's ending",
			"task_id", f.TaskID, "reason", f.SealReason, "error", err)
	}
}

// ownsSocket is the pre-claim ownership gate. Cheap by design: one map read.
func (o *Outbound) ownsSocket(installationID string) bool {
	if o.senders == nil {
		return false
	}
	id, err := util.ParseUUID(installationID)
	if err != nil || !id.Valid {
		return false
	}
	return o.senders.get(id) != nil
}

// provablyNotSent reports whether a send error is one that certainly occurred
// before any byte could leave. ws_sender marks the boundary itself: a failure
// raised by the write is wrapped in errWriteAttempted, a missing verdict is
// errAckTimeout, a verdict the caller stopped waiting for is errAckAbandoned,
// and a stated refusal is a *wecomAPIError — all four mean the peer may have
// (or, for a refusal, definitely did) see the frame.
//
// A bare context error is read the same way, and that is a choice rather than
// an inability. request() marks the post-write case itself now, so what is
// left is a cancellation raised before anything was written. Releasing the
// claim on it would be correct and is deliberately not done here: this is the
// last gate before the frame is offered to another replica, the two mistakes
// cost different amounts — an un-retried delivery against a second copy of the
// answer in the person's chat — and widening what gets re-offered is a change
// to the relay's retry behaviour, not to how an error is read.
func provablyNotSent(err error) bool {
	var apiErr *wecomAPIError
	switch {
	case err == nil:
		return false
	case errors.Is(err, errPartiallySent):
		// An answer past the cap goes out as several frames, and a failure on
		// the second says nothing about the first, which the user is already
		// reading. Retrying such a send would repeat what landed.
		return false
	case errors.As(err, &apiErr):
		return false
	case errors.Is(err, errAckTimeout):
		return false
	case errors.Is(err, errStreamBusy):
		// Nothing was written: the gate refused to put a frame out while the
		// server still owed a verdict on this req_id. Provably not sent is
		// what lets the answer go out once, by the plain route.
		return true
	case errors.Is(err, errStreamAckTimeout):
		// A stream frame whose verdict never came back is the same evidence as
		// errAckTimeout and has to be read the same way: the frame went to the
		// socket and the server said nothing. Missing here it fell to the
		// default and was reported as provably unsent, which is what let a
		// sealed bubble's answer go out a second time as a plain message.
		return false
	case errors.Is(err, errWriteAttempted):
		return false
	case errors.Is(err, errNotAttempted):
		// AHEAD of the context branch below, which this error also matches:
		// every not-attempted failure wraps the ctx.Err() that ended it. The
		// chat lock is taken and the context is checked before a frame is
		// built, so a delivery that ended at either point wrote nothing — and
		// these are the most retryable failures the path has. Reading them as
		// the ambiguous context error underneath settles the claim on a
		// message that was never offered to the socket.
		return true
	case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
		return false
	default:
		return true
	}
}

var _ relayHandler = (*Outbound)(nil)

// itemIDOf is the inbox item's own id, which is what makes a routed push
// idempotent: two replicas reading the same replayed frame key their claims on
// the same notification rather than on the moment they read it.
func itemIDOf(item map[string]any) string {
	if s, _ := item["id"].(string); s != "" {
		return s
	}
	// Older payloads carry no id. Falling back to the type plus the issue it
	// belongs to is weaker than an id but still stable for one notification,
	// which is what the claim needs.
	t, _ := item["type"].(string)
	ref, _ := item["issue_id"].(string)
	return t + ":" + ref
}