Skip to content

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

Go

MUL-7687 fix(wecom): push an issue notification through the acting agent's bot (#8803)

Basuotian3647ec9a9cc7
diff --git a/server/internal/integrations/wecom/dedupe_redis.go b/server/internal/integrations/wecom/dedupe_redis.go
index c9f7ac8994..f278a6b9c3 100644
--- a/server/internal/integrations/wecom/dedupe_redis.go
+++ b/server/internal/integrations/wecom/dedupe_redis.go
@@ -128,14 +128,37 @@ if not string.find(v, '/', 1, true) then
end
redis.call('SET', KEYS[1], ARGV[2], 'KEEPTTL')
return 1
+`
+ // ClaimState is Resolve WITHOUT the fence: it reads the same key and
+ // returns the same claimState codes, but a held claim stays held. That is
+ // what an inbox publisher polls while it waits to see whether a replica
+ // took the delivery; fencing a holder that is merely mid-delivery would
+ // hand the publisher's fallback a second card to send. Return codes are
+ // claimState values: 0 absent, 1 held, 2 settled, 3 lost.
+ redisClaimStateSource = `
+local v = redis.call('GET', KEYS[1])
+if (not v) then
+ return 0
+end
+if v == ARGV[1] then
+ return 2
+end
+if v == ARGV[2] then
+ return 3
+end
+if not string.find(v, '/', 1, true) then
+ return 2
+end
+return 1
`
)
var (
- redisClaim = redis.NewScript(redisClaimSource)
- redisRelease = redis.NewScript(redisReleaseSource)
- redisSettle = redis.NewScript(redisSettleSource)
- redisResolve = redis.NewScript(redisResolveSource)
+ redisClaim = redis.NewScript(redisClaimSource)
+ redisRelease = redis.NewScript(redisReleaseSource)
+ redisSettle = redis.NewScript(redisSettleSource)
+ redisResolve = redis.NewScript(redisResolveSource)
+ redisClaimState = redis.NewScript(redisClaimStateSource)
)
func (d *redisDedupe) Claim(ctx context.Context, key, token string, ttl time.Duration) (bool, error) {
@@ -198,3 +221,17 @@ func (d *redisDedupe) Resolve(ctx context.Context, key string) (claimState, erro
}
return claimState(n), nil
}
+
+// ClaimState is the read-only half of Resolve: it answers what the key holds
+// without fencing a holder. It is a budget-bounded round trip, like Claim;
+// its caller polls it inside a window it owns, so it must not outstay one
+// call.
+func (d *redisDedupe) ClaimState(ctx context.Context, key string) (claimState, error) {
+ ctx, cancel := context.WithTimeout(ctx, d.budget)
+ defer cancel()
+ n, err := redisClaimState.Run(ctx, d.rdb, []string{key}, claimSettledValue, claimLostValue).Int()
+ if err != nil {
+ return claimAbsent, err
+ }
+ return claimState(n), nil
+}
diff --git a/server/internal/integrations/wecom/failure_origin_test.go b/server/internal/integrations/wecom/failure_origin_test.go
index 3e85f5ac82..e3313d0d3a 100644
--- a/server/internal/integrations/wecom/failure_origin_test.go
+++ b/server/internal/integrations/wecom/failure_origin_test.go
@@ -457,9 +457,17 @@ func TestAFailureOnAReplicaWithNoSocketIsRoutedToTheOneThatHasIt(t *testing.T) {
// would have been handed to the replica holding the socket.
type recordingRelay struct{ frames []relayFrame }
-func (r *recordingRelay) publish(f relayFrame, _ string) bool {
+func (r *recordingRelay) publish(f relayFrame, _ string) relayPublish {
r.frames = append(r.frames, f)
- return true
+ return relayAccepted
+}
+
+// publishAwaitingHolder is the seam's waiting half. The routes that use it are
+// the inbox push's, and this seam is used by the typing indicator's, so it
+// answers the same way publish does: the bus took it.
+func (r *recordingRelay) publishAwaitingHolder(_ context.Context, f relayFrame, _ string) relayPublish {
+ r.frames = append(r.frames, f)
+ return relayAccepted
}
// ---- the answer path's gate has to hand the bubble back too ----
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index 18abc03224..624d39d391 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -85,6 +85,10 @@ type outboundQueries interface {
// roundTaker's taskLookup.
GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
+ // The two member lookups the inbox push picks its bot with, in the order it
+ // tries them: the acting agent's own bot first, then the recipient-wide one
+ // as the fallback. See memberBindingFor.
+ FindChannelBindingForMemberOnAgentInstallation(ctx context.Context, arg db.FindChannelBindingForMemberOnAgentInstallationParams) (db.ChannelUserBinding, error)
FindChannelBindingForMember(ctx context.Context, arg db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error)
GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)
ListAttachmentsByChatMessage(ctx context.Context, arg db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error)
@@ -529,7 +533,9 @@ func taskAddress(ctx context.Context, q deliveryLookup, taskID pgtype.UUID) (rou
}, "", true, nil
}
-// routeFrame hands a frame to the relay, and answers false when there is none.
+// routeFrame hands a frame to the relay and answers what that produced. A
+// caller with no second route reads it through relayPublish.routed; the inbox
+// push reads all four states, because only it can fall back to another bot.
//
// THE NIL CHECK IS HERE BECAUSE THE FIELD IS AN INTERFACE. It used to be a
// *RelayOutbound, whose publish begins with `if r == nil`, so a call through a
@@ -537,13 +543,25 @@ func taskAddress(ctx context.Context, q deliveryLookup, taskID pgtype.UUID) (rou
// A nil interface has no receiver to run that guard, so widening the field
// silently removed the safety three call sites were standing on. One place to
// check it, so the next call site cannot forget.
-func (o *Outbound) routeFrame(f relayFrame, eventID string) bool {
+func (o *Outbound) routeFrame(f relayFrame, eventID string) relayPublish {
if o.relay == nil {
- return false
+ return relayNotWired
}
return o.relay.publish(f, eventID)
}
+// routeFrameAwaiting is routeFrame plus the acceptance wait: it asks the relay
+// whether a replica actually took the frame, bounded by ctx. Only the inbox
+// push asks, and only for the attempt that has a second route behind it -- see
+// RelayOutbound.publishAwaitingHolder for why that distinction is worth a
+// second entry point.
+func (o *Outbound) routeFrameAwaiting(ctx context.Context, f relayFrame, eventID string) relayPublish {
+ if o.relay == nil {
+ return relayNotWired
+ }
+ return o.relay.publishAwaitingHolder(ctx, f, eventID)
+}
+
// relaySeal asks whichever replica holds this round to close it. Routed by
// round ownership, so it needs no address — see deliverRelayed.
func (o *Outbound) relaySeal(e events.Event, taskID pgtype.UUID, reason string, carriesFiles bool) {
@@ -626,7 +644,7 @@ func (o *Outbound) sendAsMessage(ctx context.Context, e events.Event, taskID pgt
WorkspaceID: e.WorkspaceID,
SessionID: e.ChatSessionID,
CarriesFiles: carriesFiles,
- }, relayEventID(e, taskID)) {
+ }, relayEventID(e, taskID)).routed() {
o.logger.DebugContext(ctx, "wecom outbound: routed to the replica holding the socket",
"installation_id", util.UUIDToString(addr.InstallationID), "chat_session_id", e.ChatSessionID)
return answerOutcome{addr: addr, routed: true}, nil
@@ -804,6 +822,17 @@ func (o *Outbound) handleInboxNew(e events.Event) {
// tryDeliverInbox is the delivery core. Returns true iff the bot pushed
// the notification.
+//
+// The bot is chosen by memberBindingFor, which prefers the acting agent's own
+// bot. Preferring it must not make the notification LESS deliverable than the
+// recipient-wide route was, so when the preferred bot provably put nothing on
+// the wire — no live socket for it anywhere in the fleet, or a write that
+// failed before a byte could leave — the recipient-wide binding is tried too.
+// That is the route this notification took before the agent's own bot was
+// preferred, and keeping it is what preserves the guarantee PR #7136 named:
+// nothing a member used to receive stops arriving. An uncertain or partial send
+// is deliberately NOT retried, because the card may already be in the member's
+// chat and a second copy is worse than a late one.
func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, recipientIDStr, workspaceIDStr string) bool {
recipientID, err := util.ParseUUID(recipientIDStr)
if err != nil || !recipientID.Valid {
@@ -813,11 +842,7 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec
if err != nil || !workspaceID.Valid {
return false
}
- binding, err := o.q.FindChannelBindingForMember(ctx, db.FindChannelBindingForMemberParams{
- WorkspaceID: workspaceID,
- MulticaUserID: recipientID,
- ChannelType: channelTypeWecom,
- })
+ binding, actingAgentBot, err := o.memberBindingFor(ctx, item, workspaceID, recipientID)
if err != nil {
if !errors.Is(err, pgx.ErrNoRows) {
o.logger.WarnContext(ctx, "wecom outbound: lookup member binding failed",
@@ -828,7 +853,6 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec
if o.senders == nil {
return false
}
- sender := o.senders.get(binding.InstallationID)
// Resolve slug for the link. Best-effort — a missing slug just falls
// back to the workspace UUID in the URL.
@@ -845,25 +869,107 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec
if content == "" {
return false
}
- // 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.
+
+ // awaitHolder is actingAgentBot and nothing else: only the agent-attributed
+ // attempt has a second route behind it, so only that one may wait to hear
+ // whether nobody took the frame. A member-authored notification has no
+ // fallback at all, and the fallback below has nothing behind it, so both
+ // keep the relay's non-blocking publish -- the wait happens on the request's
+ // own goroutine, and a verdict nobody can act on is not worth holding it for.
+ delivered, provenMiss := o.pushInbox(ctx, item, binding, recipientIDStr, content, actingAgentBot)
+ if delivered {
+ return true
+ }
+ // Only the preferred-and-agent-attributed bot needs a second route: a
+ // recipient-wide binding answering false has nowhere else to go, and a
+ // retry is owed only when the agent's bot provably delivered nothing.
+ if !provenMiss || !actingAgentBot {
+ return false
+ }
+
+ // The acting agent's bot could not have delivered, so fall back to the
+ // binding the recipient-wide lookup names — the route this notification
+ // took before the agent's own bot was preferred. A miss here is reported the
+ // way the old path reported it: no bot push, and the in-app inbox still
+ // carries the notification.
+ fallback, err := o.q.FindChannelBindingForMember(ctx, db.FindChannelBindingForMemberParams{
+ WorkspaceID: workspaceID,
+ MulticaUserID: recipientID,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ if !errors.Is(err, pgx.ErrNoRows) {
+ o.logger.WarnContext(ctx, "wecom outbound: fallback member binding lookup failed",
+ "error", err, "workspace_id", workspaceIDStr, "recipient_id", recipientIDStr)
+ }
+ return false
+ }
+ if fallback.InstallationID == binding.InstallationID {
+ // The recipient-wide answer names the same bot; sending again would only
+ // repeat the miss, not route around it.
+ return false
+ }
+ o.logger.DebugContext(ctx, "wecom outbound: inbox push falls back to the recipient-wide bot",
+ "agent_installation_id", uuidStringPub(binding.InstallationID),
+ "installation_id", uuidStringPub(fallback.InstallationID))
+ delivered, _ = o.pushInbox(ctx, item, fallback, recipientIDStr, content, false)
+ return delivered
+}
+
+// pushInbox attempts one delivery of an already-rendered inbox card through one
+// binding. provenMiss is true only when the attempt PROVES the card did not
+// reach WeCom at all — no live socket for the binding anywhere in the fleet, or
+// a send that failed before a byte could leave — which is the one case another
+// binding may be tried. A partial or uncertain send answers false, because the
+// card may already be in the member's chat and a retry would duplicate it.
+// awaitHolder asks the relay to report relayNoHolder, which costs the
+// acceptance window and is only worth paying where the caller has a second
+// route to try (see tryDeliverInbox). Everything else about the attempt is the
+// same either way.
+func (o *Outbound) pushInbox(ctx context.Context, item map[string]any, binding db.ChannelUserBinding, recipientIDStr, content string, awaitHolder bool) (delivered, provenMiss bool) {
+ sender := o.senders.get(binding.InstallationID)
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.routeFrame(relayFrame{
+ frame := relayFrame{
Kind: relayKindInbox,
InstallationID: util.UUIDToString(binding.InstallationID),
ChatID: binding.ChannelUserID,
ChatType: chatTypeSingleInt,
Content: content,
- }, relayInboxEventID(itemIDOf(item), recipientIDStr)) {
+ }
+ eventID := relayInboxEventID(itemIDOf(item), recipientIDStr, util.UUIDToString(binding.InstallationID))
+ var verdict relayPublish
+ if awaitHolder {
+ verdict = o.routeFrameAwaiting(ctx, frame, eventID)
+ } else {
+ verdict = o.routeFrame(frame, eventID)
+ }
+ switch verdict {
+ case relayAccepted:
o.logger.DebugContext(ctx, "wecom outbound: routed an inbox push to the replica holding the socket",
"installation_id", uuidStringPub(binding.InstallationID))
- return true
+ return true, false
+ case relayUncertain:
+ // The bus call failed, or the claim store could not answer. A
+ // frame that may have been accepted and may already be on its way
+ // to the member's chat must NOT be re-routed: a duplicate card is
+ // worse than a late one.
+ o.logger.WarnContext(ctx, "wecom outbound: inbox push routed but its acceptance is unknown; not re-routing",
+ "installation_id", uuidStringPub(binding.InstallationID),
+ "recipient_id", recipientIDStr)
+ return false, false
+ case relayNotWired, relayNoHolder:
+ // Proven not delivered; the shared warn and the proven-miss
+ // return below carry it out.
}
+ // relayNotWired (no relay attached) and relayNoHolder (the frame was
+ // published, but across the acceptance window no replica took the
+ // delivery claim, so nobody holds this bot's socket) both prove the
+ // push did not reach WeCom; the caller may offer it to the
+ // recipient-wide binding.
// 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
@@ -875,19 +981,110 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec
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
+ // No replica holds a socket for this bot, so the push provably did not
+ // reach WeCom and the caller may offer it to the recipient-wide binding.
+ return false, true
}
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),
"recipient_id", recipientIDStr)
- return false // send failed → no bot delivery
+ // Only a failure that proves nothing left the process may be tried on
+ // another bot; anything past the write may already be in the chat.
+ return false, provablyNotSent(err)
}
o.logger.DebugContext(ctx, "wecom outbound: inbox delivered via bot",
"installation_id", uuidStringPub(binding.InstallationID),
"recipient_id", recipientIDStr,
"inbox_type", item["type"])
- return true
+ return true, false
+}
+
+// memberBindingFor resolves which of the recipient's WeCom bots carries this
+// notification, and reports whether that bot is the acting agent's own.
+//
+// The recipient-wide lookup is deliberately no longer the only answer.
+// FindChannelBindingForMember keys on the RECIPIENT and on nothing else, so in
+// a multi-bot org — one bot per agent, one person bound to several of them —
+// the member reads every agent's activity through whichever bot they bound
+// most recently, and the bot↔agent mapping they set up disappears.
+// When the notification names an AGENT as its actor, the bot that agent owns
+// is the one the recipient talks to about that agent's work, so the agent's
+// bot is tried first, through the recipient's binding ON it.
+//
+// The recipient-wide lookup answers when the agent's bot has no binding for
+// this member (and always for a member-authored notification, which names no
+// agent). tryDeliverInbox additionally re-tries the recipient-wide binding when
+// the agent's bot provably delivered nothing, so preferring the agent's bot
+// narrows WHERE a push is carried rather than WHETHER it is carried.
+func (o *Outbound) memberBindingFor(ctx context.Context, item map[string]any, workspaceID, recipientID pgtype.UUID) (db.ChannelUserBinding, bool, error) {
+ if agentID, ok := inboxActorAgent(item); ok {
+ binding, err := o.q.FindChannelBindingForMemberOnAgentInstallation(ctx, db.FindChannelBindingForMemberOnAgentInstallationParams{
+ WorkspaceID: workspaceID,
+ MulticaUserID: recipientID,
+ ChannelType: channelTypeWecom,
+ AgentID: agentID,
+ })
+ switch {
+ case err == nil:
+ o.logger.DebugContext(ctx, "wecom outbound: inbox push follows the acting agent's bot",
+ "agent_id", uuidStringPub(agentID),
+ "installation_id", uuidStringPub(binding.InstallationID))
+ return binding, true, nil
+ case !errors.Is(err, pgx.ErrNoRows):
+ // A read failure must not silence a notification the fallback can
+ // still deliver: the fallback's own error is the one the caller
+ // reports and counts, and it is the same query the old path made.
+ o.logger.WarnContext(ctx, "wecom outbound: agent-bot binding lookup failed",
+ "error", err, "agent_id", uuidStringPub(agentID))
+ }
+ }
+ binding, err := o.q.FindChannelBindingForMember(ctx, db.FindChannelBindingForMemberParams{
+ WorkspaceID: workspaceID,
+ MulticaUserID: recipientID,
+ ChannelType: channelTypeWecom,
+ })
+ return binding, false, err
+}
+
+// inboxActorAgent reads the agent an inbox notification names as its actor,
+// when it names one. The payload is the map inboxItemToResponse builds, whose
+// actor fields are pointers (util.TextToPtr / util.UUIDToPtr) and nil for a
+// notification a member authored. Both spellings are accepted, the same
+// defensive shape itemIDOf uses, so a payload that was re-encoded on its way
+// here reads like a native one.
+func inboxActorAgent(item map[string]any) (pgtype.UUID, bool) {
+ if inboxStringField(item["actor_type"]) != "agent" {
+ return pgtype.UUID{}, false
+ }
+ id := inboxStringField(item["actor_id"])
+ if id == "" {
+ return pgtype.UUID{}, false
+ }
+ agentID, err := util.ParseUUID(id)
+ if err != nil || !agentID.Valid {
+ return pgtype.UUID{}, false
+ }
+ return agentID, true
+}
+
+// inboxStringField reads one payload string that may arrive plain or behind a
+// pointer — which is how the two publishers of an inbox item spell the actor
+// fields. Anything else, including a nil pointer, reads as absent.
+func inboxStringField(v any) string {
+ switch s := v.(type) {
+ case string:
+ return s
+ case *string:
+ if s != nil {
+ return *s
+ }
+ case pgtype.Text:
+ if s.Valid {
+ return s.String
+ }
+ }
+ return ""
}
// uuidStringPub renders a pgtype.UUID for a log line without depending on
diff --git a/server/internal/integrations/wecom/outbound_inbox_relay_db_test.go b/server/internal/integrations/wecom/outbound_inbox_relay_db_test.go
new file mode 100644
index 0000000000..57c2eabb76
--- /dev/null
+++ b/server/internal/integrations/wecom/outbound_inbox_relay_db_test.go
@@ -0,0 +1,202 @@
+package wecom
+
+// outbound_inbox_relay_db_test.go — an inbox push offered to two bots, across
+// two replicas.
+//
+// The first review round fixed the LOCAL half of the fallback: an inbox push
+// whose preferred (acting agent's) bot provably delivered nothing is offered
+// to the recipient-wide bot instead. What the second round found is that the
+// RELAY half of that decision was still a bool, so the two cases that matter
+// most were indistinguishable from the outside:
+//
+//
+// 1. The actor's bot is offline while the relay IS wired. A successful publish
+// only proves the frame was ENQUEUED. If no replica holds that bot's socket,
+// every dispatcher discards the frame, but the push reported success and
+// never tried the online recipient-wide bot: the notification was dropped
+// silently.
+//
+// 2. A publish call that returns an error. The frame may already have been
+// accepted and delivered, with only the RESPONSE lost; falling back there
+// puts a second card in the member's chat.
+//
+// These run against a real database with the same fanoutRelay / sharedDedupe /
+// newRelayReplica rig the reply-path tests use, so the acceptance window and
+// the claim fence are exercised for real. They skip when no migrated database
+// is reachable.
+
+import (
+ "context"
+ "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"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+const (
+ inboxRelayWS = "7d1a0000-0000-4000-8000-000000000001"
+ inboxRelayUser = "7d1a0000-0000-4000-8000-000000000002"
+ inboxRelayAgentA = "7d1a0000-0000-4000-8000-000000000003"
+ inboxRelayAgentB = "7d1a0000-0000-4000-8000-000000000004"
+ inboxRelayInstA = "7d1a0000-0000-4000-8000-000000000005"
+ inboxRelayInstB = "7d1a0000-0000-4000-8000-000000000006"
+
+ // The anonymized userids the two bots address the same member by.
+ inboxRelayChatA = "TBOT_A_MEMBER"
+ inboxRelayChatB = "TBOT_B_MEMBER"
+)
+
+// inboxRelayFixture is one workspace where a member is bound on two bots: the
+// acting agent's (A) and a second one (B) they bound more recently.
+type inboxRelayFixture struct {
+ workspaceID string
+ recipientID string
+ actingAgent string
+ actorInst string
+ fallbackInst string
+}
+
+func seedInboxRelayFixture(t *testing.T, pool *pgxpool.Pool) inboxRelayFixture {
+ t.Helper()
+ ctx := context.Background()
+ clean := func() {
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_user_binding WHERE workspace_id = $1`, inboxRelayWS)
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE workspace_id = $1`, inboxRelayWS)
+ _, _ = pool.Exec(ctx, `DELETE FROM agent WHERE workspace_id = $1`, inboxRelayWS)
+ _, _ = pool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, inboxRelayUser)
+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, inboxRelayWS)
+ }
+ clean()
+ t.Cleanup(clean)
+ exec := func(sql string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, sql, args...); err != nil {
+ t.Fatalf("seed inbox relay fixture: %v", err)
+ }
+ }
+ exec(`INSERT INTO workspace (id, name, slug) VALUES ($1, $2, $3)`,
+ inboxRelayWS, "inbox relay", "inbox-relay")
+ exec(`INSERT INTO "user" (id, name, email) VALUES ($1, $2, $3)`,
+ inboxRelayUser, "Inbox Recipient", "[email protected]")
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode) VALUES ($1, $2, $3, 'local')`,
+ inboxRelayAgentA, inboxRelayWS, "inbox-agent-a")
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode) VALUES ($1, $2, $3, 'local')`,
+ inboxRelayAgentB, inboxRelayWS, "inbox-agent-b")
+ exec(`INSERT INTO channel_installation
+ (id, workspace_id, agent_id, channel_type, status, installer_user_id)
+ VALUES ($1, $2, $3, 'wecom', 'active', $4)`,
+ inboxRelayInstA, inboxRelayWS, inboxRelayAgentA, inboxRelayUser)
+ exec(`INSERT INTO channel_installation
+ (id, workspace_id, agent_id, channel_type, status, installer_user_id)
+ VALUES ($1, $2, $3, 'wecom', 'active', $4)`,
+ inboxRelayInstB, inboxRelayWS, inboxRelayAgentB, inboxRelayUser)
+ // B is bound LAST, so the recipient-wide lookup answers B. That is the
+ // fallback route, and it is deliberately a different bot from A.
+ exec(`INSERT INTO channel_user_binding
+ (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id, bound_at)
+ VALUES ($1, $2, $3, 'wecom', $4, now() - interval '1 hour')`,
+ inboxRelayWS, inboxRelayUser, inboxRelayInstA, inboxRelayChatA)
+ exec(`INSERT INTO channel_user_binding
+ (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id, bound_at)
+ VALUES ($1, $2, $3, 'wecom', $4, now())`,
+ inboxRelayWS, inboxRelayUser, inboxRelayInstB, inboxRelayChatB)
+ return inboxRelayFixture{
+ workspaceID: inboxRelayWS,
+ recipientID: inboxRelayUser,
+ actingAgent: inboxRelayAgentA,
+ actorInst: inboxRelayInstA,
+ fallbackInst: inboxRelayInstB,
+ }
+}
+
+// inboxRelayEvent is one issue-comment notification as the listeners publish
+// it: a member recipient, and agent A as the actor whose bot should carry it.
+func inboxRelayEvent(fx inboxRelayFixture, itemID string) events.Event {
+ return events.Event{
+ Type: protocol.EventInboxNew,
+ Payload: map[string]any{
+ "item": map[string]any{
+ "id": itemID,
+ "type": "new_comment",
+ "title": "An issue",
+ "recipient_type": "member",
+ "recipient_id": fx.recipientID,
+ "workspace_id": fx.workspaceID,
+ "actor_type": util.TextToPtr(pgtype.Text{String: "agent", Valid: true}),
+ "actor_id": util.UUIDToPtr(mustUUID(fx.actingAgent)),
+ },
+ },
+ }
+}
+
+// TestInboxRelay_NoReplicaHoldsTheActorsBotFallsBack is finding 1: the actor's
+// bot is offline while the relay is wired, so the publish is accepted by the
+// bus and claimed by nobody. The push must fall back to the recipient-wide bot
+// — and exactly one card must reach the member.
+func TestInboxRelay_NoReplicaHoldsTheActorsBotFallsBack(t *testing.T) {
+ pool := twoReplicaDB(t)
+ fx := seedInboxRelayFixture(t, pool)
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ cfg := RelayConfig{AcceptanceWindow: 200 * time.Millisecond}
+
+ // This replica served the inbox event and holds NO socket; the other holds
+ // only the recipient-wide bot's socket, never the acting agent's.
+ publisher := newRelayReplicaWith(t, pool, fx.actorInst, false, relay, dedupe, cfg)
+ holder := newRelayReplicaWith(t, pool, fx.fallbackInst, true, relay, dedupe, cfg)
+
+ publisher.bus.Publish(inboxRelayEvent(fx, "inbox-no-holder"))
+
+ waitFor(t, "the recipient-wide bot to carry the card", func() bool { return holder.frames() == 1 })
+ if body := holder.conn.sendBody(t, 0); body["chatid"] != inboxRelayChatB {
+ t.Errorf("card chatid = %v, want the recipient-wide bot's userid %s", body["chatid"], inboxRelayChatB)
+ }
+ if n := publisher.frames(); n != 0 {
+ t.Errorf("the publisher's empty registry carried %d cards, want 0", n)
+ }
+ if got := relay.publishedTo(fx.actorInst); got != 1 {
+ t.Errorf("the acting agent's bot was offered %d frames, want 1 (the accepted, unclaimed one)", got)
+ }
+ if got := relay.publishedTo(fx.fallbackInst); got != 1 {
+ t.Errorf("the recipient-wide bot was offered %d frames, want 1", got)
+ }
+ // The unclaimed claim is FENCED under the publisher's own token, so a
+ // dispatcher that shows up late cannot deliver a duplicate.
+ key := dedupeKey(relayInboxEventID("inbox-no-holder", fx.recipientID, fx.actorInst))
+ if v := dedupe.valueOf(key); v == "" || v == claimSettledValue || v == claimLostValue {
+ t.Errorf("the unclaimed acting-agent claim holds %q, want a fencing token", v)
+ }
+}
+
+// TestInboxRelay_UncertainPublishDoesNotFallBack is finding 2: publish reports
+// failure AFTER the frame was fanned out (the response was lost). The card is
+// on its way through the actor's bot, so the recipient-wide bot must NOT be
+// tried — one card, not two.
+func TestInboxRelay_UncertainPublishDoesNotFallBack(t *testing.T) {
+ pool := twoReplicaDB(t)
+ fx := seedInboxRelayFixture(t, pool)
+ relay, dedupe := &fanoutRelay{failAfterFanout: true}, newSharedDedupe()
+ cfg := RelayConfig{AcceptanceWindow: 200 * time.Millisecond}
+
+ publisher := newRelayReplicaWith(t, pool, fx.actorInst, false, relay, dedupe, cfg)
+ holder := newRelayReplicaWith(t, pool, fx.actorInst, true, relay, dedupe, cfg)
+
+ publisher.bus.Publish(inboxRelayEvent(fx, "inbox-lost-response"))
+
+ waitFor(t, "the acting agent's bot to carry the card", func() bool { return holder.frames() == 1 })
+ if body := holder.conn.sendBody(t, 0); body["chatid"] != inboxRelayChatA {
+ t.Errorf("card chatid = %v, want the acting agent's bot %s", body["chatid"], inboxRelayChatA)
+ }
+ // Give a wrong fallback room to land before asserting its absence.
+ time.Sleep(100 * time.Millisecond)
+ if n := holder.frames(); n != 1 {
+ t.Errorf("the member received %d cards, want exactly 1: an uncertain publish must not be re-routed", n)
+ }
+ if got := relay.publishedTo(fx.fallbackInst); got != 0 {
+ t.Errorf("the recipient-wide bot was offered %d frames after an uncertain publish, want 0", got)
+ }
+}
diff --git a/server/internal/integrations/wecom/outbound_inbox_wait_test.go b/server/internal/integrations/wecom/outbound_inbox_wait_test.go
new file mode 100644
index 0000000000..624eeb7fa6
--- /dev/null
+++ b/server/internal/integrations/wecom/outbound_inbox_wait_test.go
@@ -0,0 +1,134 @@
+package wecom
+
+// outbound_inbox_wait_test.go — WHERE the acceptance window is paid.
+//
+// Bus delivery is synchronous on the caller's goroutine, and the publisher of
+// an inbox:new is the HTTP request that created the comment. Only one replica
+// holds a given bot's socket, so the confirmation wait is the common path in a
+// multi-replica deployment. It is worth paying only where the answer can be
+// acted on: the agent-attributed attempt, which has the recipient-wide bot
+// behind it. These pin that, with the real relay and claim store and the
+// production default window, so a regression that spends 2s where the verdict
+// is discarded cannot hide behind a 40ms test window.
+
+import (
+ "context"
+ "log/slog"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ inboxWaitAgentInst = "aaaaaaaa-1111-1111-1111-111111111111"
+ inboxWaitFallbackInst = "bbbbbbbb-2222-2222-2222-222222222222"
+ inboxWaitAgentID = "55555555-5555-5555-5555-555555555555"
+)
+
+// inboxWaitRig wires one Outbound to a real relay with nothing holding either
+// bot's socket here, which is the multi-replica shape: the replica serving the
+// request is not the one holding the socket.
+type inboxWaitRig struct {
+ outbound *Outbound
+ relay *fanoutRelay
+ dedupe *sharedDedupe
+ queries *fakeOutboundQueries
+}
+
+func newInboxWaitRig(t *testing.T, window time.Duration) inboxWaitRig {
+ t.Helper()
+ q := &fakeOutboundQueries{workspace: db.Workspace{Slug: "acme"}}
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ router := NewRelayOutbound(relay, dedupe, RelayConfig{AcceptanceWindow: window}, slog.Default())
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { cancel(); router.Wait() })
+ router.Start(ctx)
+
+ o := NewOutbound(q, newSendersRegistry(), nil, slog.Default(), WithRelay(router))
+ router.Attach(o)
+ relay.register(router)
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_BOT", InstallationID: mustUUID(inboxWaitAgentInst)}
+ q.memberBinding = db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT", InstallationID: mustUUID(inboxWaitFallbackInst)}
+ return inboxWaitRig{outbound: o, relay: relay, dedupe: dedupe, queries: q}
+}
+
+func (r inboxWaitRig) deliver(ctx context.Context, item map[string]any) (bool, time.Duration) {
+ start := time.Now()
+ got := r.outbound.tryDeliverInbox(ctx, item,
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444")
+ return got, time.Since(start)
+}
+
+// TestTryDeliverInbox_MemberAuthoredPushDoesNotWaitForTheAcceptanceWindow: a
+// member-authored notification has no second route, so the verdict is thrown
+// away by construction. It must not be paid for -- this is the 2s the review
+// measured on the request that created the comment.
+func TestTryDeliverInbox_MemberAuthoredPushDoesNotWaitForTheAcceptanceWindow(t *testing.T) {
+ t.Parallel()
+ // The production default: cmd/server does not set AcceptanceWindow.
+ rig := newInboxWaitRig(t, 2*time.Second)
+ item := agentInboxItem("new_comment", inboxWaitAgentID)
+ item["actor_type"] = util.TextToPtr(pgtype.Text{String: "member", Valid: true})
+
+ got, elapsed := rig.deliver(context.Background(), item)
+ if elapsed > 300*time.Millisecond {
+ t.Fatalf("a member-authored push blocked %v; a verdict with no fallback behind it must not be waited for", elapsed)
+ }
+ if !got {
+ t.Error("tryDeliverInbox = false; the bus took the frame and there is no second route to report a miss to")
+ }
+ if n := rig.dedupe.claimStateCount(); n != 0 {
+ t.Errorf("the claim was polled %d times; a member-authored push must not enter the acceptance window", n)
+ }
+}
+
+// TestTryDeliverInbox_WaitIsBoundedByTheCallersDeadline: the wait runs on the
+// request's goroutine, so the caller's budget has to cap it. A 3s window with a
+// 150ms caller must come back in the caller's time, not the window's.
+func TestTryDeliverInbox_WaitIsBoundedByTheCallersDeadline(t *testing.T) {
+ t.Parallel()
+ rig := newInboxWaitRig(t, 3*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
+ defer cancel()
+
+ got, elapsed := rig.deliver(ctx, agentInboxItem("new_comment", inboxWaitAgentID))
+ if elapsed > 900*time.Millisecond {
+ t.Fatalf("the push blocked %v with a 150ms caller budget; the caller's ctx must cap the window", elapsed)
+ }
+ if got {
+ t.Error("tryDeliverInbox = true; a caller that ran out of time confirmed nothing")
+ }
+}
+
+// TestTryDeliverInbox_FallbackAttemptDoesNotWaitAgain: the fallback is the last
+// route, so a no-holder verdict for it changes nothing. It must publish and
+// return, leaving the cost at exactly one window rather than two.
+func TestTryDeliverInbox_FallbackAttemptDoesNotWaitAgain(t *testing.T) {
+ t.Parallel()
+ // Small enough to keep the test quick, big enough that one window is
+ // several polls and two windows would be unmistakable.
+ rig := newInboxWaitRig(t, 400*time.Millisecond)
+
+ got, elapsed := rig.deliver(context.Background(), agentInboxItem("new_comment", inboxWaitAgentID))
+ if !got {
+ t.Error("tryDeliverInbox = false; the fallback publish was accepted and had no route behind it")
+ }
+ if elapsed > 2*time.Second {
+ t.Fatalf("the push took %v for a 400ms window; the fallback must not wait again", elapsed)
+ }
+ // One window at step = window/8 is about nine polls; two would be about
+ // eighteen. The bound sits between them.
+ if n := rig.dedupe.claimStateCount(); n > 12 {
+ t.Errorf("the claim was polled %d times; the fallback attempt paid a second acceptance window", n)
+ }
+ if n := rig.relay.publishedTo(inboxWaitFallbackInst); n != 1 {
+ t.Errorf("the recipient-wide bot was offered %d frames, want 1", n)
+ }
+ if n := rig.relay.publishedTo(inboxWaitAgentInst); n != 1 {
+ t.Errorf("the acting agent's bot was offered %d frames, want 1", n)
+ }
+}
diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.go
index 5abda51bee..9d8e9242a1 100644
--- a/server/internal/integrations/wecom/outbound_test.go
+++ b/server/internal/integrations/wecom/outbound_test.go
@@ -16,6 +16,7 @@ import (
"log/slog"
"sync/atomic"
"testing"
+ "time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -49,10 +50,20 @@ type fakeOutboundQueries struct {
installErr error
memberBinding db.ChannelUserBinding
memberErr error
- workspace db.Workspace
- workspaceErr error
- attachments []db.Attachment
- attachmentsErr error
+ // agentMemberBinding / agentMemberErr answer the agent-pinned member
+ // lookup, the one that makes a notification follow the bot↔agent mapping in
+ // a multi-bot org. An unset binding with no error is pgx.ErrNoRows — the bot
+ // this member never bound — which is what every test written before that
+ // lookup expects when it does not mention one. agentBindingAsked records the
+ // agent each lookup was made for, so a test can ask whether the acting
+ // agent's bot was consulted at all.
+ agentMemberBinding db.ChannelUserBinding
+ agentMemberErr error
+ agentBindingAsked []pgtype.UUID
+ workspace db.Workspace
+ workspaceErr error
+ attachments []db.Attachment
+ attachmentsErr error
// lookupGate holds every attachment lookup open until it is closed, which
// is what a slow database looks like from in here. lookupsEntered counts
// the arrivals, so a test can ask how many deliveries got as far as the
@@ -226,6 +237,21 @@ func (f *fakeOutboundQueries) GetChannelInstallation(context.Context, db.GetChan
func (f *fakeOutboundQueries) FindChannelBindingForMember(context.Context, db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error) {
return f.memberBinding, f.memberErr
}
+
+// FindChannelBindingForMemberOnAgentInstallation answers only when the rig
+// filed a binding on the agent's own bot. Production's answer for a bot this
+// member never bound is pgx.ErrNoRows, and handing back a row for every agent
+// would let a test pass that never said which bots the member is on.
+func (f *fakeOutboundQueries) FindChannelBindingForMemberOnAgentInstallation(_ context.Context, arg db.FindChannelBindingForMemberOnAgentInstallationParams) (db.ChannelUserBinding, error) {
+ f.agentBindingAsked = append(f.agentBindingAsked, arg.AgentID)
+ if f.agentMemberErr != nil {
+ return db.ChannelUserBinding{}, f.agentMemberErr
+ }
+ if !f.agentMemberBinding.InstallationID.Valid {
+ return db.ChannelUserBinding{}, pgx.ErrNoRows
+ }
+ return f.agentMemberBinding, nil
+}
func (f *fakeOutboundQueries) GetWorkspace(context.Context, pgtype.UUID) (db.Workspace, error) {
return f.workspace, f.workspaceErr
}
@@ -522,6 +548,382 @@ func TestTryDeliverInbox_NoBindingIsNoop(t *testing.T) {
}
}
+// The multi-bot rule: a notification about one agent's work is
+// pushed through THAT agent's bot, not through whichever bot the recipient
+// happens to have bound most recently. The recipient-wide answer here names a
+// different bot on purpose — delivering through the other one is the whole
+// assertion.
+func TestTryDeliverInbox_FollowsTheActingAgentsBot(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{
+ // What FindChannelBindingForMember answers: some other agent's bot.
+ memberBinding: db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT"},
+ workspace: db.Workspace{Slug: "acme"},
+ }
+ o, instID, conn := newOutboundWithConn(t, q)
+ // The member IS on the acting agent's bot, which is the socket this rig
+ // holds.
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_A_BOT", InstallationID: instID}
+ agentID := "55555555-5555-5555-5555-555555555555"
+
+ if !o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", agentID),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Fatal("tryDeliverInbox returned false; the member is bound on the acting agent's bot")
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "T_AGENT_A_BOT" {
+ t.Errorf("inbox push chatid = %v, want the acting agent's bot", body["chatid"])
+ }
+ if len(q.agentBindingAsked) != 1 || util.UUIDToString(q.agentBindingAsked[0]) != agentID {
+ t.Errorf("agent-pinned lookup asked for %v, want exactly [%s]", q.agentBindingAsked, agentID)
+ }
+}
+
+// The fallback: the agent that acted has no bot this member linked, so the
+// notification still goes out through the bot the recipient-wide lookup names.
+// Without this, preferring the agent's bot would silently drop notifications
+// for every agent the recipient never bound.
+func TestTryDeliverInbox_FallsBackWhenTheActingAgentsBotIsUnbound(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{
+ memberBinding: db.ChannelUserBinding{ChannelUserID: "T_USER_1"},
+ workspace: db.Workspace{Slug: "acme"},
+ }
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.memberBinding.InstallationID = instID
+
+ if !o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", "55555555-5555-5555-5555-555555555555"),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Fatal("tryDeliverInbox returned false; the recipient-wide binding should still deliver")
+ }
+ if body := conn.sendBody(t, 0); body["chatid"] != "T_USER_1" {
+ t.Errorf("inbox push chatid = %v, want the recipient's own bot", body["chatid"])
+ }
+ if len(q.agentBindingAsked) != 1 {
+ t.Errorf("agent-pinned lookup asked %d times, want 1 before the fallback", len(q.agentBindingAsked))
+ }
+}
+
+// A notification a member authored names no agent, so there is nothing to
+// attribute: the recipient-wide answer stands and the agent-pinned lookup is
+// never issued (a member is not an agent id, and asking would be meaningless).
+func TestTryDeliverInbox_MemberAuthoredNotificationKeepsTheRecipientWideAnswer(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{
+ memberBinding: db.ChannelUserBinding{ChannelUserID: "T_USER_1"},
+ workspace: db.Workspace{Slug: "acme"},
+ }
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.memberBinding.InstallationID = instID
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_BOT", InstallationID: instID}
+
+ item := agentInboxItem("new_comment", "55555555-5555-5555-5555-555555555555")
+ item["actor_type"] = util.TextToPtr(pgtype.Text{String: "member", Valid: true})
+ if !o.tryDeliverInbox(context.Background(), item,
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Fatal("tryDeliverInbox returned false; the member has a binding")
+ }
+ if body := conn.sendBody(t, 0); body["chatid"] != "T_USER_1" {
+ t.Errorf("inbox push chatid = %v, want the recipient-wide answer", body["chatid"])
+ }
+ if len(q.agentBindingAsked) != 0 {
+ t.Errorf("agent-pinned lookup issued for a member-authored notification: %v", q.agentBindingAsked)
+ }
+}
+
+// A failed agent-pinned read must not silence a notification the fallback can
+// still deliver.
+func TestTryDeliverInbox_AgentBotLookupFailureFallsBack(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{
+ memberBinding: db.ChannelUserBinding{ChannelUserID: "T_USER_1"},
+ agentMemberErr: errors.New("connection reset"),
+ workspace: db.Workspace{Slug: "acme"},
+ }
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.memberBinding.InstallationID = instID
+
+ if !o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", "55555555-5555-5555-5555-555555555555"),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Fatal("tryDeliverInbox returned false; a failed agent-bot read must fall back")
+ }
+ if body := conn.sendBody(t, 0); body["chatid"] != "T_USER_1" {
+ t.Errorf("inbox push chatid = %v, want the fallback bot", body["chatid"])
+ }
+}
+
+// The other half of the multi-bot rule. Preferring the acting agent's bot must
+// not make a notification LESS deliverable than the recipient-wide route was:
+// when agent A's bot has no live socket anywhere in the fleet, the push has to
+// fall back to the bot the recipient-wide lookup names — the same route that
+// carried this notification before the agent's bot was preferred.
+func TestTryDeliverInbox_FallsBackWhenTheActingAgentsBotHasNoLiveSender(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{workspace: db.Workspace{Slug: "acme"}}
+ agentInstID := mustUUID("aaaaaaaa-1111-1111-1111-111111111111") // registered nowhere: no socket on any replica
+ fallbackInstID := mustUUID("bbbbbbbb-2222-2222-2222-222222222222")
+ reg := newSendersRegistry()
+ conn := &recordingConn{}
+ reg.set(fallbackInstID, conn.autoAck(newWSSender(conn, nil)))
+ o := NewOutbound(q, reg, nil, slog.Default())
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_A_BOT", InstallationID: agentInstID}
+ q.memberBinding = db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT", InstallationID: fallbackInstID}
+
+ if !o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", "55555555-5555-5555-5555-555555555555"),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Fatal("tryDeliverInbox returned false; the recipient-wide binding still has a live socket")
+ }
+ if body := conn.sendBody(t, 0); body["chatid"] != "T_LATEST_BOT" {
+ t.Errorf("inbox push chatid = %v, want the recipient-wide bot", body["chatid"])
+ }
+}
+
+// A registered socket that refuses the write deadline is a second shape of the
+// same proof: SetWriteDeadline runs before WriteMessage, so nothing could have
+// reached the wire, and the recipient-wide bot is still owed the push.
+func TestTryDeliverInbox_FallsBackWhenTheActingAgentsBotWriteIsRefused(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{workspace: db.Workspace{Slug: "acme"}}
+ agentInstID := mustUUID("aaaaaaaa-1111-1111-1111-111111111111")
+ fallbackInstID := mustUUID("bbbbbbbb-2222-2222-2222-222222222222")
+ reg := newSendersRegistry()
+ // Agent A's socket is up, but it will not accept a frame.
+ refusing := &deadlineRefusingConn{recordingConn: &recordingConn{}}
+ reg.set(agentInstID, refusing.recordingConn.autoAck(newWSSender(refusing, nil)))
+ conn := &recordingConn{}
+ reg.set(fallbackInstID, conn.autoAck(newWSSender(conn, nil)))
+ o := NewOutbound(q, reg, nil, slog.Default())
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_A_BOT", InstallationID: agentInstID}
+ q.memberBinding = db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT", InstallationID: fallbackInstID}
+
+ if !o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", "55555555-5555-5555-5555-555555555555"),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Fatal("tryDeliverInbox returned false; a refused write is provably undelivered and must fall back")
+ }
+ if body := conn.sendBody(t, 0); body["chatid"] != "T_LATEST_BOT" {
+ t.Errorf("inbox push chatid = %v, want the recipient-wide bot", body["chatid"])
+ }
+}
+
+// The flip side of the fallback: a send whose fate is UNKNOWN — here, the
+// verdict never came back — may already be in the member's chat, so the
+// recipient-wide bot is deliberately NOT tried. Duplicating the card is worse
+// than a late one.
+func TestTryDeliverInbox_DoesNotFallBackOnAnUncertainSend(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{workspace: db.Workspace{Slug: "acme"}}
+ agentInstID := mustUUID("aaaaaaaa-1111-1111-1111-111111111111")
+ fallbackInstID := mustUUID("bbbbbbbb-2222-2222-2222-222222222222")
+ reg := newSendersRegistry()
+ agentConn := &recordingConn{swallowAckFromSend: 1}
+ agentSender := newWSSender(agentConn, nil)
+ agentSender.ackTimeout = 50 * time.Millisecond
+ reg.set(agentInstID, agentConn.autoAck(agentSender))
+ fallbackConn := &recordingConn{}
+ reg.set(fallbackInstID, fallbackConn.autoAck(newWSSender(fallbackConn, nil)))
+ o := NewOutbound(q, reg, nil, slog.Default())
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_A_BOT", InstallationID: agentInstID}
+ q.memberBinding = db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT", InstallationID: fallbackInstID}
+
+ if o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", "55555555-5555-5555-5555-555555555555"),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Error("tryDeliverInbox returned true for a send whose verdict never came back")
+ }
+ if frames := fallbackConn.sendFrames(); len(frames) != 0 {
+ t.Errorf("the recipient-wide bot was tried after an uncertain send: %d frames", len(frames))
+ }
+}
+
+// TestTryDeliverInbox_TriStateRelayMapping pins what each relay verdict means
+// to the fallback decision. Only a verdict that PROVES the card did not reach
+// WeCom may be re-routed: relayNotWired (no relay attached) and relayNoHolder
+// (published, but no replica ever took the delivery claim). relayAccepted is a
+// delivery; relayUncertain may already be one, so it must stay put.
+func TestTryDeliverInbox_TriStateRelayMapping(t *testing.T) {
+ t.Parallel()
+ const agentID = "55555555-5555-5555-5555-555555555555"
+ for _, tc := range []struct {
+ name string
+ state relayPublish
+ wantDelivered bool
+ wantFallback int
+ }{
+ {"accepted is a delivery", relayAccepted, true, 0},
+ {"uncertain is not re-routed", relayUncertain, false, 0},
+ {"no holder falls back", relayNoHolder, true, 1},
+ {"no relay falls back", relayNotWired, true, 1},
+ } {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{workspace: db.Workspace{Slug: "acme"}}
+ agentInstID := mustUUID("aaaaaaaa-1111-1111-1111-111111111111") // no socket here
+ fallbackInstID := mustUUID("bbbbbbbb-2222-2222-2222-222222222222")
+ reg := newSendersRegistry()
+ conn := &recordingConn{}
+ reg.set(fallbackInstID, conn.autoAck(newWSSender(conn, nil)))
+ relay := &scriptedRelay{state: tc.state}
+ o := NewOutbound(q, reg, nil, slog.Default(), WithRelay(relay))
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_A_BOT", InstallationID: agentInstID}
+ q.memberBinding = db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT", InstallationID: fallbackInstID}
+
+ got := o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", agentID),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444")
+ if got != tc.wantDelivered {
+ t.Errorf("tryDeliverInbox = %v, want %v", got, tc.wantDelivered)
+ }
+ if n := len(conn.sendFrames()); n != tc.wantFallback {
+ t.Errorf("the recipient-wide bot was sent %d cards, want %d", n, tc.wantFallback)
+ }
+ })
+ }
+}
+
+// TestTryDeliverInbox_OnlyTheAttemptWithASecondRouteWaits pins the split the
+// latency tests are about: the relay is asked to WAIT for a verdict only on the
+// agent-attributed attempt, because only that one has the recipient-wide bot
+// behind it. A member-authored push has no fallback at all, and the fallback
+// attempt has nothing behind it, so neither may hold the request's goroutine.
+func TestTryDeliverInbox_OnlyTheAttemptWithASecondRouteWaits(t *testing.T) {
+ t.Parallel()
+ agentInstID := mustUUID("aaaaaaaa-1111-1111-1111-111111111111")
+ fallbackInstID := mustUUID("bbbbbbbb-2222-2222-2222-222222222222")
+ const agentID = "55555555-5555-5555-5555-555555555555"
+
+ // Agent-authored, neither bot reachable here: the agent attempt waits (and
+ // misses), then the fallback attempt runs -- and must not wait again.
+ t.Run("agent attributed", func(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{workspace: db.Workspace{Slug: "acme"}}
+ relay := &scriptedRelay{state: relayNoHolder}
+ o := NewOutbound(q, newSendersRegistry(), nil, slog.Default(), WithRelay(relay))
+ q.agentMemberBinding = db.ChannelUserBinding{ChannelUserID: "T_AGENT_BOT", InstallationID: agentInstID}
+ q.memberBinding = db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT", InstallationID: fallbackInstID}
+
+ if o.tryDeliverInbox(context.Background(), agentInboxItem("new_comment", agentID),
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Error("tryDeliverInbox = true; neither bot is reachable and no verdict was a delivery")
+ }
+ if len(relay.awaited) != 2 || !relay.awaited[0] || relay.awaited[1] {
+ t.Errorf("awaited = %v, want the agent attempt to wait and the fallback attempt not to", relay.awaited)
+ }
+ })
+
+ // Member-authored: the recipient-wide binding is the only route, so the one
+ // attempt must not wait for a verdict nothing could act on.
+ t.Run("member authored", func(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{workspace: db.Workspace{Slug: "acme"}}
+ relay := &scriptedRelay{state: relayNoHolder}
+ o := NewOutbound(q, newSendersRegistry(), nil, slog.Default(), WithRelay(relay))
+ q.memberBinding = db.ChannelUserBinding{ChannelUserID: "T_LATEST_BOT", InstallationID: fallbackInstID}
+
+ item := agentInboxItem("new_comment", agentID)
+ item["actor_type"] = util.TextToPtr(pgtype.Text{String: "member", Valid: true})
+ if o.tryDeliverInbox(context.Background(), item,
+ "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Error("tryDeliverInbox = true; the only bot is unreachable")
+ }
+ if len(relay.awaited) != 1 || relay.awaited[0] {
+ t.Errorf("awaited = %v, want the single member-authored attempt not to wait", relay.awaited)
+ }
+ })
+}
+
+// scriptedRelay is the router seam with a canned verdict, so the tri-state
+// mapping in pushInbox can be pinned without a bus or a claim store.
+type scriptedRelay struct {
+ state relayPublish
+ // awaited records whether the attempt that produced the verdict asked the
+ // relay to WAIT for it. Only the agent-attributed attempt may, which is the
+ // distinction the latency tests are about.
+ awaited []bool
+ frames []relayFrame
+}
+
+func (r *scriptedRelay) publish(f relayFrame, _ string) relayPublish {
+ r.frames = append(r.frames, f)
+ r.awaited = append(r.awaited, false)
+ return r.state
+}
+
+func (r *scriptedRelay) publishAwaitingHolder(_ context.Context, f relayFrame, _ string) relayPublish {
+ r.frames = append(r.frames, f)
+ r.awaited = append(r.awaited, true)
+ return r.state
+}
+
+// deadlineRefusingConn is a socket whose write deadline cannot be set, which is
+// the one write failure raised before WriteMessage is entered (ws_sender.go's
+// writeLocked). It is the "provably nothing left this process" case the
+// fallback is owed for.
+type deadlineRefusingConn struct {
+ *recordingConn
+}
+
+func (c *deadlineRefusingConn) SetWriteDeadline(time.Time) error {
+ return errors.New("write deadline refused")
+}
+
+// inboxActorAgent reads the payload the way both publishers spell it, and
+// answers "no agent" for everything else — an actor that is a member, a
+// missing field, a nil pointer, or an id that is not a UUID.
+func TestInboxActorAgent(t *testing.T) {
+ t.Parallel()
+ agentID := "55555555-5555-5555-5555-555555555555"
+ for _, tc := range []struct {
+ name string
+ item map[string]any
+ want string
+ }{
+ {name: "pointer fields, as published", item: agentInboxItem("new_comment", agentID), want: agentID},
+ {name: "plain fields, as re-encoded", want: agentID, item: map[string]any{
+ "actor_type": "agent", "actor_id": agentID,
+ }},
+ {name: "member actor", want: "", item: map[string]any{
+ "actor_type": util.TextToPtr(pgtype.Text{String: "member", Valid: true}),
+ "actor_id": util.UUIDToPtr(mustUUID(agentID)),
+ }},
+ {name: "no actor", want: "", item: map[string]any{"actor_type": (*string)(nil)}},
+ {name: "agent actor with no id", want: "", item: map[string]any{
+ "actor_type": util.TextToPtr(pgtype.Text{String: "agent", Valid: true}),
+ }},
+ {name: "agent actor with an unparsable id", want: "", item: map[string]any{
+ "actor_type": "agent", "actor_id": "not-a-uuid",
+ }},
+ } {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got, ok := inboxActorAgent(tc.item)
+ if tc.want == "" {
+ if ok {
+ t.Errorf("inboxActorAgent = %q, want no agent", util.UUIDToString(got))
+ }
+ return
+ }
+ if !ok || util.UUIDToString(got) != tc.want {
+ t.Errorf("inboxActorAgent = (%q, %v), want (%s, true)", util.UUIDToString(got), ok, tc.want)
+ }
+ })
+ }
+}
+
+// agentInboxItem is one issue-comment notification as the listeners publish
+// it: a member recipient, and the agent whose comment it is as the actor —
+// behind pointers, which is how inboxItemToResponse builds the map.
+func agentInboxItem(notifType, agentID string) map[string]any {
+ return map[string]any{
+ "recipient_type": "member",
+ "recipient_id": "33333333-3333-3333-3333-333333333333",
+ "workspace_id": "44444444-4444-4444-4444-444444444444",
+ "type": notifType,
+ "title": "An issue",
+ "actor_type": util.TextToPtr(pgtype.Text{String: "agent", Valid: true}),
+ "actor_id": util.UUIDToPtr(mustUUID(agentID)),
+ }
+}
+
func TestHandleInboxNew_IgnoresNonMemberRecipient(t *testing.T) {
t.Parallel()
// memberErr set so that if it somehow reached the query it would no-op;
diff --git a/server/internal/integrations/wecom/outbound_two_replica_db_test.go b/server/internal/integrations/wecom/outbound_two_replica_db_test.go
index e17e9248cd..60ad8d3dff 100644
--- a/server/internal/integrations/wecom/outbound_two_replica_db_test.go
+++ b/server/internal/integrations/wecom/outbound_two_replica_db_test.go
@@ -293,6 +293,11 @@ type fanoutRelay struct {
deliverers []*RelayOutbound
log []queued
published int
+ // failAfterFanout makes PublishWithID do its whole fan-out and THEN report
+ // an error: the frame was accepted and delivered, and only the publisher's
+ // view of the call is lost. It is the shape the inbox push must treat as
+ // uncertain rather than as a miss.
+ failAfterFanout bool
}
func (f *fanoutRelay) register(r *RelayOutbound) {
@@ -314,9 +319,27 @@ func (f *fanoutRelay) PublishWithID(_, scopeID, _ string, frame []byte, id strin
for _, d := range targets {
d.DeliverWecomOutbound(scopeID, frame, id)
}
+ if f.failAfterFanout {
+ return errors.New("relay: publish response lost")
+ }
return nil
}
+// publishedTo counts the frames published for one installation, which is how a
+// test tells "the fallback was never offered" from "it was offered and
+// dropped".
+func (f *fanoutRelay) publishedTo(installationID string) int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ n := 0
+ for _, q := range f.log {
+ if q.frame.InstallationID == installationID {
+ n++
+ }
+ }
+ return n
+}
+
// 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) {
@@ -337,6 +360,9 @@ type sharedDedupe struct {
values map[string]string
fail bool
calls int
+ // stateReads counts the non-fencing reads the acceptance poll makes, which
+ // is how a test can see how many windows were paid for.
+ stateReads int
// releaseFails makes Release report failure and keep the key: a DEL that
// never reached the server.
@@ -400,6 +426,15 @@ func (d *sharedDedupe) claimCount() int {
return d.calls
}
+// claimStateCount is how many acceptance polls this store answered. One window
+// of a W-wide wait is roughly W/(W/8)+1 of them; two windows are roughly twice
+// that, which is the arithmetic a fallback that waits again would show.
+func (d *sharedDedupe) claimStateCount() int {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.stateReads
+}
+
func (d *sharedDedupe) Release(_ context.Context, key, token string) (bool, error) {
d.mu.Lock()
defer d.mu.Unlock()
@@ -469,6 +504,29 @@ func (d *sharedDedupe) Resolve(_ context.Context, key string) (claimState, error
return claimHeld, nil
}
+// ClaimState is the read the inbox publisher polls to see whether a replica
+// took the delivery. Same answers as Resolve, except a held claim is reported
+// held rather than fenced: the publisher is not resolving an outcome here, it
+// is watching a delivery it must not disturb.
+func (d *sharedDedupe) ClaimState(_ context.Context, key string) (claimState, error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.stateReads++
+ if d.fail {
+ return claimAbsent, errors.New("dedupe unavailable")
+ }
+ v, ok := d.values[key]
+ switch {
+ case !ok:
+ return claimAbsent, nil
+ case v == claimSettledValue:
+ return claimSettled, nil
+ case v == claimLostValue:
+ return claimLost, nil
+ }
+ return claimHeld, nil
+}
+
// relayReplica is one backend process wired for cross-replica routing.
type relayReplica struct {
*replica
diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.go
index c5bc2f228a..8b03bee5c4 100644
--- a/server/internal/integrations/wecom/relay_outbound.go
+++ b/server/internal/integrations/wecom/relay_outbound.go
@@ -105,6 +105,11 @@ type DedupeStore interface {
// same operation, so a holder that comes back later finds its Settle
// refused and records nothing. See RelayOutbound.settle.
Resolve(ctx context.Context, key string) (claimState, error)
+ // ClaimState is Resolve WITHOUT the fence: it reports what the key holds
+ // right now and changes nothing. It is what an inbox publish polls while it
+ // waits to see whether a replica took the delivery; Resolve would fence a
+ // holder that is merely mid-delivery. See RelayOutbound.confirmInbox.
+ ClaimState(ctx context.Context, key string) (claimState, error)
// ClaimBudget is the longest ONE round trip above may take. The store
// states it because the store enforces it: outcomeGrace pays this budget
// once per offer, and a copy of the number kept by the dispatcher would be
@@ -195,6 +200,15 @@ type RelayConfig struct {
// a tenth of one poll — and expired long before the move it existed for.
LeaseSettle time.Duration
+ // AcceptanceWindow is how long an inbox publish waits to see a replica take
+ // the delivery claim before it concludes that nobody holds that bot's
+ // socket. Its bound is the frame's trip to every replica's dispatcher plus
+ // one claim round trip (DedupeStore.ClaimBudget), NOT the re-offer chain
+ // the reply path's outcomeGrace outlasts: an inbox frame nobody claimed has
+ // no chain behind it, so waiting the chain out would only delay the
+ // fallback. Zero takes defaultRelayAcceptanceWindow.
+ AcceptanceWindow time.Duration
+
// RetryBackoff is the FIRST wait between re-offers; the chain doubles from
// there, capped at a quarter of LeaseSettle so a lease that lands early is
// not sat out. Small on purpose: the common reason a re-offer succeeds is
@@ -211,6 +225,11 @@ const (
// here would be free to drift from the thing it is meant to outlast.
defaultRelayLeaseSettle = engine.DefaultPollInterval
defaultRelayRetryBackoff = 200 * time.Millisecond
+ // defaultRelayAcceptanceWindow matches defaultClaimBudget: one claim round
+ // trip plus room for the bus fan-out and a dispatcher's turn. The two live
+ // in different files on purpose — this is the relay's bound on how long it
+ // will wait, that is the store's bound on how long one call may take.
+ defaultRelayAcceptanceWindow = 2 * time.Second
)
// withDefaults fills the zero fields and returns the completed config.
@@ -238,6 +257,9 @@ func (c RelayConfig) withDefaults() RelayConfig {
if c.RetryBackoff <= 0 {
c.RetryBackoff = defaultRelayRetryBackoff
}
+ if c.AcceptanceWindow <= 0 {
+ c.AcceptanceWindow = defaultRelayAcceptanceWindow
+ }
return c
}
@@ -372,6 +394,40 @@ const (
outcomeProvablyNotSent
)
+// relayPublish is what one trip through the cross-replica router produced.
+//
+// The bool it replaces could not tell "the bus took it" from "a replica took
+// the delivery" from "the publish call itself failed", and an inbox push needs
+// all three: only an accepted-and-claimed frame is a delivery it may stop
+// making, and only a failed publish forbids it from trying another bot.
+type relayPublish int
+
+const (
+ // relayNotWired — nothing reached the bus: no relay is attached, or the
+ // frame could not even be built. A caller may treat it as a delivery that
+ // certainly did not happen.
+ relayNotWired relayPublish = iota
+ // relayAccepted — the bus took the frame. For a reply or a seal that is the
+ // whole answer. For an inbox push it means a replica that owns the target
+ // bot's socket took the delivery claim, so somebody is carrying it.
+ relayAccepted
+ // relayNoHolder — the bus took the frame, but across the acceptance window
+ // no replica took the delivery claim: nobody holds that installation's
+ // socket, so every dispatcher discards the frame. Only an inbox push can
+ // report this (see confirmInbox). The delivery provably did not happen.
+ relayNoHolder
+ // relayUncertain — the publish call failed, or the claim store could not
+ // answer. The frame may or may not have been accepted, so nothing may be
+ // concluded and nothing may be re-routed on this evidence.
+ relayUncertain
+)
+
+// routed reports whether the bus took the frame, which is the whole question
+// the reply and seal callers ask. They have no second route to fall back to,
+// and a frame that may have been accepted is treated as not carried, so they
+// keep their old local-send behaviour.
+func (p relayPublish) routed() bool { return p == relayAccepted }
+
// seenEvents is a bounded, per-process set of relay event ids already acted on.
// It is a cheap first gate in front of the Redis claim — the publisher's own
// copy of its own frame is the common case and never needs a round trip. It is
@@ -793,27 +849,169 @@ func (r *RelayOutbound) Wait() {
}
}
-// publish hands a delivery to the other replicas. Reports whether it went out.
-func (r *RelayOutbound) publish(f relayFrame, eventID string) bool {
+// publish hands a delivery to the other replicas and reports what the bus did
+// with it. See relayPublish for why the answer is not a bool.
+//
+// It NEVER waits: every caller of this one either has no second route to take
+// when nobody holds the target bot, or is not in a position to take one. The
+// single caller that is (an inbox push with the recipient-wide bot behind it)
+// asks through publishAwaitingHolder instead, and pays the wait only there.
+func (r *RelayOutbound) publish(f relayFrame, eventID string) relayPublish {
+ return r.publishFrame(context.Background(), f, eventID, false)
+}
+
+// publishAwaitingHolder is publish plus the acceptance wait: it answers whether
+// a replica owning the target bot's socket actually took the delivery, which is
+// what an inbox push needs before it may put a second card in the member's chat
+// through another bot. The wait is bounded by ctx, and by the acceptance window
+// it configures -- see confirmInbox.
+//
+// WHY IT IS A SEPARATE ENTRY POINT. Bus delivery is synchronous on the caller's
+// goroutine, and the publisher of an inbox:new is the HTTP request that created
+// the comment; only one replica holds a given bot's socket, so this wait is the
+// common path in a multi-replica deployment. Spending it where the answer is
+// then discarded -- a member-authored push, which has no second route to try,
+// or the fallback attempt itself, which has nothing behind it -- holds the
+// request open for a verdict nobody can act on. Those callers keep publish.
+func (r *RelayOutbound) publishAwaitingHolder(ctx context.Context, f relayFrame, eventID string) relayPublish {
+ return r.publishFrame(ctx, f, eventID, true)
+}
+
+// publishFrame is the one implementation behind the two entry points.
+func (r *RelayOutbound) publishFrame(ctx context.Context, f relayFrame, eventID string, awaitHolder bool) relayPublish {
if r == nil || r.publisher == nil {
- return false
+ return relayNotWired
}
body, err := json.Marshal(f)
if err != nil {
r.logger.Warn("wecom relay: marshal outbound frame", "error", err)
- return false
+ return relayNotWired
}
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
+ // The bus call failed, but a publish whose RESPONSE was lost may still
+ // have been accepted. Nothing may be concluded from it.
+ return relayUncertain
}
// A published reply is now owed an outcome by somebody. watchOutcomes is
// that somebody — see its comment for why it cannot be anyone else.
if f.Kind == relayKindReply {
r.awaitOutcome(f, eventID)
}
- return true
+ // Reply and seal frames are fire-and-forget: their callers read only "did
+ // the bus take it", and counting a routed reply twice is what the outcome
+ // watch exists to prevent. Only the inbox push asks whether a replica
+ // actually took the delivery, because only it has a second route to fall
+ // back to -- and only when the caller asked to wait.
+ if !awaitHolder || f.Kind != relayKindInbox {
+ return relayAccepted
+ }
+ if r.dedupe == nil {
+ // No claim store means no relay in production (see DedupeStore); the
+ // bus call is the only signal available, so take it.
+ return relayAccepted
+ }
+ return r.confirmInbox(ctx, eventID)
+}
+
+// confirmInbox answers whether a replica took the delivery claim for an inbox
+// frame the bus accepted, so the publisher can tell "somebody is carrying this"
+// from "nobody holds that bot's socket" without waiting out a re-offer chain
+// that will never exist.
+//
+// It reads the claim key for up to RelayConfig.AcceptanceWindow. A claim that
+// appears means a replica owning the installation's socket engaged the
+// delivery, and the relay's own guarantees (re-offers, the outcome record) take
+// over from there. A key still absent at the end of the window means no replica
+// even took it — the frame is handed to each replica exactly once and only a
+// socket holder claims — so none ever will. The publisher then FENCES the key
+// under a token no delivery worker presents (fenceTokenFor) and reports
+// relayNoHolder, which is what lets the caller
+// route the notification somewhere else. The fence is what keeps that safe: a
+// dispatcher that is late, or a replica replaying the frame across a restart,
+// finds the claim taken and delivers nothing -- on the publishing replica too,
+// which is the one a fence under its own delivery token would NOT have stopped.
+// See fenceTokenFor.
+//
+// A claim store that cannot answer is relayUncertain: the delivery might be
+// happening, and the caller must not route a second copy on that. So is a
+// caller whose own budget ran out mid-wait -- the wait is bounded by ctx as
+// well as by the window, because this runs on a request's goroutine.
+func (r *RelayOutbound) confirmInbox(ctx context.Context, eventID string) relayPublish {
+ window := r.cfg.AcceptanceWindow
+ // THE CALLER'S BUDGET IS THE OUTER BOUND. This wait runs on the goroutine
+ // that is serving an HTTP request (see publishAwaitingHolder), so a caller
+ // that runs out of time must take the wait with it rather than be held for
+ // a window it configured elsewhere. A tighter caller deadline shortens the
+ // window; with no deadline the window stands.
+ deadline := time.Now().Add(window)
+ if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
+ deadline = d
+ }
+ // The poll's OWN deadline ends the wait; the context is the backstop that
+ // keeps a claim store which ignores its deadline from outlasting it, so it
+ // gets a little more room than the loop. Were the two equal, the context
+ // could fire in the same instant the last poll lands and the verdict would
+ // rest on which select case won: reporting "uncertain" for a bot nobody
+ // holds, and silently giving up the fallback.
+ pollCtx, cancel := context.WithTimeout(ctx, time.Until(deadline)+window/8+time.Millisecond)
+ defer cancel()
+ key := dedupeKey(eventID)
+ // Eight polls over whatever window actually applies, so a caller that
+ // shortened the wait still samples it evenly rather than once at the start
+ // and once past its own deadline.
+ step := window / 8
+ if effective := time.Until(deadline); effective < window {
+ step = effective / 8
+ }
+ if step < time.Millisecond {
+ step = time.Millisecond
+ }
+ for {
+ state, err := r.dedupe.ClaimState(pollCtx, key)
+ if err != nil {
+ r.logger.WarnContext(pollCtx, "wecom relay: inbox claim state unreadable; the push is not re-routed",
+ "error", err, "event_id", eventID)
+ return relayUncertain
+ }
+ if state != claimAbsent {
+ return relayAccepted
+ }
+ if !time.Now().Before(deadline) {
+ break
+ }
+ timer := time.NewTimer(step)
+ select {
+ case <-timer.C:
+ case <-pollCtx.Done():
+ timer.Stop()
+ return relayUncertain
+ }
+ }
+ // A caller that ran out of time has nothing left to re-route WITH: its own
+ // local send would see the same expired context, so the honest answer is
+ // that the delivery is unknown -- nothing sent, nothing re-routed. In a
+ // production request the 5s budget leaves the 2s window plenty of room, so
+ // this is the backstop rather than the common exit.
+ if err := ctx.Err(); err != nil {
+ r.logger.WarnContext(ctx, "wecom relay: the caller's budget ran out before an inbox push's bot could be confirmed; not re-routing",
+ "error", err, "event_id", eventID)
+ return relayUncertain
+ }
+ won, err := r.dedupe.Claim(pollCtx, key, r.fenceTokenFor(eventID), r.dedupeTTL)
+ if err != nil {
+ r.logger.WarnContext(pollCtx, "wecom relay: could not fence an unclaimed inbox delivery; the push is not re-routed",
+ "error", err, "event_id", eventID)
+ return relayUncertain
+ }
+ if !won {
+ // A replica took the claim between the last read and the fence.
+ return relayAccepted
+ }
+ r.logger.InfoContext(pollCtx, "wecom relay: no replica holds the inbox push's bot; its sender may route it elsewhere",
+ "event_id", eventID)
+ return relayNoHolder
}
// DeliverWecomOutbound is realtime.WecomOutboundDeliverer. It must not block:
@@ -1063,6 +1261,19 @@ func settleBudgetSpent(ctx context.Context) bool {
// delivery. Stable across re-offers on this process, unique across replicas.
func (r *RelayOutbound) tokenFor(eventID string) string { return r.owner + "/" + eventID }
+// fenceTokenFor is the token a no-holder fence is planted under, and it is
+// deliberately NOT tokenFor. Claim answers "won" when the stored value equals
+// the caller's token, so a fence planted under the publisher's own delivery
+// token would be reclaimable by that replica's dispatcher the moment its
+// socket came back -- the ordinary reconnect, not an exotic one -- and the
+// frame it then delivered would be the second card the fallback had already
+// replaced. The suffix makes the fenced value one no delivery worker ever
+// presents, so the fence holds against every worker on every replica, the
+// publishing one included. It is never released; the claim TTL retires it.
+func (r *RelayOutbound) fenceTokenFor(eventID string) string {
+ return r.tokenFor(eventID) + "/fence"
+}
+
func dedupeKey(eventID string) string { return "wecom:outbound:claim:" + eventID }
// pendingOutcome is one routed reply whose end-to-end fate is not known yet.
@@ -1280,9 +1491,13 @@ 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
+// relayInboxEventID is the same rule for an inbox push, which has no task. The
+// installation is part of the id because one push is offered to two bots: the
+// acting agent's, then the recipient-wide one. The publisher FENCES the claim
+// of a bot nobody holds before it tries the other, and distinct ids are what
+// keep that fence from also swallowing the route around it.
+func relayInboxEventID(itemID, recipientID, installationID string) string {
+ return "wecom:inbox:" + itemID + ":" + recipientID + ":" + installationID
}
// deliverRelayed performs a delivery published by another replica. It is the
diff --git a/server/internal/integrations/wecom/relay_publish_state_test.go b/server/internal/integrations/wecom/relay_publish_state_test.go
new file mode 100644
index 0000000000..22b7fa98b2
--- /dev/null
+++ b/server/internal/integrations/wecom/relay_publish_state_test.go
@@ -0,0 +1,230 @@
+package wecom
+
+// relay_publish_state_test.go — what one trip through the relay reports.
+//
+// A bool could not tell "the bus took it" from "a replica took the delivery"
+// from "the publish call failed", and an inbox push needs all three. These pin
+// the states that decision rests on, without a database: the bus and the claim
+// store are the same doubles the reply-path tests use.
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+func inboxPublishRouter(t *testing.T, relay *fanoutRelay, dedupe DedupeStore, cfg RelayConfig, handler *Outbound) *RelayOutbound {
+ t.Helper()
+ router := NewRelayOutbound(relay, dedupe, cfg, slog.Default())
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { cancel(); router.Wait() })
+ router.Start(ctx)
+ router.Attach(handler)
+ relay.register(router)
+ return router
+}
+
+// TestRelayPublish_InboxWithNoHolderIsNoHolder: the bus took the frame, but no
+// replica holds that installation's socket, so no dispatcher can take the
+// delivery. The publisher must read that as a proven miss (and must FENCE the
+// claim so a late dispatcher cannot deliver it after the fallback ran).
+func TestRelayPublish_InboxWithNoHolderIsNoHolder(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ // A handler that owns no socket at all.
+ router := inboxPublishRouter(t, relay, dedupe,
+ RelayConfig{AcceptanceWindow: 40 * time.Millisecond},
+ &Outbound{senders: newSendersRegistry(), logger: slog.Default()})
+
+ instID := util.UUIDToString(mustTestUUID(t))
+ eventID := relayInboxEventID("item-1", "recipient-1", instID)
+ got := router.publishAwaitingHolder(context.Background(), relayFrame{
+ Kind: relayKindInbox, InstallationID: instID,
+ ChatID: "T_USER", ChatType: chatTypeSingleInt, Content: "card",
+ }, eventID)
+ if got != relayNoHolder {
+ t.Fatalf("publish = %v, want relayNoHolder", got)
+ }
+ if v := dedupe.valueOf(dedupeKey(eventID)); v == "" || v == claimSettledValue || v == claimLostValue {
+ t.Fatalf("claim value = %q, want a fencing token: a late holder must find the delivery taken", v)
+ }
+}
+
+// TestRelayPublish_InboxWithAHolderIsAccepted: one replica owns the socket and
+// takes the claim, so the publisher may stop there.
+func TestRelayPublish_InboxWithAHolderIsAccepted(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ instID := mustTestUUID(t)
+ reg := newSendersRegistry()
+ conn := &recordingConn{}
+ reg.set(instID, conn.autoAck(newWSSender(conn, nil)))
+ router := inboxPublishRouter(t, relay, dedupe,
+ RelayConfig{AcceptanceWindow: 500 * time.Millisecond},
+ NewOutbound(nil, reg, nil, slog.Default()))
+
+ eventID := relayInboxEventID("item-2", "recipient-1", util.UUIDToString(instID))
+ got := router.publishAwaitingHolder(context.Background(), relayFrame{
+ Kind: relayKindInbox, InstallationID: util.UUIDToString(instID),
+ ChatID: "T_USER", ChatType: chatTypeSingleInt, Content: "card",
+ }, eventID)
+ if got != relayAccepted {
+ t.Fatalf("publish = %v, want relayAccepted", got)
+ }
+}
+
+// TestRelayPublish_FailedPublishIsUncertain: a publish call that errors is not
+// proof the frame was refused. Nothing may be concluded from it.
+func TestRelayPublish_FailedPublishIsUncertain(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ // No deliverer, so the fan-out itself is empty and only the error is left.
+ router := NewRelayOutbound(relay, dedupe, RelayConfig{}, slog.Default())
+
+ instID := util.UUIDToString(mustTestUUID(t))
+ eventID := relayInboxEventID("item-3", "recipient-1", instID)
+ relay.failAfterFanout = true
+ got := router.publishAwaitingHolder(context.Background(), relayFrame{
+ Kind: relayKindInbox, InstallationID: instID,
+ ChatID: "T_USER", ChatType: chatTypeSingleInt, Content: "card",
+ }, eventID)
+ if got != relayUncertain {
+ t.Fatalf("publish = %v, want relayUncertain", got)
+ }
+}
+
+// TestRelayPublish_UnreadableClaimStoreIsUncertain: without an answer from the
+// claim store the publisher cannot tell a holder from a miss, and a duplicate
+// card is worse than a late one, so it must not fall back.
+func TestRelayPublish_UnreadableClaimStoreIsUncertain(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ dedupe.fail = true
+ router := inboxPublishRouter(t, relay, dedupe,
+ RelayConfig{AcceptanceWindow: 40 * time.Millisecond},
+ &Outbound{senders: newSendersRegistry(), logger: slog.Default()})
+
+ instID := util.UUIDToString(mustTestUUID(t))
+ eventID := relayInboxEventID("item-4", "recipient-1", instID)
+ got := router.publishAwaitingHolder(context.Background(), relayFrame{
+ Kind: relayKindInbox, InstallationID: instID,
+ ChatID: "T_USER", ChatType: chatTypeSingleInt, Content: "card",
+ }, eventID)
+ if got != relayUncertain {
+ t.Fatalf("publish = %v, want relayUncertain", got)
+ }
+}
+
+// TestRelayPublish_ReplyKeepsTheBoolSemantics: the reply and seal paths ask
+// only "did the bus take it", and a frame that may have been accepted must not
+// be re-sent, so a failed publish still reads as not routed.
+func TestRelayPublish_ReplyKeepsTheBoolSemantics(t *testing.T) {
+ t.Parallel()
+ if got := (relayPublish(relayAccepted)).routed(); !got {
+ t.Errorf("relayAccepted.routed() = false, want true")
+ }
+ for _, p := range []relayPublish{relayNotWired, relayNoHolder, relayUncertain} {
+ if p.routed() {
+ t.Errorf("relayPublish(%d).routed() = true, want false", p)
+ }
+ }
+}
+
+// TestRelayPublish_FenceHoldsAgainstThePublishingReplica is the review's
+// remaining blocker: the fence must be unclaimable by EVERY delivery worker,
+// the one on the publishing replica included. That replica is the ordinary
+// reconnect case -- the acting agent's bot is down, the push falls back to the
+// recipient-wide bot, the socket then comes back here, and the frame the
+// fallback replaced is offered again. A fence planted under tokenFor would be
+// reclaimable by that very dispatcher (Claim answers "won" on a token match)
+// and the member would get a second card.
+func TestRelayPublish_FenceHoldsAgainstThePublishingReplica(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ reg := newSendersRegistry()
+ router := inboxPublishRouter(t, relay, dedupe,
+ RelayConfig{AcceptanceWindow: 40 * time.Millisecond},
+ NewOutbound(nil, reg, nil, slog.Default()))
+
+ instID := mustTestUUID(t)
+ inst := util.UUIDToString(instID)
+ frame := relayFrame{
+ Kind: relayKindInbox, InstallationID: inst,
+ ChatID: "T_USER", ChatType: chatTypeSingleInt, Content: "card",
+ }
+ eventID := relayInboxEventID("item-6", "recipient-1", inst)
+
+ // The bot is offline here, so nobody claims and the publisher fences the
+ // key -- the miss the fallback is owed for.
+ if got := router.publishAwaitingHolder(context.Background(), frame, eventID); got != relayNoHolder {
+ t.Fatalf("publish = %v, want relayNoHolder", got)
+ }
+ body, err := json.Marshal(frame)
+ if err != nil {
+ t.Fatalf("marshal frame: %v", err)
+ }
+
+ // The socket comes back ON THE PUBLISHING REPLICA and the same frame is
+ // offered again. The dispatcher retries it while it cannot take the claim,
+ // so give it room to try before asserting it delivered nothing.
+ conn := &recordingConn{}
+ reg.set(instID, conn.autoAck(newWSSender(conn, nil)))
+ router.DeliverWecomOutbound(inst, body, eventID)
+ time.Sleep(120 * time.Millisecond)
+ if n := conn.frameCount(); n != 0 {
+ t.Fatalf("the publishing replica delivered %d cards through the fence it planted", n)
+ }
+
+ // A DIFFERENT replica is blocked too, which it always was: the fenced value
+ // is not that replica's token either. Kept so the property is asserted as
+ // "every worker", not only the ones this change moved.
+ otherReg := newSendersRegistry()
+ otherConn := &recordingConn{}
+ otherReg.set(instID, otherConn.autoAck(newWSSender(otherConn, nil)))
+ other := NewRelayOutbound(relay, dedupe, RelayConfig{AcceptanceWindow: 40 * time.Millisecond}, slog.Default())
+ octx, ocancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { ocancel(); other.Wait() })
+ other.Start(octx)
+ other.Attach(NewOutbound(nil, otherReg, nil, slog.Default()))
+ other.DeliverWecomOutbound(inst, body, eventID)
+ time.Sleep(60 * time.Millisecond)
+ if n := otherConn.frameCount(); n != 0 {
+ t.Fatalf("another replica delivered %d cards through the fence", n)
+ }
+}
+
+// TestRelayPublish_PlainPublishNeverWaits pins the split between the two entry
+// points: an inbox frame handed to publish answers as soon as the bus took it,
+// even with a 2s window configured and no holder anywhere. Every caller that
+// cannot act on a no-holder answer -- reply and seal frames, a member-authored
+// push, the fallback attempt -- goes through here, and none of them may hold
+// the request's goroutine for a verdict it will discard.
+func TestRelayPublish_PlainPublishNeverWaits(t *testing.T) {
+ t.Parallel()
+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()
+ router := inboxPublishRouter(t, relay, dedupe,
+ RelayConfig{AcceptanceWindow: 2 * time.Second},
+ &Outbound{senders: newSendersRegistry(), logger: slog.Default()})
+
+ instID := util.UUIDToString(mustTestUUID(t))
+ start := time.Now()
+ got := router.publish(relayFrame{
+ Kind: relayKindInbox, InstallationID: instID,
+ ChatID: "T_USER", ChatType: chatTypeSingleInt, Content: "card",
+ }, relayInboxEventID("item-7", "recipient-1", instID))
+ elapsed := time.Since(start)
+
+ if got != relayAccepted {
+ t.Fatalf("publish = %v, want relayAccepted", got)
+ }
+ if elapsed > 200*time.Millisecond {
+ t.Fatalf("publish waited %v; the non-awaiting path must not spend the acceptance window", elapsed)
+ }
+ if n := dedupe.claimStateCount(); n != 0 {
+ t.Fatalf("publish polled the claim %d times; the non-awaiting path must not poll at all", n)
+ }
+}
diff --git a/server/internal/integrations/wecom/relay_settle_budget_test.go b/server/internal/integrations/wecom/relay_settle_budget_test.go
index 9d45aa7645..df3611e256 100644
--- a/server/internal/integrations/wecom/relay_settle_budget_test.go
+++ b/server/internal/integrations/wecom/relay_settle_budget_test.go
@@ -95,6 +95,10 @@ func (s *slowSettleStore) Resolve(context.Context, string) (claimState, error) {
return claimHeld, nil
}
+func (s *slowSettleStore) ClaimState(context.Context, string) (claimState, error) {
+ return claimHeld, nil
+}
+
func (s *slowSettleStore) ClaimBudget() time.Duration { return s.roundTrip }
func (s *slowSettleStore) settleAttempts() int {
diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.go
index 7a33bf1738..d6d240c5a5 100644
--- a/server/internal/integrations/wecom/typing_indicator.go
+++ b/server/internal/integrations/wecom/typing_indicator.go
@@ -733,7 +733,12 @@ func retryPending(e events.Event) bool {
// router: hand a frame to whichever replica holds the socket. *RelayOutbound
// satisfies it; nil leaves the single-replica behaviour unchanged.
type noticeRouter interface {
- publish(f relayFrame, eventID string) bool
+ publish(f relayFrame, eventID string) relayPublish
+ // publishAwaitingHolder is publish plus the acceptance wait: it answers
+ // relayNoHolder when no replica took the frame, which only a caller with a
+ // second route to try can act on. The wait is bounded by ctx. See
+ // RelayOutbound.publishAwaitingHolder for why the two are separate.
+ publishAwaitingHolder(ctx context.Context, f relayFrame, eventID string) relayPublish
}
// WithRelay lets a run's ending reach the asker from a replica that does not
@@ -762,7 +767,7 @@ func (m *TypingIndicatorManager) relaySeal(sessionID pgtype.UUID, taskID, reason
SealReason: reason,
TaskID: taskID,
SessionID: util.UUIDToString(sessionID),
- }, taskID)
+ }, taskID).routed()
}
func (m *TypingIndicatorManager) sayAsPlainMessage(ctx context.Context, sessionID pgtype.UUID, addr roundAddress, taskID, text string) error {
@@ -781,7 +786,7 @@ func (m *TypingIndicatorManager) sayAsPlainMessage(ctx context.Context, sessionI
Content: text,
TaskID: taskID,
SessionID: util.UUIDToString(sessionID),
- }, taskID) {
+ }, taskID).routed() {
m.log.DebugContext(ctx, "wecom typing: routed a run's ending to the replica holding the socket",
"chat_session_id", util.UUIDToString(sessionID),
"installation_id", util.UUIDToString(addr.InstallationID))
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 00f9b4c356..10b473751d 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -1382,6 +1382,68 @@ func (q *Queries) FindChannelBindingForMember(ctx context.Context, arg FindChann
return i, err
}
+const findChannelBindingForMemberOnAgentInstallation = `-- name: FindChannelBindingForMemberOnAgentInstallation :one
+SELECT b.id, b.workspace_id, b.multica_user_id, b.installation_id, b.channel_type, b.channel_user_id, b.config, b.bound_at FROM channel_user_binding b
+JOIN channel_installation ci ON ci.id = b.installation_id
+WHERE b.workspace_id = $1
+ AND b.multica_user_id = $2
+ AND b.channel_type = $3
+ AND ci.channel_type = $3
+ AND ci.agent_id = $4
+ AND ci.status = 'active'
+ORDER BY b.bound_at DESC
+LIMIT 1
+`
+
+type FindChannelBindingForMemberOnAgentInstallationParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ MulticaUserID pgtype.UUID `json:"multica_user_id"`
+ ChannelType string `json:"channel_type"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// Agent-attributed notification lookup: the same member lookup as
+// FindChannelBindingForMember, pinned to the ONE installation the agent whose
+// activity raised the notification owns.
+//
+// Why this exists. FindChannelBindingForMember answers by the
+// RECIPIENT alone, so in a multi-bot org — one bot per agent, several of them
+// bound by the same person — every notification a member receives is pushed
+// through whichever bot they bound most recently, no matter which agent the
+// notification is about. The recipient reads three agents' activity as if it
+// all came from one of them. Pinning the lookup to the acting agent's bot is
+// what makes the notification follow the bot↔agent mapping the sender is
+// reading.
+//
+// The tiebreak stays for the case where one member holds two channel users on
+// the same bot (two WeCom accounts, one Multica account): both rows answer,
+// and `:one` cannot take more than one, so the newest binding wins here
+// exactly as it does in the recipient-wide lookup.
+//
+// channel_type is named once and used for both columns: the installation's
+// own discriminator and the binding's must agree, or installs of two
+// platforms could cross-answer here.
+func (q *Queries) FindChannelBindingForMemberOnAgentInstallation(ctx context.Context, arg FindChannelBindingForMemberOnAgentInstallationParams) (ChannelUserBinding, error) {
+ row := q.db.QueryRow(ctx, findChannelBindingForMemberOnAgentInstallation,
+ arg.WorkspaceID,
+ arg.MulticaUserID,
+ arg.ChannelType,
+ arg.AgentID,
+ )
+ var i ChannelUserBinding
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.MulticaUserID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelUserID,
+ &i.Config,
+ &i.BoundAt,
+ )
+ return i, err
+}
+
const findLiveChannelBindingToken = `-- name: FindLiveChannelBindingToken :one
SELECT token_hash, workspace_id, installation_id, channel_type, channel_user_id, expires_at, consumed_at, created_at FROM channel_binding_token
WHERE installation_id = $1
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 7457f3f5d6..f8be647f92 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -564,6 +564,39 @@ WHERE b.workspace_id = sqlc.arg('workspace_id')
ORDER BY b.bound_at DESC
LIMIT 1;
+-- name: FindChannelBindingForMemberOnAgentInstallation :one
+-- Agent-attributed notification lookup: the same member lookup as
+-- FindChannelBindingForMember, pinned to the ONE installation the agent whose
+-- activity raised the notification owns.
+--
+-- Why this exists. FindChannelBindingForMember answers by the
+-- RECIPIENT alone, so in a multi-bot org — one bot per agent, several of them
+-- bound by the same person — every notification a member receives is pushed
+-- through whichever bot they bound most recently, no matter which agent the
+-- notification is about. The recipient reads three agents' activity as if it
+-- all came from one of them. Pinning the lookup to the acting agent's bot is
+-- what makes the notification follow the bot↔agent mapping the sender is
+-- reading.
+--
+-- The tiebreak stays for the case where one member holds two channel users on
+-- the same bot (two WeCom accounts, one Multica account): both rows answer,
+-- and `:one` cannot take more than one, so the newest binding wins here
+-- exactly as it does in the recipient-wide lookup.
+--
+-- channel_type is named once and used for both columns: the installation's
+-- own discriminator and the binding's must agree, or installs of two
+-- platforms could cross-answer here.
+SELECT b.* FROM channel_user_binding b
+JOIN channel_installation ci ON ci.id = b.installation_id
+WHERE b.workspace_id = sqlc.arg('workspace_id')
+ AND b.multica_user_id = sqlc.arg('multica_user_id')
+ AND b.channel_type = sqlc.arg('channel_type')
+ AND ci.channel_type = sqlc.arg('channel_type')
+ AND ci.agent_id = sqlc.arg('agent_id')
+ AND ci.status = 'active'
+ORDER BY b.bound_at DESC
+LIMIT 1;
+
-- name: FindReusableChannelUserBinding :one
-- Cross-installation account-link reuse (MUL-3911). When a platform user
-- messages an installation they have NOT linked, but the SAME user id is already