Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7024 fix(wecom): clear the previous bot's rows when an agent swaps bots (#7985)
Raymundo Arbogustaa684997f1ec
diff --git a/server/internal/integrations/wecom/installation.go b/server/internal/integrations/wecom/installation.goindex fff96a0fb7..a1ddacb798 100644--- a/server/internal/integrations/wecom/installation.go+++ b/server/internal/integrations/wecom/installation.go@@ -10,6 +10,7 @@ import ("context""errors""fmt"+ "log/slog""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn"@@ -61,6 +62,18 @@ type InstallationService struct {// WeCom at install time gets a 503 and retries, it does not get to install// unverified credentials over somebody else's row.probe CredentialProbe++ // logger is only ever used to say what a bot swap threw away. Nil-safe+ // through log() below, the same shape channel_media_reconciler.go uses, so+ // a struct built in a test does not have to supply one.+ logger *slog.Logger+}++func (s *InstallationService) log() *slog.Logger {+ if s.logger == nil {+ return slog.Default()+ }+ return s.logger}// InstallationOption configures the service at construction.@@ -94,10 +107,11 @@ func NewInstallationService(queries *db.Queries, tx engine.TxStarter, box *secrereturn nil, errors.New("wecom: InstallationService requires a non-nil secretbox.Box")}svc := &InstallationService{- store: NewStore(queries),- tx: tx,- box: box,- probe: NewHandshakeProbe(nil, ""),+ store: NewStore(queries),+ tx: tx,+ box: box,+ probe: NewHandshakeProbe(nil, ""),+ logger: slog.Default(),}for _, o := range opts {o(svc)@@ -221,6 +235,55 @@ func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams)if err != nil {return Installation{}, err}+ // A bot SWAP on an existing installation: the row and its id are reused —+ // UpsertChannelInstallation conflicts on (workspace_id, agent_id,+ // channel_type) and only rewrites config — so every dependent row keyed on+ // installation_id would otherwise survive into a bot it does not belong to.+ //+ // They are not merely stale. A WeCom aibot userid is anonymized per (bot,+ // user), which is the premise the whole binding flow rests on (binding.go),+ // so a carried-over channel_user_binding holds an id from a namespace the+ // new bot does not share. Outbound.tryDeliverInbox looks that binding up by+ // (workspace, member, channel_type) — not by bot — resolves the sender by+ // its installation_id, which is now the LIVE NEW bot, and addresses the OLD+ // bot's userid over it. A p2p chat binding carries the same userid as its+ // channel_chat_id, and a queued task delivery carries it again.+ //+ // Runs in this transaction, before the upsert, so a swap that fails later+ // leaves the old bot's rows intact rather than half-cleared. (#6547)+ //+ // The sweep is not airtight, and cannot be from here. The slot lock taken+ // above is the NEW bot's; the OLD bot's socket stays live until the+ // Supervisor tears it down, so an inbound message arriving under it between+ // this DELETE and the COMMIT re-inserts a binding that outlives the sweep.+ // The window is short and self-healing, but not silently: that binding is+ // the old bot's namespace, so what the user sees while it heals is one+ // message that gets no answer and no line saying why, until they re-bind.+ // Closing it properly means a second clear once the old connection is+ // confirmed down, which this transaction cannot observe — a Supervisor+ // signal for "old connection torn down" is the hook to hang it on.+ if carried.ID.Valid && carried.BotID != "" && carried.BotID != p.BotID {+ cleared, err := qtx.Queries.ClearChannelInstallationBotScopedRows(ctx, carried.ID)+ if err != nil {+ return Installation{}, fmt.Errorf("wecom: clear previous bot's rows: %w", err)+ }+ // A queued task delivery is a RUNNING task's answer. Dropping it is+ // right — its address is the old bot's userid, unreachable from the new+ // connection either way — but processEvent then finds no row and+ // returns nil, with no counter and no line of its own, so this is the+ // only place that can say where the answer went. A queued outbound+ // message is the same story one table over, usually zero for WeCom, and+ // counted here rather than reasoned about the day it is not.+ s.log().InfoContext(ctx, "wecom: bot swap cleared the previous bot's rows",+ "installation_id", uuidStringPub(carried.ID),+ "previous_bot_id", carried.BotID,+ "user_bindings", cleared.UserBindings,+ "chat_session_bindings", cleared.ChatSessionBindings,+ "queued_task_deliveries_dropped", cleared.TaskDeliveries,+ "queued_outbound_messages_dropped", cleared.OutboundMessages,+ )+ }+// The chat name is optional in the dialog, so an admin rotating a leaked// secret leaves it blank — and blanking it would put group slash commands// back to the whitespace guess that this field exists to replace. Keep whatdiff --git a/server/internal/integrations/wecom/installation_bot_swap_test.go b/server/internal/integrations/wecom/installation_bot_swap_test.gonew file mode 100644index 0000000000..3ef9467328--- /dev/null+++ b/server/internal/integrations/wecom/installation_bot_swap_test.go@@ -0,0 +1,263 @@+package wecom++// installation_bot_swap_test.go — a bot swap must not leave the previous bot's+// rows behind (#6547). DB-backed, because the whole claim is about what+// survives an upsert that reuses the installation row; skips when no migrated+// database is reachable, like installation_bot_name_test.go beside it.+//+// Why it matters: a WeCom aibot userid is anonymized per (bot, user), so a+// channel_user_binding that outlives the bot it was made under holds an id the+// new bot does not share. Outbound.tryDeliverInbox finds that binding by+// (workspace, member, channel_type), resolves the sender by its reused+// installation_id — the LIVE NEW bot — and sends to the OLD bot's userid.++import (+ "context"+ "log/slog"+ "sync"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+)++const (+ wcSwapWS = "5c09e202-0000-4000-8000-000000000001"+ wcSwapRuntime = "5c09e202-0000-4000-8000-000000000003"+ wcSwapAgent = "5c09e202-0000-4000-8000-00000000000a"+ wcSwapUser = "5c09e202-0000-4000-8000-000000000005"+ wcSwapChat = "5c09e202-0000-4000-8000-000000000007"+ wcSwapBinding = "5c09e202-0000-4000-8000-00000000000b"+ wcSwapTask = "5c09e202-0000-4000-8000-00000000000c"++ wcSwapBotA = "bot_swap_a"+ wcSwapBotB = "bot_swap_b"++ // The anonymized userid bot A knows this member by. Bot B has never+ // issued it and cannot address it.+ wcSwapUserIDUnderA = "TBOT_A_USERID"+)++func setupBotSwap(t *testing.T) (context.Context, *pgxpool.Pool, *InstallationService) {+ t.Helper()+ pool := reclaimTestDB(t)+ ctx := context.Background()+ // The seeded rows are cleaned explicitly, by their own identifiers: none of+ // these tables has a foreign key to installation or workspace (MUL-3515 §4),+ // so dropping those rows does not take them with it — and one of the tests+ // below asserts its rows SURVIVE, which would otherwise leave a+ // channel_chat_session_binding behind to collide with the next run on the+ // UNIQUE (chat_session_id).+ clean := func() {+ _, _ = pool.Exec(ctx, `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, wcSwapChat)+ _, _ = pool.Exec(ctx, `DELETE FROM channel_user_binding WHERE workspace_id = $1`, wcSwapWS)+ _, _ = pool.Exec(ctx, `DELETE FROM channel_binding_token WHERE workspace_id = $1`, wcSwapWS)+ _, _ = pool.Exec(ctx, `DELETE FROM channel_inbound_message_dedup WHERE message_id = $1`, "msg_under_bot_a")+ _, _ = pool.Exec(ctx, `DELETE FROM channel_task_delivery WHERE task_id = $1`, wcSwapTask)+ _, _ = pool.Exec(ctx, `DELETE FROM channel_outbound_message WHERE binding_id = $1`, wcSwapBinding)+ _, _ = pool.Exec(ctx, `DELETE FROM channel_outbound_card_message WHERE chat_session_id = $1`, wcSwapChat)+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE config->>'app_id' = ANY($1)`,+ []string{wcSwapBotA, wcSwapBotB})+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wcSwapWS)+ }+ clean()+ exec := func(q string, args ...any) {+ if _, err := pool.Exec(ctx, q, args...); err != nil {+ t.Fatalf("seed bot-swap fixture: %v", err)+ }+ }+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'wecom bot swap', 'wecom-bot-swap', '') ON CONFLICT (id) DO NOTHING`, wcSwapWS)+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)+VALUES ($1, $2, 'wecom bot swap runtime', 'local', 'multica_daemon') ON CONFLICT (id) DO NOTHING`, wcSwapRuntime, wcSwapWS)+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id)+VALUES ($1, $2, 'wecom bot swap agent', 'local', $3) ON CONFLICT (id) DO NOTHING`, wcSwapAgent, wcSwapWS, wcSwapRuntime)+ t.Cleanup(clean)+ svc, _ := newReclaimSvc(t, pool)+ return ctx, pool, svc+}++func botSwapParams(bot string) InstallationParams {+ return InstallationParams{+ WorkspaceID: mustUUID(wcSwapWS),+ AgentID: mustUUID(wcSwapAgent),+ InstallerUserID: mustUUID(wcSwapUser),+ BotID: bot,+ Secret: "s3cr3t",+ }+}++// seedBotScopedRows writes one row of each kind a member's traffic leaves+// under an installation. None of these tables has a foreign key (MUL-3515 §4),+// which is exactly why the cleanup has to be explicit.+func seedBotScopedRows(t *testing.T, ctx context.Context, pool *pgxpool.Pool, installationID pgtype.UUID) {+ t.Helper()+ exec := func(q string, args ...any) {+ if _, err := pool.Exec(ctx, q, args...); err != nil {+ t.Fatalf("seed bot-scoped row: %v", err)+ }+ }+ exec(`INSERT INTO channel_user_binding (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id, config)+VALUES ($1, $2, $3, 'wecom', $4, '{}'::jsonb)`, wcSwapWS, wcSwapUser, installationID, wcSwapUserIDUnderA)+ exec(`INSERT INTO channel_chat_session_binding (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config)+VALUES ($1, $2, 'wecom', $3, 'p2p', '{}'::jsonb)`, wcSwapChat, installationID, wcSwapUserIDUnderA)+ exec(`INSERT INTO channel_binding_token (token_hash, workspace_id, installation_id, channel_type, channel_user_id, expires_at)+VALUES ($1, $2, $3, 'wecom', $4, now() + interval '10 minutes')`, "hash_"+wcSwapUserIDUnderA, wcSwapWS, installationID, wcSwapUserIDUnderA)+ exec(`INSERT INTO channel_inbound_message_dedup (installation_id, message_id)+VALUES ($1, $2)`, installationID, "msg_under_bot_a")+ // The outbound three. They are the same defect one step later: each carries+ // the old bot's userid as the address it would be sent to, over the new+ // bot's connection. channel_outbound_card_message has no installation_id+ // and no FK, so it hangs off the chat-session binding above — the only link+ // back, and the reason the query reaches it through that binding rather+ // than directly.+ exec(`INSERT INTO channel_task_delivery (task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, route_revision, config)+VALUES ($1, $2, $3, 'wecom', $4, 'p2p', 1, '{}'::jsonb)`, wcSwapTask, wcSwapBinding, installationID, wcSwapUserIDUnderA)+ exec(`INSERT INTO channel_outbound_message (installation_id, channel_type, channel_message_id, binding_id, route_revision, outbound_kind)+VALUES ($1, 'wecom', $2, $3, 1, 'reply')`, installationID, "sent_under_bot_a", wcSwapBinding)+ exec(`INSERT INTO channel_outbound_card_message (chat_session_id, channel_type, channel_chat_id, channel_card_message_id)+VALUES ($1, 'wecom', $2, $3)`, wcSwapChat, wcSwapUserIDUnderA, "card_under_bot_a")+}++// countBotScopedRows totals the rows still hanging off an installation.+func countBotScopedRows(t *testing.T, ctx context.Context, pool *pgxpool.Pool, installationID pgtype.UUID) map[string]int {+ t.Helper()+ counts := map[string]int{}+ for _, table := range []string{+ "channel_user_binding",+ "channel_chat_session_binding",+ "channel_binding_token",+ "channel_inbound_message_dedup",+ "channel_task_delivery",+ "channel_outbound_message",+ } {+ var n int+ // The table name is a constant from the list above, never input.+ if err := pool.QueryRow(ctx,+ `SELECT count(*) FROM `+table+` WHERE installation_id = $1`, installationID,+ ).Scan(&n); err != nil {+ t.Fatalf("count %s: %v", table, err)+ }+ counts[table] = n+ }+ // Counted by chat session, not installation: this is the one table with+ // neither column nor FK, which is why it is reached through the binding.+ var cards int+ if err := pool.QueryRow(ctx,+ `SELECT count(*) FROM channel_outbound_card_message WHERE chat_session_id = $1`, wcSwapChat,+ ).Scan(&cards); err != nil {+ t.Fatalf("count channel_outbound_card_message: %v", err)+ }+ counts["channel_outbound_card_message"] = cards+ return counts+}++// TestSwappingTheBotClearsThePreviousBotsRows is #6547: the installation row is+// reused, so without an explicit purge every dependent row crosses over into a+// bot whose userid namespace does not contain them.+func TestSwappingTheBotClearsThePreviousBotsRows(t *testing.T) {+ ctx, pool, svc := setupBotSwap(t)+ swept := &sweptCounts{}+ svc.logger = slog.New(swept)++ under, err := svc.Upsert(ctx, botSwapParams(wcSwapBotA))+ if err != nil {+ t.Fatalf("first install: %v", err)+ }+ seedBotScopedRows(t, ctx, pool, under.ID)++ swapped, err := svc.Upsert(ctx, botSwapParams(wcSwapBotB))+ if err != nil {+ t.Fatalf("bot swap: %v", err)+ }+ // The premise of the bug. If the id ever stops being reused this test is+ // asserting nothing, so state it rather than assume it.+ if swapped.ID != under.ID {+ t.Fatalf("installation id changed on swap (%v -> %v); this test no longer covers #6547",+ under.ID, swapped.ID)+ }++ for table, n := range countBotScopedRows(t, ctx, pool, swapped.ID) {+ if n != 0 {+ t.Errorf("%s still has %d row(s) from the previous bot — the new bot would "++ "address userids from a namespace it does not share", table, n)+ }+ }++ // The counts are the only trace a dropped reply leaves. A queued task+ // delivery and a queued outbound message both vanish without a line of+ // their own — processEvent finds no row and returns nil — so a zero here+ // while a row was actually deleted is a person waiting for an answer that+ // no log can account for.+ line, ok := swept.line()+ if !ok {+ t.Fatal("no bot-swap log line; a swap that clears rows must say what it cleared")+ }+ for _, field := range []string{+ "user_bindings", "chat_session_bindings",+ "queued_task_deliveries_dropped", "queued_outbound_messages_dropped",+ } {+ if line[field] != 1 {+ t.Errorf("%s = %d, want the 1 seeded row reported", field, line[field])+ }+ }+}++// sweptCounts captures the bot-swap log line. The counts go nowhere else: the+// service returns an Installation, not a report.+type sweptCounts struct {+ mu sync.Mutex+ counts map[string]int64+ seen bool+}++func (c *sweptCounts) Enabled(context.Context, slog.Level) bool { return true }+func (c *sweptCounts) WithAttrs([]slog.Attr) slog.Handler { return c }+func (c *sweptCounts) WithGroup(string) slog.Handler { return c }++func (c *sweptCounts) Handle(_ context.Context, r slog.Record) error {+ if r.Message != "wecom: bot swap cleared the previous bot's rows" {+ return nil+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ c.counts = map[string]int64{}+ c.seen = true+ r.Attrs(func(a slog.Attr) bool {+ if a.Value.Kind() == slog.KindInt64 {+ c.counts[a.Key] = a.Value.Int64()+ }+ return true+ })+ return nil+}++func (c *sweptCounts) line() (map[string]int64, bool) {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.counts, c.seen+}++// TestRotatingTheSecretKeepsTheBindings is the other half, and the one a+// too-eager purge would break: pasting a fresh secret for the SAME bot is a+// credential rotation, not a swap. Clearing there would silently unbind every+// member and make them link their account again.+func TestRotatingTheSecretKeepsTheBindings(t *testing.T) {+ ctx, pool, svc := setupBotSwap(t)++ under, err := svc.Upsert(ctx, botSwapParams(wcSwapBotA))+ if err != nil {+ t.Fatalf("first install: %v", err)+ }+ seedBotScopedRows(t, ctx, pool, under.ID)++ rotated, err := svc.Upsert(ctx, botSwapParams(wcSwapBotA))+ if err != nil {+ t.Fatalf("secret rotation: %v", err)+ }+ for table, n := range countBotScopedRows(t, ctx, pool, rotated.ID) {+ if n != 1 {+ t.Errorf("%s has %d row(s) after a same-bot rotation, want the 1 seeded — "++ "a rotation must not unbind anybody", table, n)+ }+ }+}diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.goindex 2e06350ec6..b4827224fa 100644--- a/server/pkg/db/generated/channel.sql.go+++ b/server/pkg/db/generated/channel.sql.go@@ -364,6 +364,102 @@ func (q *Queries) ClearChannelChatSessionPendingFreshForRevision(ctx context.Conreturn err}+const clearChannelInstallationBotScopedRows = `-- name: ClearChannelInstallationBotScopedRows :one+WITH cleared_chat_sessions AS (+ DELETE FROM channel_chat_session_binding AS binding+ WHERE binding.installation_id = $1+ RETURNING binding.chat_session_id+),+cleared_outbound_cards AS (+ DELETE FROM channel_outbound_card_message AS card+ WHERE card.chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)+ RETURNING card.id+),+cleared_task_deliveries AS (+ DELETE FROM channel_task_delivery AS delivery+ WHERE delivery.installation_id = $1+ RETURNING delivery.task_id+),+cleared_outbound_messages AS (+ DELETE FROM channel_outbound_message AS outbound+ WHERE outbound.installation_id = $1+ RETURNING outbound.channel_message_id+),+cleared_binding_tokens AS (+ DELETE FROM channel_binding_token AS token+ WHERE token.installation_id = $1+ RETURNING token.token_hash+),+cleared_inbound_dedup AS (+ DELETE FROM channel_inbound_message_dedup AS dedup+ WHERE dedup.installation_id = $1+ RETURNING dedup.message_id+),+cleared_user_bindings AS (+ DELETE FROM channel_user_binding AS user_binding+ WHERE user_binding.installation_id = $1+ RETURNING user_binding.id+)+SELECT+ (SELECT count(*) FROM cleared_user_bindings)::bigint AS user_bindings,+ (SELECT count(*) FROM cleared_chat_sessions)::bigint AS chat_session_bindings,+ (SELECT count(*) FROM cleared_task_deliveries)::bigint AS task_deliveries,+ (SELECT count(*) FROM cleared_outbound_messages)::bigint AS outbound_messages+`++type ClearChannelInstallationBotScopedRowsRow struct {+ UserBindings int64 `json:"user_bindings"`+ ChatSessionBindings int64 `json:"chat_session_bindings"`+ TaskDeliveries int64 `json:"task_deliveries"`+ OutboundMessages int64 `json:"outbound_messages"`+}++// Bot-swap cleanup. Pointing an existing installation at a DIFFERENT bot keeps+// the installation row and its id — UpsertChannelInstallation conflicts on+// (workspace_id, agent_id, channel_type) and only rewrites config — so every+// dependent row keyed on installation_id survives into a bot it does not belong+// to. This clears the ones that are scoped to the OLD bot (#6547).+//+// Why they are invalid rather than merely stale: a WeCom aibot userid is+// anonymized per (bot, user), so a carried-over channel_user_binding addresses+// the new bot with an id from a namespace it does not share — Outbound's inbox+// push resolves the sender by installation_id (reused, hence the LIVE new bot)+// and then sends to the OLD bot's userid. The same reasoning covers a p2p chat+// binding, whose channel_chat_id IS that userid, and every queued outbound row+// carrying one.+//+// The installation itself, and the audit trail beneath it, deliberately stay:+// the row is the same connection under new credentials, and a channel_inbound_+// audit row still records something an operator can act on. Reclaim DETACHes+// audit only because the installation is going away, which here it is not.+//+// chat_session is likewise NOT touched. Deleting the binding detaches the WeCom+// route from the Chat, the same shape a disconnect leaves behind; the Chat and+// its history are the user's work product and outlive whichever bot carried+// them. channel_outbound_card_message has no installation_id and no FK, so it+// is reached through the just-removed bindings — the only link back — and goes+// because the platform message ids on it belong to the old bot.+//+// Returns what it removed. A queued channel_task_delivery is a RUNNING task's+// answer: processEvent finds no row and returns nil, so the answer is dropped+// with no counter and no log line of its own. Deleting it is still right — the+// address on it is the old bot's userid and unreachable either way — but+// whoever is waiting for that answer deserves one line saying where it went.+// channel_outbound_message is counted for the same reason and not because it is+// expected to be non-zero: a dropped queued send is a reply that never arrives,+// and a count nobody has to read costs nothing next to guessing later.+func (q *Queries) ClearChannelInstallationBotScopedRows(ctx context.Context, installationID pgtype.UUID) (ClearChannelInstallationBotScopedRowsRow, error) {+ row := q.db.QueryRow(ctx, clearChannelInstallationBotScopedRows, installationID)+ var i ClearChannelInstallationBotScopedRowsRow+ err := row.Scan(+ &i.UserBindings,+ &i.ChatSessionBindings,+ &i.TaskDeliveries,+ &i.OutboundMessages,+ )+ return i, err+}+const consumeChannelBindingToken = `-- name: ConsumeChannelBindingToken :oneUPDATE channel_binding_tokenSET consumed_at = now()diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sqlindex f7b2ac9c4f..a8be4a31d5 100644--- a/server/pkg/db/queries/channel.sql+++ b/server/pkg/db/queries/channel.sql@@ -264,6 +264,82 @@ detached_audit AS ()SELECT id FROM dead;+-- name: ClearChannelInstallationBotScopedRows :one+-- Bot-swap cleanup. Pointing an existing installation at a DIFFERENT bot keeps+-- the installation row and its id — UpsertChannelInstallation conflicts on+-- (workspace_id, agent_id, channel_type) and only rewrites config — so every+-- dependent row keyed on installation_id survives into a bot it does not belong+-- to. This clears the ones that are scoped to the OLD bot (#6547).+--+-- Why they are invalid rather than merely stale: a WeCom aibot userid is+-- anonymized per (bot, user), so a carried-over channel_user_binding addresses+-- the new bot with an id from a namespace it does not share — Outbound's inbox+-- push resolves the sender by installation_id (reused, hence the LIVE new bot)+-- and then sends to the OLD bot's userid. The same reasoning covers a p2p chat+-- binding, whose channel_chat_id IS that userid, and every queued outbound row+-- carrying one.+--+-- The installation itself, and the audit trail beneath it, deliberately stay:+-- the row is the same connection under new credentials, and a channel_inbound_+-- audit row still records something an operator can act on. Reclaim DETACHes+-- audit only because the installation is going away, which here it is not.+--+-- chat_session is likewise NOT touched. Deleting the binding detaches the WeCom+-- route from the Chat, the same shape a disconnect leaves behind; the Chat and+-- its history are the user's work product and outlive whichever bot carried+-- them. channel_outbound_card_message has no installation_id and no FK, so it+-- is reached through the just-removed bindings — the only link back — and goes+-- because the platform message ids on it belong to the old bot.+--+-- Returns what it removed. A queued channel_task_delivery is a RUNNING task's+-- answer: processEvent finds no row and returns nil, so the answer is dropped+-- with no counter and no log line of its own. Deleting it is still right — the+-- address on it is the old bot's userid and unreachable either way — but+-- whoever is waiting for that answer deserves one line saying where it went.+-- channel_outbound_message is counted for the same reason and not because it is+-- expected to be non-zero: a dropped queued send is a reply that never arrives,+-- and a count nobody has to read costs nothing next to guessing later.+WITH cleared_chat_sessions AS (+ DELETE FROM channel_chat_session_binding AS binding+ WHERE binding.installation_id = @installation_id+ RETURNING binding.chat_session_id+),+cleared_outbound_cards AS (+ DELETE FROM channel_outbound_card_message AS card+ WHERE card.chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)+ RETURNING card.id+),+cleared_task_deliveries AS (+ DELETE FROM channel_task_delivery AS delivery+ WHERE delivery.installation_id = @installation_id+ RETURNING delivery.task_id+),+cleared_outbound_messages AS (+ DELETE FROM channel_outbound_message AS outbound+ WHERE outbound.installation_id = @installation_id+ RETURNING outbound.channel_message_id+),+cleared_binding_tokens AS (+ DELETE FROM channel_binding_token AS token+ WHERE token.installation_id = @installation_id+ RETURNING token.token_hash+),+cleared_inbound_dedup AS (+ DELETE FROM channel_inbound_message_dedup AS dedup+ WHERE dedup.installation_id = @installation_id+ RETURNING dedup.message_id+),+cleared_user_bindings AS (+ DELETE FROM channel_user_binding AS user_binding+ WHERE user_binding.installation_id = @installation_id+ RETURNING user_binding.id+)+SELECT+ (SELECT count(*) FROM cleared_user_bindings)::bigint AS user_bindings,+ (SELECT count(*) FROM cleared_chat_sessions)::bigint AS chat_session_bindings,+ (SELECT count(*) FROM cleared_task_deliveries)::bigint AS task_deliveries,+ (SELECT count(*) FROM cleared_outbound_messages)::bigint AS outbound_messages;+-- name: DeleteChannelInstallationsBySystemRuntimeAgents :exec-- Application-layer replacement for the (deliberately absent, MUL-3515 §4)-- workspace/agent ON DELETE CASCADE: on runtime teardown, before the system