Skip to content

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

Go

MUL-6570 feat(wecom): route a reply to the replica that holds the bot's socket (#7429)

Xichang(Seacen) Zhao1dd6b9ecdbaa
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index 2392c5a44e..dd83436c90 100644
--- a/SELF_HOSTING.md
+++ b/SELF_HOSTING.md
@@ -378,7 +378,12 @@ The Usage / Runtime dashboards read from a derived `task_usage_hourly` table pop
Multiple backend replicas are safe: each replica ticks every 30 seconds and tries to claim the current 5-minute UTC plan, but the unique key `(job_name, scope_kind, scope_id, plan_time)` means only one wins each plan. Inspect steady-state operation:
-> **Exception — WeCom (企业微信) smart bot must run single-replica.** Unlike Slack and Lark, whose outbound is stateless HTTP that any replica can perform, the WeCom smart bot's only outbound path is an in-process WebSocket long connection. Agent replies and inbox pushes are delivered only by the replica currently holding a given bot's connection lease. If you run more than one backend replica with WeCom enabled (`MULTICA_WECOM_SECRET_KEY` set), responses produced on a replica that does not hold the lease are silently dropped and the WeCom user sees nothing. Until cross-replica outbound routing lands, run the WeCom-enabled backend as a single replica. Everything else (including the rollup scheduler above) is multi-replica safe.
+> **WeCom (企业微信) smart bot and replica count.** Unlike Slack and Lark, whose outbound is stateless HTTP that any replica can perform, the WeCom smart bot's only outbound path is an in-process WebSocket long connection, held by the replica that owns that bot's lease. What happens to a reply produced on a *different* replica depends on the realtime relay:
+>
+> - **Sharded or dual relay mode (`REDIS_URL` set, the default with Redis):** the reply or inbox push is forwarded to the lease holder over the relay and delivered. Multi-replica WeCom is supported in this mode.
+> - **Legacy relay mode, or no Redis:** the reply is dropped and the WeCom user sees nothing. Run the WeCom-enabled backend as a single replica in this configuration.
+>
+> In **every** mode there is one residual window: a reply produced while *no* replica holds a live connection to that bot — all of them mid-reconnect — is not delivered. It is **counted**: the replica that routed it checks afterwards whether any replica ever claimed the delivery, and increments `multica_wecom_outbound_dropped_total{reason="no_live_connection"}` when none did, so the window can be measured on a deployment rather than guessed at. If a rare lost reply during reconnects is unacceptable, a single replica remains the most conservative deployment. Everything else (including the rollup scheduler above) is multi-replica safe.
```sql
SELECT plan_time, status, attempt, runner_id,
diff --git a/apps/docs/content/docs/channels.ja.mdx b/apps/docs/content/docs/channels.ja.mdx
index ac30b06b47..e9fe18f25b 100644
--- a/apps/docs/content/docs/channels.ja.mdx
+++ b/apps/docs/content/docs/channels.ja.mdx
@@ -98,7 +98,12 @@ MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
これらのキーは、保存された Bot の認証情報を暗号化します。生成、保管、ローテーションの方法は[環境変数](/environment-variables)を参照してください。Multica Cloud ではすでに設定済みです。
-WeCom はさらにバックエンドを**単一レプリカ**で運用する必要があります。送信経路が 1 つのプロセスが保持する WebSocket だけのため、他のレプリカで生成された返信は破棄されます。レプリカ間の送信ルーティングが実装されるまで、WeCom を有効にしたバックエンドは多重化しないでください。
+WeCom の送信経路は、1 つのプロセスが保持する WebSocket だけです。**別のレプリカ**で生成された返信がどうなるかは、リアルタイムリレーのモードによって決まります。
+
+- **シャード / デュアルリレーモード**(`REDIS_URL` を設定、Redis がある場合のデフォルト):返信は接続を保持するレプリカへ転送されて配信されます。**マルチレプリカ運用に対応しています。**
+- **レガシーリレーモード、または Redis なし**:返信は破棄されます。この構成では WeCom を有効にしたバックエンドを単一レプリカで運用してください。
+
+どのモードでも、**どのレプリカも**接続を保持していない瞬間(全て再接続中)に生成された返信は配信されません。ただし計測はされます。転送したレプリカが後からその配信をどのレプリカかが引き受けたかを確認し、誰も引き受けていなければ `multica_wecom_outbound_dropped_total{reason="no_live_connection"}` を加算するため、この窓の大きさは実測できます。この損失が許容できない場合は、単一レプリカが最も保守的な構成です。
## 次のステップ
diff --git a/apps/docs/content/docs/channels.ko.mdx b/apps/docs/content/docs/channels.ko.mdx
index 39904dac2d..b5f78e4358 100644
--- a/apps/docs/content/docs/channels.ko.mdx
+++ b/apps/docs/content/docs/channels.ko.mdx
@@ -98,7 +98,12 @@ MULTICA_TELEGRAM_SECRET_KEY=<base64로 인코딩한 32바이트 키>
이 키는 Bot 자격 증명을 암호화해 저장하는 데 사용됩니다. 생성, 보관, 교체 방법은 [환경 변수](/environment-variables)를 참고하세요. Multica Cloud에는 이미 설정되어 있습니다.
-WeCom은 추가로 백엔드를 **단일 레플리카**로 운영해야 합니다. 발신 경로가 한 프로세스가 보유한 WebSocket뿐이어서 다른 레플리카에서 생성된 응답은 폐기됩니다. 레플리카 간 발신 라우팅이 구현되기 전까지 WeCom을 켠 백엔드는 다중화하지 마세요.
+WeCom의 발신 경로는 한 프로세스가 보유한 WebSocket뿐입니다. **다른 레플리카**에서 생성된 응답이 어떻게 되는지는 실시간 릴레이 모드에 따라 달라집니다.
+
+- **샤딩 / 듀얼 릴레이 모드**(`REDIS_URL` 설정, Redis가 있을 때의 기본값): 응답이 연결을 보유한 레플리카로 전달되어 배달됩니다. **다중 레플리카 운영을 지원합니다.**
+- **레거시 릴레이 모드 또는 Redis 없음**: 응답이 폐기됩니다. 이 구성에서는 WeCom을 켠 백엔드를 단일 레플리카로 운영하세요.
+
+어떤 모드에서든 **어느 레플리카도** 연결을 보유하지 않은 순간(모두 재연결 중)에 생성된 응답은 배달되지 않습니다. 다만 집계는 됩니다. 응답을 전달한 레플리카가 이후에 어느 레플리카든 그 배달을 가져갔는지 확인하고, 아무도 가져가지 않았으면 `multica_wecom_outbound_dropped_total{reason="no_live_connection"}` 을 올리므로 이 구간의 크기를 실제로 측정할 수 있습니다. 이 손실을 허용할 수 없다면 단일 레플리카가 가장 보수적인 구성입니다.
## 다음 단계
diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdx
index 16815565af..cc49e5d37b 100644
--- a/apps/docs/content/docs/channels.mdx
+++ b/apps/docs/content/docs/channels.mdx
@@ -98,7 +98,12 @@ MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
These keys encrypt stored Bot credentials. See [Environment variables](/environment-variables) for how to generate, store, and rotate them. Multica Cloud already has this configured.
-WeCom additionally requires a **single backend replica**: its only outbound path is the WebSocket held by one process, so replies produced on another replica are dropped. Run the WeCom-enabled backend unreplicated until cross-replica outbound routing lands.
+WeCom's only outbound path is the WebSocket held by one process, so what happens to a reply produced on a *different* replica depends on the realtime relay:
+
+- **Sharded or dual relay mode** (`REDIS_URL` set — the default with Redis): the reply is forwarded to the replica holding the connection and delivered. Multi-replica WeCom is supported.
+- **Legacy relay mode, or no Redis**: the reply is dropped. Run the WeCom-enabled backend as a single replica in this configuration.
+
+In every mode, a reply produced while *no* replica holds a live connection (all mid-reconnect) is not delivered. It is counted as `multica_wecom_outbound_dropped_total{reason="no_live_connection"}` by the replica that routed it, so the size of that window is measurable; if the loss is unacceptable, a single replica remains the most conservative deployment.
## Next steps
diff --git a/apps/docs/content/docs/channels.zh.mdx b/apps/docs/content/docs/channels.zh.mdx
index 59cef53e85..4a6b0c8078 100644
--- a/apps/docs/content/docs/channels.zh.mdx
+++ b/apps/docs/content/docs/channels.zh.mdx
@@ -98,7 +98,12 @@ MULTICA_TELEGRAM_SECRET_KEY=<base64 编码的 32 字节密钥>
这些密钥用于加密保存 Bot 凭据。生成、保存和轮换方法见[环境变量](/environment-variables)。Multica Cloud 已完成这项配置。
-企业微信还要求后端**只部署单个副本**:它的出站只有一条路径,即某个进程持有的 WebSocket,因此在其他副本上产生的回复会被丢弃。在跨副本出站路由实现之前,请不要对启用企业微信的后端做多副本部署。
+企业微信的出站只有一条路径——某个进程持有的 WebSocket。回复产生在**其他副本**上时会发生什么,取决于实时中继(realtime relay)的模式:
+
+- **分片或双写中继模式**(配置了 `REDIS_URL`,有 Redis 时的默认):回复会转发给持有连接的副本并送达,**支持多副本部署**。
+- **legacy 中继模式,或没有 Redis**:回复会被丢弃。这种配置下请把启用企业微信的后端保持单副本。
+
+任何模式下都有一个残留窗口:回复产生时**没有任何副本**持有活连接(全部在重连中),这条回复不会送达。但它会被记录下来——转发它的副本事后会去确认有没有副本认领过这次投递,没有就给 `multica_wecom_outbound_dropped_total{reason="no_live_connection"}` 加一,所以这个窗口有多大是能实测出来的。如果这种丢失不可接受,单副本仍是最保守的部署方式。
## 接下来
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 5a5fee3a62..db9cc15391 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -9,6 +9,7 @@ import (
"os/signal"
"strconv"
"strings"
+ "sync"
"syscall"
"time"
@@ -19,6 +20,7 @@ import (
"github.com/multica-ai/multica/server/internal/dbstartup"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/integrations/wecom"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/profiling"
@@ -372,6 +374,16 @@ func main() {
go hub.Run()
daemonHub := daemonws.NewHub()
var daemonWakeup service.TaskWakeupNotifier = daemonHub
+ // Nil unless a Redis relay is running: without one there is only one
+ // replica, and it both publishes the completion and holds the socket.
+ var wecomRelay WecomRelay
+ // Built here rather than in the router because the relay's shard readers
+ // start before the router exists, and a deliverer registered after they
+ // start would miss the replay window they open with. The registry is a
+ // bare map with no dependencies, so it can be minted this early and handed
+ // down.
+ wecomSenders := wecom.NewSendersRegistry()
+ var wecomRelayOutbound *wecom.RelayOutbound
// MUL-1138: when REDIS_URL is set, route fanout through a Redis relay so
// multiple API nodes can deliver each other's events. Without it the hub
@@ -389,14 +401,31 @@ func main() {
var shardedReadRedis *redis.Client
var legacyReadRedis *redis.Client
var relay realtime.ManagedRelay
+ // stopRelay halts the relay readers and drains the WeCom dispatcher. It is
+ // called from the shutdown BODY, before the channel supervisor is torn
+ // down — the dispatcher's drain sends over the sockets the supervisor
+ // owns, and each supervised connection clears its sender on exit, so a
+ // drain that runs after that teardown finds ownsSocket false for every
+ // installation and discards everything it was built to save. The defer
+ // keeps a second call (idempotent via the Once) for the early-return
+ // paths that never reach the body's shutdown sequence.
+ var stopRelayOnce sync.Once
+ stopRelay := func() {
+ stopRelayOnce.Do(func() {
+ if relay != nil {
+ relay.Stop()
+ }
+ relayCancel()
+ if relay != nil {
+ relay.Wait()
+ }
+ // Join the dispatcher BEFORE its Redis clients go away, or the
+ // drain races the teardown it depends on.
+ wecomRelayOutbound.Wait()
+ })
+ }
defer func() {
- if relay != nil {
- relay.Stop()
- }
- relayCancel()
- if relay != nil {
- relay.Wait()
- }
+ stopRelay()
closeRedisClient("realtime-read-legacy", legacyReadRedis)
closeRedisClient("realtime-read-sharded", shardedReadRedis)
closeRedisClient("realtime-read", relayReadRedis)
@@ -435,6 +464,7 @@ func main() {
legacyReadRedis = newNamedRedisClient(opts, "realtime-read-legacy")
sharded := realtime.NewShardedStreamRelay(hub, relayWriteRedis, shardedReadRedis, relayConfig)
sharded.SetDaemonRuntimeDeliverer(daemonHub)
+ wecomRelay = sharded
legacy := realtime.NewRedisRelayWithClientsAndConfig(hub, relayWriteRedis, legacyReadRedis, relayConfig.RetentionConfig())
relay = realtime.NewMirroredRelay(sharded, legacy)
daemonWakeup = daemonws.NewRelayNotifier(daemonHub, sharded)
@@ -442,9 +472,33 @@ func main() {
relayReadRedis = newNamedRedisClient(opts, "realtime-read")
sharded := realtime.NewShardedStreamRelay(hub, relayWriteRedis, relayReadRedis, relayConfig)
sharded.SetDaemonRuntimeDeliverer(daemonHub)
+ wecomRelay = sharded
relay = sharded
daemonWakeup = daemonws.NewRelayNotifier(daemonHub, sharded)
}
+ if wecomRelay != nil {
+ // LeaseSettle comes from the supervisor's own knob rather than
+ // from a constant here: the re-offer chain exists to outlast a
+ // lease move, and how long that takes is the supervisor's poll
+ // interval, which a deployment can tune.
+ leaseSettle, err := channelLeasePollInterval()
+ if err != nil {
+ slog.Warn("wecom relay: unreadable lease poll interval, using the dispatcher default",
+ "error", err)
+ leaseSettle = 0
+ }
+ wecomRelayOutbound = wecom.NewRelayOutbound(wecomRelay,
+ wecom.NewRedisDedupe(relayWriteRedis, 0, slog.Default()),
+ wecom.RelayConfig{
+ ReplayGrace: relayConfig.ReplayGrace,
+ LeaseSettle: leaseSettle,
+ }, slog.Default())
+ wecomRelay.SetWecomOutboundDeliverer(wecomRelayOutbound)
+ wecomRelayOutbound.Start(relayCtx)
+ }
+ // Every deliverer is registered by this point. The shard readers
+ // open on a replay window, so anything registered after Start
+ // silently misses it.
relay.Start(relayCtx)
broadcaster = realtime.NewDualWriteBroadcaster(hub, relay)
storePoolSize := 0
@@ -577,6 +631,8 @@ func main() {
WecomMetrics: wecomMetrics,
DaemonHub: daemonHub,
DaemonWakeup: daemonWakeup,
+ WecomSenders: wecomSenders,
+ WecomRelayOutbound: wecomRelayOutbound,
FeatureFlags: flags,
HeartbeatScheduler: heartbeatScheduler,
LLMMaxRetries: llmMaxRetries,
@@ -732,69 +788,78 @@ func main() {
signal.Stop(quit)
slog.Info("shutting down server")
- autopilotCancel()
-
- // Order matters: drain in-flight HTTP first so any heartbeat handlers
- // finish calling Schedule() before we stop the scheduler. Otherwise a
- // late heartbeat could enqueue a pending ID after Run has already
- // drained and exited, and Stop() would not flush it.
- apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
- if err := srv.Shutdown(apiShutdownCtx); err != nil {
- apiShutdownCancel()
- slog.Error("server forced to shutdown", "error", err)
- os.Exit(1)
- }
- apiShutdownCancel()
-
- // HTTP is fully drained — safe to stop the sweeper and flush the
- // final batch of queued heartbeat bumps.
- sweepCancel()
- heartbeatScheduler.Stop()
- if h.WebhookDeliveryWorker != nil && !h.WebhookDeliveryWorker.WaitWithTimeout(5*time.Second) {
- slog.Warn("webhook delivery worker did not exit within shutdown timeout")
- }
- if h.TelegramOutbound != nil && !h.TelegramOutbound.WaitWithTimeout(5*time.Second) {
- slog.Warn("telegram outbound workers did not exit within shutdown timeout")
- }
-
- // Join the channel supervisor's per-installation goroutines so the
- // lease renewer can issue a final release before process exit;
- // otherwise the next replica would have to wait the full LeaseTTL
- // before picking up the installation on the other side of the
- // redeploy. The wait is bounded — if a supervisor is wedged (DB
- // pool stalled, a connector ignoring ctx, etc.) the fallback is the
- // natural LeaseTTL expiry on the other side, which is strictly better
- // than holding shutdown open forever. Then drain the Feishu runtime:
- // the supervisors have stopped delivering inbound events, so flush the
- // debounced run triggers and join any in-flight outbound replies
- // (each bounded by ReplyTimeout) so a binding card / offline notice is
- // not lost on shutdown.
- if h.ChannelSupervisor != nil {
- if !h.ChannelSupervisor.WaitWithTimeout(h.ChannelSupervisor.ShutdownTimeout()) {
- slog.Warn("channel supervisor: connections did not exit within shutdown timeout; proceeding",
- "timeout", h.ChannelSupervisor.ShutdownTimeout().String(),
- )
- }
- if h.ChannelRouter != nil {
+
+ // The order below is the contract, and shutdown.go is where it is stated
+ // and pinned. The one that is not self-evident: the WeCom dispatcher must
+ // be drained BEFORE sweepCancel, not merely before the supervisor is
+ // joined — cancelling the sweeper context is already what makes every
+ // supervised connection clear its sender, and a drain past that point
+ // finds no socket to deliver over.
+ shutdownSequence{
+ StopAutopilot: autopilotCancel,
+ DrainHTTP: func() {
+ apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ if err := srv.Shutdown(apiShutdownCtx); err != nil {
+ apiShutdownCancel()
+ slog.Error("server forced to shutdown", "error", err)
+ os.Exit(1)
+ }
+ apiShutdownCancel()
+ },
+ StopOutboundRelay: stopRelay,
+ CancelWorkers: sweepCancel,
+ StopHeartbeats: heartbeatScheduler.Stop,
+ JoinWebhookWorker: func() {
+ if h.WebhookDeliveryWorker != nil && !h.WebhookDeliveryWorker.WaitWithTimeout(5*time.Second) {
+ slog.Warn("webhook delivery worker did not exit within shutdown timeout")
+ }
+ },
+ JoinTelegram: func() {
+ if h.TelegramOutbound != nil && !h.TelegramOutbound.WaitWithTimeout(5*time.Second) {
+ slog.Warn("telegram outbound workers did not exit within shutdown timeout")
+ }
+ },
+ // Joined so the lease renewer can issue a final release before exit;
+ // otherwise the next replica waits out the whole LeaseTTL on the far
+ // side of a redeploy. Bounded: a wedged supervisor falls back to the
+ // natural expiry rather than holding shutdown open.
+ JoinChannelSupervisor: func() {
+ if h.ChannelSupervisor == nil {
+ return
+ }
+ if !h.ChannelSupervisor.WaitWithTimeout(h.ChannelSupervisor.ShutdownTimeout()) {
+ slog.Warn("channel supervisor: connections did not exit within shutdown timeout; proceeding",
+ "timeout", h.ChannelSupervisor.ShutdownTimeout().String(),
+ )
+ }
+ },
+ DrainChannelRouter: func() {
+ if h.ChannelSupervisor == nil || h.ChannelRouter == nil {
+ return
+ }
drainCtx, drainCancel := context.WithTimeout(context.Background(), 10*time.Second)
if !h.ChannelRouter.Drain(drainCtx) {
slog.Warn("channel router: drain deadline reached; deferred media fallback remains durable")
}
drainCancel()
- }
- }
-
- if metricsServer != nil {
- metricsShutdownCtx, metricsShutdownCancel := context.WithTimeout(context.Background(), 3*time.Second)
- if err := metricsServer.Shutdown(metricsShutdownCtx); err != nil {
- slog.Error("metrics server forced to shutdown", "error", err)
- }
- metricsShutdownCancel()
- }
- profilingShutdownCtx, profilingShutdownCancel := context.WithTimeout(context.Background(), 3*time.Second)
- if err := profilingServer.Shutdown(profilingShutdownCtx); err != nil {
- slog.Error("pprof server forced to shutdown", "error", err)
- }
- profilingShutdownCancel()
+ },
+ StopMetricsServer: func() {
+ if metricsServer == nil {
+ return
+ }
+ metricsShutdownCtx, metricsShutdownCancel := context.WithTimeout(context.Background(), 3*time.Second)
+ if err := metricsServer.Shutdown(metricsShutdownCtx); err != nil {
+ slog.Error("metrics server forced to shutdown", "error", err)
+ }
+ metricsShutdownCancel()
+ },
+ StopProfiling: func() {
+ profilingShutdownCtx, profilingShutdownCancel := context.WithTimeout(context.Background(), 3*time.Second)
+ if err := profilingServer.Shutdown(profilingShutdownCtx); err != nil {
+ slog.Error("pprof server forced to shutdown", "error", err)
+ }
+ profilingShutdownCancel()
+ },
+ }.run()
slog.Info("server stopped")
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index eaa3f9a31c..f044a832d8 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -220,6 +220,22 @@ type RouterOptions struct {
// ChannelLeaseRedis is a dedicated non-blocking Redis client/pool. It is
// required only when CHANNEL_WS_LEASE_BACKEND=redis.
ChannelLeaseRedis *redis.Client
+ // WecomRelay is the realtime relay, seen through the two halves the WeCom
+ // adapter needs: publish a reply to the other replicas, and register as
+ // the consumer that delivers the ones they publish. Nil on a deployment
+ // with no Redis — where it is also unnecessary, because one replica both
+ // publishes the completion and holds the socket.
+ // WecomSenders is the process-wide installation→socket registry, minted in
+ // main so the relay's deliverer can be registered before the shard readers
+ // start. Nil is tolerated (tests, embedders): one is minted here instead.
+ WecomSenders *wecom.SendersRegistry
+
+ // WecomRelayOutbound is the cross-replica router, already registered with
+ // the relay and running. Nil on a deployment with no Redis, where it is
+ // also unnecessary: one replica publishes the completion and holds the
+ // socket both.
+ WecomRelayOutbound *wecom.RelayOutbound
+
// WecomMetrics is the WeCom adapter's health sink. Nil discards every
// counter, which is what a deployment with /metrics turned off gets.
WecomMetrics *obsmetrics.WecomMetrics
@@ -294,6 +310,19 @@ func buildChannelSupervisor(
return engine.NewSupervisor(installations, leases, registry, inbound, cfg)
}
+// channelLeasePollInterval is how often a Supervisor scans for installations
+// it should be holding, and therefore how long a WebSocket lease takes to
+// finish moving to another replica.
+//
+// Read through one function because two places are sized by it: the supervisor
+// itself, and the WeCom cross-replica dispatcher's re-offer chain — a frame
+// that arrives mid-move has to stay offerable until the move completes, and
+// pinning that to a constant of its own would let the two drift apart on any
+// deployment that tunes the knob.
+func channelLeasePollInterval() (time.Duration, error) {
+ return strictPositiveDurationEnv("CHANNEL_WS_LEASE_POLL_INTERVAL", 30*time.Second)
+}
+
func channelSupervisorConfigFromEnv(leaseMetrics *obsmetrics.ChannelLeaseMetrics) (engine.Config, error) {
ttl, err := strictPositiveDurationEnv("CHANNEL_WS_LEASE_TTL", 180*time.Second)
if err != nil {
@@ -303,7 +332,7 @@ func channelSupervisorConfigFromEnv(leaseMetrics *obsmetrics.ChannelLeaseMetrics
if err != nil {
return engine.Config{}, err
}
- poll, err := strictPositiveDurationEnv("CHANNEL_WS_LEASE_POLL_INTERVAL", 30*time.Second)
+ poll, err := channelLeasePollInterval()
if err != nil {
return engine.Config{}, err
}
@@ -898,7 +927,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// ChannelDeps write side and the Replier read side both
// receive it, and each Channel.Connect self-registers on
// entry and clears on exit.
- wecomSenders := wecom.NewSendersRegistry()
+ wecomSenders := opts.WecomSenders
+ if wecomSenders == nil {
+ wecomSenders = wecom.NewSendersRegistry()
+ }
wecomReplier := wecom.NewOutboundReplier(wecom.OutboundReplierConfig{
Binding: wecomBinding,
@@ -973,7 +1005,23 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// as "the bot cannot connect".
wecomOutboundOpts = append(wecomOutboundOpts,
wecom.WithOutboundMetrics(wecomMetricsOrNil(opts.WecomMetrics)))
- wecom.NewOutbound(queries, wecomSenders, slog.Default(), wecomOutboundOpts...).Register(bus)
+ // Cross-replica routing. Built here rather than in main
+ // because the senders registry it guards is created here, and
+ // registered back onto the relay so every node's read loop
+ // reaches it. See wecom/relay_outbound.go.
+ if opts.WecomRelayOutbound != nil {
+ opts.WecomRelayOutbound.SetMetrics(wecomMetricsOrNil(opts.WecomMetrics))
+ wecomOutboundOpts = append(wecomOutboundOpts, wecom.WithRelay(opts.WecomRelayOutbound))
+ slog.Info("wecom integration: cross-replica outbound routing enabled")
+ }
+ wecomOutbound := wecom.NewOutbound(queries, wecomSenders, slog.Default(), wecomOutboundOpts...)
+ wecomOutbound.Register(bus)
+ // The dispatcher has been consuming since before this router
+ // existed; this is where it learns who performs a delivery.
+ // Anything it read in the meantime is waiting in its queue.
+ if opts.WecomRelayOutbound != nil {
+ opts.WecomRelayOutbound.Attach(wecomOutbound)
+ }
// Ranges the media fetcher may dial despite looking reserved.
// Empty by default, which leaves the SSRF guard exactly as
@@ -1011,7 +1059,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// limiting), not "more than one replica". See wecom/outbound.go
// and SELF_HOSTING.md. Remove once outbound routes to the lease
// holder.
- slog.Warn("wecom integration: WeCom agent replies and inbox pushes are delivered only by the replica holding each bot's WebSocket lease. If you run more than one backend replica, responses produced on a replica that does not hold the lease will be dropped — run the WeCom-enabled backend as a single replica until cross-replica outbound routing is implemented.")
+ if opts.WecomRelayOutbound != nil {
+ slog.Info("wecom integration: cross-replica outbound routing enabled — agent replies and inbox pushes produced on a replica that does not hold the bot's WebSocket lease are forwarded to the lease holder over the realtime relay. A reply produced while NO replica holds a live connection (every one mid-reconnect) is still lost; see wecom/relay_outbound.go.")
+ } else {
+ slog.Warn("wecom integration: WeCom agent replies and inbox pushes are delivered only by the replica holding each bot's WebSocket lease. If you run more than one backend replica, responses produced on a replica that does not hold the lease will be dropped — run the WeCom-enabled backend as a single replica, or run a sharded/dual realtime relay (REDIS_URL), which enables cross-replica outbound routing.")
+ }
}
}
} else {
@@ -2430,6 +2482,15 @@ func composioCallbackBaseURL(publicURL string) string {
return appURLFromEnv()
}
+// WecomRelay is what the WeCom adapter needs from the realtime relay:
+// publish under ScopeWecomOutbound, and register the consumer that acts on
+// frames the other replicas publish. *realtime.ShardedStreamRelay and
+// *realtime.RedisRelay both satisfy it.
+type WecomRelay interface {
+ PublishWithID(scopeType, scopeID, exclude string, frame []byte, id string) error
+ SetWecomOutboundDeliverer(d realtime.WecomOutboundDeliverer)
+}
+
// wecomMetricsOrNil keeps a typed nil out of the adapter's interface field.
// A *WecomMetrics that is nil still satisfies wecom.Metrics, so assigning it
// directly would give the adapter a non-nil interface holding a nil pointer —
diff --git a/server/cmd/server/shutdown.go b/server/cmd/server/shutdown.go
new file mode 100644
index 0000000000..711e2dd526
--- /dev/null
+++ b/server/cmd/server/shutdown.go
@@ -0,0 +1,79 @@
+package main
+
+// shutdown.go — the order teardown runs in, as named steps rather than as the
+// order statements happen to appear in main().
+//
+// It is a type because one of the orderings is load-bearing and invisible at
+// the call site. The WeCom cross-replica dispatcher delivers over the
+// WebSockets the channel supervisor owns, and every supervised connection
+// clears its sender from the registry as it exits. The supervisor starts
+// exiting the moment its context is cancelled — not when it is joined — so
+// "stop the relay before joining the supervisor" is not enough: by then the
+// registry is already empty and the dispatcher's drain finds no socket for any
+// installation and discards everything it exists to save.
+//
+// So the relay stop has to come before the cancel, and a comment saying so is
+// exactly the kind of claim that quietly stops being true. TestShutdownSequence
+// pins it against this type.
+
+// shutdownSequence is every teardown step, in the order it must run. A nil step
+// is skipped, which is what lets a deployment without a metrics server or
+// without channels use the same sequence.
+type shutdownSequence struct {
+ // StopAutopilot first: it schedules work the rest of the system performs.
+ StopAutopilot func()
+
+ // DrainHTTP before anything that serves it. In-flight handlers finish
+ // calling Schedule() before the scheduler stops, and no new task
+ // completion can arrive after this — which is what makes the relay stop
+ // below a drain rather than a race.
+ DrainHTTP func()
+
+ // StopOutboundRelay BEFORE CancelWorkers. See the file header: the
+ // dispatcher's drain can only deliver while the supervised sockets are
+ // still live, and CancelWorkers is what starts tearing them down.
+ StopOutboundRelay func()
+
+ // CancelWorkers cancels the sweeper context every background loop is
+ // bound to, including the channel supervisor.
+ CancelWorkers func()
+
+ // StopHeartbeats flushes the final batch of queued heartbeat bumps.
+ StopHeartbeats func()
+
+ JoinWebhookWorker func()
+ JoinTelegram func()
+
+ // JoinChannelSupervisor waits for the per-installation goroutines so the
+ // lease renewer can issue a final release before exit; without it the next
+ // replica waits out the whole LeaseTTL after a redeploy.
+ JoinChannelSupervisor func()
+
+ // DrainChannelRouter flushes debounced run triggers and joins in-flight
+ // outbound replies, now that no supervisor is delivering inbound events.
+ DrainChannelRouter func()
+
+ StopMetricsServer func()
+ StopProfiling func()
+}
+
+// run performs the sequence. The order here IS the contract.
+func (s shutdownSequence) run() {
+ for _, step := range []func(){
+ s.StopAutopilot,
+ s.DrainHTTP,
+ s.StopOutboundRelay,
+ s.CancelWorkers,
+ s.StopHeartbeats,
+ s.JoinWebhookWorker,
+ s.JoinTelegram,
+ s.JoinChannelSupervisor,
+ s.DrainChannelRouter,
+ s.StopMetricsServer,
+ s.StopProfiling,
+ } {
+ if step != nil {
+ step()
+ }
+ }
+}
diff --git a/server/cmd/server/shutdown_test.go b/server/cmd/server/shutdown_test.go
new file mode 100644
index 0000000000..c9760b8e3b
--- /dev/null
+++ b/server/cmd/server/shutdown_test.go
@@ -0,0 +1,79 @@
+package main
+
+import (
+ "slices"
+ "testing"
+)
+
+// The order teardown runs in is a contract, and one link in it is the kind that
+// a comment can claim while the code does the opposite: the WeCom cross-replica
+// dispatcher delivers over sockets the channel supervisor owns, each supervised
+// connection clears its sender as it exits, and the supervisor starts exiting
+// the moment its context is cancelled — not when it is joined.
+//
+// So "relay before supervisor" has to mean "relay before the CANCEL", and this
+// pins it against the same type main() runs.
+func TestShutdownSequence_RunsInTheDocumentedOrder(t *testing.T) {
+ var ran []string
+ record := func(name string) func() {
+ return func() { ran = append(ran, name) }
+ }
+ shutdownSequence{
+ StopAutopilot: record("autopilot"),
+ DrainHTTP: record("http"),
+ StopOutboundRelay: record("relay"),
+ CancelWorkers: record("cancel"),
+ StopHeartbeats: record("heartbeats"),
+ JoinWebhookWorker: record("webhooks"),
+ JoinTelegram: record("telegram"),
+ JoinChannelSupervisor: record("supervisor"),
+ DrainChannelRouter: record("router"),
+ StopMetricsServer: record("metrics"),
+ StopProfiling: record("pprof"),
+ }.run()
+
+ want := []string{
+ "autopilot", "http", "relay", "cancel", "heartbeats",
+ "webhooks", "telegram", "supervisor", "router", "metrics", "pprof",
+ }
+ if !slices.Equal(ran, want) {
+ t.Fatalf("shutdown order = %v, want %v", ran, want)
+ }
+}
+
+// The one ordering with a user-visible consequence, asserted on its own so a
+// future reshuffle fails with the reason attached rather than as a diff of two
+// long lists.
+func TestShutdownSequence_DrainsTheOutboundRelayBeforeCancellingTheWorkers(t *testing.T) {
+ var ran []string
+ shutdownSequence{
+ StopOutboundRelay: func() { ran = append(ran, "relay") },
+ CancelWorkers: func() { ran = append(ran, "cancel") },
+ }.run()
+
+ relay := slices.Index(ran, "relay")
+ cancel := slices.Index(ran, "cancel")
+ if relay < 0 || cancel < 0 {
+ t.Fatalf("both steps must run, got %v", ran)
+ }
+ if relay > cancel {
+ t.Fatal("the relay drain runs after the worker cancel — by then every supervised " +
+ "connection has cleared its sender, so the drain finds no socket for any " +
+ "installation and discards the replies it exists to save")
+ }
+}
+
+// A deployment without channels, without a metrics server, or without a
+// Telegram worker leaves those steps nil. Skipping them must not skip the rest.
+func TestShutdownSequence_SkipsTheStepsADeploymentDoesNotHave(t *testing.T) {
+ var ran []string
+ shutdownSequence{
+ DrainHTTP: func() { ran = append(ran, "http") },
+ CancelWorkers: func() { ran = append(ran, "cancel") },
+ StopProfiling: func() { ran = append(ran, "pprof") },
+ }.run()
+
+ if want := []string{"http", "cancel", "pprof"}; !slices.Equal(ran, want) {
+ t.Fatalf("shutdown order = %v, want %v", ran, want)
+ }
+}
diff --git a/server/internal/integrations/channel/engine/supervisor.go b/server/internal/integrations/channel/engine/supervisor.go
index ec51b671ac..76c1c17ea2 100644
--- a/server/internal/integrations/channel/engine/supervisor.go
+++ b/server/internal/integrations/channel/engine/supervisor.go
@@ -179,15 +179,33 @@ type Config struct {
LeaseMetrics LeaseMetrics
}
+// The defaults are named and exported because they are not private taste:
+// other packages are sized against them. The WeCom cross-replica dispatcher
+// re-offers a frame until a lease has finished moving, which takes one
+// DefaultPollInterval, and drains inside a shutdown bounded by
+// DefaultShutdownTimeout. A copy of either number over there would be a second
+// definition free to drift from this one.
+const (
+ // DefaultLeaseTTL is how long a lease grant stays valid unrenewed.
+ DefaultLeaseTTL = 180 * time.Second
+ // DefaultPollInterval is how often a Supervisor scans for installations it
+ // should be holding, and therefore how long a lease takes to move to
+ // another replica.
+ DefaultPollInterval = 30 * time.Second
+ // DefaultShutdownTimeout bounds how long Wait blocks joining the
+ // per-installation goroutines.
+ DefaultShutdownTimeout = 15 * time.Second
+)
+
func (c Config) withDefaults() Config {
if c.LeaseTTL == 0 {
- c.LeaseTTL = 180 * time.Second
+ c.LeaseTTL = DefaultLeaseTTL
}
if c.LeaseRenewInterval == 0 {
c.LeaseRenewInterval = min(60*time.Second, c.LeaseTTL/3)
}
if c.PollInterval == 0 {
- c.PollInterval = min(30*time.Second, c.LeaseRenewInterval/2)
+ c.PollInterval = min(DefaultPollInterval, c.LeaseRenewInterval/2)
}
if c.LeaseErrorRetryInterval == 0 {
c.LeaseErrorRetryInterval = min(5*time.Second, c.LeaseRenewInterval/4)
@@ -214,7 +232,7 @@ func (c Config) withDefaults() Config {
c.RotationWaitTimeout = c.DisconnectTimeout + c.LeaseReleaseTimeout
}
if c.ShutdownTimeout == 0 {
- c.ShutdownTimeout = 15 * time.Second
+ c.ShutdownTimeout = DefaultShutdownTimeout
}
if c.Now == nil {
c.Now = time.Now
diff --git a/server/internal/integrations/wecom/dedupe_redis.go b/server/internal/integrations/wecom/dedupe_redis.go
new file mode 100644
index 0000000000..867ed155a2
--- /dev/null
+++ b/server/internal/integrations/wecom/dedupe_redis.go
@@ -0,0 +1,82 @@
+package wecom
+
+// dedupe_redis.go — the at-most-once claim behind a routed delivery.
+//
+// It lives on the same Redis the relay itself runs on, which is the whole
+// reason this is not a new dependency: no Redis means no relay, which means no
+// cross-replica routing and nothing to deduplicate. A deployment that never
+// needed Redis is not asked for it now.
+//
+// SET NX PX is the claim. One key per turn, keyed on the same event id the
+// stream entry carries, so a frame replayed after a restart and a frame read
+// by two replicas mid-lease-move meet the same key.
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// redisDedupe is a DedupeStore backed by one Redis key per delivery.
+type redisDedupe struct {
+ rdb *redis.Client
+ log *slog.Logger
+ budget time.Duration
+}
+
+// NewRedisDedupe builds the production claim store. A nil client yields nil,
+// which RelayOutbound reads as "no cross-restart claim" — correct only where
+// there is no relay either. A budget of zero takes defaultClaimBudget; tests
+// shrink it so the outcome grace derived from it stays a test's worth of time.
+func NewRedisDedupe(rdb *redis.Client, budget time.Duration, log *slog.Logger) DedupeStore {
+ if rdb == nil {
+ return nil
+ }
+ if log == nil {
+ log = slog.Default()
+ }
+ if budget <= 0 {
+ budget = defaultClaimBudget
+ }
+ return &redisDedupe{rdb: rdb, log: log, budget: budget}
+}
+
+// defaultClaimBudget bounds one round trip. A dispatcher worker waiting on
+// Redis is a worker not delivering, and the frame is replayable, so failing
+// fast and letting the replay bring it back beats holding the queue.
+const defaultClaimBudget = 2 * time.Second
+
+// ClaimBudget reports the bound this store actually applies, which is what
+// sizes RelayOutbound.outcomeGrace.
+func (d *redisDedupe) ClaimBudget() time.Duration { return d.budget }
+
+func (d *redisDedupe) Claim(ctx context.Context, key string, ttl time.Duration) (bool, error) {
+ ctx, cancel := context.WithTimeout(ctx, d.budget)
+ defer cancel()
+ return d.rdb.SetNX(ctx, key, "1", ttl).Result()
+}
+
+// Held reports whether a claim is currently taken. One EXISTS, on the same
+// bounded budget as the claim itself: the caller is deciding whether to record
+// a lost reply, and a Redis that cannot answer must not become evidence.
+func (d *redisDedupe) Held(ctx context.Context, key string) (bool, error) {
+ ctx, cancel := context.WithTimeout(ctx, d.budget)
+ defer cancel()
+ n, err := d.rdb.Exists(ctx, key).Result()
+ return n > 0, err
+}
+
+// Release gives a claim back for a delivery that provably did not happen.
+// Best effort by design: a Release that fails leaves a key that expires on its
+// own, which costs one un-retried delivery in the replay window rather than a
+// duplicate in somebody's chat.
+func (d *redisDedupe) Release(ctx context.Context, key string) {
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), d.budget)
+ defer cancel()
+ if err := d.rdb.Del(ctx, key).Err(); err != nil {
+ d.log.WarnContext(ctx, "wecom relay: could not release a delivery claim",
+ "error", err, "key", key)
+ }
+}
diff --git a/server/internal/integrations/wecom/metrics.go b/server/internal/integrations/wecom/metrics.go
index c179935fae..d993f8c4aa 100644
--- a/server/internal/integrations/wecom/metrics.go
+++ b/server/internal/integrations/wecom/metrics.go
@@ -94,6 +94,23 @@ type Metrics interface {
// rate would be paged for deliveries that happened.
RecordOutboundUnconfirmed(reason string)
RecordAttachmentUnconfirmed(reason string)
+
+ // RecordRelayShed counts an ADMISSION decision on the cross-replica
+ // dispatcher: one routed frame refused because its queue was full. Its own
+ // unit, labelled by what kind of frame it was, because the reply counters
+ // above are per REPLY and the relay carries inbox notifications too — an
+ // inbox push counted as a dropped reply would make the delivered/dropped
+ // ratio track which replica happened to hold a socket rather than any
+ // outcome. Always recorded, on whichever replica refused the frame.
+ //
+ // It moves no reply counter, not even on the replica holding the socket.
+ // Every replica reads every frame, and during a lease handoff two of them
+ // hold a sender at once, so no replica can tell locally whether its own
+ // shed cost the user anything — each one answering for itself is what
+ // reported a single reply as delivered and dropped together. Whether a shed
+ // reply was really lost is settled once by the replica that routed it, in
+ // RelayOutbound.watchOutcomes.
+ RecordRelayShed(kind string)
}
// nopMetrics is what the constructor falls back to. A nil sink must never be a
@@ -112,6 +129,7 @@ func (nopMetrics) RecordAttachmentDropped(string) {}
func (nopMetrics) RecordAttachmentDeliveryShed() {}
func (nopMetrics) RecordOutboundUnconfirmed(string) {}
func (nopMetrics) RecordAttachmentUnconfirmed(string) {}
+func (nopMetrics) RecordRelayShed(string) {}
// orNopMetrics turns an unset sink into one that is safe to call.
func orNopMetrics(m Metrics) Metrics {
diff --git a/server/internal/integrations/wecom/metrics_test.go b/server/internal/integrations/wecom/metrics_test.go
index ffce6c0876..61e32988f3 100644
--- a/server/internal/integrations/wecom/metrics_test.go
+++ b/server/internal/integrations/wecom/metrics_test.go
@@ -63,6 +63,10 @@ func (m *countingMetrics) RecordAttachmentDropped(reason string) {
m.bump("attachment_dropped:" + reason)
}
func (m *countingMetrics) RecordAttachmentDeliveryShed() { m.bump("attachment_shed") }
+func (m *countingMetrics) RecordRelayShed(kind string) {
+ m.bump("relay_shed")
+ m.bump("relay_shed:" + kind)
+}
func (m *countingMetrics) RecordOutboundUnconfirmed(reason string) {
m.bump("outbound_unconfirmed")
m.bump("outbound_unconfirmed:" + reason)
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index 025ee5d6ff..c8e98d02b2 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -12,15 +12,21 @@ package wecom
// same way OutboundReplier's messages do (markdown msgtype, which
// renders plaintext without escaping).
//
-// SINGLE-REPLICA CONSTRAINT: WeCom's only outbound path is the in-process
-// WebSocket held in the sendersRegistry, but EventChatDone / EventInboxNew are
-// dispatched on the in-process events.Bus. On a multi-replica deployment the
-// replica that publishes the event is not necessarily the one holding the
-// bot's WS lease, so senders.get() returns nil and the reply cannot be
-// delivered from here (Slack/Lark are immune — their outbound is stateless
-// HTTP any replica can perform). Until outbound is routed to the lease holder,
-// a WeCom-enabled backend must run as a single replica; boot emits a warning
-// when a multi-replica setup (REDIS_URL) is detected. See router.go.
+// REPLICA TOPOLOGY: WeCom's only outbound path is the in-process WebSocket
+// held in the sendersRegistry, but EventChatDone / EventInboxNew are
+// dispatched on the in-process events.Bus, so the replica that publishes an
+// event is not necessarily the one holding the bot's WS lease (Slack/Lark are
+// immune — their outbound is stateless HTTP any replica can perform).
+//
+// With a sharded/dual realtime relay running, a reply or inbox push produced
+// off-lease is forwarded to the lease holder over the relay
+// (relay_outbound.go) and the single-replica constraint no longer applies to
+// routing. Without a relay — legacy mode, or no REDIS_URL — the constraint
+// stands: run the WeCom-enabled backend as a single replica. In every mode, a
+// delivery produced while NO replica holds a live connection (all of them
+// mid-reconnect) is still lost; that residual window is a durability problem
+// the relay deliberately does not solve. Boot logs which of the two regimes is
+// in effect. See router.go.
import (
"context"
@@ -73,6 +79,11 @@ type Outbound struct {
// outbound_outcome.go for why the drop breakdown exists at all.
metrics Metrics
+ // relay routes a reply to the replica holding the bot's socket when this
+ // one does not. Nil on a deployment with no Redis, where it is also
+ // unnecessary: one replica publishes and holds the socket both.
+ relay *RelayOutbound
+
// Two counters bound attachment delivery, and they are two because one
// cannot be in both places at once.
//
@@ -225,8 +236,33 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
if o.senders == nil {
return errors.New("wecom: sender registry not configured")
}
+ chatType := aibotChatTypeFromChannel(channel.ChatType(binding.ChatType))
sender := o.senders.get(inst.ID)
if sender == nil {
+ // Before giving up: this reply may simply have been produced on the
+ // wrong replica. Hand it to the one holding the socket.
+ //
+ // Counted by the replica that delivers it, not here — so a reply that
+ // is routed and then delivered appears once, on the sender's side.
+ // A reply routed while EVERY replica is mid-reconnect is read by
+ // nobody and counted by nobody; that window is the durability problem
+ // this deliberately does not solve (relay_outbound.go).
+ if o.relay.publish(relayFrame{
+ Kind: relayKindReply,
+ InstallationID: util.UUIDToString(inst.ID),
+ ChatID: binding.ChannelChatID,
+ ChatType: chatType,
+ Content: content,
+ TaskID: util.UUIDToString(taskID),
+ MessageID: chatDoneMessageID(e.Payload),
+ WorkspaceID: e.WorkspaceID,
+ SessionID: e.ChatSessionID,
+ CarriesFiles: o.mayCarryAttachments(e),
+ }, relayEventID(e, taskID)) {
+ o.logger.DebugContext(ctx, "wecom outbound: routed to the replica holding the socket",
+ "installation_id", util.UUIDToString(inst.ID), "chat_session_id", e.ChatSessionID)
+ return nil
+ }
// No live WS for this installation on this replica. Two causes:
// (1) the Supervisor lost the lease or is mid-reconnect — transient,
// and the user's next inbound message reaches the reconnected loop;
@@ -238,7 +274,6 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
// rather than drop it silently.
return errNoLiveConnection
}
- chatType := aibotChatTypeFromChannel(channel.ChatType(binding.ChatType))
// Words first. An empty completion reaches here only because a file is
// bound to it, and an empty markdown bubble ahead of that file would be
// noise the user has to scroll past.
@@ -362,9 +397,6 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec
return false
}
sender := o.senders.get(binding.InstallationID)
- if sender == nil {
- return false // supervisor down or reconnecting — no live connection
- }
// Resolve slug for the link. Best-effort — a missing slug just falls
// back to the workspace UUID in the URL.
@@ -379,6 +411,35 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec
// Smart-bot inbox notifications are 1:1 pushes to the bound user. The
// binding row's channel_user_id is the bot-scoped T-* userid — WeCom
// treats that as the chatid for a single (chat_type=1) send.
+ if sender == nil {
+ // No socket here. Same shape as the reply path: hand it to the replica
+ // that holds one. An inbox push is as user-visible as an answer, and
+ // leaving it local was the reason the single-replica constraint had to
+ // stay even with replies routed.
+ if o.relay.publish(relayFrame{
+ Kind: relayKindInbox,
+ InstallationID: util.UUIDToString(binding.InstallationID),
+ ChatID: binding.ChannelUserID,
+ ChatType: chatTypeSingleInt,
+ Content: content,
+ }, relayInboxEventID(itemIDOf(item), recipientIDStr)) {
+ o.logger.DebugContext(ctx, "wecom outbound: routed an inbox push to the replica holding the socket",
+ "installation_id", uuidStringPub(binding.InstallationID))
+ return true
+ }
+ // Logged, not counted on the reply counters. Their documented unit is
+ // AGENT REPLIES, and an inbox notification recorded there would show up
+ // as a reply this adapter owed somebody and failed to deliver — the
+ // same unit error the relayed-inbox path in deliverRelayed already
+ // avoids, and the reason the delivered/dropped ratio can be read as an
+ // outcome at all. The member still receives this in the in-app inbox,
+ // which is what makes a missed bot push a degradation rather than a
+ // loss.
+ o.logger.WarnContext(ctx, "wecom outbound: inbox push not delivered and not routable",
+ "installation_id", uuidStringPub(binding.InstallationID),
+ "recipient_id", recipientIDStr)
+ return false // supervisor down or reconnecting — no live connection
+ }
if err := sender.sendTextCtx(ctx, binding.ChannelUserID, chatTypeSingleInt, content); err != nil {
o.logger.WarnContext(ctx, "wecom outbound: inbox push failed",
"error", err, "installation_id", uuidStringPub(binding.InstallationID),
diff --git a/server/internal/integrations/wecom/outbound_media.go b/server/internal/integrations/wecom/outbound_media.go
index ecb7906db4..28b268e0b0 100644
--- a/server/internal/integrations/wecom/outbound_media.go
+++ b/server/internal/integrations/wecom/outbound_media.go
@@ -171,14 +171,23 @@ func (o *Outbound) mayCarryAttachments(e events.Event) bool {
// already landed and the reply's outcome is settled, so only the per-file
// counters move here.
func (o *Outbound) deliverAttachments(e events.Event, to attachmentTarget, carriesTheReply bool) {
+ o.deliverAttachmentsByID(chatDoneMessageID(e.Payload), e.WorkspaceID, to, carriesTheReply)
+}
+
+// deliverAttachmentsByID is deliverAttachments for a caller holding ids rather
+// than the event — the relayed path, where the event was published on another
+// replica and only its identifiers crossed the wire. The files themselves are
+// read here, by the replica that will send them, rather than shipped through
+// Redis.
+func (o *Outbound) deliverAttachmentsByID(rawMessageID, rawWorkspaceID string, to attachmentTarget, carriesTheReply bool) {
if o.objects == nil || o.senders == nil {
return
}
- messageID, err := util.ParseUUID(chatDoneMessageID(e.Payload))
+ messageID, err := util.ParseUUID(rawMessageID)
if err != nil || !messageID.Valid {
return // a turn with no assistant message has nothing bound to it
}
- workspaceID, err := util.ParseUUID(e.WorkspaceID)
+ workspaceID, err := util.ParseUUID(rawWorkspaceID)
if err != nil || !workspaceID.Valid {
return
}
diff --git a/server/internal/integrations/wecom/outbound_outcome.go b/server/internal/integrations/wecom/outbound_outcome.go
index 8de9715434..05c63df71f 100644
--- a/server/internal/integrations/wecom/outbound_outcome.go
+++ b/server/internal/integrations/wecom/outbound_outcome.go
@@ -31,12 +31,13 @@ import (
type dropReason string
const (
- // dropNoConnection — no live WebSocket for this installation in THIS
- // process. Either the Supervisor is mid-reconnect, or, on a multi-replica
- // deployment, the lease is held by a different replica than the one that
- // published the completion, which is the constraint SELF_HOSTING.md
- // documents. The two are indistinguishable from here; a deployment's
- // replica count is what tells them apart.
+ // dropNoConnection — no live WebSocket carried this reply. Two situations
+ // reach it. Without a relay: none in THIS process, which on a
+ // multi-replica deployment cannot be told apart from the lease simply
+ // being held elsewhere. With one: the reply WAS routed to every replica
+ // and none of them held a connection either, which is the residual window
+ // SELF_HOSTING.md describes — recorded once, by the replica that routed
+ // it, from the claim nobody took (RelayOutbound.watchOutcomes).
dropNoConnection dropReason = "no_live_connection"
// dropTaskMissing — the task the completion belongs to could not be
diff --git a/server/internal/integrations/wecom/outbound_two_replica_db_test.go b/server/internal/integrations/wecom/outbound_two_replica_db_test.go
new file mode 100644
index 0000000000..3c5b91c630
--- /dev/null
+++ b/server/internal/integrations/wecom/outbound_two_replica_db_test.go
@@ -0,0 +1,942 @@
+package wecom
+
+// outbound_two_replica_db_test.go — GH #7215 reproduced against a real
+// database, with two replicas.
+//
+// The unit-level reproduction (outbound_cross_replica_test.go) drives a fake
+// queries layer, which proves the subscriber's branching but not that a real
+// deployment reaches those branches: every lookup ahead of the sender —
+// the binding row, the task, the immutable channel_ingested stamp on the
+// input batch, the installation's status — is answered by a mock there. If any
+// of them behaved differently against real SQL, the "reply is dropped" verdict
+// would be an artefact of the double.
+//
+// So this one keeps the fakes only where the WeCom platform would be, and runs
+// everything else for real: *db.Queries against a migrated database, two
+// Outbound subscribers on two independent event buses, each with its own
+// sendersRegistry. That IS the production shape. events.Bus is in-process
+// (internal/events/bus.go), and a chat completion is published by whichever
+// replica served the daemon's POST /tasks/{id}/complete — a load-balancer
+// decision, unrelated to which replica won that installation's WebSocket
+// lease.
+//
+// Skips when no migrated database is reachable, same as the other _db_ tests
+// in this package.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "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"
+)
+
+// frameCount reads the recorded frames under the double's own lock, so these
+// tests stay clean under -race even where a delivery runs on its own goroutine.
+func (c *recordingConn) frameCount() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.frames)
+}
+
+func twoReplicaDB(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ dsn := os.Getenv("DATABASE_URL")
+ if dsn == "" {
+ dsn = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Skipf("no database: %v", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ t.Skipf("database not reachable: %v", err)
+ }
+ var present bool
+ if err := pool.QueryRow(ctx,
+ "SELECT to_regclass('public.channel_chat_session_binding') IS NOT NULL").Scan(&present); err != nil || !present {
+ pool.Close()
+ t.Skip("channel tables not present (database not migrated)")
+ }
+ t.Cleanup(pool.Close)
+ return pool
+}
+
+// boundTurn is one WeCom conversation as the database holds it after a user
+// asked a question in the room and the agent finished answering: an active
+// installation, a session bound to a chat, and a task whose input batch
+// carries the immutable channel_ingested stamp.
+type boundTurn struct {
+ sessionID string
+ taskID string
+ instID string
+ chatID string
+}
+
+func seedBoundTurn(t *testing.T, pool *pgxpool.Pool) boundTurn {
+ t.Helper()
+ ctx := context.Background()
+ // Ids come from the database rather than a Go uuid package: this package's
+ // tests already bind the identifier `uuid` for their own fixtures, and
+ // gen_random_uuid() is already what every one of these tables defaults to.
+ newID := func() string {
+ t.Helper()
+ var id string
+ if err := pool.QueryRow(ctx, `SELECT gen_random_uuid()::text`).Scan(&id); err != nil {
+ t.Fatalf("seed: mint id: %v", err)
+ }
+ return id
+ }
+ tag := strings.ReplaceAll(newID(), "-", "")[:12]
+
+ turn := boundTurn{
+ sessionID: newID(), taskID: newID(), instID: newID(),
+ chatID: "CHAT_" + tag,
+ }
+ wsID, userID, agentID, inputTaskID := newID(), newID(), newID(), newID()
+
+ exec := func(sql string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, sql, args...); err != nil {
+ t.Fatalf("seed: %s: %v", strings.SplitN(strings.TrimSpace(sql), "\n", 2)[0], err)
+ }
+ }
+ // Reverse order of creation, so foreign keys hold on the way out.
+ t.Cleanup(func() {
+ for _, sql := range []string{
+ `DELETE FROM chat_message WHERE chat_session_id = $1`,
+ `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`,
+ } {
+ _, _ = pool.Exec(ctx, sql, turn.sessionID)
+ }
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_task_delivery WHERE task_id = $1`, turn.taskID)
+ _, _ = pool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = ANY($1)`,
+ []string{turn.taskID, inputTaskID})
+ _, _ = pool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, turn.sessionID)
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE id = $1`, turn.instID)
+ _, _ = pool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID)
+ _, _ = pool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, userID)
+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wsID)
+ })
+
+ exec(`INSERT INTO workspace (id, name, slug) VALUES ($1, $2, $3)`,
+ wsID, "repro7215 "+tag, "repro7215-"+tag)
+ exec(`INSERT INTO "user" (id, name, email) VALUES ($1, $2, $3)`,
+ userID, "Repro "+tag, "repro-"+tag+"@example.com")
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode) VALUES ($1, $2, $3, 'local')`,
+ agentID, wsID, "repro-agent-"+tag)
+ exec(`INSERT INTO chat_session (id, workspace_id, agent_id, creator_id) VALUES ($1, $2, $3, $4)`,
+ turn.sessionID, wsID, agentID, userID)
+ exec(`INSERT INTO channel_installation
+ (id, workspace_id, agent_id, channel_type, status, installer_user_id)
+ VALUES ($1, $2, $3, 'wecom', 'active', $4)`,
+ turn.instID, wsID, agentID, userID)
+ bindingID := newID()
+ exec(`INSERT INTO channel_chat_session_binding
+ (id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
+ VALUES ($1, $2, $3, 'wecom', $4, 'p2p')`,
+ bindingID, turn.sessionID, turn.instID, turn.chatID)
+
+ // The turn the user's message belongs to, and the turn that answered it.
+ // A reply task reaches the provenance verdict through chat_input_task_id,
+ // which is what an auto-retry clone inherits — so the stamp is read off
+ // the batch owner, not off the answering task.
+ // completed_at is not decoration: agent_task_queue_active_requires_runtime
+ // insists a row is either attached to a runtime or finished.
+ exec(`INSERT INTO agent_task_queue (id, agent_id, chat_session_id, status, completed_at)
+ VALUES ($1, $2, $3, 'completed', now())`, inputTaskID, agentID, turn.sessionID)
+ exec(`INSERT INTO agent_task_queue (id, agent_id, chat_session_id, status, completed_at, chat_input_task_id)
+ VALUES ($1, $2, $3, 'completed', now(), $4)`, turn.taskID, agentID, turn.sessionID, inputTaskID)
+ // Since MUL-6661 (#7468) the outbound address is a per-task delivery
+ // snapshot, not the session binding: processEvent resolves the route via
+ // GetChannelTaskDelivery(task_id) and returns silently without a row. The
+ // engine writes this row when it ingests the message; a seed that skips it
+ // is a turn the outbound path correctly ignores.
+ exec(`INSERT INTO channel_task_delivery
+ (task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, route_revision, config)
+ VALUES ($1, $2, $3, 'wecom', $4, 'p2p', 1, '{}')`,
+ turn.taskID, bindingID, turn.instID, turn.chatID)
+ exec(`INSERT INTO chat_message (chat_session_id, role, content, task_id, channel_ingested)
+ VALUES ($1, 'user', 'S270 的价格', $2, true)`, turn.sessionID, inputTaskID)
+
+ return turn
+}
+
+// replica is one backend process: its own event bus, its own senders registry,
+// its own subscriber. Everything below the adapter — the database — is shared,
+// exactly as it is in production.
+type replica struct {
+ bus *events.Bus
+ conn *recordingConn // nil when this replica holds no socket
+ logs *strings.Builder
+ mx *countingMetrics
+}
+
+func newReplica(t *testing.T, pool *pgxpool.Pool, instID string, holdsSocket bool) *replica {
+ t.Helper()
+ r := &replica{bus: events.New(), logs: &strings.Builder{}, mx: newCountingMetrics()}
+ reg := newSendersRegistry()
+ if holdsSocket {
+ r.conn = &recordingConn{}
+ var pg pgtype.UUID
+ if err := pg.Scan(instID); err != nil {
+ t.Fatalf("parse installation id: %v", err)
+ }
+ reg.set(pg, r.conn.autoAck(newWSSender(r.conn, nil)))
+ }
+ o := NewOutbound(db.New(pool), reg,
+ slog.New(slog.NewTextHandler(r.logs, &slog.HandlerOptions{Level: slog.LevelDebug})),
+ WithOutboundMetrics(r.mx))
+ o.Register(r.bus)
+ return r
+}
+
+func chatDoneFor(turn boundTurn) events.Event {
+ return events.Event{
+ Type: protocol.EventChatDone,
+ WorkspaceID: "",
+ ActorType: "system",
+ ChatSessionID: turn.sessionID,
+ Payload: protocol.ChatDonePayload{
+ ChatSessionID: turn.sessionID,
+ TaskID: turn.taskID,
+ Content: "S270 的价格是 1280 元。",
+ },
+ }
+}
+
+func (r *replica) frames() int {
+ if r.conn == nil {
+ return 0
+ }
+ return r.conn.frameCount()
+}
+
+// TestTwoReplicas_ReplyPublishedOffLeaseIsDropped is the reproduction. Replica
+// A holds the bot's socket; replica B served the daemon's completion callback
+// and therefore publishes chat:done. Every database lookup on the way is real
+// and every one of them succeeds — the turn is impeccable. The reply still
+// never leaves, because the socket is in the other process.
+func TestTwoReplicas_ReplyPublishedOffLeaseIsDropped(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+
+ leaseHolder := newReplica(t, pool, turn.instID, true)
+ publisher := newReplica(t, pool, turn.instID, false)
+
+ publisher.bus.Publish(chatDoneFor(turn))
+
+ if n := leaseHolder.frames(); n != 0 {
+ t.Fatalf("the lease holder's socket carried %d frames; the publishing replica cannot reach it", n)
+ }
+ if got := publisher.mx.get("outbound_dropped:no_live_connection"); got != 1 {
+ t.Errorf("drop counter = %d, want 1. log:\n%s", got, publisher.logs.String())
+ }
+ if got := publisher.mx.get("outbound_delivered"); got != 0 {
+ t.Errorf("publisher counted %d deliveries; it holds no socket", got)
+ }
+ // The lease holder never heard about this turn at all: the bus does not
+ // cross processes, which is the whole mechanism.
+ if got := leaseHolder.mx.get("outbound_delivered") + leaseHolder.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("the lease holder saw %d outcomes for an event published elsewhere", got)
+ }
+}
+
+// TestTwoReplicas_SameReplicaDelivers is the control. Identical rows, identical
+// event, identical code. The only thing that changed is which of the two
+// processes published it.
+func TestTwoReplicas_SameReplicaDelivers(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+
+ leaseHolder := newReplica(t, pool, turn.instID, true)
+ _ = newReplica(t, pool, turn.instID, false)
+
+ leaseHolder.bus.Publish(chatDoneFor(turn))
+
+ if n := leaseHolder.frames(); n != 1 {
+ t.Fatalf("frames = %d, want 1. log:\n%s", n, leaseHolder.logs.String())
+ }
+ body := leaseHolder.conn.sendBody(t, 0)
+ if body["chatid"] != turn.chatID {
+ t.Errorf("chatid = %v, want %s", body["chatid"], turn.chatID)
+ }
+ if got := leaseHolder.mx.get("outbound_delivered"); got != 1 {
+ t.Errorf("delivered counter = %d, want 1", got)
+ }
+ if got := leaseHolder.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("dropped counter = %d, want 0", got)
+ }
+}
+
+// fanoutRelay is the Redis Stream relay reduced to the two properties this
+// depends on: every node sees every frame published under a scope, and a node
+// that starts late replays what it missed. Registered deliverers stand in for
+// the other replicas' shard read loops.
+type fanoutRelay struct {
+ mu sync.Mutex
+ deliverers []*RelayOutbound
+ log []queued
+ published int
+}
+
+func (f *fanoutRelay) register(r *RelayOutbound) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.deliverers = append(f.deliverers, r)
+}
+
+func (f *fanoutRelay) PublishWithID(_, scopeID, _ string, frame []byte, id string) error {
+ var decoded relayFrame
+ if err := json.Unmarshal(frame, &decoded); err != nil {
+ return err
+ }
+ f.mu.Lock()
+ f.published++
+ f.log = append(f.log, queued{frame: decoded, eventID: id})
+ targets := append([]*RelayOutbound(nil), f.deliverers...)
+ f.mu.Unlock()
+ for _, d := range targets {
+ d.DeliverWecomOutbound(scopeID, frame, id)
+ }
+ return nil
+}
+
+// replayTo re-delivers everything published so far to one node, which is what
+// a shard reader does on startup: it begins at (now - ReplayGrace), not "$".
+func (f *fanoutRelay) replayTo(r *RelayOutbound) {
+ f.mu.Lock()
+ entries := append([]queued(nil), f.log...)
+ f.mu.Unlock()
+ for _, e := range entries {
+ body, _ := json.Marshal(e.frame)
+ r.DeliverWecomOutbound(e.frame.InstallationID, body, e.eventID)
+ }
+}
+
+// sharedDedupe stands in for the Redis claim: one map, shared by every replica
+// in the test, surviving a "restart" because the process it models does not
+// own it. That is the whole property the in-process seen-set lacked.
+type sharedDedupe struct {
+ mu sync.Mutex
+ held map[string]bool
+ fail bool
+ calls int
+}
+
+func newSharedDedupe() *sharedDedupe { return &sharedDedupe{held: map[string]bool{}} }
+
+func (d *sharedDedupe) Claim(_ context.Context, key string, _ time.Duration) (bool, error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.calls++
+ if d.fail {
+ return false, errors.New("dedupe unavailable")
+ }
+ if d.held[key] {
+ return false, nil
+ }
+ d.held[key] = true
+ return true, nil
+}
+
+func (d *sharedDedupe) holds(key string) bool {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.held[key]
+}
+
+func (d *sharedDedupe) claimCount() int {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.calls
+}
+
+func (d *sharedDedupe) Release(_ context.Context, key string) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ delete(d.held, key)
+}
+
+// ClaimBudget is a fake's budget: small, because it is what sizes the outcome
+// grace these tests wait out and nothing here talks to a real server.
+func (d *sharedDedupe) ClaimBudget() time.Duration { return 20 * time.Millisecond }
+
+func (d *sharedDedupe) Held(_ context.Context, key string) (bool, error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if d.fail {
+ return false, errors.New("dedupe unavailable")
+ }
+ return d.held[key], nil
+}
+
+// relayReplica is one backend process wired for cross-replica routing.
+type relayReplica struct {
+ *replica
+ router *RelayOutbound
+ reg *sendersRegistry
+ instID pgtype.UUID
+}
+
+func newRelayReplica(t *testing.T, pool *pgxpool.Pool, instID string, holdsSocket bool, relay *fanoutRelay, dedupe DedupeStore) *relayReplica {
+ return newRelayReplicaWith(t, pool, instID, holdsSocket, relay, dedupe, RelayConfig{})
+}
+
+// newRelayReplicaWith is the same, with the dispatcher sized by the caller.
+func newRelayReplicaWith(t *testing.T, pool *pgxpool.Pool, instID string, holdsSocket bool, relay *fanoutRelay, dedupe DedupeStore, cfg RelayConfig) *relayReplica {
+ t.Helper()
+ base := &replica{bus: events.New(), logs: &strings.Builder{}, mx: newCountingMetrics()}
+ reg := newSendersRegistry()
+ var pg pgtype.UUID
+ if err := pg.Scan(instID); err != nil {
+ t.Fatalf("parse installation id: %v", err)
+ }
+ if holdsSocket {
+ base.conn = &recordingConn{}
+ reg.set(pg, base.conn.autoAck(newWSSender(base.conn, nil)))
+ }
+ log := slog.New(slog.NewTextHandler(base.logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
+
+ // Registered and started BEFORE the subscriber exists, which is the real
+ // boot order: the relay's readers open on a replay window and anything
+ // registered after them misses it.
+ router := NewRelayOutbound(relay, dedupe, cfg, log)
+ router.SetMetrics(base.mx)
+ relay.register(router)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { cancel(); router.Wait() })
+ router.Start(ctx)
+
+ o := NewOutbound(db.New(pool), reg, log, WithOutboundMetrics(base.mx), WithRelay(router))
+ o.Register(base.bus)
+ router.Attach(o)
+ return &relayReplica{replica: base, router: router, reg: reg, instID: pg}
+}
+
+// TestTwoReplicas_RelayCarriesTheReplyToTheLeaseHolder is the fix. Same two
+// replicas and the same event on the same (wrong) one — and the answer arrives.
+func TestTwoReplicas_RelayCarriesTheReplyToTheLeaseHolder(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+
+ holder := newRelayReplica(t, pool, turn.instID, true, relay, dedupe)
+ publisher := newRelayReplica(t, pool, turn.instID, false, relay, dedupe)
+
+ publisher.bus.Publish(chatDoneFor(turn))
+
+ waitFor(t, "the lease holder to deliver", func() bool { return holder.frames() == 1 })
+ body := holder.conn.sendBody(t, 0)
+ if body["chatid"] != turn.chatID {
+ t.Errorf("chatid = %v, want %s", body["chatid"], turn.chatID)
+ }
+ waitFor(t, "the delivery to be counted once", func() bool {
+ return holder.mx.get("outbound_delivered") == 1
+ })
+ if got := publisher.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("publisher recorded %d drops for a reply it routed", got)
+ }
+}
+
+// TestRelay_StartupReplayDoesNotResend — the review finding. A shard reader
+// starts at (now - ReplayGrace), so a restarted replica re-reads frames it may
+// already have delivered. The claim has to outlive the process for that to be
+// safe; an in-process set is empty exactly when it matters.
+func TestRelay_StartupReplayDoesNotResend(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+
+ holder := newRelayReplica(t, pool, turn.instID, true, relay, dedupe)
+ publisher := newRelayReplica(t, pool, turn.instID, false, relay, dedupe)
+ publisher.bus.Publish(chatDoneFor(turn))
+ waitFor(t, "the first delivery", func() bool { return holder.frames() == 1 })
+
+ // The lease holder restarts: a brand new process, an empty in-process set,
+ // the same socket, and the relay replays its window into it.
+ restarted := newRelayReplica(t, pool, turn.instID, true, relay, dedupe)
+ relay.replayTo(restarted.router)
+
+ // Two claim attempts, not three: the publisher holds no socket and — since
+ // the ownership gate — never competes for the claim at all. The two are
+ // the original holder's winning claim and the restarted replica's losing
+ // one against the replayed frame.
+ waitFor(t, "the replay to be consumed", func() bool { return dedupe.claimCount() >= 2 })
+ if n := restarted.frames(); n != 0 {
+ t.Fatalf("the restarted replica re-sent %d already-delivered replies", n)
+ }
+}
+
+// TestRelay_LeaseMoveDoesNotDoubleSend — two replicas both holding a socket for
+// the same installation is the window a lease transfer opens. Both read the
+// frame; exactly one may send it.
+func TestRelay_LeaseMoveDoesNotDoubleSend(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+
+ a := newRelayReplica(t, pool, turn.instID, true, relay, dedupe)
+ b := newRelayReplica(t, pool, turn.instID, true, relay, dedupe)
+ publisher := newRelayReplica(t, pool, turn.instID, false, relay, dedupe)
+
+ publisher.bus.Publish(chatDoneFor(turn))
+
+ waitFor(t, "exactly one of them to send", func() bool { return a.frames()+b.frames() == 1 })
+ time.Sleep(50 * time.Millisecond) // give the loser a chance to be wrong
+ if got := a.frames() + b.frames(); got != 1 {
+ t.Fatalf("frames across both lease holders = %d, want exactly 1", got)
+ }
+}
+
+// TestRelay_DispatchNeverBlocksTheShardReader — DeliverWecomOutbound runs on
+// the shared realtime read loop. If it waited for the platform, one unhealthy
+// bot would hold up browser traffic, daemon wakeups and every other bot on the
+// shard. The double here never answers, so a synchronous implementation would
+// sit in ackTimeout.
+func TestRelay_DispatchNeverBlocksTheShardReader(t *testing.T) {
+ t.Parallel()
+ silent := &recordingConn{} // never acks
+ reg := newSendersRegistry()
+ instID := mustTestUUID(t)
+ reg.set(instID, newWSSender(silent, nil))
+
+ router := NewRelayOutbound(nil, nil, RelayConfig{}, slog.Default())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer func() { cancel(); router.Wait() }()
+ router.Start(ctx)
+ router.Attach(&Outbound{senders: reg, logger: slog.Default()})
+
+ body, _ := json.Marshal(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",
+ })
+ start := time.Now()
+ router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-1")
+ if elapsed := time.Since(start); elapsed > 200*time.Millisecond {
+ t.Fatalf("DeliverWecomOutbound blocked the shard reader for %s", elapsed)
+ }
+}
+
+// TestRelay_ShedsRatherThanStalls — when a bot's queue is full the frame is
+// dropped and counted, because the alternative is stalling the shard.
+//
+// Asserted at the BOUNDARY rather than approximately: QueueDepth frames are
+// accepted and the next one is not, so the configured depth is the depth.
+func TestRelay_ShedsRatherThanStalls(t *testing.T) {
+ t.Parallel()
+ mx := newCountingMetrics()
+ const depth = 4
+ router := NewRelayOutbound(nil, nil, RelayConfig{QueueDepth: depth}, slog.Default())
+ router.SetMetrics(mx)
+ // Attached but never started: nothing drains, so the queue fills.
+ router.Attach(&ownsSocketHandler{owns: true})
+ body, _ := json.Marshal(relayFrame{Kind: relayKindReply, InstallationID: "inst-1"})
+ for i := 0; i < depth; i++ {
+ router.DeliverWecomOutbound("inst-1", body, "ev")
+ }
+ if got := mx.get("relay_shed"); got != 0 {
+ t.Fatalf("shed %d frames while the queue still had room for them", got)
+ }
+ router.DeliverWecomOutbound("inst-1", body, "ev")
+ if got := mx.get("relay_shed:reply"); got != 1 {
+ t.Fatalf("relay_shed:reply = %d, want 1 — the frame past the depth must be shed and counted", got)
+ }
+ // The admission decision is ALL it records. Whether that shed cost the user
+ // the reply is settled once, later, by the publisher's outcome watch — no
+ // replica can tell from here. See TestRelayShed_NeverMovesTheReplyCounter.
+ if got := mx.get("outbound_dropped"); got != 0 {
+ t.Fatalf("outbound_dropped = %d, want 0 — a shed is an admission decision, not a reply outcome", got)
+ }
+}
+
+// The same queue, an inbox notification instead of a reply. It must be shed the
+// same way and counted in a DIFFERENT place: outbound_dropped counts agent
+// replies, and an inbox push filed there makes the delivered/dropped ratio
+// track which replica held a socket rather than what happened to anyone.
+func TestRelay_AnInboxPushShedDoesNotMoveTheReplyCounters(t *testing.T) {
+ t.Parallel()
+ mx := newCountingMetrics()
+ const depth = 2
+ router := NewRelayOutbound(nil, nil, RelayConfig{QueueDepth: depth}, slog.Default())
+ router.SetMetrics(mx)
+ router.Attach(&ownsSocketHandler{owns: true})
+ body, _ := json.Marshal(relayFrame{Kind: relayKindInbox, InstallationID: "inst-1"})
+ for i := 0; i < depth+3; i++ {
+ router.DeliverWecomOutbound("inst-1", body, "ev")
+ }
+ if got := mx.get("outbound_dropped"); got != 0 {
+ t.Fatalf("outbound_dropped = %d, want 0 — an inbox push is not an agent reply", got)
+ }
+ if got := mx.get("relay_shed:inbox"); got != 3 {
+ t.Fatalf("relay_shed:inbox = %d, want 3 — the sheds must still be visible somewhere", got)
+ }
+}
+
+// TestRelay_DedupeOutageWithholdsRatherThanDuplicates — a claim store that
+// cannot answer must not silently become an at-least-once path. The frame stays
+// replayable, so withholding costs latency; delivering costs a duplicate
+// answer in somebody's room.
+func TestRelay_DedupeOutageWithholdsRatherThanDuplicates(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ dedupe.fail = true
+
+ holder := newRelayReplica(t, pool, turn.instID, true, relay, dedupe)
+ publisher := newRelayReplica(t, pool, turn.instID, false, relay, dedupe)
+
+ publisher.bus.Publish(chatDoneFor(turn))
+
+ waitFor(t, "the claim attempt", func() bool { return dedupe.claimCount() > 0 })
+ time.Sleep(50 * time.Millisecond)
+ if n := holder.frames(); n != 0 {
+ t.Fatalf("delivered %d frames with no working claim store", n)
+ }
+}
+
+// TestTwoReplicas_NoRelayStillDrops pins that the router is opt-in: a
+// deployment with no Redis gets exactly the old behaviour.
+func TestTwoReplicas_NoRelayStillDrops(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+
+ leaseHolder := newReplica(t, pool, turn.instID, true)
+ publisher := newReplica(t, pool, turn.instID, false)
+
+ publisher.bus.Publish(chatDoneFor(turn))
+
+ if n := leaseHolder.frames(); n != 0 {
+ t.Fatalf("frames = %d, want 0 without a relay", n)
+ }
+ if got := publisher.mx.get("outbound_dropped:no_live_connection"); got != 1 {
+ t.Errorf("drop counter = %d, want 1", got)
+ }
+}
+
+// ---- the second review round's three orderings ---------------------------
+
+// TestRelay_NonHolderNeverCompetesForTheClaim — the stranding found in review.
+// The claim is a cross-replica SET NX: if a replica without the socket were
+// allowed to win it, the real holder would lose the race and return, the
+// winner would discover it cannot send and release, and nothing would ever
+// wake the loser again — every party correct, the reply lost. The gate is
+// therefore ownership BEFORE the claim: a non-holder must never touch it.
+func TestRelay_NonHolderNeverCompetesForTheClaim(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+
+ // Only a non-holder is registered: empty registry.
+ reg := newSendersRegistry()
+ router := NewRelayOutbound(relay, dedupe, RelayConfig{}, slog.Default())
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { cancel(); router.Wait() })
+ router.Start(ctx)
+ router.Attach(&Outbound{senders: reg, logger: slog.Default()})
+ relay.register(router)
+
+ instID := mustTestUUID(t)
+ body, _ := json.Marshal(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",
+ })
+ router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-strand")
+
+ time.Sleep(80 * time.Millisecond)
+ if got := dedupe.claimCount(); got != 0 {
+ t.Fatalf("a replica with no socket made %d claim attempts; the real holder would have been stranded", got)
+ }
+
+ // The holder arrives later — a replay hands it the same frame, and because
+ // the claim was never consumed, it delivers.
+ conn := &recordingConn{}
+ holderReg := newSendersRegistry()
+ holderReg.set(instID, conn.autoAck(newWSSender(conn, nil)))
+ holderRouter := NewRelayOutbound(relay, dedupe, RelayConfig{}, slog.Default())
+ hctx, hcancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { hcancel(); holderRouter.Wait() })
+ holderRouter.Start(hctx)
+ holderRouter.Attach(&Outbound{senders: holderReg, logger: slog.Default()})
+ holderRouter.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-strand")
+
+ waitFor(t, "the late holder to deliver", func() bool { return conn.frameCount() == 1 })
+}
+
+// writeFailConn fails inside WriteMessage — the ambiguous point: the frame may
+// have reached the peer before the local side surfaced the error, which is
+// exactly what ws_sender's errWriteAttempted marks.
+type writeFailConn struct{}
+
+func (writeFailConn) ReadMessage() (int, []byte, error) { select {} }
+func (writeFailConn) WriteMessage(int, []byte) error { return errTestWriteBoom }
+func (writeFailConn) SetReadDeadline(time.Time) error { return nil }
+func (writeFailConn) SetWriteDeadline(time.Time) error { return nil }
+func (writeFailConn) Close() error { return nil }
+
+var errTestWriteBoom = errors.New("boom mid-write")
+
+// TestRelay_AttemptedWriteKeepsTheClaim — the second finding. A failure raised
+// by the write itself is not proof of non-delivery; releasing the claim there
+// lets the replay put the same answer in the chat twice. The claim must stay.
+func TestRelay_AttemptedWriteKeepsTheClaim(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+
+ instID := mustTestUUID(t)
+ reg := newSendersRegistry()
+ reg.set(instID, newWSSender(writeFailConn{}, nil))
+ router := NewRelayOutbound(relay, dedupe, RelayConfig{}, slog.Default())
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { cancel(); router.Wait() })
+ router.Start(ctx)
+ mx := newCountingMetrics()
+ router.Attach(NewOutbound(nil, reg, slog.Default(), WithOutboundMetrics(mx)))
+
+ body, _ := json.Marshal(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",
+ })
+ router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-attempted")
+
+ // An attempted write is an UNKNOWN outcome, so it files under unconfirmed
+ // — never under dropped, whose contract promises the answer is not coming.
+ waitFor(t, "the unconfirmed outcome to be recorded", func() bool { return mx.get("outbound_unconfirmed") == 1 })
+ if got := mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("dropped = %d, want 0 — the peer may already have the frame", got)
+ }
+ if !dedupe.holds(dedupeKey("ev-attempted")) {
+ t.Fatal("the claim was released after an ATTEMPTED write; a retry would resend a frame the peer may already have")
+ }
+}
+
+// TestDeliverRelayed_ContextErrorsDoNotRelease — a bare context error is
+// ambiguous: request() returns one both before the write and while waiting for
+// the verdict after it. Treated as possibly-sent, so the outcome must not be
+// the claim-releasing one.
+func TestDeliverRelayed_ContextErrorsDoNotRelease(t *testing.T) {
+ t.Parallel()
+ instID := mustTestUUID(t)
+ reg := newSendersRegistry()
+ conn := &recordingConn{}
+ reg.set(instID, conn.autoAck(newWSSender(conn, nil)))
+ o := NewOutbound(nil, reg, slog.Default())
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // already expired: sendTextCtx fails on its pre-write check
+ got := o.deliverRelayed(ctx, relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",
+ })
+ if got == outcomeProvablyNotSent {
+ t.Fatal("a context error released the claim; it is ambiguous and must not")
+ }
+}
+
+// TestProvablyNotSent_Classification pins the boundary the claim release
+// rides on.
+func TestProvablyNotSent_Classification(t *testing.T) {
+ t.Parallel()
+ if provablyNotSent(&wecomAPIError{Cmd: cmdSendMsg, Code: 45002}) {
+ t.Error("a stated refusal was answered — the frame was seen")
+ }
+ if provablyNotSent(errAckTimeout) {
+ t.Error("a missing verdict may still be a delivery")
+ }
+ if provablyNotSent(fmt.Errorf("%w: %w", errWriteAttempted, errTestWriteBoom)) {
+ t.Error("an attempted write may have reached the peer")
+ }
+ if provablyNotSent(context.Canceled) || provablyNotSent(context.DeadlineExceeded) {
+ t.Error("a bare context error is ambiguous")
+ }
+ if !provablyNotSent(errors.New("wecom: send_msg requires chat_id")) {
+ t.Error("a pre-write local failure is the one case that IS provably unsent")
+ }
+}
+
+// ---- round-3 review regressions (Bohan) ----------------------------------
+
+// TestRelay_LeaseMoveMidFlightIsRescuedByRetry — the stranding: A passes the
+// ownership check, the lease moves to B, A wins the claim, B loses it and
+// returns, A discovers it no longer holds the socket and releases. Without a
+// local retry nobody ever comes back — each replica reads a stream frame
+// exactly once. The bounded requeue is what rescues it: B's losing attempt
+// retries, finds the claim free, and delivers.
+func TestRelay_LeaseMoveMidFlightIsRescuedByRetry(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ instID := mustTestUUID(t)
+
+ // Replica A: passes ownsSocket, then finds the sender gone at delivery —
+ // a handler whose ownership answer and whose delivery disagree, which is
+ // exactly what a lease moving between the two moments looks like.
+ aRouter := NewRelayOutbound(relay, dedupe, RelayConfig{}, slog.Default())
+ actx, acancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { acancel(); aRouter.Wait() })
+ aRouter.Start(actx)
+ aRouter.Attach(&flipHandler{})
+
+ // Replica B: genuinely holds the socket throughout.
+ conn := &recordingConn{}
+ bReg := newSendersRegistry()
+ bReg.set(instID, conn.autoAck(newWSSender(conn, nil)))
+ bRouter := NewRelayOutbound(relay, dedupe, RelayConfig{}, slog.Default())
+ bctx, bcancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { bcancel(); bRouter.Wait() })
+ bRouter.Start(bctx)
+ bRouter.Attach(&Outbound{senders: bReg, logger: slog.Default()})
+
+ relay.register(aRouter)
+ relay.register(bRouter)
+
+ body, _ := json.Marshal(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",
+ })
+ // Both replicas read the frame, as every replica does.
+ aRouter.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-move")
+ bRouter.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-move")
+
+ // Whichever ordering the race takes, the retry must land the reply.
+ waitLong(t, "the reply to be rescued", func() bool { return conn.frameCount() == 1 })
+ time.Sleep(100 * time.Millisecond)
+ if got := conn.frameCount(); got != 1 {
+ t.Fatalf("frames = %d, want exactly 1", got)
+ }
+}
+
+// flipHandler owns the socket when asked and does not when delivering — the
+// deterministic shape of a lease that moved between the check and the send.
+type flipHandler struct{}
+
+func (*flipHandler) ownsSocket(string) bool { return true }
+func (*flipHandler) deliverRelayed(context.Context, relayFrame) deliveryOutcome {
+ return outcomeNotOurs
+}
+
+// waitLong is waitFor with room for the retry backoff schedule.
+func waitLong(t *testing.T, what string, cond func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(8 * time.Second)
+ for time.Now().Before(deadline) {
+ if cond() {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatalf("timed out waiting for %s", what)
+}
+
+// TestDedupeTTL_CoversTheReplayWindow — the invariant the TTL exists for: a
+// claim must outlive the window in which its frame can be replayed, and that
+// window is an operator knob, not a constant.
+func TestDedupeTTL_CoversTheReplayWindow(t *testing.T) {
+ t.Parallel()
+ if got := dedupeTTLFor(0); got != minDedupeTTL {
+ t.Errorf("zero grace: ttl = %v, want the floor %v", got, minDedupeTTL)
+ }
+ if got := dedupeTTLFor(5 * time.Minute); got != minDedupeTTL {
+ t.Errorf("default grace: ttl = %v, want the floor %v", got, minDedupeTTL)
+ }
+ if got := dedupeTTLFor(2 * time.Hour); got != 4*time.Hour {
+ t.Errorf("2h grace: ttl = %v, want 4h — the claim must outlive the replay window", got)
+ }
+ if got := dedupeTTLFor(2 * time.Hour); got <= 2*time.Hour {
+ t.Errorf("ttl %v does not cover a 2h replay window", got)
+ }
+}
+
+// TestRelayedInboxPushDoesNotMoveTheReplyCounters — an inbox push is not an
+// agent reply; the delivered/dropped ratio must not track socket placement.
+func TestRelayedInboxPushDoesNotMoveTheReplyCounters(t *testing.T) {
+ t.Parallel()
+ instID := mustTestUUID(t)
+
+ // Success path.
+ okConn := &recordingConn{}
+ okReg := newSendersRegistry()
+ okReg.set(instID, okConn.autoAck(newWSSender(okConn, nil)))
+ okMx := newCountingMetrics()
+ ok := NewOutbound(nil, okReg, slog.Default(), WithOutboundMetrics(okMx))
+ if got := ok.deliverRelayed(context.Background(), relayFrame{
+ Kind: relayKindInbox, InstallationID: util.UUIDToString(instID),
+ ChatID: "T-USER", ChatType: chatTypeSingleInt, Content: "you were mentioned",
+ }); got != outcomeDone {
+ t.Fatalf("outcome = %v, want done", got)
+ }
+ if n := okConn.frameCount(); n != 1 {
+ t.Fatalf("frames = %d, want 1 — the push itself must go out", n)
+ }
+ if got := okMx.get("outbound_delivered"); got != 0 {
+ t.Errorf("delivered = %d, want 0 — an inbox push is not a reply", got)
+ }
+
+ // Failure path.
+ badConn := &recordingConn{refuseCode: 45002, refuseMsg: "too long"}
+ badReg := newSendersRegistry()
+ badReg.set(instID, badConn.autoAck(newWSSender(badConn, nil)))
+ badMx := newCountingMetrics()
+ bad := NewOutbound(nil, badReg, slog.Default(), WithOutboundMetrics(badMx))
+ bad.deliverRelayed(context.Background(), relayFrame{
+ Kind: relayKindInbox, InstallationID: util.UUIDToString(instID),
+ ChatID: "T-USER", ChatType: chatTypeSingleInt, Content: "you were mentioned",
+ })
+ if got := badMx.get("outbound_dropped") + badMx.get("outbound_unconfirmed"); got != 0 {
+ t.Errorf("reply counters moved (%d) for a failed inbox push", got)
+ }
+}
+
+// TestDrainDeliversOnlyWhileSocketsLive — why main stops the relay BEFORE the
+// channel supervisor: each supervised connection clears its sender on exit, so
+// a drain that runs after that teardown finds no socket and discards
+// everything it exists to save. Component-level: the same queued frame drains
+// to the wire with the socket registered and to nothing with it cleared. The
+// production ordering itself lives in main.go's stopRelay call site.
+func TestDrainDeliversOnlyWhileSocketsLive(t *testing.T) {
+ t.Parallel()
+ for _, live := range []bool{true, false} {
+ instID := mustTestUUID(t)
+ conn := &recordingConn{}
+ reg := newSendersRegistry()
+ sender := conn.autoAck(newWSSender(conn, nil))
+ reg.set(instID, sender)
+ router := NewRelayOutbound(nil, nil, RelayConfig{}, slog.Default())
+ ctx, cancel := context.WithCancel(context.Background())
+ router.Attach(&Outbound{senders: reg, logger: slog.Default()})
+
+ body, _ := json.Marshal(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "queued before shutdown",
+ })
+ router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-drain")
+ if !live {
+ reg.clear(instID, sender) // what supervisor teardown does
+ }
+ // Workers start already cancelled: everything runs as drain.
+ cancel()
+ router.Start(ctx)
+ router.Wait()
+
+ want := 0
+ if live {
+ want = 1
+ }
+ if got := conn.frameCount(); got != want {
+ t.Fatalf("live=%v: frames = %d, want %d", live, got, want)
+ }
+ }
+}
diff --git a/server/internal/integrations/wecom/relay_ordering_db_test.go b/server/internal/integrations/wecom/relay_ordering_db_test.go
new file mode 100644
index 0000000000..a4589aaf52
--- /dev/null
+++ b/server/internal/integrations/wecom/relay_ordering_db_test.go
@@ -0,0 +1,504 @@
+package wecom
+
+// relay_ordering_db_test.go — the four things the cross-replica dispatcher
+// promises beyond "the reply arrives", each against the real thing it depends
+// on: a migrated database for the turn, and a real Redis for the claim.
+//
+// 1. Two answers to the same person arrive in the order they were produced,
+// INCLUDING when the first one has to be offered again.
+// 2. A re-offer belongs to the worker, so nothing can enqueue after shutdown.
+// 3. A reply nobody delivered is counted once, by one owner.
+// 4. The sizing constants hold to the operational bounds they claim.
+//
+// The claim store here is redisDedupe against a real server, not a map: the
+// property under test in (1) and (3) is what SET NX / EXISTS actually do
+// across processes, and a map cannot be wrong about that in the same ways.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/redis/go-redis/v9"
+
+ "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/util"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// wecomTestRedis is the same gate the rest of the repository uses for
+// Redis-backed tests: REDIS_TEST_URL, a dedicated DB index, flushed around
+// each test so one run cannot see another's claims.
+const wecomRelayTestRedisDB = 12
+
+// testClaimBudget is the claim round trip these tests give the real store. It
+// sizes outcomeGrace (once per offer), so the production 2s would make the
+// outcome-watch tests below sleep for a quarter minute apiece.
+const testClaimBudget = 20 * time.Millisecond
+
+func wecomTestRedis(t *testing.T) *redis.Client {
+ t.Helper()
+ url := os.Getenv("REDIS_TEST_URL")
+ if url == "" {
+ t.Skip("REDIS_TEST_URL not set")
+ }
+ opts, err := redis.ParseURL(url)
+ if err != nil {
+ t.Fatalf("parse REDIS_TEST_URL: %v", err)
+ }
+ opts.DB = wecomRelayTestRedisDB
+ rdb := redis.NewClient(opts)
+ ctx := context.Background()
+ if err := rdb.Ping(ctx).Err(); err != nil {
+ t.Skipf("REDIS_TEST_URL unreachable: %v", err)
+ }
+ if err := rdb.FlushDB(ctx).Err(); err != nil {
+ t.Fatalf("flushdb: %v", err)
+ }
+ t.Cleanup(func() {
+ rdb.FlushDB(context.Background())
+ rdb.Close()
+ })
+ return rdb
+}
+
+// blipOnce wraps a REAL claim store and fails its first Claim, which is the
+// one fault a live Redis cannot be asked to produce on cue. Everything else —
+// the SET NX, the TTL, the EXISTS behind the outcome watch — is the real
+// implementation against the real server.
+type blipOnce struct {
+ DedupeStore
+ mu sync.Mutex
+ done bool
+}
+
+func (b *blipOnce) Claim(ctx context.Context, key string, ttl time.Duration) (bool, error) {
+ b.mu.Lock()
+ first := !b.done
+ b.done = true
+ b.mu.Unlock()
+ if first {
+ return false, errors.New("wecom test: redis blip")
+ }
+ return b.DedupeStore.Claim(ctx, key, ttl)
+}
+
+// sentTexts is what actually reached the chat, in order.
+func sentTexts(t *testing.T, c *recordingConn) []string {
+ t.Helper()
+ c.mu.Lock()
+ frames := append([]frameEnvelope(nil), c.frames...)
+ c.mu.Unlock()
+ var out []string
+ for _, f := range frames {
+ var body struct {
+ Markdown struct {
+ Content string `json:"content"`
+ } `json:"markdown"`
+ }
+ if err := json.Unmarshal(f.Body, &body); err != nil {
+ continue
+ }
+ if body.Markdown.Content != "" {
+ out = append(out, body.Markdown.Content)
+ }
+ }
+ return out
+}
+
+// seedSiblingTurn adds a SECOND completed turn to a seeded conversation, so two
+// replies compete for one installation's queue — which is where ordering means
+// anything at all.
+func seedSiblingTurn(t *testing.T, pool *pgxpool.Pool, turn boundTurn) boundTurn {
+ t.Helper()
+ ctx := context.Background()
+ newID := func() string {
+ t.Helper()
+ var id string
+ if err := pool.QueryRow(ctx, `SELECT gen_random_uuid()::text`).Scan(&id); err != nil {
+ t.Fatalf("seed sibling: mint id: %v", err)
+ }
+ return id
+ }
+ var agentID, bindingID string
+ if err := pool.QueryRow(ctx,
+ `SELECT agent_id::text FROM chat_session WHERE id = $1`, turn.sessionID).Scan(&agentID); err != nil {
+ t.Fatalf("seed sibling: read agent: %v", err)
+ }
+ if err := pool.QueryRow(ctx,
+ `SELECT binding_id::text FROM channel_task_delivery WHERE task_id = $1`, turn.taskID).Scan(&bindingID); err != nil {
+ t.Fatalf("seed sibling: read binding: %v", err)
+ }
+ sibling := boundTurn{
+ sessionID: turn.sessionID, taskID: newID(),
+ instID: turn.instID, chatID: turn.chatID,
+ }
+ inputTaskID := newID()
+ t.Cleanup(func() {
+ _, _ = pool.Exec(ctx, `DELETE FROM chat_message WHERE task_id = $1`, inputTaskID)
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_task_delivery WHERE task_id = $1`, sibling.taskID)
+ _, _ = pool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = ANY($1)`,
+ []string{sibling.taskID, inputTaskID})
+ })
+ exec := func(sql string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, sql, args...); err != nil {
+ t.Fatalf("seed sibling: %s: %v", strings.SplitN(strings.TrimSpace(sql), "\n", 2)[0], err)
+ }
+ }
+ exec(`INSERT INTO agent_task_queue (id, agent_id, chat_session_id, status, completed_at)
+ VALUES ($1, $2, $3, 'completed', now())`, inputTaskID, agentID, sibling.sessionID)
+ exec(`INSERT INTO agent_task_queue (id, agent_id, chat_session_id, status, completed_at, chat_input_task_id)
+ VALUES ($1, $2, $3, 'completed', now(), $4)`, sibling.taskID, agentID, sibling.sessionID, inputTaskID)
+ exec(`INSERT INTO channel_task_delivery
+ (task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, route_revision, config)
+ VALUES ($1, $2, $3, 'wecom', $4, 'p2p', 1, '{}')`,
+ sibling.taskID, bindingID, sibling.instID, sibling.chatID)
+ exec(`INSERT INTO chat_message (chat_session_id, role, content, task_id, channel_ingested)
+ VALUES ($1, 'user', '第二个问题', $2, true)`, sibling.sessionID, inputTaskID)
+ return sibling
+}
+
+func chatDoneWith(turn boundTurn, content string) events.Event {
+ e := chatDoneFor(turn)
+ e.Payload = protocol.ChatDonePayload{
+ ChatSessionID: turn.sessionID,
+ TaskID: turn.taskID,
+ Content: content,
+ }
+ return e
+}
+
+// ---------------------------------------------------------------------------
+// 1. Ordering across a re-offer
+// ---------------------------------------------------------------------------
+
+// Two answers for one bot, produced in order, where the FIRST one's claim hits
+// a Redis blip and has to be offered again. The second must not overtake it.
+//
+// This is the defect the review reproduced: the old dispatcher scheduled the
+// re-offer with time.AfterFunc and moved straight on to the next item, so the
+// wire order was [second, first] — two answers arriving in a chat in the
+// opposite order to the questions that produced them.
+func TestRelay_ARetriedReplyKeepsItsPlaceInLine(t *testing.T) {
+ pool := twoReplicaDB(t)
+ rdb := wecomTestRedis(t)
+ first := seedBoundTurn(t, pool)
+ second := seedSiblingTurn(t, pool, first)
+
+ relay := &fanoutRelay{}
+ dedupe := &blipOnce{DedupeStore: NewRedisDedupe(rdb, testClaimBudget, slog.Default())}
+
+ // One shard, so both replies are provably on the same worker: with the
+ // default eight the two installations would be the same anyway, but a
+ // single queue says so rather than relying on the hash.
+ cfg := RelayConfig{Shards: 1, LeaseSettle: 400 * time.Millisecond, RetryBackoff: 20 * time.Millisecond}
+ holder := newRelayReplicaWith(t, pool, first.instID, true, relay, dedupe, cfg)
+ publisher := newRelayReplicaWith(t, pool, first.instID, false, relay, dedupe, cfg)
+
+ const firstAnswer, secondAnswer = "答案一", "答案二"
+ publisher.bus.Publish(chatDoneWith(first, firstAnswer))
+ publisher.bus.Publish(chatDoneWith(second, secondAnswer))
+
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ if len(sentTexts(t, holder.conn)) >= 2 {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ got := sentTexts(t, holder.conn)
+ if len(got) != 2 {
+ t.Fatalf("the chat received %v, want both answers", got)
+ }
+ if got[0] != firstAnswer || got[1] != secondAnswer {
+ t.Fatalf("delivery order = %v, want [%q %q] — the retried reply was overtaken",
+ got, firstAnswer, secondAnswer)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 2. A pending re-offer belongs to the worker
+// ---------------------------------------------------------------------------
+
+// Wait() must mean it, and the way to see whether it does is to ask what
+// happens to a reply that is between offers when the process stops.
+//
+// The old re-offer lived on a time.AfterFunc that nothing joined and nothing
+// drained: it checked the context, found it cancelled, and returned — taking
+// the frame with it. So a reply that had failed once and was waiting to be
+// tried again was silently discarded by the very shutdown that runs a drain
+// specifically so replies are not discarded. Owning the wait inside the worker
+// is what puts that frame somewhere the drain can find it.
+func TestRelay_AReplyWaitingToBeRetriedIsStillDrainedOnShutdown(t *testing.T) {
+ t.Parallel()
+ h := &failsOnceHandler{}
+ router := NewRelayOutbound(&fanoutRelay{}, nil,
+ // A backoff far longer than the test, so the frame is provably still
+ // waiting when the shutdown arrives rather than racing it.
+ RelayConfig{Shards: 1, LeaseSettle: 40 * time.Second, RetryBackoff: 20 * time.Second},
+ slog.Default())
+ router.Attach(h)
+ ctx, cancel := context.WithCancel(context.Background())
+ router.Start(ctx)
+
+ body, _ := json.Marshal(relayFrame{Kind: relayKindReply, InstallationID: "inst-1", Content: "hi"})
+ router.DeliverWecomOutbound("inst-1", body, "ev-1")
+
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) && h.calls() == 0 {
+ time.Sleep(5 * time.Millisecond)
+ }
+ if h.calls() != 1 {
+ t.Fatalf("first attempt ran %d times, want 1", h.calls())
+ }
+
+ cancel()
+ router.Wait()
+
+ if got := h.calls(); got != 2 {
+ t.Fatalf("delivery attempts = %d, want 2 — a reply waiting to be retried was "+
+ "discarded by the shutdown instead of drained", got)
+ }
+ if !h.deliveredOK() {
+ t.Error("the drained retry did not reach the wire")
+ }
+ // And nothing is left behind it.
+ for i, q := range router.queues {
+ if n := len(q); n != 0 {
+ t.Errorf("shard %d still holds %d frames after Wait", i, n)
+ }
+ }
+}
+
+// failsOnceHandler refuses the first delivery in a way that provably put
+// nothing on the wire — so the frame is owed another offer — and accepts the
+// second.
+type failsOnceHandler struct {
+ mu sync.Mutex
+ n int
+ delivered bool
+}
+
+func (h *failsOnceHandler) ownsSocket(string) bool { return true }
+func (h *failsOnceHandler) deliverRelayed(context.Context, relayFrame) deliveryOutcome {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.n++
+ if h.n == 1 {
+ return outcomeProvablyNotSent
+ }
+ h.delivered = true
+ return outcomeDone
+}
+func (h *failsOnceHandler) calls() int {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.n
+}
+func (h *failsOnceHandler) deliveredOK() bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.delivered
+}
+
+// ---------------------------------------------------------------------------
+// 3. One owner for the end-to-end outcome
+// ---------------------------------------------------------------------------
+
+// No replica holds a socket. Every party behaves correctly — the publisher
+// routes it, each consumer reads it and correctly declines — and the user gets
+// nothing. Somebody has to say so, exactly once.
+//
+// Before this, nobody did: the publisher returned after a successful publish
+// and every consumer returned at the ownership gate, so the reply vanished
+// with no counter moving, while the PR text claimed this counter could size
+// the window.
+func TestRelay_AReplyNoReplicaCouldSendIsCountedOnce(t *testing.T) {
+ pool := twoReplicaDB(t)
+ rdb := wecomTestRedis(t)
+ turn := seedBoundTurn(t, pool)
+
+ relay := &fanoutRelay{}
+ dedupe := NewRedisDedupe(rdb, testClaimBudget, slog.Default())
+ // A short chain so the grace the watch waits out is a test's worth of time
+ // rather than a lease poll's.
+ cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond}
+
+ // Neither replica holds the socket: both are mid-reconnect, which is the
+ // residual window SELF_HOSTING.md describes.
+ a := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)
+ b := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)
+
+ a.bus.Publish(chatDoneWith(turn, "nobody can send this"))
+
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ if a.mx.get("outbound_dropped:no_live_connection")+b.mx.get("outbound_dropped:no_live_connection") > 0 {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ total := a.mx.get("outbound_dropped:no_live_connection") + b.mx.get("outbound_dropped:no_live_connection")
+ if total != 1 {
+ t.Fatalf("no_live_connection = %d across both replicas, want exactly 1 — "+
+ "a reply nobody could send must be counted once, by one owner", total)
+ }
+ if delivered := a.mx.get("outbound_delivered") + b.mx.get("outbound_delivered"); delivered != 0 {
+ t.Errorf("outbound_delivered = %d, want 0 — nothing reached anybody", delivered)
+ }
+}
+
+// The other half of the same rule, and the one that keeps it honest: when a
+// replica DOES deliver, the publisher's watch must stay quiet. A claim that is
+// held is the evidence that somebody took it.
+func TestRelay_ADeliveredReplyIsCountedOnceAndNotAlsoLost(t *testing.T) {
+ pool := twoReplicaDB(t)
+ rdb := wecomTestRedis(t)
+ turn := seedBoundTurn(t, pool)
+
+ relay := &fanoutRelay{}
+ dedupe := NewRedisDedupe(rdb, testClaimBudget, slog.Default())
+ cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond}
+ holder := newRelayReplicaWith(t, pool, turn.instID, true, relay, dedupe, cfg)
+ publisher := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)
+
+ publisher.bus.Publish(chatDoneWith(turn, "答案"))
+
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) && len(sentTexts(t, holder.conn)) == 0 {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if got := sentTexts(t, holder.conn); len(got) != 1 {
+ t.Fatalf("the chat received %v, want the one answer", got)
+ }
+ // Past the whole grace, so the watch has run and had its say.
+ time.Sleep(600 * time.Millisecond)
+
+ if got := holder.mx.get("outbound_delivered"); got != 1 {
+ t.Errorf("outbound_delivered on the holder = %d, want 1", got)
+ }
+ if got := publisher.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("outbound_dropped on the publisher = %d, want 0 — it was delivered", got)
+ }
+ if got := holder.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("outbound_dropped on the holder = %d, want 0", got)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 4. The sizing constants against the bounds they claim
+// ---------------------------------------------------------------------------
+
+// The re-offer chain exists to outlast a lease move, and how long that takes is
+// the channel supervisor's poll interval — an external bound, and a knob. The
+// old fixed five attempts at 200ms covered about three seconds against a 30s
+// default poll: it expired while the replica that would deliver was still on
+// its way.
+func TestRelayRetryPlan_OutlastsALeaseMove(t *testing.T) {
+ t.Parallel()
+ for _, settle := range []time.Duration{
+ 5 * time.Second,
+ 30 * time.Second, // the CHANNEL_WS_LEASE_POLL_INTERVAL default
+ 2 * time.Minute,
+ } {
+ cfg := RelayConfig{LeaseSettle: settle}.withDefaults()
+ plan := cfg.retryPlan()
+ var total time.Duration
+ for _, d := range plan {
+ total += d
+ if d > settle {
+ t.Errorf("settle=%s: a single backoff of %s is longer than the move it waits for", settle, d)
+ }
+ }
+ if total < settle {
+ t.Errorf("settle=%s: the chain covers only %s — it gives up while the lease is still moving",
+ settle, total)
+ }
+ if len(plan) > relayRetryChainCap {
+ t.Errorf("settle=%s: %d attempts exceeds the chain cap %d", settle, len(plan), relayRetryChainCap)
+ }
+ }
+}
+
+// A default deployment's chain has to cover the default poll interval. Stated
+// as its own assertion because this is the number that was wrong.
+func TestRelayRetryPlan_DefaultsCoverTheDefaultPollInterval(t *testing.T) {
+ t.Parallel()
+ cfg := RelayConfig{}.withDefaults()
+ if cfg.LeaseSettle != engine.DefaultPollInterval {
+ t.Fatalf("default LeaseSettle = %s, want the supervisor's default poll interval %s",
+ cfg.LeaseSettle, engine.DefaultPollInterval)
+ }
+ var total time.Duration
+ for _, d := range cfg.retryPlan() {
+ total += d
+ }
+ if total < engine.DefaultPollInterval {
+ t.Fatalf("the default chain covers %s against a %s lease move", total, engine.DefaultPollInterval)
+ }
+}
+
+// The drain runs inside the process's own shutdown, so its budget has to fit
+// under the channel supervisor's — the thing that is joined after it. A drain
+// budget larger than that would push shutdown past the supervisor's own bound
+// and cost the final lease release, which is what makes the next replica wait
+// out a whole LeaseTTL after a redeploy.
+func TestRelayDrainBudget_FitsUnderTheSupervisorShutdownTimeout(t *testing.T) {
+ t.Parallel()
+ cfg := RelayConfig{}.withDefaults()
+ if cfg.DrainBudget >= engine.DefaultShutdownTimeout {
+ t.Fatalf("drain budget %s does not fit under the supervisor's shutdown timeout %s",
+ cfg.DrainBudget, engine.DefaultShutdownTimeout)
+ }
+}
+
+// The claim has to outlive the replay window it guards, at every grace an
+// operator can set — including one longer than the floor.
+func TestDedupeTTL_OutlivesEveryReplayWindow(t *testing.T) {
+ t.Parallel()
+ for _, grace := range []time.Duration{0, time.Minute, 5 * time.Minute, 2 * time.Hour} {
+ if ttl := dedupeTTLFor(grace); ttl <= grace {
+ t.Errorf("grace=%s: claim TTL %s expires inside the window it guards", grace, ttl)
+ }
+ }
+}
+
+// The outcome watch must not call a reply lost while it is still being
+// re-offered: the grace has to sit past the whole chain.
+func TestRelayOutcomeGrace_OutlastsTheReOfferChain(t *testing.T) {
+ t.Parallel()
+ r := NewRelayOutbound(nil, nil, RelayConfig{}, slog.Default())
+ var chain time.Duration
+ for _, d := range r.retryPlan {
+ chain += d
+ }
+ if r.outcomeGrace() <= chain {
+ t.Fatalf("outcome grace %s is inside the %s re-offer chain — a reply still in flight would be counted lost",
+ r.outcomeGrace(), chain)
+ }
+}
+
+// shardFor must stay inside the configured queue count, including for a
+// non-default shard count. A hash that indexed past the slice would panic on
+// the shard read loop, which is the one goroutine that must never fail.
+func TestRelayShardFor_StaysInsideTheConfiguredQueues(t *testing.T) {
+ t.Parallel()
+ for _, shards := range []int{1, 3, 8, 64} {
+ r := NewRelayOutbound(nil, nil, RelayConfig{Shards: shards}, slog.Default())
+ for i := 0; i < 500; i++ {
+ id := util.UUIDToString(mustTestUUID(t))
+ if got := r.shardFor(id); got < 0 || got >= shards {
+ t.Fatalf("shards=%d: shardFor(%s) = %d, outside the queues", shards, id, got)
+ }
+ }
+ }
+}
diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.go
new file mode 100644
index 0000000000..d3ed44d3ae
--- /dev/null
+++ b/server/internal/integrations/wecom/relay_outbound.go
@@ -0,0 +1,1095 @@
+package wecom
+
+// relay_outbound.go — how a reply reaches the replica that can send it.
+//
+// WeCom is the one channel with no outbound REST path: every write goes over
+// the aibot WebSocket, and the WS lease means exactly one replica holds it.
+// chat:done, meanwhile, is published on the in-process events.Bus by whichever
+// replica served the daemon's POST /tasks/{id}/complete — a load-balancer
+// decision. Off-lease, outbound.go used to have nothing to do but drop the
+// reply (GH #7215, #6890; SELF_HOSTING.md states the resulting constraint).
+//
+// This routes it over the Redis Stream relay the repository already runs for
+// exactly this shape of problem: daemonws.RelayNotifier wakes a daemon
+// connected to another replica by publishing under ScopeDaemonRuntime, and
+// every node's XREAD loop hands the frame to whoever holds that connection.
+//
+// THREE THINGS THAT MECHANISM REQUIRES OF ITS CONSUMERS, and that a naive copy
+// of the daemon-wakeup shape does not satisfy:
+//
+// 1. It replays. A shard reader starts from (now - ReplayGrace), not "$", so
+// events published while a pod was down are re-read — its own doc says
+// "downstream consumers must be idempotent". A per-process seen-set is not
+// idempotent across a restart, and does not span two replicas either. The
+// claim therefore lives in Redis, keyed on the turn, with a lifetime that
+// comfortably outlasts the replay window. Redis is not a new dependency
+// here: it IS the transport. No Redis means no relay, which means no
+// cross-replica delivery and nothing to deduplicate.
+//
+// 2. It calls the consumer SYNCHRONOUSLY on the shard read loop. The daemon
+// wakeup's work there is a map lookup and a buffered write; ours is a
+// network round trip that waits up to ackTimeout for the platform's
+// verdict. Doing that inline would let one unhealthy bot stall browser
+// realtime traffic, daemon wakeups, and every other bot on that shard. So
+// DeliverWecomOutbound only hands the frame to a bounded queue and
+// returns.
+//
+// 3. Its readers start early. Registration therefore has to be possible
+// before the senders registry and the subscriber exist: this object is
+// built and registered first, and Attach supplies the handler afterwards.
+// Frames that arrive in between wait in the queue rather than being
+// dropped against a nil field.
+//
+// ORDERING: every reply for one installation is carried by one queue and one
+// worker, in the order it arrived — INCLUDING across a re-offer. A frame that
+// has to be tried again does not go to the back of the queue; it parks at the
+// head of its own installation's line and everything behind it waits, because
+// two answers to the same person arriving in the wrong order is the defect
+// this ordering exists to prevent.
+//
+// Sharding is a CONCURRENCY bound, not an isolation guarantee: installations
+// are hashed onto RelayConfig.Shards queues, so two bots that collide on a
+// shard do wait behind each other. What the shard count buys is that one slow
+// bot cannot occupy every worker.
+
+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 reports whether the caller is the first to take key. It must be
+ // atomic across processes.
+ Claim(ctx context.Context, key string, ttl time.Duration) (bool, error)
+ // Release gives a claim back, for a delivery that provably did not happen.
+ Release(ctx context.Context, key string)
+ // Held reports whether key is claimed right now. It is how the publisher
+ // learns, after the fact, whether ANY replica took a delivery it routed —
+ // see RelayOutbound.watchOutcomes.
+ Held(ctx context.Context, key string) (bool, 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 {
+ // 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
+
+ // 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
+)
+
+// withDefaults fills the zero fields and returns the completed config.
+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
+ }
+ 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
+ InstallationID string `json:"installation_id"`
+ ChatID string `json:"chat_id"`
+ ChatType int `json:"chat_type"`
+ Content string `json:"content"`
+ 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"`
+}
+
+const (
+ relayKindReply = "reply"
+ relayKindInbox = "inbox"
+)
+
+// 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) deliveryOutcome
+ // ownsSocket answers "does this process hold that installation's live
+ // connection right now". It gates the global claim — see perform.
+ ownsSocket(installationID string) bool
+}
+
+// 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
+)
+
+// 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
+ 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
+
+ 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(),
+ 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{}
+}
+
+// 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. Reports whether it went out.
+func (r *RelayOutbound) publish(f relayFrame, eventID string) bool {
+ if r == nil || r.publisher == nil {
+ return false
+ }
+ body, err := json.Marshal(f)
+ if err != nil {
+ r.logger.Warn("wecom relay: marshal outbound frame", "error", err)
+ return false
+ }
+ if err := r.publisher.PublishWithID(realtime.ScopeWecomOutbound, f.InstallationID, "", body, eventID); err != nil {
+ r.logger.Warn("wecom relay: publish failed",
+ "error", err, "installation_id", f.InstallationID, "task_id", f.TaskID)
+ return false
+ }
+ // 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)
+ }
+ return true
+}
+
+// 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
+ }
+ select {
+ case r.queues[r.shardFor(f.InstallationID)] <- 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")
+ }
+}
+
+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 {
+ // 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)
+ if r.dedupe != nil {
+ won, err := r.dedupe.Claim(ctx, key, 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
+ }
+ }
+ outcome := r.handler.deliverRelayed(ctx, item.frame)
+ if outcome == outcomeDone {
+ 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).
+ r.seen.forget(item.eventID)
+ if r.dedupe != nil {
+ r.dedupe.Release(ctx, key)
+ }
+ return false
+}
+
+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()
+ }
+ total := budget * time.Duration(len(r.retryPlan)+1)
+ for _, d := range r.retryPlan {
+ total += d
+ }
+ 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 set by
+// whoever took the delivery and released only by a replica that proved it sent
+// nothing. So once the re-offer chain can no longer be running, a key that is
+// absent means the reply reached nobody. One Redis EXISTS 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) {
+ held, err := r.dedupe.Held(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
+ }
+ if held {
+ return // somebody took it; the replica that did is what counts it
+ }
+ 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 *RelayOutbound) 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.
+func relayInboxEventID(itemID, recipientID string) string {
+ return "wecom:inbox:" + itemID + ":" + recipientID
+}
+
+// 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) deliveryOutcome {
+ instID, err := util.ParseUUID(f.InstallationID)
+ if err != nil || !instID.Valid {
+ return outcomeDone // unaddressable; a retry cannot make it addressable
+ }
+ if o.senders == nil {
+ return outcomeNotOurs
+ }
+ sender := o.senders.get(instID)
+ if sender == nil {
+ return outcomeNotOurs // the replica holding the lease will take it
+ }
+ if f.Content != "" {
+ if err := sender.sendTextCtx(ctx, f.ChatID, f.ChatType, f.Content); err != nil {
+ // The reply counters are 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, and the delivered/dropped ratio would track
+ // socket placement instead of outcomes.
+ if f.Kind == relayKindReply {
+ if reason := unconfirmedReason(err); reason != "" {
+ o.unconfirmedFor(ctx, f.SessionID, f.Kind, reason, err)
+ } else {
+ o.droppedFor(ctx, f.SessionID, f.Kind, classifyDrop(err), err)
+ }
+ } else {
+ o.logger.WarnContext(ctx, "wecom relay: inbox push failed on the lease holder",
+ "error", err, "installation_id", f.InstallationID)
+ }
+ // 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) {
+ return outcomeProvablyNotSent
+ }
+ return outcomeDone
+ }
+ if f.Kind == relayKindReply {
+ o.delivered()
+ }
+ }
+ if f.Kind == relayKindInbox {
+ return outcomeDone
+ }
+ if f.CarriesFiles {
+ o.deliverAttachmentsByID(f.MessageID, f.WorkspaceID, attachmentTarget{
+ InstallationID: instID,
+ ChatID: f.ChatID,
+ ChatType: f.ChatType,
+ SessionID: f.SessionID,
+ }, f.Content == "")
+ }
+ return outcomeDone
+}
+
+// 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, and a stated refusal is a *wecomAPIError — all three mean the
+// peer may have (or, for a refusal, definitely did) see the frame. A bare
+// context error is ambiguous — request() returns one both from its pre-write
+// check and from the post-write wait — so it is treated as possibly sent,
+// which costs an un-retried delivery rather than a duplicate.
+func provablyNotSent(err error) bool {
+ var apiErr *wecomAPIError
+ switch {
+ case err == nil:
+ return false
+ case errors.As(err, &apiErr):
+ return false
+ case errors.Is(err, errAckTimeout):
+ return false
+ case errors.Is(err, errWriteAttempted):
+ return false
+ 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
+}
diff --git a/server/internal/integrations/wecom/relay_outbound_attribution_test.go b/server/internal/integrations/wecom/relay_outbound_attribution_test.go
new file mode 100644
index 0000000000..45bb2bddf8
--- /dev/null
+++ b/server/internal/integrations/wecom/relay_outbound_attribution_test.go
@@ -0,0 +1,247 @@
+package wecom
+
+// relay_outbound_attribution_test.go — three properties the dispatcher gets
+// wrong in ways nothing else here would notice, because each one is about
+// ATTRIBUTION rather than delivery: who a shed belongs to, how long a reply may
+// still be in flight before it counts as lost, and which of two answers goes
+// out first when the process is on its way down.
+//
+// None of them needs a database or a Redis: each is a decision the dispatcher
+// makes on its own, so the test makes it directly.
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// ---------------------------------------------------------------------------
+// 1. A shed is an admission decision, never a reply outcome
+// ---------------------------------------------------------------------------
+
+// ownsSocketHandler holds the socket, or does not, and records nothing else.
+type ownsSocketHandler struct {
+ mu sync.Mutex
+ owns bool
+ calls []relayFrame
+}
+
+func (h *ownsSocketHandler) ownsSocket(string) bool { return h.owns }
+func (h *ownsSocketHandler) deliverRelayed(_ context.Context, f relayFrame) deliveryOutcome {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.calls = append(h.calls, f)
+ return outcomeDone
+}
+func (h *ownsSocketHandler) sent() []relayFrame {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return append([]relayFrame(nil), h.calls...)
+}
+
+// shedRouter is a router wired to shed: depth 1, never started, so the first
+// frame fills the only slot and the second has nowhere to go. No timing.
+func shedRouter(t *testing.T, owns bool) (*RelayOutbound, *countingMetrics) {
+ t.Helper()
+ r := NewRelayOutbound(&fanoutRelay{}, nil, RelayConfig{Shards: 1, QueueDepth: 1}, slog.Default())
+ mx := newCountingMetrics()
+ r.SetMetrics(mx)
+ r.Attach(&ownsSocketHandler{owns: owns})
+ return r, mx
+}
+
+func shedTwice(t *testing.T, r *RelayOutbound, kind string) {
+ t.Helper()
+ body, err := json.Marshal(relayFrame{Kind: kind, InstallationID: "inst-1", Content: "答案"})
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ r.DeliverWecomOutbound("inst-1", body, "ev-1") // fills the queue
+ r.DeliverWecomOutbound("inst-1", body, "ev-2") // shed
+}
+
+// No replica can decide a reply's fate from a shed, so none of them may move
+// the reply counter — not even the one holding the socket.
+//
+// Every replica reads every frame. 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 "do I hold the socket" is not proof of being the only one
+// who could. Each replica answering for itself is what produced one reply
+// counted as delivered and dropped at the same time. The publisher's
+// watchOutcomes is the single owner that settles it after the fact.
+func TestRelayShed_NeverMovesTheReplyCounter(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ owns bool
+ }{
+ {"holding the socket", true},
+ {"holding no socket", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ r, mx := shedRouter(t, tc.owns)
+ shedTwice(t, r, relayKindReply)
+
+ if got := mx.get("relay_shed:" + relayKindReply); got != 1 {
+ t.Errorf("relay_shed = %d, want 1 — the admission decision still happened", got)
+ }
+ if got := mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("outbound_dropped = %d, want 0 — a shed is not a reply outcome; "+
+ "the publisher's outcome watch settles that, once", got)
+ }
+ })
+ }
+}
+
+// An inbox push moves relay_shed under its own label and nothing else: its
+// unit is not an agent reply.
+func TestRelayShed_AnInboxPushIsLabelledSeparately(t *testing.T) {
+ t.Parallel()
+ r, mx := shedRouter(t, true)
+ shedTwice(t, r, relayKindInbox)
+
+ if got := mx.get("relay_shed:" + relayKindInbox); got != 1 {
+ t.Errorf("relay_shed:%s = %d, want 1", relayKindInbox, got)
+ }
+ if got := mx.get("relay_shed:"+relayKindReply) + mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("reply counters moved by %d on an inbox push, want 0", got)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 2. The outcome grace carries one claim round trip PER OFFER
+// ---------------------------------------------------------------------------
+
+// budgetStore is a DedupeStore that only exists to state a budget.
+type budgetStore struct {
+ DedupeStore
+ budget time.Duration
+}
+
+func (b budgetStore) ClaimBudget() time.Duration { return b.budget }
+
+// The re-offer chain makes a claim on every attempt, not once for the whole
+// chain, and each of those can burn the full budget. A grace built from the
+// backoffs plus a single round trip therefore expires while the chain is still
+// running against a slow store — and the watcher records no_live_connection
+// for a reply the very next attempt then delivers, so one reply moves both
+// counters.
+func TestRelayOutcomeGrace_CoversAClaimRoundTripPerOffer(t *testing.T) {
+ t.Parallel()
+ const budget = 2 * time.Second
+ r := NewRelayOutbound(nil, budgetStore{budget: budget}, RelayConfig{}, slog.Default())
+
+ var chain time.Duration
+ for _, d := range r.retryPlan {
+ chain += d
+ }
+ // Worst case the chain can actually take: every backoff, plus a claim that
+ // times out on the first offer and on each re-offer.
+ worst := chain + budget*time.Duration(len(r.retryPlan)+1)
+
+ if r.outcomeGrace() < worst {
+ t.Fatalf("outcome grace %s is shorter than the %s a fully timed-out chain can take "+
+ "(%d offers × %s claim + %s of backoff) — the watch would call a reply lost while "+
+ "it was still being retried, and the retry would then deliver it",
+ r.outcomeGrace(), worst, len(r.retryPlan)+1, budget, chain)
+ }
+}
+
+// The grace is sized from the budget the STORE enforces, not from a number the
+// dispatcher keeps for itself — that is the whole reason ClaimBudget is on the
+// interface. A store with a different bound must move the grace with it.
+func TestRelayOutcomeGrace_TracksTheStoresOwnBudget(t *testing.T) {
+ t.Parallel()
+ small := NewRelayOutbound(nil, budgetStore{budget: 10 * time.Millisecond}, RelayConfig{}, slog.Default())
+ large := NewRelayOutbound(nil, budgetStore{budget: 10 * time.Second}, RelayConfig{}, slog.Default())
+ if small.outcomeGrace() >= large.outcomeGrace() {
+ t.Fatalf("grace did not follow the store's budget: 10ms store gave %s, 10s store gave %s",
+ small.outcomeGrace(), large.outcomeGrace())
+ }
+}
+
+// The production store's default is what the dispatcher inherits when a
+// deployment does not override it.
+func TestRedisDedupe_DefaultsToTheDocumentedClaimBudget(t *testing.T) {
+ t.Parallel()
+ rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"}) // never dialled
+ t.Cleanup(func() { rdb.Close() })
+ if got := NewRedisDedupe(rdb, 0, slog.Default()).ClaimBudget(); got != defaultClaimBudget {
+ t.Fatalf("ClaimBudget() = %s, want the documented default %s", got, defaultClaimBudget)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 3. Shutdown does not invert two answers
+// ---------------------------------------------------------------------------
+
+// A worker can take a frame off the queue in the same turn the cancel fires:
+// the select is fair, so the queue branch can win against an already-closed
+// Done. That frame is handed to the drain as `first`.
+//
+// It arrived AFTER whatever is parked at its installation's line, so performing
+// it first inverts two answers in the user's chat — the exact reordering
+// offer() exists to prevent, undone on the way out. drainRemaining is called
+// directly here because the interleaving that produces it is a race by nature,
+// and the decision under test is not.
+func TestRelayDrain_DoesNotLetALateFrameOvertakeAParkedOne(t *testing.T) {
+ t.Parallel()
+ h := &ownsSocketHandler{owns: true}
+ router := NewRelayOutbound(&fanoutRelay{}, nil, RelayConfig{Shards: 1}, slog.Default())
+ router.Attach(h)
+
+ const inst = "inst-1"
+ // "first" in the chat is the one already parked, waiting out its backoff.
+ lines := map[string]*hold{
+ inst: {items: []queued{{
+ frame: relayFrame{Kind: relayKindReply, InstallationID: inst, Content: "answer-1"},
+ eventID: "ev-1",
+ }}},
+ }
+ // The one the worker had just taken off the queue when the cancel won.
+ late := queued{
+ frame: relayFrame{Kind: relayKindReply, InstallationID: inst, Content: "answer-2"},
+ eventID: "ev-2",
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ router.drainRemaining(ctx, make(chan queued), lines, &late)
+
+ var got []string
+ for _, f := range h.sent() {
+ got = append(got, f.Content)
+ }
+ want := []string{"answer-1", "answer-2"}
+ if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
+ t.Fatalf("the chat received %v, want %v — shutdown let a later reply overtake the one "+
+ "already waiting at the head of its installation's line", got, want)
+ }
+}
+
+// A late frame for an installation with no line has nothing to overtake, so it
+// still goes out on the drain rather than being stranded.
+func TestRelayDrain_ALateFrameWithNoLineIsStillDelivered(t *testing.T) {
+ t.Parallel()
+ h := &ownsSocketHandler{owns: true}
+ router := NewRelayOutbound(&fanoutRelay{}, nil, RelayConfig{Shards: 1}, slog.Default())
+ router.Attach(h)
+
+ late := queued{
+ frame: relayFrame{Kind: relayKindReply, InstallationID: "inst-2", Content: "answer"},
+ eventID: "ev-1",
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ router.drainRemaining(ctx, make(chan queued), map[string]*hold{}, &late)
+
+ if got := h.sent(); len(got) != 1 || got[0].Content != "answer" {
+ t.Fatalf("drained %d frames (%v), want the one answer", len(got), got)
+ }
+}
diff --git a/server/internal/integrations/wecom/senders_registry.go b/server/internal/integrations/wecom/senders_registry.go
index 998a51e053..92efaf60bc 100644
--- a/server/internal/integrations/wecom/senders_registry.go
+++ b/server/internal/integrations/wecom/senders_registry.go
@@ -24,6 +24,10 @@ import (
)
// sendersRegistry is a goroutine-safe installation_id → wsSender map.
+// SendersRegistry is exported only so boot can mint one before the relay's
+// shard readers start; every method stays unexported.
+type SendersRegistry = sendersRegistry
+
type sendersRegistry struct {
mu sync.RWMutex
byKey map[string]*wsSender
@@ -38,7 +42,7 @@ func newSendersRegistry() *sendersRegistry {
// same registry into both the wecom ChannelDeps (writer side) and the
// OutboundReplier (reader side). Kept exported so router.go can wire it
// without importing an unexported type.
-func NewSendersRegistry() *sendersRegistry { return newSendersRegistry() }
+func NewSendersRegistry() *SendersRegistry { return newSendersRegistry() }
func (r *sendersRegistry) set(id pgtype.UUID, s *wsSender) {
r.mu.Lock()
diff --git a/server/internal/metrics/wecom.go b/server/internal/metrics/wecom.go
index a87ac12d59..f902310585 100644
--- a/server/internal/metrics/wecom.go
+++ b/server/internal/metrics/wecom.go
@@ -61,6 +61,10 @@ type WecomMetrics struct {
AttachmentSheds prometheus.Counter
OutboundUnconfirmed *prometheus.CounterVec
AttachmentUnconfirmed *prometheus.CounterVec
+ // RelayShed counts admission decisions on the cross-replica dispatcher,
+ // labelled by frame kind. Its own metric because the relay carries inbox
+ // notifications as well as replies and the reply counters are per reply.
+ RelayShed *prometheus.CounterVec
}
func NewWecomMetrics() *WecomMetrics {
@@ -104,6 +108,10 @@ func NewWecomMetrics() *WecomMetrics {
Namespace: "multica", Subsystem: "wecom", Name: "outbound_attachment_unconfirmed_total",
Help: "Files whose delivery outcome is UNKNOWN, by reason. Counts FILES, same unit as the attachment delivered/dropped pair; see outbound_unconfirmed_total for why unknown is not a drop.",
}, []string{"reason"}),
+ RelayShed: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica", Subsystem: "wecom", Name: "outbound_relay_shed_total",
+ Help: "Frames the cross-replica dispatcher refused because a shard queue was full, by kind (reply|inbox). An ADMISSION decision, not a per-reply outcome: the relay carries inbox notifications too, and counting those as dropped replies would make the delivered/dropped ratio track which replica held a socket instead of what happened to anyone's message. Recorded on whichever replica refused the frame, and it moves no reply counter: every replica reads every frame, so no replica can tell locally whether its own shed cost the user anything. Whether a shed reply was in fact lost is settled once by the replica that routed it, as outbound_dropped_total{reason=\"no_live_connection\"} when no replica claimed the delivery.",
+ }, []string{"kind"}),
}
}
@@ -114,6 +122,7 @@ func (m *WecomMetrics) Collectors() []prometheus.Collector {
m.OutboundDelivered, m.OutboundDropped, m.OutboundSkipped,
m.AttachmentDelivered, m.AttachmentDropped, m.AttachmentSheds,
m.OutboundUnconfirmed, m.AttachmentUnconfirmed,
+ m.RelayShed,
}
}
@@ -141,3 +150,7 @@ func (m *WecomMetrics) RecordOutboundUnconfirmed(reason string) {
func (m *WecomMetrics) RecordAttachmentUnconfirmed(reason string) {
m.AttachmentUnconfirmed.WithLabelValues(reason).Inc()
}
+
+func (m *WecomMetrics) RecordRelayShed(kind string) {
+ m.RelayShed.WithLabelValues(kind).Inc()
+}
diff --git a/server/internal/realtime/broadcaster.go b/server/internal/realtime/broadcaster.go
index a90c7ee67f..058542b07f 100644
--- a/server/internal/realtime/broadcaster.go
+++ b/server/internal/realtime/broadcaster.go
@@ -11,6 +11,22 @@ const (
// ScopeDaemonRuntime routes daemon wakeup frames through the Redis relay.
// It is consumed by the daemon WebSocket hub, not by browser clients.
ScopeDaemonRuntime = "daemon_runtime"
+
+ // ScopeWecomOutbound routes a WeCom reply to the replica holding that
+ // installation's aibot WebSocket.
+ //
+ // WeCom is the one channel whose outbound has no REST path: a reply can
+ // only leave the process that holds the socket, and the WS lease makes
+ // that exactly one process. But chat:done is published on the in-process
+ // events.Bus by whichever replica served the daemon's completion callback,
+ // which is a load-balancer decision. Off-lease, the reply used to be
+ // dropped (GH #7215, #6890, and the single-replica exception in
+ // SELF_HOSTING.md).
+ //
+ // The scope id is the installation id, so this is the same shape as
+ // ScopeDaemonRuntime: the thing that must act lives on one specific
+ // replica, and the relay is how the others reach it.
+ ScopeWecomOutbound = "wecom_outbound"
)
// Broadcaster is the abstraction every realtime event producer should depend
@@ -46,5 +62,12 @@ type DaemonRuntimeDeliverer interface {
DeliverDaemonRuntime(scopeID string, frame []byte, eventID string)
}
+// WecomOutboundDeliverer consumes wecom-outbound scoped relay frames. Every
+// replica receives every frame; the implementation delivers only when it holds
+// that installation's socket and ignores the rest, so exactly one acts.
+type WecomOutboundDeliverer interface {
+ DeliverWecomOutbound(scopeID string, frame []byte, eventID string)
+}
+
// Compile-time assertion that *Hub continues to satisfy Broadcaster.
var _ Broadcaster = (*Hub)(nil)
diff --git a/server/internal/realtime/redis_relay.go b/server/internal/realtime/redis_relay.go
index d1c889add4..5800ad8fab 100644
--- a/server/internal/realtime/redis_relay.go
+++ b/server/internal/realtime/redis_relay.go
@@ -105,7 +105,7 @@ func redisString(v any) string {
}
}
-func deliverEnvelope(hub *Hub, daemonRuntime DaemonRuntimeDeliverer, ev envelope) {
+func deliverEnvelope(hub *Hub, daemonRuntime DaemonRuntimeDeliverer, wecomOutbound WecomOutboundDeliverer, ev envelope) {
if ev.PayloadJSON == "" {
return
}
@@ -115,6 +115,10 @@ func deliverEnvelope(hub *Hub, daemonRuntime DaemonRuntimeDeliverer, ev envelope
if daemonRuntime != nil {
daemonRuntime.DeliverDaemonRuntime(ev.ScopeID, frame, ev.EventID)
}
+ case ScopeWecomOutbound:
+ if wecomOutbound != nil {
+ wecomOutbound.DeliverWecomOutbound(ev.ScopeID, frame, ev.EventID)
+ }
case "global":
hub.fanoutAllDedup(frame, "", ev.EventID)
case ScopeUser:
@@ -147,6 +151,7 @@ type RedisRelay struct {
ttlScanSeen map[string]struct{}
daemonRuntime DaemonRuntimeDeliverer
+ wecomOutbound WecomOutboundDeliverer
}
type scopeConsumer struct {
@@ -192,6 +197,10 @@ func NewRedisRelayWithClientsAndConfig(hub *Hub, writeRDB, readRDB *redis.Client
// NodeID returns this relay's randomly-assigned node identifier.
func (r *RedisRelay) NodeID() string { return r.nodeID }
+func (r *RedisRelay) SetWecomOutboundDeliverer(d WecomOutboundDeliverer) {
+ r.wecomOutbound = d
+}
+
func (r *RedisRelay) SetDaemonRuntimeDeliverer(d DaemonRuntimeDeliverer) {
r.daemonRuntime = d
}
@@ -460,7 +469,7 @@ func (r *RedisRelay) deliverMessage(scopeType, scopeID string, msg redis.XMessag
if ev.ScopeID == "" {
ev.ScopeID = scopeID
}
- deliverEnvelope(r.hub, r.daemonRuntime, ev)
+ deliverEnvelope(r.hub, r.daemonRuntime, r.wecomOutbound, ev)
}
// fanoutUser is implemented in hub.go.
diff --git a/server/internal/realtime/sharded_stream_relay.go b/server/internal/realtime/sharded_stream_relay.go
index 1666a1067d..7edd1aad5a 100644
--- a/server/internal/realtime/sharded_stream_relay.go
+++ b/server/internal/realtime/sharded_stream_relay.go
@@ -170,6 +170,7 @@ type ShardedStreamRelay struct {
streamGeneration []atomic.Uint64
daemonRuntime DaemonRuntimeDeliverer
+ wecomOutbound WecomOutboundDeliverer
}
func NewShardedStreamRelay(hub *Hub, writeRDB, readRDB *redis.Client, config ShardedStreamRelayConfig) *ShardedStreamRelay {
@@ -192,6 +193,10 @@ func NewShardedStreamRelay(hub *Hub, writeRDB, readRDB *redis.Client, config Sha
func (r *ShardedStreamRelay) NodeID() string { return r.nodeID }
+func (r *ShardedStreamRelay) SetWecomOutboundDeliverer(d WecomOutboundDeliverer) {
+ r.wecomOutbound = d
+}
+
func (r *ShardedStreamRelay) SetDaemonRuntimeDeliverer(d DaemonRuntimeDeliverer) {
r.daemonRuntime = d
}
@@ -478,7 +483,7 @@ func (r *ShardedStreamRelay) deliverMessage(msg redis.XMessage) {
if !ok || ev.Scope == "" || ev.ScopeID == "" {
return
}
- deliverEnvelope(r.hub, r.daemonRuntime, ev)
+ deliverEnvelope(r.hub, r.daemonRuntime, r.wecomOutbound, ev)
}
func (r *ShardedStreamRelay) heartbeatLoop(ctx context.Context) {