Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7969: feat(server): record structured claim decision outcomes (#9184)

Thne482ec69c1135
diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.go
index a08a8975ff..f027ceb834 100644
--- a/server/internal/metrics/business.go
+++ b/server/internal/metrics/business.go
@@ -46,6 +46,12 @@ type BusinessMetrics struct {
taskTotalSeconds *prometheus.HistogramVec
taskInProgress *prometheus.GaugeVec
taskIterations *prometheus.HistogramVec
+ // taskClaimDecision counts claim-path decisions by the poll path that
+ // made them, the outcome, and the reason; one increment per claim
+ // attempt or per poll-level decision that never enters a claim attempt.
+ // See the funnel in internal/service/task_claim_decision.go and the
+ // prewarm table below.
+ taskClaimDecision *prometheus.CounterVec
llmTokens *prometheus.CounterVec
llmCostUSD *prometheus.CounterVec
@@ -165,6 +171,12 @@ func NewBusinessMetrics() *BusinessMetrics {
Help: "Retry attempt count observed when an agent task reaches a terminal state.",
Buckets: []float64{1, 2, 3, 4, 5, 10},
}, metricLabels("multica_agent_task_iteration_count")),
+ taskClaimDecision: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "agent_task",
+ Name: "claim_decision_total",
+ Help: "Claim decisions by claim path, outcome, and reason; one increment per claim attempt or per poll-level decision that never enters a claim attempt.",
+ }, metricLabels("multica_agent_task_claim_decision_total")),
llmTokens: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "multica",
Subsystem: "llm",
@@ -301,6 +313,7 @@ func NewBusinessMetrics() *BusinessMetrics {
events: newBusinessEventMetrics(),
}
m.prewarmFailureReasons()
+ m.prewarmClaimDecisions()
for _, reason := range []string{RuntimeGCSkipEligibilityChanged, RuntimeGCSkipNonTerminalTask, RuntimeGCSkipWorkspaceMismatch} {
m.runtimeGCSkipped.WithLabelValues(reason).Add(0)
}
@@ -329,6 +342,7 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {
m.taskTotalSeconds,
m.taskInProgress,
m.taskIterations,
+ m.taskClaimDecision,
m.llmTokens,
m.llmCostUSD,
m.llmUnpricedTokens,
@@ -405,6 +419,17 @@ func (m *BusinessMetrics) RecordEntitlementDecision(gate, action, reason string)
}
}
+// RecordClaimDecision counts one claim-path decision. Labels are normalized
+// upstream by the single funnel in internal/service/task_claim_decision.go;
+// this method deliberately does not re-normalize (same contract as
+// RecordEntitlementDecision).
+func (m *BusinessMetrics) RecordClaimDecision(claimPath, outcome, reason string) {
+ if m == nil {
+ return
+ }
+ m.taskClaimDecision.WithLabelValues(claimPath, outcome, reason).Inc()
+}
+
// 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
@@ -761,3 +786,68 @@ func (m *BusinessMetrics) prewarmFailureReasons() {
}
}
}
+
+// prewarmClaimDecisions seeds every (claim_path, outcome, reason) series the
+// claim paths can emit so an outcome that has not fired since this process
+// started reads as zero instead of as a missing series (same rationale as the
+// agent_runtime_lookup grid above). The table mirrors claimReasonFor in
+// internal/service/task_claim_decision.go; keep the two in sync when an
+// outcome is added.
+func (m *BusinessMetrics) prewarmClaimDecisions() {
+ for _, s := range claimDecisionSeries() {
+ m.taskClaimDecision.WithLabelValues(s.claimPath, s.outcome, s.reason).Add(0)
+ }
+}
+
+type claimDecisionSeriesKey struct{ claimPath, outcome, reason string }
+
+// claimDecisionSeries enumerates the closed set of legal label combinations:
+// the claimTask outcomes shared by every poll path, the no_tasks reason split
+// by whether the caller had a candidate list, and the poll exits (single
+// runtime and batch) that never enter claimTask. Values mirror the constants
+// in internal/service/task_claim_decision.go.
+func claimDecisionSeries() []claimDecisionSeriesKey {
+ claimTaskOutcomes := []claimDecisionSeriesKey{
+ {"", "claimed", "claimed"},
+ {"", "no_capacity", "agent_concurrency_cap"},
+ {"", "no_runtime", "agent_unbound"},
+ {"", "runtime_mismatch", "agent_rebound"},
+ {"", "error_get_agent", "error"},
+ {"", "error_count_running", "error"},
+ {"", "error_claim", "error"},
+ {"", "error_reanchor_chat_input", "error"},
+ {"", "error_transaction", "error"},
+ }
+ var series []claimDecisionSeriesKey
+ for _, claimPath := range []string{"agent", "runtime", "batch"} {
+ for _, o := range claimTaskOutcomes {
+ series = append(series, claimDecisionSeriesKey{claimPath, o.outcome, o.reason})
+ }
+ }
+ // The agent path has no candidate list, so its no_tasks can only say the
+ // cause is unknown; the runtime and batch paths see the candidate count.
+ series = append(series, claimDecisionSeriesKey{"agent", "no_tasks", "unknown_candidates"})
+ for _, claimPath := range []string{"runtime", "batch"} {
+ series = append(series,
+ claimDecisionSeriesKey{claimPath, "no_tasks", "candidates_unclaimed"},
+ claimDecisionSeriesKey{claimPath, "no_tasks", "no_visible_candidates"},
+ )
+ }
+ for _, s := range []claimDecisionSeriesKey{
+ {"runtime", "empty_cache_hit", "empty_cache"},
+ {"runtime", "empty_db", "no_visible_candidates"},
+ {"runtime", "reclaimed_dispatched", "stale_dispatch_recovered"},
+ {"runtime", "error_promote_deferred", "error"},
+ {"runtime", "error_reclaim_dispatched", "error"},
+ {"runtime", "error_list", "error"},
+ {"batch", "empty_cache_hit", "empty_cache"},
+ {"batch", "empty_db", "no_visible_candidates"},
+ {"batch", "reclaimed_dispatched", "stale_dispatch_recovered"},
+ {"batch", "error_promote_deferred", "error"},
+ {"batch", "error_reclaim_dispatched", "error"},
+ {"batch", "error_list", "error"},
+ } {
+ series = append(series, s)
+ }
+ return series
+}
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index ffeb7f6c38..608b74a566 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -35,6 +35,7 @@ const (
labelGate = "gate"
labelOutcome = "outcome"
labelStage = "stage"
+ labelClaimPath = "claim_path"
)
var businessMetricLabels = map[string][]string{
@@ -45,6 +46,7 @@ var businessMetricLabels = map[string][]string{
"multica_agent_task_failed_total": {labelSource, labelRuntimeMode, labelFailureReason},
"multica_agent_task_queue_wait_seconds": {labelSource, labelRuntimeMode},
"multica_agent_task_claimable_wait_seconds": {labelSource, labelRuntimeMode},
+ "multica_agent_task_claim_decision_total": {labelClaimPath, labelOutcome, labelReason},
"multica_agent_task_run_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},
"multica_agent_task_total_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},
"multica_agent_task_in_progress": {labelSource, labelRuntimeMode},
diff --git a/server/internal/service/runtime_claim_access_test.go b/server/internal/service/runtime_claim_access_test.go
index 17f82b4535..4350f37390 100644
--- a/server/internal/service/runtime_claim_access_test.go
+++ b/server/internal/service/runtime_claim_access_test.go
@@ -249,7 +249,7 @@ func TestClaimTaskRejectsMismatchedAgentRuntime(t *testing.T) {
fixture := newRuntimeClaimAccessFixture(t, "public", false, false, "queued")
svc := NewTaskService(db.New(fixture.pool), fixture.pool, nil, events.New())
- claimed, err := svc.claimTask(ctx, fixture.agentID, fixture.runtimeID)
+ claimed, err := svc.claimTask(ctx, fixture.agentID, fixture.runtimeID, claimScope{claimPath: claimPathRuntime})
if err != nil {
t.Fatalf("claim task: %v", err)
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index f7a5db9c0b..3b5cbb2ce6 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3540,7 +3540,7 @@ func (s *TaskService) broadcastChatCancelFinalized(ctx context.Context, task db.
// ClaimTask atomically claims the next queued task for an agent on its current
// runtime, respecting max_concurrent_tasks.
func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.AgentTaskQueue, error) {
- return s.claimTask(ctx, agentID, pgtype.UUID{})
+ return s.claimTask(ctx, agentID, pgtype.UUID{}, claimScope{claimPath: claimPathAgent})
}
// claimTask is the runtime-scoped claim primitive used by daemon poll paths.
@@ -3548,14 +3548,16 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.A
// agent's currently bound runtime. Scoping the SQL claim itself prevents an
// offline candidate on runtime A from causing the same agent's task on runtime
// B to be dispatched and then dropped by the caller's runtime guard.
-func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {
+func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.UUID, scope claimScope) (*db.AgentTaskQueue, error) {
start := time.Now()
outcome := "unknown"
var getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs int64
var claimed *db.AgentTaskQueue
var reclaimCheckAfter time.Time
+ var decisionDetail claimDecisionDetail
defer func() {
s.maybeLogClaimSlow(agentID, outcome, start, getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs)
+ s.recordClaimDecision(agentID, runtimeID, outcome, scope, decisionDetail)
}()
err := s.runInTx(ctx, func(qtx *db.Queries) error {
@@ -3592,7 +3594,7 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.U
return fmt.Errorf("count running tasks: %w", err)
}
if running >= int64(agent.MaxConcurrentTasks) {
- slog.Debug("task claim: no capacity", "agent_id", util.UUIDToString(agentID), "running", running, "max", agent.MaxConcurrentTasks)
+ decisionDetail = claimDecisionDetail{running: running, maxConcurrent: int64(agent.MaxConcurrentTasks)}
outcome = "no_capacity"
return nil
}
@@ -3608,7 +3610,6 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.U
claimAgentMs = time.Since(t0).Milliseconds()
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
- slog.Debug("task claim: no tasks available", "agent_id", util.UUIDToString(agentID))
outcome = "no_tasks"
return nil
}
@@ -3708,6 +3709,7 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
runtimeKey := util.UUIDToString(runtimeID)
if err := s.PromoteDueDeferredTasksForRuntime(ctx, runtimeID); err != nil {
outcome = "error_promote_deferred"
+ s.recordClaimDecision(pgtype.UUID{}, runtimeID, outcome, claimScope{claimPath: claimPathRuntime}, claimDecisionDetail{})
return nil, err
}
@@ -3732,6 +3734,7 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
)
s.trackTaskForReclaim(stale, reclaimCheckAfter)
outcome = "reclaimed_dispatched"
+ s.recordClaimDecision(stale.AgentID, runtimeID, outcome, claimScope{claimPath: claimPathRuntime}, claimDecisionDetail{})
claimedFlag = true
slog.Info("stale dispatched task reclaimed",
"task_id", util.UUIDToString(stale.ID),
@@ -3742,6 +3745,7 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
}
if !errors.Is(err, pgx.ErrNoRows) {
outcome = "error_reclaim_dispatched"
+ s.recordClaimDecision(pgtype.UUID{}, runtimeID, outcome, claimScope{claimPath: claimPathRuntime}, claimDecisionDetail{})
return nil, fmt.Errorf("reclaim stale dispatched task: %w", err)
}
s.ReclaimCheck.MarkChecked(
@@ -3754,6 +3758,7 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
if s.EmptyClaim.IsEmpty(ctx, runtimeKey) {
outcome = "empty_cache_hit"
+ s.recordClaimDecision(pgtype.UUID{}, runtimeID, outcome, claimScope{claimPath: claimPathRuntime}, claimDecisionDetail{})
return nil, nil
}
@@ -3771,17 +3776,26 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
listCount = len(tasks)
if err != nil {
outcome = "error_list"
+ s.recordClaimDecision(pgtype.UUID{}, runtimeID, outcome, claimScope{claimPath: claimPathRuntime}, claimDecisionDetail{})
return nil, fmt.Errorf("list queued claim candidates: %w", err)
}
if len(tasks) == 0 {
s.EmptyClaim.MarkEmpty(ctx, runtimeKey, preSelectVersion)
outcome = "empty_db"
+ s.recordClaimDecision(pgtype.UUID{}, runtimeID, outcome, claimScope{claimPath: claimPathRuntime}, claimDecisionDetail{})
return nil, nil
}
loopStart := time.Now()
triedAgents := map[string]struct{}{}
+ // Candidate rows per agent, counted before the loop so each claimTask call
+ // can report whether the runtime saw work for that agent (the #8551
+ // attribution split between candidates_blocked and no_candidates).
+ candidatesByAgent := make(map[string]int, len(tasks))
+ for i := range tasks {
+ candidatesByAgent[util.UUIDToString(tasks[i].AgentID)]++
+ }
var claimed *db.AgentTaskQueue
for _, candidate := range tasks {
agentKey := util.UUIDToString(candidate.AgentID)
@@ -3791,7 +3805,10 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
triedAgents[agentKey] = struct{}{}
tried++
- task, err := s.claimTask(ctx, candidate.AgentID, runtimeID)
+ task, err := s.claimTask(ctx, candidate.AgentID, runtimeID, claimScope{
+ claimPath: claimPathRuntime,
+ candidates: candidatesByAgent[agentKey],
+ })
if err != nil {
loopMs = time.Since(loopStart).Milliseconds()
outcome = "error_claim"
@@ -3806,6 +3823,15 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
if claimed != nil {
claimedFlag = true
outcome = "claimed"
+ } else if len(tasks) > 0 {
+ // Work was visible for at least one agent but every claim attempt lost
+ // (capacity cap, SQL serialization fence, or runtime binding). This is
+ // the key signal for attributing queue waits to a fence rather than to
+ // an empty queue (#8551).
+ slog.Debug("claim poll exhausted candidates without a claim",
+ "runtime_id", runtimeKey,
+ "candidates", len(tasks),
+ )
}
return claimed, nil
@@ -4017,6 +4043,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
slog.Info("promote deferred tasks (batch): slot taken by a concurrent enqueue, skipping this tick")
promoted = nil
} else if err != nil {
+ s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "error_promote_deferred", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})
return nil, fmt.Errorf("promote deferred tasks: %w", err)
}
for _, task := range promoted {
@@ -4052,6 +4079,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
MaxTasks: int32(maxTasks),
})
if err != nil {
+ s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "error_reclaim_dispatched", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})
return nil, fmt.Errorf("reclaim stale dispatched tasks: %w", err)
}
// The UPDATE's fixed setup/locking cost dominates array width. Query and
@@ -4067,6 +4095,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
for i := range reclaimed {
s.trackTaskForReclaim(reclaimed[i], reclaimCheckAfter)
claimed = append(claimed, reclaimed[i])
+ s.recordClaimDecision(reclaimed[i].AgentID, reclaimed[i].RuntimeID, "reclaimed_dispatched", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})
slog.Info("stale dispatched task reclaimed (batch)",
"task_id", util.UUIDToString(reclaimed[i].ID),
"runtime_id", util.UUIDToString(reclaimed[i].RuntimeID),
@@ -4089,12 +4118,15 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
nonEmpty = append(nonEmpty, rid)
}
if len(nonEmpty) == 0 {
+ s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "empty_cache_hit", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})
+ slog.Debug("batch claim: all runtimes empty-cached", "runtimes", len(uniqueIDs))
return claimed, nil
}
// 4. One candidate SELECT across the non-empty set.
candidates, err := s.Queries.ListQueuedClaimCandidatesByRuntimes(ctx, nonEmpty)
if err != nil {
+ s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "error_list", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})
// Steps 2/6 commit reclaimed/claimed tasks in their own transactions,
// so `claimed` may already hold tasks dispatched server-side. Dropping
// them with a 500 makes the daemon HTTP-fall-back and claim a SECOND
@@ -4125,12 +4157,30 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
s.EmptyClaim.MarkEmpty(ctx, key, versions[key])
}
}
+ if len(candidates) == 0 {
+ // Poll-level decision: the candidate query saw nothing claimable for
+ // any runtime in the batch (it already filters wakeup validity and
+ // agent/runtime binding, so this is about visible candidates, not
+ // about the queue being empty).
+ s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "empty_db", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})
+ return claimed, nil
+ }
// 6. Claim per distinct agent through the runtime-scoped helper, preserving
// per-(issue, agent) serialization, capacity caps, and dispatch side effects.
triedAgents := make(map[string]struct{}, len(candidates))
+ // Candidate rows per agent for the claim-decision scope; see the singular
+ // path above for why it is counted before the loop.
+ candidatesByAgent := make(map[string]int, len(candidates))
+ for i := range candidates {
+ candidatesByAgent[util.UUIDToString(candidates[i].AgentID)]++
+ }
for i := range candidates {
if len(claimed) >= maxTasks {
+ slog.Debug("batch claim: reached max tasks",
+ "claimed", len(claimed),
+ "candidates_remaining", len(candidates)-i,
+ )
break
}
agentKey := util.UUIDToString(candidates[i].AgentID)
@@ -4139,7 +4189,10 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
}
triedAgents[agentKey] = struct{}{}
- task, err := s.claimTask(ctx, candidates[i].AgentID, candidates[i].RuntimeID)
+ task, err := s.claimTask(ctx, candidates[i].AgentID, candidates[i].RuntimeID, claimScope{
+ claimPath: claimPathBatch,
+ candidates: candidatesByAgent[agentKey],
+ })
if err != nil {
// Each scoped claim commits in its own transaction, so earlier
// iterations (and step-2 reclaims) are already dispatched
@@ -4160,6 +4213,10 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
// a defensive contract check so a future query change cannot route work
// to a runtime this daemon does not host.
if _, ok := runtimeInSet[util.UUIDToString(task.RuntimeID)]; !ok {
+ slog.Debug("batch claim: skipping claimed task outside requested runtime set",
+ "task_id", util.UUIDToString(task.ID),
+ "runtime_id", util.UUIDToString(task.RuntimeID),
+ )
continue
}
claimed = append(claimed, *task)
diff --git a/server/internal/service/task_claim_decision.go b/server/internal/service/task_claim_decision.go
new file mode 100644
index 0000000000..2b5c9941fd
--- /dev/null
+++ b/server/internal/service/task_claim_decision.go
@@ -0,0 +1,187 @@
+package service
+
+import (
+ "log/slog"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// Claim decision observability (#8551, queue-wait attribution).
+//
+// Every daemon poll decides whether a task is dispatched, skipped, or left
+// waiting, and until now most of those decisions were invisible: claimTask's
+// internal outcome string only surfaced through the >=300ms slow log, two
+// outcomes had scattered debug lines, and no_runtime / runtime_mismatch had
+// nothing at all. The worst blind spot is outcome=no_tasks — it collapses the
+// ClaimAgentTask SQL fences (wakeup gate, runtime liveness, per-(issue, agent)
+// serialization, rebind fence) into one value even though the caller's
+// candidate list knew whether work was visible at all.
+//
+// recordClaimDecision below is the single funnel for this. Counting unit: one
+// increment per claim attempt (one claimTask call, from its defer) plus one
+// per poll-level decision that never enters claimTask — a poll
+// short-circuiting on the empty cache, a poll whose candidate query returns
+// nothing claimable, each recovered stale-dispatched task, and each poll-level
+// error exit. Poll decisions and claim attempts are distinct outcomes, so the
+// two layers cannot double-count the same decision. Nothing here changes any
+// decision — the outcomes mirror strings the claim paths already produce, and
+// the mapping is pure.
+//
+// Reason semantics are deliberately evidence-bounded. The candidate queries
+// already filter on wakeup validity and agent/runtime binding, so an empty
+// result only proves no *visible* candidates — never that the queue holds no
+// tasks (reason: no_visible_candidates). Conversely, candidates observed with
+// a no_tasks outcome proves only that no task was claimed on this attempt —
+// the exact cause (a SQL fence versus another request winning the row) is
+// unknown (reason: candidates_unclaimed).
+
+// Outcomes produced inside claimTask, shared by every caller.
+const (
+ claimOutcomeClaimed = "claimed"
+ claimOutcomeNoTasks = "no_tasks"
+ claimOutcomeNoCapacity = "no_capacity"
+ claimOutcomeNoRuntime = "no_runtime"
+ claimOutcomeRuntimeMismatch = "runtime_mismatch"
+ claimOutcomeErrorGetAgent = "error_get_agent"
+ claimOutcomeErrorCountRunning = "error_count_running"
+ claimOutcomeErrorClaim = "error_claim"
+ claimOutcomeErrorReanchorChatInput = "error_reanchor_chat_input"
+ claimOutcomeErrorTransaction = "error_transaction"
+)
+
+// Outcomes of claim polls (ClaimTaskForRuntime and the batch
+// ClaimTasksForRuntimes) that return before claimTask is ever entered, plus
+// stale-dispatch recovery. claimOutcomeNoTask is ClaimTaskForRuntime's initial
+// slow-log outcome; no funnel call records it.
+const (
+ claimOutcomeNoTask = "no_task"
+ claimOutcomeEmptyCacheHit = "empty_cache_hit"
+ claimOutcomeEmptyDB = "empty_db"
+ claimOutcomeReclaimedDispatched = "reclaimed_dispatched"
+ claimOutcomeErrorPromoteDeferred = "error_promote_deferred"
+ claimOutcomeErrorReclaimDispatched = "error_reclaim_dispatched"
+ claimOutcomeErrorList = "error_list"
+)
+
+// Reasons narrow an outcome into the cause a dashboard or debug-log reader
+// cares about, stating only what the evidence supports. The
+// candidates_unclaimed vs no_visible_candidates split inside no_tasks is the
+// #8551 signal: the former says work was visible yet nothing was claimed on
+// this attempt (cause unknown — fence or lost race), the latter says the
+// candidate query itself saw nothing claimable.
+const (
+ claimReasonClaimed = "claimed"
+ claimReasonNoVisibleCandidates = "no_visible_candidates"
+ claimReasonCandidatesUnclaimed = "candidates_unclaimed"
+ claimReasonUnknownCandidates = "unknown_candidates"
+ claimReasonAgentConcurrencyCap = "agent_concurrency_cap"
+ claimReasonAgentUnbound = "agent_unbound"
+ claimReasonAgentRebound = "agent_rebound"
+ claimReasonEmptyCache = "empty_cache"
+ claimReasonStaleDispatchRecover = "stale_dispatch_recovered"
+ claimReasonError = "error"
+)
+
+// Claim poll paths, as seen by the counter's claim_path label. Distinct from
+// the task-origin `source` label used by the other multica_agent_task_*
+// metrics: those classify where a task came from (issue, chat, autopilot),
+// while this classifies which poll path made the decision.
+const (
+ claimPathAgent = "agent" // ClaimTask (agent-triggered claim)
+ claimPathRuntime = "runtime" // ClaimTaskForRuntime (single-runtime poll)
+ claimPathBatch = "batch" // ClaimTasksForRuntimes (machine-level batch)
+)
+
+// claimScope is informational context the caller already holds. candidates is
+// how many rows in the caller's candidate list belong to the agent being
+// claimed; the agent path has no list, so it reports zero and its no_tasks
+// outcome maps to unknown_candidates rather than a definitive
+// no_visible_candidates.
+type claimScope struct {
+ claimPath string
+ candidates int
+}
+
+// claimDecisionDetail carries the capacity numbers behind a no_capacity
+// decision. Left zero for every other outcome.
+type claimDecisionDetail struct {
+ running int64
+ maxConcurrent int64
+}
+
+// claimReasonFor maps an outcome onto the closed reason enum above. Unknown
+// inputs degrade to "error" rather than minting a new series: a value nobody
+// classified is not evidence of a healthy path.
+func claimReasonFor(outcome string, scope claimScope) string {
+ switch outcome {
+ case claimOutcomeNoTasks:
+ if scope.candidates > 0 {
+ return claimReasonCandidatesUnclaimed
+ }
+ if scope.claimPath == claimPathAgent {
+ return claimReasonUnknownCandidates
+ }
+ return claimReasonNoVisibleCandidates
+ case claimOutcomeNoCapacity:
+ return claimReasonAgentConcurrencyCap
+ case claimOutcomeRuntimeMismatch:
+ return claimReasonAgentRebound
+ case claimOutcomeNoRuntime:
+ return claimReasonAgentUnbound
+ case claimOutcomeClaimed:
+ return claimReasonClaimed
+ case claimOutcomeEmptyCacheHit:
+ return claimReasonEmptyCache
+ case claimOutcomeEmptyDB:
+ return claimReasonNoVisibleCandidates
+ case claimOutcomeReclaimedDispatched:
+ return claimReasonStaleDispatchRecover
+ default:
+ // Every error_* outcome, and anything unrecognized.
+ return claimReasonError
+ }
+}
+
+// normalizeClaimPath keeps the counter's claim_path label a closed enum:
+// values outside the three known poll paths land on "other".
+func normalizeClaimPath(claimPath string) string {
+ switch claimPath {
+ case claimPathAgent, claimPathRuntime, claimPathBatch:
+ return claimPath
+ default:
+ return "other"
+ }
+}
+
+// recordClaimDecision is the single observability funnel for the claim path:
+// metric first, then log, so a logging problem can never lose the counter.
+// runtimeID may be the zero UUID (the agent path passes no runtime).
+//
+// The empty-poll outcomes (empty_cache_hit, empty_db) fire on every idle
+// poll — the hottest path in the scheduler — so they are counted but
+// deliberately not logged; a debug line per idle poll would flood any
+// deployment running with debug logging enabled.
+func (s *TaskService) recordClaimDecision(agentID, runtimeID pgtype.UUID, outcome string, scope claimScope, detail claimDecisionDetail) {
+ scope.claimPath = normalizeClaimPath(scope.claimPath)
+ reason := claimReasonFor(outcome, scope)
+ if s.Metrics != nil {
+ s.Metrics.RecordClaimDecision(scope.claimPath, outcome, reason)
+ }
+ if outcome == claimOutcomeEmptyCacheHit || outcome == claimOutcomeEmptyDB {
+ return
+ }
+ attrs := []any{
+ "outcome", outcome,
+ "reason", reason,
+ "claim_path", scope.claimPath,
+ "agent_id", util.UUIDToString(agentID),
+ "runtime_id", util.UUIDToString(runtimeID),
+ "candidates", scope.candidates,
+ }
+ if outcome == claimOutcomeNoCapacity {
+ attrs = append(attrs, "running", detail.running, "max", detail.maxConcurrent)
+ }
+ slog.Debug("task claim decision", attrs...)
+}
diff --git a/server/internal/service/task_claim_decision_db_test.go b/server/internal/service/task_claim_decision_db_test.go
new file mode 100644
index 0000000000..3316becdff
--- /dev/null
+++ b/server/internal/service/task_claim_decision_db_test.go
@@ -0,0 +1,254 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// DB-backed coverage for the claim decision funnel. These tests follow the
+// package's sharedTestPool convention: without a reachable Postgres they skip,
+// so `go test ./...` stays usable without a database. Every case builds its
+// own fixture; testutil.Insert registers reverse-order cleanup so cases never
+// share rows.
+
+// claimDecisionFixture is one workspace / runtime / agent / issue plus a
+// TaskService wired to real metrics, so each case can assert exactly which
+// (source, outcome, reason) series the claim path incremented.
+type claimDecisionFixture struct {
+ svc *TaskService
+ metrics *obsmetrics.BusinessMetrics
+ fx *testutil.Fixture
+ pool *pgxpool.Pool
+ agentID pgtype.UUID
+ runtimeID pgtype.UUID
+ issueID string
+}
+
+func newClaimDecisionFixture(t *testing.T, maxConcurrent int) *claimDecisionFixture {
+ t.Helper()
+
+ pool := sharedTestPool(t)
+ bootstrap := testutil.New(pool, "", "")
+ suffix := time.Now().UnixNano()
+ ownerID := bootstrap.User(t,
+ fmt.Sprintf("claim-decision-owner-%d", suffix),
+ fmt.Sprintf("claim-decision-owner-%[email protected]", suffix),
+ )
+ workspaceID := bootstrap.Workspace(t,
+ fmt.Sprintf("claim-decision-%d", suffix),
+ fmt.Sprintf("claim-decision-%d", suffix),
+ )
+ fx := testutil.New(pool, workspaceID, ownerID)
+ fx.Member(t, workspaceID, ownerID, "owner")
+ runtimeID := fx.Runtime(t, "claim-decision-runtime", testutil.Cols{
+ "visibility": "public",
+ "owner_id": ownerID,
+ })
+ agentID := fx.Agent(t, "claim-decision-agent", runtimeID, testutil.Cols{
+ "owner_id": ownerID,
+ "max_concurrent_tasks": maxConcurrent,
+ })
+ issueID := fx.Issue(t, "claim decision issue")
+
+ m := obsmetrics.NewBusinessMetrics()
+ svc := NewTaskService(db.New(pool), pool, nil, events.New())
+ svc.Metrics = m
+
+ return &claimDecisionFixture{
+ svc: svc,
+ metrics: m,
+ fx: fx,
+ pool: pool,
+ agentID: util.MustParseUUID(agentID),
+ runtimeID: util.MustParseUUID(runtimeID),
+ issueID: issueID,
+ }
+}
+
+// insertTask queues a task for the fixture agent on the fixture runtime.
+func (f *claimDecisionFixture) insertTask(t *testing.T, status string) string {
+ t.Helper()
+
+ cols := testutil.Cols{
+ "runtime_id": util.UUIDToString(f.runtimeID),
+ "issue_id": f.issueID,
+ "status": status,
+ }
+ if status == "dispatched" {
+ cols["dispatched_at"] = testutil.Raw("now() - interval '10 minutes'")
+ cols["prepare_lease_expires_at"] = testutil.Raw("now() - interval '1 minute'")
+ }
+ return f.fx.Task(t, util.UUIDToString(f.agentID), cols)
+}
+
+// TestClaimDecisionDBClaimedRuntimePoll covers the happy path: a queued task,
+// an agent with capacity, and a healthy runtime produce exactly one
+// (runtime, claimed, claimed) increment from claimTask's defer.
+func TestClaimDecisionDBClaimedRuntimePoll(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+
+ claimed, err := f.svc.ClaimTaskForRuntime(context.Background(), f.runtimeID)
+ if err != nil {
+ t.Fatalf("ClaimTaskForRuntime: %v", err)
+ }
+ if claimed == nil {
+ t.Fatal("ClaimTaskForRuntime returned nil, want the queued task")
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathRuntime, claimOutcomeClaimed, claimReasonClaimed); got != 1 {
+ t.Fatalf("claim_decision_total{runtime,claimed,claimed} = %v, want 1", got)
+ }
+}
+
+// TestClaimDecisionDBNoCapacity covers the concurrency cap: max_concurrent_tasks=0
+// leaves the task visible to the candidate list, so the claim attempt runs and
+// is rejected by the capacity check rather than by the queue being empty.
+func TestClaimDecisionDBNoCapacity(t *testing.T) {
+ f := newClaimDecisionFixture(t, 0)
+ f.insertTask(t, "queued")
+
+ claimed, err := f.svc.ClaimTaskForRuntime(context.Background(), f.runtimeID)
+ if err != nil {
+ t.Fatalf("ClaimTaskForRuntime: %v", err)
+ }
+ if claimed != nil {
+ t.Fatalf("ClaimTaskForRuntime claimed %s, want nil", util.UUIDToString(claimed.ID))
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathRuntime, claimOutcomeNoCapacity, claimReasonAgentConcurrencyCap); got != 1 {
+ t.Fatalf("claim_decision_total{runtime,no_capacity,agent_concurrency_cap} = %v, want 1", got)
+ }
+}
+
+// TestClaimDecisionDBCandidatesUnclaimed is the core #8551 scenario: the
+// queued task stays visible to the candidate list, yet the claim still
+// returns nothing, so the wait belongs to an unclaimed-attempt rather than to
+// an empty candidate set.
+//
+// The fence exercised here is runtime liveness: the candidate query's
+// authorization fence checks binding and visibility but not liveness, while
+// ClaimAgentTask additionally requires r.status='online' with a fresh
+// heartbeat. Marking the runtime offline after enqueue therefore leaves the
+// candidate visible while the claim is rejected — outcome=no_tasks must be
+// attributed to candidates_unclaimed (candidates observed, nothing claimed;
+// the exact cause is unknown from the Go side). The same collapse hides the
+// other SQL fences (wakeup gate, per-(issue, agent) serialization, rebind),
+// and a lost race against another claimer looks identical — which is why the
+// reason states only what the evidence supports.
+func TestClaimDecisionDBCandidatesUnclaimed(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+
+ if _, err := f.pool.Exec(context.Background(),
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, f.runtimeID,
+ ); err != nil {
+ t.Fatalf("take runtime offline: %v", err)
+ }
+
+ claimed, err := f.svc.ClaimTaskForRuntime(context.Background(), f.runtimeID)
+ if err != nil {
+ t.Fatalf("ClaimTaskForRuntime: %v", err)
+ }
+ if claimed != nil {
+ t.Fatalf("ClaimTaskForRuntime claimed %s, want nil", util.UUIDToString(claimed.ID))
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathRuntime, claimOutcomeNoTasks, claimReasonCandidatesUnclaimed); got != 1 {
+ t.Fatalf("claim_decision_total{runtime,no_tasks,candidates_unclaimed} = %v, want 1", got)
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathRuntime, claimOutcomeNoTasks, claimReasonNoVisibleCandidates); got != 0 {
+ t.Fatalf("claim_decision_total{runtime,no_tasks,no_visible_candidates} = %v, want 0", got)
+ }
+}
+
+// TestClaimDecisionDBEmptyQueue covers the idle poll: no candidates at all
+// produce outcome=empty_db (reason no_visible_candidates) from the poll-level
+// exit that never enters claimTask. The candidate query already filters
+// wakeup validity and agent/runtime binding, so the reason states only that
+// nothing was visible — not that the queue holds no tasks.
+func TestClaimDecisionDBEmptyQueue(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+
+ claimed, err := f.svc.ClaimTaskForRuntime(context.Background(), f.runtimeID)
+ if err != nil {
+ t.Fatalf("ClaimTaskForRuntime: %v", err)
+ }
+ if claimed != nil {
+ t.Fatalf("ClaimTaskForRuntime claimed %s, want nil", util.UUIDToString(claimed.ID))
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathRuntime, claimOutcomeEmptyDB, claimReasonNoVisibleCandidates); got != 1 {
+ t.Fatalf("claim_decision_total{runtime,empty_db,no_visible_candidates} = %v, want 1", got)
+ }
+}
+
+// TestClaimDecisionDBBatchClaimed covers the batch poll's happy path: one
+// queued task claimed through ClaimTasksForRuntimes increments the
+// (batch, claimed, claimed) series once via claimTask's defer.
+func TestClaimDecisionDBBatchClaimed(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+
+ claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)
+ if err != nil {
+ t.Fatalf("ClaimTasksForRuntimes: %v", err)
+ }
+ if len(claimed) != 1 {
+ t.Fatalf("ClaimTasksForRuntimes claimed %d tasks, want 1", len(claimed))
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathBatch, claimOutcomeClaimed, claimReasonClaimed); got != 1 {
+ t.Fatalf("claim_decision_total{batch,claimed,claimed} = %v, want 1", got)
+ }
+}
+
+// TestClaimDecisionDBBatchNoVisibleCandidates covers the batch poll's idle
+// exit: the candidate query returns nothing, so the poll records
+// (batch, empty_db, no_visible_candidates) without ever entering claimTask.
+func TestClaimDecisionDBBatchNoVisibleCandidates(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+
+ claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)
+ if err != nil {
+ t.Fatalf("ClaimTasksForRuntimes: %v", err)
+ }
+ if len(claimed) != 0 {
+ t.Fatalf("ClaimTasksForRuntimes claimed %d tasks, want 0", len(claimed))
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathBatch, claimOutcomeEmptyDB, claimReasonNoVisibleCandidates); got != 1 {
+ t.Fatalf("claim_decision_total{batch,empty_db,no_visible_candidates} = %v, want 1", got)
+ }
+}
+
+// TestClaimDecisionDBBatchCandidatesUnclaimed mirrors the singular-path
+// unclaimed scenario through the batch poll: the runtime goes offline after
+// enqueue, the candidate stays visible, and the claim attempt records
+// (batch, no_tasks, candidates_unclaimed).
+func TestClaimDecisionDBBatchCandidatesUnclaimed(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+
+ if _, err := f.pool.Exec(context.Background(),
+ `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, f.runtimeID,
+ ); err != nil {
+ t.Fatalf("take runtime offline: %v", err)
+ }
+
+ claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)
+ if err != nil {
+ t.Fatalf("ClaimTasksForRuntimes: %v", err)
+ }
+ if len(claimed) != 0 {
+ t.Fatalf("ClaimTasksForRuntimes claimed %d tasks, want 0", len(claimed))
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathBatch, claimOutcomeNoTasks, claimReasonCandidatesUnclaimed); got != 1 {
+ t.Fatalf("claim_decision_total{batch,no_tasks,candidates_unclaimed} = %v, want 1", got)
+ }
+}
diff --git a/server/internal/service/task_claim_decision_test.go b/server/internal/service/task_claim_decision_test.go
new file mode 100644
index 0000000000..3dcc8f6d4c
--- /dev/null
+++ b/server/internal/service/task_claim_decision_test.go
@@ -0,0 +1,183 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+)
+
+// This runs without a database: claimReasonFor, normalizeClaimPath, and the
+// metric funnel are pure functions over their arguments.
+
+// TestClaimDecisionReasonFor pins the outcome -> reason mapping, especially
+// the #8551 split inside no_tasks: candidates > 0 means work was visible and
+// nothing was claimed on this attempt (exact cause unknown), zero candidates
+// on a list-bearing path means the candidate query saw nothing claimable, and
+// the list-less agent path can only report "unknown".
+func TestClaimDecisionReasonFor(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ outcome string
+ scope claimScope
+ want string
+ }{
+ {name: "claimed stays claimed", outcome: claimOutcomeClaimed, scope: claimScope{claimPath: claimPathAgent}, want: claimReasonClaimed},
+ {name: "claimed via runtime poll", outcome: claimOutcomeClaimed, scope: claimScope{claimPath: claimPathRuntime, candidates: 3}, want: claimReasonClaimed},
+ {name: "no capacity maps to concurrency cap", outcome: claimOutcomeNoCapacity, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonAgentConcurrencyCap},
+ {name: "no runtime maps to unbound agent", outcome: claimOutcomeNoRuntime, scope: claimScope{claimPath: claimPathAgent}, want: claimReasonAgentUnbound},
+ {name: "runtime mismatch maps to rebound agent", outcome: claimOutcomeRuntimeMismatch, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonAgentRebound},
+
+ {name: "no tasks with candidates is unclaimed", outcome: claimOutcomeNoTasks, scope: claimScope{claimPath: claimPathRuntime, candidates: 1}, want: claimReasonCandidatesUnclaimed},
+ {name: "no tasks unclaimed on batch path", outcome: claimOutcomeNoTasks, scope: claimScope{claimPath: claimPathBatch, candidates: 2}, want: claimReasonCandidatesUnclaimed},
+ {name: "no tasks without candidates is nothing visible", outcome: claimOutcomeNoTasks, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonNoVisibleCandidates},
+ {name: "no tasks without candidates on batch", outcome: claimOutcomeNoTasks, scope: claimScope{claimPath: claimPathBatch}, want: claimReasonNoVisibleCandidates},
+ {name: "no tasks on agent path is unknown", outcome: claimOutcomeNoTasks, scope: claimScope{claimPath: claimPathAgent}, want: claimReasonUnknownCandidates},
+ {name: "agent path with candidates is still unclaimed", outcome: claimOutcomeNoTasks, scope: claimScope{claimPath: claimPathAgent, candidates: 1}, want: claimReasonCandidatesUnclaimed},
+
+ {name: "empty cache hit", outcome: claimOutcomeEmptyCacheHit, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonEmptyCache},
+ {name: "empty db means nothing visible", outcome: claimOutcomeEmptyDB, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonNoVisibleCandidates},
+ {name: "empty db on batch means nothing visible", outcome: claimOutcomeEmptyDB, scope: claimScope{claimPath: claimPathBatch}, want: claimReasonNoVisibleCandidates},
+ {name: "reclaimed dispatch", outcome: claimOutcomeReclaimedDispatched, scope: claimScope{claimPath: claimPathBatch}, want: claimReasonStaleDispatchRecover},
+
+ {name: "error get agent", outcome: claimOutcomeErrorGetAgent, scope: claimScope{claimPath: claimPathAgent}, want: claimReasonError},
+ {name: "error count running", outcome: claimOutcomeErrorCountRunning, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonError},
+ {name: "error claim", outcome: claimOutcomeErrorClaim, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonError},
+ {name: "error reanchor chat input", outcome: claimOutcomeErrorReanchorChatInput, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonError},
+ {name: "error transaction", outcome: claimOutcomeErrorTransaction, scope: claimScope{claimPath: claimPathBatch}, want: claimReasonError},
+ {name: "error promote deferred", outcome: claimOutcomeErrorPromoteDeferred, scope: claimScope{claimPath: claimPathBatch}, want: claimReasonError},
+ {name: "error reclaim dispatched", outcome: claimOutcomeErrorReclaimDispatched, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonError},
+ {name: "error list", outcome: claimOutcomeErrorList, scope: claimScope{claimPath: claimPathBatch}, want: claimReasonError},
+
+ // Unknown inputs degrade to "error" instead of minting a series.
+ {name: "unrecognized outcome", outcome: "no_task", scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonError},
+ {name: "bogus outcome", outcome: "surprise", scope: claimScope{claimPath: claimPathAgent}, want: claimReasonError},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ got := claimReasonFor(tt.outcome, tt.scope)
+ if got != tt.want {
+ t.Fatalf("claimReasonFor(%q, %+v) = %q, want %q", tt.outcome, tt.scope, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestClaimDecisionNormalizePath keeps the claim_path label a closed enum.
+func TestClaimDecisionNormalizePath(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ claimPath string
+ want string
+ }{
+ {claimPath: claimPathAgent, want: claimPathAgent},
+ {claimPath: claimPathRuntime, want: claimPathRuntime},
+ {claimPath: claimPathBatch, want: claimPathBatch},
+ {claimPath: "", want: "other"},
+ {claimPath: "daemon", want: "other"},
+ {claimPath: "AGENT", want: "other"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.claimPath, func(t *testing.T) {
+ t.Parallel()
+ if got := normalizeClaimPath(tt.claimPath); got != tt.want {
+ t.Fatalf("normalizeClaimPath(%q) = %q, want %q", tt.claimPath, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestClaimDecisionNilMetricsIsSafe covers self-hosted deployments and tests
+// that run without the metrics listener: the funnel must not panic and must
+// still skip the (suppressed) hot-path log branches.
+func TestClaimDecisionNilMetricsIsSafe(t *testing.T) {
+ t.Parallel()
+
+ svc := &TaskService{}
+ for _, outcome := range []string{
+ claimOutcomeClaimed,
+ claimOutcomeNoTasks,
+ claimOutcomeNoCapacity,
+ claimOutcomeNoRuntime,
+ claimOutcomeRuntimeMismatch,
+ claimOutcomeEmptyCacheHit,
+ claimOutcomeEmptyDB,
+ claimOutcomeErrorClaim,
+ } {
+ svc.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, outcome, claimScope{claimPath: claimPathRuntime, candidates: 1}, claimDecisionDetail{running: 2, maxConcurrent: 2})
+ }
+}
+
+// TestClaimDecisionIncrementsLabeledSeries verifies the funnel lands each
+// decision on exactly its (claim_path, outcome, reason) series, that an
+// unclassified path is normalized to "other", and that a never-fired
+// prewarmed series still reads as zero rather than being absent.
+func TestClaimDecisionIncrementsLabeledSeries(t *testing.T) {
+ t.Parallel()
+
+ m := obsmetrics.NewBusinessMetrics()
+ svc := &TaskService{Metrics: m}
+
+ svc.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, claimOutcomeNoTasks, claimScope{claimPath: claimPathRuntime, candidates: 2}, claimDecisionDetail{})
+ svc.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, claimOutcomeNoTasks, claimScope{claimPath: claimPathAgent}, claimDecisionDetail{})
+ svc.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, claimOutcomeNoCapacity, claimScope{claimPath: claimPathAgent}, claimDecisionDetail{running: 3, maxConcurrent: 3})
+ svc.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, claimOutcomeEmptyDB, claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})
+ svc.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, claimOutcomeErrorList, claimScope{claimPath: "daemon"}, claimDecisionDetail{})
+
+ tests := []struct {
+ claimPath, outcome, reason string
+ want float64
+ }{
+ {claimPathRuntime, claimOutcomeNoTasks, claimReasonCandidatesUnclaimed, 1},
+ {claimPathRuntime, claimOutcomeNoTasks, claimReasonNoVisibleCandidates, 0},
+ {claimPathAgent, claimOutcomeNoTasks, claimReasonUnknownCandidates, 1},
+ {claimPathAgent, claimOutcomeNoCapacity, claimReasonAgentConcurrencyCap, 1},
+ {claimPathBatch, claimOutcomeEmptyDB, claimReasonNoVisibleCandidates, 1},
+ // An unknown path is normalized to "other" rather than minting a
+ // per-call-site series.
+ {"other", claimOutcomeErrorList, claimReasonError, 1},
+ {claimPathRuntime, claimOutcomeErrorList, claimReasonError, 0},
+ // Prewarmed series that have not fired read as zero, including the
+ // batch poll exits.
+ {claimPathBatch, claimOutcomeNoTasks, claimReasonCandidatesUnclaimed, 0},
+ {claimPathBatch, claimOutcomeReclaimedDispatched, claimReasonStaleDispatchRecover, 0},
+ {claimPathBatch, claimOutcomeEmptyCacheHit, claimReasonEmptyCache, 0},
+ {claimPathBatch, claimOutcomeErrorPromoteDeferred, claimReasonError, 0},
+ {claimPathRuntime, claimOutcomeReclaimedDispatched, claimReasonStaleDispatchRecover, 0},
+ }
+ for _, tt := range tests {
+ t.Run(tt.claimPath+"/"+tt.outcome+"/"+tt.reason, func(t *testing.T) {
+ t.Parallel()
+ if got := claimDecisionCount(t, m, tt.claimPath, tt.outcome, tt.reason); got != tt.want {
+ t.Fatalf("claim_decision_total{%s,%s,%s} = %v, want %v", tt.claimPath, tt.outcome, tt.reason, got, tt.want)
+ }
+ })
+ }
+}
+
+// ---- helpers ---------------------------------------------------------------
+
+// claimDecisionCount reads one (claim_path, outcome, reason) series of the
+// claim decision counter out of a freshly gathered registry.
+func claimDecisionCount(t *testing.T, m *obsmetrics.BusinessMetrics, claimPath, outcome, reason string) float64 {
+ t.Helper()
+
+ fam := obsmetrics.GatherForTest(t, m)["multica_agent_task_claim_decision_total"]
+ if fam == nil {
+ t.Fatalf("multica_agent_task_claim_decision_total not registered")
+ }
+ for _, mtr := range fam.GetMetric() {
+ if labelValue(mtr, "claim_path") == claimPath && labelValue(mtr, "outcome") == outcome && labelValue(mtr, "reason") == reason {
+ return mtr.GetCounter().GetValue()
+ }
+ }
+ t.Fatalf("no sample for %s/%s/%s", claimPath, outcome, reason)
+ return 0
+}