Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6569 feat(wecom): give every undelivered reply a reason an operator can count (#7428)
Xichang(Seacen) Zhao7c0e75045259
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f1ca5febff..eaa3f9a31c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -967,6 +967,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BuswecomOutboundOpts = append(wecomOutboundOpts, wecom.WithAttachments(store))h.DeclareChannelFileDelivery(string(wecom.TypeWecom))}+ // The outbound subscriber reports to the same sink the+ // connection path uses, so an operator reads "replies are+ // being dropped, and for which reason" off the same dashboard+ // as "the bot cannot connect".+ wecomOutboundOpts = append(wecomOutboundOpts,+ wecom.WithOutboundMetrics(wecomMetricsOrNil(opts.WecomMetrics)))wecom.NewOutbound(queries, wecomSenders, slog.Default(), wecomOutboundOpts...).Register(bus)// Ranges the media fetcher may dial despite looking reserved.diff --git a/server/internal/integrations/wecom/metrics.go b/server/internal/integrations/wecom/metrics.goindex d8674f3854..c179935fae 100644--- a/server/internal/integrations/wecom/metrics.go+++ b/server/internal/integrations/wecom/metrics.go@@ -52,16 +52,66 @@ type Metrics interface {// engine is not keeping up with one bot's traffic, and past a point// WeCom stops seeing the socket drained and replaces the connection.RecordCallbackQueueBlocked()++ // RecordOutboundDelivered — one reply reached the user. It is the+ // denominator: without it a flat drop counter cannot be told apart from a+ // quiet day, and "the bot went silent" is exactly the report that cannot+ // afford that ambiguity.+ RecordOutboundDelivered()+ // RecordOutboundDropped — one reply the adapter owed a user and did not+ // deliver, labelled with why (outbound_outcome.go's closed reason set).+ // Every reason here leaves somebody in WeCom waiting on an answer that is+ // not coming, so this IS an error total and the label says which failure it+ // was. The ordinary outcomes — a question typed in the web UI on a+ // WeCom-bound session, an installation revoked between trigger and reply —+ // are not counted here; RecordOutboundSkipped has them.+ RecordOutboundDropped(reason string)+ // RecordOutboundSkipped — a completion this adapter was never going to+ // deliver, because it was not owed to a WeCom user in the first place. Kept+ // apart from dropped on purpose: counting a web-UI question's answer as a+ // failed WeCom delivery makes ordinary web usage look like an outage.+ RecordOutboundSkipped(reason string)++ // RecordAttachmentDelivered / RecordAttachmentDropped count FILES, one per+ // file, while the three above count REPLIES, one per reply. The two units+ // are separate because a reply whose words arrived and whose file did not+ // is a delivered reply with a failed attachment, and collapsing that into+ // one number can only lie in one direction or the other.+ RecordAttachmentDelivered()+ RecordAttachmentDropped(reason string)++ // RecordAttachmentDeliveryShed counts a SCHEDULING decision: one delivery+ // attempt refused admission before the lookup ran. Its own unit because at+ // that point nothing knows whether the turn carries zero files or five —+ // counting it as file drops fabricates cardinality in both directions.+ RecordAttachmentDeliveryShed()++ // RecordOutboundUnconfirmed / RecordAttachmentUnconfirmed — the outcome is+ // UNKNOWN: the frame reached the wire (or the wait for its verdict was cut+ // short) and the message may already be in front of the user. Its own pair+ // because folding it into dropped would inflate a definite failure rate+ // with sends that probably succeeded, and an operator paging on the drop+ // rate would be paged for deliveries that happened.+ RecordOutboundUnconfirmed(reason string)+ RecordAttachmentUnconfirmed(reason string)}// nopMetrics is what the constructor falls back to. A nil sink must never be a// nil-pointer dereference on the read loop.type nopMetrics struct{}-func (nopMetrics) RecordConnectFailure() {}-func (nopMetrics) RecordAuthFailure() {}-func (nopMetrics) RecordCallbackQueued() {}-func (nopMetrics) RecordCallbackQueueBlocked() {}+func (nopMetrics) RecordConnectFailure() {}+func (nopMetrics) RecordAuthFailure() {}+func (nopMetrics) RecordCallbackQueued() {}+func (nopMetrics) RecordCallbackQueueBlocked() {}+func (nopMetrics) RecordOutboundDelivered() {}+func (nopMetrics) RecordOutboundDropped(string) {}+func (nopMetrics) RecordOutboundSkipped(string) {}+func (nopMetrics) RecordAttachmentDelivered() {}+func (nopMetrics) RecordAttachmentDropped(string) {}+func (nopMetrics) RecordAttachmentDeliveryShed() {}+func (nopMetrics) RecordOutboundUnconfirmed(string) {}+func (nopMetrics) RecordAttachmentUnconfirmed(string) {}// orNopMetrics turns an unset sink into one that is safe to call.func orNopMetrics(m Metrics) Metrics {diff --git a/server/internal/integrations/wecom/metrics_test.go b/server/internal/integrations/wecom/metrics_test.goindex 1c30368daa..ffce6c0876 100644--- a/server/internal/integrations/wecom/metrics_test.go+++ b/server/internal/integrations/wecom/metrics_test.go@@ -48,6 +48,29 @@ func (m *countingMetrics) RecordConnectFailure() { m.bump("connect_failurefunc (m *countingMetrics) RecordAuthFailure() { m.bump("auth_failure") }func (m *countingMetrics) RecordCallbackQueued() { m.bump("callback_queued") }func (m *countingMetrics) RecordCallbackQueueBlocked() { m.bump("callback_blocked") }+func (m *countingMetrics) RecordOutboundDelivered() { m.bump("outbound_delivered") }+func (m *countingMetrics) RecordOutboundDropped(reason string) {+ m.bump("outbound_dropped")+ m.bump("outbound_dropped:" + reason)+}+func (m *countingMetrics) RecordOutboundSkipped(reason string) {+ m.bump("outbound_skipped")+ m.bump("outbound_skipped:" + reason)+}+func (m *countingMetrics) RecordAttachmentDelivered() { m.bump("attachment_delivered") }+func (m *countingMetrics) RecordAttachmentDropped(reason string) {+ m.bump("attachment_dropped")+ m.bump("attachment_dropped:" + reason)+}+func (m *countingMetrics) RecordAttachmentDeliveryShed() { m.bump("attachment_shed") }+func (m *countingMetrics) RecordOutboundUnconfirmed(reason string) {+ m.bump("outbound_unconfirmed")+ m.bump("outbound_unconfirmed:" + reason)+}+func (m *countingMetrics) RecordAttachmentUnconfirmed(reason string) {+ m.bump("attachment_unconfirmed")+ m.bump("attachment_unconfirmed:" + reason)+}var _ Metrics = (*countingMetrics)(nil)diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex c935fe7c13..025ee5d6ff 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -69,6 +69,10 @@ type Outbound struct {// test can run it inline and observe the result deterministically.spawn func(func())+ // metrics counts what happened to each reply. Nil discards; see+ // outbound_outcome.go for why the drop breakdown exists at all.+ metrics Metrics+// Two counters bound attachment delivery, and they are two because one// cannot be in both places at once.//@@ -132,9 +136,16 @@ func (o *Outbound) handleEvent(e events.Event) {// publish call site. Fresh ctx with a tight timeout, same as Slack.ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()+ // One place records an undelivered reply, so a drop is counted exactly+ // once and always carries a reason. The branches inside processEvent that+ // end a turn without an error of their own record themselves and return+ // nil; everything that surfaces here is classified from the error.if err := o.processEvent(ctx, e); err != nil {- o.logger.WarnContext(ctx, "wecom outbound: reply delivery failed",- "error", err, "chat_session_id", e.ChatSessionID)+ if reason := unconfirmedReason(err); reason != "" {+ o.unconfirmed(ctx, e, reason, err)+ } else {+ o.dropped(ctx, e, classifyDrop(err), err)+ }}}@@ -150,7 +161,8 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {// the work away.content := chatDoneContent(e.Payload)if content == "" && !o.mayCarryAttachments(e) {- return nil // nothing to say, nothing to send+ o.skipped(ctx, e, skipNothingToSay)+ return nil}// Only bound, non-empty completions reach here, so classify the task// origin before loading credentials or sending. A question asked in the@@ -168,6 +180,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {// the room's message either.taskID, ok := chatDoneTaskID(e)if !ok {+ o.dropped(ctx, e, dropTaskMissing, nil)return nil}delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)@@ -185,6 +198,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {if err != nil {if errors.Is(err, pgx.ErrNoRows) {// Cancelled and deleted while its completion was in flight.+ o.dropped(ctx, e, dropTaskMissing, nil)return nil}return fmt.Errorf("wecom: load agent task: %w", err)@@ -194,6 +208,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {return fmt.Errorf("wecom: classify task input origin: %w", err)}if !deliver {+ o.skipped(ctx, e, skipOriginNotChannel)return nil}inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{@@ -204,7 +219,8 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {return fmt.Errorf("wecom: load installation: %w", err)}if inst.Status != string(InstallationActive) {- return nil // revoked between trigger and reply+ o.skipped(ctx, e, skipInstallationInactive) // revoked between trigger and reply+ return nil}if o.senders == nil {return errors.New("wecom: sender registry not configured")@@ -220,7 +236,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {// file's header). Either way, buffering is wrong — the reply is stale// by the time a socket returns — so we surface it to the caller's WARN// rather than drop it silently.- return errors.New("wecom: connection not ready on this replica")+ return errNoLiveConnection}chatType := aibotChatTypeFromChannel(channel.ChatType(binding.ChatType))// Words first. An empty completion reaches here only because a file is@@ -230,14 +246,19 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {if err := sender.sendTextCtx(ctx, binding.ChannelChatID, chatType, content); err != nil {return err}+ o.delivered()}// Then whatever the agent produced alongside them, as its own message — a// WeCom reply cannot carry a file inline.+ // carriesTheReply is true when the files ARE the answer: an empty+ // completion reached here only because one is bound to it, so nothing has+ // been counted for this reply yet and the attachment path owes its outcome.o.deliverAttachments(e, attachmentTarget{InstallationID: binding.InstallationID,ChatID: binding.ChannelChatID,ChatType: chatType,- })+ SessionID: e.ChatSessionID,+ }, content == "")return nil}diff --git a/server/internal/integrations/wecom/outbound_media.go b/server/internal/integrations/wecom/outbound_media.goindex 237ea8edea..ecb7906db4 100644--- a/server/internal/integrations/wecom/outbound_media.go+++ b/server/internal/integrations/wecom/outbound_media.go@@ -140,6 +140,9 @@ type attachmentTarget struct {InstallationID pgtype.UUIDChatID stringChatType int+ // SessionID is carried only so a delivery that fails minutes later can+ // still name the conversation it belonged to in the log and the counter.+ SessionID string}// OutboundOption configures the chat-done subscriber at construction.@@ -162,7 +165,12 @@ func (o *Outbound) mayCarryAttachments(e events.Event) bool {// deliverAttachments hands the answer's files to a goroutine of their own, if// there are any to hand over. It is called after the words are out, and// returns immediately.-func (o *Outbound) deliverAttachments(e events.Event, to attachmentTarget) {+// carriesTheReply says the files ARE this reply's substance — the agent said+// nothing and bound a file instead. When it is true nothing has recorded a+// reply outcome yet and this path owes exactly one; when it is false the words+// already landed and the reply's outcome is settled, so only the per-file+// counters move here.+func (o *Outbound) deliverAttachments(e events.Event, to attachmentTarget, carriesTheReply bool) {if o.objects == nil || o.senders == nil {return}@@ -189,6 +197,15 @@ func (o *Outbound) deliverAttachments(e events.Event, to attachmentTarget) {// have carried none is the false alarm the post-lookup gate exists to// avoid.if !o.admitAttachmentDelivery() {+ // A scheduling refusal, counted under its own unit, and NOTHING else:+ // the comment above is literal — this gate runs before the lookup, so+ // it knows neither how many files the turn carries nor whether it+ // carries any at all. A per-file counter fed from here fabricates+ // cardinality, and a reply outcome asserted from here fabricates the+ // reply: an empty completion with zero bound files would be counted+ // as a dropped reply when the lookup would have classified it as+ // nothing_to_say. What cannot be known here is not recorded here.+ o.attachmentShed()o.logger.Warn("wecom outbound: attachment delivery not admitted, too many already running","installation_id", uuidStringPub(to.InstallationID),"admitted", maxAdmittedAttachmentDeliveries)@@ -198,7 +215,7 @@ func (o *Outbound) deliverAttachments(e events.Event, to attachmentTarget) {defer o.releaseAttachmentAdmission()ctx, cancel := context.WithTimeout(context.Background(), attachmentBudget)defer cancel()- o.sendAttachments(ctx, messageID, workspaceID, to)+ o.sendAttachments(ctx, messageID, workspaceID, to, carriesTheReply)})}@@ -215,7 +232,15 @@ func (o *Outbound) deliverAttachments(e events.Event, to attachmentTarget) {// one can only be reported honestly by something that already knows a file was// waiting. Rationing this stage ahead of the lookup would either stay silent// about a file that was dropped or warn about a file that never existed.-func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID pgtype.UUID, to attachmentTarget) {+func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID pgtype.UUID, to attachmentTarget, carriesTheReply bool) {+ // replyFailed records this reply's single outcome, but only when the files+ // ARE the reply. When words already landed the reply is settled and only+ // the per-file counters move.+ replyFailed := func(reason dropReason, err error) {+ if carriesTheReply {+ o.droppedFor(ctx, to.SessionID, "chat:done", reason, err)+ }+ }rows, err := o.q.ListAttachmentsByChatMessage(ctx, db.ListAttachmentsByChatMessageParams{ChatMessageID: messageID,WorkspaceID: workspaceID,@@ -224,9 +249,14 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID po.logger.WarnContext(ctx, "wecom outbound: attachment lookup failed","error", err, "chat_message_id", uuidStringPub(messageID))o.tellUser(ctx, to, mediaLookupFailedText)+ replyFailed(dropTransport, err)return}if len(rows) == 0 {+ // mayCarryAttachments said there might be one; there was not.+ if carriesTheReply {+ o.skippedFor(ctx, to.SessionID, skipNothingToSay)+ }return}// Past here a file is known to be waiting, so every way out of this@@ -237,6 +267,13 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID p// wait for it, and unlike admission it can name what was dropped, so the// user hears about it.if !o.claimAttachmentSlot() {+ // Unlike admission, the rows are known here, so the accounting can be+ // exact: one drop per file that will not be sent, and — when the files+ // were the reply — the reply's own outcome.+ for range rows {+ o.attachmentDropped(ctx, dropAttachmentNotAdmitted, nil)+ }+ replyFailed(dropAttachmentNotAdmitted, nil)o.logger.WarnContext(ctx, "wecom outbound: attachment delivery shed, too many already pending","installation_id", uuidStringPub(to.InstallationID),"attachments", len(rows),@@ -254,11 +291,17 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID pcase attachmentSlots <- struct{}{}:defer func() { <-attachmentSlots }()case <-ctx.Done():+ // The rows are known here, so every one of them settles: nothing was+ // sent, which is the one case that is provably local.+ for range rows {+ o.attachmentDropped(ctx, dropTransport, ctx.Err())+ }o.logger.WarnContext(ctx, "wecom outbound: attachment delivery gave up waiting for a slot","installation_id", uuidStringPub(to.InstallationID), "attachments", len(rows))// Deliberately on a fresh context: the one that expired is the reason// we are here, and reusing it would drop the sentence too.o.tellUser(context.WithoutCancel(ctx), to, mediaSendFailedText)+ replyFailed(dropTransport, ctx.Err())return}@@ -271,16 +314,40 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID p// the socket that is missing. The log is the only place this can go.o.logger.WarnContext(ctx, "wecom outbound: no live connection for attachment delivery","installation_id", uuidStringPub(to.InstallationID), "attachments", len(rows))+ for range rows {+ o.attachmentDropped(ctx, dropNoConnection, nil)+ }+ replyFailed(dropNoConnection, nil)return}failed, unknown := 0, 0+ // replyReason aggregates the DEFINITE per-file reasons for the reply's own+ // outcome, under worseDropReason's precedence — so a single refused file+ // surfaces as platform_refused on the reply too. Unknown outcomes stay out+ // of it: a file that may have arrived must not turn the reply into a+ // definite drop.+ var replyReason dropReason+ var replyUnconfirmed stringfor _, row := range rows {state, err := o.sendAttachment(ctx, sender, row, to)switch state {case deliveryDefinitelyFailed:failed+++ r := classifyDrop(err)+ o.attachmentDropped(ctx, r, err)+ replyReason = worseDropReason(replyReason, r)case deliveryUnknown:unknown+++ // Not a failure: the frame may well have arrived. Filed under its+ // own counter so the drop rate stays a rate of definite drops.+ r := unconfirmedReason(err)+ if r == "" {+ r = "ack_timeout" // sendOutcome and unconfirmedReason share a set; belt and braces+ }+ o.attachmentUnconfirmed(ctx, r, err)+ replyUnconfirmed = worseUnconfirmedReason(replyUnconfirmed, r)+ default:+ o.attachmentDelivered()}if err != nil {// The object's URL stays out of the log: it is an address that@@ -294,6 +361,21 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID p"size_bytes", row.SizeBytes)}}+ if carriesTheReply {+ // The files were the answer. Three honest endings: any file arrived —+ // delivered; none arrived and at least one failure is definite — a+ // drop under the worst definite reason; nothing definite either way —+ // unconfirmed, because calling a maybe-delivered reply a drop points+ // the operator at a resend the user may already have.+ switch {+ case failed+unknown < len(rows):+ o.delivered()+ case failed > 0:+ o.droppedFor(ctx, to.SessionID, "chat:done", replyReason, nil)+ default:+ o.unconfirmedFor(ctx, to.SessionID, "chat:done", replyUnconfirmed, nil)+ }+ }// The answer is already on the user's screen and it may well refer to a// file. Saying nothing would leave them looking for one that never comes —// but saying "it failed" about a file that did arrive is its own harm, sodiff --git a/server/internal/integrations/wecom/outbound_media_test.go b/server/internal/integrations/wecom/outbound_media_test.goindex fd4d4fbd04..0e1280038e 100644--- a/server/internal/integrations/wecom/outbound_media_test.go+++ b/server/internal/integrations/wecom/outbound_media_test.go@@ -755,7 +755,7 @@ func TestDeliverAttachments_AdmissionBoundsTheLookupStage(t *testing.T) {const surplus = 16submitted := maxAdmittedAttachmentDeliveries + surplusfor i := 0; i < submitted; i++ {- o.deliverAttachments(chatDoneEvent("done"), target)+ o.deliverAttachments(chatDoneEvent("done"), target, false)}// Wait for the admitted ones to park in the query rather than sleeping: a@@ -869,11 +869,300 @@ func TestDeliverAttachments_IgnoresATurnItCannotAddress(t *testing.T) {target := attachmentTarget{InstallationID: instID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt}// No message id on the payload — nothing was bound to this turn.- o.deliverAttachments(events.Event{WorkspaceID: testWorkspaceID, Payload: protocol.ChatDonePayload{}}, target)+ o.deliverAttachments(events.Event{WorkspaceID: testWorkspaceID, Payload: protocol.ChatDonePayload{}}, target, false)// No workspace id.- o.deliverAttachments(chatDoneEvent("x"), attachmentTarget{InstallationID: instID, ChatID: ""})+ o.deliverAttachments(chatDoneEvent("x"), attachmentTarget{InstallationID: instID, ChatID: ""}, false)if n := len(conn.cmdFrames(cmdUploadMediaInit)); n != 0 {t.Errorf("upload init frames = %d, want 0", n)}}++// ---- outcome accounting on the shed and failure paths --------------------+//+// These are control-flow tests, deliberately: the exported-contract test in+// internal/metrics proves the collector names and labels, but says nothing+// about which branches feed them — which is exactly how three accounting bugs+// passed a green CI.++// newMediaRigWithMetrics is newOutboundWithMedia plus a counting sink.+func newMediaRigWithMetrics(t *testing.T, q outboundQueries, objects mediaObjectStore) (*Outbound, pgtype.UUID, *mediaConn, *countingMetrics) {+ t.Helper()+ reg := newSendersRegistry()+ instID := mustTestUUID(t)+ conn := newMediaConn()+ reg.set(instID, conn.newSender())+ mx := newCountingMetrics()+ opts := []OutboundOption{WithOutboundMetrics(mx)}+ if objects != nil {+ opts = append(opts, WithAttachments(objects))+ }+ o := NewOutbound(q, reg, slog.Default(), opts...)+ o.spawn = func(f func()) { f() }+ return o, instID, conn, mx+}++// Admission is refused before the lookup, so nothing knows how many files the+// turn holds — zero here, in fact. The old accounting recorded one file drop+// anyway; the truthful record is one SHED delivery, no file drops, and no+// reply outcome for a reply whose words already landed.+func TestAdmissionShed_CountsASchedulingDecisionNotFiles(t *testing.T) {+ t.Parallel()+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "a.pdf", Url: "u"})+ q.attachments = nil // the turn turns out to carry no file at all+ o, instID, _, mx := newMediaRigWithMetrics(t, q, &fakeObjectStore{})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ for i := 0; i < maxAdmittedAttachmentDeliveries; i++ {+ if !o.admitAttachmentDelivery() {+ t.Fatalf("admission %d refused before the cap", i)+ }+ }++ if err := o.processEvent(context.Background(), chatDoneEvent("Words landed.")); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if got := mx.get("attachment_shed"); got != 1 {+ t.Errorf("attachment_shed = %d, want 1", got)+ }+ if got := mx.get("attachment_dropped"); got != 0 {+ t.Errorf("attachment_dropped = %d, want 0 — no file is known to exist here", got)+ }+ if got := mx.get("outbound_dropped"); got != 0 {+ t.Errorf("outbound_dropped = %d, want 0 — the words were delivered", got)+ }+ if got := mx.get("outbound_delivered"); got != 1 {+ t.Errorf("outbound_delivered = %d, want 1", got)+ }+}++// The pending cap is refused after the lookup: one known file, and for a+// file-only reply the whole reply. Before this round the branch recorded+// neither.+func TestPendingShed_SettlesTheFilesAndTheReply(t *testing.T) {+ t.Parallel()+ q := oneAttachmentQueries(t, db.Attachment{+ ID: mustTestUUID(t), Filename: "a.pdf", Url: "https://cdn.example/obj/a", SizeBytes: 1,+ })+ o, instID, _, mx := newMediaRigWithMetrics(t, q, &fakeObjectStore{key: "obj/a", data: []byte("x")})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ for i := 0; i < maxPendingAttachmentDeliveries; i++ {+ if !o.claimAttachmentSlot() {+ t.Fatalf("slot %d refused before the cap", i)+ }+ }++ // An empty completion: the file IS the reply.+ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if got := mx.get("attachment_dropped:attachment_not_admitted"); got != 1 {+ t.Errorf("attachment_dropped:attachment_not_admitted = %d, want 1", got)+ }+ if got := mx.get("outbound_dropped:attachment_not_admitted"); got != 1 {+ t.Errorf("outbound_dropped:attachment_not_admitted = %d, want 1 — the file was the reply", got)+ }+ if got := mx.get("outbound_delivered"); got != 0 {+ t.Errorf("outbound_delivered = %d, want 0", got)+ }+}++// A file-only reply whose single file the platform refused: the reply's own+// reason must be the file's reason, not a generic transport_error.+func TestRefusedFileOnlyReply_KeepsThePlatformsReason(t *testing.T) {+ t.Parallel()+ q := oneAttachmentQueries(t, db.Attachment{+ ID: mustTestUUID(t), Filename: "big.bin", Url: "https://cdn.example/obj/bin",+ })+ o, instID, conn, mx := newMediaRigWithMetrics(t, q, &fakeObjectStore{key: "obj/bin", data: []byte("DATA")})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ conn.refuse[cmdUploadMediaInit] = 40058++ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if got := mx.get("attachment_dropped:platform_refused"); got != 1 {+ t.Errorf("attachment_dropped:platform_refused = %d, want 1", got)+ }+ if got := mx.get("outbound_dropped:platform_refused"); got != 1 {+ t.Errorf("outbound_dropped:platform_refused = %d, want 1 — the reply's reason is its file's reason", got)+ }+ if got := mx.get("outbound_dropped:transport_error"); got != 0 {+ t.Errorf("outbound_dropped:transport_error = %d, want 0 — the classified reason was discarded", got)+ }+}++// Three files, all refused: three file drops, ONE reply outcome. The two units+// must not leak into each other in either direction.+func TestMultiFileFailure_CountsFilesPerFileAndTheReplyOnce(t *testing.T) {+ t.Parallel()+ rows := []db.Attachment{+ {ID: mustTestUUID(t), Filename: "a.bin", Url: "https://cdn.example/obj/a"},+ {ID: mustTestUUID(t), Filename: "b.bin", Url: "https://cdn.example/obj/b"},+ {ID: mustTestUUID(t), Filename: "c.bin", Url: "https://cdn.example/obj/c"},+ }+ q := oneAttachmentQueries(t, rows[0])+ q.attachments = rows+ o, instID, conn, mx := newMediaRigWithMetrics(t, q, &fakeObjectStore{key: "obj/a", data: []byte("D")})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ conn.refuse[cmdUploadMediaInit] = 40058++ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if got := mx.get("attachment_dropped:platform_refused"); got != 3 {+ t.Errorf("attachment_dropped:platform_refused = %d, want 3 — files count per file", got)+ }+ if got := mx.get("outbound_dropped"); got != 1 {+ t.Errorf("outbound_dropped = %d, want exactly 1 — a reply settles once", got)+ }+}++// worseDropReason is the multi-file aggregation rule; pin it so the reply+// reason stays a rule and never becomes an accident of loop order.+func TestWorseDropReason_PrecedenceIsStable(t *testing.T) {+ t.Parallel()+ if got := worseDropReason(dropTransport, dropPlatformRefused); got != dropPlatformRefused {+ t.Errorf("refusal must outrank a transport failure, got %s", got)+ }+ if got := worseDropReason(dropPlatformRefused, dropTransport); got != dropPlatformRefused {+ t.Errorf("refusal must outrank a transport failure regardless of order, got %s", got)+ }+ if got := worseDropReason("", dropTransport); got != dropTransport {+ t.Errorf("anything outranks the zero value, got %s", got)+ }+}++// ---- round-3 review regressions ------------------------------------------++// The admission gate cannot assert a reply failure: an empty completion with+// ZERO bound files, shed at admission, must record a shed and nothing else —+// the lookup it never ran is the only thing that could have said whether a+// reply payload existed at all.+func TestAdmissionShed_EmptyContentZeroFilesAssertsNoReplyOutcome(t *testing.T) {+ t.Parallel()+ q := oneAttachmentQueries(t, db.Attachment{ID: mustTestUUID(t), Filename: "a.pdf", Url: "u"})+ q.attachments = nil+ o, instID, _, mx := newMediaRigWithMetrics(t, q, &fakeObjectStore{})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ for i := 0; i < maxAdmittedAttachmentDeliveries; i++ {+ if !o.admitAttachmentDelivery() {+ t.Fatalf("admission %d refused before the cap", i)+ }+ }++ // Empty completion: mayCarryAttachments says maybe, admission says no.+ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if got := mx.get("attachment_shed"); got != 1 {+ t.Errorf("attachment_shed = %d, want 1", got)+ }+ if got := mx.get("outbound_dropped"); got != 0 {+ t.Errorf("outbound_dropped = %d, want 0 — nothing here knew a reply payload existed", got)+ }+ if got := mx.get("outbound_delivered") + mx.get("outbound_unconfirmed"); got != 0 {+ t.Errorf("some reply outcome was asserted (%d) from a gate that cannot know one", got)+ }+}++// Three known files stuck behind a full pending queue: the slot-wait timeout+// settles each of them, not none of them.+func TestSlotWaitTimeout_SettlesEveryKnownFile(t *testing.T) {+ rows := []db.Attachment{+ {ID: mustTestUUID(t), Filename: "a.bin", Url: "https://cdn.example/obj/a"},+ {ID: mustTestUUID(t), Filename: "b.bin", Url: "https://cdn.example/obj/b"},+ {ID: mustTestUUID(t), Filename: "c.bin", Url: "https://cdn.example/obj/c"},+ }+ q := oneAttachmentQueries(t, rows[0])+ q.attachments = rows+ o, instID, _, mx := newMediaRigWithMetrics(t, q, &fakeObjectStore{key: "obj/a", data: []byte("D")})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ // Occupy the package-level in-flight slots so the wait must give up, on a+ // context that is already expired. Not t.Parallel: attachmentSlots is+ // shared with every other delivery in the package, and holding it while+ // unrelated tests run would measure this harness, not the code.+ for i := 0; i < maxConcurrentAttachmentDeliveries; i++ {+ attachmentSlots <- struct{}{}+ }+ defer func() {+ for i := 0; i < maxConcurrentAttachmentDeliveries; i++ {+ <-attachmentSlots+ }+ }()+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ o.sendAttachments(ctx, mustParseTaskUUID(t, testMessageID), mustParseTaskUUID(t, testWorkspaceID),+ attachmentTarget{InstallationID: instID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt, SessionID: testSessionID}, true)++ if got := mx.get("attachment_dropped:transport_error"); got != 3 {+ t.Errorf("attachment_dropped:transport_error = %d, want 3 — every known file settles", got)+ }+ if got := mx.get("outbound_dropped"); got != 1 {+ t.Errorf("outbound_dropped = %d, want exactly 1 for the file-only reply", got)+ }+}++// Three known files and no live sender: one drop PER FILE, one reply outcome.+func TestNoLiveSender_SettlesEveryKnownFile(t *testing.T) {+ t.Parallel()+ rows := []db.Attachment{+ {ID: mustTestUUID(t), Filename: "a.bin", Url: "https://cdn.example/obj/a"},+ {ID: mustTestUUID(t), Filename: "b.bin", Url: "https://cdn.example/obj/b"},+ {ID: mustTestUUID(t), Filename: "c.bin", Url: "https://cdn.example/obj/c"},+ }+ q := oneAttachmentQueries(t, rows[0])+ q.attachments = rows+ mx := newCountingMetrics()+ reg := newSendersRegistry() // empty: no live sender+ instID := mustTestUUID(t)+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ o := NewOutbound(q, reg, slog.Default(), WithOutboundMetrics(mx), WithAttachments(&fakeObjectStore{}))+ o.spawn = func(f func()) { f() }++ o.sendAttachments(context.Background(), mustParseTaskUUID(t, testMessageID), mustParseTaskUUID(t, testWorkspaceID),+ attachmentTarget{InstallationID: instID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt, SessionID: testSessionID}, true)++ if got := mx.get("attachment_dropped:no_live_connection"); got != 3 {+ t.Errorf("attachment_dropped:no_live_connection = %d, want 3", got)+ }+ if got := mx.get("outbound_dropped:no_live_connection"); got != 1 {+ t.Errorf("outbound_dropped:no_live_connection = %d, want 1", got)+ }+}++// An unknown outcome is not a drop. A file whose upload got no verdict files+// under unconfirmed, and a file-only reply whose every file is unknown settles+// the reply as unconfirmed — never as a definite drop an operator would act on.+func TestUnknownOutcome_IsUnconfirmedNotDropped(t *testing.T) {+ t.Parallel()+ q := oneAttachmentQueries(t, db.Attachment{+ ID: mustTestUUID(t), Filename: "a.png", Url: "https://cdn.example/obj/a", ContentType: "image/png",+ })+ o, instID, conn, mx := newMediaRigWithMetrics(t, q, &fakeObjectStore{key: "obj/a", data: []byte("PNGDATA")})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ conn.dropAcks[cmdSendMsg] = 1 // the media push gets no verdict → deliveryUnknown++ if err := o.processEvent(context.Background(), chatDoneEvent("")); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ if got := mx.get("attachment_unconfirmed"); got != 1 {+ t.Errorf("attachment_unconfirmed = %d, want 1. counts=%v", got, mx.counts)+ }+ if got := mx.get("attachment_dropped"); got != 0 {+ t.Errorf("attachment_dropped = %d, want 0 — the file may have arrived", got)+ }+ if got := mx.get("outbound_unconfirmed"); got != 1 {+ t.Errorf("outbound_unconfirmed = %d, want 1 for the file-only reply", got)+ }+ if got := mx.get("outbound_dropped"); got != 0 {+ t.Errorf("outbound_dropped = %d, want 0", got)+ }+}diff --git a/server/internal/integrations/wecom/outbound_outcome.go b/server/internal/integrations/wecom/outbound_outcome.gonew file mode 100644index 0000000000..8de9715434--- /dev/null+++ b/server/internal/integrations/wecom/outbound_outcome.go@@ -0,0 +1,290 @@+package wecom++// outbound_outcome.go — what happened to a reply this adapter was asked to+// deliver, as something an operator can count.+//+// Every branch on the outbound path that ends a turn without putting words in+// front of the user used to be a bare `return nil` or a lone WARN. That is the+// shape of GH #7215 and #6890: the answer is in the Multica transcript, the+// WeCom chat stays quiet, and the server-side evidence is either one line with+// no reason attached or nothing at all. With several distinct causes producing+// one indistinguishable symptom, neither we nor a deployment's operator can say+// which one fired, and a fix is a guess.+//+// So each of those branches names itself. The counter is the durable half — it+// is always incremented — and the log level is the judgement half: a reason a+// person should act on logs at WARN, one that is ordinary in a healthy+// deployment logs at DEBUG and is only ever read as a rate.+//+// The reason set is closed on purpose. It is a metric label, and an open one is+// the unbounded-cardinality problem forbiddenMetricLabels exists to prevent.++import (+ "context"+ "errors"++ "github.com/multica-ai/multica/server/internal/events"+)++// dropReason names why a reply did not reach the user. Closed set: see the+// file header.+type dropReason string++const (+ // dropNoConnection — no live WebSocket for this installation in THIS+ // process. Either the Supervisor is mid-reconnect, or, on a multi-replica+ // deployment, the lease is held by a different replica than the one that+ // published the completion, which is the constraint SELF_HOSTING.md+ // documents. The two are indistinguishable from here; a deployment's+ // replica count is what tells them apart.+ dropNoConnection dropReason = "no_live_connection"++ // dropTaskMissing — the task the completion belongs to could not be+ // resolved: no id on the event, or the row was reaped while its ending was+ // in flight.+ dropTaskMissing dropReason = "task_missing"++ // dropPlatformRefused — WeCom answered the send with a non-zero errcode.+ // A stated refusal: the frame was over budget, the bot is no longer in the+ // chat, the tenant is rate limited.+ dropPlatformRefused dropReason = "platform_refused"++ // dropTransport — nothing reached the platform, for a local reason. The+ // write itself failed, or a lookup ahead of it did, or this delivery's own+ // budget ran out before it got a turn on the wire. What the three have in+ // common is the fact an operator needs: the failure is on our side of the+ // socket, so nothing was shown to anybody.+ dropTransport dropReason = "transport_error"++ // dropAttachmentNotAdmitted — the delivery was shed because too many were+ // already running or pending.+ //+ // It appears on BOTH units, and means a different thing on each. On the+ // file counter it is one file that will not be sent. On the reply counter+ // it appears only when the files WERE the reply — an empty completion that+ // reached delivery because something was bound to it — and there it means+ // the user got nothing at all. A reply whose words already landed is+ // settled before this gate and never reaches it.+ dropAttachmentNotAdmitted dropReason = "attachment_not_admitted"+)++// skipReason names a completion this adapter was never going to deliver. Kept+// in its own set, and behind its own counter, because "we chose not to send+// this" and "we owed this and failed" answer different questions and only one+// of them is an incident.+type skipReason string++const (+ // skipOriginNotChannel — the turn was asked in the Multica web UI on a+ // session that originated in WeCom, so its answer belongs in Multica only.+ // Ordinary in a healthy deployment, and the single largest source of this+ // counter on a busy workspace.+ skipOriginNotChannel skipReason = "origin_not_channel"++ // skipInstallationInactive — the installation was revoked between the+ // trigger and the reply. Not a delivery failure: there is no longer an+ // installation to deliver through, and the bot is gone from the user's+ // side too.+ skipInstallationInactive skipReason = "installation_inactive"++ // skipNothingToSay — an empty completion carrying no file. There was never+ // a message here.+ skipNothingToSay skipReason = "nothing_to_say"+)++// actionable reports whether a reason is one a person should look at. The+// others are ordinary in a healthy deployment and would drown the log.+// actionable reports whether a reason is one a person should look at. Every+// drop is, now that the two ordinary outcomes have moved to skipReason.+func (r dropReason) actionable() bool { return true }++// errNoLiveConnection — no live WebSocket for this installation in this+// process. A sentinel rather than a fresh errors.New at the call site, so+// classifyDrop can name it instead of pattern-matching prose.+var errNoLiveConnection = errors.New("wecom: connection not ready on this replica")++// unconfirmedReason names a failure whose OUTCOME IS UNKNOWN — the message may+// already be in front of the user — and returns "" for one that is definite.+// The set mirrors sendOutcome's deliveryUnknown exactly: a verdict that never+// came, a failure raised by the write itself (the peer may hold bytes the+// local side reported an error for), and a context cut short while either was+// pending. Callers MUST consult this before classifyDrop: an unknown filed as+// a drop tells an operator to resend a message the user may already have.+func unconfirmedReason(err error) string {+ switch {+ case err == nil:+ return ""+ case errors.Is(err, errAckTimeout):+ return "ack_timeout"+ case errors.Is(err, errWriteAttempted):+ return "write_attempted"+ case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):+ return "interrupted"+ }+ return ""+}++// classifyDrop turns a DEFINITE send failure into the reason an operator+// reads. Definite is the caller's obligation: consult unconfirmedReason first.+func classifyDrop(err error) dropReason {+ var apiErr *wecomAPIError+ switch {+ case err == nil:+ return ""+ case errors.Is(err, errNoLiveConnection):+ return dropNoConnection+ case errors.As(err, &apiErr):+ return dropPlatformRefused+ default:+ return dropTransport+ }+}++// dropped records one undelivered reply: always a counter, and a log line whose+// level says whether somebody should act.+//+// Deliberately not an error return. Several of these branches are reached on+// events that were never this adapter's to answer, and turning them into errors+// would change what processEvent's callers — and a dozen existing tests — mean+// by "nothing to do here".+func (o *Outbound) dropped(ctx context.Context, e events.Event, reason dropReason, err error) {+ o.droppedFor(ctx, e.ChatSessionID, e.Type, reason, err)+}++// droppedFor is dropped for a caller that has a session id rather than the+// event — the attachment path, which runs long after the event is gone.+func (o *Outbound) droppedFor(ctx context.Context, sessionID, eventType string, reason dropReason, err error) {+ o.mx().RecordOutboundDropped(string(reason))+ attrs := []any{+ "reason", string(reason),+ "chat_session_id", sessionID,+ "event", eventType,+ }+ if err != nil {+ attrs = append(attrs, "error", err)+ }+ if reason.actionable() {+ o.logger.WarnContext(ctx, "wecom outbound: reply not delivered", attrs...)+ return+ }+ o.logger.DebugContext(ctx, "wecom outbound: reply not delivered", attrs...)+}++// unconfirmed records one reply whose outcome is unknown. WARN, because a+// person deciding whether to resend needs to know this is NOT a failure.+func (o *Outbound) unconfirmed(ctx context.Context, e events.Event, reason string, err error) {+ o.unconfirmedFor(ctx, e.ChatSessionID, e.Type, reason, err)+}++func (o *Outbound) unconfirmedFor(ctx context.Context, sessionID, eventType, reason string, err error) {+ o.mx().RecordOutboundUnconfirmed(reason)+ attrs := []any{"reason", reason, "chat_session_id", sessionID, "event", eventType}+ if err != nil {+ attrs = append(attrs, "error", err)+ }+ o.logger.WarnContext(ctx, "wecom outbound: reply delivery unconfirmed", attrs...)+}++// attachmentUnconfirmed records one FILE whose outcome is unknown.+func (o *Outbound) attachmentUnconfirmed(ctx context.Context, reason string, err error) {+ o.mx().RecordAttachmentUnconfirmed(reason)+ attrs := []any{"reason", reason}+ if err != nil {+ attrs = append(attrs, "error", err)+ }+ o.logger.WarnContext(ctx, "wecom outbound: attachment delivery unconfirmed", attrs...)+}++// skipped records one completion this adapter was never going to deliver.+// Always DEBUG: none of these is an incident, and on a workspace where people+// use the web UI against WeCom-bound sessions this is the busiest path here.+func (o *Outbound) skipped(ctx context.Context, e events.Event, reason skipReason) {+ o.skippedFor(ctx, e.ChatSessionID, reason)+}++func (o *Outbound) skippedFor(ctx context.Context, sessionID string, reason skipReason) {+ o.mx().RecordOutboundSkipped(string(reason))+ o.logger.DebugContext(ctx, "wecom outbound: reply not owed to WeCom",+ "reason", string(reason), "chat_session_id", sessionID)+}++// attachmentDelivered / attachmentDropped record ONE FILE. See the note on the+// Metrics interface for why files and replies are counted separately.+func (o *Outbound) attachmentDelivered() { o.mx().RecordAttachmentDelivered() }++func (o *Outbound) attachmentDropped(ctx context.Context, reason dropReason, err error) {+ o.mx().RecordAttachmentDropped(string(reason))+ attrs := []any{"reason", string(reason)}+ if err != nil {+ attrs = append(attrs, "error", err)+ }+ o.logger.WarnContext(ctx, "wecom outbound: attachment not delivered", attrs...)+}++// attachmentShed records one delivery attempt refused admission before the+// lookup. Not a file count: nothing knows yet whether a file exists.+func (o *Outbound) attachmentShed() { o.mx().RecordAttachmentDeliveryShed() }++// worseUnconfirmedReason is worseDropReason's twin, for the other unit. A reply+// whose files came back unknown for more than one reason needs its own outcome+// chosen by a rule rather than by whichever row the loop happened to end on —+// the same objection that made the definite side a documented precedence.+//+// Ordered by how much each one establishes about the frame. ack_timeout is the+// most specific: the frame reached the wire and only its verdict is missing.+// write_attempted is next: the local side reported a failure, and the peer may+// still hold the bytes. interrupted says least — the wait ended and where it+// ended is not knowable from here.+func worseUnconfirmedReason(a, b string) string {+ rank := func(r string) int {+ switch r {+ case "ack_timeout":+ return 3+ case "write_attempted":+ return 2+ case "interrupted":+ return 1+ default:+ return 0+ }+ }+ if rank(b) > rank(a) {+ return b+ }+ return a+}++// worseDropReason is the aggregation rule for a reply whose files failed for+// more than one reason. Precedence: a stated refusal beats a local transport+// failure beats a verdict that never came — ordered by how specific a fact+// each is about why the content did not arrive. Stable and documented so the+// multi-file reply reason is a rule, not an accident of loop order.+func worseDropReason(a, b dropReason) dropReason {+ rank := func(r dropReason) int {+ switch r {+ case dropPlatformRefused:+ return 3+ case dropTransport:+ return 2+ default:+ return 0+ }+ }+ if rank(b) > rank(a) {+ return b+ }+ return a+}++// 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.+func (o *Outbound) delivered() { o.mx().RecordOutboundDelivered() }++// mx returns the metrics sink, or a no-op one. Mirrors wecomChannel.mx.+func (o *Outbound) mx() Metrics { return orNopMetrics(o.metrics) }++// WithOutboundMetrics attaches the adapter's health sink to the subscriber.+func WithOutboundMetrics(m Metrics) OutboundOption {+ return func(o *Outbound) { o.metrics = m }+}diff --git a/server/internal/integrations/wecom/outbound_outcome_test.go b/server/internal/integrations/wecom/outbound_outcome_test.gonew file mode 100644index 0000000000..c51d9241ea--- /dev/null+++ b/server/internal/integrations/wecom/outbound_outcome_test.go@@ -0,0 +1,454 @@+package wecom++// outbound_outcome_test.go — that every branch which ends a turn without+// putting words in front of the user now names itself.+//+// The point is not that these branches exist; most of them are correct. It is+// that they used to be indistinguishable from outside. One symptom — the answer+// is in the Multica transcript, the WeCom chat stayed quiet — with five+// different causes and no way to tell which fired, is a report that can be+// argued about but not settled.++import (+ "bytes"+ "context"+ "errors"+ "log/slog"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"++ "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"+)++const (+ outcomeSession = "22222222-2222-2222-2222-222222222222"+ outcomeTask = "33333333-3333-3333-3333-333333333333"+)++// outcomeRig is one subscriber with a live socket, its log, and its counters.+// The socket is live in every case here, so nothing a test observes can be+// blamed on connectivity.+type outcomeRig struct {+ o *Outbound+ conn *recordingConn+ logs *bytes.Buffer+ mx *countingMetrics+}++func newOutcomeRig(t *testing.T, q *fakeOutboundQueries, withSocket bool) *outcomeRig {+ t.Helper()+ r := &outcomeRig{logs: &bytes.Buffer{}, mx: newCountingMetrics()}+ reg := newSendersRegistry()+ instID := mustTestUUID(t)+ if withSocket {+ r.conn = &recordingConn{}+ reg.set(instID, r.conn.autoAck(newWSSender(r.conn, nil)))+ }+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ r.o = NewOutbound(q, reg,+ slog.New(slog.NewTextHandler(r.logs, &slog.HandlerOptions{Level: slog.LevelDebug})),+ WithOutboundMetrics(r.mx))+ return r+}++func (r *outcomeRig) frames() int {+ if r.conn == nil {+ return 0+ }+ r.conn.mu.Lock()+ defer r.conn.mu.Unlock()+ return len(r.conn.frames)+}++// deliverableTurn is a completed turn that has every right to be delivered:+// bound session, active installation, asked in the room, words to say.+func deliverableTurn(t *testing.T) *fakeOutboundQueries {+ t.Helper()+ q := &fakeOutboundQueries{+ sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1", ChatType: "p2p"},+ installation: db.ChannelInstallation{Status: string(InstallationActive)},+ channelIngested: askedOverWecom(),+ }+ q.fileTask(t, outcomeTask)+ return q+}++func outcomeEvent() events.Event {+ return events.Event{+ Type: protocol.EventChatDone,+ ChatSessionID: outcomeSession,+ Payload: protocol.ChatDonePayload{Content: "the answer", TaskID: outcomeTask},+ }+}++func TestEveryUndeliveredReplyNamesItself(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ reason string+ actionable bool+ socket bool+ setup func(t *testing.T, q *fakeOutboundQueries)+ }{+ {+ name: "no socket in this process", reason: "no_live_connection", actionable: true, socket: false,+ setup: func(*testing.T, *fakeOutboundQueries) {},+ },+ {+ name: "the platform refused the frame", reason: "platform_refused", actionable: true, socket: true,+ setup: func(*testing.T, *fakeOutboundQueries) {},+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ tc.setup(t, q)+ r := newOutcomeRig(t, q, tc.socket)+ if tc.reason == "platform_refused" {+ r.conn.refuseCode, r.conn.refuseMsg = 45002, "content exceed max length"+ }++ r.o.handleEvent(outcomeEvent())++ if got := r.mx.get("outbound_dropped:" + tc.reason); got != 1 {+ t.Fatalf("counter for %s = %d, want 1. log:\n%s", tc.reason, got, r.logs.String())+ }+ out := r.logs.String()+ if !strings.Contains(out, "reason="+tc.reason) {+ t.Errorf("log does not name the reason:\n%s", out)+ }+ // A reason somebody must act on is a WARN; one that is ordinary in+ // a healthy deployment is a DEBUG, so it can be read as a rate+ // without drowning the log.+ if warned := strings.Contains(out, "level=WARN"); warned != tc.actionable {+ t.Errorf("level=WARN present = %v, want %v:\n%s", warned, tc.actionable, out)+ }+ if got := r.mx.get("outbound_delivered"); got != 0 {+ t.Errorf("delivered = %d on a turn that was not delivered", got)+ }+ })+ }+}++// TestDeliveredIsCounted — the denominator. Without it a drop rate of zero and+// a bot nobody messaged are the same number, which is the ambiguity the whole+// breakdown exists to remove.+func TestDeliveredIsCounted(t *testing.T) {+ t.Parallel()+ r := newOutcomeRig(t, deliverableTurn(t), true)++ r.o.handleEvent(outcomeEvent())++ if got := r.mx.get("outbound_delivered"); got != 1 {+ t.Errorf("delivered = %d, want 1. log:\n%s", got, r.logs.String())+ }+ if got := r.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("dropped = %d, want 0", got)+ }+ if n := r.frames(); n != 1 {+ t.Errorf("frames = %d, want 1", n)+ }+}++// TestNonWecomSessionIsNotADrop — this subscriber sees every chat:done in the+// deployment, including Slack's and the web UI's. Those are not this adapter's+// to answer and must not inflate the drop rate.+func TestNonWecomSessionIsNotADrop(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ q.sessionErr = pgx.ErrNoRows+ r := newOutcomeRig(t, q, true)++ r.o.handleEvent(outcomeEvent())++ if got := r.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("dropped = %d; another platform's session is not a WeCom drop", got)+ }+ if r.logs.Len() != 0 {+ t.Errorf("logged something for another platform's session:\n%s", r.logs.String())+ }+}++// TestRefusalIsNotATransportError — a refusal the server stated and a frame+// that never left call for opposite responses (fix the message vs retry the+// connection), so they must not share a bucket.+func TestRefusalIsNotATransportError(t *testing.T) {+ t.Parallel()+ if got := classifyDrop(&wecomAPIError{Cmd: cmdSendMsg, Code: 45002, Msg: "too long"}); got != dropPlatformRefused {+ t.Errorf("a stated refusal classified as %q", got)+ }+ if got := unconfirmedReason(errAckTimeout); got != "ack_timeout" {+ t.Errorf("a missing verdict classified as %q, want the unconfirmed ack_timeout", got)+ }+ if got := unconfirmedReason(errWriteAttempted); got != "write_attempted" {+ t.Errorf("an attempted write classified as %q, want the unconfirmed write_attempted", got)+ }+ if got := unconfirmedReason(errors.New("wecom: send_msg requires chat_id")); got != "" {+ t.Errorf("a provably local failure marked unconfirmed (%q); it is a definite drop", got)+ }+ if got := classifyDrop(errNoLiveConnection); got != dropNoConnection {+ t.Errorf("a missing socket classified as %q", got)+ }+ if got := classifyDrop(nil); got != "" {+ t.Errorf("success classified as %q", got)+ }+}++// TestNilMetricsSinkIsSafe — a deployment with /metrics off must not panic on+// the first dropped reply.+func TestNilMetricsSinkIsSafe(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ reg := newSendersRegistry()+ instID := mustTestUUID(t)+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ o := NewOutbound(q, reg, slog.Default()) // no WithOutboundMetrics++ o.handleEvent(outcomeEvent()) // no socket registered: takes the drop path+}++// TestReasonStringsArePinned — these are metric label values. Renaming one+// silently retires whatever alert or dashboard reads it, and the rename would+// otherwise pass every test in this package: nothing else asserts the strings+// themselves, only that some reason was recorded.+func TestReasonStringsArePinned(t *testing.T) {+ t.Parallel()+ for want, got := range map[string]dropReason{+ "no_live_connection": dropNoConnection,+ "task_missing": dropTaskMissing,+ "platform_refused": dropPlatformRefused,+ "transport_error": dropTransport,+ "attachment_not_admitted": dropAttachmentNotAdmitted,+ } {+ if string(got) != want {+ t.Errorf("reason = %q, want %q", got, want)+ }+ }+}++// TestSkipReasonStringsArePinned — the skipped set is a metric label too.+func TestSkipReasonStringsArePinned(t *testing.T) {+ t.Parallel()+ for want, got := range map[string]skipReason{+ "origin_not_channel": skipOriginNotChannel,+ "installation_inactive": skipInstallationInactive,+ "nothing_to_say": skipNothingToSay,+ } {+ if string(got) != want {+ t.Errorf("skip reason = %q, want %q", got, want)+ }+ }+}++// TestNotOwedIsSkippedNotDropped — the review finding. A question typed in the+// web UI on a WeCom-bound session was never owed to a WeCom user, so counting+// it as a failed delivery makes ordinary web usage read as an outage.+func TestNotOwedIsSkippedNotDropped(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name, reason string+ setup func(q *fakeOutboundQueries)+ }{+ {"asked in the web UI", "origin_not_channel", func(q *fakeOutboundQueries) { q.channelIngested = askedInTheWebUI() }},+ {"installation revoked", "installation_inactive", func(q *fakeOutboundQueries) { q.installation.Status = "revoked" }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ tc.setup(q)+ r := newOutcomeRig(t, q, true)++ r.o.handleEvent(outcomeEvent())++ if got := r.mx.get("outbound_skipped:" + tc.reason); got != 1 {+ t.Errorf("skipped:%s = %d, want 1", tc.reason, got)+ }+ if got := r.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("dropped = %d; this reply was never owed to WeCom", got)+ }+ if strings.Contains(r.logs.String(), "level=WARN") {+ t.Errorf("logged a WARN for an ordinary outcome:\n%s", r.logs.String())+ }+ })+ }+}++// TestActionableSplitIsPinned — every drop reaches an operator now that the+// ordinary outcomes have their own counter.+func TestActionableSplitIsPinned(t *testing.T) {+ t.Parallel()+ for _, r := range []dropReason{+ dropNoConnection, dropTaskMissing, dropPlatformRefused,+ dropTransport, dropAttachmentNotAdmitted,+ } {+ if !r.actionable() {+ t.Errorf("%s is a drop and must reach an operator", r)+ }+ }+}++// TestCompletionWithNoTaskIdIsCounted — the origin gate cannot run without a+// task to read the provenance stamp off, so the turn is withheld. Rare, but it+// used to be the quietest branch of all: no log, no counter, nothing.+func TestCompletionWithNoTaskIdIsCounted(t *testing.T) {+ t.Parallel()+ r := newOutcomeRig(t, deliverableTurn(t), true)++ e := outcomeEvent()+ e.Payload = protocol.ChatDonePayload{Content: "the answer"} // no TaskID+ r.o.handleEvent(e)++ if got := r.mx.get("outbound_dropped:task_missing"); got != 1 {+ t.Errorf("task_missing = %d, want 1. log:\n%s", got, r.logs.String())+ }+ if n := r.frames(); n != 0 {+ t.Errorf("frames = %d, want 0", n)+ }+}++// Every way out of sendAttachments before the per-file loop has to settle BOTH+// units: one outcome per file that will not be sent, and — when the files were+// the reply — exactly one reply outcome. Table-driven because the four exits+// were fixed one at a time and each fix left the others unasserted.+//+// It also pins which reason each exit files under, which is the half a comment+// cannot enforce: attachment_not_admitted appears on the reply counter only+// here, and only because these files WERE the answer.+func TestSendAttachments_EveryEarlyExitSettlesBothUnits(t *testing.T) {+ t.Parallel()+ const files = 3+ for _, tc := range []struct {+ name string+ arrange func(t *testing.T, o *Outbound, q *fakeOutboundQueries) context.Context+ wantFiles string // attachment_dropped:<reason>, "" when the rows are not known yet+ wantReply string // outbound_dropped:<reason>+ wantNFiles int+ }{+ {+ name: "the lookup itself failed, so no file is known",+ arrange: func(_ *testing.T, _ *Outbound, q *fakeOutboundQueries) context.Context {+ q.attachmentsErr = errors.New("wecom test: database is unwell")+ return context.Background()+ },+ wantReply: "transport_error",+ wantNFiles: 0,+ },+ {+ name: "too many deliveries are already pending",+ arrange: func(_ *testing.T, o *Outbound, _ *fakeOutboundQueries) context.Context {+ o.pendingMu.Lock()+ o.pendingAttachments = maxPendingAttachmentDeliveries+ o.pendingMu.Unlock()+ return context.Background()+ },+ wantFiles: "attachment_not_admitted",+ wantReply: "attachment_not_admitted",+ wantNFiles: files,+ },+ {+ name: "the budget ran out waiting for a concurrency slot",+ arrange: func(_ *testing.T, _ *Outbound, _ *fakeOutboundQueries) context.Context {+ // Every slot taken, and a context already spent: the select+ // takes its ctx.Done arm without waiting on anything.+ for i := 0; i < maxConcurrentAttachmentDeliveries; i++ {+ attachmentSlots <- struct{}{}+ }+ t.Cleanup(func() {+ for i := 0; i < maxConcurrentAttachmentDeliveries; i++ {+ <-attachmentSlots+ }+ })+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ return ctx+ },+ wantFiles: "transport_error",+ wantReply: "transport_error",+ wantNFiles: files,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ q := deliverableTurn(t)+ for i := 0; i < files; i++ {+ q.attachments = append(q.attachments, db.Attachment{+ ID: mustTestUUID(t), Filename: "f.bin",+ Url: "https://cdn.example/obj/f", SizeBytes: 4,+ })+ }+ r := newOutcomeRig(t, q, true)+ ctx := tc.arrange(t, r.o, q)++ // carriesTheReply: an empty completion whose files ARE the answer,+ // which is the only shape where a file outcome is also the reply's.+ r.o.sendAttachments(ctx, mustTestUUID(t), mustTestUUID(t),+ attachmentTarget{InstallationID: q.installation.ID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt},+ true)++ if got := r.mx.get("attachment_dropped"); got != tc.wantNFiles {+ t.Errorf("attachment_dropped = %d, want %d — one per file that will not be sent",+ got, tc.wantNFiles)+ }+ if tc.wantFiles != "" {+ if got := r.mx.get("attachment_dropped:" + tc.wantFiles); got != tc.wantNFiles {+ t.Errorf("attachment_dropped:%s = %d, want %d", tc.wantFiles, got, tc.wantNFiles)+ }+ }+ if got := r.mx.get("outbound_dropped"); got != 1 {+ t.Errorf("outbound_dropped = %d, want exactly 1 — the files were the reply", got)+ }+ if got := r.mx.get("outbound_dropped:" + tc.wantReply); got != 1 {+ t.Errorf("outbound_dropped:%s = %d, want 1. log:\n%s", tc.wantReply, got, r.logs.String())+ }+ })+ }+}++// A reply whose words already landed is settled: the same exits must move the+// file counter and leave the reply counter alone.+func TestSendAttachments_AnEarlyExitDoesNotReCountASettledReply(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ q.attachments = append(q.attachments, db.Attachment{+ ID: mustTestUUID(t), Filename: "f.bin", Url: "https://cdn.example/obj/f", SizeBytes: 4,+ })+ r := newOutcomeRig(t, q, true)+ r.o.pendingMu.Lock()+ r.o.pendingAttachments = maxPendingAttachmentDeliveries+ r.o.pendingMu.Unlock()++ r.o.sendAttachments(context.Background(), mustTestUUID(t), mustTestUUID(t),+ attachmentTarget{InstallationID: q.installation.ID, ChatID: "CHAT_1", ChatType: chatTypeSingleInt},+ false) // the words went out on their own++ if got := r.mx.get("attachment_dropped:attachment_not_admitted"); got != 1 {+ t.Errorf("attachment_dropped = %d, want 1", got)+ }+ if got := r.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("outbound_dropped = %d, want 0 — that reply was delivered and counted already", got)+ }+}++// The unknown side needs a rule for the same reason the definite side does: a+// reply with several unconfirmed files must not report whichever reason the+// loop happened to end on.+func TestWorseUnconfirmedReason_IsARuleNotALoopOrder(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct{ a, b, want string }{+ {"", "interrupted", "interrupted"},+ {"interrupted", "write_attempted", "write_attempted"},+ {"write_attempted", "interrupted", "write_attempted"},+ {"write_attempted", "ack_timeout", "ack_timeout"},+ {"ack_timeout", "interrupted", "ack_timeout"},+ {"ack_timeout", "ack_timeout", "ack_timeout"},+ } {+ if got := worseUnconfirmedReason(tc.a, tc.b); got != tc.want {+ t.Errorf("worseUnconfirmedReason(%q, %q) = %q, want %q", tc.a, tc.b, got, tc.want)+ }+ }+}diff --git a/server/internal/metrics/wecom.go b/server/internal/metrics/wecom.goindex 5820d8542d..a87ac12d59 100644--- a/server/internal/metrics/wecom.go+++ b/server/internal/metrics/wecom.go@@ -32,11 +32,35 @@ import "github.com/prometheus/client_golang/prometheus"// there: the two connection failures reach the Supervisor as a returned error// and are logged with installation_id, while a blocked ingest queue is// counted and nothing else — the counter says some bot is behind, not which.+// The outbound counters answer a different question from the connection ones,+// and it is the question GH #7215 and #6890 were filed as: a reply was+// produced, the transcript has it, and the WeCom chat stayed quiet. Several+// unrelated causes end that way and from the chat they are one symptom, so+// each is counted where an operator can act on it: a frame the platform+// refused, or no socket for this installation in this process, is a drop; a+// turn that originated in the web UI, or an installation revoked between+// trigger and reply, was never owed to WeCom and is a skip; a frame whose+// verdict never came back may already be on the user's screen and is+// unconfirmed, not a drop. Delivered is the denominator: without it, a drop+// rate of zero and a bot nobody messaged look identical, which is the same+// ambiguity the connection counters exist to remove.+//+// reason is a closed set (wecom/outbound_outcome.go). It is the only label+// here, and it stays bounded by construction — no installation, workspace or+// session id, same rule as everywhere else in this package.type WecomMetrics struct {- ConnectFailures prometheus.Counter- AuthFailures prometheus.Counter- CallbacksQueued prometheus.Counter- CallbackQueueBlocked prometheus.Counter+ ConnectFailures prometheus.Counter+ AuthFailures prometheus.Counter+ CallbacksQueued prometheus.Counter+ CallbackQueueBlocked prometheus.Counter+ OutboundDelivered prometheus.Counter+ OutboundDropped *prometheus.CounterVec+ OutboundSkipped *prometheus.CounterVec+ AttachmentDelivered prometheus.Counter+ AttachmentDropped *prometheus.CounterVec+ AttachmentSheds prometheus.Counter+ OutboundUnconfirmed *prometheus.CounterVec+ AttachmentUnconfirmed *prometheus.CounterVec}func NewWecomMetrics() *WecomMetrics {@@ -54,6 +78,32 @@ func NewWecomMetrics() *WecomMetrics {"Inbound callbacks handed to the ingest worker. The baseline every other inbound number is read against."),CallbackQueueBlocked: counter("inbound_queue_blocked_total","Times the read loop had to wait on a full ingest queue. Backpressure by design; a rising rate means the engine is behind and the socket is about to stop being drained."),+ OutboundDelivered: counter("outbound_delivered_total",+ "Agent replies this adapter put in front of a WeCom user. The denominator the drop breakdown is read against."),+ OutboundDropped: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "wecom", Name: "outbound_dropped_total",+ Help: "Agent replies the adapter owed a WeCom user and did not deliver, by reason. Every reason here means somebody in WeCom is waiting on an answer that is not coming; the completions the adapter was never going to deliver are counted apart, in outbound_skipped_total.",+ }, []string{"reason"}),+ OutboundSkipped: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "wecom", Name: "outbound_skipped_total",+ Help: "Completions this adapter was never going to deliver to WeCom, by reason. Kept apart from dropped because none of these is a delivery failure: origin_not_channel is a question typed in Multica on a WeCom-bound session, installation_inactive means there is no longer an installation to deliver through, nothing_to_say is an empty completion carrying no file. Counting them as drops would make ordinary web usage read as a WeCom outage.",+ }, []string{"reason"}),+ AttachmentDelivered: counter("outbound_attachment_delivered_total",+ "Files put in front of a WeCom user. Counts FILES; the outbound_delivered/dropped/skipped trio counts REPLIES."),+ AttachmentDropped: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "wecom", Name: "outbound_attachment_dropped_total",+ Help: "Files an agent produced that did not reach the WeCom user, by reason. Separate from the reply counters because a reply whose words arrived and whose file did not is a delivered reply with a failed attachment, and one number cannot say both.",+ }, []string{"reason"}),+ AttachmentSheds: counter("outbound_attachment_delivery_shed_total",+ "Attachment delivery attempts refused admission before the lookup ran. Counts SCHEDULING decisions, not files: at that point nothing knows whether the turn carries zero files or five, so a per-file count from this gate would fabricate cardinality."),+ OutboundUnconfirmed: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "wecom", Name: "outbound_unconfirmed_total",+ Help: "Agent replies whose delivery outcome is UNKNOWN: the frame reached the wire (write_attempted), the verdict never came back (ack_timeout), or the wait was cut short (interrupted). The message may already be in front of the user, which is why these are not drops — an operator paging on the drop rate must not be paged for deliveries that probably happened, and nothing here should prompt a resend.",+ }, []string{"reason"}),+ AttachmentUnconfirmed: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "wecom", Name: "outbound_attachment_unconfirmed_total",+ Help: "Files whose delivery outcome is UNKNOWN, by reason. Counts FILES, same unit as the attachment delivered/dropped pair; see outbound_unconfirmed_total for why unknown is not a drop.",+ }, []string{"reason"}),}}@@ -61,6 +111,9 @@ func (m *WecomMetrics) Collectors() []prometheus.Collector {return []prometheus.Collector{m.ConnectFailures, m.AuthFailures,m.CallbacksQueued, m.CallbackQueueBlocked,+ m.OutboundDelivered, m.OutboundDropped, m.OutboundSkipped,+ m.AttachmentDelivered, m.AttachmentDropped, m.AttachmentSheds,+ m.OutboundUnconfirmed, m.AttachmentUnconfirmed,}}@@ -70,3 +123,21 @@ func (m *WecomMetrics) RecordConnectFailure() { m.ConnectFailures.Inc() }func (m *WecomMetrics) RecordAuthFailure() { m.AuthFailures.Inc() }func (m *WecomMetrics) RecordCallbackQueued() { m.CallbacksQueued.Inc() }func (m *WecomMetrics) RecordCallbackQueueBlocked() { m.CallbackQueueBlocked.Inc() }+func (m *WecomMetrics) RecordOutboundDelivered() { m.OutboundDelivered.Inc() }+func (m *WecomMetrics) RecordOutboundDropped(reason string) {+ m.OutboundDropped.WithLabelValues(reason).Inc()+}+func (m *WecomMetrics) RecordOutboundSkipped(reason string) {+ m.OutboundSkipped.WithLabelValues(reason).Inc()+}+func (m *WecomMetrics) RecordAttachmentDelivered() { m.AttachmentDelivered.Inc() }+func (m *WecomMetrics) RecordAttachmentDropped(reason string) {+ m.AttachmentDropped.WithLabelValues(reason).Inc()+}+func (m *WecomMetrics) RecordAttachmentDeliveryShed() { m.AttachmentSheds.Inc() }+func (m *WecomMetrics) RecordOutboundUnconfirmed(reason string) {+ m.OutboundUnconfirmed.WithLabelValues(reason).Inc()+}+func (m *WecomMetrics) RecordAttachmentUnconfirmed(reason string) {+ m.AttachmentUnconfirmed.WithLabelValues(reason).Inc()+}diff --git a/server/internal/metrics/wecom_test.go b/server/internal/metrics/wecom_test.goindex df03dba79b..f0a53eeec7 100644--- a/server/internal/metrics/wecom_test.go+++ b/server/internal/metrics/wecom_test.go@@ -157,3 +157,67 @@ func wecomValueOf(m *dto.Metric) float64 {}return 0}++// TestWecomOutboundMetricsAreExported covers the EXPORTED contract, not the+// adapter's test double: the names Prometheus will scrape, the reason label,+// and that every collector is actually registered. A dashboard reads these+// strings; a rename that only the double knows about is a silent outage of+// whatever alert watches them.+func TestWecomOutboundMetricsAreExported(t *testing.T) {+ m := NewWecomMetrics()+ reg := prometheus.NewRegistry()+ for _, c := range m.Collectors() {+ if err := reg.Register(c); err != nil {+ t.Fatalf("register: %v", err)+ }+ }++ m.RecordOutboundDelivered()+ m.RecordOutboundDropped("no_live_connection")+ m.RecordOutboundSkipped("origin_not_channel")+ m.RecordAttachmentDelivered()+ m.RecordAttachmentDropped("platform_refused")+ m.RecordAttachmentDeliveryShed()+ m.RecordOutboundUnconfirmed("ack_timeout")+ m.RecordAttachmentUnconfirmed("write_attempted")++ got, err := reg.Gather()+ if err != nil {+ t.Fatalf("gather: %v", err)+ }+ seen := map[string]bool{}+ labels := map[string]string{}+ for _, mf := range got {+ seen[mf.GetName()] = true+ for _, mm := range mf.GetMetric() {+ for _, l := range mm.GetLabel() {+ labels[mf.GetName()+"/"+l.GetName()] = l.GetValue()+ }+ }+ }+ for _, want := range []string{+ "multica_wecom_outbound_delivered_total",+ "multica_wecom_outbound_dropped_total",+ "multica_wecom_outbound_skipped_total",+ "multica_wecom_outbound_attachment_delivered_total",+ "multica_wecom_outbound_attachment_dropped_total",+ "multica_wecom_outbound_attachment_delivery_shed_total",+ "multica_wecom_outbound_unconfirmed_total",+ "multica_wecom_outbound_attachment_unconfirmed_total",+ } {+ if !seen[want] {+ t.Errorf("%s was not exported", want)+ }+ }+ for name, want := range map[string]string{+ "multica_wecom_outbound_dropped_total/reason": "no_live_connection",+ "multica_wecom_outbound_skipped_total/reason": "origin_not_channel",+ "multica_wecom_outbound_attachment_dropped_total/reason": "platform_refused",+ "multica_wecom_outbound_unconfirmed_total/reason": "ack_timeout",+ "multica_wecom_outbound_attachment_unconfirmed_total/reason": "write_attempted",+ } {+ if labels[name] != want {+ t.Errorf("%s = %q, want %q", name, labels[name], want)+ }+ }+}