Skip to content

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

Go

fix(wecom): send a long answer in pieces instead of losing it (#8344)

Xichang(Seacen) Zhao51e4aef22e99
diff --git a/server/internal/integrations/wecom/long_reply_test.go b/server/internal/integrations/wecom/long_reply_test.go
new file mode 100644
index 0000000000..2e3efb01e4
--- /dev/null
+++ b/server/internal/integrations/wecom/long_reply_test.go
@@ -0,0 +1,827 @@
+package wecom
+
+// long_reply_test.go — what happens to an answer longer than one WeCom
+// message.
+//
+// aibot caps a single body at 20480 utf8 bytes and refuses anything past it
+// WHOLE: it does not clip, it answers 45002 and writes nothing. So a long
+// answer used to reach the person in one of two ways, both of them bad. Down
+// the plain path it never arrived at all — the frame was refused and the only
+// record was a log line. Into a streaming bubble it arrived clipped, ending in
+// an ellipsis, with no way to read the rest of it anywhere: WeCom has no edit
+// and no unsend, and the tail of a code review or a pasted log is not filler.
+//
+// The invariant these tests hold the code to is the person's, not the wire's:
+// whatever the agent wrote, the person can read all of it in the chat. How
+// many messages that takes is an implementation detail; losing any of it is
+// the defect.
+
+import (
+ "context"
+ "encoding/json"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// capEnforcingConn is the server's own rule: a markdown body past the cap is
+// refused with 45002 and never written into the chat. Modelling the refusal
+// rather than just recording the write is the point — delivered() returns what
+// the person can actually read, so a test cannot pass by writing a frame
+// nobody ever saw.
+type capEnforcingConn struct {
+ mu sync.Mutex
+ frames []frameEnvelope
+ seen []string // contents of the frames the server accepted
+ sender *wsSender
+}
+
+func (c *capEnforcingConn) WriteMessage(_ int, data []byte) error {
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err != nil {
+ return err
+ }
+ content := markdownContentOf(env)
+ code, msg := 0, ""
+ if len(content) > sendMsgContentLimit {
+ code, msg = 45002, "content exceed max length"
+ }
+ c.mu.Lock()
+ c.frames = append(c.frames, env)
+ if code == 0 && env.Cmd == cmdSendMsg {
+ c.seen = append(c.seen, content)
+ }
+ s := c.sender
+ c.mu.Unlock()
+ if s != nil {
+ s.routeResponse(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}, ErrCode: code, ErrMsg: msg})
+ }
+ return nil
+}
+
+func (c *capEnforcingConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
+func (c *capEnforcingConn) SetReadDeadline(time.Time) error { return nil }
+func (c *capEnforcingConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *capEnforcingConn) Close() error { return nil }
+
+// delivered is everything the person can read, in the order it arrived.
+func (c *capEnforcingConn) delivered() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]string{}, c.seen...)
+}
+
+// markdownContentOf pulls the body text out of an aibot_send_msg frame.
+func markdownContentOf(env frameEnvelope) string {
+ if env.Cmd != cmdSendMsg {
+ return ""
+ }
+ var body map[string]any
+ if json.Unmarshal(env.Body, &body) != nil {
+ return ""
+ }
+ md, _ := body["markdown"].(map[string]any)
+ if md == nil {
+ return ""
+ }
+ s, _ := md["content"].(string)
+ return s
+}
+
+// sendMsgLabel is what one aibot_send_msg put in front of the reader: the
+// markdown body for text, and "<msgtype> <media_id>" for a file. Both go out
+// on the same push, so a test of the ORDER of what the reader sees has to hold
+// both — a wire record that keeps only the text cannot tell whether a picture
+// landed in the middle of an answer.
+func sendMsgLabel(env frameEnvelope) string {
+ if env.Cmd != cmdSendMsg {
+ return ""
+ }
+ if md := markdownContentOf(env); md != "" {
+ return md
+ }
+ var body map[string]any
+ if json.Unmarshal(env.Body, &body) != nil {
+ return ""
+ }
+ kind, _ := body["msgtype"].(string)
+ nested, _ := body[kind].(map[string]any)
+ if nested == nil {
+ return kind
+ }
+ id, _ := nested["media_id"].(string)
+ return kind + " " + id
+}
+
+// pieceMarker is the continuation counter splitForWire appends. It is stripped
+// before reassembly because it is the adapter's word, not the agent's.
+var pieceMarker = regexp.MustCompile(`\n\n\(\d+/\d+\)$`)
+
+func reassemble(pieces []string) string {
+ var b strings.Builder
+ for _, p := range pieces {
+ b.WriteString(pieceMarker.ReplaceAllString(p, ""))
+ }
+ return b.String()
+}
+
+// aLongAnswer is a body over two frames' worth with no line breaks in it, so
+// the split falls on a rune boundary and reassembly is byte-exact. Multi-byte
+// runes on purpose: a cut through one would corrupt the text either side of it.
+func aLongAnswer() string {
+ return strings.Repeat("答案很长,这是第一段。", sendMsgContentLimit/10)
+}
+
+// TestALongAnswerReachesTheChatWhole is the plain path — no bubble, the way
+// every reply arrived before streaming and the way one still arrives when the
+// bubble is gone. WeCom refuses the oversized frame outright, so without a
+// split the person asks a question and gets nothing back at all.
+
+// TestALongAnswerReachesTheChatWhole is the plain path — no bubble, the way
+// every reply arrived before streaming and the way one still arrives when the
+// bubble is gone. WeCom refuses the oversized frame outright, so without a
+// split the person asks a question and gets nothing back at all.
+func TestALongAnswerReachesTheChatWhole(t *testing.T) {
+ t.Parallel()
+ conn := &capEnforcingConn{}
+ sender := newWSSender(conn, nil)
+ conn.sender = sender
+
+ answer := aLongAnswer()
+ if err := sender.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, answer); err != nil {
+ t.Fatalf("sending a %d-byte answer failed: %v", len(answer), err)
+ }
+
+ got := conn.delivered()
+ if len(got) == 0 {
+ t.Fatalf("a %d-byte answer produced nothing the person can read: WeCom refuses a body past %d bytes "+
+ "whole, so the question went unanswered and the only record is a log line",
+ len(answer), sendMsgContentLimit)
+ }
+ for i, piece := range got {
+ if len(piece) > sendMsgContentLimit {
+ t.Fatalf("piece %d is %d bytes, past the %d-byte cap the server refuses — including its own continuation marker",
+ i+1, len(piece), sendMsgContentLimit)
+ }
+ }
+ if whole := reassemble(got); whole != answer {
+ t.Fatalf("the person can read %d bytes of a %d-byte answer; %d bytes of what the agent wrote never reached the chat",
+ len(whole), len(answer), len(answer)-len(whole))
+ }
+}
+
+// TestAShortAnswerIsUntouched: splitting must cost the ordinary reply nothing —
+// no extra frame, and above all no counter appended to an answer that is one
+// message long.
+func TestAShortAnswerIsUntouched(t *testing.T) {
+ t.Parallel()
+ conn := &capEnforcingConn{}
+ sender := newWSSender(conn, nil)
+ conn.sender = sender
+
+ const answer = "答案是 42"
+ if err := sender.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, answer); err != nil {
+ t.Fatalf("sendTextCtx: %v", err)
+ }
+ got := conn.delivered()
+ if len(got) != 1 || got[0] != answer {
+ t.Fatalf("a short answer went out as %q, want exactly [%q]", got, answer)
+ }
+}
+
+// TestEachPieceSaysTheAnswerContinues: the reader has to know a message is
+// part of something longer, or they read the first piece as the whole answer
+// and act on half of it. The counter belongs to no language on purpose — it
+// needs no translation, and it cannot contradict an answer written in one.
+func TestEachPieceSaysTheAnswerContinues(t *testing.T) {
+ t.Parallel()
+ pieces := splitForWire(aLongAnswer())
+ if len(pieces) < 2 {
+ t.Fatalf("the fixture did not split: %d piece(s)", len(pieces))
+ }
+ for i, p := range pieces[:len(pieces)-1] {
+ want := "\n\n(" + strconv.Itoa(i+1) + "/" + strconv.Itoa(len(pieces)) + ")"
+ if !strings.HasSuffix(p, want) {
+ t.Fatalf("piece %d does not end in %q, so the reader has nothing telling them the answer continues; it ends %q",
+ i+1, want, tail(p, 12))
+ }
+ }
+ if last := pieces[len(pieces)-1]; pieceMarker.MatchString(last) {
+ t.Fatalf("the final piece carries a continuation marker (%q), which promises more that never comes", tail(last, 12))
+ }
+}
+
+// TestAPieceNeverEndsMidCharacter: a cut through a multi-byte rune shows up in
+// the chat as a replacement glyph on both sides of the seam.
+func TestAPieceNeverEndsMidCharacter(t *testing.T) {
+ t.Parallel()
+ for i, p := range splitForWire(aLongAnswer()) {
+ if !utf8.ValidString(p) {
+ t.Fatalf("piece %d is not valid utf8 — the cut went through a character, "+
+ "and the reader sees a replacement glyph on both sides of the seam", i+1)
+ }
+ }
+}
+
+// TestTheCutPrefersALineBoundary: a long answer is usually a log or a code
+// block, and a piece that ends mid-line reads far worse than one that ends
+// where the text already ended. The preference is bounded — a break near the
+// start of the budget would waste most of a message.
+func TestTheCutPrefersALineBoundary(t *testing.T) {
+ t.Parallel()
+ line := strings.Repeat("x", 79) + "\n"
+ pieces := splitForWire(strings.Repeat(line, sendMsgContentLimit/len(line)*2+40))
+ if len(pieces) < 2 {
+ t.Fatalf("the fixture did not split: %d piece(s)", len(pieces))
+ }
+ for i, p := range pieces[:len(pieces)-1] {
+ body := pieceMarker.ReplaceAllString(p, "")
+ // The break that ended the last line stays with it, so a piece cut at
+ // a line boundary ends in one. Splitting on it would leave an empty
+ // final element that is not a short line.
+ if !strings.HasSuffix(body, "\n") {
+ t.Fatalf("piece %d ends %q, want the line break that ended its last line", i+1, tail(body, 12))
+ }
+ for j, got := range strings.Split(strings.TrimSuffix(body, "\n"), "\n") {
+ if len(got) != len(line)-1 {
+ t.Fatalf("piece %d line %d is %d characters of a %d-character line — the cut fell mid-line",
+ i+1, j+1, len(got), len(line)-1)
+ }
+ }
+ }
+}
+
+func tail(s string, n int) string {
+ if len(s) <= n {
+ return s
+ }
+ return s[len(s)-n:]
+}
+
+// aLongAnswerWithLineBreaks is the fixture the line-boundary branch needs: the
+// cut lands on a '\n' rather than a rune boundary, and the text carries the
+// three things a seam can eat — a single newline, a run of them, and multi-byte
+// runes either side.
+//
+// Built so the breaks fall at irregular distances: a fixture whose lines are
+// all the same length can put every cut in the same relative position and miss
+// the case where the chosen break is the last byte of the budget.
+func aLongAnswerWithLineBreaks() string {
+ var b strings.Builder
+ for i := 0; b.Len() < sendMsgContentLimit*2+500; i++ {
+ switch i % 7 {
+ case 0:
+ b.WriteString("第一行,带一个换行\n")
+ case 3:
+ // A blank line: two breaks in a row, which is what a paragraph
+ // boundary in a pasted log looks like.
+ b.WriteString("一段结束\n\n")
+ case 5:
+ // No break at all, so some cuts still fall on a rune boundary.
+ b.WriteString(strings.Repeat("连续文字没有换行", 40))
+ default:
+ b.WriteString("普通的一行,长度不一样一点点\n")
+ }
+ }
+ return b.String()
+}
+
+// Every byte the agent wrote comes back, including the line breaks at the
+// seams. This is the invariant this file's header states, and it is the one
+// the first version of the split broke: wireCutPoint returned the index OF the
+// newline and splitForWire then trimmed leading newlines from the same index,
+// so one break vanished at every cut — worst on pasted logs and code, which is
+// the content the split exists for.
+//
+// REVERSE VERIFICATION: return nl instead of nl+1 from wireCutPoint, or put
+// strings.TrimLeft(remaining[cut:], "\n") back, and this fails with the
+// reassembled answer shorter than the original by one byte per seam.
+func TestReassemblingThePiecesGivesBackEveryByte(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ body string
+ }{
+ {"line breaks, blank lines and multi-byte runes", aLongAnswerWithLineBreaks()},
+ {"no line breaks at all", aLongAnswer()},
+ {"a single break right at the budget", strings.Repeat("字", sendMsgContentLimit/3) + "\n" + strings.Repeat("字", sendMsgContentLimit)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ pieces := splitForWire(tc.body)
+ if len(pieces) < 2 {
+ t.Fatalf("fixture produced %d piece(s); it is not exercising the split", len(pieces))
+ }
+ got := reassemble(pieces)
+ if got == tc.body {
+ return
+ }
+ // Report where they part company rather than dumping 40KB.
+ n := 0
+ for n < len(got) && n < len(tc.body) && got[n] == tc.body[n] {
+ n++
+ }
+ t.Fatalf("reassembled %d bytes from %d pieces, want the original %d — they part at byte %d: original has %q, reassembly has %q",
+ len(got), len(pieces), len(tc.body), n,
+ safeWindow(tc.body, n), safeWindow(got, n))
+ })
+ }
+}
+
+// safeWindow is a short excerpt around i, for a failure message that has to be
+// readable when the fixture is tens of kilobytes.
+func safeWindow(s string, i int) string {
+ lo, hi := i-12, i+12
+ if lo < 0 {
+ lo = 0
+ }
+ if hi > len(s) {
+ hi = len(s)
+ }
+ return s[lo:hi]
+}
+
+// Each piece still has to fit the wire. The reassembly test above would pass
+// against a split that emitted the whole answer as one oversized piece, which
+// is the failure the platform refuses with 45002.
+func TestEveryPieceFitsTheWireLimit(t *testing.T) {
+ t.Parallel()
+ for _, body := range []string{aLongAnswerWithLineBreaks(), aLongAnswer()} {
+ for i, p := range splitForWire(body) {
+ if len(p) > sendMsgContentLimit {
+ t.Fatalf("piece %d is %d bytes, over the %d the server takes", i+1, len(p), sendMsgContentLimit)
+ }
+ }
+ }
+}
+
+// Keeping every byte says nothing about WHICH side of the seam a line break
+// lands on, and the two are not equally readable: a piece that opens with the
+// break that ended the previous piece's last line renders as a blank first
+// line, which looks like the message lost something. The break belongs to the
+// line it terminated, so the cut goes after it.
+//
+// REVERSE VERIFICATION: return nl instead of nl+1 from wireCutPoint and this
+// fails with piece 2 starting "\n…".
+func TestNoPieceOpensWithTheBreakThatEndedTheLastOne(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct{ name, body string }{
+ {"line breaks, blank lines and multi-byte runes", aLongAnswerWithLineBreaks()},
+ {"a single break right at the budget", strings.Repeat("字", sendMsgContentLimit/3) + "\n" + strings.Repeat("字", sendMsgContentLimit)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ pieces := splitForWire(tc.body)
+ for i, p := range pieces[1:] {
+ if strings.HasPrefix(p, "\n") {
+ t.Fatalf("piece %d opens with %q — the break that ended piece %d fell into the gap", i+2, safeWindow(p, 0), i+1)
+ }
+ }
+ })
+ }
+}
+
+// ---------------------------------------------------------------------------
+// a partial send counts the same on both paths
+// ---------------------------------------------------------------------------
+
+// One long answer, piece one accepted and piece two refused, is one
+// user-visible event: most of the answer is in the chat and some of it is not.
+// It has to move the same counter wherever the send happened, or a partial
+// delivery pages an operator on a multi-replica deployment and passes
+// unnoticed on a single-replica one — the same reply, two verdicts, decided by
+// which replica held the socket.
+//
+// The pair below is the direct path (the replica that produced the
+// completion); the relay pair further down is the lease holder.
+//
+// REVERSE VERIFICATION: drop the errPartiallySent arm from recordSend and this
+// reports outbound_delivered = 0 with outbound_dropped = 1.
+func TestDirectPath_ARefusedSecondPieceCountsDelivered(t *testing.T) {
+ t.Parallel()
+ o, conn, mx := newPartialSendRig(t)
+ conn.refuseFromSend = 2
+
+ if err := o.processEvent(context.Background(), aLongAnswerEvent()); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+
+ if got := len(conn.sendFrames()); got < 2 {
+ t.Fatalf("the socket saw %d send frame(s); the fixture did not split", got)
+ }
+ assertPartialCounted(t, mx, "a refused second piece")
+}
+
+// The other half: the second piece's verdict never comes back. The user's
+// screen is in the same state — piece one is on it — and the same counter has
+// to move, for the same reason: the operator action an unconfirmed reply
+// invites is "resend it", and resending prints piece one twice.
+//
+// REVERSE VERIFICATION: drop the errPartiallySent arm from recordSend and this
+// reports outbound_unconfirmed = 1 with outbound_delivered = 0.
+func TestDirectPath_ALostAckOnTheSecondPieceCountsDelivered(t *testing.T) {
+ t.Parallel()
+ o, conn, mx := newPartialSendRig(t)
+ conn.swallowAckFromSend = 2
+
+ // The frame goes out and no verdict ever comes back. ackTimeout is five
+ // seconds and a test that stands still for it is a test nobody runs, so
+ // the caller's own deadline ends the wait instead — which is the same
+ // branch of request(), and the same shape of failure the outbound
+ // subscriber sees when a delivery runs out its budget mid-answer.
+ ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
+ defer cancel()
+ if err := o.processEvent(ctx, aLongAnswerEvent()); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if got := len(conn.sendFrames()); got < 2 {
+ t.Fatalf("the socket saw %d send frame(s); the second piece never reached the wire, so this is not a lost verdict", got)
+ }
+ assertPartialCounted(t, mx, "a lost ack on the second piece")
+}
+
+// newPartialSendRig is one replica that holds the socket, with counters.
+func newPartialSendRig(t *testing.T) (*Outbound, *recordingConn, *countingMetrics) {
+ t.Helper()
+ q := &fakeOutboundQueries{
+ sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1", ChatType: "group"},
+ installation: db.ChannelInstallation{Status: string(InstallationActive)},
+ channelIngested: askedOverWecom(),
+ }
+ q.fileTask(t, "33333333-3333-3333-3333-333333333333")
+ reg := newSendersRegistry()
+ instID := mustTestUUID(t)
+ conn := &recordingConn{}
+ reg.set(instID, conn.autoAck(newWSSender(conn, testLogger())))
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ mx := newCountingMetrics()
+ return NewOutbound(q, reg, testLogger(), WithOutboundMetrics(mx)), conn, mx
+}
+
+func aLongAnswerEvent() events.Event {
+ return events.Event{
+ ChatSessionID: "22222222-2222-2222-2222-222222222222",
+ Payload: protocol.ChatDonePayload{
+ Content: aLongAnswer(),
+ TaskID: "33333333-3333-3333-3333-333333333333",
+ },
+ }
+}
+
+func assertPartialCounted(t *testing.T, mx *countingMetrics, what string) {
+ t.Helper()
+ if got := mx.get("outbound_delivered"); got != 1 {
+ t.Errorf("outbound_delivered = %d, want 1 — %s still left most of the answer on the person's screen", got, what)
+ }
+ if got := mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("outbound_dropped = %d, want 0 — a drop tells an operator to resend, and a resend prints piece one twice", got)
+ }
+ if got := mx.get("outbound_unconfirmed"); got != 0 {
+ t.Errorf("outbound_unconfirmed = %d, want 0 — the delivery is not unknown; part of it is on screen", got)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// the pieces of one answer are contiguous on the wire
+// ---------------------------------------------------------------------------
+
+// slowAckConn answers every frame, after a delay, from its own goroutine —
+// which is what the real server does and what the sender's mutex does NOT
+// cover: mu orders one frame write and is released before the ack wait.
+type slowAckConn struct {
+ mu sync.Mutex
+ texts []string
+ sender *wsSender
+ delay time.Duration
+
+ // swallowFrom, when non-zero, is the 1-based aibot_send_msg from which no
+ // verdict ever comes back — a peer that took the bytes and went quiet.
+ // The frame is still recorded: it reached the wire, which is the half this
+ // models.
+ swallowFrom int
+ sends int
+}
+
+func (c *slowAckConn) WriteMessage(_ int, data []byte) error {
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err != nil {
+ return err
+ }
+ c.mu.Lock()
+ swallow := false
+ if env.Cmd == cmdSendMsg {
+ c.texts = append(c.texts, sendMsgLabel(env))
+ c.sends++
+ swallow = c.swallowFrom > 0 && c.sends >= c.swallowFrom
+ }
+ s, d := c.sender, c.delay
+ c.mu.Unlock()
+ if s != nil && !swallow {
+ go func() {
+ time.Sleep(d)
+ s.routeResponse(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}})
+ }()
+ }
+ return nil
+}
+
+func (c *slowAckConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
+func (c *slowAckConn) SetReadDeadline(time.Time) error { return nil }
+func (c *slowAckConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *slowAckConn) Close() error { return nil }
+
+func (c *slowAckConn) wire() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]string(nil), c.texts...)
+}
+
+// One long answer and one unrelated push to the same chat, started together.
+// The answer's pieces have to reach the wire as one run: a reader who finds
+// somebody else's message between "(1/3)" and "(2/3)" has no way to tell which
+// text the counters belong to, and with two long answers in flight the
+// counters cannot be matched back at all — which is worse than the status quo,
+// where a long answer simply never arrived.
+//
+// The ack delay is what makes this reproduce: the sender's mutex is released
+// before the wait, so without a per-chat lock the interloper wins the mutex
+// while piece one is still unacknowledged.
+//
+// REVERSE VERIFICATION: remove the s.chats.acquire/release pair from
+// sendTextCtx and this fails with the interloper between two pieces.
+func TestThePiecesOfOneAnswerAreContiguousOnTheWire(t *testing.T) {
+ t.Parallel()
+ conn := &slowAckConn{delay: 30 * time.Millisecond}
+ sender := newWSSender(conn, testLogger())
+ conn.sender = sender
+
+ answer := aLongAnswer()
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ if err := sender.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, answer); err != nil {
+ t.Errorf("sending the long answer: %v", err)
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ // Started a beat later so the answer is already mid-flight; without
+ // the lock this lands between two of its pieces.
+ time.Sleep(10 * time.Millisecond)
+ if err := sender.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "INTERLOPER"); err != nil {
+ t.Errorf("sending the unrelated push: %v", err)
+ }
+ }()
+ wg.Wait()
+
+ assertAnswerIsUninterrupted(t, conn.wire(), "INTERLOPER")
+}
+
+// assertAnswerIsUninterrupted reads the wire as the person does: every push
+// that is not the interloper is a piece of the one answer, and the interloper
+// must sit before all of them or after all of them, never inside the run.
+func assertAnswerIsUninterrupted(t *testing.T, wire []string, interloper string) {
+ t.Helper()
+ first, last := -1, -1
+ for i, f := range wire {
+ if f == interloper {
+ continue
+ }
+ if first < 0 {
+ first = i
+ }
+ last = i
+ }
+ if first < 0 || last <= first {
+ t.Fatalf("the answer produced %d piece(s) on the wire: %v", last-first+1, summarize(wire))
+ }
+ for i := first; i <= last; i++ {
+ if wire[i] == interloper {
+ t.Fatalf("%q landed at position %d, between pieces of one answer: %v", interloper, i+1, summarize(wire))
+ }
+ }
+}
+
+// The same rule, for the push the lock never covered. sendTextCtx takes the
+// per-chat lock and sendMedia went straight to request(), so a file delivered
+// while an answer was still being written landed between two of its pieces —
+// and the comment above sendTextCtx says in as many words that the lock is
+// held for every send and names media as the thing it keeps out.
+//
+// Attachment delivery is asynchronous (deliverAttachmentsByID spawns it), so
+// this is not a rare interleaving: the answer's pieces and the file it came
+// with are in flight at the same time by construction.
+//
+// The ack delay is what reproduces it. The sender's write mutex is released
+// before the wait, so the media push wins that mutex while piece one is still
+// unacknowledged.
+//
+// REVERSE VERIFICATION: drop the s.chats.acquire/release pair from sendMedia
+// and this fails with the file between two pieces.
+func TestAFileDoesNotLandBetweenThePiecesOfOneAnswer(t *testing.T) {
+ t.Parallel()
+ conn := &slowAckConn{delay: 30 * time.Millisecond}
+ sender := newWSSender(conn, testLogger())
+ conn.sender = sender
+
+ answer := aLongAnswer()
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ if err := sender.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, answer); err != nil {
+ t.Errorf("sending the long answer: %v", err)
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ // A beat later, so the answer is already mid-flight — the shape of a
+ // file the same turn produced, delivered by its own goroutine.
+ time.Sleep(10 * time.Millisecond)
+ if err := sender.sendMedia(context.Background(), "CHAT_1", chatTypeSingleInt, mediaSend{
+ Kind: mediaTypeImage,
+ MediaID: "MEDIA_1",
+ }); err != nil {
+ t.Errorf("sending the file: %v", err)
+ }
+ }()
+ wg.Wait()
+
+ assertAnswerIsUninterrupted(t, conn.wire(), "image MEDIA_1")
+}
+
+// The other side of the same rule: the lock is per chat, so an answer to one
+// room must not hold up a push to another. Serializing the whole socket would
+// pass the test above and be a head-of-line block on every other conversation.
+//
+// REVERSE VERIFICATION: key the lock on a constant instead of chatID and this
+// times out — the second chat's push waits out the first answer's acks.
+func TestAnAnswerToOneChatDoesNotHoldUpAnother(t *testing.T) {
+ t.Parallel()
+ conn := &slowAckConn{delay: 40 * time.Millisecond}
+ sender := newWSSender(conn, testLogger())
+ conn.sender = sender
+
+ // Three pieces at 40ms an ack is ~120ms of answer; the other chat's single
+ // frame is ~40ms and starts 10ms in. So "did it wait" is not a stopwatch
+ // reading — the other push has to come back while the answer is still
+ // going, and a socket-wide lock cannot produce that.
+ slow := aLongAnswerWithLineBreaks()
+ if n := len(splitForWire(slow)); n < 3 {
+ t.Fatalf("the slow fixture is %d piece(s); it does not hold the lock long enough to tell the two designs apart", n)
+ }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ _ = sender.sendTextCtx(context.Background(), "CHAT_SLOW", chatTypeSingleInt, slow)
+ }()
+
+ other := make(chan error, 1)
+ go func() {
+ time.Sleep(10 * time.Millisecond)
+ other <- sender.sendTextCtx(context.Background(), "CHAT_OTHER", chatTypeSingleInt, "a short reply")
+ }()
+
+ select {
+ case err := <-other:
+ if err != nil {
+ t.Fatalf("the other chat's push failed: %v", err)
+ }
+ case <-done:
+ t.Fatal("the answer to one chat finished before a push to another got through — the lock is not per chat, it is the whole socket")
+ case <-time.After(5 * time.Second):
+ t.Fatal("a push to a different chat never came back")
+ }
+ <-done
+}
+
+// The lock has a second outcome, and before this nothing had a name for it:
+// the WAIT runs out. sendTextCtx takes the chat's turn first and builds a
+// frame second, so a caller whose context ends while queued has put not one
+// byte anywhere — and that is the most retryable failure this package has.
+//
+// Both classifiers read it as the opposite. acquire returned a bare ctx.Err(),
+// so unconfirmedReason filed it under "interrupted" — an outcome nobody may
+// resend, because the message might be on the person's screen — and
+// provablyNotSent said false, which tells the relay to settle the claim and
+// stop offering the frame. The user gets nothing and the party whose job is to
+// try again is told not to.
+//
+// REVERSE VERIFICATION: return ctx.Err() bare from chatLocks.acquire again and
+// this reports provablyNotSent = false and unconfirmedReason = "interrupted",
+// with the same zero frames on the wire.
+func TestGivingUpOnTheChatsTurnIsAProvableNonDelivery(t *testing.T) {
+ t.Parallel()
+ conn := &slowAckConn{delay: time.Millisecond}
+ sender := newWSSender(conn, testLogger())
+ conn.sender = sender
+
+ // Somebody else is mid-answer to this chat; the lock is theirs.
+ release, err := sender.chats.acquire(context.Background(), "CHAT_1")
+ if err != nil {
+ t.Fatalf("taking the chat's turn: %v", err)
+ }
+ defer release()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ defer cancel()
+ sendErr := sender.sendTextCtx(ctx, "CHAT_1", chatTypeSingleInt, "答案")
+
+ if sendErr == nil {
+ t.Fatal("the send reported success while another caller held the chat's turn")
+ }
+ if got := conn.wire(); len(got) != 0 {
+ t.Fatalf("%d frame(s) reached the wire: %v — nothing here is a send that never started", len(got), summarize(got))
+ }
+ if !provablyNotSent(sendErr) {
+ t.Errorf("provablyNotSent(%v) = false, want true — the relay settles the claim on that answer and stops re-offering a message that never reached the socket", sendErr)
+ }
+ if got := unconfirmedReason(sendErr); got != "" {
+ t.Errorf("unconfirmedReason(%v) = %q, want \"\" — %q says the message may be on the person's screen, and nothing was written", sendErr, got, got)
+ }
+
+ // And the direct path's own verdict, through the one mapping it uses.
+ mx := newCountingMetrics()
+ o := NewOutbound(&fakeOutboundQueries{}, newSendersRegistry(), testLogger(), WithOutboundMetrics(mx))
+ o.recordSend(context.Background(), testSessionID, "chat:done", sendErr)
+ if got := mx.get("outbound_dropped"); got != 1 {
+ t.Errorf("outbound_dropped = %d, want 1 — the reply is definitely not delivered", got)
+ }
+ if got := mx.get("outbound_unconfirmed"); got != 0 {
+ t.Errorf("outbound_unconfirmed = %d, want 0 — \"result unknown\" is what stops an operator resending a message nobody ever sent", got)
+ }
+}
+
+// summarize keeps a failure message readable when the pieces are 20KB each.
+func summarize(wire []string) []string {
+ out := make([]string, 0, len(wire))
+ for _, f := range wire {
+ if len(f) > 24 {
+ out = append(out, strconv.Itoa(len(f))+" bytes ending "+tail(f, 8))
+ continue
+ }
+ out = append(out, f)
+ }
+ return out
+}
+
+// A long answer whose tail is a run of blank lines puts that run in a piece of
+// its own, and the last piece carries no marker — so it would reach the chat as
+// an empty bubble, which is what hasVisibleChar stops at the call sites. The
+// split has to stop it too, because by then the call site has already seen a
+// body with visible characters in it.
+//
+// REVERSE VERIFICATION: remove the filter in splitForWire and this fails with
+// the last piece carrying no visible character.
+func TestAPieceThatRendersAsNothingIsNotSent(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct{ name, body string }{
+ {"a tail of blank lines", "答案的正文在这里。\n" + strings.Repeat("\n", sendMsgContentLimit*2)},
+ {"a blank run in the middle", strings.Repeat("字", sendMsgContentLimit/2) + strings.Repeat("\n", sendMsgContentLimit) + "结尾还有字"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if !hasVisibleChar(tc.body) {
+ t.Fatalf("the fixture has nothing visible in it; the call sites would never reach the split")
+ }
+ if len(tc.body) <= sendMsgContentLimit {
+ t.Fatalf("the fixture is %d bytes and never reaches the split", len(tc.body))
+ }
+ pieces := splitForWire(tc.body)
+ for i, p := range pieces {
+ if !hasVisibleChar(p) {
+ t.Errorf("piece %d/%d is %d bytes with nothing visible in it — it reaches the chat as an empty bubble",
+ i+1, len(pieces), len(p))
+ }
+ }
+ // Nothing a reader can see is lost: every visible rune of the
+ // original is still there, in order.
+ if got, want := visibleOnly(reassemble(pieces)), visibleOnly(tc.body); got != want {
+ t.Fatalf("the visible text changed: %d runes reached the chat, want %d", len([]rune(got)), len([]rune(want)))
+ }
+ })
+ }
+}
+
+// visibleOnly is the original with everything the client renders as nothing
+// taken out, which is the part the split promises to preserve.
+func visibleOnly(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ if !unicode.IsSpace(r) && !unicode.IsControl(r) {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
diff --git a/server/internal/integrations/wecom/media_upload.go b/server/internal/integrations/wecom/media_upload.go
index 2a2d47506d..630efc8da1 100644
--- a/server/internal/integrations/wecom/media_upload.go
+++ b/server/internal/integrations/wecom/media_upload.go
@@ -325,13 +325,29 @@ func (s *wsSender) sendMedia(ctx context.Context, chatID string, chatType int, m
if err != nil {
return err
}
- // Through sendMsgFrame: a file and a piece of an answer are the same
- // aibot_send_msg to WeCom and spend the same per-chat allowance, so a turn
- // that answers in words and then sends three attachments has to count as
- // four (rate_limit.go). The retry that comes with it is safe on this route
- // for the reason spelled out below — a STATED refusal is the server saying
- // it did not act on the frame, which is the one failure that cannot leave
- // a copy of the file behind.
+ // The same per-chat lock every text push takes, for the same reason and
+ // against the same reader: a file delivered while an answer is still being
+ // written lands between two of its pieces, and the counters in "(1/3)" no
+ // longer say which text they belong to. Attachment delivery is spawned
+ // (deliverAttachmentsByID), so the two ARE concurrent by construction.
+ //
+ // Taken here and not around the upload above it. The lock's job is the
+ // order of what the chat receives, and an upload puts nothing in the chat
+ // — it is megabytes over several round trips, and holding the chat's turn
+ // for it would park every other message to that chat behind a transfer
+ // that has not yet decided to become a message.
+ release, err := s.chats.acquire(ctx, chatID)
+ if err != nil {
+ return err
+ }
+ defer release()
+ // Through sendMsgFrame and not request: a file and a piece of an answer
+ // are the same aibot_send_msg to WeCom and spend the same per-chat
+ // allowance, so a turn that answers in words and then sends three
+ // attachments has to count as four (rate_limit.go). The retry that comes
+ // with it is safe on this route for the reason spelled out below — a
+ // STATED refusal is the server saying it did not act on the frame, which
+ // is the one failure that cannot leave a copy of the file behind.
if err := s.sendMsgFrame(ctx, chatID, body); err != nil {
// A verdict that never came is not a refusal. The frame went out, and
// the read loop can simply have been busy. Resending on that would put
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index 7947c7266e..5ad275ed89 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -290,10 +290,16 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
// as the words that answered the turn also tells the file below it that
// the reply has already been accounted for.
if hasVisibleChar(content) {
- if err := sender.sendTextCtx(ctx, binding.ChannelChatID, chatType, content); err != nil {
- return err
+ err := sender.sendTextCtx(ctx, binding.ChannelChatID, chatType, content)
+ // Recorded here rather than returned, so this send and the relay's
+ // go through the one mapping in recordSend. Returning it as well
+ // would have handleChatDone classify the same send a second time.
+ o.recordSend(ctx, e.ChatSessionID, e.Type, err)
+ if err != nil && !errors.Is(err, errPartiallySent) {
+ // Nothing of the answer landed. The files are not an answer on
+ // their own, so the turn ends here.
+ return nil
}
- o.delivered()
}
// Then whatever the agent produced alongside them, as its own message — a
// WeCom reply cannot carry a file inline.
diff --git a/server/internal/integrations/wecom/outbound_media.go b/server/internal/integrations/wecom/outbound_media.go
index 4b3d930755..2799924ec9 100644
--- a/server/internal/integrations/wecom/outbound_media.go
+++ b/server/internal/integrations/wecom/outbound_media.go
@@ -486,6 +486,13 @@ func sendOutcome(err error) deliveryState {
switch {
case err == nil:
return deliveryDelivered
+ case errors.Is(err, errNotAttempted):
+ // AHEAD of the context arm below, which this also matches: every
+ // not-attempted failure wraps the ctx.Err() that ended it. A push that
+ // never got the chat's turn, or whose context was already over when
+ // request was entered, was never built let alone written — so the file
+ // is definitely not there, and the person can be told so plainly.
+ return deliveryDefinitelyFailed
case errors.Is(err, errAckTimeout),
errors.Is(err, errWriteAttempted),
errors.Is(err, context.Canceled),
diff --git a/server/internal/integrations/wecom/outbound_outcome.go b/server/internal/integrations/wecom/outbound_outcome.go
index 05c63df71f..d72efb0003 100644
--- a/server/internal/integrations/wecom/outbound_outcome.go
+++ b/server/internal/integrations/wecom/outbound_outcome.go
@@ -119,6 +119,15 @@ func unconfirmedReason(err error) string {
return "ack_timeout"
case errors.Is(err, errWriteAttempted):
return "write_attempted"
+ case errors.Is(err, errNotAttempted):
+ // AHEAD of the context branch below, which this error also matches:
+ // every not-attempted failure wraps the ctx.Err() that ended it. What
+ // it marks is that the wait ended before a frame existed — the chat's
+ // turn never came, or the context was already over when request was
+ // entered — so these are the context failures on this path that are
+ // certain rather than unknown. "interrupted" would tell an operator
+ // not to resend a message nobody ever sent.
+ return ""
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
return "interrupted"
}
@@ -280,6 +289,41 @@ func worseDropReason(a, b dropReason) dropReason {
// delivered records one reply that reached the user. Without it the drop
// counters have no denominator, and "no drops today" cannot be told apart from
// "no traffic today" — which is the same silence #7215 was reported as.
+// recordSend files the counter for one completed text send. It is the single
+// definition of that mapping, and it has to stay single: the two paths that
+// put an agent's words in front of a WeCom user — processEvent on the replica
+// that produced the completion, and deliverRelayed on the one holding the
+// socket — used to classify a PARTIAL send differently. The same user-visible
+// event, piece one in the chat and piece two refused, counted as
+// outbound_delivered on a single-replica deployment and outbound_dropped once
+// the reply went through the relay, so whether a partial delivery paged
+// anybody depended on which replica happened to hold the lease.
+//
+// A partial send counts as delivered, and WARNs with what did not land. The
+// alternative reading — record a drop — tells an operator to resend an answer
+// the user is already reading, and a resend would print the first piece a
+// second time. Neither counter is a good fit for "most of it arrived"; this is
+// the one that does not invite a harmful action.
+//
+// Callers must not also return the error to a layer that classifies it again:
+// one send moves one counter.
+func (o *Outbound) recordSend(ctx context.Context, sessionID, eventType string, err error) {
+ switch {
+ case err == nil:
+ o.delivered()
+ case errors.Is(err, errPartiallySent):
+ o.logger.WarnContext(ctx, "wecom outbound: only part of a long answer reached the chat",
+ "error", err, "chat_session_id", sessionID, "event", eventType)
+ o.delivered()
+ default:
+ if reason := unconfirmedReason(err); reason != "" {
+ o.unconfirmedFor(ctx, sessionID, eventType, reason, err)
+ return
+ }
+ o.droppedFor(ctx, sessionID, eventType, classifyDrop(err), err)
+ }
+}
+
func (o *Outbound) delivered() { o.mx().RecordOutboundDelivered() }
// mx returns the metrics sink, or a no-op one. Mirrors wecomChannel.mx.
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 1232a74dae..95a18b6723 100644
--- a/server/internal/integrations/wecom/outbound_two_replica_db_test.go
+++ b/server/internal/integrations/wecom/outbound_two_replica_db_test.go
@@ -807,26 +807,91 @@ func TestRelay_AttemptedWriteKeepsTheClaim(t *testing.T) {
}
}
-// TestDeliverRelayed_ContextErrorsDoNotRelease — a bare context error is
-// ambiguous: request() returns one both before the write and while waiting for
-// the verdict after it. Treated as possibly-sent, so the outcome must not be
-// the claim-releasing one.
-func TestDeliverRelayed_ContextErrorsDoNotRelease(t *testing.T) {
+// A cancellation is TWO facts on this path, and the relay owes them opposite
+// answers. request raises one before it mints a req_id and one while waiting
+// for the verdict after the frame is on the wire (ws_sender.go); the first is
+// proof of non-delivery, the second is proof of nothing. One test covered both
+// with the possibly-sent answer, which is right for the second and loses the
+// answer on the first — so it is two tests, one per fact.
+//
+// The pre-write half: the socket saw no bytes, so the claim goes back and the
+// dispatcher offers the frame again. Releasing here cannot duplicate anything,
+// and NOT releasing here is a reply nobody ever retries.
+//
+// REVERSE VERIFICATION: return the bare ctx.Err() from request's pre-write
+// check again and this fails with outcomeDone and a record of a reply the chat
+// never saw.
+func TestDeliverRelayed_APreWriteContextErrorReleasesTheClaim(t *testing.T) {
t.Parallel()
instID := mustTestUUID(t)
reg := newSendersRegistry()
conn := &recordingConn{}
- reg.set(instID, conn.autoAck(newWSSender(conn, nil)))
+ reg.set(instID, conn.autoAck(newWSSender(conn, slog.Default())))
o := NewOutbound(nil, reg, slog.Default())
ctx, cancel := context.WithCancel(context.Background())
- cancel() // already expired: sendTextCtx fails on its pre-write check
+ cancel() // already over: the chat is free, so request's pre-write check is what fails
got := o.deliverRelayed(ctx, relayFrame{
Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",
})
+
+ if n := conn.frameCount(); n != 0 {
+ t.Fatalf("%d frame(s) reached the socket; this test is no longer about a send that never started", n)
+ }
+ if got.outcome != outcomeProvablyNotSent {
+ t.Fatalf("outcome = %v, want outcomeProvablyNotSent — the claim stays held on an answer "+
+ "the socket never saw, and the dispatcher stops offering it", got.outcome)
+ }
+ if got.record != nil {
+ t.Error("a frame still owed another offer carries a record; counting it here counts it once per attempt")
+ }
+}
+
+// The post-write half: the frame is on the wire and only its verdict is
+// missing, so the claim STAYS and the reply files as unconfirmed. Releasing it
+// would let a re-offer put the same answer in the chat a second time, with
+// nothing to undo it with.
+func TestDeliverRelayed_AContextErrorAwaitingTheAckKeepsTheClaim(t *testing.T) {
+ t.Parallel()
+ instID := mustTestUUID(t)
+ reg := newSendersRegistry()
+ conn := &recordingConn{} // no autoAck: the frame goes out and no verdict comes back
+ reg.set(instID, newWSSender(conn, slog.Default()))
+ mx := newCountingMetrics()
+ o := NewOutbound(nil, reg, slog.Default(), WithOutboundMetrics(mx))
+
+ // Cancelled once the frame is ON THE WIRE, so which of request's two
+ // context errors this raises is a fact about the run rather than a race
+ // against a timer.
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go func() {
+ for conn.frameCount() == 0 {
+ time.Sleep(time.Millisecond)
+ }
+ cancel()
+ }()
+ got := o.deliverRelayed(ctx, relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",
+ })
+
+ if n := conn.frameCount(); n != 1 {
+ t.Fatalf("%d frame(s) reached the socket, want 1; this test is about a cancellation AFTER the write", n)
+ }
if got.outcome == outcomeProvablyNotSent {
- t.Fatal("a context error released the claim; it is ambiguous and must not")
+ t.Fatal("the claim was released for a frame the peer may already hold; a re-offer prints the answer twice")
+ }
+ if got.record == nil {
+ t.Fatal("a finished frame carries no record, so this reply moves no counter at all")
+ }
+ got.record()
+ if n := mx.get("outbound_unconfirmed"); n != 1 {
+ t.Errorf("outbound_unconfirmed = %d, want 1 — the verdict is missing, which is not the same as a failure", n)
+ }
+ if n := mx.get("outbound_dropped"); n != 0 {
+ t.Errorf("outbound_dropped = %d, want 0 — dropped promises the answer is not coming, and it may already be there", n)
}
}
diff --git a/server/internal/integrations/wecom/relay_ordering_db_test.go b/server/internal/integrations/wecom/relay_ordering_db_test.go
index ac3d2193b7..bab246403a 100644
--- a/server/internal/integrations/wecom/relay_ordering_db_test.go
+++ b/server/internal/integrations/wecom/relay_ordering_db_test.go
@@ -338,8 +338,17 @@ func TestRelay_AReplyNoReplicaCouldSendIsCountedOnce(t *testing.T) {
relay := &fanoutRelay{}
dedupe := NewRedisDedupe(rdb, testClaimBudget, slog.Default())
// A short chain so the grace the watch waits out is a test's worth of time
- // rather than a lease poll's.
- cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond}
+ // rather than a lease poll's. Every term outcomeGrace is built from has to
+ // come down together, and DeliveryBudget is one of them: it is charged per
+ // OFFER, because an offer that fails provably-unsent hands the claim back
+ // and the next one gets a budget of its own. Left at its ackTimeout
+ // default this chain's grace is forty seconds.
+ cfg := RelayConfig{
+ Shards: 1,
+ LeaseSettle: 120 * time.Millisecond,
+ RetryBackoff: 20 * time.Millisecond,
+ DeliveryBudget: 20 * time.Millisecond,
+ }
// Neither replica holds the socket: both are mid-reconnect, which is the
// residual window SELF_HOSTING.md describes.
@@ -375,7 +384,12 @@ func TestRelay_ADeliveredReplyIsCountedOnceAndNotAlsoLost(t *testing.T) {
relay := &fanoutRelay{}
dedupe := NewRedisDedupe(rdb, testClaimBudget, slog.Default())
- cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond}
+ cfg := RelayConfig{
+ Shards: 1,
+ LeaseSettle: 120 * time.Millisecond,
+ RetryBackoff: 20 * time.Millisecond,
+ DeliveryBudget: 20 * time.Millisecond, // per offer, like the claim budget — see the test above
+ }
holder := newRelayReplicaWith(t, pool, turn.instID, true, relay, dedupe, cfg)
publisher := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)
@@ -388,8 +402,12 @@ func TestRelay_ADeliveredReplyIsCountedOnceAndNotAlsoLost(t *testing.T) {
if got := sentTexts(t, holder.conn); len(got) != 1 {
t.Fatalf("the chat received %v, want the one answer", got)
}
- // Past the whole grace, so the watch has run and had its say.
- time.Sleep(600 * time.Millisecond)
+ // Past the whole grace, so the watch has run and had its say. Read off
+ // the dispatcher rather than written down: a fixed 600ms was under the
+ // grace this config produces, so the assertions below were passing on a
+ // watch that had not run yet — they proved nothing about what it does
+ // when it does run.
+ time.Sleep(publisher.router.outcomeGrace() + 200*time.Millisecond)
if got := holder.mx.get("outbound_delivered"); got != 1 {
t.Errorf("outbound_delivered on the holder = %d, want 1", got)
diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.go
index 1920b3263a..b6ac1a523a 100644
--- a/server/internal/integrations/wecom/relay_outbound.go
+++ b/server/internal/integrations/wecom/relay_outbound.go
@@ -138,10 +138,20 @@ func dedupeTTLFor(replayGrace time.Duration) time.Duration {
// A zero field takes its documented default.
type RelayConfig struct {
// DeliveryBudget is the longest one delivery attempt may take once it
- // holds the claim — the send and its ack wait. Zero means ackTimeout. It
- // sizes the publisher's outcome grace (outcomeGrace): the last offer of
- // the chain may still be inside its ack wait when the chain's timing is
- // over. Tests shrink it with everything else.
+ // holds the claim, and it bounds the WHOLE logical delivery: the wait for
+ // the target chat's turn, and every piece a long answer is split into with
+ // its own ack wait. Zero means ackTimeout.
+ //
+ // One budget for all of it, because that is what the publisher's outcome
+ // grace reserves for one offer (outcomeGrace) — a grace sized for one ack
+ // while the delivery waits for several is a Resolve that fences a reply
+ // its holder is still writing.
+ //
+ // The grace charges it PER OFFER, not once for the chain: an offer that
+ // fails provably-unsent hands the claim back, so the next offer starts
+ // with a budget of its own. Lowering it therefore shortens the grace
+ // twelve-fold on the defaults, which is why tests that wait a grace out
+ // shrink it along with the claim budget and the lease settle.
DeliveryBudget time.Duration
// Shards is how many independent queues carry frames, and it is a
@@ -863,7 +873,27 @@ func (r *RelayOutbound) perform(ctx context.Context, item queued) bool {
return false
}
}
- res := r.handler.deliverRelayed(ctx, item.frame)
+ // DeliveryBudget is what the publisher's outcomeGrace charges per offer
+ // (outcomeGrace, below), so it has to be what this delivery actually
+ // gets. It was documented as the bound and never applied: the send's only
+ // limit was ackTimeout, the constant, whatever the config said. An
+ // operator who lowered the budget shrank the grace without shortening the
+ // delivery, and a Resolve landing inside an ack wait fences a reply that
+ // is on its way.
+ //
+ // A budget PER OFFER and not one for the chain, because this is where the
+ // claim is taken and given back: an offer that ends provably-unsent
+ // releases the claim a few lines down, and the next offer arrives here
+ // and opens a fresh one.
+ //
+ // The default is ackTimeout, so a deployment that sets nothing sees no
+ // change. A delivery cut here ends in a context error, which
+ // unconfirmedReason reads as unknown rather than failed — correct when
+ // the cut lands after the write, and marked as certain when it lands
+ // before one (errNotAttempted, ws_sender.go).
+ dctx, cancelDelivery := context.WithTimeout(ctx, r.cfg.deliveryBudget())
+ res := r.handler.deliverRelayed(dctx, item.frame)
+ cancelDelivery()
if res.outcome == outcomeDone {
// FINISHED. The holder's record is made only once the claim says
// so: Settle is a compare-and-set on this replica's token, and a
@@ -1059,11 +1089,26 @@ func (r *RelayOutbound) outcomeGrace() time.Duration {
// The settle retry on the finished offer: its extra attempts and the
// pauses between them (settleClaim).
total += time.Duration(claimSettleAttempts-1) * (budget + r.settleRetryBackoff())
- // Plus the last offer's own delivery: a claim taken on the final attempt
- // is still being written and acked when the chain's timing says the chain
- // is over, and a Resolve that lands inside that ack wait fences a reply
- // that is about to be delivered. The send waits at most ackTimeout.
- total += r.cfg.deliveryBudget()
+ // Plus a DELIVERY PER OFFER, not one for the chain. perform gives every
+ // claimed delivery a budget of its own, and the failure that spends the
+ // whole of one is also the failure that hands the claim back: an offer
+ // whose chat is busy waits for the chat's turn until its budget runs out
+ // and comes back errChatBusy, which is provablyNotSent, so the claim is
+ // released and the frame is offered again with a fresh budget. Charging
+ // one delivery to the chain therefore sized the grace for a chain that
+ // cannot happen — every offer's backoff plus one offer's delivery — and
+ // on the defaults that is 5s of grace against 60s the chain can spend.
+ //
+ // The Resolve that lands inside a live offer is the whole cost: it fences
+ // the key as lost in the same operation, so the holder that comes back
+ // records nothing while the counter already says the reply was dropped.
+ // One reply, counted lost and delivered at once.
+ //
+ // The other direction — a delivery that outlives the budget perform gave
+ // it — cannot happen: it IS the budget, applied to the context the
+ // delivery runs on, so an answer split into several frames spends it
+ // across all of them rather than taking an ack wait per piece.
+ total += r.cfg.deliveryBudget() * time.Duration(offers)
return total
}
@@ -1288,13 +1333,11 @@ func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResult
}
sendErr := err
if f.Kind == relayKindReply {
- record = func() {
- if reason := unconfirmedReason(sendErr); reason != "" {
- o.unconfirmedFor(ctx, f.SessionID, f.Kind, reason, sendErr)
- } else {
- o.droppedFor(ctx, f.SessionID, f.Kind, classifyDrop(sendErr), sendErr)
- }
- }
+ // The same mapping the direct path uses. A partial send in
+ // particular has to agree across the two, or one reply counts
+ // as delivered or dropped depending on which replica held the
+ // socket — see recordSend.
+ record = func() { o.recordSend(ctx, f.SessionID, f.Kind, sendErr) }
} else {
record = func() {
o.logger.WarnContext(ctx, "wecom relay: inbox push failed on the lease holder",
@@ -1353,12 +1396,26 @@ func provablyNotSent(err error) bool {
switch {
case err == nil:
return false
+ case errors.Is(err, errPartiallySent):
+ // An answer past the cap goes out as several frames, and a failure on
+ // the second says nothing about the first, which the user is already
+ // reading. Retrying such a send would repeat what landed.
+ return false
case errors.As(err, &apiErr):
return false
case errors.Is(err, errAckTimeout):
return false
case errors.Is(err, errWriteAttempted):
return false
+ case errors.Is(err, errNotAttempted):
+ // AHEAD of the context branch below, which this error also matches:
+ // every not-attempted failure wraps the ctx.Err() that ended it. The
+ // chat lock is taken and the context is checked before a frame is
+ // built, so a delivery that ended at either point wrote nothing — and
+ // these are the most retryable failures the path has. Reading them as
+ // the ambiguous context error underneath settles the claim on a
+ // message that was never offered to the socket.
+ return true
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
return false
default:
diff --git a/server/internal/integrations/wecom/relay_outbound_attribution_test.go b/server/internal/integrations/wecom/relay_outbound_attribution_test.go
index f84130e04d..ffb1ff2091 100644
--- a/server/internal/integrations/wecom/relay_outbound_attribution_test.go
+++ b/server/internal/integrations/wecom/relay_outbound_attribution_test.go
@@ -18,6 +18,8 @@ import (
"time"
"github.com/redis/go-redis/v9"
+
+ "github.com/multica-ai/multica/server/internal/util"
)
// ---------------------------------------------------------------------------
@@ -145,19 +147,127 @@ func TestRelayOutcomeGrace_CoversEveryStoreRoundTripTheChainCanMake(t *testing.T
// Worst case the chain can actually take. TWO store round trips per
// offer, because every offer ends in a Release or a Settle on the same
// budget as its Claim; the finished offer's settle retries on top; and
- // the delivery itself. Counting one round trip per offer left up to half
- // the store time out of the arithmetic, and the absent state is not
- // fenced — so a grace that expires early is recorded as a loss while a
- // later offer can still claim, deliver and settle.
+ // a DELIVERY BUDGET PER OFFER, because perform hands each claimed
+ // delivery a budget of its own (relay_outbound.go) and the failure that
+ // spends the whole of one — the chat's turn never coming — is
+ // provablyNotSent, so it releases the claim and the frame is offered
+ // again. Counting the delivery once measured a chain that cannot happen:
+ // one offer's delivery plus every offer's backoff. Counting one round
+ // trip per offer left up to half the store time out on the same
+ // arithmetic, and the absent state is not fenced — so a grace that
+ // expires early is recorded as a loss while a later offer can still
+ // claim, deliver and settle.
worst := chain + budget*time.Duration(2*offers) +
time.Duration(claimSettleAttempts-1)*(budget+r.settleRetryBackoff()) +
- r.cfg.deliveryBudget()
+ r.cfg.deliveryBudget()*time.Duration(offers)
if r.outcomeGrace() < worst {
t.Fatalf("outcome grace %s is shorter than the %s a fully timed-out chain can take "+
- "(%d offers × 2 × %s of store round trips + %s of backoff + %d settle retries + %s of delivery) — "+
+ "(%d offers × 2 × %s of store round trips + %s of backoff + %d settle retries + %d × %s of delivery) — "+
"the watch would call a reply lost while it was still being retried, and the retry would then deliver it",
- r.outcomeGrace(), worst, offers, budget, chain, claimSettleAttempts-1, r.cfg.deliveryBudget())
+ r.outcomeGrace(), worst, offers, budget, chain, claimSettleAttempts-1, offers, r.cfg.deliveryBudget())
+ }
+}
+
+// graceObserverStore is a claim store that answers like sharedDedupe and
+// records HOW FAR THE CHAIN HAD GOT when the outcome watch first resolved the
+// reply. One Claim per offer, so the count is the offer the watcher landed on.
+type graceObserverStore struct {
+ *sharedDedupe
+ budget time.Duration
+
+ mu sync.Mutex
+ resolved bool
+ claims int
+}
+
+func (g *graceObserverStore) ClaimBudget() time.Duration { return g.budget }
+
+func (g *graceObserverStore) Resolve(ctx context.Context, key string) (claimState, error) {
+ g.mu.Lock()
+ if !g.resolved {
+ g.resolved, g.claims = true, g.sharedDedupe.claimCount()
+ }
+ g.mu.Unlock()
+ return g.sharedDedupe.Resolve(ctx, key)
+}
+
+func (g *graceObserverStore) didResolve() bool {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ return g.resolved
+}
+
+func (g *graceObserverStore) claimsWhenResolved() int {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ return g.claims
+}
+
+// The arithmetic above is only as good as its model of what an offer costs, so
+// this checks it against the thing itself: a chat nobody ever gives up, a
+// dispatcher re-offering the frame across its whole chain, and the publisher's
+// own watcher deciding when the reply is lost.
+//
+// A busy chat is the case that makes every offer expensive. sendTextCtx waits
+// for the chat's turn before it builds anything, so an offer against a held
+// lock spends its ENTIRE DeliveryBudget and comes back errChatBusy — provably
+// unsent, so perform releases the claim and the dispatcher offers the frame
+// again with its own fresh budget. Eight offers, eight budgets.
+//
+// What must not happen is the watcher resolving mid-chain. Resolve fences the
+// key as lost in the same operation, so a holder that comes back records
+// nothing while the counter already says the reply was dropped — the "one
+// reply counted as delivered and dropped at the same time" outcome
+// deliverRelayed's comment says this package no longer has.
+//
+// REVERSE VERIFICATION: count the delivery once in outcomeGrace and this fails
+// with the watch resolving around the fifth of eight offers.
+func TestRelayOutcomeGrace_OutlastsAChainThatSpendsADeliveryBudgetPerOffer(t *testing.T) {
+ t.Parallel()
+ store := &graceObserverStore{sharedDedupe: newSharedDedupe(), budget: 20 * time.Millisecond}
+
+ instID := mustTestUUID(t)
+ conn := &recordingConn{}
+ sender := conn.autoAck(newWSSender(conn, testLogger()))
+ // Somebody else is mid-answer to this chat and never finishes.
+ release, err := sender.chats.acquire(context.Background(), "CHAT_1")
+ if err != nil {
+ t.Fatalf("taking the chat's turn: %v", err)
+ }
+ defer release()
+ reg := newSendersRegistry()
+ reg.set(instID, sender)
+
+ relay := &fanoutRelay{}
+ router := NewRelayOutbound(relay, store, RelayConfig{
+ Shards: 1,
+ DeliveryBudget: 100 * time.Millisecond,
+ LeaseSettle: 40 * time.Millisecond,
+ RetryBackoff: 5 * time.Millisecond,
+ }, testLogger())
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() { cancel(); router.Wait() })
+ router.Start(ctx)
+ router.Attach(NewOutbound(nil, reg, testLogger()))
+ relay.register(router)
+
+ offers := len(router.retryPlan) + 1
+ router.publish(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "答案",
+ SessionID: testSessionID,
+ }, "ev-busy-chat")
+
+ waitLong(t, "the outcome watch to resolve the routed reply", store.didResolve)
+ if got := store.claimsWhenResolved(); got < offers {
+ t.Fatalf("the watch resolved the reply on offer %d of %d — the chain was still running, "+
+ "and Resolve fences the key, so a later offer that delivered would have recorded nothing "+
+ "while the loss was already counted (grace %s, %d offers × %s of delivery alone)",
+ got, offers, router.outcomeGrace(), offers, router.cfg.deliveryBudget())
+ }
+ if got := conn.sendFrames(); len(got) != 0 {
+ t.Fatalf("%d frame(s) reached the wire while the chat's turn was held by somebody else", len(got))
}
}
diff --git a/server/internal/integrations/wecom/relay_relayed_send_test.go b/server/internal/integrations/wecom/relay_relayed_send_test.go
index 7b7b0ff087..821d4ec959 100644
--- a/server/internal/integrations/wecom/relay_relayed_send_test.go
+++ b/server/internal/integrations/wecom/relay_relayed_send_test.go
@@ -53,6 +53,15 @@ type deadlineFlakyConn struct {
attempts int
// failOn reports whether the n-th (1-based) write deadline is refused.
failOn func(n int) bool
+
+ // refuseFromSend and swallowAckFromSend act on aibot_send_msg frames,
+ // counted 1-based, so a test can refuse or lose the verdict on the SECOND
+ // piece of a split answer after the first one landed. Unlike failOn these
+ // are failures the peer stated or swallowed, not ones raised before the
+ // write — which is what makes the send partial rather than unsent.
+ refuseFromSend int
+ swallowAckFromSend int
+ sends int
}
func (c *deadlineFlakyConn) newSender() *wsSender {
@@ -87,13 +96,21 @@ func (c *deadlineFlakyConn) WriteMessage(_ int, data []byte) error {
}
_ = json.Unmarshal(env.Body, &body)
c.mu.Lock()
- if env.Cmd == cmdSendMsg && body.MsgType == "markdown" {
- c.texts = append(c.texts, body.Markdown.Content)
+ code, msg, swallow := 0, "", false
+ if env.Cmd == cmdSendMsg {
+ c.sends++
+ if c.refuseFromSend > 0 && c.sends >= c.refuseFromSend {
+ code, msg = 45002, "content exceed max length"
+ }
+ swallow = c.swallowAckFromSend > 0 && c.sends >= c.swallowAckFromSend
+ if code == 0 && body.MsgType == "markdown" {
+ c.texts = append(c.texts, body.Markdown.Content)
+ }
}
s := c.sender
c.mu.Unlock()
- if s != nil {
- s.routeResponse(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}})
+ if s != nil && !swallow {
+ s.routeResponse(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}, ErrCode: code, ErrMsg: msg})
}
return nil
}
@@ -145,6 +162,14 @@ func newRelaySendRig(t *testing.T, failOn func(n int) bool) *relaySendRig {
// newRelaySendRigWithDedupe is the rig with a claim store, for the paths the
// claim gate takes part in.
func newRelaySendRigWithDedupe(t *testing.T, failOn func(n int) bool, dedupe DedupeStore) *relaySendRig {
+ t.Helper()
+ return newRelaySendRigWithConfig(t, failOn, dedupe, relayRetryConfig)
+}
+
+// newRelaySendRigWithConfig is the rig with the chain sized by the test, for
+// the ones that have to watch a whole re-offer chain run against something
+// slower than a millisecond.
+func newRelaySendRigWithConfig(t *testing.T, failOn func(n int) bool, dedupe DedupeStore, cfg RelayConfig) *relaySendRig {
t.Helper()
reg := newSendersRegistry()
instID := mustTestUUID(t)
@@ -157,7 +182,7 @@ func newRelaySendRigWithDedupe(t *testing.T, failOn func(n int) bool, dedupe Ded
// No dedupe store: that is the single-replica claim gate, and it leaves the
// retry chain — the thing under test — exactly as it is in production.
- router := NewRelayOutbound(&fanoutRelay{}, dedupe, relayRetryConfig, testLogger())
+ router := NewRelayOutbound(&fanoutRelay{}, dedupe, cfg, testLogger())
router.SetMetrics(mx)
router.Attach(o)
ctx, cancel := context.WithCancel(context.Background())
@@ -402,3 +427,312 @@ func TestRelayedReply_ASettleThatNeverExecutedIsRetried(t *testing.T) {
t.Fatalf("claim value = %q, want %q", v, claimSettledValue)
}
}
+
+// ---------------------------------------------------------------------------
+// the same partial send, on the lease holder
+// ---------------------------------------------------------------------------
+
+// The relay half of the pair in long_reply_test.go. A reply produced on
+// another replica, split because it is over the cap, with its second piece
+// refused here: the person's screen is in exactly the state the direct path
+// leaves it in, so the counter has to agree.
+//
+// It also must not be re-offered. provablyNotSent reads errPartiallySent as
+// "something reached the peer", and a retry would print piece one a second
+// time in a chat with no unsend.
+//
+// REVERSE VERIFICATION: drop the errPartiallySent arm from recordSend and this
+// reports outbound_dropped = 1 with outbound_delivered = 0 — the very split
+// this test exists to close, since the direct path counts the same event
+// delivered.
+func TestRelayedReply_ARefusedSecondPieceCountsDeliveredAndIsNotReoffered(t *testing.T) {
+ t.Parallel()
+ rig := newRelaySendRig(t, nil)
+ rig.conn.refuseFromSend = 2
+
+ rig.route(t, aLongAnswer())
+ waitFor(t, "the lease holder to take the reply", func() bool {
+ return rig.mx.get("outbound_delivered")+rig.mx.get("outbound_dropped")+rig.mx.get("outbound_unconfirmed") > 0
+ })
+ rig.stop()
+
+ if got := rig.mx.get("outbound_delivered"); got != 1 {
+ t.Errorf("outbound_delivered = %d, want 1 — the direct path counts this same event delivered", got)
+ }
+ if got := rig.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("outbound_dropped = %d, want 0 — a drop here and a delivery on the direct path is the same reply with two verdicts", got)
+ }
+ if got := rig.mx.get("outbound_unconfirmed"); got != 0 {
+ t.Errorf("outbound_unconfirmed = %d, want 0", got)
+ }
+ if got := len(rig.conn.sent()); got != 1 {
+ t.Errorf("the chat received %d piece(s), want 1 — piece two was refused and must not be re-offered", got)
+ }
+}
+
+// The lost-verdict half. The dispatcher gives a delivery a bounded budget, so
+// the wait ends there rather than on ackTimeout, and the frame is still not
+// owed another offer: piece one is already on the person's screen.
+//
+// REVERSE VERIFICATION: same revert, and this reports outbound_unconfirmed = 1
+// with outbound_delivered = 0.
+func TestRelayedReply_ALostAckOnTheSecondPieceCountsDelivered(t *testing.T) {
+ t.Parallel()
+ rig := newRelaySendRig(t, nil)
+ rig.conn.swallowAckFromSend = 2
+
+ rig.route(t, aLongAnswer())
+ // Both pieces reach the wire; the second one's verdict never comes back.
+ // What ends that wait is the delivery's own deadline — DeliveryBudget,
+ // 20ms on this rig — and here the dispatcher shutting down gets there
+ // first. Either way it is the same ctx.Err() out of request(), without a
+ // test that stands still for the five-second ackTimeout.
+ waitFor(t, "both pieces to reach the wire", func() bool {
+ return rig.conn.writeAttempts() >= 2
+ })
+ rig.stop()
+
+ if got := rig.mx.get("outbound_delivered"); got != 1 {
+ t.Errorf("outbound_delivered = %d, want 1", got)
+ }
+ if got := rig.mx.get("outbound_unconfirmed"); got != 0 {
+ t.Errorf("outbound_unconfirmed = %d, want 0 — part of the answer is on screen, so the delivery is not unknown", got)
+ }
+ if got := rig.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("outbound_dropped = %d, want 0", got)
+ }
+}
+
+// A routed reply that never reached the socket because the chat was busy is
+// OFFERED AGAIN, and arrives. This is the retryable failure of the whole set:
+// sendTextCtx takes the chat's turn before it builds a frame, so a delivery
+// whose budget runs out while queued put nothing anywhere.
+//
+// It used to end the reply. acquire returned a bare ctx.Err(), provablyNotSent
+// read that as "may have been sent", and the dispatcher settled the claim and
+// stopped — a message the user never received, with the one party that could
+// have re-sent it told not to.
+//
+// The lock is held here for less than the retry chain lasts, which is the real
+// shape of the thing: the chat is busy with the answer before this one, not
+// broken.
+//
+// REVERSE VERIFICATION: return ctx.Err() bare from chatLocks.acquire again and
+// this fails with "timed out waiting for the reply to reach the chat", the
+// chat having received nothing and outbound_unconfirmed = 1.
+func TestRelayedReply_AReplyThatNeverGotTheChatsTurnIsOfferedAgain(t *testing.T) {
+ t.Parallel()
+ // Its own chain rather than the millisecond one the rest of the file uses,
+ // sized by the two things this test needs to keep apart. The chat is busy
+ // for LONGER than one delivery budget, so the first offers really do give
+ // up waiting — that is the failure under test — and for far less than the
+ // whole re-offer chain, so a later offer still has one to spare. Ten
+ // offers over ~1.3s of backoff against a chat busy for 120ms.
+ budget := 40 * time.Millisecond
+ rig := newRelaySendRigWithConfig(t, nil, nil, RelayConfig{
+ Shards: 1, LeaseSettle: 800 * time.Millisecond,
+ RetryBackoff: 20 * time.Millisecond, DeliveryBudget: budget,
+ })
+
+ // Somebody else has the chat's turn — an answer already going out on this
+ // socket. The first offer's budget runs out inside the wait.
+ release, err := rig.conn.sender.chats.acquire(context.Background(), "CHAT_1")
+ if err != nil {
+ t.Fatalf("taking the chat's turn: %v", err)
+ }
+ go func() {
+ time.Sleep(3 * budget)
+ release()
+ }()
+
+ rig.route(t, "答案")
+ waitFor(t, "the reply to reach the chat on a later offer", func() bool {
+ return len(rig.conn.sent()) > 0
+ })
+ rig.stop()
+
+ if got := rig.conn.sent(); len(got) != 1 {
+ t.Fatalf("the chat received %d message(s), want 1: %v", len(got), got)
+ }
+ if got := rig.mx.get("outbound_delivered"); got != 1 {
+ t.Errorf("outbound_delivered = %d, want 1", got)
+ }
+ if got := rig.mx.get("outbound_unconfirmed"); got != 0 {
+ t.Errorf("outbound_unconfirmed = %d, want 0 — a delivery that never got the chat's turn wrote nothing, so its outcome is not unknown", got)
+ }
+ if got := rig.mx.get("outbound_dropped"); got != 0 {
+ t.Errorf("outbound_dropped = %d, want 0 — the frame was re-offered and arrived", got)
+ }
+}
+
+// DeliveryBudget is the number outcomeGrace is computed from, so a delivery
+// that outlives it makes the publisher's grace a wrong answer: a Resolve
+// landing inside an ack wait fences a reply that is still being written. It
+// was documented as the bound on "the send and its ack wait" and never
+// applied — the only limit the send had was ackTimeout, the constant.
+//
+// The socket here writes and never answers, which before this was a five
+// second wait whatever the config said.
+//
+// REVERSE VERIFICATION: hand deliverRelayed the dispatcher's ctx again and
+// this fails with the delivery taking ackTimeout (5s) against a 120ms budget.
+func TestADeliveryIsBoundedByTheBudgetItsGraceIsComputedFrom(t *testing.T) {
+ t.Parallel()
+ budget := 120 * time.Millisecond
+ cfg := RelayConfig{Shards: 1, LeaseSettle: 40 * time.Millisecond, RetryBackoff: 5 * time.Millisecond, DeliveryBudget: budget}
+
+ reg := newSendersRegistry()
+ instID := mustTestUUID(t)
+ conn := &silentAckConn{}
+ reg.set(instID, conn.newSender())
+ mx := newCountingMetrics()
+ o := NewOutbound(&fakeOutboundQueries{}, reg, testLogger(), WithOutboundMetrics(mx))
+ o.spawn = func(f func()) { f() }
+ router := NewRelayOutbound(&fanoutRelay{}, nil, cfg, testLogger())
+ router.SetMetrics(mx)
+ router.Attach(o)
+ ctx, cancel := context.WithCancel(context.Background())
+ router.Start(ctx)
+ t.Cleanup(func() { cancel(); router.Wait() })
+
+ body, err := json.Marshal(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeGroupInt, Content: "答案",
+ SessionID: testSessionID, TaskID: testTaskID,
+ })
+ if err != nil {
+ t.Fatalf("marshal relay frame: %v", err)
+ }
+ started := time.Now()
+ router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-budget")
+ // The delivery is over when its outcome is filed. A send cut by the
+ // budget ends in a context error, which unconfirmedReason reads as
+ // unknown — the frame went out and no verdict came back.
+ waitFor(t, "the delivery to record an outcome inside its budget rather than at ackTimeout", func() bool {
+ return mx.get("outbound_unconfirmed")+mx.get("outbound_dropped")+mx.get("outbound_delivered") > 0
+ })
+ took := time.Since(started)
+
+ if conn.attempts() == 0 {
+ t.Fatal("nothing was written; this test is not measuring a delivery")
+ }
+ if got := mx.get("outbound_unconfirmed"); got != 1 {
+ t.Errorf("outbound_unconfirmed = %d, want 1 — a delivery cut by its own budget is unknown, not failed", got)
+ }
+ // ackTimeout is five seconds. Anything near it means the budget was not
+ // applied; a small multiple of the budget is scheduling noise.
+ if took > 2*time.Second {
+ t.Fatalf("the delivery took %s against a %s budget — the send is still bounded by ackTimeout, not by the number the grace is computed from", took, budget)
+ }
+}
+
+// ONE budget covers the whole logical delivery — the wait for the chat's turn
+// and every piece of the answer — which is what makes the publisher's grace an
+// answer again.
+//
+// Splitting moved the arithmetic under outcomeGrace. Before it, a text
+// delivery waited on exactly one ack, so an offer's delivery cost one ack
+// wait. After it, one logical send waits for the chat's turn and then for N
+// consecutive acks, while the grace reserves one budget per offer — so a slow
+// multi-piece answer outlives its offer's budget and Resolve fences a reply
+// whose holder is still writing it.
+//
+// The cap is applied once, around deliverRelayed, so everything inside — the
+// lock wait and all the pieces — shares the one budget the grace sets aside.
+// Here the chat is busy for the first 60ms and the third piece is never
+// acknowledged, and the whole thing still ends inside one budget.
+//
+// REVERSE VERIFICATION: hand deliverRelayed the dispatcher's ctx again and
+// this fails with "timed out waiting for the delivery to end inside one
+// budget" — the unacknowledged piece waits out ackTimeout, five seconds,
+// against a 300ms budget.
+func TestASlowMultiPieceDeliveryFitsInTheOneBudgetTheGraceReserves(t *testing.T) {
+ t.Parallel()
+ budget := 300 * time.Millisecond
+ cfg := RelayConfig{Shards: 1, LeaseSettle: 40 * time.Millisecond, RetryBackoff: 5 * time.Millisecond, DeliveryBudget: budget}
+
+ reg := newSendersRegistry()
+ instID := mustTestUUID(t)
+ conn := &slowAckConn{delay: 40 * time.Millisecond, swallowFrom: 3}
+ sender := newWSSender(conn, testLogger())
+ conn.sender = sender
+ reg.set(instID, sender)
+ mx := newCountingMetrics()
+ o := NewOutbound(&fakeOutboundQueries{}, reg, testLogger(), WithOutboundMetrics(mx))
+ o.spawn = func(f func()) { f() }
+ router := NewRelayOutbound(&fanoutRelay{}, nil, cfg, testLogger())
+ router.SetMetrics(mx)
+ router.Attach(o)
+ ctx, cancel := context.WithCancel(context.Background())
+ router.Start(ctx)
+ t.Cleanup(func() { cancel(); router.Wait() })
+
+ // The chat is busy when the delivery starts: the budget has to cover the
+ // wait for its turn, not only the sending.
+ release, err := sender.chats.acquire(context.Background(), "CHAT_1")
+ if err != nil {
+ t.Fatalf("taking the chat's turn: %v", err)
+ }
+ go func() {
+ time.Sleep(60 * time.Millisecond)
+ release()
+ }()
+
+ body, err := json.Marshal(relayFrame{
+ Kind: relayKindReply, InstallationID: util.UUIDToString(instID),
+ ChatID: "CHAT_1", ChatType: chatTypeGroupInt, Content: aLongAnswer(),
+ SessionID: testSessionID, TaskID: testTaskID,
+ })
+ if err != nil {
+ t.Fatalf("marshal relay frame: %v", err)
+ }
+ started := time.Now()
+ router.DeliverWecomOutbound(util.UUIDToString(instID), body, "ev-slow-split")
+ waitFor(t, "the delivery to end inside one budget rather than on the ack timeout of one piece", func() bool {
+ return mx.get("outbound_delivered")+mx.get("outbound_unconfirmed")+mx.get("outbound_dropped") > 0
+ })
+ took := time.Since(started)
+
+ if got := len(conn.wire()); got < 3 {
+ t.Fatalf("%d piece(s) reached the wire, want at least 3 — this is not measuring a multi-piece delivery", got)
+ }
+ // Generous against scheduling noise and still nowhere near the five
+ // seconds an unbounded delivery spends on the piece nobody acknowledges.
+ if limit := budget + 400*time.Millisecond; took > limit {
+ t.Fatalf("the delivery took %s against a %s budget — the pieces after the first are outside the bound the grace is computed from", took, budget)
+ }
+ if grace := router.outcomeGrace(); grace <= took {
+ t.Errorf("outcomeGrace() = %s and the delivery took %s — the publisher gives up while its holder is still sending", grace, took)
+ }
+ if got := mx.get("outbound_delivered"); got != 1 {
+ t.Errorf("outbound_delivered = %d, want 1 — two pieces are on the person's screen", got)
+ }
+}
+
+// silentAckConn writes and never answers, which is the shape of a peer that
+// took the bytes and went quiet.
+type silentAckConn struct {
+ mu sync.Mutex
+ sender *wsSender
+ writes int
+}
+
+func (c *silentAckConn) newSender() *wsSender {
+ s := newWSSender(c, testLogger())
+ c.mu.Lock()
+ c.sender = s
+ c.mu.Unlock()
+ return s
+}
+
+func (c *silentAckConn) WriteMessage(int, []byte) error {
+ c.mu.Lock()
+ c.writes++
+ c.mu.Unlock()
+ return nil
+}
+func (c *silentAckConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
+func (c *silentAckConn) SetReadDeadline(time.Time) error { return nil }
+func (c *silentAckConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *silentAckConn) Close() error { return nil }
+func (c *silentAckConn) attempts() int { c.mu.Lock(); defer c.mu.Unlock(); return c.writes }
diff --git a/server/internal/integrations/wecom/replier_test.go b/server/internal/integrations/wecom/replier_test.go
index 6eafbd7441..adfdf5e032 100644
--- a/server/internal/integrations/wecom/replier_test.go
+++ b/server/internal/integrations/wecom/replier_test.go
@@ -55,6 +55,14 @@ type recordingConn struct {
sender *wsSender
refuseCode int
refuseMsg string
+
+ // refuseFromSend and swallowAckFromSend act on aibot_send_msg frames
+ // only, counted 1-based, and are how a test refuses or loses the verdict
+ // on the SECOND piece of a split answer while the first one lands. Zero
+ // leaves both off.
+ refuseFromSend int
+ swallowAckFromSend int
+ sends int
}
// autoAck wires the double to answer the sender's writes. Call it after
@@ -73,8 +81,16 @@ func (c *recordingConn) WriteMessage(_ int, data []byte) error {
c.frames = append(c.frames, env)
s := c.sender
code, msg := c.refuseCode, c.refuseMsg
+ swallow := false
+ if env.Cmd == cmdSendMsg {
+ c.sends++
+ if c.refuseFromSend > 0 && c.sends >= c.refuseFromSend {
+ code, msg = 45002, "content exceed max length"
+ }
+ swallow = c.swallowAckFromSend > 0 && c.sends >= c.swallowAckFromSend
+ }
c.mu.Unlock()
- if s != nil {
+ if s != nil && !swallow {
s.routeResponse(frameEnvelope{
Headers: frameHeaders{ReqID: env.Headers.ReqID},
ErrCode: code,
@@ -83,6 +99,20 @@ func (c *recordingConn) WriteMessage(_ int, data []byte) error {
}
return nil
}
+
+// sendFrames is every aibot_send_msg body the socket was handed, refused ones
+// included — what reached the wire, not what the person can read.
+func (c *recordingConn) sendFrames() []frameEnvelope {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var out []frameEnvelope
+ for _, f := range c.frames {
+ if f.Cmd == cmdSendMsg {
+ out = append(out, f)
+ }
+ }
+ return out
+}
func (c *recordingConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
func (c *recordingConn) SetReadDeadline(time.Time) error { return nil }
func (c *recordingConn) SetWriteDeadline(time.Time) error { return nil }
diff --git a/server/internal/integrations/wecom/send_verdict_test.go b/server/internal/integrations/wecom/send_verdict_test.go
index 9b0a7475ed..3c7772a082 100644
--- a/server/internal/integrations/wecom/send_verdict_test.go
+++ b/server/internal/integrations/wecom/send_verdict_test.go
@@ -5,6 +5,7 @@ package wecom
// the server refused was indistinguishable from one it accepted.
import (
+ "context"
"errors"
"testing"
"time"
@@ -49,3 +50,97 @@ func TestSendTextSucceedsOnAZeroErrcode(t *testing.T) {
t.Fatalf("wrote %d frames, want 1", n)
}
}
+
+// A send whose context was already over when it began is the one failure on
+// this path that is certain, and all three classifiers used to call it
+// uncertain.
+//
+// request checks the context before it mints a req_id, before it registers a
+// waiter and before it builds a frame (ws_sender.go), so at that point NOTHING
+// has left this process. It returned a bare ctx.Err() there, which is also
+// what the wait for a verdict AFTER the write used to return — and every
+// classifier reads a bare context error as "the frame may be in front of the
+// person already", because for the post-write case that is the true reading.
+// So a send that never started filed as "outcome unknown": the direct path
+// counted it unconfirmed, which is the one outcome nobody may resend; the
+// relay settled its claim and stopped re-offering the frame; and the media
+// path told the user its file might have arrived. The answer is lost and the
+// party whose job is to try again is told not to.
+//
+// It is reachable in production and not only from a test. chatLocks.acquire's
+// blocking select has two ready cases the moment the lock frees and the
+// delivery budget expires together, and Go picks among ready cases at random,
+// so it can hand back the chat's turn together with a context that is already
+// over — and this check is the next thing that runs. perform gives every
+// claimed delivery a DeliveryBudget of its own (relay_outbound.go), so that
+// coincidence gets one chance per offer rather than one per reply.
+//
+// Both pushes are here because both reach the same check by the same route:
+// sendTextCtx and sendMedia take the chat's turn and then call sendMsgFrame,
+// which calls request.
+//
+// REVERSE VERIFICATION: return the bare ctx.Err() from request's pre-write
+// check again and every assertion below flips — provablyNotSent false,
+// unconfirmedReason "interrupted", sendOutcome unknown, on both pushes.
+func TestASendThatNeverStartedIsProvablyNotSent(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ send func(*wsSender, context.Context) error
+ }{
+ {"a text push", func(s *wsSender, ctx context.Context) error {
+ return s.sendTextCtx(ctx, "CHAT_1", chatTypeSingleInt, "答案")
+ }},
+ {"a media push", func(s *wsSender, ctx context.Context) error {
+ return s.sendMedia(ctx, "CHAT_1", chatTypeSingleInt, mediaSend{
+ Kind: mediaTypeFile, MediaID: "MEDIA_1",
+ })
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ conn := &recordingConn{}
+ sender := conn.autoAck(newWSSender(conn, testLogger()))
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ // Nobody holds this chat, and acquire takes a free chat without
+ // consulting the context at all (ws_sender.go) — so the failure
+ // below is request's pre-write check and nothing else.
+ err := tc.send(sender, ctx)
+
+ if err == nil {
+ t.Fatal("a send on a context that was already over reported success")
+ }
+ if got := conn.sendFrames(); len(got) != 0 {
+ t.Fatalf("%d frame(s) reached the wire: %v — nothing here is a send that never started", len(got), got)
+ }
+ // The relay's classifier: false settles the claim and stops the
+ // re-offer chain on an answer the socket never saw.
+ if !provablyNotSent(err) {
+ t.Errorf("provablyNotSent(%v) = false, want true", err)
+ }
+ // The direct path's: a reason here counts the reply unconfirmed,
+ // which tells an operator not to resend a message nobody sent.
+ if got := unconfirmedReason(err); got != "" {
+ t.Errorf("unconfirmedReason(%v) = %q, want \"\" — %q says the message may be on the person's screen", err, got, got)
+ }
+ // The media path's: unknown is never retried and is described to
+ // the user in words that hold either way.
+ if got := sendOutcome(err); got != deliveryDefinitelyFailed {
+ t.Errorf("sendOutcome(%v) = %v, want %v", err, got, deliveryDefinitelyFailed)
+ }
+ // And the cause is still in there, which two readers need. The log
+ // line wants to say what ended the send; and sendMsgFrame's
+ // closing switch answers a throttled retry that was cut short
+ // before its second write with the FIRST attempt's stated refusal,
+ // through the context arm this error has to keep matching
+ // (rate_limit.go). Dropping the cause would send that arm to its
+ // default and report a cancellation over a definite refusal.
+ if !errors.Is(err, context.Canceled) {
+ t.Errorf("errors.Is(%v, context.Canceled) = false — the cause is what the log line "+
+ "and sendMsgFrame's closing switch read", err)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.go
index e4bfbec382..fa37b67df1 100644
--- a/server/internal/integrations/wecom/ws_frame.go
+++ b/server/internal/integrations/wecom/ws_frame.go
@@ -13,8 +13,10 @@ package wecom
import (
"encoding/json"
"errors"
+ "fmt"
"strings"
"unicode"
+ "unicode/utf8"
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
@@ -881,3 +883,112 @@ func hasVisibleChar(s string) bool {
}
return false
}
+
+// sendMsgContentLimit is the cap on one aibot_send_msg markdown body: the same
+// 20480 utf8 bytes the stream frame gets
+// (https://developer.work.weixin.qq.com/document/path/101138). A body past it
+// is refused WHOLE — the server does not clip it — and the refusal arrives as
+// errcode 45002 on the ack, so before splitForWire a long answer simply never
+// appeared in the chat.
+const sendMsgContentLimit = 20480
+
+// splitForWire cuts a reply into pieces the platform will accept, and returns
+// the input untouched when it already fits — which is nearly always, so the
+// common path allocates nothing.
+//
+// Splitting rather than truncating is the point. A long answer is a code
+// review, a pasted log, a document draft: the tail is not filler, and neither
+// a reply the server refuses whole nor one that stops at an ellipsis with no
+// way to read the rest is an answer. The cut prefers a line boundary, then a
+// rune boundary, so a piece never ends mid-character and rarely ends mid-line.
+//
+// Each piece carries a marker so the reader knows the answer continues. This
+// is the one place the adapter adds words to an agent's own text, which is why
+// the marker is a bare counter rather than a sentence: it belongs to no
+// language, so it needs no translation and cannot contradict an answer written
+// in one.
+func splitForWire(content string) []string {
+ if len(content) <= sendMsgContentLimit {
+ return []string{content}
+ }
+
+ var pieces []string
+ remaining := content
+ for len(remaining) > 0 {
+ // Reserve room for the widest marker this piece could end up with.
+ // The total is not known until the split is done, so the placeholder
+ // stands in for it: "…" is three bytes, which covers a total up to
+ // three digits — far past any answer that reaches this function.
+ marker := fmt.Sprintf("\n\n(%d/…)", len(pieces)+1)
+ budget := sendMsgContentLimit - len(marker)
+ if len(remaining) <= sendMsgContentLimit {
+ pieces = append(pieces, remaining)
+ break
+ }
+ cut := wireCutPoint(remaining, budget)
+ // Nothing is dropped at the seam. The cut is an index into remaining
+ // and both sides of it are kept: a line break the cut point chose ends
+ // the piece it belongs to, so concatenating the pieces with their
+ // markers stripped gives the answer back byte for byte. An earlier
+ // version trimmed leading newlines here, which silently ate a
+ // paragraph break out of every log and code block long enough to
+ // split.
+ pieces = append(pieces, remaining[:cut])
+ remaining = remaining[cut:]
+ }
+
+ // A piece with nothing visible in it is not sent. A long answer that ends
+ // in a run of blank lines puts that run in a piece of its own — the last
+ // piece carries no marker, so nothing else makes it visible — and that
+ // piece reaches the chat as an empty bubble, which is the thing
+ // hasVisibleChar exists at the call sites to prevent. Dropping it costs
+ // the reader nothing: what is dropped is whitespace that would have
+ // occupied a whole message on its own.
+ //
+ // Filtered before the markers go on, so the numbering counts the pieces
+ // the person actually receives.
+ kept := pieces[:0]
+ for _, p := range pieces {
+ if hasVisibleChar(p) {
+ kept = append(kept, p)
+ }
+ }
+ pieces = kept
+
+ // The count is only knowable once the split is done, so the markers go on
+ // afterwards. The last piece gets none: there is nothing after it to
+ // promise, and the reader can see that for themselves.
+ total := len(pieces)
+ for i := range pieces {
+ if i == total-1 {
+ continue
+ }
+ pieces[i] += fmt.Sprintf("\n\n(%d/%d)", i+1, total)
+ }
+ return pieces
+}
+
+// wireCutPoint picks where to end a piece: the last line break inside the
+// budget when there is one worth using, otherwise the last rune boundary.
+func wireCutPoint(s string, budget int) int {
+ if budget >= len(s) {
+ return len(s)
+ }
+ // A line break in the last quarter of the budget is worth taking; one
+ // near the start would waste most of a frame. The cut goes AFTER it, so
+ // the break stays at the end of the piece it terminated rather than
+ // falling into the gap between two frames.
+ if nl := strings.LastIndexByte(s[:budget], '\n'); nl > budget*3/4 {
+ return nl + 1
+ }
+ cut := budget
+ for cut > 0 && !utf8.RuneStart(s[cut]) {
+ cut--
+ }
+ if cut == 0 {
+ // A single rune wider than the budget cannot happen at this size, but
+ // returning 0 would loop forever, so fall back to the raw cut.
+ return budget
+ }
+ return cut
+}
diff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.go
index 91b518bb10..3b0b44222a 100644
--- a/server/internal/integrations/wecom/ws_sender.go
+++ b/server/internal/integrations/wecom/ws_sender.go
@@ -90,8 +90,138 @@ type wsSender struct {
// job, because a pong echoes the server's req_id and that may be empty
// or repeated. It never goes on the wire.
seq uint64
+
+ // chats serializes whole logical messages per target chat. mu orders one
+ // frame write; it is released before the ack wait, which is where an
+ // unrelated send used to land between two pieces of one answer.
+ //
+ // EVERY push the reader sees takes it: text through sendTextCtx and files
+ // through sendMedia. Half of that is no rule at all — a picture between
+ // "(1/3)" and "(2/3)" is the same unreadable chat as a stray sentence
+ // there, and attachment delivery is spawned alongside the answer it came
+ // with, so the two are concurrent by construction rather than by
+ // coincidence. What it does NOT cover is the upload: that puts nothing in
+ // the chat, and holding the chat's turn for a multi-megabyte transfer
+ // would queue every other message behind bytes that have not yet become a
+ // message.
+ chats chatLocks
+}
+
+// chatLocks is one lock per target chat, created on demand and dropped when
+// the last holder leaves, so a process that has talked to many chats does not
+// keep an entry for each of them forever.
+//
+// Per CHAT rather than per connection on purpose: a second answer to a
+// different room has no reason to queue behind this one, and the ping loop
+// writes through request/write and never takes a chat lock at all, so it
+// cannot be held up by a send.
+type chatLocks struct {
+ mu sync.Mutex
+ locks map[string]*chatLock
+}
+
+type chatLock struct {
+ // ch is a mutex that can be waited on with a context: capacity one, a
+ // token in it means held.
+ ch chan struct{}
+ refs int
}
+// acquire blocks until this chat is free or ctx ends. The returned release is
+// nil when it returns an error.
+//
+// The wait is bounded by whoever holds it: a holder is inside at most one
+// ackTimeout per piece, and the pieces of one answer are few. A caller on
+// context.Background therefore waits rather than interleaving, which is the
+// whole point — the alternative is the reader seeing an unrelated message
+// wedged into the middle of an answer.
+func (c *chatLocks) acquire(ctx context.Context, chatID string) (func(), error) {
+ c.mu.Lock()
+ if c.locks == nil {
+ c.locks = make(map[string]*chatLock)
+ }
+ l := c.locks[chatID]
+ if l == nil {
+ l = &chatLock{ch: make(chan struct{}, 1)}
+ c.locks[chatID] = l
+ }
+ l.refs++
+ c.mu.Unlock()
+
+ release := func() {
+ <-l.ch
+ c.mu.Lock()
+ l.refs--
+ if l.refs == 0 {
+ delete(c.locks, chatID)
+ }
+ c.mu.Unlock()
+ }
+ drop := func() {
+ c.mu.Lock()
+ l.refs--
+ if l.refs == 0 {
+ delete(c.locks, chatID)
+ }
+ c.mu.Unlock()
+ }
+
+ // A free chat is taken without consulting the context at all. select picks
+ // at RANDOM among ready cases, so a caller whose context is already dead
+ // arriving at a chat nobody holds would otherwise be turned away half the
+ // time for a chat nobody was using.
+ //
+ // It also keeps errChatBusy honest: it is returned only when the chat
+ // really was somebody else's and the wait ran out. What the caller gets
+ // instead is request's pre-write check, which is the same fact under a
+ // different name — both wrap errNotAttempted, so the classifiers cannot
+ // tell them apart and do not need to.
+ select {
+ case l.ch <- struct{}{}:
+ return release, nil
+ default:
+ }
+ select {
+ case l.ch <- struct{}{}:
+ return release, nil
+ case <-ctx.Done():
+ drop()
+ return nil, fmt.Errorf("%w: %w", errChatBusy, ctx.Err())
+ }
+}
+
+// errNotAttempted marks a send that ended BEFORE any byte could leave this
+// process. It is the one mark on this path that means "certainly not
+// delivered", and it is the only thing the three classifiers have to test for
+// — provablyNotSent (relay_outbound.go), unconfirmedReason (outbound_outcome.go)
+// and sendOutcome (outbound_media.go).
+//
+// It exists because the bare ctx.Err() these paths used to return said the
+// opposite. Every classifier reads a context error as "the frame may be in
+// front of the person already" — the right reading for a context that ended
+// while waiting for a VERDICT (errAckAbandoned), and the exact inversion of
+// one that ended before the write. So the direct path filed a message it had
+// never sent as "outcome unknown", which is the one outcome nobody may resend;
+// the relay settled its claim and stopped offering it; and the media path told
+// the user their file might have arrived. The user got nothing and the party
+// whose job is to try again was told not to.
+//
+// Every not-attempted failure WRAPS this rather than carrying its own
+// unrelated sentinel, so the classifiers ask one question instead of keeping a
+// list in step with this file. Two failures wrap it today: the chat lock's
+// wait running out (errChatBusy) and request's pre-write check.
+//
+// Each of those also wraps ctx.Err(), because the cause is worth having in a
+// log line. That is why every classifier has to test for this AHEAD of its
+// generic context branch — errors.Is finds context.Canceled in here too.
+var errNotAttempted = errors.New("wecom: nothing was written")
+
+// errChatBusy — the wait for this chat's turn ended before the turn came, and
+// NOT ONE BYTE went anywhere. The lock is taken before a frame is built, so
+// this and request's pre-write check are the two failures on the send path
+// that are provably non-deliveries.
+var errChatBusy = fmt.Errorf("%w; the wait for this chat's turn ended first", errNotAttempted)
+
func newWSSender(conn wsConn, log *slog.Logger) *wsSender {
if log == nil {
log = slog.Default()
@@ -202,7 +332,13 @@ func (s *wsSender) deliverReply(env frameEnvelope) bool {
// errcode, errAckTimeout, or a transport failure.
func (s *wsSender) request(ctx context.Context, cmd string, body map[string]any) (json.RawMessage, error) {
if err := ctx.Err(); err != nil {
- return nil, err
+ // Marked, for the same reason the wait below is marked and the
+ // opposite fact. Nothing has been minted, registered or built at this
+ // point, so this is proof the peer saw nothing — and a bare ctx.Err()
+ // here is indistinguishable from the one twenty lines down, which
+ // proves the opposite. A caller that cannot tell them apart has to
+ // read both the same way, and either reading is wrong for one of them.
+ return nil, fmt.Errorf("%w: %w", errNotAttempted, err)
}
reqID := newReqID()
w, ok := s.awaitReply(reqID)
@@ -302,15 +438,16 @@ var errWriteAttempted = errors.New("wecom: frame write attempted")
// than replacing it, so every errors.Is(err, context.Canceled) reader keeps
// working and the outcome still files as "interrupted".
//
-// It exists because request returns ctx.Err() from two places that mean
+// It exists because request raises a context error in two places that mean
// opposite things — the check ahead of the write, where nothing left this
-// process, and the wait after it, where the peer may already hold the frame.
-// Until this mark, the two differed only in the line that raised them, which
-// is not something a caller can see. A caller weighing a cancellation against
-// another outcome it already holds then has to read every cancellation the
-// same way, and either one of those readings is wrong. sendMsgFrame is that
-// caller: it holds a refusal WeCom stated for a first frame, and must not let
-// it speak for a second one that is already on the wire.
+// process (errNotAttempted), and the wait after it, where the peer may already
+// hold the frame. Until the two marks, they differed only in the line that
+// raised them, which is not something a caller can see. A caller weighing a
+// cancellation against another outcome it already holds then has to read every
+// cancellation the same way, and either one of those readings is wrong.
+// sendMsgFrame is that caller: it holds a refusal WeCom stated for a first
+// frame, and must not let it speak for a second one that is already on the
+// wire.
var errAckAbandoned = errors.New("wecom: the wait for the verdict was cut short after the frame went out")
// sendText pushes an aibot_send_msg (proactive push) with plain text to a
@@ -330,7 +467,67 @@ func (s *wsSender) sendText(chatID string, chatTypeInt int, content string) erro
// Safe to block here only because inbound callbacks no longer run on the read
// loop (wecom_channel.go): the read loop is the sole deliverer of acks, so a
// send that waited for one from inside a callback would have waited on itself.
+// It is also where a long answer is cut into pieces the server will accept.
+// That belongs here rather than at any one call site because a body past the
+// cap is refused WHOLE: every caller that pushes plain text — the agent's
+// reply, an inbox card, a relayed frame — would otherwise have to remember the
+// rule, and the one that forgot would lose its message silently.
+//
+// A piece that fails stops the rest: the pieces after it are the tail of an
+// answer whose head did not arrive, and sending them alone would read as the
+// bot replying to nothing.
+//
+// A failure past the FIRST piece is wrapped in errPartiallySent, because the
+// caller's question — may this send be tried again? — has a different answer
+// once part of the answer is in the chat.
func (s *wsSender) sendTextCtx(ctx context.Context, chatID string, chatTypeInt int, content string) error {
+ pieces := splitForWire(content)
+ // Held for every send, not only a split one: a single-frame push from
+ // another caller — an inbox card, the file this same answer produced
+ // (sendMedia takes the same lock), the unsupported-type notice — is
+ // exactly what used to arrive between piece one and piece two, and with
+ // two long answers in flight at once the (n/total) counters could not be
+ // matched back to their own text.
+ //
+ // A caller whose context ends while queued here gets errChatBusy, which
+ // wraps errNotAttempted: nothing has been built yet, let alone written,
+ // and the classifiers have to be able to tell that from a context that
+ // ended while waiting for a verdict.
+ release, err := s.chats.acquire(ctx, chatID)
+ if err != nil {
+ return err
+ }
+ defer release()
+ for i, piece := range pieces {
+ if err := s.sendOneTextCtx(ctx, chatID, chatTypeInt, piece); err != nil {
+ if i > 0 {
+ return fmt.Errorf("%w: %w", errPartiallySent, err)
+ }
+ return err
+ }
+ }
+ return nil
+}
+
+// errPartiallySent marks a long answer whose LATER piece failed after an
+// earlier one was accepted by the server.
+//
+// It exists for one caller decision. Everything else on this path asks "did
+// this frame reach the peer", and for the failing piece the honest answer may
+// still be no — but the SEND is not the frame. splitForWire cuts one answer
+// into several aibot_send_msg frames, and by the time piece two fails, piece
+// one is already in the user's chat. A caller that reads the failure as "this
+// send put nothing on the wire" and retries the whole content prints the first
+// piece a second time, which is the one outcome a retry exists to avoid.
+//
+// So this is deliberately NOT a claim about the failing frame — provablyNotSent
+// asks about the send as a whole, and this answers that question.
+var errPartiallySent = errors.New("wecom: an earlier piece of this answer was already accepted")
+
+// sendOneTextCtx writes exactly one aibot_send_msg frame and reads its ack.
+// Nothing here may exceed the cap: splitForWire is the only thing standing
+// between an agent's answer and a 45002 refusal.
+func (s *wsSender) sendOneTextCtx(ctx context.Context, chatID string, chatTypeInt int, content string) error {
body, err := sendMsgTextBody(chatID, chatTypeInt, content)
if err != nil {
return err