Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(wecom): ask again before a queued reply is written to a revoked installation (#9694)
Xichang(Seacen) Zhaobf8970aa3392
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex 59aa18c6e1..a8c843a030 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -635,7 +635,14 @@ func (o *Outbound) sendAsMessage(ctx context.Context, e events.Event, taskID pgtif !hasVisibleChar(content) {return answerOutcome{addr: addr}, nil}- err = sender.sendTextCtx(ctx, addr.ChatID, addr.ChatType, content)+ err = sender.sendTextCtx(guardReply(ctx, o.q, addr.InstallationID), addr.ChatID, addr.ChatType, content)+ if errors.Is(err, errInstallationGone) && !errors.Is(err, errPartiallySent) {+ // Revoked while this answer waited for its turn on the socket. Not a+ // failed delivery: the same skip taskAddress files when the revocation+ // came before the address was read. The files go nowhere either.+ o.skippedFor(ctx, e.ChatSessionID, skipInstallationInactive)+ return answerOutcome{addr: addr}, errNothingToSay+ }// Recorded here rather than returned, so this send and the relay's go// through the one mapping in recordSend (#8344).o.recordSend(ctx, e.ChatSessionID, e.Type, err)@@ -729,10 +736,17 @@ func chatDoneTaskID(e events.Event) (pgtype.UUID, bool) {//// senders and streams are non-nil here: a turn has a bubble only through them.func (o *Outbound) finishStream(ctx context.Context, h streamHandle, text string) error {- err := o.streams.seal(ctx, o.senders, h, text)+ err := o.streams.seal(guardReply(ctx, o.q, h.InstallationID), o.senders, h, text)if err == nil {return nil}+ if errors.Is(err, errInstallationGone) {+ // Not a failed seal: nobody may write here any more. The caller's+ // fallback reaches the same verdict on its own.+ o.logger.InfoContext(ctx, "wecom outbound: bubble left open, installation revoked",+ "installation_id", uuidStringPub(h.InstallationID))+ return err+ }o.logger.WarnContext(ctx, "wecom outbound: in-place reply failed, sending a new message instead","installation_id", uuidStringPub(h.InstallationID),"stream_unusable", streamUnusable(err), "error", err)@@ -949,7 +963,7 @@ func (o *Outbound) pushInbox(ctx context.Context, item map[string]any, binding d// 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 {+ if err := sender.sendTextCtx(guardReply(ctx, o.q, binding.InstallationID), 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)@@ -1102,10 +1116,23 @@ func (c installationCheck) String() string {// database blip on one attempt confirmed a one-shot chat:done as handled and// threw the answer away.func (o *Outbound) mayStillWrite(ctx context.Context, id pgtype.UUID) installationCheck {+ return readInstallationCheck(ctx, o.q, id)+}++// installationReader is the one read a permission check makes. Both the+// outbound subscriber's queries and the typing manager's delivery lookup carry+// it, which is what lets the two ask the same question of the same row.+type installationReader interface {+ GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)+}++// readInstallationCheck is mayStillWrite for a caller that is not the outbound+// subscriber.+func readInstallationCheck(ctx context.Context, q installationReader, id pgtype.UUID) installationCheck {if !id.Valid {return installationGone}- inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{+ inst, err := q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{ID: id,ChannelType: channelTypeWecom,})@@ -1121,3 +1148,47 @@ func (o *Outbound) mayStillWrite(ctx context.Context, id pgtype.UUID) installati}return installationOK}++// errInstallationGone marks a reply frame refused at the socket because its+// installation was revoked, or its row is gone, after the reply was addressed.+// What it settles is the obligation: there is no longer an installation to+// deliver through, so the reply is not owed to anyone — skipInstallationInactive,+// the same outcome taskAddress reaches when the revocation came first.+var errInstallationGone = errors.New("wecom: installation revoked")++// replyWriteGuard is the permission check for the frames of a reply: the+// message, each piece of a long one, and the closing frame of its bubble. It+// is installed in the context (withWriteGuard) and run by the ws layer with+// the writer in hand, for the same reason attachmentWriteGuard is: the address+// was read once, before the chat's turn and the writer's, and a revocation in+// between is otherwise written straight through.+//+// Unlike attachmentWriteGuard it keeps the two refusals apart, because a reply+// has an outcome to report and the two are opposite facts about it. Gone is+// errInstallationGone. Unreadable is a lookup that failed ahead of the write —+// the dropTransport case, and on the relay one more offer, since the answer is+// still owed and still the only copy.+func replyWriteGuard(q installationReader, id pgtype.UUID) func(context.Context) error {+ return func(ctx context.Context) error {+ ctx, cancel := context.WithTimeout(ctx, permissionReadBudget)+ defer cancel()+ switch check := readInstallationCheck(ctx, q, id); check {+ case installationOK:+ return nil+ case installationGone:+ return errInstallationGone+ default:+ return fmt.Errorf("wecom: installation could not be read (%s)", check)+ }+ }+}++// guardReply puts replyWriteGuard on ctx. A nil reader leaves ctx as it was:+// a manager built without a delivery lookup has nothing to ask, and writes as+// it did before the guard existed.+func guardReply(ctx context.Context, q installationReader, id pgtype.UUID) context.Context {+ if q == nil {+ return ctx+ }+ return withWriteGuard(ctx, replyWriteGuard(q, id))+}diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.goindex 9d8e9242a1..32bd8a1760 100644--- a/server/internal/integrations/wecom/outbound_test.go+++ b/server/internal/integrations/wecom/outbound_test.go@@ -224,15 +224,53 @@ func (f *fakeOutboundQueries) GetChannelTaskDelivery(_ context.Context, taskID pf.refuseImpossibleRouting(id)}return db.ChannelTaskDelivery{- BindingID: f.sessionBinding.ID, InstallationID: f.sessionBinding.InstallationID,+ BindingID: f.sessionBinding.ID, InstallationID: f.deliveryInstallationID(),ChannelType: channelType, ChannelChatID: f.sessionBinding.ChannelChatID,ChatType: f.sessionBinding.ChatType,ChannelMessageID: f.sessionBinding.LastMessageID, ChannelThreadID: f.sessionBinding.LastThreadID,RouteRevision: f.sessionBinding.RouteRevision, Config: f.sessionBinding.Config,}, nil}-func (f *fakeOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {- return f.installation, f.installErr++// rigInstallationID is the bot a turn came in on when the rig never named one.+// The delivery row's installation_id is NOT NULL in production, and the write+// guard reads the installation by that id, so a rig that leaves it unset still+// has to be answering about some bot.+var rigInstallationID = pgtype.UUID{Bytes: [16]byte{0xfe, 0xed}, Valid: true}++// deliveryInstallationID is the bot the turn's delivery row names: the+// binding's when the rig set one, else the installation the rig filed, else+// rigInstallationID.+func (f *fakeOutboundQueries) deliveryInstallationID() pgtype.UUID {+ switch {+ case f.sessionBinding.InstallationID.Valid:+ return f.sessionBinding.InstallationID+ case f.installation.ID.Valid:+ return f.installation.ID+ }+ return rigInstallationID+}++// GetChannelInstallation answers BY ID, because production does — and the+// reply write guard asks it about whichever bot a frame is about to go out on.+//+// The delivery row's bot is the installation the rig filed. A bot a member+// binding was found on is active: both binding lookups join on ci.status =+// 'active' (queries/channel.sql), so production cannot hand back a binding on+// any other kind. Every other id has no row.+func (f *fakeOutboundQueries) GetChannelInstallation(_ context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ if f.installErr != nil {+ return db.ChannelInstallation{}, f.installErr+ }+ switch {+ case arg.ID == f.deliveryInstallationID():+ inst := f.installation+ inst.ID = arg.ID+ return inst, nil+ case arg.ID.Valid && (arg.ID == f.memberBinding.InstallationID || arg.ID == f.agentMemberBinding.InstallationID):+ return db.ChannelInstallation{ID: arg.ID, Status: string(InstallationActive)}, nil+ }+ return db.ChannelInstallation{}, pgx.ErrNoRows}func (f *fakeOutboundQueries) FindChannelBindingForMember(context.Context, db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error) {return f.memberBinding, f.memberErrdiff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.goindex b8d0e07f77..84cae65c44 100644--- a/server/internal/integrations/wecom/relay_outbound.go+++ b/server/internal/integrations/wecom/relay_outbound.go@@ -1553,7 +1553,18 @@ func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResult// that was going to close the bubble is what the room gets instead — the// same substitution the local path makes (outbound.go).if hasVisibleChar(text) && !spoke {- if err := sender.sendTextCtx(ctx, f.ChatID, f.ChatType, text); err != nil {+ if err := sender.sendTextCtx(guardReply(ctx, o.q, instID), f.ChatID, f.ChatType, text); err != nil {+ if f.Kind == relayKindReply && errors.Is(err, errInstallationGone) && !errors.Is(err, errPartiallySent) {+ // Revoked while the reply waited. Final, unlike the other+ // refusals that precede the write: no replica may write it, so+ // another offer would only walk the retry chain and come back+ // as no_live_connection. An inbox push takes the ordinary+ // route below — the publisher offers a proven miss to the+ // member's other bot, which is still the right place for it.+ return relayResult{outcome: outcomeDone, record: func() {+ o.skippedFor(ctx, f.SessionID, skipInstallationInactive)+ }}+ }// WHETHER THIS FRAME IS FINISHED IS SETTLED BEFORE ANY COUNTER// MOVES. A frame that is owed another offer is still in flight,// and counting it here counts it once per attempt: the dispatcherdiff --git a/server/internal/integrations/wecom/relay_relayed_send_test.go b/server/internal/integrations/wecom/relay_relayed_send_test.goindex 5dda6d8d41..271ee5f41b 100644--- a/server/internal/integrations/wecom/relay_relayed_send_test.go+++ b/server/internal/integrations/wecom/relay_relayed_send_test.go@@ -27,6 +27,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// ---------------------------------------------------------------------------@@ -177,7 +178,10 @@ func newRelaySendRigWithConfig(t *testing.T, failOn func(n int) bool, dedupe Dedreg.set(instID, conn.newSender())mx := newCountingMetrics()- o := NewOutbound(&fakeOutboundQueries{}, reg, nil, testLogger(), WithOutboundMetrics(mx))+ // The bot the frame names was live when the publisher addressed it, and+ // still is: the write guard asks.+ q := &fakeOutboundQueries{installation: db.ChannelInstallation{ID: instID, Status: string(InstallationActive)}}+ o := NewOutbound(q, reg, nil, testLogger(), WithOutboundMetrics(mx))o.spawn = func(f func()) { f() }// No dedupe store: that is the single-replica claim gate, and it leaves thediff --git a/server/internal/integrations/wecom/reply_revocation_test.go b/server/internal/integrations/wecom/reply_revocation_test.gonew file mode 100644index 0000000000..d39f43e60c--- /dev/null+++ b/server/internal/integrations/wecom/reply_revocation_test.go@@ -0,0 +1,433 @@+package wecom++// reply_revocation_test.go — a reply whose installation is revoked, or whose+// permission cannot be read, while the reply waits for its turn on the socket.+//+// The rule is attachment_revocation_test.go's, applied to words: once the+// permission is gone, nothing more of the reply is written — not the message,+// not the closing frame of its bubble, not the notice a failed run leaves.+// The address was read before the chat's turn and the writer's; each test+// holds the writer, changes the permission while the frame waits for it, lets+// it go, and counts what reached the socket.+//+// What separates the two ways of losing it is the outcome. Revoked is a reply+// nobody is owed (skipInstallationInactive). Unreadable is a lookup that failed+// ahead of the write: a drop on the direct path, another offer on the relay.++import (+ "context"+ "errors"+ "sync/atomic"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// replyRevocationRig is one chat on one installation, with a turn asked over+// WeCom and no bubble: the answer goes out as a plain message.+type replyRevocationRig struct {+ o *Outbound+ q *revocableQueries+ conn *mediaConn+ sender *wsSender+ mx *countingMetrics+}++func newReplyRevocationRig(t *testing.T) *replyRevocationRig {+ t.Helper()+ id := mustTestUUID(t)+ inner := &fakeOutboundQueries{+ sessionBinding: db.ChannelChatSessionBinding{InstallationID: id, ChannelChatID: "CHAT_1", ChatType: "group"},+ installation: db.ChannelInstallation{ID: id, Status: string(InstallationActive)},+ channelIngested: askedOverWecom(),+ }+ inner.fileTask(t, testTaskID)+ r := &replyRevocationRig{+ q: &revocableQueries{fakeOutboundQueries: inner, id: id},+ conn: newMediaConn(),+ mx: newCountingMetrics(),+ }+ r.sender = r.conn.newSender()+ reg := newSendersRegistry()+ reg.set(id, r.sender)+ r.o = NewOutbound(r.q, reg, nil, testLogger(), WithOutboundMetrics(r.mx))+ r.o.spawn = func(f func()) { f() }+ return r+}++// whileTheWriterIsHeld runs send with the socket's writer taken, lets it reach+// the wait, applies change, and frees the writer. It returns once send has.+func whileTheWriterIsHeld(t *testing.T, sender *wsSender, send func(), change func()) {+ t.Helper()+ if err := sender.lockWriter(context.Background()); err != nil {+ t.Fatal(err)+ }+ done := make(chan struct{})+ go func() {+ defer close(done)+ send()+ }()+ settle() // the frame is now parked on the writer+ change()+ sender.unlockWriter()+ select {+ case <-done:+ case <-time.After(10 * time.Second):+ t.Fatal("the send never returned")+ }+}++// The answer was addressed while the installation was live, and waits for the+// writer while it is revoked. It must not go, and it is not a failed delivery:+// the same skip the address lookup files when the revocation came first.+//+// REVERSE VERIFICATION: drop guardReply from sendAsMessage's sendTextCtx and+// this fails with the answer on the wire and counted delivered.+func TestAnAnswerQueuedForTheWriterIsNotSentAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newReplyRevocationRig(t)+ var err error+ whileTheWriterIsHeld(t, r.sender,+ func() { err = r.o.processEvent(context.Background(), chatDoneEvent("the answer")) },+ func() { r.q.revoked.Store(true) })++ if err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Fatalf("%d send frames, want 0: the answer went out after the revoke", n)+ }+ if got := r.mx.get("outbound_skipped:" + string(skipInstallationInactive)); got != 1 {+ t.Errorf("outbound_skipped:installation_inactive = %d, want 1", got)+ }+ if got := r.mx.get("outbound_delivered") + r.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("delivered+dropped = %d, want 0: a revoked installation is not owed the reply", got)+ }+}++// The same wait, but the permission read fails instead. Nothing goes either,+// and this time it is a drop: the reply was owed and was not delivered.+func TestAnAnswerWhosePermissionCannotBeReadIsNotSent(t *testing.T) {+ t.Parallel()+ r := newReplyRevocationRig(t)+ var err error+ whileTheWriterIsHeld(t, r.sender,+ func() { err = r.o.processEvent(context.Background(), chatDoneEvent("the answer")) },+ func() { r.q.unreadable.Store(true) })++ if err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Fatalf("%d send frames, want 0", n)+ }+ if got := r.mx.get("outbound_dropped:" + string(dropTransport)); got != 1 {+ t.Errorf("outbound_dropped:transport_error = %d, want 1", got)+ }+ if got := r.mx.get("outbound_skipped"); got != 0 {+ t.Errorf("outbound_skipped = %d, want 0: an unreadable permission is not a revocation", got)+ }+}++// A long answer goes out in pieces, and the guard asks before each. Revoked+// after the first piece, the rest stays unsent; the first is on the reader's+// screen, so the reply counts as delivered — the partial-send rule.+func TestALongAnswerRevokedAfterItsFirstPieceStopsThere(t *testing.T) {+ t.Parallel()+ r := newReplyRevocationRig(t)+ r.conn.onWrite = func(cmd string) {+ if cmd == cmdSendMsg {+ r.q.revoked.Store(true)+ }+ }+ long := longAnswerOfPieces(t, 3)++ if err := r.o.processEvent(context.Background(), chatDoneEvent(long)); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 1 {+ t.Fatalf("%d send frames, want 1: pieces kept going after the revoke", n)+ }+ if got := r.mx.get("outbound_delivered"); got != 1 {+ t.Errorf("outbound_delivered = %d, want 1: the first piece is on screen", got)+ }+ if got := r.mx.get("outbound_skipped"); got != 0 {+ t.Errorf("outbound_skipped = %d, want 0: part of the answer did land", got)+ }+}++// longAnswerOfPieces builds an answer splitForWire cuts into n pieces.+func longAnswerOfPieces(t *testing.T, n int) string {+ t.Helper()+ line := "a line of the answer that is long enough to add up\n"+ text := ""+ for len(splitForWire(text)) < n {+ text += line+ }+ return text+}++// A reply routed from another replica waits for the writer on the one that+// holds the socket, and is revoked there. The frame is finished — no replica+// may write it, so another offer would only walk the retry chain — and it is+// recorded as the skip, not as a drop.+//+// REVERSE VERIFICATION: drop guardReply from deliverRelayed's sendTextCtx and+// this fails with the reply on the wire.+func TestARelayedReplyQueuedForTheWriterIsNotSentAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newReplyRevocationRig(t)+ var res relayResult+ whileTheWriterIsHeld(t, r.sender,+ func() { res = r.o.deliverRelayed(context.Background(), r.relayedReply()) },+ func() { r.q.revoked.Store(true) })++ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Fatalf("%d send frames, want 0: the relayed reply went out after the revoke", n)+ }+ if res.outcome != outcomeDone {+ t.Fatalf("outcome = %v, want outcomeDone: a revoked installation will not take the frame on any replica", res.outcome)+ }+ if res.record == nil {+ t.Fatal("no record: the skip would go uncounted")+ }+ res.record()+ if got := r.mx.get("outbound_skipped:" + string(skipInstallationInactive)); got != 1 {+ t.Errorf("outbound_skipped:installation_inactive = %d, want 1", got)+ }+ if got := r.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("outbound_dropped = %d, want 0", got)+ }+}++// Unreadable on the relay is one more offer: the reply is still owed, and still+// the only copy.+func TestARelayedReplyWhosePermissionCannotBeReadIsOfferedAgain(t *testing.T) {+ t.Parallel()+ r := newReplyRevocationRig(t)+ var res relayResult+ whileTheWriterIsHeld(t, r.sender,+ func() { res = r.o.deliverRelayed(context.Background(), r.relayedReply()) },+ func() { r.q.unreadable.Store(true) })++ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Fatalf("%d send frames, want 0", n)+ }+ if res.outcome != outcomeProvablyNotSent {+ t.Fatalf("outcome = %v, want outcomeProvablyNotSent", res.outcome)+ }+}++func (r *replyRevocationRig) relayedReply() relayFrame {+ return relayFrame{+ Kind: relayKindReply,+ InstallationID: util.UUIDToString(r.q.id),+ ChatID: "CHAT_1",+ ChatType: chatTypeGroupInt,+ Content: "the answer",+ TaskID: testTaskID,+ SessionID: testSessionID,+ }+}++// An inbox push to a member's bot waits for the writer and the bot is revoked.+// Nothing goes, and it is a proven miss: the caller may offer the push to the+// member's other bot, which the binding lookup only returns when it is active.+//+// REVERSE VERIFICATION: drop guardReply from pushInbox and this fails with the+// push on the wire.+func TestAnInboxPushQueuedForTheWriterIsNotSentAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newReplyRevocationRig(t)+ binding := db.ChannelUserBinding{InstallationID: r.q.id, ChannelUserID: "USER_1"}+ var delivered, provenMiss bool+ whileTheWriterIsHeld(t, r.sender,+ func() {+ delivered, provenMiss = r.o.pushInbox(context.Background(),+ map[string]any{"id": "ITEM_1", "type": "mention"}, binding, "RECIPIENT", "a notification", false)+ },+ func() { r.q.revoked.Store(true) })++ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Fatalf("%d send frames, want 0: the push went out after the revoke", n)+ }+ if delivered || !provenMiss {+ t.Fatalf("delivered=%v provenMiss=%v, want false/true: nothing left the process", delivered, provenMiss)+ }+}++// revocableBubbleRig is a bubbleRig whose installation can be revoked or made+// unreadable mid-flight, on both halves: the outbound subscriber that closes a+// bubble with the answer and the typing manager that closes it with a notice.+type revocableBubbleRig struct {+ *bubbleRig+ rq *revocableQueries+ mx *countingMetrics+}++func newRevocableBubbleRig(t *testing.T) *revocableBubbleRig {+ t.Helper()+ rig := newBubbleRig(t)+ rq := &revocableQueries{fakeOutboundQueries: rig.q, id: rig.instID}+ mx := newCountingMetrics()+ rig.out = NewOutbound(rq, rig.senders, rig.streams, nil, WithOutboundMetrics(mx))+ rig.typing = NewTypingIndicator(TypingIndicatorConfig{+ Senders: rig.senders, Streams: rig.streams, Tasks: rig.q, Deliveries: rq,+ })+ rig.bus = events.New()+ rig.typing.Register(rig.bus)+ return &revocableBubbleRig{bubbleRig: rig, rq: rq, mx: mx}+}++func (r *revocableBubbleRig) closingFrames(t *testing.T) int {+ t.Helper()+ n := 0+ for _, f := range r.conn.streamFrames(t) {+ if f["finish"] == true {+ n+++ }+ }+ return n+}++func (r *revocableBubbleRig) answerEvent(t *testing.T, taskName, content string) events.Event {+ return events.Event{+ ChatSessionID: bubbleSession,+ TaskID: taskUUID(t, taskName),+ Payload: protocol.ChatDonePayload{Content: content},+ }+}++// The bubble was painted while the installation was live. The answer's closing+// frame waits for the writer and the installation is revoked: no closing+// frame, and no plain message in its place either.+//+// REVERSE VERIFICATION: remove the guard from writeStreamFrame and this fails+// with the answer in the bubble.+func TestABubblesClosingFrameIsNotWrittenAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newRevocableBubbleRig(t)+ r.ran(t, "REQ-1", "task-1")+ var err error+ whileTheWriterIsHeld(t, r.senders.get(r.instID),+ func() { err = r.out.processEvent(context.Background(), r.answerEvent(t, "task-1", "the answer")) },+ func() { r.rq.revoked.Store(true) })++ if err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if n := r.closingFrames(t); n != 0 {+ t.Fatalf("%d closing frames, want 0: the bubble was closed with the answer after the revoke", n)+ }+ if n := len(r.conn.pushes(t)); n != 0 {+ t.Fatalf("%d plain messages, want 0: the fallback went out after the revoke", n)+ }+ if got := r.mx.get("outbound_skipped:" + string(skipInstallationInactive)); got != 1 {+ t.Errorf("outbound_skipped:installation_inactive = %d, want 1", got)+ }+}++// A failed run's notice closes the bubble from the typing manager. Revoked+// while the notice waits: neither the closing frame nor the fallback message.+//+// REVERSE VERIFICATION: drop guardReply from writeClosing and this fails with+// the notice in the bubble.+func TestAFailedRunsNoticeIsNotWrittenAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newRevocableBubbleRig(t)+ r.ran(t, "REQ-1", "task-1")+ whileTheWriterIsHeld(t, r.senders.get(r.instID),+ func() { r.failed(t, "task-1", false) },+ func() { r.rq.revoked.Store(true) })++ if n := r.closingFrames(t); n != 0 {+ t.Fatalf("%d closing frames, want 0: the failure notice closed the bubble after the revoke", n)+ }+ if n := len(r.conn.pushes(t)); n != 0 {+ t.Fatalf("%d plain messages, want 0", n)+ }+}++// A run's ending said as a plain message — the round has no bubble — waits for+// the writer and is revoked.+//+// REVERSE VERIFICATION: drop guardReply from sayAsPlainMessage and this fails+// with the ending on the wire.+func TestARunsEndingSaidAsAMessageIsNotSentAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newRevocableBubbleRig(t)+ addr := roundAddress{InstallationID: r.instID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt}+ var err error+ whileTheWriterIsHeld(t, r.senders.get(r.instID),+ func() {+ err = r.typing.sayAsPlainMessage(context.Background(), bubbleSessionID(t), addr, taskUUID(t, "task-1"), "the run failed")+ },+ func() { r.rq.revoked.Store(true) })++ if !errors.Is(err, errInstallationGone) {+ t.Fatalf("err = %v, want errInstallationGone", err)+ }+ if n := len(r.conn.pushes(t)); n != 0 {+ t.Fatalf("%d plain messages, want 0", n)+ }+}++// blippingQueries answers the installation as active, except for the reads+// the test arms to fail — a database that drops one query and answers the next.+type blippingQueries struct {+ *fakeOutboundQueries+ id pgtype.UUID+ failures atomic.Int32+}++func (b *blippingQueries) GetChannelInstallation(_ context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ if b.failures.Add(-1) >= 0 {+ return db.ChannelInstallation{}, errors.New("wecom test: one query dropped")+ }+ if arg.ID != b.id {+ return db.ChannelInstallation{}, errors.New("wecom test: asked about another installation")+ }+ return db.ChannelInstallation{ID: b.id, Status: string(InstallationActive)}, nil+}++// The closing frame goes out and its ack is lost. Before the retry, one+// permission read fails, so the retry is refused unwritten. That refusal says+// nothing about the first frame, which may be on screen: the ending is+// unknown, and the answer must not follow as a plain message — the next read+// succeeds, so nothing else would stop it.+//+// REVERSE VERIFICATION: take the retry's error in streamStore.seal whatever it+// is, and this fails with the answer sent a second time as a message.+func TestARetryRefusedUnwrittenLeavesTheClosingFrameUnknown(t *testing.T) {+ t.Parallel()+ rig, mx := retryRig(t)+ bq := &blippingQueries{fakeOutboundQueries: rig.q, id: rig.instID}+ rig.out = NewOutbound(bq, rig.senders, rig.streams, nil, WithOutboundMetrics(mx))+ rig.ran(t, "REQ-BLIP", "task-1")+ rig.conn.loseClosingAcks = 1+ rig.conn.onClosing = func() { bq.failures.Store(1) }++ rig.answer(t, "the agent reply", "task-1")++ closing := 0+ for _, f := range rig.conn.streamFrames(t) {+ if f["finish"] == true {+ closing+++ }+ }+ if closing != 1 {+ t.Fatalf("%d closing frames, want 1: the refused retry wrote nothing", closing)+ }+ if n := len(rig.conn.pushes(t)); n != 0 {+ t.Fatalf("the answer also went out as %d plain message(s); the user may read it twice", n)+ }+ if got := mx.get("outbound_unconfirmed"); got != 1 {+ t.Errorf("outbound_unconfirmed = %d, want 1", got)+ }+}diff --git a/server/internal/integrations/wecom/stream_store.go b/server/internal/integrations/wecom/stream_store.goindex 4da94764ac..293d1bfbbd 100644--- a/server/internal/integrations/wecom/stream_store.go+++ b/server/internal/integrations/wecom/stream_store.go@@ -948,7 +948,15 @@ func (s *streamStore) seal(ctx context.Context, senders *sendersRegistry, h streif attempt == 0 {err = senders.stream(ctx, h, text, true)} else {- err = senders.streamRewrite(ctx, h, text, true)+ retryErr := senders.streamRewrite(ctx, h, text, true)+ if provablyNotSent(retryErr) {+ // A retry that wrote nothing says nothing about the frame before+ // it, which reached the socket and was never answered. Keep that+ // reading: taking the retry's would call the bubble provably+ // empty and send its words again as a message.+ break+ }+ err = retryErr}if !errors.Is(err, errStreamAckTimeout) || attempt >= streamCloseRetries {breakdiff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.goindex de8bbb90fd..2f6701b83a 100644--- a/server/internal/integrations/wecom/typing_indicator.go+++ b/server/internal/integrations/wecom/typing_indicator.go@@ -761,7 +761,13 @@ func (m *TypingIndicatorManager) sayAsPlainMessage(ctx context.Context, sessionIreturn nil}}- err := m.senders.sendTextCtx(ctx, addr.InstallationID, addr.ChatID, addr.ChatType, text)+ err := m.senders.sendTextCtx(guardReply(ctx, m.deliveries, addr.InstallationID), addr.InstallationID, addr.ChatID, addr.ChatType, text)+ if errors.Is(err, errInstallationGone) && !errors.Is(err, errPartiallySent) {+ m.log.InfoContext(ctx, "wecom typing: a run's ending not said, installation revoked",+ "chat_session_id", util.UUIDToString(sessionID),+ "installation_id", util.UUIDToString(addr.InstallationID))+ return err+ }if err != nil {m.log.WarnContext(ctx, "wecom typing: could not deliver a run's ending","chat_session_id", util.UUIDToString(sessionID),@@ -897,7 +903,15 @@ func taskIDFromEvent(e events.Event) string {// handle, captured at ingest, because by now the binding row may point at a// different chat.func (m *TypingIndicatorManager) writeClosing(ctx context.Context, sessionID pgtype.UUID, h streamHandle, text, why string) {+ // The bubble was painted while the installation was live. Whether it may+ // still be written is asked of each frame, the seal's and the fallback's.+ ctx = guardReply(ctx, m.deliveries, h.InstallationID)err := m.streams.seal(ctx, m.senders, h, text)+ if errors.Is(err, errInstallationGone) {+ m.log.InfoContext(ctx, "wecom typing: bubble left open, installation revoked",+ "chat_session_id", util.UUIDToString(sessionID), "reason", why)+ return+ }switch classifySeal(err) {case sealOnScreen:returndiff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.goindex 1cee08ccdc..cee7bced98 100644--- a/server/internal/integrations/wecom/ws_sender.go+++ b/server/internal/integrations/wecom/ws_sender.go@@ -985,8 +985,9 @@ type writeGuardKey struct{}// ctx that carries none behaves exactly as before.//// It covers what goes through request — the upload steps and aibot_send_msg,-// text or media. Stream frames take their own path (writeStreamFrame) and do-// not consult it; nothing puts a guard on those today.+// text or media — and stream frames (writeStreamFrame), which is how the+// closing frame of a bubble is held to the same check as the message it would+// otherwise fall back to.//// The guard runs while the writer is held, so it must be quick: whatever it// waits for, the ping loop and every other send on this socket wait for too.@@ -1018,6 +1019,13 @@ func (s *wsSender) writeStreamFrame(ctx context.Context, reqID, streamID string,return err}defer s.unlockWriter()+ // Ahead of beginStreamFrameLocked: a frame the guard refuses never takes+ // the turn's place, so there is nothing to give back.+ if guard := writeGuardFrom(ctx); guard != nil {+ if err := guard(ctx); err != nil {+ return fmt.Errorf("%w: %w", errNotAttempted, err)+ }+ }if !s.beginStreamFrameLocked(reqID, streamID, w, finish) {return errStreamSuperseded}