Skip to content

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

Go

MUL-8401: fix(wecom): deliver a relayed seal to the replica holding the bubble (#9717)

Xichang(Seacen) Zhao3451e311a629
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index e48a4bb2dd..78e8356011 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -535,7 +535,7 @@ func (o *Outbound) routeFrameAwaiting(ctx context.Context, f relayFrame, eventID
}
// relaySeal asks whichever replica holds this round to close it. Routed by
-// round ownership, so it needs no address — see deliverRelayed.
+// round ownership, so it needs no address — see relayKindSeal.
func (o *Outbound) relaySeal(e events.Event, taskID pgtype.UUID, reason string, carriesFiles bool) {
id := util.UUIDToString(taskID)
if id == "" {
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 60ad8d3dff..a985906cbe 100644
--- a/server/internal/integrations/wecom/outbound_two_replica_db_test.go
+++ b/server/internal/integrations/wecom/outbound_two_replica_db_test.go
@@ -307,6 +307,12 @@ func (f *fanoutRelay) register(r *RelayOutbound) {
}
func (f *fanoutRelay) PublishWithID(_, scopeID, _ string, frame []byte, id string) error {
+ if scopeID == "" {
+ // What the shard reader does with it (ShardedStreamRelay.deliverMessage):
+ // the frame is written and nobody ever reads it. A fake that delivered
+ // it anyway hid that every relayed seal was lost this way.
+ return nil
+ }
var decoded relayFrame
if err := json.Unmarshal(frame, &decoded); err != nil {
return err
diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.go
index 8cd758867b..f00549c0d5 100644
--- a/server/internal/integrations/wecom/relay_outbound.go
+++ b/server/internal/integrations/wecom/relay_outbound.go
@@ -291,6 +291,17 @@ const (
// reply whose round is gone falls through to an ordinary push; one
// cancel-all click would then put 这次处理已取消 into every chat in the
// deployment. A seal frame with no round does NOTHING AT ALL.
+ //
+ // And it is for whoever holds the ROUND, which is not a question the
+ // socket or the claim can answer, so it takes neither: it is published
+ // under its task id, since it carries no installation and the stream
+ // reader drops a frame with no scope id, and perform hands it to every
+ // replica's deliverRelayed without the ownership gate or the claim. Gated
+ // on the socket it reached nobody; claimed once for the deployment, the
+ // replica that won could be one without the round, and the holder would
+ // lose the race and never close the bubble. Every replica but the holder
+ // finds no round and returns, and a copy that reaches the holder twice
+ // finds the round already taken.
relayKindSeal = "seal"
)
@@ -846,7 +857,11 @@ func (r *RelayOutbound) publishFrame(ctx context.Context, f relayFrame, eventID
r.logger.Warn("wecom relay: marshal outbound frame", "error", err)
return relayNotWired
}
- if err := r.publisher.PublishWithID(realtime.ScopeWecomOutbound, f.InstallationID, "", body, eventID); err != nil {
+ scope := f.InstallationID
+ if f.Kind == relayKindSeal {
+ scope = f.TaskID // see relayKindSeal
+ }
+ if err := r.publisher.PublishWithID(realtime.ScopeWecomOutbound, scope, "", body, eventID); err != nil {
r.logger.Warn("wecom relay: publish failed",
"error", err, "installation_id", f.InstallationID, "task_id", f.TaskID)
// The bus call failed, but a publish whose RESPONSE was lost may still
@@ -988,7 +1003,7 @@ func (r *RelayOutbound) DeliverWecomOutbound(scopeID string, frame []byte, event
return
}
select {
- case r.queues[r.shardFor(f.InstallationID)] <- queued{frame: f, eventID: eventID}:
+ case r.queues[r.shardFor(dispatchKey(f))] <- queued{frame: f, eventID: eventID}:
default:
// Shed rather than stall the shard. Counted, because a reply nobody
// gets is exactly what this whole path exists to stop being silent.
@@ -996,6 +1011,19 @@ func (r *RelayOutbound) DeliverWecomOutbound(scopeID string, frame []byte, event
}
}
+// dispatchKey picks the shard queue a frame waits on. Replies and inbox pushes
+// go by installation, which is what keeps one bot's frames in order. A seal
+// carries no installation, so keying it the same way would put every seal in
+// the deployment on one queue behind one worker, and a cancel-all burst past
+// QueueDepth would be shed: those bubbles would keep spinning. A seal needs no
+// ordering against anything but its own round, so it goes by task id.
+func dispatchKey(f relayFrame) string {
+ if f.Kind == relayKindSeal {
+ return f.TaskID
+ }
+ return f.InstallationID
+}
+
func (r *RelayOutbound) shardFor(installationID string) int {
h := fnv.New32a()
_, _ = h.Write([]byte(installationID))
@@ -1007,6 +1035,13 @@ func (r *RelayOutbound) shardFor(installationID string) int {
// False means it is owed another offer, which the caller schedules at the head
// of the installation's line.
func (r *RelayOutbound) perform(ctx context.Context, item queued) bool {
+ if item.frame.Kind == relayKindSeal {
+ // Neither gate below applies: see relayKindSeal.
+ dctx, cancel := context.WithTimeout(ctx, r.cfg.deliveryBudget())
+ r.handler.deliverRelayed(dctx, item.frame)
+ cancel()
+ return true
+ }
// Ownership FIRST, the global claim second. The claim is a cross-replica
// SET NX: every replica reads every frame, and if one that cannot send
// were allowed to win it, the replica that can send would lose the race,
diff --git a/server/internal/integrations/wecom/relay_seal_test.go b/server/internal/integrations/wecom/relay_seal_test.go
index 1a02e70fc4..71171255a2 100644
--- a/server/internal/integrations/wecom/relay_seal_test.go
+++ b/server/internal/integrations/wecom/relay_seal_test.go
@@ -2,6 +2,10 @@ package wecom
import (
"context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
"testing"
"github.com/multica-ai/multica/server/internal/util"
@@ -161,3 +165,134 @@ func TestARelayedAttachmentOnlyAnswerStillClosesTheBubble(t *testing.T) {
t.Errorf("sealed with %q, want %q — the copy is the round's, in the round's own locale", sealed, want)
}
}
+
+// ---- and the frame has to get there ----
+
+// The tests above check each end on its own: the publisher routes a seal, and
+// a seal handed to deliverRelayed closes the round. What lies between them is
+// the relay, and it addressed every frame by installation: the stream reader
+// drops a frame with no scope id, and perform asks whether this replica owns
+// that installation's socket before anything else. A seal carries no
+// installation, so it reached nobody. These run both processes joined by the
+// relay itself.
+
+// sealPair is two processes joined by the relay: holder painted the bubble for
+// task-1, elsewhere holds no round and no socket, and the ending lands there.
+type sealPair struct {
+ holder, elsewhere *bubbleRig
+ dedupe *sharedDedupe
+}
+
+func newSealPair(t *testing.T) sealPair {
+ t.Helper()
+ p := sealPair{holder: newBubbleRig(t), elsewhere: newBoundRoomRig(t), dedupe: newSharedDedupe()}
+ p.holder.ran(t, "REQ-1", "task-1")
+ p.elsewhere.senders.clear(p.elsewhere.instID, p.elsewhere.conn.sender)
+ p.elsewhere.askedInTheRoom(t, "task-1")
+
+ fan := &fanoutRelay{}
+ for _, rig := range []*bubbleRig{p.holder, p.elsewhere} {
+ router := NewRelayOutbound(fan, p.dedupe, RelayConfig{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ fan.register(router)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { cancel(); router.Wait() })
+ router.Start(ctx)
+ router.Attach(rig.out)
+ if rig == p.elsewhere {
+ rig.typing.WithRelay(router)
+ rig.out = NewOutbound(rig.q, rig.senders, rig.streams, nil, WithRelay(router))
+ }
+ }
+ return p
+}
+
+// sealedWith waits for the holder's bubble to close and returns its last words.
+func (p sealPair) sealedWith(t *testing.T) string {
+ t.Helper()
+ sealed := ""
+ waitFor(t, "the holder to close the bubble", func() bool {
+ for _, f := range p.holder.conn.streamFrames(t) {
+ if f["finish"] == true {
+ sealed, _ = f["content"].(string)
+ }
+ }
+ return sealed != ""
+ })
+ return sealed
+}
+
+// REVERSE VERIFICATION: publish the seal under its installation again, or put
+// it back behind the ownership gate, and the bubble is never closed. Put it
+// back behind the claim and no claim is the assertion that fails.
+func TestACancellationElsewhereClosesTheBubbleThroughTheRelay(t *testing.T) {
+ t.Parallel()
+ p := newSealPair(t)
+
+ p.elsewhere.cancelled(t, "task-1")
+
+ if got, want := p.sealedWith(t), copyFor(DefaultLocale).StreamCancelled; got != want {
+ t.Errorf("sealed with %q, want %q", got, want)
+ }
+ if n := p.dedupe.claimCount(); n != 0 {
+ t.Errorf("the seal took %d claim(s) — claimed once for the deployment, a replica without the "+
+ "round can win it and the holder never closes the bubble", n)
+ }
+ if got := pushedTexts(t, p.elsewhere.conn); len(got) != 0 {
+ t.Errorf("the replica without the round said %q", got)
+ }
+}
+
+// The other wordless ending that is routed: a completion with nothing to say.
+func TestACompletionWithNothingToSayElsewhereClosesTheBubbleThroughTheRelay(t *testing.T) {
+ t.Parallel()
+ p := newSealPair(t)
+ p.elsewhere.queueTask(t, taskUUID(t, "task-1"), "")
+
+ p.elsewhere.answer(t, "", "task-1")
+
+ if got, want := p.sealedWith(t), wordlessSealCopy(DefaultLocale, false); got != want {
+ t.Errorf("sealed with %q, want %q", got, want)
+ }
+ if n := p.dedupe.claimCount(); n != 0 {
+ t.Errorf("the seal took %d claim(s)", n)
+ }
+}
+
+// A seal carries no installation, so dispatching it by installation put every
+// seal in the deployment on one shard queue. A cancel-all burst bigger than
+// that one queue was shed, and those bubbles kept spinning.
+//
+// REVERSE VERIFICATION: dispatch seals by InstallationID again and the burst
+// lands on one queue, which overflows.
+func TestABurstOfSealsIsSpreadAcrossTheDispatchQueues(t *testing.T) {
+ t.Parallel()
+ const shards, depth = 8, 4
+ r := NewRelayOutbound(nil, nil, RelayConfig{Shards: shards, QueueDepth: depth},
+ slog.New(slog.NewTextHandler(io.Discard, nil)))
+ // Not started: frames stay in the queues where they can be counted.
+ const n = shards * depth / 2
+ for i := 0; i < n; i++ {
+ frame, err := json.Marshal(relayFrame{
+ Kind: relayKindSeal,
+ SealReason: sealReasonCancelled,
+ TaskID: fmt.Sprintf("00000000-0000-0000-0000-%012d", i),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.DeliverWecomOutbound("", frame, fmt.Sprintf("seal-%d", i))
+ }
+ queued, used := 0, 0
+ for _, q := range r.queues {
+ queued += len(q)
+ if len(q) > 0 {
+ used++
+ }
+ }
+ if queued != n {
+ t.Errorf("%d of %d seals were queued, the rest shed", queued, n)
+ }
+ if used < 2 {
+ t.Errorf("all seals went to %d queue(s); they should spread by task id", used)
+ }
+}
diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.go
index 2f6701b83a..f4817fb580 100644
--- a/server/internal/integrations/wecom/typing_indicator.go
+++ b/server/internal/integrations/wecom/typing_indicator.go
@@ -724,7 +724,7 @@ func (m *TypingIndicatorManager) WithRelay(r noticeRouter) *TypingIndicatorManag
// relaySeal asks whichever replica holds this round to close it, and says
// nothing about where that replica is. No address lookup: a seal frame is
-// routed by round ownership — see deliverRelayed — which is what lets the
+// routed by round ownership — see relayKindSeal — which is what lets the
// cancellation path keep its refusal to chase an address.
func (m *TypingIndicatorManager) relaySeal(sessionID pgtype.UUID, taskID, reason string) bool {
if m.relay == nil || taskID == "" {