Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6884 feat(metrics): attribute agent_runtime lookups by product source (#7822)
Bohan Jiangeddb0dc2ad1e
diff --git a/server/internal/handler/agent_runtime_skills.go b/server/internal/handler/agent_runtime_skills.goindex 06aaa6d767..ef356a264b 100644--- a/server/internal/handler/agent_runtime_skills.go+++ b/server/internal/handler/agent_runtime_skills.go@@ -9,6 +9,7 @@ import ("github.com/go-chi/chi/v5""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -110,7 +111,7 @@ func (h *Handler) SetAgentRuntimeSkillEnabled(w http.ResponseWriter, r *http.ReqwriteError(w, http.StatusConflict, "agent is no longer assigned to this runtime")return}- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeID)+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if err != nil || rt.WorkspaceID != agent.WorkspaceID {writeError(w, http.StatusNotFound, "runtime not found")returndiff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex ef415c5711..d790bcc84e 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -883,7 +883,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {// Shared verdict: an unbound agent and a machine whose CLI cannot run are// both refusals here, with their own codes. A merely offline runtime is not// checked at all — chat messages queue for it, as they always have.- if verdict, err := service.AgentReadiness(r.Context(), h.Queries, agent); err == nil && verdict.Blocked() {+ if verdict, err := service.AgentReadiness(r.Context(), h.runtimeLookup(obsmetrics.RuntimeLookupSourceChat), agent); err == nil && verdict.Blocked() {h.writeDispatchBlocked(w, http.StatusConflict, verdict.Reason)return}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 607665a0fb..35f45bd3bd 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -17,6 +17,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -3135,7 +3136,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issucontinue}// Same shared verdict as the direct-agent branch below.- if verdict, err := service.AgentReadiness(ctx, h.Queries, agent); err == nil && verdict.Blocked() {+ if verdict, err := service.AgentReadiness(ctx, h.runtimeLookup(obsmetrics.RuntimeLookupSourceComment), agent); err == nil && verdict.Blocked() {blockUnusableTarget("squad", m.ID, agent, verdict)continue}@@ -3194,7 +3195,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu// will not start doing so on its own (MUL-6164). A merely offline// runtime keeps queueing — that wait ends by itself when the machine// returns, and taking it away would remove a behaviour people rely on.- if verdict, err := service.AgentReadiness(ctx, h.Queries, agent); err == nil && verdict.Blocked() {+ if verdict, err := service.AgentReadiness(ctx, h.runtimeLookup(obsmetrics.RuntimeLookupSourceComment), agent); err == nil && verdict.Blocked() {blockUnusableTarget("agent", m.ID, agent, verdict)continue}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 5f655111ad..6c3df1603c 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -85,7 +85,7 @@ func (h *Handler) requireDaemonRuntimeAccess(w http.ResponseWriter, r *http.Requif !ok {return db.AgentRuntime{}, false}- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceDaemonAPI, runtimeUUID)if err != nil {if isNotFound(err) {writeError(w, http.StatusNotFound, "runtime not found")@@ -942,7 +942,7 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {for i, rid := range req.RuntimeIDs {// Look up the runtime and verify ownership.- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUIDs[i])+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceDaemonAPI, runtimeUUIDs[i])if err != nil {slog.Warn("deregister: runtime not found", "runtime_id", rid, "error", err)continue@@ -1087,7 +1087,7 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {return}lookupStart := time.Now()- rt, lookupErr := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)+ rt, lookupErr := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceHeartbeatHTTP, runtimeUUID)runtimeLookupMs = time.Since(lookupStart).Milliseconds()if lookupErr != nil {// Only pgx.ErrNoRows means the runtime row is gone. Daemon reads this@@ -1172,7 +1172,7 @@ func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonwsif err != nil {return nil, fmt.Errorf("invalid runtime_id: %w", err)}- rt, err := h.Queries.GetAgentRuntime(ctx, runtimeUUID)+ rt, err := h.getAgentRuntime(ctx, obsmetrics.RuntimeLookupSourceHeartbeatWS, runtimeUUID)if err != nil {if isNotFound(err) {return &protocol.DaemonHeartbeatAckPayload{@@ -4364,7 +4364,7 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {provider := normalizeProvider(u.Provider)if provider == "" {if !runtimeProviderLoaded {- if rt, err := h.Queries.GetAgentRuntime(r.Context(), task.RuntimeID); err == nil {+ if rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceTask, task.RuntimeID); err == nil {runtimeProvider = normalizeProvider(rt.Provider)} else {slog.Warn("load runtime provider for usage backfill failed",diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 164f630034..e6850bea82 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -24,6 +24,7 @@ import ("github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"@@ -2577,7 +2578,7 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {// — but with the verdict's own code, so "CLI cannot run" no longer arrives// as "runtime is offline" and sends the user to reconnect a machine that is// already connected (MUL-6164).- if verdict, err := service.AgentReadiness(r.Context(), h.Queries, agent); err != nil {+ if verdict, err := service.AgentReadiness(r.Context(), h.runtimeLookup(obsmetrics.RuntimeLookupSourceIssue), agent); err != nil {writeError(w, http.StatusInternalServerError, "failed to check agent runtime")return} else if !verdict.Ready() {@@ -2594,13 +2595,13 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {// twenty seconds later. Dev-built// daemons (git-describe shape) are exempted inside CheckMinCLIVersion// so `make daemon` works without weakening staging or production.- if status, payload := h.checkQuickCreateDaemonVersion(r.Context(), agent.RuntimeID); status != 0 {+ if status, payload := h.checkQuickCreateDaemonVersion(r.Context(), obsmetrics.RuntimeLookupSourceIssue, agent.RuntimeID); status != 0 {writeJSON(w, status, payload)return}if priority != "" || dueDate != "" {if status, payload := h.checkQuickCreateDaemonVersionAtLeast(- r.Context(), agent.RuntimeID, agentpkg.MinQuickCreateFieldsCLIVersion,+ r.Context(), obsmetrics.RuntimeLookupSourceIssue, agent.RuntimeID, agentpkg.MinQuickCreateFieldsCLIVersion,); status != 0 {writeJSON(w, status, payload)return@@ -2687,7 +2688,7 @@ func writeAgentUnavailable(w http.ResponseWriter, reason string, reasonCode disp// agent's runtime is offline so the user gets immediate feedback in the// modal instead of an inbox failure twenty seconds later.func (h *Handler) isRuntimeOnline(ctx context.Context, runtimeID pgtype.UUID) bool {- rt, err := h.Queries.GetAgentRuntime(ctx, runtimeID)+ rt, err := h.getAgentRuntime(ctx, obsmetrics.RuntimeLookupSourceIssue, runtimeID)if err != nil {return false}@@ -2708,12 +2709,12 @@ func (h *Handler) isRuntimeOnline(ctx context.Context, runtimeID pgtype.UUID) bo// "min_version": "0.2.21",// "runtime_id": "<uuid>"// }-func (h *Handler) checkQuickCreateDaemonVersion(ctx context.Context, runtimeID pgtype.UUID) (int, map[string]any) {- return h.checkQuickCreateDaemonVersionAtLeast(ctx, runtimeID, agentpkg.MinQuickCreateCLIVersion)+func (h *Handler) checkQuickCreateDaemonVersion(ctx context.Context, source string, runtimeID pgtype.UUID) (int, map[string]any) {+ return h.checkQuickCreateDaemonVersionAtLeast(ctx, source, runtimeID, agentpkg.MinQuickCreateCLIVersion)}-func (h *Handler) checkQuickCreateDaemonVersionAtLeast(ctx context.Context, runtimeID pgtype.UUID, minimum string) (int, map[string]any) {- rt, err := h.Queries.GetAgentRuntime(ctx, runtimeID)+func (h *Handler) checkQuickCreateDaemonVersionAtLeast(ctx context.Context, source string, runtimeID pgtype.UUID, minimum string) (int, map[string]any) {+ rt, err := h.getAgentRuntime(ctx, source, runtimeID)if err != nil {// Runtime row vanished between the online check and here — treat// as unavailable rather than wedging the request on a 500.@@ -3871,7 +3872,7 @@ func (h *Handler) isAgentAssigneeReady(ctx context.Context, issue db.Issue) bool// The shared verdict, not a local re-check (service.AgentReadiness). Only a// BLOCKED verdict stops the enqueue: an offline machine still queues,// because that work runs when the machine comes back.- verdict, err := service.AgentReadiness(ctx, h.Queries, agent)+ verdict, err := service.AgentReadiness(ctx, h.runtimeLookup(obsmetrics.RuntimeLookupSourceIssue), agent)if err != nil || !verdict.Blocked() {return err == nil}diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.goindex af062414c9..6110b70537 100644--- a/server/internal/handler/issue_trigger.go+++ b/server/internal/handler/issue_trigger.go@@ -7,6 +7,7 @@ import ("net/http""github.com/jackc/pgx/v5/pgtype"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"agentver "github.com/multica-ai/multica/server/pkg/agent"@@ -263,7 +264,7 @@ func (h *Handler) runtimeSupportsHandoff(ctx context.Context, agentID pgtype.UUIif err != nil || !agent.RuntimeID.Valid {return false}- rt, err := h.Queries.GetAgentRuntime(ctx, agent.RuntimeID)+ rt, err := h.getAgentRuntime(ctx, obsmetrics.RuntimeLookupSourceIssue, agent.RuntimeID)if err != nil {return false}diff --git a/server/internal/handler/mika_agent.go b/server/internal/handler/mika_agent.goindex d8cb25b3db..623061431d 100644--- a/server/internal/handler/mika_agent.go+++ b/server/internal/handler/mika_agent.go@@ -9,6 +9,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid"@@ -133,7 +134,7 @@ func (h *Handler) resolveMikaAgent(w http.ResponseWriter, r *http.Request, worksif !ok {return db.Agent{}, false, false}- runtime, err := h.Queries.GetAgentRuntime(r.Context(), runtimeID)+ runtime, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if err != nil || uuidToString(runtime.WorkspaceID) != workspaceID {writeError(w, http.StatusBadRequest, "runtime not found in this workspace")return db.Agent{}, false, falsediff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex fb2a7012ef..01e9c8efd4 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -13,6 +13,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent"@@ -109,7 +110,7 @@ type RuntimeUsageResponse struct {// same tool).func (h *Handler) GetRuntimeUsage(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -163,7 +164,7 @@ func (h *Handler) listRuntimeUsage(ctx context.Context, runtimeID pgtype.UUID, t// GetRuntimeTaskActivity returns hourly task activity distribution for a runtime.func (h *Handler) GetRuntimeTaskActivity(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -221,7 +222,7 @@ type RuntimeUsageByAgentResponse struct {// since the cutoff window. Drives the runtime-detail "Cost by agent" tab.func (h *Handler) GetRuntimeUsageByAgent(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -293,7 +294,7 @@ type RuntimeUsageByHourResponse struct {// `?tz=` param or the authenticated user's stored user.timezone.func (h *Handler) GetRuntimeUsageByHour(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -491,7 +492,7 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {return}- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeUUID)if err != nil {writeError(w, http.StatusNotFound, "runtime not found")return@@ -630,18 +631,40 @@ func canEditRuntime(member db.Member, rt db.AgentRuntime) bool {return rt.OwnerID.Valid && uuidToString(rt.OwnerID) == uuidToString(member.UserID)}+// getAgentRuntime reads one agent_runtime row by id and attributes the read to+// source, which labels multica_agent_runtime_lookup_total (MUL-6884). Pick the+// obsmetrics.RuntimeLookupSource* constant that names the product behaviour+// driving the read, not the file the call happens to live in: a poll loop+// counted as generic API traffic is exactly the confusion the metric exists to+// remove.+func (h *Handler) getAgentRuntime(ctx context.Context, source string, id pgtype.UUID) (db.AgentRuntime, error) {+ return h.runtimeLookup(source).Get(ctx, id)+}++// 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 {+ return service.RuntimeLookup{Queries: h.Queries, Metrics: h.Metrics, Source: source}+}+// requireRuntimeReadAccess protects runtime data and machine-triggering// capabilities. Governance access is deliberately separate: workspace owners// and admins may list, rename, or delete another member's private runtime,// but a private machine is readable or usable only by its owner. Returning// 404 for that case prevents a known runtime ID from becoming an oracle.-func (h *Handler) requireRuntimeReadAccess(w http.ResponseWriter, r *http.Request, runtimeID string) (db.AgentRuntime, db.Member, bool) {+//+// source names the product behaviour behind the read for+// multica_agent_runtime_lookup_total (MUL-6884). It matters here more than+// anywhere else: this one gate serves both a rarely-opened usage tab and+// several 500ms browser poll loops, and counting them together would hide the+// polling the metric exists to measure.+func (h *Handler) requireRuntimeReadAccess(w http.ResponseWriter, r *http.Request, source, runtimeID string) (db.AgentRuntime, db.Member, bool) {runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")if !ok {return db.AgentRuntime{}, db.Member{}, false}- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)+ rt, err := h.getAgentRuntime(r.Context(), source, runtimeUUID)if err != nil {writeError(w, http.StatusNotFound, "runtime not found")return db.AgentRuntime{}, db.Member{}, false@@ -808,7 +831,7 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {return}- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeUUID)if err != nil {writeError(w, http.StatusNotFound, "runtime not found")return@@ -1029,7 +1052,7 @@ func (h *Handler) UnbindAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.Rereturn}- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeUUID)if err != nil {writeError(w, http.StatusNotFound, "runtime not found")returndiff --git a/server/internal/handler/runtime_local_skills.go b/server/internal/handler/runtime_local_skills.goindex b32a90859b..b1f88991a5 100644--- a/server/internal/handler/runtime_local_skills.go+++ b/server/internal/handler/runtime_local_skills.go@@ -14,6 +14,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""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""github.com/multica-ai/multica/server/pkg/protocol"@@ -548,8 +549,8 @@ func runtimeLocalSkillRequestTerminal(status RuntimeLocalSkillRequestStatus) boo// machines remain owner-only even for admins; public runtimes are readable by// workspace members. Flows that copy skill files off the owner's machine add// the stricter owner-only check in requireRuntimeLocalSkillAccess.-func (h *Handler) requireRuntimeCapabilityReadAccess(w http.ResponseWriter, r *http.Request, runtimeID string) (runtimeIDAndWorkspace, db.Member, bool) {- rt, member, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+func (h *Handler) requireRuntimeCapabilityReadAccess(w http.ResponseWriter, r *http.Request, source, runtimeID string) (runtimeIDAndWorkspace, db.Member, bool) {+ rt, member, ok := h.requireRuntimeReadAccess(w, r, source, runtimeID)if !ok {return runtimeIDAndWorkspace{}, db.Member{}, false}@@ -568,8 +569,8 @@ func (h *Handler) requireRuntimeCapabilityReadAccess(w http.ResponseWriter, r *h// requireRuntimeLocalSkillAccess additionally requires the caller to own the// runtime. Import reads full skill file contents from the owner's machine, so// it stays owner-only even for workspace owners/admins.-func (h *Handler) requireRuntimeLocalSkillAccess(w http.ResponseWriter, r *http.Request, runtimeID string) (runtimeIDAndWorkspace, bool) {- rt, member, ok := h.requireRuntimeCapabilityReadAccess(w, r, runtimeID)+func (h *Handler) requireRuntimeLocalSkillAccess(w http.ResponseWriter, r *http.Request, source, runtimeID string) (runtimeIDAndWorkspace, bool) {+ rt, member, ok := h.requireRuntimeCapabilityReadAccess(w, r, source, runtimeID)if !ok {return runtimeIDAndWorkspace{}, false}@@ -592,7 +593,7 @@ type runtimeIDAndWorkspace struct {func (h *Handler) InitiateListLocalSkills(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeCapabilityReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeCapabilityReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -612,7 +613,7 @@ func (h *Handler) InitiateListLocalSkills(w http.ResponseWriter, r *http.Requestfunc (h *Handler) GetLocalSkillListRequest(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeCapabilityReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeCapabilityReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeLocalSkillPoll, runtimeID)if !ok {return}@@ -633,7 +634,7 @@ func (h *Handler) GetLocalSkillListRequest(w http.ResponseWriter, r *http.Requesfunc (h *Handler) InitiateImportLocalSkill(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, ok := h.requireRuntimeLocalSkillAccess(w, r, runtimeID)+ rt, ok := h.requireRuntimeLocalSkillAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -697,7 +698,7 @@ func (h *Handler) InitiateImportLocalSkill(w http.ResponseWriter, r *http.Requesfunc (h *Handler) GetLocalSkillImportRequest(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, ok := h.requireRuntimeLocalSkillAccess(w, r, runtimeID)+ rt, ok := h.requireRuntimeLocalSkillAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeLocalSkillImportPoll, runtimeID)if !ok {return}diff --git a/server/internal/handler/runtime_lookup_metrics_test.go b/server/internal/handler/runtime_lookup_metrics_test.gonew file mode 100644index 0000000000..40b6d744a2--- /dev/null+++ b/server/internal/handler/runtime_lookup_metrics_test.go@@ -0,0 +1,121 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/google/uuid"+ dto "github.com/prometheus/client_model/go"++ "github.com/multica-ai/multica/server/internal/daemonws"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// TestAgentRuntimeLookupSourcesAreDistinct drives the three entry points the+// investigation in MUL-6884 could not tell apart — the WebSocket heartbeat, the+// HTTP heartbeat fallback, and a browser poll — and asserts each lands on its+// own source.+//+// This is the whole point of the metric. All three issue the same statement, so+// pg_stat_statements sums them into one row; if they also shared a Prometheus+// label the counter would answer no question the database could not already+// answer, and the follow-up decision (raise the heartbeat interval, or back off+// the 500ms polls) would still be a guess.+func TestAgentRuntimeLookupSourcesAreDistinct(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ m := withTestMetrics(t)+ ctx := context.Background()+ runtimeID := dbfx.Runtime(t, "Lookup source runtime", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "device_info": "lookup source runtime",+ })++ before := lookupSnapshot(t, m)++ if _, err := testHandler.HandleDaemonWSHeartbeat(ctx,+ daemonws.ClientIdentity{WorkspaceID: testWorkspaceID}, runtimeID, false); err != nil {+ t.Fatalf("HandleDaemonWSHeartbeat: %v", err)+ }++ httpBeat := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat",+ map[string]any{"runtime_id": runtimeID}, testWorkspaceID, "lookup-source-daemon")+ testutil.Call(t, testHandler.DaemonHeartbeat, httpBeat).Want(http.StatusOK)++ // A model poll for a runtime that no longer exists: the read-access gate+ // runs the lookup before any auth check, so this exercises the poll's+ // source and the not_found classification in one request.+ poll := withURLParam(httptest.NewRequest(http.MethodGet,+ "/api/runtimes/"+uuid.NewString()+"/models/req-1", nil), "runtimeId", uuid.NewString())+ testutil.Call(t, testHandler.GetModelListRequest, poll).Want(http.StatusNotFound)++ after := lookupSnapshot(t, m)+ for _, want := range []struct {+ source, result string+ }{+ {obsmetrics.RuntimeLookupSourceHeartbeatWS, obsmetrics.RuntimeLookupResultOK},+ {obsmetrics.RuntimeLookupSourceHeartbeatHTTP, obsmetrics.RuntimeLookupResultOK},+ {obsmetrics.RuntimeLookupSourceRuntimeModelPoll, obsmetrics.RuntimeLookupResultNotFound},+ } {+ key := want.source + "/" + want.result+ if got := after[key] - before[key]; got != 1 {+ t.Errorf("%s delta = %v, want 1", key, got)+ }+ }+ // The poll must not have been billed to the heartbeat, nor the heartbeats+ // to each other.+ for _, key := range []string{+ obsmetrics.RuntimeLookupSourceHeartbeatWS + "/" + obsmetrics.RuntimeLookupResultNotFound,+ obsmetrics.RuntimeLookupSourceHeartbeatHTTP + "/" + obsmetrics.RuntimeLookupResultNotFound,+ obsmetrics.RuntimeLookupSourceRuntimeModelPoll + "/" + obsmetrics.RuntimeLookupResultOK,+ obsmetrics.RuntimeLookupSourceOther + "/" + obsmetrics.RuntimeLookupResultOK,+ } {+ if got := after[key] - before[key]; got != 0 {+ t.Errorf("%s delta = %v, want 0", key, got)+ }+ }+}++// ---- helpers --------------------------------------------------------------++// withTestMetrics installs a fresh collector on the shared test handler for the+// duration of one test. testHandler.Metrics is nil by default, which every+// Record* call tolerates — so without this the counter would silently stay at+// zero and the assertions above would pass for the wrong reason.+func withTestMetrics(t *testing.T) *obsmetrics.BusinessMetrics {+ t.Helper()++ previous := testHandler.Metrics+ m := obsmetrics.NewBusinessMetrics()+ testHandler.Metrics = m+ t.Cleanup(func() { testHandler.Metrics = previous })+ return m+}++func lookupSnapshot(t *testing.T, m *obsmetrics.BusinessMetrics) map[string]float64 {+ t.Helper()++ fam := obsmetrics.GatherForTest(t, m)["multica_agent_runtime_lookup_total"]+ if fam == nil {+ t.Fatalf("multica_agent_runtime_lookup_total not registered")+ }+ out := map[string]float64{}+ for _, mtr := range fam.GetMetric() {+ out[metricLabel(mtr, "source")+"/"+metricLabel(mtr, "result")] = mtr.GetCounter().GetValue()+ }+ return out+}++func metricLabel(m *dto.Metric, name string) string {+ for _, l := range m.GetLabel() {+ if l.GetName() == name {+ return l.GetValue()+ }+ }+ return ""+}diff --git a/server/internal/handler/runtime_models.go b/server/internal/handler/runtime_models.goindex d99e56f49f..2de306cea6 100644--- a/server/internal/handler/runtime_models.go+++ b/server/internal/handler/runtime_models.go@@ -9,6 +9,7 @@ import ("time""github.com/go-chi/chi/v5"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/pkg/protocol")@@ -317,7 +318,7 @@ func modelListRequestTerminal(status ModelListStatus) bool {// HeartbeatInterval away.func (h *Handler) InitiateListModels(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -428,7 +429,7 @@ func (h *Handler) requestDaemonPendingWork(runtimeID, kind string) {// GetModelListRequest returns the status of a model list request.func (h *Handler) GetModelListRequest(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, _, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeModelPoll, runtimeID)if !ok {return}diff --git a/server/internal/handler/runtime_update.go b/server/internal/handler/runtime_update.goindex bef556534c..634c4ca197 100644--- a/server/internal/handler/runtime_update.go+++ b/server/internal/handler/runtime_update.go@@ -10,6 +10,7 @@ import ("time""github.com/go-chi/chi/v5"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics")// ---------------------------------------------------------------------------@@ -211,7 +212,7 @@ func (s *InMemoryUpdateStore) Fail(_ context.Context, id string, errMsg string)// InitiateUpdate creates a new CLI update request (protected route, called by frontend).func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, member, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, member, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)if !ok {return}@@ -261,7 +262,7 @@ func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {// GetUpdate returns the status of an update request (protected route, called by frontend).func (h *Handler) GetUpdate(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")- rt, member, ok := h.requireRuntimeReadAccess(w, r, runtimeID)+ rt, member, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeUpdatePoll, runtimeID)if !ok {return}diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex 392297b71f..29d96a3c08 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -16,6 +16,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"agentpkg "github.com/multica-ai/multica/server/pkg/agent"@@ -773,7 +774,7 @@ func (h *Handler) prepareAgentCommentSubIssue(w http.ResponseWriter, r *http.Reqif err != nil {return nil, sourceContextBadRequest("agent not found")}- verdict, err := service.AgentReadiness(r.Context(), h.Queries, agent)+ verdict, err := service.AgentReadiness(r.Context(), h.runtimeLookup(obsmetrics.RuntimeLookupSourceSourceContext), agent)if err != nil {return nil, err}@@ -781,11 +782,11 @@ func (h *Handler) prepareAgentCommentSubIssue(w http.ResponseWriter, r *http.ReqwriteAgentUnavailable(w, verdict.Detail, verdict.Reason)return nil, errSourceContextResponseWritten}- if status, payload := h.checkQuickCreateDaemonVersion(r.Context(), agent.RuntimeID); status != 0 {+ if status, payload := h.checkQuickCreateDaemonVersion(r.Context(), obsmetrics.RuntimeLookupSourceSourceContext, agent.RuntimeID); status != 0 {writeJSON(w, status, payload)return nil, errSourceContextResponseWritten}- runtime, err := h.Queries.GetAgentRuntime(r.Context(), agent.RuntimeID)+ runtime, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceSourceContext, agent.RuntimeID)if err != nil || !runtimeHasCapability(runtime.Metadata, protocol.DaemonCapabilitySourceContextQuickCreateV1) {writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"code": "source_context_quick_create_unsupported", "error": "selected agent runtime must be updated before using captured context"})return nil, errSourceContextResponseWritten@@ -799,7 +800,7 @@ func (h *Handler) prepareAgentCommentSubIssue(w http.ResponseWriter, r *http.ReqdueDate = parsed.Time.Format("2006-01-02")}if priority != "" || dueDate != "" {- if status, payload := h.checkQuickCreateDaemonVersionAtLeast(r.Context(), agent.RuntimeID, agentpkg.MinQuickCreateFieldsCLIVersion); status != 0 {+ if status, payload := h.checkQuickCreateDaemonVersionAtLeast(r.Context(), obsmetrics.RuntimeLookupSourceSourceContext, agent.RuntimeID, agentpkg.MinQuickCreateFieldsCLIVersion); status != 0 {writeJSON(w, status, payload)return nil, errSourceContextResponseWritten}@@ -829,7 +830,7 @@ func (h *Handler) prepareAgentCommentSubIssue(w http.ResponseWriter, r *http.Reqfunc (h *Handler) createAgentCommentSubIssue(w http.ResponseWriter, r *http.Request, workspaceID, userID pgtype.UUID, prepared preparedAgentCommentSubIssue, capture service.SourceContextCapture, limits service.SourceContextLimitUsage) error {// Recheck the capability after potentially long streaming copies. A runtime// can re-register during the copy; the final enqueue must still fail closed.- runtime, err := h.Queries.GetAgentRuntime(r.Context(), prepared.runtimeID)+ runtime, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceSourceContext, prepared.runtimeID)if err != nil || !runtimeHasCapability(runtime.Metadata, protocol.DaemonCapabilitySourceContextQuickCreateV1) {writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"code": "source_context_quick_create_unsupported", "error": "selected agent runtime must be updated before using captured context"})return errSourceContextResponseWrittendiff --git a/server/internal/metrics/agent_runtime_lookup_test.go b/server/internal/metrics/agent_runtime_lookup_test.gonew file mode 100644index 0000000000..0707315667--- /dev/null+++ b/server/internal/metrics/agent_runtime_lookup_test.go@@ -0,0 +1,177 @@+package metrics_test++import (+ "go/ast"+ "go/parser"+ "go/token"+ "io/fs"+ "path/filepath"+ "sort"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/metrics"+ dto "github.com/prometheus/client_model/go"+)++const runtimeLookupMetric = "multica_agent_runtime_lookup_total"++// TestAgentRuntimeLookupPrewarmsEverySeries asserts the counter ships every+// source x result combination at zero. An absent series and a zero series look+// the same on a dashboard but behave differently: rate() over an absent series+// returns nothing at all, so a source that has genuinely never fired would be+// indistinguishable from one nobody instrumented.+func TestAgentRuntimeLookupPrewarmsEverySeries(t *testing.T) {+ t.Parallel()++ m := metrics.NewBusinessMetrics()+ fam := metrics.GatherForTest(t, m)[runtimeLookupMetric]+ if fam == nil {+ t.Fatalf("%s not registered", runtimeLookupMetric)+ }++ want := map[string]struct{}{}+ for _, source := range metrics.AllRuntimeLookupSources() {+ for _, result := range metrics.AllRuntimeLookupResults() {+ want[source+"/"+result] = struct{}{}+ }+ }+ for _, mtr := range fam.GetMetric() {+ delete(want, labelPair(mtr, "source")+"/"+labelPair(mtr, "result"))+ }+ if len(want) > 0 {+ missing := make([]string, 0, len(want))+ for k := range want {+ missing = append(missing, k)+ }+ sort.Strings(missing)+ t.Errorf("prewarm missed %d series: %s", len(missing), strings.Join(missing, ", "))+ }+}++// TestRecordAgentRuntimeLookupNormalizesLabels asserts a call site that passes+// an unclassified source or an unknown result cannot mint a new series. The+// unknown result deliberately lands on "error" rather than "ok": a lookup+// nobody classified is not evidence that the read succeeded.+func TestRecordAgentRuntimeLookupNormalizesLabels(t *testing.T) {+ t.Parallel()++ m := metrics.NewBusinessMetrics()+ m.RecordAgentRuntimeLookup(metrics.RuntimeLookupSourceHeartbeatWS, metrics.RuntimeLookupResultOK)+ m.RecordAgentRuntimeLookup(metrics.RuntimeLookupSourceHeartbeatWS, metrics.RuntimeLookupResultNotFound)+ m.RecordAgentRuntimeLookup(" HEARTBEAT_WS ", metrics.RuntimeLookupResultOK)+ m.RecordAgentRuntimeLookup("brand_new_call_site", "who_knows")++ counts := runtimeLookupCounts(t, m)+ for _, tc := range []struct {+ source, result string+ want float64+ }{+ {metrics.RuntimeLookupSourceHeartbeatWS, metrics.RuntimeLookupResultOK, 2},+ {metrics.RuntimeLookupSourceHeartbeatWS, metrics.RuntimeLookupResultNotFound, 1},+ {metrics.RuntimeLookupSourceOther, metrics.RuntimeLookupResultError, 1},+ } {+ if got := counts[tc.source+"/"+tc.result]; got != tc.want {+ t.Errorf("%s/%s = %v, want %v", tc.source, tc.result, got, tc.want)+ }+ }++ var total float64+ for _, v := range counts {+ total += v+ }+ if total != 4 {+ t.Errorf("total samples = %v, want 4 (an unknown label must reuse a series, not add one)", total)+ }+}++// TestNoDirectGetAgentRuntimeCalls walks every non-test Go file under+// server/internal and server/cmd and asserts nothing calls the sqlc+// GetAgentRuntime method except service.RuntimeLookup.Get.+//+// The metric is only worth reading if it counts every read. A call site that+// goes straight to Queries.GetAgentRuntime does not fail, does not warn, and+// does not show up — it silently shrinks whichever source it belonged to, which+// is exactly the kind of quiet undercount that would send the follow-up+// optimisation work after the wrong caller.+func TestNoDirectGetAgentRuntimeCalls(t *testing.T) {+ t.Parallel()++ root := repoRoot(t)+ // The wrapper itself, keyed by path relative to server/ and by the name of+ // the one function allowed to make the call.+ wrapper := filepath.Join(root, "internal", "service", "agent_runtime_lookup.go")++ var offenders []string+ fset := token.NewFileSet()+ for _, dir := range []string{"internal", "cmd"} {+ err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {+ return nil+ }+ f, parseErr := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)+ if parseErr != nil {+ return parseErr+ }+ for _, decl := range f.Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok || fn.Body == nil {+ continue+ }+ if path == wrapper && fn.Name.Name == "Get" {+ continue+ }+ ast.Inspect(fn.Body, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok || sel.Sel.Name != "GetAgentRuntime" {+ return true+ }+ offenders = append(offenders, fset.Position(call.Pos()).String()+" (in "+fn.Name.Name+")")+ return true+ })+ }+ return nil+ })+ if err != nil {+ t.Fatalf("walk %s: %v", dir, err)+ }+ }++ if len(offenders) > 0 {+ sort.Strings(offenders)+ t.Errorf("found %d direct GetAgentRuntime call(s) — read through service.RuntimeLookup with a source label so %s stays complete:\n %s",+ len(offenders), runtimeLookupMetric, strings.Join(offenders, "\n "))+ }+}++// ---- helpers --------------------------------------------------------------++func runtimeLookupCounts(t *testing.T, m *metrics.BusinessMetrics) map[string]float64 {+ t.Helper()++ fam := metrics.GatherForTest(t, m)[runtimeLookupMetric]+ if fam == nil {+ t.Fatalf("%s not registered", runtimeLookupMetric)+ }+ out := map[string]float64{}+ for _, mtr := range fam.GetMetric() {+ out[labelPair(mtr, "source")+"/"+labelPair(mtr, "result")] = mtr.GetCounter().GetValue()+ }+ return out+}++func labelPair(m *dto.Metric, name string) string {+ for _, l := range m.GetLabel() {+ if l.GetName() == name {+ return l.GetValue()+ }+ }+ return ""+}diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 93cdd4ed2a..193695cf21 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -70,6 +70,12 @@ 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 *prometheus.CounterVec+activeMu sync.MutexactiveTasks map[string]activeTaskLabels@@ -265,6 +271,10 @@ func NewBusinessMetrics() *BusinessMetrics {Namespace: "multica", Subsystem: "autopilot_quota", Name: "decision_total",Help: "Total autopilot quota admission outcomes.",}, 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.",+ }, metricLabels("multica_agent_runtime_lookup_total")),activeTasks: map[string]activeTaskLabels{},events: newBusinessEventMetrics(),}@@ -272,6 +282,15 @@ func NewBusinessMetrics() *BusinessMetrics {for _, reason := range []string{RuntimeGCSkipEligibilityChanged, RuntimeGCSkipNonTerminalTask, RuntimeGCSkipWorkspaceMismatch} {m.runtimeGCSkipped.WithLabelValues(reason).Add(0)}+ // Prewarm the full source x result grid (45 series) so a source that has+ // not fired since this process started reads as zero rather than as a+ // missing series — rate() over an absent series returns nothing, which on+ // a dashboard is indistinguishable from "we never instrumented that path".+ for _, source := range AllRuntimeLookupSources() {+ for _, result := range AllRuntimeLookupResults() {+ m.agentRuntimeLookup.WithLabelValues(source, result).Add(0)+ }+ }return m}@@ -309,6 +328,7 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.entitlementDecision,m.entitlementVersionRegression,m.autopilotQuotaDecision,+ m.agentRuntimeLookup,}, m.events.collectors()...)}@@ -338,6 +358,22 @@ func (m *BusinessMetrics) RecordEntitlementDecision(gate, action, reason string)}}+// RecordAgentRuntimeLookup counts one single-row agent_runtime read.+//+// 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 site+// ends up counted twice or not at all. Both labels are normalized here, so a+// typo at a call site degrades to "other"/"error" instead of minting a series.+func (m *BusinessMetrics) RecordAgentRuntimeLookup(source, result string) {+ if m == nil {+ return+ }+ m.agentRuntimeLookup.WithLabelValues(+ NormalizeAgentRuntimeLookupSource(source),+ NormalizeAgentRuntimeLookupResult(result),+ ).Inc()+}+func (m *BusinessMetrics) RecordEntitlementVersionRegression() {if m != nil {m.entitlementVersionRegression.Inc()diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex c60162cf27..744e7398aa 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -60,6 +60,7 @@ var businessMetricLabels = map[string][]string{"multica_runtime_sweeper_stage_duration_seconds": {labelStage},"multica_runtime_sweeper_candidate_rows_total": {labelStage},"multica_runtime_sweeper_rows_changed_total": {labelStage},+ "multica_agent_runtime_lookup_total": {labelSource, labelResult},// PR3 funnel / community / commercial."multica_signup_total": {labelSignupSource},@@ -180,14 +181,22 @@ var ("cache_read": "cache_read","cache_write": "cache_write",}- knownFailureReasons = map[string]string{}- modelAliasUnsafeRe = regexp.MustCompile(`[^a-z0-9._:/+-]+`)+ knownFailureReasons = map[string]string{}+ knownRuntimeLookupSources = map[string]string{}+ knownRuntimeLookupResults = map[string]string{}+ modelAliasUnsafeRe = regexp.MustCompile(`[^a-z0-9._:/+-]+`))func init() {for _, reason := range taskfailure.AllReasons() {knownFailureReasons[reason.String()] = reason.String()}+ for _, source := range AllRuntimeLookupSources() {+ knownRuntimeLookupSources[source] = source+ }+ for _, result := range AllRuntimeLookupResults() {+ knownRuntimeLookupResults[result] = result+ }}func validateBusinessMetricLabels() {@@ -208,6 +217,121 @@ func metricLabels(metric string) []string {return labels}+// Agent-runtime lookup sources (MUL-6884). A single-row read of agent_runtime+// is issued from a dozen unrelated product paths, and every one of them+// collapses into the same normalized SQL fingerprint in pg_stat_statements —+// so the database can say how many reads happened but never which feature+// asked for them. These labels are that missing half.+//+// The list is a closed enum on purpose: it is the label set of a counter that+// fires on the hottest read in the system, so it must stay bounded no matter+// how many runtimes, workspaces, or routes exist. Anything unrecognized lands+// on RuntimeLookupSourceOther, which should sit at ~0 — a non-zero rate there+// means a new call site was added without classifying it.+const (+ // RuntimeLookupSourceHeartbeatWS is the daemon WebSocket heartbeat, one+ // read per runtime per HeartbeatInterval.+ RuntimeLookupSourceHeartbeatWS = "heartbeat_ws"+ // RuntimeLookupSourceHeartbeatHTTP is the POST /api/daemon/heartbeat+ // fallback used when the WebSocket ack does not arrive.+ RuntimeLookupSourceHeartbeatHTTP = "heartbeat_http"+ // RuntimeLookupSourceDaemonAPI covers daemon-authenticated endpoints other+ // than the heartbeat: WS upgrade, result reports, deregister, task calls.+ RuntimeLookupSourceDaemonAPI = "daemon_api"+ // RuntimeLookupSourceRuntimeModelPoll is the browser polling a model+ // discovery request (every 500ms while the picker waits).+ RuntimeLookupSourceRuntimeModelPoll = "runtime_model_poll"+ // RuntimeLookupSourceRuntimeLocalSkillPoll is the browser polling a local+ // skill / MCP discovery request.+ RuntimeLookupSourceRuntimeLocalSkillPoll = "runtime_local_skill_poll"+ // RuntimeLookupSourceRuntimeLocalSkillImportPoll is the browser polling a+ // local skill import, which the UI allows up to ten of concurrently.+ RuntimeLookupSourceRuntimeLocalSkillImportPoll = "runtime_local_skill_import_poll"+ // RuntimeLookupSourceRuntimeUpdatePoll is the browser polling CLI update+ // progress.+ RuntimeLookupSourceRuntimeUpdatePoll = "runtime_update_poll"+ // RuntimeLookupSourceRuntimeAPI is every other runtime-scoped API call:+ // reads, management, and the read-access gate itself.+ RuntimeLookupSourceRuntimeAPI = "runtime_api"+ // RuntimeLookupSourceIssue covers issue create / assign / quick-create and+ // the trigger-preview readiness checks.+ RuntimeLookupSourceIssue = "issue"+ // RuntimeLookupSourceComment covers mention and sub-issue readiness checks+ // on comments.+ RuntimeLookupSourceComment = "comment"+ // RuntimeLookupSourceChat covers the pre-send readiness check on chat.+ RuntimeLookupSourceChat = "chat"+ // RuntimeLookupSourceAutopilot covers autopilot admission and dispatch.+ RuntimeLookupSourceAutopilot = "autopilot"+ // RuntimeLookupSourceSourceContext covers the source-context quick-create+ // capability gates, including the deliberate post-copy recheck.+ RuntimeLookupSourceSourceContext = "source_context"+ // RuntimeLookupSourceTask covers task analytics context and the usage+ // provider backfill.+ RuntimeLookupSourceTask = "task"+ // RuntimeLookupSourceOther is the catch-all for an unclassified call site.+ RuntimeLookupSourceOther = "other"+)++// Agent-runtime lookup results. Kept separate from the generic status labels+// because the distinction that matters here is "the row is gone" (the daemon+// self-heal signal) versus "the database failed", and collapsing those two+// would hide a real outage behind a normal deletion.+const (+ RuntimeLookupResultOK = "ok"+ RuntimeLookupResultNotFound = "not_found"+ RuntimeLookupResultError = "error"+)++// AllRuntimeLookupSources lists every source label in a stable order. Used to+// prewarm the counter so a source that has not fired yet is a visible zero+// instead of an absent series.+func AllRuntimeLookupSources() []string {+ return []string{+ RuntimeLookupSourceHeartbeatWS,+ RuntimeLookupSourceHeartbeatHTTP,+ RuntimeLookupSourceDaemonAPI,+ RuntimeLookupSourceRuntimeModelPoll,+ RuntimeLookupSourceRuntimeLocalSkillPoll,+ RuntimeLookupSourceRuntimeLocalSkillImportPoll,+ RuntimeLookupSourceRuntimeUpdatePoll,+ RuntimeLookupSourceRuntimeAPI,+ RuntimeLookupSourceIssue,+ RuntimeLookupSourceComment,+ RuntimeLookupSourceChat,+ RuntimeLookupSourceAutopilot,+ RuntimeLookupSourceSourceContext,+ RuntimeLookupSourceTask,+ RuntimeLookupSourceOther,+ }+}++// AllRuntimeLookupResults lists every result label in a stable order.+func AllRuntimeLookupResults() []string {+ return []string{RuntimeLookupResultOK, RuntimeLookupResultNotFound, RuntimeLookupResultError}+}++// NormalizeAgentRuntimeLookupSource maps a call-site source onto the closed+// enum above. An unknown value becomes "other" rather than a new series.+func NormalizeAgentRuntimeLookupSource(value string) string {+ value = strings.ToLower(strings.TrimSpace(value))+ if normalized, ok := knownRuntimeLookupSources[value]; ok {+ return normalized+ }+ return RuntimeLookupSourceOther+}++// NormalizeAgentRuntimeLookupResult maps a lookup outcome onto the closed+// enum above. An unknown value is treated as an error: a result nobody+// classified is not evidence that the read succeeded.+func NormalizeAgentRuntimeLookupResult(value string) string {+ value = strings.ToLower(strings.TrimSpace(value))+ if normalized, ok := knownRuntimeLookupResults[value]; ok {+ return normalized+ }+ return RuntimeLookupResultError+}+func NormalizeTaskSource(value string) string {value = strings.ToLower(strings.TrimSpace(value))if normalized, ok := knownSources[value]; ok {diff --git a/server/internal/service/agent_ready.go b/server/internal/service/agent_ready.goindex f548a79a6c..a7c6060637 100644--- a/server/internal/service/agent_ready.go+++ b/server/internal/service/agent_ready.go@@ -82,6 +82,10 @@ const runtimeOfflineCodeNotExecutable = "not_executable"// AgentReadiness reports whether an agent can accept new work right now, and// what the caller should do when it cannot.//+// The lookup carries the connection to read on plus the source label the+// runtime read is attributed to (MUL-6884), so each admission path stays+// distinguishable in multica_agent_runtime_lookup_total.+//// err is non-nil only on DB lookup failure for the runtime row. Callers that// treat a transient DB error as "do not skip" (the autopilot admission gate)// should swallow it; callers that need a hard yes/no (the squad-leader@@ -98,7 +102,7 @@ const runtimeOfflineCodeNotExecutable = "not_executable"// one starts allowing "starting" runtimes while another doesn't, and the bug// only surfaces when a user assigns the same agent through two different entry// points. Touch this function, all of them move together.-func AgentReadiness(ctx context.Context, q *db.Queries, agent db.Agent) (AgentVerdict, error) {+func AgentReadiness(ctx context.Context, lookup RuntimeLookup, agent db.Agent) (AgentVerdict, error) {if agent.ArchivedAt.Valid {return AgentVerdict{Availability: AgentBlocked,@@ -113,7 +117,7 @@ func AgentReadiness(ctx context.Context, q *db.Queries, agent db.Agent) (AgentVeDetail: "agent has no runtime bound",}, nil}- rt, err := q.GetAgentRuntime(ctx, agent.RuntimeID)+ rt, err := lookup.Get(ctx, agent.RuntimeID)if err != nil {return AgentVerdict{}, err}diff --git a/server/internal/service/agent_runtime_lookup.go b/server/internal/service/agent_runtime_lookup.gonew file mode 100644index 0000000000..0a3140f948--- /dev/null+++ b/server/internal/service/agent_runtime_lookup.go@@ -0,0 +1,81 @@+package service++import (+ "context"+ "errors"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ 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).+//+// 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.+//+// Source is a closed enum from the metrics package (obsmetrics.RuntimeLookupSource*).+// Metrics may be nil — tests and self-hosted deployments without the metrics+// listener run without it, and the counter is best-effort by construction.+type RuntimeLookup struct {+ // Queries is the connection the read runs on. Callers inside a+ // transaction must pass the transaction's queries, not the pool's, so the+ // read sees the same snapshot as the rest of the transaction.+ Queries *db.Queries+ Metrics *obsmetrics.BusinessMetrics+ Source string+}++// Get reads one agent_runtime row and counts it against the lookup's source.+//+// The row and error are returned untouched: callers already distinguish+// pgx.ErrNoRows (the runtime was deleted — the daemon reads that as "drop your+// local registration") from a transient database failure, and collapsing the+// two here would turn a hiccup into a spurious self-heal.+func (l RuntimeLookup) Get(ctx context.Context, id pgtype.UUID) (db.AgentRuntime, error) {+ rt, err := l.Queries.GetAgentRuntime(ctx, id)+ l.Metrics.RecordAgentRuntimeLookup(l.Source, runtimeLookupResult(err))+ return rt, err+}++func runtimeLookupResult(err error) string {+ switch {+ case err == nil:+ return obsmetrics.RuntimeLookupResultOK+ case errors.Is(err, pgx.ErrNoRows):+ return obsmetrics.RuntimeLookupResultNotFound+ default:+ return obsmetrics.RuntimeLookupResultError+ }+}++// runtimeLookup returns the issue-sourced lookup, bound to the caller's+// connection so a read inside the create transaction stays inside it.+func (s *IssueService) runtimeLookup(q *db.Queries) RuntimeLookup {+ return RuntimeLookup{Queries: q, Metrics: s.Metrics, Source: obsmetrics.RuntimeLookupSourceIssue}+}++// runtimeLookup returns the task-sourced lookup for analytics context and the+// usage provider backfill.+func (s *TaskService) runtimeLookup() RuntimeLookup {+ return RuntimeLookup{Queries: s.Queries, Metrics: s.Metrics, Source: obsmetrics.RuntimeLookupSourceTask}+}++// runtimeLookup returns the autopilot-sourced lookup. AutopilotService holds no+// metrics collector of its own; it shares the task service's, which the router+// wires from the same registry.+func (s *AutopilotService) runtimeLookup() RuntimeLookup {+ var m *obsmetrics.BusinessMetrics+ if s.TaskSvc != nil {+ m = s.TaskSvc.Metrics+ }+ return RuntimeLookup{Queries: s.Queries, Metrics: m, Source: obsmetrics.RuntimeLookupSourceAutopilot}+}diff --git a/server/internal/service/agent_runtime_lookup_test.go b/server/internal/service/agent_runtime_lookup_test.gonew file mode 100644index 0000000000..cf6d98bf46--- /dev/null+++ b/server/internal/service/agent_runtime_lookup_test.go@@ -0,0 +1,111 @@+package service++import (+ "context"+ "errors"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ dto "github.com/prometheus/client_model/go"++ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestRuntimeLookupClassifiesResult pins the distinction the metric exists to+// preserve: a deleted runtime row (pgx.ErrNoRows, which the daemon reads as+// "drop your local registration") must not be counted as a database failure,+// and neither may be counted as a success. Collapsing them would make a real+// outage indistinguishable from a user deleting a machine.+func TestRuntimeLookupClassifiesResult(t *testing.T) {+ t.Parallel()++ dbErr := errors.New("connection reset")+ for _, tc := range []struct {+ name string+ scanErr error+ wantResult string+ wantErr error+ }{+ {"found", nil, obsmetrics.RuntimeLookupResultOK, nil},+ {"deleted", pgx.ErrNoRows, obsmetrics.RuntimeLookupResultNotFound, pgx.ErrNoRows},+ {"db down", dbErr, obsmetrics.RuntimeLookupResultError, dbErr},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()++ m := obsmetrics.NewBusinessMetrics()+ lookup := RuntimeLookup{+ Queries: db.New(scanErrDBTX{err: tc.scanErr}),+ Metrics: m,+ Source: obsmetrics.RuntimeLookupSourceHeartbeatWS,+ }++ _, err := lookup.Get(context.Background(), pgtype.UUID{})+ if !errors.Is(err, tc.wantErr) {+ t.Fatalf("Get error = %v, want %v", err, tc.wantErr)+ }+ if got := lookupCount(t, m, obsmetrics.RuntimeLookupSourceHeartbeatWS, tc.wantResult); got != 1 {+ t.Errorf("heartbeat_ws/%s = %v, want 1", tc.wantResult, got)+ }+ })+ }+}++// TestRuntimeLookupNilMetricsIsSafe covers self-hosted deployments and tests+// that run without the metrics listener: the read must still happen.+func TestRuntimeLookupNilMetricsIsSafe(t *testing.T) {+ t.Parallel()++ lookup := RuntimeLookup{Queries: db.New(scanErrDBTX{err: pgx.ErrNoRows}), Source: obsmetrics.RuntimeLookupSourceTask}+ if _, err := lookup.Get(context.Background(), pgtype.UUID{}); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("Get error = %v, want pgx.ErrNoRows", err)+ }+}++// ---- helpers --------------------------------------------------------------++func lookupCount(t *testing.T, m *obsmetrics.BusinessMetrics, source, result string) float64 {+ t.Helper()++ fam := obsmetrics.GatherForTest(t, m)["multica_agent_runtime_lookup_total"]+ if fam == nil {+ t.Fatalf("multica_agent_runtime_lookup_total not registered")+ }+ for _, mtr := range fam.GetMetric() {+ if labelValue(mtr, "source") == source && labelValue(mtr, "result") == result {+ return mtr.GetCounter().GetValue()+ }+ }+ t.Fatalf("no sample for %s/%s", source, result)+ return 0+}++func labelValue(m *dto.Metric, name string) string {+ for _, l := range m.GetLabel() {+ if l.GetName() == name {+ return l.GetValue()+ }+ }+ return ""+}++// scanErrDBTX is a db.DBTX whose single-row reads fail with a fixed error, so+// the wrapper's error classification is testable without a database.+type scanErrDBTX struct{ err error }++func (d scanErrDBTX) Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) {+ return pgconn.CommandTag{}, d.err+}++func (d scanErrDBTX) Query(context.Context, string, ...interface{}) (pgx.Rows, error) {+ return nil, d.err+}++func (d scanErrDBTX) QueryRow(context.Context, string, ...interface{}) pgx.Row { return errRow{d.err} }++type errRow struct{ err error }++func (r errRow) Scan(...any) error { return r.err }diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 29735db0ee..8a81394de1 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -949,7 +949,7 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,}return fmt.Errorf("resolve leader: %w", err)}- verdict, err := AgentReadiness(ctx, s.Queries, agent)+ verdict, err := AgentReadiness(ctx, s.runtimeLookup(), agent)if err != nil {return fmt.Errorf("check agent readiness: %w", err)}@@ -1313,7 +1313,7 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil// chance to succeed.return "", "", false}- verdict, err := AgentReadiness(ctx, s.Queries, agent)+ verdict, err := AgentReadiness(ctx, s.runtimeLookup(), agent)if err != nil {slog.Warn("autopilot admission: failed to load runtime","autopilot_id", util.UUIDToString(ap.ID),diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex ac0f8ab6e8..5d8eb35f51 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -731,7 +731,7 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,if issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status) == "backlog" {return pgtype.UUID{}}- verdict, admitted := agentAssigneeVerdict(ctx, s.Queries, issue)+ verdict, admitted := agentAssigneeVerdict(ctx, s.runtimeLookup(s.Queries), issue)if !admitted && verdict.Reason == dispatch.ReasonRuntimeUnusable {// Assignment has no response the assigner reads for this outcome, so the// refusal explains itself on the issue instead of vanishing (MUL-6164).@@ -777,11 +777,11 @@ func (s *IssueService) shouldEnqueueAgentTaskWithQueries(ctx context.Context, qif issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status) == "backlog" {return false}- return isAgentAssigneeReadyWithQueries(ctx, q, issue)+ return isAgentAssigneeReadyWithQueries(ctx, s.runtimeLookup(q), issue)}-func isAgentAssigneeReadyWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {- _, ok := agentAssigneeVerdict(ctx, q, issue)+func isAgentAssigneeReadyWithQueries(ctx context.Context, lookup RuntimeLookup, issue db.Issue) bool {+ _, ok := agentAssigneeVerdict(ctx, lookup, issue)return ok}@@ -791,15 +791,15 @@ func isAgentAssigneeReadyWithQueries(ctx context.Context, q *db.Queries, issue d//// Only a BLOCKED verdict stops the enqueue. A merely offline machine still// queues: that work runs when the laptop comes back, and people rely on it.-func agentAssigneeVerdict(ctx context.Context, q *db.Queries, issue db.Issue) (AgentVerdict, bool) {+func agentAssigneeVerdict(ctx context.Context, lookup RuntimeLookup, issue db.Issue) (AgentVerdict, bool) {if !issue.AssigneeType.Valid || issue.AssigneeType.String != "agent" || !issue.AssigneeID.Valid {return AgentVerdict{}, false}- agent, err := q.GetAgent(ctx, issue.AssigneeID)+ agent, err := lookup.Queries.GetAgent(ctx, issue.AssigneeID)if err != nil {return AgentVerdict{}, false}- verdict, err := AgentReadiness(ctx, q, agent)+ verdict, err := AgentReadiness(ctx, lookup, agent)if err != nil {return AgentVerdict{}, false}@@ -828,7 +828,7 @@ func (s *IssueService) isSquadLeaderReady(ctx context.Context, issue db.Issue) bif err != nil {return false}- verdict, err := AgentReadiness(ctx, s.Queries, agent)+ verdict, err := AgentReadiness(ctx, s.runtimeLookup(s.Queries), agent)if err != nil {return false}diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.goindex 954ef0dfc9..0e6df5ba5f 100644--- a/server/internal/service/issue_trigger.go+++ b/server/internal/service/issue_trigger.go@@ -180,7 +180,7 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,if err != nil {return IssueRunTrigger{}, false}- verdict, err := AgentReadiness(ctx, s.Queries, leader)+ verdict, err := AgentReadiness(ctx, s.runtimeLookup(s.Queries), leader)if err != nil || !verdict.Ready() {return IssueRunTrigger{}, false}diff --git a/server/internal/service/reason_code_test.go b/server/internal/service/reason_code_test.goindex d6937435b7..3abb99258f 100644--- a/server/internal/service/reason_code_test.go+++ b/server/internal/service/reason_code_test.go@@ -44,10 +44,10 @@ func TestAgentReadinessVerdict(t *testing.T) {// The agent-only half needs no runtime row, so AgentReadiness answers before// it queries one.- if got, _ := AgentReadiness(t.Context(), nil, db.Agent{}); got.Reason != dispatch.ReasonAgentRuntimeRequired || !got.Blocked() {+ if got, _ := AgentReadiness(t.Context(), RuntimeLookup{}, db.Agent{}); got.Reason != dispatch.ReasonAgentRuntimeRequired || !got.Blocked() {t.Errorf("no runtime bound: got %+v, want blocked/agent_runtime_required", got)}- if got, _ := AgentReadiness(t.Context(), nil, db.Agent{ArchivedAt: archivedAt, RuntimeID: validRuntime}); got.Reason != dispatch.ReasonTargetUnavailable || !got.Blocked() {+ if got, _ := AgentReadiness(t.Context(), RuntimeLookup{}, db.Agent{ArchivedAt: archivedAt, RuntimeID: validRuntime}); got.Reason != dispatch.ReasonTargetUnavailable || !got.Blocked() {t.Errorf("archived agent: got %+v, want blocked/target_unavailable", got)}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 778e10cf91..a4f0b3becf 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -925,7 +925,7 @@ func (s *TaskService) taskAnalyticsContext(ctx context.Context, task db.AgentTas}if task.RuntimeID.Valid {- if rt, err := s.Queries.GetAgentRuntime(ctx, task.RuntimeID); err == nil {+ if rt, err := s.runtimeLookup().Get(ctx, task.RuntimeID); err == nil {tc.WorkspaceID = util.UUIDToString(rt.WorkspaceID)tc.RuntimeMode = rt.RuntimeModetc.Provider = rt.Provider