Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(wecom): name the two exits that leave a reply unaccounted for (MUL-7318) (#8348)
Xichang(Seacen) Zhaoda139a7c972e
diff --git a/server/internal/integrations/wecom/metrics.go b/server/internal/integrations/wecom/metrics.goindex 1f26c83665..b001f83faf 100644--- a/server/internal/integrations/wecom/metrics.go+++ b/server/internal/integrations/wecom/metrics.go@@ -100,14 +100,21 @@ type Metrics interface {// 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.+ // was — most of them before the frame ever reaches WeCom. The completions+ // this adapter did not owe, and the ones nothing here can attribute to a+ // WeCom chat, are counted apart, by RecordOutboundSkipped.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 — a completion this adapter did not send because it+ // was not WeCom's to send, labelled with why (outbound_outcome.go's closed+ // skip set). 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.+ //+ // Not every reason here is harmless, so this total is not one to read as a+ // single number. no_delivery_row is a turn the channel ingested with no row+ // saying which chat — a reply that may well be owed, with nothing left that+ // can name the room — and it is the one reason in the set that logs at+ // WARN. Alert on it by label, not on the sum.RecordOutboundSkipped(reason string)// RecordAttachmentDelivered / RecordAttachmentDropped count FILES, one perdiff --git a/server/internal/integrations/wecom/origin_gate_db_test.go b/server/internal/integrations/wecom/origin_gate_db_test.gonew file mode 100644index 0000000000..9ffc97263a--- /dev/null+++ b/server/internal/integrations/wecom/origin_gate_db_test.go@@ -0,0 +1,299 @@+package wecom++// origin_gate_db_test.go — GetTaskChannelOrigin against real SQL.+//+// The origin gate used to be two calls with a Go `if` between them, and the+// fake in outbound_test.go could answer for both: a test could file a retry+// clone, watch which id the stamp was read for, and pin the whole rule without+// a database. Consolidating the gate into one query moved that rule into+// COALESCE(chat_input_task_id, id), where a fake cannot answer for it — it does+// not perform the join. So the rule is pinned here instead, against Postgres.+//+// The four rows below are the four shapes the classification has to keep apart,+// and each one is a case where getting it wrong costs something specific: a+// retry clone read off its own id answers "web UI" for a turn a room is waiting+// on; a task row that is gone read as "false" turns a lost reply into the most+// ordinary event in the deployment; a legacy row with no batch owner assumed+// channel-ingested reports every pre-MUL-4351 web turn as a channel turn whose+// route went missing.+//+// Skips when no migrated database is reachable, same as the other _db_ tests in+// this package.++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ dbfx "github.com/multica-ai/multica/server/internal/testutil"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// originLab is one workspace holding the task shapes the gate has to tell+// apart. Ids are the task ids a chat:done would carry.+type originLab struct {+ retryClone string // owns nothing; inherits a parent whose batch IS stamped+ webUI string // owns its batch; the batch carries no stamp+ channel string // owns its batch; the batch IS stamped+ legacyPlain string // chat_input_task_id NULL, own messages unstamped+ legacyInRoom string // chat_input_task_id NULL, own messages stamped+ legacyRetry string // the auto-retry of legacyInRoom: NULL owner, owns nothing+ reaped string // no agent_task_queue row at all+}++func seedOriginLab(t *testing.T, pool *pgxpool.Pool) originLab {+ t.Helper()+ ctx := context.Background()+ newID := func() string {+ t.Helper()+ var id string+ if err := pool.QueryRow(ctx, `SELECT gen_random_uuid()::text`).Scan(&id); err != nil {+ t.Fatalf("seed: mint id: %v", err)+ }+ return id+ }+ tag := strings.ReplaceAll(newID(), "-", "")[:12]+ lab := originLab{+ retryClone: newID(), webUI: newID(), channel: newID(),+ legacyPlain: newID(), legacyInRoom: newID(), legacyRetry: newID(), reaped: newID(),+ }+ parentID := newID() // the retry clone's batch owner++ // Fixtures rather than hand-written INSERTs and a hand-maintained DELETE+ // chain: they delete in reverse creation order, so a shape added later+ // cannot leave the teardown one row behind (AGENTS.md:118).+ f := dbfx.New(pool, "", "")+ f.WorkspaceID = f.Workspace(t, "origin "+tag, "origin-"+tag)+ f.UserID = f.User(t, "Origin "+tag, "origin-"+tag+"@example.com")+ agentID := f.Agent(t, "origin-agent-"+tag, "", dbfx.Cols{"runtime_mode": "local"})+ sessionID := f.Insert(t, "chat_session", dbfx.Cols{+ "workspace_id": f.WorkspaceID,+ "agent_id": agentID,+ "creator_id": f.UserID,+ })++ // completed_at is not decoration: agent_task_queue_active_requires_runtime+ // insists a row is either attached to a runtime or finished.+ task := func(id string, owner any) {+ t.Helper()+ f.Task(t, agentID, dbfx.Cols{+ "id": id,+ "chat_session_id": sessionID,+ "status": "completed",+ "completed_at": dbfx.Raw("now()"),+ "chat_input_task_id": owner,+ })+ }+ msg := func(owner string, ingested bool) {+ t.Helper()+ f.Insert(t, "chat_message", dbfx.Cols{+ "chat_session_id": sessionID,+ "role": "user",+ "content": "q",+ "task_id": owner,+ "channel_ingested": ingested,+ })+ }++ // The retry chain: FailTask's child inherits chat_input_task_id, and the+ // user's message stays tagged with the parent that sealed the batch.+ task(parentID, parentID)+ task(lab.retryClone, parentID)+ msg(parentID, true)++ task(lab.webUI, lab.webUI)+ msg(lab.webUI, false)++ task(lab.channel, lab.channel)+ msg(lab.channel, true)++ // Migration 158 left BOTH legacy direct rows and channel tasks NULL here.+ // Which of the two a NULL row was is answerable only from its own messages.+ task(lab.legacyPlain, nil)+ msg(lab.legacyPlain, false)++ task(lab.legacyInRoom, nil)+ msg(lab.legacyInRoom, true)++ // THE SEVENTH SHAPE, built the way FailTask builds it rather than by hand.+ // CreateRetryTask copies chat_input_task_id verbatim — agent.sql says a+ // plain copy is deliberate, because legacy and channel parents carry NULL+ // and must stay NULL — so the clone of a NULL-owner parent owns nothing and+ // the verdict alone reads it as web UI. CopyChannelTaskDelivery then hands+ // it the parent's WeCom route anyway. A hand-built row could drift from+ // either; these cannot.+ //+ // CreateRetryTask makes the clone ACTIVE, and+ // agent_task_queue_active_requires_runtime (migration 251) needs a runtime+ // on an active row. A real parent has one and the clone inherits it, so the+ // fixture gives the parent one rather than relaxing the constraint.+ runtimeID := f.Runtime(t, "origin-runtime-"+tag)+ f.Exec(t, `UPDATE agent_task_queue SET runtime_id = $1 WHERE id = $2`, runtimeID, lab.legacyInRoom)++ q := db.New(pool)+ f.Cleanup(t, `DELETE FROM agent_task_queue WHERE id = $1`, lab.legacyRetry)+ if _, err := q.CreateRetryTask(ctx, db.CreateRetryTaskParams{+ ID: mustPgUUID(t, lab.legacyInRoom),+ NewTaskID: mustPgUUID(t, lab.legacyRetry),+ }); err != nil {+ t.Fatalf("CreateRetryTask: %v", err)+ }++ // The other half of what FailTask writes. The parent's route is seeded flat+ // because it is the inbound path's output, not the retry's; the clone's is+ // made by the query FailTask actually calls.+ f.InsertNoID(t, "channel_task_delivery", dbfx.Cols{+ "task_id": lab.legacyInRoom,+ "binding_id": newID(),+ "installation_id": newID(),+ "channel_type": "wecom",+ "channel_chat_id": "room-" + tag,+ "chat_type": "group",+ "route_revision": 1,+ }, "task_id = $1", lab.legacyInRoom)+ f.Cleanup(t, `DELETE FROM channel_task_delivery WHERE task_id = $1`, lab.legacyRetry)+ if err := q.CopyChannelTaskDelivery(ctx, db.CopyChannelTaskDeliveryParams{+ ChildTaskID: mustPgUUID(t, lab.legacyRetry),+ ParentTaskID: mustPgUUID(t, lab.legacyInRoom),+ }); err != nil {+ t.Fatalf("CopyChannelTaskDelivery: %v", err)+ }++ return lab+}++func TestGetTaskChannelOrigin_RealSQL(t *testing.T) {+ pool := twoReplicaDB(t)+ lab := seedOriginLab(t, pool)+ q := db.New(pool)++ for _, tc := range []struct {+ name string+ taskID string+ ingested bool+ // ownerUnknown is the second fact the query reports. It is not a+ // detail: it is what lets the delivery branch fail open on a row whose+ // verdict cannot speak for it, and the row that regressed is exactly+ // one where ingested is false and this is true.+ ownerUnknown bool+ why string+ // precondition checks that the fixture really built the shape this+ // case is about, before the query is asked. It lives here rather than+ // in seedOriginLab because it is an assertion about the product's own+ // writes (AGENTS.md: product assertions stay in the test).+ precondition func(t *testing.T)+ }{+ {+ name: "a retry clone reaches its parent's batch", taskID: lab.retryClone, ingested: true,+ why: "the clone owns no messages of its own; read off its own id it answers 'web UI' " ++ "for a turn a room is waiting on, which is the retry half of MUL-4988",+ },+ {+ name: "a question typed in the web UI", taskID: lab.webUI, ingested: false,+ why: "the ordinary completion in the deployment, and the one that must not warn",+ },+ {+ name: "a question asked in the room", taskID: lab.channel, ingested: true,+ why: "the turn a missing delivery row is actionable for",+ },+ {+ // These two rows differ in the only place a verdict could come+ // from — one's own message carries the channel stamp and the+ // other's does not — and the query answers both the same, because+ // with no owner it reads neither. That is not a gap: delivering a+ // turn that may be the room's costs a reply in the wrong place,+ // while refusing one costs a room waiting forever, and+ // engine.TaskInputIsChannelIngested has always picked the first.+ // batch_owner_unknown is how a caller that needs the OTHER+ // direction — whether to warn about a missing route — tells this+ // pair apart from a verdict that was actually established.+ name: "a legacy row with no batch owner, asked in Multica", taskID: lab.legacyPlain, ingested: true,+ ownerUnknown: true,+ why: "NULL chat_input_task_id is 'legacy row OR channel task' (migration 158), so the " ++ "row cannot say which. It is delivered, and batch_owner_unknown is what keeps the " ++ "no-route WARN off it",+ },+ {+ name: "a legacy row with no batch owner, asked in the room", taskID: lab.legacyInRoom, ingested: true,+ ownerUnknown: true,+ why: "the same answer as the row above, from the same absent owner — which is why the " ++ "second fact exists rather than a second verdict",+ },+ {+ // THE SEVENTH SHAPE, and the one that regressed. Built through the+ // real CreateRetryTask and CopyChannelTaskDelivery so the fixture+ // cannot drift from what FailTask actually writes.+ name: "the auto-retry of a legacy row with no batch owner", taskID: lab.legacyRetry,+ ingested: true, ownerUnknown: true,+ why: "CreateRetryTask copies a NULL owner verbatim and the clone owns no messages, so a " ++ "gate keyed on the task's own id reads it as web UI — while CopyChannelTaskDelivery " ++ "has already given it the parent's WeCom route, and the room is waiting. Keying on " ++ "the owner alone, as engine.TaskInputIsChannelIngested does, is what delivers it",+ precondition: func(t *testing.T) {+ ctx := context.Background()+ clone, err := q.GetAgentTask(ctx, mustPgUUID(t, lab.legacyRetry))+ if err != nil {+ t.Fatalf("load the retry clone: %v", err)+ }+ if clone.ChatInputTaskID.Valid {+ t.Fatalf("the clone inherited owner %v; this case only exists because it stays NULL",+ clone.ChatInputTaskID)+ }+ parent, err := q.GetChannelTaskDelivery(ctx, mustPgUUID(t, lab.legacyInRoom))+ if err != nil {+ t.Fatalf("load the parent's route: %v", err)+ }+ route, err := q.GetChannelTaskDelivery(ctx, clone.ID)+ if err != nil {+ t.Fatalf("the clone has no route: %v — without one it is not a row anyone is "++ "waiting on, and the case stops being the one that regressed", err)+ }+ if route.ChannelType != channelTypeWecom || route.ChannelChatID != parent.ChannelChatID {+ t.Fatalf("the clone's route is %s/%s, want the parent's wecom/%s",+ route.ChannelType, route.ChannelChatID, parent.ChannelChatID)+ }+ },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ if tc.precondition != nil {+ tc.precondition(t)+ }+ got, err := q.GetTaskChannelOrigin(context.Background(), mustPgUUID(t, tc.taskID))+ if err != nil {+ t.Fatalf("GetTaskChannelOrigin: %v", err)+ }+ if got.ChannelIngested != tc.ingested {+ t.Errorf("channel_ingested = %v, want %v — %s", got.ChannelIngested, tc.ingested, tc.why)+ }+ if got.BatchOwnerUnknown != tc.ownerUnknown {+ t.Errorf("batch_owner_unknown = %v, want %v — it is what lets the delivery branch "++ "fail open on a row the verdict cannot speak for", got.BatchOwnerUnknown, tc.ownerUnknown)+ }+ })+ }++ t.Run("a task row that is gone", func(t *testing.T) {+ _, err := q.GetTaskChannelOrigin(context.Background(), mustPgUUID(t, lab.reaped))+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("err = %v, want pgx.ErrNoRows — the absence of a verdict has to stay "++ "distinguishable from a negative one, or a reply reaped mid-completion is filed "++ "as the most ordinary event in the deployment", err)+ }+ })+}++func mustPgUUID(t *testing.T, id string) pgtype.UUID {+ t.Helper()+ var out pgtype.UUID+ if err := out.Scan(id); err != nil {+ t.Fatalf("parse uuid %q: %v", id, err)+ }+ return out+}diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex dc6f7b5ef1..ed59123a0c 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -59,7 +59,6 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/integrations/channel"- "github.com/multica-ai/multica/server/internal/integrations/channel/engine""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -74,12 +73,17 @@ type outboundQueries interface {// answer still in flight across one of those belongs to the room that// asked, not to whatever the session points at by the time it lands.GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)- // GetAgentTask serves two readers on this path. The origin gate reads the- // row to get at the channel_ingested stamp; the round matcher reads it to- // resolve an auto-retry clone back to the turn that owns its input batch,- // which is the id the round was bound under.+ // GetTaskChannelOrigin is the origin gate's whole question — does the task+ // row exist, and did its input arrive over a channel — in one round trip.+ // It answers what GetAgentTask followed by TaskHasChannelIngestedMessages+ // answers, and the query is a transcription of+ // engine.TaskInputIsChannelIngested rather than a second opinion on it.+ GetTaskChannelOrigin(ctx context.Context, id pgtype.UUID) (db.GetTaskChannelOriginRow, error)+ // GetAgentTask is the round matcher's, not the gate's: it resolves an+ // auto-retry clone back to the turn that owns its input batch, which is the+ // id the round was bound under. NewOutbound passes this same value as the+ // roundTaker's taskLookup.GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)- TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)FindChannelBindingForMember(ctx context.Context, arg db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error)GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)@@ -298,20 +302,31 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {o.dropped(ctx, e, dropTaskMissing, nil)return nil}- task, err := o.q.GetAgentTask(ctx, taskID)+ // One keyed read, not two: GetTaskChannelOrigin answers what GetAgentTask+ // followed by engine.TaskInputIsChannelIngested answers, and answers it the+ // same way — including for a task whose input batch has no owner, which is+ // channel-ingested. This read is synchronous on the completion response+ // (see the query's comment), so the round trip it saves is one the daemon+ // waits for.+ origin, err := o.q.GetTaskChannelOrigin(ctx, taskID)if err != nil {if errors.Is(err, pgx.ErrNoRows) {- // Cancelled and deleted while its completion was in flight.+ // Cancelled and deleted while its completion was in flight. NOT+ // folded into "asked in the web UI": that exit is the ordinary one+ // and this row was owed an answer.o.dropped(ctx, e, dropTaskMissing, nil)return nil}- return fmt.Errorf("wecom: load agent task: %w", err)- }- deliver, err := engine.TaskInputIsChannelIngested(ctx, o.q, task)- if err != nil {- return fmt.Errorf("wecom: classify task input origin: %w", err)+ // Recorded rather than returned. The caller would file a context error+ // as an unconfirmed delivery — unconfirmedReason maps it to+ // "interrupted", which tells an operator the user may ALREADY HAVE this+ // reply and a resend would duplicate it. Nothing was written to a+ // socket here and nothing was going to be: this gate is upstream of+ // every send. The honest record is the one dropTransport describes.+ o.dropped(ctx, e, dropTransport, err)+ return nil}- if !deliver {+ if !origin.ChannelIngested {// Give the bubble back. A run typed in Multica can hold the room's// round — it is bound off task:queued, and a chat task's event carries// nothing that tells the two apart — so returning here without@@ -336,7 +351,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {// found a bubble is all deliverAnswer needs to know: the bubble is a cache,// and a round with none goes down the plain path.t, _ := o.rounds().take(ctx, sessionID, byTask(taskIDFromEvent(e)))- said, err := o.deliverAnswer(ctx, e, taskID, t, content, carriesFiles)+ said, err := o.deliverAnswer(ctx, e, taskID, t, content, carriesFiles, origin.BatchOwnerUnknown)if errors.Is(err, errOutcomeRecorded) {// The branch that tried to speak has already filed its own outcome// through recordSend. Counting it here as well is the double count@@ -391,7 +406,10 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {// Nothing here re-asks where the question came from. processEvent has already// refused every run that is not this room's, which is what makes it safe for// this function to write without asking.-func (o *Outbound) deliverAnswer(ctx context.Context, e events.Event, taskID pgtype.UUID, t roundTurn, content string, carriesFiles bool) (answerOutcome, error) {+// ownerUnknown is the origin gate's second fact, carried rather than re-read:+// it decides the LOG LEVEL on a turn that turns out to have no delivery row,+// and nothing else. See sendAsMessage.+func (o *Outbound) deliverAnswer(ctx context.Context, e events.Event, taskID pgtype.UUID, t roundTurn, content string, carriesFiles, ownerUnknown bool) (answerOutcome, error) {if t.HasBubble {// A bubble on screen has to end in words. An empty completion is a// legitimate outcome — the agent had nothing to add — but an endless@@ -452,7 +470,7 @@ func (o *Outbound) deliverAnswer(ctx context.Context, e events.Event, taskID pgt// no words to carry it sends none, and returns the address the files go// to.}- return o.sendAsMessage(ctx, e, taskID, content, carriesFiles)+ return o.sendAsMessage(ctx, e, taskID, content, carriesFiles, ownerUnknown)}// taskAddress resolves the chat a turn's words go to, off the task's own@@ -541,8 +559,8 @@ func (o *Outbound) relaySeal(e events.Event, taskID pgtype.UUID, reason string,// round with no bubble left to put it in — a restart mid-run, a stream past its// window, a frame the server refused. It returns where it spoke, which is where// the files that follow go.-func (o *Outbound) sendAsMessage(ctx context.Context, e events.Event, taskID pgtype.UUID, content string, carriesFiles bool) (answerOutcome, error) {- addr, skip, _, err := taskAddress(ctx, o.q, taskID)+func (o *Outbound) sendAsMessage(ctx context.Context, e events.Event, taskID pgtype.UUID, content string, carriesFiles, ownerUnknown bool) (answerOutcome, error) {+ addr, skip, hadRow, err := taskAddress(ctx, o.q, taskID)if err != nil {return answerOutcome{}, err}@@ -551,8 +569,32 @@ func (o *Outbound) sendAsMessage(ctx context.Context, e events.Event, taskID pgtreturn answerOutcome{}, errNothingToSay}if !addr.known() {- // No route recorded for this turn, or the row names another platform.- // Nothing to send and nobody to count it against.+ // The two reasons to have no address are one quiet return from the+ // outside, and only one of them means somebody is waiting. Every turn+ // that reaches here is past the origin gate, so its question DID come+ // in over a channel — which is what makes a missing row worth a word+ // rather than the ordinary traffic of a shared bus. Ahead of the gate+ // this same branch also caught every question ever typed in the Multica+ // web UI, and an exit shared with those could only be silent.+ //+ // Behind the gate, a missing row means a turn the channel ingested and+ // nobody can now address. In a steady-state deployment there is no such+ // turn: the row is written inside the same transaction that enqueues a+ // channel task. What produces one is an upgrade, and the answer it+ // belongs to is going nowhere — so it is counted and warned about+ // rather than left as a quiet return. See skipNoDeliveryRow.+ switch {+ case hadRow:+ o.skippedFor(ctx, e.ChatSessionID, skipNotWecomTurn)+ case ownerUnknown:+ // The gate delivered this turn on the open side of an unanswerable+ // verdict: its input batch has no owner, so nothing here ever+ // established it was a channel's. Warning would put the loudest+ // line this adapter has on a pre-158 web turn that auto-retried.+ o.skippedFor(ctx, e.ChatSessionID, skipRouteUnattributable)+ default:+ o.skippedFor(ctx, e.ChatSessionID, skipNoDeliveryRow)+ }return answerOutcome{}, errNothingToSay}if o.senders == nil {diff --git a/server/internal/integrations/wecom/outbound_outcome.go b/server/internal/integrations/wecom/outbound_outcome.goindex 56d4c468de..95bd8bccbf 100644--- a/server/internal/integrations/wecom/outbound_outcome.go+++ b/server/internal/integrations/wecom/outbound_outcome.go@@ -69,10 +69,24 @@ const (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.+// skipReason names a completion this adapter did not send because it was not+// WeCom's to send: not owed, not applicable, or not attributable to a WeCom+// chat at all. Kept in its own set, and behind its own counter, because "this+// was not ours to deliver" and "we owed this and failed" answer different+// questions, and counting a web-UI question's answer as a failed WeCom delivery+// makes ordinary usage read as an outage.+//+// The boundary is the obligation, not the wire. Most of the reasons above are+// settled before a frame is written too — a task that cannot be resolved, no+// socket to write on, a delivery refused admission, a budget spent before its+// turn — and what makes those drops is that a WeCom user was owed the answer.+//+// What stopped holding when skipNoDeliveryRow arrived is the other half of what+// this set used to claim: that none of them is an incident. That one is a skip+// for the third reason rather than the first — a turn the channel ingested with+// nothing left that can say which chat — so a reply may well be owed and nobody+// can place it. actionable() says which side of that line each reason falls+// on.type skipReason stringconst (@@ -91,14 +105,72 @@ const (// skipNothingToSay — an empty completion carrying no file. There was never// a message here.skipNothingToSay skipReason = "nothing_to_say"++ // skipNotWecomTurn — the turn has a delivery row and it names another+ // platform. This subscriber sees every chat:done in the deployment, so on+ // a workspace running Slack or Lark alongside WeCom this is ordinary and+ // frequent. Named rather than left silent because the branch next to it —+ // no delivery row at all — is not ordinary, and one unnamed exit shared by+ // the two makes the abnormal one invisible.+ skipNotWecomTurn skipReason = "not_wecom_turn"++ // skipNoDeliveryRow — the turn's input came in over a channel, and no+ // channel_task_delivery row says which one. Nothing here can address a+ // reply, so nothing is sent.+ //+ // The only reason this happens in a healthy deployment is an UPGRADE: a+ // task enqueued by a build that did not write delivery rows yet, finishing+ // under one that reads them (service/task.go writes the row inside the+ // enqueue transaction for every channel turn, so a steady-state channel+ // task always has one). The user is left waiting on an answer that exists+ // in the Multica transcript, which is the shape of #7215 all over again —+ // so this is the one skip reason a person should act on: drain the running+ // and queued channel tasks before swapping the image, or backfill the rows+ // for the ones still in flight.+ //+ // Not a DROP: this adapter never wrote to a socket and was never going to —+ // there is no address to write to — and dropped is the number an operator+ // reads as "a reply this adapter owed did not arrive at the platform".+ //+ // It is reached BEHIND the origin gate, which is what makes it mean+ // anything. Ahead of the gate the same branch also caught every question+ // ever typed in the Multica web UI, and an exit shared with those could+ // only be silent. A delivery row naming another platform leaves by+ // skipNotWecomTurn above, so what is left here is a channel turn nobody can+ // address.+ skipNoDeliveryRow skipReason = "no_delivery_row"++ // skipRouteUnattributable — no delivery row, and no way to say whose turn+ // it was. The gate delivered it on the open side of an unanswerable+ // verdict: its input batch has no owner (chat_input_task_id NULL), which+ // migration 158 left on legacy web rows and legacy channel rows alike, so+ // nothing establishes this turn was ever a channel's.+ //+ // Same branch as skipNoDeliveryRow, one level quieter, and the split is the+ // point. Delivering under an unanswerable verdict is right — the auto-retry+ // of a legacy channel turn depends on it, and a reply in the wrong place+ // costs less than a room waiting forever. WARNING under one is not: a+ // pre-158 web turn that auto-retried has exactly this shape, and it would+ // arrive as the loudest line this adapter has.+ //+ // So one verdict, two directions: deliver on the open side, warn on the+ // closed one. Counted rather than folded into the reason above, because an+ // operator who sees this number rise has learned something different — that+ // rows this old are still finishing — and nothing they can act on.+ skipRouteUnattributable skipReason = "route_unattributable")-// 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 }+// actionable reports whether a skip is one a person should look at. Almost none+// are, which is a property of this set rather than its definition — what+// separates it from dropReason is the obligation, see the type comment — so the+// one that is gets a WARN and the rest stay at DEBUG, where they can be read as+// a rate without drowning the log.+func (r skipReason) actionable() bool { return r == skipNoDeliveryRow }+// 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.@@ -216,17 +288,33 @@ func (o *Outbound) attachmentUnconfirmed(ctx context.Context, reason string, erro.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+// skipped records one completion this adapter did not send. DEBUG for all but+// one of them: none of those is an incident, and on a workspace where people// use the web UI against WeCom-bound sessions this is the busiest path here.+// skipNoDeliveryRow is the exception and logs at WARN — see its comment for why+// an upgrade is the only thing that produces it.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)+ attrs := []any{"reason", string(reason), "chat_session_id", sessionID}+ switch {+ case reason.actionable():+ // Its own line, not the default one at a louder level: "not owed to+ // WeCom" is what the ordinary reasons mean, and the actionable one is+ // precisely the case where the reply may well have been owed and there+ // is no longer anything that can say to whom.+ o.logger.WarnContext(ctx, "wecom outbound: a channel turn with no route, so nothing was sent", attrs...)+ case reason == skipRouteUnattributable:+ // Its own line too, at DEBUG. "Not owed" is a claim this reason cannot+ // make: with no route and no batch owner, nothing here can say whether+ // the turn was ever a channel's, let alone whether a reply was owed.+ o.logger.DebugContext(ctx, "wecom outbound: no route and no batch owner to attribute the turn to, so nothing was sent", attrs...)+ default:+ o.logger.DebugContext(ctx, "wecom outbound: reply not owed to WeCom", attrs...)+ }}// attachmentDelivered / attachmentDropped record ONE FILE. See the note on thediff --git a/server/internal/integrations/wecom/outbound_outcome_test.go b/server/internal/integrations/wecom/outbound_outcome_test.goindex 88bad675b8..32c1c8083c 100644--- a/server/internal/integrations/wecom/outbound_outcome_test.go+++ b/server/internal/integrations/wecom/outbound_outcome_test.go@@ -158,19 +158,136 @@ func TestDeliveredIsCounted(t *testing.T) {// 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) {+//+// The three of them leave by three different exits, and which one fired is the+// whole question an operator brings here: "the answer is in Multica and the+// chat stayed quiet" is a report about somebody waiting when the turn had a+// route and nobody can name it, and a non-event when it was Slack's turn all+// along.+//+// REVERSE VERIFICATION: return nil from either of the two branches in+// processEvent instead of naming a skip reason, and the counters for the two+// exits collapse to zero while the drop rate stays at zero either way — which+// is exactly the indistinguishability this pins. Build and vet stay silent.+// The auto-retry of a legacy channel turn. FailTask's clone inherits the+// parent's NULL chat_input_task_id and owns no messages of its own, so the+// batch is the one migration 158 left with no owner at all, and the clone owns+// no messages of its own — so a gate that keyed the batch on the task's own id+// would read it as web UI, while CopyChannelTaskDelivery has already handed it+// the parent's WeCom route. The room waits forever and the silence is logged at+// DEBUG as the most ordinary event in the deployment.+//+// A batch with no owner is channel-ingested, which is what+// engine.TaskInputIsChannelIngested has always answered for the same row and+// what #5645 shipped. This pins that the one-read gate did not change it.+func TestTheAutoRetryOfALegacyChannelTurnStillAnswersTheRoom(t *testing.T) {t.Parallel()q := deliverableTurn(t)- q.sessionErr = pgx.ErrNoRows+ q.fileNoOwnerTask(t, outcomeTask) // NULL chat_input_task_id, no messages of its ownr := 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 n := r.frames(); n != 1 {+ t.Fatalf("frames = %d, want 1 — the room this retry belongs to is still waiting on it. log:\n%s",+ n, r.logs.String())}- if r.logs.Len() != 0 {- t.Errorf("logged something for another platform's session:\n%s", r.logs.String())+ if got := r.mx.get("outbound_skipped:" + string(skipOriginNotChannel)); got != 0 {+ t.Errorf("skipped as a web turn %d times; a delivery row said otherwise", got)+ }+}++func TestNonWecomSessionIsNotADrop(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ reason skipReason+ actionable bool+ // notOwed is whether the log may say "not owed to WeCom". True only+ // where that is established; the missing-route pair are the two exits+ // where a reply may have been owed, or nothing can say.+ notOwed bool+ setup func(t *testing.T, q *fakeOutboundQueries)+ }{+ {+ // Slack's or Lark's turn, on the bus this subscriber shares.+ name: "another platform's delivery row", reason: skipNotWecomTurn, notOwed: true,+ setup: func(_ *testing.T, q *fakeOutboundQueries) { q.sessionChannelType = "slack" },+ },+ {+ // Asked in the Multica web UI on a session that originated in a+ // room. There is no room waiting.+ name: "asked in the web UI", reason: skipOriginNotChannel, notOwed: true,+ setup: func(_ *testing.T, q *fakeOutboundQueries) { q.channelIngested = askedInTheWebUI() },+ },+ {+ // Asked in the Multica web UI on a session that never touched a+ // channel, which is every ordinary turn in the deployment: no+ // delivery row, and none was ever owed. It has to leave by the web+ // UI's exit and not the missing-route one, or the loudest line in+ // the log fires once per web message.+ name: "asked in the web UI with no delivery row", reason: skipOriginNotChannel, notOwed: true,+ setup: func(_ *testing.T, q *fakeOutboundQueries) {+ q.channelIngested = askedInTheWebUI()+ q.sessionErr = pgx.ErrNoRows+ },+ },+ {+ // A channel turn whose route was never recorded. Somebody asked in+ // a room and nothing here can say which one, so this is the one an+ // operator has to act on.+ name: "a channel turn with no delivery row", reason: skipNoDeliveryRow, actionable: true,+ setup: func(_ *testing.T, q *fakeOutboundQueries) { q.sessionErr = pgx.ErrNoRows },+ },+ {+ // The other half of the pair above. The gate delivered this one+ // because a batch with no owner is channel-ingested, and then there+ // was no route to deliver it on. It leaves by its own exit, one+ // level quieter: a pre-158 web turn that auto-retried has exactly+ // this shape, and warning about it would put the loudest line this+ // adapter has on ordinary traffic.+ name: "no delivery row and no batch owner to attribute it to", reason: skipRouteUnattributable,+ setup: func(t *testing.T, q *fakeOutboundQueries) {+ q.fileNoOwnerTask(t, outcomeTask)+ q.sessionErr = pgx.ErrNoRows+ },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ tc.setup(t, q)+ r := newOutcomeRig(t, q, true)++ r.o.handleEvent(outcomeEvent())++ if got := r.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("dropped = %d; a turn this adapter never owed is not a WeCom drop", got)+ }+ if got := r.mx.get("outbound_skipped:" + string(tc.reason)); got != 1 {+ t.Fatalf("outbound_skipped:%s = %d, want 1 — this exit is unnamed from outside. log:\n%s",+ tc.reason, got, r.logs.String())+ }+ if n := r.frames(); n != 0 {+ t.Errorf("frames = %d, want 0 — nothing was owed to this chat", n)+ }+ out := r.logs.String()+ if !strings.Contains(out, "reason="+string(tc.reason)) {+ t.Errorf("log does not name the reason:\n%s", out)+ }+ // The actionable one is a WARN an operator can alert on; the+ // ordinary two stay at DEBUG, where they are a rate rather than a+ // page.+ if warned := strings.Contains(out, "level=WARN"); warned != tc.actionable {+ t.Errorf("level=WARN present = %v, want %v:\n%s", warned, tc.actionable, out)+ }+ // "Not owed" is a claim about the obligation, and the log is what an+ // operator greps. It holds for the exits where it is established and+ // for no other.+ if said := strings.Contains(out, "not owed"); said != tc.notOwed {+ t.Errorf("log says \"not owed\" = %v, want %v:\n%s", said, tc.notOwed, out)+ }+ })}}@@ -405,3 +522,219 @@ func TestWorseUnconfirmedReason_IsARuleNotALoopOrder(t *testing.T) {}}}++// TestAReapedTaskRowIsStillADrop — the origin gate has to read a task row to+// answer anything, and that row can be gone: cancelled and reaped while its+// completion was in flight. That is not an answer to "where was this asked", it+// is the absence of one, and main counted it as+// outbound_dropped{reason="task_missing"} at WARN.+//+// Folded into a gate that returns a bool it became origin_not_channel at DEBUG+// — a lost reply wearing the label of the most ordinary event in the+// deployment, one level below where anybody is looking. That is the+// indistinguishability this file exists to remove, put back by the change that+// removes it.+//+// REVERSE VERIFICATION: return originWebUI from taskOriginOf's pgx.ErrNoRows+// branch (the collapse a bool forces) and both cases fail on the first+// assertion, with outbound_dropped:task_missing = 0 and a DEBUG+// origin_not_channel line in the log the failure prints.+func TestAReapedTaskRowIsStillADrop(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ setup func(q *fakeOutboundQueries)+ }{+ {+ // The case main covered: the delivery row is there and says wecom,+ // so this turn WAS ours and somebody is owed the answer.+ name: "with a wecom delivery row",+ setup: func(*fakeOutboundQueries) {},+ },+ {+ // No delivery row either, so nothing here can even say which+ // platform the turn belonged to. Counted the same way regardless: a+ // task row that vanished mid-completion is not ordinary for any of+ // them, and the missing-task-id branch at the top of processEvent+ // already files every platform's ending under this reason.+ name: "with no delivery row",+ setup: func(q *fakeOutboundQueries) { q.sessionErr = pgx.ErrNoRows },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ q.originErr = pgx.ErrNoRows+ tc.setup(q)+ r := newOutcomeRig(t, q, true)++ r.o.handleEvent(outcomeEvent())++ if got := r.mx.get("outbound_dropped:" + string(dropTaskMissing)); got != 1 {+ t.Fatalf("outbound_dropped:%s = %d, want 1 — a task row that is gone is a missing row, "++ "not a verdict about where the question was asked. log:\n%s",+ dropTaskMissing, got, r.logs.String())+ }+ if got := r.mx.get("outbound_skipped:" + string(skipOriginNotChannel)); got != 0 {+ t.Errorf("outbound_skipped:%s = %d; this was not a question typed in the web UI, and "++ "filing it as one is how the case disappears", skipOriginNotChannel, got)+ }+ out := r.logs.String()+ if !strings.Contains(out, "reason="+string(dropTaskMissing)) {+ t.Errorf("log does not name the reason:\n%s", out)+ }+ // WARN, not DEBUG: main's level for this, and the level an operator+ // alerts on. At DEBUG it is read as a rate, which is the wrong+ // treatment for a row that should never be missing.+ if !strings.Contains(out, "level=WARN") {+ t.Errorf("a reaped task row logged below WARN:\n%s", out)+ }+ if n := r.frames(); n != 0 {+ t.Errorf("frames = %d, want 0 — nothing could be addressed", n)+ }+ })+ }+}++// Every channel's chat:done pays for the origin gate, and what this pins is the+// PRICE. The gate runs ahead of the delivery-row lookup so a run typed in the+// web UI can give the room's bubble back before anything else touches the round+// (#8355), which means this subscriber asks it once for every completion on a+// bus every channel publishes to — another platform's turn included.+//+// ONE keyed read, where it used to be two: GetAgentTask, then the+// channel_ingested stamp. Both were on the completion response's path — this+// runs inside events.Bus.Publish, below CompleteTaskWithTransition, which the+// daemon's POST /tasks/{id}/complete waits for — so the round trip saved is one+// the user waits for, on every completion in the deployment.+//+// Pinned because a cost paid once per completion is the kind that is measured+// once, written into a comment, and then grows back.+//+// REVERSE VERIFICATION: put the two-read pair back and this fails with 2.+func TestTheOriginGateCostsOneReadPerCompletion(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ q.sessionChannelType = "slack" // another channel's turn: the busiest shape on a shared bus+ r := newOutcomeRig(t, q, true)++ r.o.handleEvent(outcomeEvent())++ if got := q.originGateReads; got != 1 {+ t.Fatalf("the origin gate ran %d read(s) for one completion, want exactly 1", got)+ }+ if got := r.mx.get("outbound_skipped:" + string(skipNotWecomTurn)); got != 1 {+ t.Fatalf("outbound_skipped:%s = %d, want 1", skipNotWecomTurn, got)+ }+}++// And the path that DOES pay for it, with the price written down. Every+// completion of a question typed in the Multica web UI arrives in the+// no-delivery-row branch — EnqueueChatTask writes no delivery row, only+// EnqueueChannelChatTask does — so on a deployment running WeCom this branch,+// not the one with a row, carries most of the traffic.+//+// ONE read each time, and the assertion is an equality on both sides for that+// reason: GetTaskChannelOrigin answers task existence and channel provenance+// together, so the branch costs one round trip on top of the delivery lookup+// main already did. It was two — GetAgentTask, then the channel_ingested stamp+// — and every one of them was on the completion response's path, see the+// contract above taskOriginOf.+//+// Pinned because a cost paid once per web message is the kind that is measured+// once, written into a comment, and then grows. The exit table is+// TestNonWecomSessionIsNotADrop's; what this one owns is the price and what the+// price buys.+//+// REVERSE VERIFICATION: split the gate back into GetAgentTask plus+// TaskHasChannelIngestedMessages and this fails with 2 lookups; drop the gate+// from that branch and record skipNoDeliveryRow unconditionally — the cheap+// version the cost argument pushes toward — and it fails with 0 lookups and+// no_delivery_row in place of origin_not_channel, which is the loudest line in+// the file firing once per web message.+func TestTheWebUITurnWithNoRowPaysForTheOriginGate(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ q.channelIngested = askedInTheWebUI()+ q.sessionErr = pgx.ErrNoRows+ r := newOutcomeRig(t, q, true)++ r.o.handleEvent(outcomeEvent())++ if got := q.originAskedFor; len(got) != 1 || got[0] != outcomeTask {+ t.Errorf("origin-classification queries = %v, want exactly one, keyed on the completed task "++ "%s — this runs on every web-UI completion in the deployment, and the completion "++ "response waits for it", got, outcomeTask)+ }+ // What the read buys: this turn leaves by the web UI's exit at DEBUG+ // instead of the missing-route WARN.+ if got := r.mx.get("outbound_skipped:" + string(skipOriginNotChannel)); got != 1 {+ t.Fatalf("outbound_skipped:%s = %d, want 1 — then the lookup bought nothing. log:\n%s",+ skipOriginNotChannel, got, r.logs.String())+ }+}++// TestAGateFailureIsNotAnUnconfirmedReply — a read that fails before anything+// reaches a socket is not an unconfirmed delivery.+//+// unconfirmedReason maps context.Canceled and context.DeadlineExceeded to+// "interrupted", and it is right to: on the SEND path a context error leaves a+// frame that may already be at the peer, which outbound_media.go:478-485 argues+// for at length. handleEvent then applies that reading to everything+// processEvent returns, including reads taken long before any byte moves — and+// an unconfirmed reply tells an operator the user may ALREADY HAVE this+// message, so a resend would duplicate it and the right move is to go and look.+// For a lookup that failed, all of that is false.+//+// Both of the origin gate's call sites are here because they fail for the same+// reason and must record the same thing. What they do NOT share is the budget:+// see the test below.+//+// REVERSE VERIFICATION: return the gate's error from either branch instead of+// recording it, and that row fails with outbound_dropped:transport_error = 0+// and an outbound_unconfirmed:interrupted WARN in the log the failure prints.+func TestAGateFailureIsNotAnUnconfirmedReply(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ setup func(q *fakeOutboundQueries)+ }{+ {+ // The observability call site: no delivery row, so nothing was+ // ever going to be sent and the read only decides a log level.+ name: "no delivery row",+ setup: func(q *fakeOutboundQueries) { q.sessionErr = pgx.ErrNoRows },+ },+ {+ // The delivery call site: the row says the turn is WeCom's, so a+ // reply WAS owed. Still nothing on the wire — the gate is upstream+ // of the socket — so still a definite drop, not an unknown.+ name: "a wecom delivery row",+ setup: func(*fakeOutboundQueries) {},+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ q := deliverableTurn(t)+ q.originErr = context.DeadlineExceeded+ tc.setup(q)+ r := newOutcomeRig(t, q, true)++ r.o.handleEvent(outcomeEvent())++ if got := r.mx.get("outbound_unconfirmed"); got != 0 {+ t.Errorf("outbound_unconfirmed = %d; nothing was written to a socket, so telling an "++ "operator the user may already have this reply is false. log:\n%s",+ got, r.logs.String())+ }+ if got := r.mx.get("outbound_dropped:" + string(dropTransport)); got != 1 {+ t.Fatalf("outbound_dropped:%s = %d, want 1 — a turn this adapter could not classify "++ "at all still has to be counted once, and definitely. log:\n%s",+ dropTransport, got, r.logs.String())+ }+ if n := r.frames(); n != 0 {+ t.Errorf("frames = %d, want 0", n)+ }+ })+ }+}diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.goindex 2d91396050..5abda51bee 100644--- a/server/internal/integrations/wecom/outbound_test.go+++ b/server/internal/integrations/wecom/outbound_test.go@@ -66,6 +66,9 @@ type fakeOutboundQueries struct {tasks map[string]db.AgentTaskQueuetaskErr errortaskGets int+ // originGateReads counts GetTaskChannelOrigin calls. It is the gate's whole+ // price: one keyed read per completion, where it used to be two.+ originGateReads int// channelIngested is the channel_ingested stamp on the input batch the// task owns: askedOverWecom for a question typed in the room,// askedInTheWebUI for one typed in Multica.@@ -269,6 +272,35 @@ func (f *fakeOutboundQueries) GetAgentTask(_ context.Context, id pgtype.UUID) (d}return task, nil}++// GetTaskChannelOrigin is one read in production, so it is one method here —+// but the ANSWER is composed from the same two facts the two-read path composes+// it from, rather than being a second stamp this double could set+// independently. A double that can disagree with+// engine.TaskInputIsChannelIngested about the same row is a double that will.+func (f *fakeOutboundQueries) GetTaskChannelOrigin(ctx context.Context, id pgtype.UUID) (db.GetTaskChannelOriginRow, error) {+ f.originGateReads+++ if f.taskErr != nil {+ return db.GetTaskChannelOriginRow{}, f.taskErr+ }+ task, ok := f.tasks[util.UUIDToString(id)]+ if !ok {+ // The query selects from agent_task_queue, so a task nobody filed has+ // no row here either — and ErrNoRows is the answer the caller tells+ // apart from a negative verdict.+ return db.GetTaskChannelOriginRow{}, pgx.ErrNoRows+ }+ if !task.ChatInputTaskID.Valid {+ // A batch with no owner is channel-ingested: no stamp is read, so no+ // rig is asked for one. fileNoOwnerTask is the only way to get here,+ // and it says in its own comment that it opts that task out of+ // failStampNotSet.+ return db.GetTaskChannelOriginRow{ChannelIngested: true, BatchOwnerUnknown: true}, nil+ }+ ingested, err := f.TaskHasChannelIngestedMessages(ctx, task.ChatInputTaskID)+ return db.GetTaskChannelOriginRow{ChannelIngested: ingested}, err+}+func (f *fakeOutboundQueries) TaskHasChannelIngestedMessages(_ context.Context, taskID pgtype.UUID) (bool, error) {f.originAskedFor = append(f.originAskedFor, util.UUIDToString(taskID))if f.originErr != nil {@@ -325,6 +357,21 @@ func (f *fakeOutboundQueries) fileRetryClone(t testing.TB, id, owner string) {f.tasks[util.UUIDToString(taskID)] = db.AgentTaskQueue{ID: taskID, ChatInputTaskID: ownerID}}+// fileNoOwnerTask files a row migration 158 left behind: chat_input_task_id+// NULL, so the origin gate delivers it without evidence and the log level on a+// missing route has to come from somewhere else. Such a task reads no+// channel_ingested stamp, so this is the one way to file a task without+// answering failStampNotSet for it.+func (f *fakeOutboundQueries) fileNoOwnerTask(t testing.TB, id string) {+ t.Helper()+ f.t = t+ taskID := mustParseTaskUUID(t, id)+ if f.tasks == nil {+ f.tasks = map[string]db.AgentTaskQueue{}+ }+ f.tasks[util.UUIDToString(taskID)] = db.AgentTaskQueue{ID: taskID}+}+func mustParseTaskUUID(t testing.TB, id string) pgtype.UUID {t.Helper()parsed, err := util.ParseUUID(id)diff --git a/server/internal/metrics/wecom.go b/server/internal/metrics/wecom.goindex 2c80d752e6..5c3579b681 100644--- a/server/internal/metrics/wecom.go+++ b/server/internal/metrics/wecom.go@@ -38,12 +38,15 @@ import "github.com/prometheus/client_golang/prometheus"// 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.+// turn that originated in the web UI, another platform's turn on the bus this+// adapter shares, or an installation revoked between trigger and reply, was+// never owed to WeCom and is a skip — as is a channel turn with no row saying+// which chat, the one skip worth waking somebody for, because there a reply may+// well be owed and nothing left can name the room; 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@@ -95,11 +98,11 @@ func NewWecomMetrics() *WecomMetrics {"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.",+ 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; most of them are settled before the frame reaches WeCom, so read this as a count of unpaid obligations rather than of network failures. The completions this adapter did not owe, and the ones nothing here can attribute to a WeCom chat, 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.",+ Help: "Completions this adapter did not send to WeCom, by reason: it did not owe them, or nothing here could attribute them to a WeCom chat. Kept apart from dropped, which counts the replies a WeCom user was owed and did not get; what separates the two is the obligation, not whether a frame was written. Four of these were never owed to WeCom, and counting them as drops would make ordinary usage read as an outage: origin_not_channel is a question typed in Multica on a WeCom-bound session, not_wecom_turn is another platform's turn on the bus this subscriber shares, installation_inactive means there is no longer an installation to deliver through, nothing_to_say is an empty completion carrying no file. The fifth is the one label here worth an alert: no_delivery_row is a turn the channel ingested with no row saying which chat, so a reply may well be owed and nothing left can name the room — in practice a task enqueued before an upgrade and finishing after it. The sixth is neither: route_unattributable is a turn with no row and no batch owner, so nothing here can say whether it was ever a channel's, let alone whether a reply was owed — in practice a row old enough to predate batch owners still finishing, and a rising count says only that such rows remain.",}, []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."),diff --git a/server/internal/metrics/wecom_test.go b/server/internal/metrics/wecom_test.goindex 701089ecda..a4419949b4 100644--- a/server/internal/metrics/wecom_test.go+++ b/server/internal/metrics/wecom_test.go@@ -1,6 +1,7 @@package metricsimport (+ "strings""testing""github.com/prometheus/client_golang/prometheus"@@ -47,3 +48,149 @@ func gatherWecomCounterValues(t *testing.T, reg prometheus.Gatherer) map[string]}return values}++// The Help string is the whole of what an operator is told about a counter: it+// ships on /metrics and it is what a dashboard prints beside the series. So the+// two tests below ask of that text the question an on-call brings at 3am —+// which of these labels means somebody is waiting, and which one do I act on.+//+// Asserting that the labels are all mentioned is not enough, and that is not a+// hypothetical. The list was asserted; the prose around it was then rewritten+// to say the drop/skip boundary is whether a frame went on the wire; the test+// stayed green while the Help pointed the reader away from the alert. What+// actually separates the two counters is the OBLIGATION — was a reply owed to a+// WeCom user — and four of the five drop reasons are settled before anything is+// written to a socket. So these assert where each label sits relative to that+// line, not that it appears.+//+// The words are load-bearing. Reword the Help and this goes red; keep the claim+// and the test moves with it.+func TestSkippedHelpPutsEachReasonOnTheRightSideOfTheAlertLine(t *testing.T) {+ help := helpFor(t, "multica_wecom_outbound_skipped_total", func(m *WecomMetrics) {+ m.RecordOutboundSkipped("no_delivery_row")+ })+ // Four that were never owed to WeCom, the one that may well have been, and+ // (below) the one nothing here can say either way about.+ ordinary := []string{+ "origin_not_channel", "not_wecom_turn", "installation_inactive", "nothing_to_say",+ }+ const actionable = "no_delivery_row"++ alert := sentenceNaming(t, help, actionable)+ if !containsAny(alert, "may well be owed", "may be owed") {+ t.Errorf("the %q sentence does not say a reply may be owed, which is the whole reason it is "++ "not filed with the harmless four:\n%s", actionable, alert)+ }+ if !strings.Contains(alert, "alert") {+ t.Errorf("the %q sentence does not tell the operator this is the label to alert on:\n%s",+ actionable, alert)+ }+ for _, reason := range ordinary {+ if strings.Contains(alert, reason) {+ t.Errorf("%q shares a sentence with %q, so the Help reads as though the alert covers it "++ "too:\n%s", reason, actionable, alert)+ }+ line := sentenceNaming(t, help, reason)+ if !containsAny(line, "never owed", "not owed") {+ t.Errorf("the %q sentence does not say it was never owed to WeCom — without that, the "++ "reader has no rule for why these four are not drops:\n%s", reason, line)+ }+ }++ // And the one on neither side. With no route and no batch owner nothing can+ // say whether a reply was owed, so the Help must neither file it with the+ // harmless four ("never owed") nor with the alert.+ const unattributable = "route_unattributable"+ line := sentenceNaming(t, help, unattributable)+ if strings.Contains(alert, unattributable) {+ t.Errorf("%q shares a sentence with %q, so the Help reads as though the alert covers it:\n%s",+ unattributable, actionable, alert)+ }+ if containsAny(line, "never owed", "not owed") {+ t.Errorf("the %q sentence says it was not owed, which is the one thing nothing here can "++ "establish about it:\n%s", unattributable, line)+ }+ if !strings.Contains(line, "nothing here can say") {+ t.Errorf("the %q sentence does not say the owner is unknowable, so the reader has no rule "++ "for why it is neither a drop nor an alert:\n%s", unattributable, line)+ }+}++// The dropped counter is the same question read from the other end, so its Help+// has to draw the same line: a drop is a reply somebody was OWED and did not+// get. Not "a frame that went out and failed" — task_missing is decided before+// anything is sent, no_live_connection means there was no socket to send on,+// attachment_not_admitted is refused at admission, and transport_error covers a+// delivery whose budget ran out before its turn on the wire. Four of the five+// never reach WeCom at all. A Help that defines the counter by the wire sends+// an operator hunting a network fault for a reply that was lost on our side of+// it.+func TestDroppedHelpDefinesADropByWhatWasOwed(t *testing.T) {+ help := helpFor(t, "multica_wecom_outbound_dropped_total", func(m *WecomMetrics) {+ m.RecordOutboundDropped("task_missing")+ })+ if first := sentences(help)[0]; !strings.Contains(first, "owed") {+ t.Errorf("the opening sentence does not define a drop by what was owed:\n%s", first)+ }+ if !strings.Contains(help, "outbound_skipped_total") {+ t.Errorf("the help does not say where the completions that were not owed are counted:\n%s", help)+ }+ if containsAny(help, "on the wire", "went out") {+ t.Errorf("the help defines the drop set by whether the frame reached WeCom; four of the five "++ "reasons never get that far:\n%s", help)+ }+}++// helpFor gathers one counter family and returns its Help. A CounterVec with no+// children is gathered as no family at all, so record has to put a label value+// in before the text is readable.+func helpFor(t *testing.T, name string, record func(*WecomMetrics)) string {+ t.Helper()+ reg := prometheus.NewRegistry()+ m := NewWecomMetrics()+ for _, collector := range m.Collectors() {+ if err := reg.Register(collector); err != nil {+ t.Fatalf("register WeCom collector: %v", err)+ }+ }+ record(m)+ families, err := reg.Gather()+ if err != nil {+ t.Fatalf("gather WeCom metrics: %v", err)+ }+ for _, family := range families {+ if family.GetName() == name {+ if help := family.GetHelp(); help != "" {+ return help+ }+ t.Fatalf("%s carries no help text", name)+ }+ }+ t.Fatalf("%s is not exported at all", name)+ return ""+}++func sentences(help string) []string { return strings.Split(help, ". ") }++// sentenceNaming returns the sentence that names reason, and ends the test if+// none does: a label an operator meets in the breakdown and cannot find in the+// Help leaves them with nothing to read.+func sentenceNaming(t *testing.T, help, reason string) string {+ t.Helper()+ for _, sentence := range sentences(help) {+ if strings.Contains(sentence, reason) {+ return sentence+ }+ }+ t.Fatalf("the help does not explain the %q label:\n%s", reason, help)+ return ""+}++func containsAny(s string, subs ...string) bool {+ for _, sub := range subs {+ if strings.Contains(s, sub) {+ return true+ }+ }+ return false+}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 1653c60409..94ccc385a7 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -1237,6 +1237,86 @@ func (q *Queries) GetPublicChatSessionInWorkspace(ctx context.Context, arg GetPureturn i, err}+const getTaskChannelOrigin = `-- name: GetTaskChannelOrigin :one+SELECT (+ task.chat_input_task_id IS NULL+ OR EXISTS (+ SELECT 1+ FROM chat_message+ WHERE task_id = task.chat_input_task_id+ AND role = 'user'+ AND channel_ingested+ )+)::boolean AS channel_ingested,+ (task.chat_input_task_id IS NULL)::boolean AS batch_owner_unknown+FROM agent_task_queue AS task+WHERE task.id = $1+`++type GetTaskChannelOriginRow struct {+ ChannelIngested bool `json:"channel_ingested"`+ BatchOwnerUnknown bool `json:"batch_owner_unknown"`+}++// The whole origin question for one completed task in one round trip: is the+// task row still there, and did its input arrive over a channel?+//+// This answers exactly what engine.TaskInputIsChannelIngested answers, in one+// read instead of two (GetAgentTask, then TaskHasChannelIngestedMessages). That+// function is the definition; this is a transcription of it, not an improvement+// on it. Both halves are load-bearing:+//+// - A task with NO input batch owner is channel-ingested. Migration 158 left+// both legacy direct rows and channel tasks NULL here, so the owner cannot+// say which one a row was, and the adapters that read this deliver by+// default — the behaviour #5645 shipped. Keying the EXISTS on the task's+// own id instead (COALESCE(chat_input_task_id, id)) silently stops+// delivering the auto-retry of a legacy channel task: CreateRetryTask+// copies a NULL owner verbatim, on purpose (see agent.sql), and the clone+// owns no messages — so it reads as web UI while CopyChannelTaskDelivery+// has already given it the room's route.+// - Otherwise the verdict is the batch OWNER'S, not the task's. An auto-retry+// clone inherits its parent's chat_input_task_id while the user's message+// stays tagged with the parent, so reading the owner is what lets the clone+// reach the verdict its parent already has (MUL-4351).+//+// NO ROW means the task is gone — cancelled and reaped while its ending was in+// flight. Callers receive pgx.ErrNoRows and must not fold that into "asked in+// the web UI": it is the absence of a verdict, not a negative one, and the two+// are recorded differently.+//+// One round trip rather than two because this read is SYNCHRONOUS ON THE+// COMPLETION RESPONSE. It runs inside events.Bus.Publish+// (internal/events/bus.go:61-76), below TaskService.broadcastChatDone+// (internal/service/task.go:7330) and CompleteTaskWithTransition+// (internal/service/task.go:4518), which the daemon's POST /tasks/{id}/complete+// waits for before it answers (internal/handler/daemon.go:4269).+//+// batch_owner_unknown IS THE SAME FACT, REPORTED SEPARATELY, and it exists for+// one reader: the log level on a turn that has no delivery row.+//+// channel_ingested above says "deliver this", and for a NULL owner it says so+// without evidence — which is right, because delivering is the safe side and+// the auto-retry of a legacy channel turn depends on it. Warning is the other+// direction: a missing route is worth paging an operator about only when+// something actually established the turn was a channel's. A NULL owner+// establishes nothing, so a missing route on one of those is not evidence of a+// lost reply; migration 158 left legacy web rows and channel rows alike NULL+// here, and reading it as "channel" would put the loudest line this adapter has+// on a pre-158 web turn that auto-retried.+//+// So one verdict, two readings: deliver on the open side, warn on the closed+// one. The query reports both and chooses neither.+//+// Plan: agent_task_queue_pkey for the row, idx_chat_message_input_owner for the+// EXISTS. Neither side scans.+func (q *Queries) GetTaskChannelOrigin(ctx context.Context, id pgtype.UUID) (GetTaskChannelOriginRow, error) {+ row := q.db.QueryRow(ctx, getTaskChannelOrigin, id)+ var i GetTaskChannelOriginRow+ err := row.Scan(&i.ChannelIngested, &i.BatchOwnerUnknown)+ return i, err+}+const hasActiveChatTaskForSession = `-- name: HasActiveChatTaskForSession :oneSELECT EXISTS (SELECT 1 FROM agent_task_queuediff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex acdb489a4d..9687de4fc3 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -522,6 +522,73 @@ SELECT EXISTS (AND channel_ingested) AS channel_ingested;+-- name: GetTaskChannelOrigin :one+-- The whole origin question for one completed task in one round trip: is the+-- task row still there, and did its input arrive over a channel?+--+-- This answers exactly what engine.TaskInputIsChannelIngested answers, in one+-- read instead of two (GetAgentTask, then TaskHasChannelIngestedMessages). That+-- function is the definition; this is a transcription of it, not an improvement+-- on it. Both halves are load-bearing:+--+-- * A task with NO input batch owner is channel-ingested. Migration 158 left+-- both legacy direct rows and channel tasks NULL here, so the owner cannot+-- say which one a row was, and the adapters that read this deliver by+-- default — the behaviour #5645 shipped. Keying the EXISTS on the task's+-- own id instead (COALESCE(chat_input_task_id, id)) silently stops+-- delivering the auto-retry of a legacy channel task: CreateRetryTask+-- copies a NULL owner verbatim, on purpose (see agent.sql), and the clone+-- owns no messages — so it reads as web UI while CopyChannelTaskDelivery+-- has already given it the room's route.+-- * Otherwise the verdict is the batch OWNER'S, not the task's. An auto-retry+-- clone inherits its parent's chat_input_task_id while the user's message+-- stays tagged with the parent, so reading the owner is what lets the clone+-- reach the verdict its parent already has (MUL-4351).+--+-- NO ROW means the task is gone — cancelled and reaped while its ending was in+-- flight. Callers receive pgx.ErrNoRows and must not fold that into "asked in+-- the web UI": it is the absence of a verdict, not a negative one, and the two+-- are recorded differently.+--+-- One round trip rather than two because this read is SYNCHRONOUS ON THE+-- COMPLETION RESPONSE. It runs inside events.Bus.Publish+-- (internal/events/bus.go:61-76), below TaskService.broadcastChatDone+-- (internal/service/task.go:7330) and CompleteTaskWithTransition+-- (internal/service/task.go:4518), which the daemon's POST /tasks/{id}/complete+-- waits for before it answers (internal/handler/daemon.go:4269).+--+-- batch_owner_unknown IS THE SAME FACT, REPORTED SEPARATELY, and it exists for+-- one reader: the log level on a turn that has no delivery row.+--+-- channel_ingested above says "deliver this", and for a NULL owner it says so+-- without evidence — which is right, because delivering is the safe side and+-- the auto-retry of a legacy channel turn depends on it. Warning is the other+-- direction: a missing route is worth paging an operator about only when+-- something actually established the turn was a channel's. A NULL owner+-- establishes nothing, so a missing route on one of those is not evidence of a+-- lost reply; migration 158 left legacy web rows and channel rows alike NULL+-- here, and reading it as "channel" would put the loudest line this adapter has+-- on a pre-158 web turn that auto-retried.+--+-- So one verdict, two readings: deliver on the open side, warn on the closed+-- one. The query reports both and chooses neither.+--+-- Plan: agent_task_queue_pkey for the row, idx_chat_message_input_owner for the+-- EXISTS. Neither side scans.+SELECT (+ task.chat_input_task_id IS NULL+ OR EXISTS (+ SELECT 1+ FROM chat_message+ WHERE task_id = task.chat_input_task_id+ AND role = 'user'+ AND channel_ingested+ )+)::boolean AS channel_ingested,+ (task.chat_input_task_id IS NULL)::boolean AS batch_owner_unknown+FROM agent_task_queue AS task+WHERE task.id = $1;+-- name: SetChatMessageChannelOutboundProvenanceByTask :execrows-- The assistant row is committed before EventChatDone is published. Attach the-- external identifiers produced by the adapter to that durable turn so a live