Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6788: perf(server): batch claim-path attachment and runtime lookups (#7696)
importcpp261522e3e3d7
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 62c0385e65..56c275691b 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -1001,6 +1001,10 @@ func (h *Handler) loadAgentRuntimeAvailability(ctx context.Context, agents []db.return result, nil}+ // Read directly rather than through RuntimeLookup: this resolves rows for a+ // list of agents instead of resolving a runtime a caller asked for, so it+ // has no honest source label on multica_agent_runtime_lookup_total yet. See+ // the exception noted on service.RuntimeLookup (MUL-6884).runtimes, err := h.Queries.GetAgentRuntimes(ctx, runtimeIDs)if err != nil {return nil, errdiff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 55fb4a9b18..541dc430dc 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -948,11 +948,30 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {// Track affected workspaces for WS notifications.affectedWorkspaces := make(map[string]bool)+ // Batch the runtime lookups instead of one GetAgentRuntime per id (N+1),+ // while keeping the MUL-6884 per-source attribution: getAgentRuntimes+ // records one multica_agent_runtime_lookup_total result per requested id.+ // A read error is NOT "the rows don't exist": fail closed with 500 (like+ // ListRuntimesForClaim) so a transient blip can't report a successful+ // deregister while every runtime silently stays online until the liveness+ // sweep reaps it. GetMany keys rows by canonical UUID string so a+ // differently-cased request id still matches; a genuinely missing id is+ // simply absent from the map and falls through to the "runtime not found"+ // skip below, preserving the per-runtime verify / setOffline semantics.+ runtimesByID, err := h.getAgentRuntimes(r.Context(), obsmetrics.RuntimeLookupSourceDaemonAPI, runtimeUUIDs)+ if err != nil {+ slog.Error("deregister: batch runtime lookup failed", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to load runtimes")+ return+ }+for i, rid := range req.RuntimeIDs {- // Look up the runtime and verify ownership.- rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceDaemonAPI, runtimeUUIDs[i])- if err != nil {- slog.Warn("deregister: runtime not found", "runtime_id", rid, "error", err)+ // Look up the runtime and verify ownership. Key by the parsed UUID's+ // canonical form (runtimeUUIDs[i]) so a differently-cased request id+ // still matches the row; rid is kept for OfflineReasons and logging.+ rt, ok := runtimesByID[uuidToString(runtimeUUIDs[i])]+ if !ok {+ slog.Warn("deregister: runtime not found", "runtime_id", rid)continue}@@ -1731,14 +1750,37 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {// Resolve all requested runtimes in one query (instead of a point lookup// per runtime), then authorize each; skip (don't fail) unknown/unauthorized// ids so a single stale runtime can't sink the whole batch.- runtimes, err := h.Queries.GetAgentRuntimes(r.Context(), ids)+ //+ // This read goes through RuntimeLookup like every other agent_runtime read+ // by id (MUL-6884), so the claim path is attributed on+ // multica_agent_runtime_lookup_total instead of being invisible on it. That+ // matters more here than on any other caller: both /tasks/claim and /claim+ // route to this handler and the WebSocket claim RPC replays through it, so+ // an unattributed read here would make the busiest reader in the system+ // look idle next to once-per-shutdown deregisters.+ foundByID, err := h.getAgentRuntimes(r.Context(), obsmetrics.RuntimeLookupSourceDaemonAPI, ids)if err != nil {writeError(w, http.StatusInternalServerError, "failed to load runtimes")return}- runtimeByID := make(map[string]db.AgentRuntime, len(runtimes))- authorized := make([]pgtype.UUID, 0, len(runtimes))- for _, rt := range runtimes {+ // Iterate ids rather than ranging the returned map: authorized[] is passed+ // to ClaimTasksForRuntimes, where maxTasks can cut the set off partway, so+ // map iteration order would decide which runtimes get the remaining slots.+ // (ids is itself built from a map above, so this pins the order to one+ // source rather than making it fully deterministic — worth tightening, but+ // not in this change.)+ //+ // runtimeByID must end up holding ONLY authorized rows: the post-claim loop+ // below treats a miss in it as a stray cross-daemon claim and drops the+ // task. GetMany returns every row it found, so the authorized subset is+ // collected separately rather than reusing its map.+ runtimeByID := make(map[string]db.AgentRuntime, len(foundByID))+ authorized := make([]pgtype.UUID, 0, len(foundByID))+ for _, id := range ids {+ rt, ok := foundByID[uuidToString(id)]+ if !ok {+ continue+ }if !h.verifyDaemonWorkspaceAccess(r, uuidToString(rt.WorkspaceID)) {continue}@@ -2903,21 +2945,54 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu}parts := make([]string, 0, len(unanswered))+ // Batch attachment lookups instead of one query per unanswered message+ // (N+1). The batch orders globally by created_at, so grouping by+ // chat_message_id keeps each message's attachments in created_at order,+ // and iterating unanswered below in its original order reproduces the+ // exact append order of the previous per-message loop.+ messageIDs := make([]pgtype.UUID, 0, len(unanswered))+ for _, m := range unanswered {+ messageIDs = append(messageIDs, m.ID)+ }+ attsByMessage := make(map[string][]db.Attachment, len(unanswered))+ if len(messageIDs) > 0 {+ atts, attErr := h.Queries.ListAttachmentsByChatMessageIDs(r.Context(), db.ListAttachmentsByChatMessageIDsParams{+ Column1: messageIDs,+ WorkspaceID: parseUUID(resp.WorkspaceID),+ })+ // A read failure must NOT masquerade as "no attachments". Attachment+ // IDs are the agent's only handle for downloading user files, and+ // batching widened the blast radius from one message's attachments to+ // the whole turn's. Fail closed exactly like the chat-input load above+ // (MUL-6788 review): preserve the just-dispatched task so the+ // stale-dispatched reclaim redelivers it, rather than starting the run+ // with files silently missing.+ if attErr != nil {+ slog.Error("chat claim: load chat attachments failed; preserving task for redelivery",+ "task_id", uuidToString(task.ID),+ "chat_session_id", uuidToString(cs.ID),+ "error", attErr)+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{+ outcome: "error_chat_attachment_load",+ status: http.StatusInternalServerError,+ message: "failed to load chat attachments",+ }+ }+ for _, a := range atts {+ mid := uuidToString(a.ChatMessageID)+ attsByMessage[mid] = append(attsByMessage[mid], a)+ }+ }for _, m := range unanswered {if strings.TrimSpace(m.Content) != "" {parts = append(parts, m.Content)}- if atts, attErr := h.Queries.ListAttachmentsByChatMessage(r.Context(), db.ListAttachmentsByChatMessageParams{- ChatMessageID: m.ID,- WorkspaceID: parseUUID(resp.WorkspaceID),- }); attErr == nil && len(atts) > 0 {- for _, a := range atts {- resp.ChatMessageAttachments = append(resp.ChatMessageAttachments, ChatAttachmentMeta{- ID: uuidToString(a.ID),- Filename: a.Filename,- ContentType: a.ContentType,- })- }+ for _, a := range attsByMessage[uuidToString(m.ID)] {+ resp.ChatMessageAttachments = append(resp.ChatMessageAttachments, ChatAttachmentMeta{+ ID: uuidToString(a.ID),+ Filename: a.Filename,+ ContentType: a.ContentType,+ })}}resp.ChatMessage = strings.Join(parts, "\n\n")diff --git a/server/internal/handler/daemon_claim_attachment_batch_test.go b/server/internal/handler/daemon_claim_attachment_batch_test.gonew file mode 100644index 0000000000..9b8d5bb206--- /dev/null+++ b/server/internal/handler/daemon_claim_attachment_batch_test.go@@ -0,0 +1,199 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// The MUL-6788 batch rewrite replaced the per-message ListAttachmentsByChatMessage+// loop in buildClaimedTaskResponse with one ListAttachmentsByChatMessageIDs read.+// These tests pin the two behaviours the review called out: the grouped output+// must reproduce the previous append order (messages in their own order, each+// message's attachments in created_at order), and a FAILED batch read must fail+// closed — the agent's only handle for user files is the attachment ID, so a+// swallowed error would silently start the run with files missing and no+// redelivery.++// claimAttachmentsResponse decodes just the attachment slice off a claim.+type claimAttachmentsResponse struct {+ Task *struct {+ ChatMessage string `json:"chat_message"`+ ChatMessageAttachments []struct {+ ID string `json:"id"`+ Filename string `json:"filename"`+ } `json:"chat_message_attachments"`+ } `json:"task"`+}++// seedLegacyChatUserMessage inserts a user message on a legacy (NULL+// chat_input_task_id) chat task with an explicit created_at so message order is+// deterministic, and returns its id.+func seedLegacyChatUserMessage(t *testing.T, sessionID, content, createdAt string) string {+ t.Helper()+ return dbfx.Insert(t, "chat_message", testutil.Cols{+ "chat_session_id": sessionID,+ "role": "user",+ "content": content,+ "created_at": createdAt,+ })+}++// seedMessageAttachment binds an attachment to a chat message with an explicit+// created_at, so a test can interleave two messages' attachment timestamps and+// prove the per-message grouping keeps each message's attachments in+// created_at order regardless of the global batch ordering.+func seedMessageAttachment(t *testing.T, sessionID, messageID, filename, createdAt string) string {+ t.Helper()+ return dbfx.Insert(t, "attachment", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "chat_session_id": sessionID,+ "chat_message_id": messageID,+ "uploader_type": "member",+ "uploader_id": testUserID,+ "filename": filename,+ "url": "https://cdn.example/" + filename,+ "content_type": "image/png",+ "size_bytes": 10,+ "created_at": createdAt,+ })+}++// claimForRuntimeExpecting drives the single-runtime claim through handler h and+// returns the response recorder wrapper asserting the wanted status.+func claimForRuntimeExpecting(t *testing.T, h *Handler, runtimeID, daemonID string, want int) *testutil.Response {+ t.Helper()+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, daemonID)+ req = withURLParam(req, "runtimeId", runtimeID)+ return testutil.Call(t, h.ClaimTaskByRuntime, req).Want(want)+}++// TestClaimChatAttachmentsPreserveMessageThenCreatedAtOrder seeds two unanswered+// messages whose attachment created_at values interleave globally, then claims+// and asserts the response lists attachments in message order first and, within+// a message, in created_at order — the exact append order the per-message loop+// produced before batching.+func TestClaimChatAttachmentsPreserveMessageThenCreatedAtOrder(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, sessionID, runtimeID, daemonID := setupDirectChatSession(t, ctx, "attachment order chat")++ // Two user messages, m1 before m2. Attachment timestamps interleave across+ // messages (m1.a=00:01, m2.a=00:02, m1.b=00:03, m2.b=00:04) so a naive+ // "global created_at" flatten would produce m1a,m2a,m1b,m2b — the grouping+ // must instead yield m1a,m1b,m2a,m2b.+ m1 := seedLegacyChatUserMessage(t, sessionID, "first", "2020-01-01T00:00:01Z")+ m2 := seedLegacyChatUserMessage(t, sessionID, "second", "2020-01-01T00:00:05Z")+ m1a := seedMessageAttachment(t, sessionID, m1, "m1a.png", "2020-01-01T00:00:01Z")+ m2a := seedMessageAttachment(t, sessionID, m2, "m2a.png", "2020-01-01T00:00:02Z")+ m1b := seedMessageAttachment(t, sessionID, m1, "m1b.png", "2020-01-01T00:00:03Z")+ m2b := seedMessageAttachment(t, sessionID, m2, "m2b.png", "2020-01-01T00:00:04Z")++ // A legacy (NULL chat_input_task_id) queued chat task for this session.+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": sessionID,+ "status": "queued",+ })++ var resp claimAttachmentsResponse+ claimForRuntimeExpecting(t, testHandler, runtimeID, daemonID, http.StatusOK).JSON(&resp)+ if resp.Task == nil {+ t.Fatal("expected a claimed task")+ }++ gotIDs := make([]string, 0, len(resp.Task.ChatMessageAttachments))+ for _, a := range resp.Task.ChatMessageAttachments {+ gotIDs = append(gotIDs, a.ID)+ }+ want := []string{m1a, m1b, m2a, m2b}+ if strings.Join(gotIDs, ",") != strings.Join(want, ",") {+ t.Errorf("attachment order = %v, want %v (message order, then per-message created_at)", gotIDs, want)+ }+}++// chatAttachmentBatchFailDBTX passes every statement through to the real pool+// EXCEPT the batched chat-message attachment read, which it fails.+type chatAttachmentBatchFailDBTX struct{ inner db.DBTX }++func (f chatAttachmentBatchFailDBTX) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {+ return f.inner.Exec(ctx, sql, args...)+}++func (f chatAttachmentBatchFailDBTX) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ if strings.Contains(sql, "FROM attachment") && strings.Contains(sql, "chat_message_id = ANY(") {+ return nil, errInjectedChatAttachmentRead+ }+ return f.inner.Query(ctx, sql, args...)+}++func (f chatAttachmentBatchFailDBTX) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ return f.inner.QueryRow(ctx, sql, args...)+}++var errInjectedChatAttachmentRead = errors.New("injected chat attachment batch read failure")++func newChatAttachmentReadFailureHandler(t *testing.T) *Handler {+ t.Helper()+ return New(+ db.New(chatAttachmentBatchFailDBTX{inner: testPool}),+ testPool,+ testHandler.Hub,+ testHandler.Bus,+ testHandler.EmailService,+ nil,+ nil,+ analytics.NoopClient{},+ Config{},+ )+}++// TestClaimChatAttachmentBatchReadErrorFailsClosed pins the core review fix on+// the claim path: a failed attachment batch read must reject the claim with 500+// and leave the task eligible for the stale-dispatched reclaim. The claim UPDATE+// moves the task to 'dispatched' with started_at still NULL; the failure branch+// must leave it exactly there (not cancelled, not started) so reclaim can+// redeliver it once the recovery window lapses.+func TestClaimChatAttachmentBatchReadErrorFailsClosed(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, sessionID, runtimeID, daemonID := setupDirectChatSession(t, ctx, "attachment error chat")++ m1 := seedLegacyChatUserMessage(t, sessionID, "with a file", "2020-01-01T00:00:01Z")+ seedMessageAttachment(t, sessionID, m1, "doc.png", "2020-01-01T00:00:01Z")++ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": sessionID,+ "status": "queued",+ })++ h := newChatAttachmentReadFailureHandler(t)+ claimForRuntimeExpecting(t, h, runtimeID, daemonID, http.StatusInternalServerError)++ // The task must be parked exactly at the claim's dispatched state so the+ // stale-dispatched reclaim can redeliver it — not cancelled, and not moved+ // on to started/running.+ var status string+ var startedAt *string+ dbfx.QueryRow(t, `SELECT status, started_at::text FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status, &startedAt)+ if status != "dispatched" {+ t.Errorf("task status = %q, want dispatched (parked for stale-dispatched reclaim)", status)+ }+ if startedAt != nil {+ t.Errorf("task started_at = %v, want NULL (the failed claim must not have started the run)", *startedAt)+ }+}diff --git a/server/internal/handler/daemon_deregister_batch_test.go b/server/internal/handler/daemon_deregister_batch_test.gonew file mode 100644index 0000000000..36961ebe42--- /dev/null+++ b/server/internal/handler/daemon_deregister_batch_test.go@@ -0,0 +1,123 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// The MUL-6788 batch rewrite collapsed the per-runtime GetAgentRuntime loop in+// DaemonDeregister into one GetAgentRuntimes read. These tests pin the two+// behaviours the review called out: the success path still processes existing+// ids and skips missing ones — resolving a differently-cased id to its row via+// the canonical-UUID map key — and a FAILED batch read must fail closed with+// 500 instead of reporting a successful deregister while every runtime silently+// stays online.++var errInjectedRuntimeBatchRead = errors.New("injected runtime batch read failure")++// runtimeBatchFailDBTX passes every statement through to the real pool EXCEPT+// the batched GetAgentRuntimes read, which it fails.+type runtimeBatchFailDBTX struct{ inner db.DBTX }++func (f runtimeBatchFailDBTX) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {+ return f.inner.Exec(ctx, sql, args...)+}++func (f runtimeBatchFailDBTX) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ if strings.Contains(sql, "FROM agent_runtime") && strings.Contains(sql, "= ANY(") {+ return nil, errInjectedRuntimeBatchRead+ }+ return f.inner.Query(ctx, sql, args...)+}++func (f runtimeBatchFailDBTX) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ return f.inner.QueryRow(ctx, sql, args...)+}++// newRuntimeBatchReadFailureHandler is testHandler with the batched runtime+// read broken. It shares the same pool, hub and bus so everything else behaves+// normally.+func newRuntimeBatchReadFailureHandler(t *testing.T) *Handler {+ t.Helper()+ return New(+ db.New(runtimeBatchFailDBTX{inner: testPool}),+ testPool,+ testHandler.Hub,+ testHandler.Bus,+ testHandler.EmailService,+ nil,+ nil,+ analytics.NoopClient{},+ Config{},+ )+}++func runtimeStatus(t *testing.T, runtimeID string) string {+ t.Helper()+ var status string+ dbfx.QueryRow(t, `SELECT status FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&status)+ return status+}++// TestDaemonDeregisterMixedRuntimeIDs covers the success path after batching:+// two distinct existing runtimes both go offline — one requested by its own+// (lowercase) id and the other requested ONLY by its upper-cased form, which+// proves the canonical-UUID map keying resolves a differently-cased id — while+// a well-formed but never-registered id is skipped. Using two separate+// runtimes (rather than one id in two cases) is deliberate: if the uppercase+// form wrongly fell through to "not found", a single-runtime test would still+// pass because the lowercase form already flipped that row offline.+func TestDaemonDeregisterMixedRuntimeIDs(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ lower := dbfx.Runtime(t, "deregister mixed lower", testutil.Cols{"status": "online"})+ upperOnly := dbfx.Runtime(t, "deregister mixed upper", testutil.Cols{"status": "online"})+ // A well-formed UUID that is not in the table.+ missing := "00000000-0000-0000-0000-0000000009ff"++ req := newRequest("POST", "/api/daemon/deregister", map[string]any{+ "runtime_ids": []string{lower, missing, strings.ToUpper(upperOnly)},+ })+ testutil.Call(t, testHandler.DaemonDeregister, req).Want(http.StatusOK)++ if got := runtimeStatus(t, lower); got != "offline" {+ t.Errorf("lowercase-requested runtime status = %q, want offline", got)+ }+ if got := runtimeStatus(t, upperOnly); got != "offline" {+ t.Errorf("uppercase-only-requested runtime status = %q, want offline (canonical UUID map key must resolve it)", got)+ }+}++// TestDaemonDeregisterBatchReadErrorFailsClosed pins the core review fix: when+// the batch runtime lookup fails, the handler must return 500 and leave the+// runtime online — not swallow the error, skip every id, and report 200 ok+// while the runtime keeps attracting claims until the liveness sweep reaps it.+func TestDaemonDeregisterBatchReadErrorFailsClosed(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ h := newRuntimeBatchReadFailureHandler(t)++ online := dbfx.Runtime(t, "deregister batch-error online", testutil.Cols{"status": "online"})++ req := newRequest("POST", "/api/daemon/deregister", map[string]any{+ "runtime_ids": []string{online},+ })+ testutil.Call(t, h.DaemonDeregister, req).Want(http.StatusInternalServerError)++ if got := runtimeStatus(t, online); got != "online" {+ t.Errorf("runtime status = %q, want online (deregister must not have taken effect)", got)+ }+}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 8d97111bd4..e9aba7716f 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -641,6 +641,14 @@ func (h *Handler) getAgentRuntime(ctx context.Context, source string, id pgtype.return h.runtimeLookup(source).Get(ctx, id)}+// getAgentRuntimes is the batch sibling of getAgentRuntime: one query for many+// ids, attributed to source the same way (MUL-6788). It returns the rows keyed+// by canonical UUID string and surfaces the read error so batch callers fail+// closed instead of treating a failed read as "no rows exist".+func (h *Handler) getAgentRuntimes(ctx context.Context, source string, ids []pgtype.UUID) (map[string]db.AgentRuntime, error) {+ return h.runtimeLookup(source).GetMany(ctx, ids)+}+// runtimeLookup is the same reader, unexecuted, for handlers that hand it to a// shared readiness helper instead of reading the row themselves.func (h *Handler) runtimeLookup(source string) service.RuntimeLookup {diff --git a/server/internal/handler/runtime_lookup_metrics_test.go b/server/internal/handler/runtime_lookup_metrics_test.goindex 3bb3a73ad9..b63132c6ec 100644--- a/server/internal/handler/runtime_lookup_metrics_test.go+++ b/server/internal/handler/runtime_lookup_metrics_test.go@@ -88,6 +88,59 @@ func TestAgentRuntimeLookupWSHotPathIsZeroRead(t *testing.T) {}}+// TestAgentRuntimeLookupBatchClaimIsAttributed pins the MUL-6788 review fix at+// the handler level: the batch claim endpoint must report its runtime reads on+// multica_agent_runtime_lookup_total like every other reader.+//+// This is the counter's most load-bearing series, not a completeness exercise.+// Both /tasks/claim and /claim route here (router.go) and the WebSocket claim+// RPC replays through the same handler, so a claim path that reads the rows+// straight off h.Queries contributes nothing while once-per-shutdown+// deregisters contribute steadily — making the busiest reader in the system+// read as idle when the sources are compared, which is the exact inversion the+// source label was added to prevent.+//+// One request mixes an existing runtime with a well-formed but unregistered id+// so both classifications are covered, and asserts the batch bills exactly one+// result per requested id rather than one per SQL query.+func TestAgentRuntimeLookupBatchClaimIsAttributed(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ m := withTestMetrics(t)+ runtimeID := dbfx.Runtime(t, "Batch claim lookup attribution", testutil.Cols{+ "daemon_id": batchClaimTestDaemonID,+ "device_info": "batch claim lookup attribution",+ })+ missing := uuid.NewString()++ before := lookupSnapshot(t, m)++ // max_tasks=0 returns before the runtime read, so claim a real slot.+ testutil.Call(t, testHandler.ClaimTasksByRuntime,+ batchClaimRequest(testWorkspaceID, []string{runtimeID, missing}, 1, "")).Want(http.StatusOK)++ after := lookupSnapshot(t, m)+ for _, want := range []struct {+ source, result string+ delta float64+ }{+ {obsmetrics.RuntimeLookupSourceDaemonAPI, obsmetrics.RuntimeLookupResultOK, 1},+ {obsmetrics.RuntimeLookupSourceDaemonAPI, obsmetrics.RuntimeLookupResultNotFound, 1},+ // A successful batch read is not an error for the ids that missed.+ {obsmetrics.RuntimeLookupSourceDaemonAPI, obsmetrics.RuntimeLookupResultError, 0},+ // The claim must not land on the bucket for unclassified call sites.+ {obsmetrics.RuntimeLookupSourceOther, obsmetrics.RuntimeLookupResultOK, 0},+ {obsmetrics.RuntimeLookupSourceOther, obsmetrics.RuntimeLookupResultNotFound, 0},+ } {+ key := want.source + "/" + want.result+ if got := after[key] - before[key]; got != want.delta {+ t.Errorf("%s delta = %v, want %v", key, got, want.delta)+ }+ }+}+// ---- helpers --------------------------------------------------------------// withTestMetrics installs a fresh collector on the shared test handler for thediff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 2256e79c72..8b47585cb1 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -71,10 +71,14 @@ type BusinessMetrics struct {entitlementVersionRegression prometheus.CounterautopilotQuotaDecision *prometheus.CounterVec- // agentRuntimeLookup counts single-row agent_runtime reads by product- // source. Every source shares one SQL fingerprint, so this is the only- // place the split between daemon heartbeats, browser polling, and- // readiness gates is observable. See labels.go for the closed enum.+ // agentRuntimeLookup counts logical agent_runtime lookups by product+ // source — one increment per requested runtime id, whether that id was+ // resolved by its own point read or as one element of a batch query, so+ // the counter is a lookup rate and NOT a database-query QPS. Point reads+ // share one SQL fingerprint and batch reads use another; this counter adds+ // the product-source attribution that neither query shape exposes on its+ // own, including daemon heartbeats, browser polling, and readiness gates.+ // See labels.go for the closed enum.agentRuntimeLookup *prometheus.CounterVecactiveMu sync.Mutex@@ -281,7 +285,7 @@ func NewBusinessMetrics() *BusinessMetrics {}, metricLabels("multica_autopilot_quota_decision_total")),agentRuntimeLookup: prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "multica", Subsystem: "agent_runtime", Name: "lookup_total",- Help: "Total single-row agent_runtime reads by product source and outcome.",+ Help: "Total logical agent_runtime lookups by product source and outcome (one per requested id, not per SQL query).",}, metricLabels("multica_agent_runtime_lookup_total")),activeTasks: map[string]activeTaskLabels{},events: newBusinessEventMetrics(),@@ -367,7 +371,10 @@ func (m *BusinessMetrics) RecordEntitlementDecision(gate, action, reason string)}}-// RecordAgentRuntimeLookup counts one single-row agent_runtime read.+// RecordAgentRuntimeLookup counts one logical agent_runtime lookup — one+// requested runtime id resolved, whether by a point read or as one element of+// a batch query. It is therefore a lookup rate, not a SQL-query count: a single+// batch read that resolves N ids increments this N times.//// Call it from service.RuntimeLookup and nowhere else: the point of the metric// is that every read is attributed, and a second entry point is how a call sitediff --git a/server/internal/service/agent_runtime_lookup.go b/server/internal/service/agent_runtime_lookup.goindex 0a3140f948..40e9cfd2f7 100644--- a/server/internal/service/agent_runtime_lookup.go+++ b/server/internal/service/agent_runtime_lookup.go@@ -8,19 +8,30 @@ import ("github.com/jackc/pgx/v5/pgtype"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")-// RuntimeLookup is the only way production code reads a single agent_runtime-// row by id (MUL-6884).+// RuntimeLookup is how production code reads agent_runtime rows by id+// (MUL-6884) — one row via Get, or many in one query via GetMany. Every read+// that resolves a runtime for a product behaviour goes through it, so+// multica_agent_runtime_lookup_total can attribute that behaviour.//-// The query itself is a primary-key point read and has never been the problem.-// What is missing is attribution: daemon heartbeats, browser polling loops, and-// a dozen readiness gates all issue the same statement, so pg_stat_statements-// can report that agent_runtime is one of the busiest reads in the system while-// saying nothing about which product behaviour is driving it. Routing every-// read through one type, carrying the source with it, is what makes that-// question answerable before anyone starts changing heartbeat intervals.+// One reader is deliberately outside it: the agent-list presence projection+// (handler.loadAgentRuntimeAvailability) batch-reads runtime rows to derive a+// coarse liveness bucket for agents whose runtime the viewer may not see. It+// resolves rows for agents rather than resolving a runtime a caller asked for,+// and it is unclassified rather than counted as some existing source, because+// folding it into one would make that source's rate stop meaning what its name+// says. Classifying it is worth doing; it needs its own source constant and is+// not part of MUL-6788.+//+// Point-read callers share one SQL fingerprint, while GetMany uses a separate+// batch-query fingerprint. pg_stat_statements can show that either query is+// busy, but not whether daemon heartbeats, browser polling loops, or readiness+// gates are driving it. Routing both query shapes through one type, carrying+// the source with each lookup, makes that question answerable before anyone+// starts changing heartbeat intervals.//// Source is a closed enum from the metrics package (obsmetrics.RuntimeLookupSource*).// Metrics may be nil — tests and self-hosted deployments without the metrics@@ -46,6 +57,39 @@ func (l RuntimeLookup) Get(ctx context.Context, id pgtype.UUID) (db.AgentRuntimereturn rt, err}+// GetMany reads the requested agent_runtime rows in one query and keeps the+// per-source attribution GetAgentRuntime callers get, without issuing N point+// reads (MUL-6788). It returns the rows keyed by their canonical UUID string+// so a differently-cased request id still resolves.+//+// Metric accounting mirrors N individual Get calls: a batch read error counts+// one "error" per requested id (the whole lookup failed for each), and on+// success each id is counted "ok" when its row came back and "not_found" when+// it did not — so multica_agent_runtime_lookup_total keeps the same shape it+// had before batching. The read error is returned untouched so callers can fail+// closed instead of treating a hiccup as "every runtime is gone".+func (l RuntimeLookup) GetMany(ctx context.Context, ids []pgtype.UUID) (map[string]db.AgentRuntime, error) {+ rows, err := l.Queries.GetAgentRuntimes(ctx, ids)+ if err != nil {+ for range ids {+ l.Metrics.RecordAgentRuntimeLookup(l.Source, obsmetrics.RuntimeLookupResultError)+ }+ return nil, err+ }+ byID := make(map[string]db.AgentRuntime, len(rows))+ for _, rt := range rows {+ byID[util.UUIDToString(rt.ID)] = rt+ }+ for _, id := range ids {+ if _, ok := byID[util.UUIDToString(id)]; ok {+ l.Metrics.RecordAgentRuntimeLookup(l.Source, obsmetrics.RuntimeLookupResultOK)+ } else {+ l.Metrics.RecordAgentRuntimeLookup(l.Source, obsmetrics.RuntimeLookupResultNotFound)+ }+ }+ return byID, nil+}+func runtimeLookupResult(err error) string {switch {case err == nil:diff --git a/server/internal/service/agent_runtime_lookup_test.go b/server/internal/service/agent_runtime_lookup_test.goindex cf6d98bf46..3cd6f5e667 100644--- a/server/internal/service/agent_runtime_lookup_test.go+++ b/server/internal/service/agent_runtime_lookup_test.go@@ -11,6 +11,7 @@ import (dto "github.com/prometheus/client_model/go"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -65,6 +66,87 @@ func TestRuntimeLookupNilMetricsIsSafe(t *testing.T) {}}+// TestRuntimeLookupGetManyFailsClosed pins the contract MUL-6788's review added:+// a failed batch read is returned as an error, not swallowed into an empty map+// that a caller could mistake for "none of these runtimes exist". The metric+// also stays honest — one "error" per requested id, matching what N individual+// Get calls would have recorded.+func TestRuntimeLookupGetManyFailsClosed(t *testing.T) {+ t.Parallel()++ dbErr := errors.New("connection reset")+ m := obsmetrics.NewBusinessMetrics()+ lookup := RuntimeLookup{+ Queries: db.New(scanErrDBTX{err: dbErr}),+ Metrics: m,+ Source: obsmetrics.RuntimeLookupSourceDaemonAPI,+ }++ ids := []pgtype.UUID{{}, {}, {}}+ got, err := lookup.GetMany(context.Background(), ids)+ if !errors.Is(err, dbErr) {+ t.Fatalf("GetMany error = %v, want %v", err, dbErr)+ }+ if got != nil {+ t.Errorf("GetMany map = %v, want nil on error", got)+ }+ if n := lookupCount(t, m, obsmetrics.RuntimeLookupSourceDaemonAPI, obsmetrics.RuntimeLookupResultError); n != float64(len(ids)) {+ t.Errorf("daemon_api/error = %v, want %d", n, len(ids))+ }+}++// TestRuntimeLookupGetManyNilMetricsIsSafe mirrors the single-read nil-metrics+// guard for the batch path.+func TestRuntimeLookupGetManyNilMetricsIsSafe(t *testing.T) {+ t.Parallel()++ lookup := RuntimeLookup{Queries: db.New(scanErrDBTX{err: errors.New("db down")}), Source: obsmetrics.RuntimeLookupSourceDaemonAPI}+ if _, err := lookup.GetMany(context.Background(), []pgtype.UUID{{}}); err == nil {+ t.Fatal("GetMany error = nil, want the injected read failure")+ }+}++// TestRuntimeLookupGetManySuccessClassifiesEachID is the important success-path+// case: the batch runs one SQL query but the metric must still record one+// logical lookup per REQUESTED id — ok for an id whose row came back,+// not_found for one that did not, and a repeated id counted once per+// occurrence (the same shape N individual Get calls would have produced). The+// returned map is keyed by canonical UUID string so a requested id resolves+// regardless of case.+func TestRuntimeLookupGetManySuccessClassifiesEachID(t *testing.T) {+ t.Parallel()++ found := mustUUID(t, "11111111-1111-1111-1111-111111111111")+ missing := mustUUID(t, "22222222-2222-2222-2222-222222222222")++ m := obsmetrics.NewBusinessMetrics()+ lookup := RuntimeLookup{+ // The query returns only the found row; missing is absent.+ Queries: db.New(runtimeRowsDBTX{rows: []db.AgentRuntime{{ID: found}}}),+ Metrics: m,+ Source: obsmetrics.RuntimeLookupSourceDaemonAPI,+ }++ // Request found twice (duplicate) plus the missing id.+ ids := []pgtype.UUID{found, missing, found}+ got, err := lookup.GetMany(context.Background(), ids)+ if err != nil {+ t.Fatalf("GetMany error = %v, want nil", err)+ }+ if _, ok := got[util.UUIDToString(found)]; !ok {+ t.Errorf("found id missing from result map %v", got)+ }+ if _, ok := got[util.UUIDToString(missing)]; ok {+ t.Errorf("missing id must not be in result map %v", got)+ }+ if n := lookupCount(t, m, obsmetrics.RuntimeLookupSourceDaemonAPI, obsmetrics.RuntimeLookupResultOK); n != 2 {+ t.Errorf("daemon_api/ok = %v, want 2 (found requested twice)", n)+ }+ if n := lookupCount(t, m, obsmetrics.RuntimeLookupSourceDaemonAPI, obsmetrics.RuntimeLookupResultNotFound); n != 1 {+ t.Errorf("daemon_api/not_found = %v, want 1", n)+ }+}+// ---- helpers --------------------------------------------------------------func lookupCount(t *testing.T, m *obsmetrics.BusinessMetrics, source, result string) float64 {@@ -109,3 +191,65 @@ func (d scanErrDBTX) QueryRow(context.Context, string, ...interface{}) pgx.Row {type errRow struct{ err error }func (r errRow) Scan(...any) error { return r.err }++func mustUUID(t *testing.T, s string) pgtype.UUID {+ t.Helper()+ u, err := util.ParseUUID(s)+ if err != nil {+ t.Fatalf("parse uuid %q: %v", s, err)+ }+ return u+}++// runtimeRowsDBTX is a db.DBTX whose Query returns a fixed set of AgentRuntime+// rows, so GetMany's success branch (per-id ok/not_found classification) is+// testable without a database. Only the columns GetAgentRuntimes scans are+// served; GetMany only keys on ID, so unset columns stay zero-valued.+type runtimeRowsDBTX struct{ rows []db.AgentRuntime }++func (d runtimeRowsDBTX) Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) {+ return pgconn.CommandTag{}, nil+}++func (d runtimeRowsDBTX) Query(context.Context, string, ...interface{}) (pgx.Rows, error) {+ return &runtimeRows{rows: d.rows}, nil+}++func (d runtimeRowsDBTX) QueryRow(context.Context, string, ...interface{}) pgx.Row {+ return errRow{err: pgx.ErrNoRows}+}++// runtimeRows is a minimal pgx.Rows over a slice of AgentRuntime. Scan writes+// each row's fields positionally into the destinations GetAgentRuntimes passes.+type runtimeRows struct {+ rows []db.AgentRuntime+ i int+}++func (r *runtimeRows) Close() {}+func (r *runtimeRows) Err() error { return nil }+func (r *runtimeRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} }+func (r *runtimeRows) FieldDescriptions() []pgconn.FieldDescription { return nil }+func (r *runtimeRows) Values() ([]any, error) { return nil, nil }+func (r *runtimeRows) RawValues() [][]byte { return nil }+func (r *runtimeRows) Conn() *pgx.Conn { return nil }++func (r *runtimeRows) Next() bool {+ if r.i >= len(r.rows) {+ return false+ }+ r.i+++ return true+}++// Scan copies the current row's ID into the first destination — the only field+// GetMany reads — and leaves the rest untouched.+func (r *runtimeRows) Scan(dest ...any) error {+ row := r.rows[r.i-1]+ if len(dest) > 0 {+ if p, ok := dest[0].(*pgtype.UUID); ok {+ *p = row.ID+ }+ }+ return nil+}