Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(server): introduce pkg/taskfailure classifier and switch in-flight failure_reason writes (MUL-2946) (#3693)
Multica Eve10afd1af1b3a
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 28c473992d..6789dd40c1 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -19,6 +19,7 @@ import ("github.com/multica-ai/multica/server/internal/daemon/execenv""github.com/multica-ai/multica/server/internal/daemon/repocache""github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/taskfailure")// ErrRepoNotConfigured is returned by ensureRepoReady when the requested repo@@ -2141,7 +2142,15 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {if err := d.client.StartTask(ctx, task.ID); err != nil {taskLog.Error("start task failed", "error", err)- if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error()), "", "", "agent_error"); failErr != nil {+ startErrMsg := fmt.Sprintf("start task failed: %s", err.Error())+ // MUL-2946: classify the wrapper error so the failure_reason+ // column lands in the canonical refined taxonomy rather than+ // the legacy coarse "agent_error" bucket. A start-task failure+ // most commonly surfaces as ReasonAgentUnknown (no rule+ // matches "start task failed: <…>"), but a future provider /+ // network blip in the wrapper layer would still classify+ // correctly without us touching this site.+ if failErr := d.client.FailTask(ctx, task.ID, startErrMsg, "", "", taskfailure.Classify(startErrMsg).String()); failErr != nil {taskLog.Error("fail task after start error", "error", failErr)}return@@ -2196,7 +2205,11 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {taskLog.Error("task failed", "error", err)// runTask returned without a TaskResult, so we don't have a SessionID// to forward — best we can do is record the failure.- if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "agent_error"); failErr != nil {+ // MUL-2946: route the bare error string through the canonical+ // classifier so the failure_reason column reflects the actual+ // shape of the failure (provider 5xx, network, process crash,+ // …) rather than the coarse legacy "agent_error" bucket.+ if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", taskfailure.Classify(err.Error()).String()); failErr != nil {taskLog.Error("fail task callback failed", "error", failErr)}return@@ -2387,16 +2400,35 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tasreturn}taskLog.Error("complete task rejected by server, falling back to fail", "error", err)- if failErr := d.client.FailTask(ctx, taskID, fmt.Sprintf("complete task failed: %s", err.Error()), result.SessionID, result.WorkDir, "agent_error"); failErr != nil {+ // MUL-2946: this fallback fires when a server-side complete+ // callback was permanently rejected (4xx other than 408/429)+ // — the agent itself succeeded, so the err here describes the+ // server response rather than an agent failure. The classifier+ // is unlikely to match anything in the server's error text and+ // will land at ReasonAgentUnknown ("agent_error.unknown"),+ // which is the canonical replacement for the legacy+ // "agent_error" coarse bucket.+ fallbackErrMsg := fmt.Sprintf("complete task failed: %s", err.Error())+ if failErr := d.client.FailTask(ctx, taskID, fallbackErrMsg, result.SessionID, result.WorkDir, taskfailure.Classify(fallbackErrMsg).String()); failErr != nil {taskLog.Error("fail task fallback also failed", "error", failErr)}default:failureReason := result.FailureReasonif failureReason == "" {if result.Status == "cancelled" {+ // "cancelled" is a deliberate non-failure terminal+ // state masquerading as a failure_reason — preserved+ // outside the canonical taxonomy so the UI can render+ // it differently from a real failure.failureReason = "cancelled"} else {- failureReason = "agent_error"+ // MUL-2946: classify the agent's comment text so the+ // failure_reason lands in the refined taxonomy+ // (provider_auth_or_access, context_overflow,+ // process_failure, …) instead of the legacy coarse+ // "agent_error" bucket. Empty comment lands in+ // ReasonAgentUnknown.+ failureReason = taskfailure.Classify(result.Comment).String()}}taskLog.Info("task did not complete, reporting failure", "status", result.Status, "failure_reason", failureReason)@@ -3011,6 +3043,18 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot itaskLog.Warn("agent failed with poisoned API error, classifying as blocked","failure_reason", failureReason,)+ } else {+ // MUL-2946: classifyPoisonedError only matches the+ // session-poisoning Anthropic 400 shape. Everything else+ // falls through to taskfailure.Classify, which maps the+ // raw error string to one of the 14 agent_error.*+ // sub-reasons (provider auth, capacity, context overflow,+ // runner crash, …) or to ReasonAgentUnknown. This keeps+ // the failure_reason column in the canonical refined+ // taxonomy at write time instead of waiting on the+ // MUL-1949 offline backfill to re-classify after the+ // fact.+ failureReason = taskfailure.Classify(errMsg).String()}return TaskResult{Status: "blocked",diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 9fd704f35e..7f7044787c 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1719,32 +1719,49 @@ func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {cases := []struct {name stringstatus string+ comment stringfailureReasonIn stringwantFailureReason string}{{name: "blocked with explicit reason preserves it",status: "blocked",+ comment: "rate limit reached",failureReasonIn: "iteration_limit",wantFailureReason: "iteration_limit",},{- name: "blocked without reason defaults to agent_error",+ // MUL-2946: when the daemon doesn't supply a refined+ // reason, the comment text is run through+ // taskfailure.Classify so the failure_reason column+ // lands in the canonical refined taxonomy instead of+ // the legacy "agent_error" coarse bucket.+ name: "blocked without reason classifies comment as rate-limit",status: "blocked",+ comment: "rate limit reached",failureReasonIn: "",- wantFailureReason: "agent_error",+ wantFailureReason: "agent_error.provider_capacity_or_rate_limit",},{- name: "cancelled defaults to cancelled reason",+ name: "blocked without reason and unrecognized comment lands in agent_error.unknown",+ status: "blocked",+ comment: "the agent gave up for reasons we don't recognize",+ failureReasonIn: "",+ wantFailureReason: "agent_error.unknown",+ },+ {+ name: "cancelled defaults to cancelled reason regardless of comment",status: "cancelled",+ comment: "rate limit reached",failureReasonIn: "",wantFailureReason: "cancelled",},{- name: "unknown status fails closed",+ name: "unknown status routes through classifier",status: "weird_new_status",+ comment: "rate limit reached",failureReasonIn: "",- wantFailureReason: "agent_error",+ wantFailureReason: "agent_error.provider_capacity_or_rate_limit",},}@@ -1757,7 +1774,7 @@ func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}d.reportTaskResult(context.Background(), "task-x", TaskResult{Status: tc.status,- Comment: "rate limit reached",+ Comment: tc.comment,SessionID: "ses-x",WorkDir: "/tmp/x",FailureReason: tc.failureReasonIn,@@ -1768,7 +1785,7 @@ func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {if rec.path != "/api/daemon/tasks/task-x/fail" {t.Fatalf("expected /fail endpoint for status=%q, got %s", tc.status, rec.path)}- if rec.payload["error"] != "rate limit reached" {+ if rec.payload["error"] != tc.comment {t.Errorf("error body: got %v", rec.payload["error"])}if got := rec.payload["failure_reason"]; got != tc.wantFailureReason {diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.goindex 6757bb7509..d168bf6450 100644--- a/server/internal/daemon/poisoned.go+++ b/server/internal/daemon/poisoned.go@@ -4,6 +4,7 @@ import ("strings""github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/taskfailure")// FailureReason values for tasks whose session is "poisoned" — i.e.@@ -24,10 +25,18 @@ import (// stuck without agent progress. Resuming that Codex session can replay the// same stuck state, while a fresh manual rerun may succeed. Detected via// classifyResumeUnsafeTimeout.+//+// MUL-2946: ReasonIterationLimit and ReasonAPIInvalidRequest are aliased+// to the canonical taskfailure values so the daemon and the in-flight+// classifier (used by every other failure path) share a single source+// of truth. agent_fallback_message and codex_semantic_inactivity are+// pre-existing operational reasons not in the canonical 21 — kept as+// string literals here until a follow-up PR migrates them or extends+// the taxonomy.const (- FailureReasonIterationLimit = "iteration_limit"+ FailureReasonIterationLimit = string(taskfailure.ReasonIterationLimit)FailureReasonAgentFallbackMsg = "agent_fallback_message"- FailureReasonAPIInvalidRequest = "api_invalid_request"+ FailureReasonAPIInvalidRequest = string(taskfailure.ReasonAPIInvalidRequest)FailureReasonCodexSemanticInactivity = "codex_semantic_inactivity")diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 700ec6f874..5e6a42ed82 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -21,6 +21,7 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/redact"+ "github.com/multica-ai/multica/server/pkg/taskfailure")type TaskService struct {@@ -1194,8 +1195,23 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu// chat turn would silently start a brand-new session and lose memory.//// failureReason is a coarse classifier consumed by the auto-retry path.-// Pass "" when unknown (treated as 'agent_error').+// Pass "" when unknown — the server runs the raw error text through+// taskfailure.Classify so the persisted failure_reason still lands in+// the canonical refined taxonomy rather than the legacy "agent_error"+// coarse bucket. Daemon callers that already produced a refined reason+// (via classifyPoisonedError, the timeout / runtime classifier, etc.)+// will have their value preserved untouched.func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, failureReason string) (*db.AgentTaskQueue, error) {+ // MUL-2946: synthesise a refined reason from the error text whenever the+ // caller didn't supply one. This is the last write-path guard against+ // "agent_error" coarse rows ending up in agent_task_queue.failure_reason+ // — every other path either provides a classified reason directly+ // (sweepers writing 'queued_expired' / 'runtime_offline' / 'timeout'+ // / 'runtime_recovery' via SQL) or runs the daemon's classifyPoisonedError+ // + taskfailure.Classify chain.+ if failureReason == "" {+ failureReason = taskfailure.Classify(errMsg).String()+ }var task db.AgentTaskQueueif err := s.runInTx(ctx, func(qtx *db.Queries) error {t, err := qtx.FailAgentTask(ctx, db.FailAgentTaskParams{diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.gonew file mode 100644index 0000000000..e073a01256--- /dev/null+++ b/server/pkg/taskfailure/classify.go@@ -0,0 +1,229 @@+package taskfailure++import (+ "regexp"+ "strings"+)++// providerHTTP5xxRe matches a 3-digit number starting with 5 (5xx HTTP+// status code) that isn't surrounded by other digits. Mirrors the SQL+// regex `(^|[^0-9])5[0-9][0-9]([^0-9]|$)` from MUL-1949 — keeps phrases+// like "1500ms" or "1.5.0" from accidentally landing in+// provider_server_error.+//+// Compiled at package init: the classifier is on the in-flight write+// path for every failed task, so paying the regex compile cost at+// startup rather than per-call matters.+var providerHTTP5xxRe = regexp.MustCompile(`(^|[^0-9])5[0-9][0-9]([^0-9]|$)`)++// Classify maps a free-form error string from the agent runtime / CLI+// to one of the 14 agent_error.* sub-reasons. Always returns a valid+// Reason; falls back to ReasonAgentUnknown when no rule matches and for+// empty input.+//+// The rule order mirrors the SQL CASE expression in MUL-1949+// (db-boy's offline backfill query). The SQL is the source of truth:+// when the two diverge, this Go classifier is wrong and should be+// updated to match. Keeping them in lock-step is required so that+// in-flight rows and historically backfilled rows share the same+// taxonomy.+//+// Matching is case-insensitive substring against the lowercased input.+// More-specific rules come before more-generic ones (e.g.+// context_overflow before provider_quota_limit, because "token limit"+// would otherwise be claimed by the quota bucket via "limit").+//+// Why a substring classifier rather than structured error codes: the+// 11 backend wrappers (server/pkg/agent/*) all surface upstream API+// failures verbatim in Result.Error, often as `API Error: 400 {...}`+// or as raw stderr tails. Insisting on structured codes would require+// touching every backend; a string classifier gives us refined+// failure_reason today and lets per-backend structured upgrades land+// independently.+func Classify(rawError string) Reason {+ trimmed := strings.TrimSpace(rawError)+ if trimmed == "" {+ // SQL maps NULL/empty to a separate bucket ("empty_error"),+ // but that bucket is not part of the canonical 21. In-flight+ // callers should never hand us empty input — if they do, the+ // safest landing is the catchall.+ return ReasonAgentUnknown+ }+ lower := strings.ToLower(trimmed)++ switch {+ // 1. Context / token window overflow. Checked early so "token+ // limit" doesn't get swallowed by the broader "limit" / "quota"+ // rule below.+ case containsAny(lower,+ "context length",+ "context_length_exceeded",+ "maximum context",+ "prompt is too long",+ "context size has been exceeded",+ ),+ // SQL had `%token%limit%` — ILIKE wildcard between tokens. We+ // approximate with both substrings present, which catches+ // "token limit", "tokens per minute limit", etc., without the+ // false positives a naive `Contains("token") || Contains("limit")`+ // would generate.+ strings.Contains(lower, "token") && strings.Contains(lower, "limit"):+ return ReasonAgentContextOverflow++ // 2. Missing config / API key. Checked before auth because+ // "missing API key" partly overlaps with "invalid api key"+ // wording but is structurally a config error, not an auth+ // rejection.+ case strings.Contains(lower, "missing environment variable"),+ strings.Contains(lower, "missing") && strings.Contains(lower, "api_key"),+ strings.Contains(lower, "api key") && strings.Contains(lower, "required"),+ strings.Contains(lower, "no llm provider configured"),+ strings.Contains(lower, "no provider configured"):+ return ReasonAgentMissingConfig++ // 3. Auth / access. 401 / 403 / "Not logged in" / invalid token+ // / lacks access to the model.+ case containsAny(lower,+ "401",+ "403",+ "unauthorized",+ "login required",+ "not logged in",+ "please login again",+ "refresh token",+ "invalid api key",+ "access token",+ "subscription access",+ "does not have access",+ "you may not have access",+ ):+ return ReasonAgentProviderAuthOrAccess++ // 4. Quota / billing. 402 / insufficient balance / monthly usage+ // limit / credits exhausted.+ case containsAny(lower,+ "402",+ "insufficient_balance",+ "balance is too low",+ "monthly usage limit",+ "usage limit",+ "you've hit your limit",+ // Curly apostrophe variant: providers and copy-pasted error+ // strings sometimes use U+2019 instead of ASCII '. SQL ILIKE+ // would not match the curly form either, so this is a small+ // in-flight improvement on top of the SQL classifier.+ "you\u2019ve hit your limit",+ "credits",+ "quota",+ ):+ return ReasonAgentProviderQuotaLimit++ // 5. Capacity / rate limit. 429 / 529 / overloaded / rate limit.+ case containsAny(lower,+ "429",+ "rate limit",+ "overloaded",+ "529",+ "no capacity available",+ ):+ return ReasonAgentProviderCapacityOrRateLimit++ // 6. Provider 5xx / server error. The 5xx regex is checked here+ // rather than as plain string matches because the SQL uses an+ // anchored regex — see providerHTTP5xxRe's docstring.+ case containsAny(lower,+ "server had an error",+ "provider returned error",+ "internal error",+ "service unavailable",+ "bad gateway",+ ),+ providerHTTP5xxRe.MatchString(lower):+ return ReasonAgentProviderServerError++ // 7. Provider network. Stream cut, dial failures, DNS / I/O+ // timeout below the HTTP layer.+ case containsAny(lower,+ "stream disconnected",+ "error sending request",+ "unable to connect",+ "dial tcp",+ "connection refused",+ "connectionrefused",+ "dns",+ "i/o timeout",+ ):+ return ReasonAgentProviderNetwork++ // 8. Model not found / unavailable. The SQL uses `%model%not%found%`,+ // which matches "model … not found" with anything in between;+ // we approximate with both substrings present, which captures+ // typical phrasings like "model X not found" and "the requested+ // model was not found".+ case strings.Contains(lower, "model") && strings.Contains(lower, "not found"),+ containsAny(lower,+ "unknown model",+ "selected model",+ "http 404",+ "404 page not found",+ ):+ return ReasonAgentModelNotFoundOrUnavailable++ // 9. Empty / unparseable output from the agent CLI itself. These+ // strings come from server/pkg/agent/*.go wrappers and are+ // stable.+ case containsAny(lower,+ "returned empty output",+ "returned no parseable output",+ ):+ return ReasonAgentEmptyOrUnparseableOutput++ // 10. Agent subprocess hard timeout (per-task wall clock).+ case strings.Contains(lower, "timed out after"):+ return ReasonAgentTimeout++ // 11. Runner CLI binary missing.+ case strings.Contains(lower, "executable not found"):+ return ReasonAgentRuntimeMissingExecutable++ // 12. Runner CLI version too old / incompatible protocol.+ case containsAny(lower,+ "below the minimum supported version",+ "requires a newer version",+ ):+ return ReasonAgentRuntimeVersionUnsupported++ // 13. Agent / runner process-level failure. Checked last among+ // specific rules because "exit status" / "signal" can co-occur+ // with more specific upstream errors that SHOULD win (e.g. an+ // agent that crashed *because* the provider rate-limited it+ // should be classified as rate-limited, not as a process+ // failure).+ case containsAny(lower,+ "exit status",+ "signal",+ "panic",+ "sigsegv",+ "process exited",+ "pipe has been ended",+ "file already closed",+ "initialize failed",+ ):+ return ReasonAgentProcessFailure+ }++ return ReasonAgentUnknown+}++// containsAny reports whether s contains any of the supplied substrings.+// Caller is responsible for lowercasing s ahead of time so the helper+// stays cheap on the hot path — pre-lowercasing once is faster than+// case-folding inside each substring scan.+func containsAny(s string, subs ...string) bool {+ for _, sub := range subs {+ if strings.Contains(s, sub) {+ return true+ }+ }+ return false+}diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.gonew file mode 100644index 0000000000..fc1c98e862--- /dev/null+++ b/server/pkg/taskfailure/classify_test.go@@ -0,0 +1,250 @@+package taskfailure++import "testing"++// TestClassifyEmptyAndWhitespace pins the empty/whitespace contract.+// Daemon callers should never hand us empty error text — but if they+// do, returning the catchall is safer than panicking.+func TestClassifyEmptyAndWhitespace(t *testing.T) {+ t.Parallel()++ cases := []string{"", " ", "\n\t \n"}+ for _, in := range cases {+ if got := Classify(in); got != ReasonAgentUnknown {+ t.Errorf("Classify(%q) = %q, want %q", in, got, ReasonAgentUnknown)+ }+ }+}++// TestClassifyRules walks every classifier rule with a real-world+// sample taken from MUL-1949's db-boy production analysis (top error+// prefixes from `agent_task_queue.error` over a 7-day window). When+// MUL-1949's SQL grows a new rule, add a fixture here so the in-flight+// classifier and the offline backfill stay in lock-step.+//+// One test case per rule is the minimum bar; rules with notable+// boundary conditions (e.g. the 5xx regex) get a dedicated subtest+// further down.+func TestClassifyRules(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ in string+ want Reason+ }{+ // 1. Context overflow.+ {"context length exceeded", "Error: context length exceeded for model gpt-4", ReasonAgentContextOverflow},+ {"context_length_exceeded code", `{"error":{"code":"context_length_exceeded"}}`, ReasonAgentContextOverflow},+ {"maximum context", "Maximum context window of 200000 tokens has been exceeded", ReasonAgentContextOverflow},+ {"prompt is too long", "API Error: prompt is too long: 250000 tokens > 200000 maximum", ReasonAgentContextOverflow},+ {"context size has been exceeded", "context size has been exceeded; consider /compact", ReasonAgentContextOverflow},+ {"token limit", "Hit the token limit for this conversation", ReasonAgentContextOverflow},++ // 2. Missing config.+ {"missing env var", "Missing environment variable: `MIFY_API_KEY`.", ReasonAgentMissingConfig},+ {"missing api_key", "Failed to authenticate: missing api_key in config", ReasonAgentMissingConfig},+ {"api key required", "An api key is required to use this provider", ReasonAgentMissingConfig},+ {"no llm provider configured", "no llm provider configured; set OPENAI_API_KEY", ReasonAgentMissingConfig},+ {"no provider configured", "no provider configured for runtime", ReasonAgentMissingConfig},++ // 3. Provider auth / access.+ {"401", "API Error: 401 Unauthorized", ReasonAgentProviderAuthOrAccess},+ {"403", "API Error: 403 Forbidden", ReasonAgentProviderAuthOrAccess},+ {"unauthorized text", "Request unauthorized for this organization", ReasonAgentProviderAuthOrAccess},+ {"login required", "login required: please run /login", ReasonAgentProviderAuthOrAccess},+ {"not logged in", "Not logged in · Please run /login", ReasonAgentProviderAuthOrAccess},+ {"please login again", "Session expired, please login again", ReasonAgentProviderAuthOrAccess},+ {"refresh token", "refresh token has expired", ReasonAgentProviderAuthOrAccess},+ {"invalid api key", "Invalid API key provided", ReasonAgentProviderAuthOrAccess},+ {"access token", "access token has been revoked", ReasonAgentProviderAuthOrAccess},+ {"subscription access", "Your organization has disabled Claude subscription access for Claude Code", ReasonAgentProviderAuthOrAccess},+ {"does not have access", "Your account does not have access to this model", ReasonAgentProviderAuthOrAccess},+ {"may not have access", "you may not have access to claude-3-opus", ReasonAgentProviderAuthOrAccess},++ // 4. Provider quota / billing.+ {"402", "API Error: 402 Payment Required", ReasonAgentProviderQuotaLimit},+ {"insufficient_balance", `{"error":{"code":"insufficient_balance"}}`, ReasonAgentProviderQuotaLimit},+ {"balance is too low", "balance is too low to make this request", ReasonAgentProviderQuotaLimit},+ {"monthly usage limit", "You've hit your org's monthly usage limit", ReasonAgentProviderQuotaLimit},+ {"usage limit", "Account exceeded the daily usage limit", ReasonAgentProviderQuotaLimit},+ {"hit your limit ascii", "you've hit your limit; upgrade to continue", ReasonAgentProviderQuotaLimit},+ {"hit your limit curly", "you\u2019ve hit your limit", ReasonAgentProviderQuotaLimit},+ {"credits", "Your account has 0 credits remaining", ReasonAgentProviderQuotaLimit},+ {"quota", "quota exceeded for project foo", ReasonAgentProviderQuotaLimit},++ // 5. Capacity / rate limit.+ {"429", "API Error: 429 Too Many Requests", ReasonAgentProviderCapacityOrRateLimit},+ {"529", "Server overloaded: HTTP 529", ReasonAgentProviderCapacityOrRateLimit},+ {"rate limit", "rate limit exceeded for tier 3", ReasonAgentProviderCapacityOrRateLimit},+ {"overloaded", "overloaded_error: please retry", ReasonAgentProviderCapacityOrRateLimit},+ {"no capacity available", "no capacity available; try again later", ReasonAgentProviderCapacityOrRateLimit},++ // 6. Provider 5xx / server error.+ {"server had an error", "the server had an error processing your request", ReasonAgentProviderServerError},+ {"provider returned error", "provider returned error: malformed response", ReasonAgentProviderServerError},+ {"internal error", "An internal error occurred while serving the request", ReasonAgentProviderServerError},+ {"500 with delimiter", "API Error: 500 Internal Server Error", ReasonAgentProviderServerError},+ {"503 anywhere", "got HTTP 503 from provider", ReasonAgentProviderServerError},+ {"503 at start", "503 service degraded", ReasonAgentProviderServerError},+ {"504 at end", "upstream returned 504", ReasonAgentProviderServerError},+ {"service unavailable", "service unavailable, retry later", ReasonAgentProviderServerError},+ {"bad gateway", "Bad Gateway: upstream rejected", ReasonAgentProviderServerError},++ // 7. Provider network.+ {"stream disconnected", "stream disconnected before completion", ReasonAgentProviderNetwork},+ {"error sending request", "error sending request for url (https://api.example.com/v1)", ReasonAgentProviderNetwork},+ {"unable to connect", "unable to connect to provider", ReasonAgentProviderNetwork},+ {"dial tcp", "dial tcp 1.2.3.4:443: connect: connection refused", ReasonAgentProviderNetwork},+ {"connection refused alone", "connection refused", ReasonAgentProviderNetwork},+ {"connectionrefused single", "ConnectionRefused", ReasonAgentProviderNetwork},+ {"dns", "dns lookup failed", ReasonAgentProviderNetwork},+ {"i/o timeout", "read tcp 1.2.3.4:443: i/o timeout", ReasonAgentProviderNetwork},++ // 8. Model not found / unavailable.+ {"model not found", "Error: model claude-3-opus-99 not found", ReasonAgentModelNotFoundOrUnavailable},+ {"model not found phrase", "the model was not found in this account", ReasonAgentModelNotFoundOrUnavailable},+ {"unknown model", "unknown model 'foo-1.0'", ReasonAgentModelNotFoundOrUnavailable},+ {"selected model", "the selected model is no longer supported", ReasonAgentModelNotFoundOrUnavailable},+ {"http 404", "HTTP 404: model endpoint not registered", ReasonAgentModelNotFoundOrUnavailable},+ {"404 page not found", "404 page not found", ReasonAgentModelNotFoundOrUnavailable},++ // 9. Empty / unparseable output.+ {"returned empty output", "openclaw returned empty output", ReasonAgentEmptyOrUnparseableOutput},+ {"returned no parseable output", "kimi returned no parseable output", ReasonAgentEmptyOrUnparseableOutput},++ // 10. Agent timeout.+ {"timed out after", "claude timed out after 2h0m0s", ReasonAgentTimeout},++ // 11. Runtime missing executable.+ {"executable not found", "executable not found in $PATH", ReasonAgentRuntimeMissingExecutable},++ // 12. Runtime version unsupported.+ {"below the minimum supported version", "claude CLI 0.1.0 is below the minimum supported version 0.5.0", ReasonAgentRuntimeVersionUnsupported},+ {"requires a newer version", "this protocol requires a newer version of the runtime", ReasonAgentRuntimeVersionUnsupported},++ // 13. Process failure.+ {"exit status", "agent exit status 137", ReasonAgentProcessFailure},+ {"signal", "agent terminated by signal: killed", ReasonAgentProcessFailure},+ {"panic", "panic: runtime error: invalid memory address", ReasonAgentProcessFailure},+ {"sigsegv", "fatal error: SIGSEGV", ReasonAgentProcessFailure},+ {"process exited", "process exited with status 1", ReasonAgentProcessFailure},+ {"pipe has been ended", "the pipe has been ended", ReasonAgentProcessFailure},+ {"file already closed", "write |1: file already closed", ReasonAgentProcessFailure},+ {"initialize failed", "initialize failed: backend not ready", ReasonAgentProcessFailure},++ // 14. Catchall.+ {"unrecognized", "the agent gave up for reasons unknown", ReasonAgentUnknown},+ {"sentence with no marker", "Hello world.", ReasonAgentUnknown},+ }++ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ if got := Classify(c.in); got != c.want {+ t.Fatalf("Classify(%q) = %q, want %q", c.in, got, c.want)+ }+ })+ }+}++// TestClassifyOrderingPriorities pins the rule precedence between+// overlapping rules. These cases caught regressions during MUL-2946 PR1+// review: the SQL CASE ordering matters and a naive Go switch could+// silently route them differently.+func TestClassifyOrderingPriorities(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ in string+ want Reason+ }{+ // "token limit" mentions both "context-ish" tokens AND+ // "limit". The context_overflow rule must win because the+ // quota-limit rule's "limit" trigger would otherwise swallow+ // it.+ {"token limit beats quota", "you exceeded the token limit", ReasonAgentContextOverflow},++ // 401 + missing api_key: the missing_config rule runs before+ // auth precisely so we don't classify a config error as an+ // auth rejection.+ {"missing api key beats 401", "missing api_key for openai (401 returned downstream)", ReasonAgentMissingConfig},++ // Both "429" and "rate limit" present — should still land in+ // the capacity bucket, not the quota bucket.+ {"429 rate limit", "API Error: 429 rate limit reached", ReasonAgentProviderCapacityOrRateLimit},++ // "exit status" co-occurring with a stronger upstream marker+ // — the upstream classification should win because the+ // process_failure rule is checked last.+ {"exit status with 401 upstream", "exit status 1: API Error: 401 Unauthorized", ReasonAgentProviderAuthOrAccess},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ if got := Classify(c.in); got != c.want {+ t.Errorf("Classify(%q) = %q, want %q", c.in, got, c.want)+ }+ })+ }+}++// TestClassify5xxRegex pins the boundary behavior of the 5xx HTTP+// status detector. The SQL classifier uses an anchored regex+// `(^|[^0-9])5[0-9][0-9]([^0-9]|$)`; this Go classifier mirrors it via+// providerHTTP5xxRe. Without the anchors, "1500ms" and "1.5.0" would+// be misclassified as a server error.+func TestClassify5xxRegex(t *testing.T) {+ t.Parallel()++ hits := []string{+ "503",+ " 504 ",+ "got 502 from upstream",+ "upstream returned 599\n",+ }+ for _, in := range hits {+ if got := Classify(in); got != ReasonAgentProviderServerError {+ t.Errorf("Classify(%q) = %q, want %q", in, got, ReasonAgentProviderServerError)+ }+ }++ misses := []string{+ "1500ms latency observed",+ "version 1.5.0 unsupported",+ "5000 tokens generated",+ "agent slept for 1500 seconds",+ }+ for _, in := range misses {+ if got := Classify(in); got == ReasonAgentProviderServerError {+ t.Errorf("Classify(%q) = %q, want NOT provider_server_error", in, got)+ }+ }+}++// TestClassifyAlwaysReturnsAgentSide guarantees Classify never returns+// a platform-side reason. Platform-side reasons originate from+// sweepers / scheduler / poisoned classifier paths that don't pass+// through Classify; the in-flight classifier's job is exclusively to+// pick among the 14 agent_error.* sub-reasons (or fall back to+// ReasonAgentUnknown). A future change that accidentally returned,+// say, ReasonRuntimeOffline from Classify would break Prometheus+// label semantics — pin it here.+func TestClassifyAlwaysReturnsAgentSide(t *testing.T) {+ t.Parallel()++ samples := []string{+ "",+ "random text",+ "401 Unauthorized",+ "context length exceeded",+ "503 internal server error",+ "timed out after 2h0m0s",+ "exit status 1",+ }+ for _, s := range samples {+ got := Classify(s)+ if !got.IsAgentError() {+ t.Errorf("Classify(%q) = %q, must be agent_error.* (in-flight classifier never returns platform-side reasons)", s, got)+ }+ }+}diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.gonew file mode 100644index 0000000000..4eab95a395--- /dev/null+++ b/server/pkg/taskfailure/failure.go@@ -0,0 +1,247 @@+// Package taskfailure is the canonical, refined taxonomy of values written+// into agent_task_queue.failure_reason and chat_message.failure_reason.+//+// History: until MUL-1949, server/daemon code wrote one of a small handful+// of coarse failure_reason values ("agent_error", "timeout",+// "runtime_offline", …). The "agent_error" bucket grew to ~30% of all+// failures and hid the real cause (provider 401, quota exceeded, context+// overflow, runner crash, etc.) inside the free-form `error` text column.+// MUL-1949's offline backfill SQL re-classified those rows into 14+// agent_error.* sub-reasons via a CASE expression on the error text.+//+// This package lifts that classifier into the in-flight write path so the+// stored failure_reason is already refined when the row is first+// persisted, and so server / daemon / cloud share a single source of+// truth for the canonical 21 values. PR1 of the Grafana board plan+// ([MUL-2946](https://multica/issues/MUL-2946)). Subsequent PRs use+// AllReasons() to pre-warm the Prometheus failure_reason label set.+//+// The 21 canonical values fall into two groups:+//+// - 7 platform-side values (no `agent_error.` prefix) emitted by the+// server-side sweepers and daemon classifiers when the failure is+// attributable to the platform/scheduler/runtime layer rather than+// anything the agent process did:+//+// queued_expired, runtime_offline, runtime_recovery, timeout,+// iteration_limit, agent_blocked, api_invalid_request+//+// - 14 agent-side values (with `agent_error.` prefix) produced by+// Classify(rawError) when the agent process surfaced an error string.+// IsAgentError reports membership in this set.+//+// Wire stability: the string forms of these constants are persisted into+// the database and surfaced as Prometheus labels. Renaming a value is a+// breaking change. New values may be added — but only after the SQL+// classifier in MUL-1949 grows a matching rule and a backfill migration+// re-classifies historical rows.+package taskfailure++import "strings"++// Reason is a string-backed enum of the canonical failure_reason values+// stored in agent_task_queue.failure_reason. Use the Reason* constants+// rather than string literals so the compiler catches typos and a future+// taxonomy change can be made package-wide.+type Reason string++// agentErrorPrefix marks the 14 sub-reasons that originate inside the+// agent process (provider error, runner crash, context overflow, etc.)+// as opposed to the 7 platform-side reasons (queue expiry, runtime+// offline, sweeper timeout, etc.). IsAgentError uses this prefix so+// callers don't have to enumerate the agent-side reasons by hand.+const agentErrorPrefix = "agent_error."++const (+ // Platform / scheduler side: failure attributable to Multica+ // infrastructure rather than anything the agent process did. These+ // are emitted by server-side sweepers (ExpireStaleQueuedTasks,+ // FailStaleTasks, FailTasksForOfflineRuntimes,+ // RecoverOrphanedTasksForRuntime) and the daemon's poisoned-session+ // classifier (api_invalid_request, iteration_limit, agent_blocked).+ // IsAgentError returns false for all of these.++ // ReasonQueuedExpired: task sat in 'queued' past the TTL without+ // being claimed (typically autopilot backlog while the assignee's+ // runtime is offline). Written by ExpireStaleQueuedTasks.+ ReasonQueuedExpired Reason = "queued_expired"++ // ReasonRuntimeOffline: the runtime owning a dispatched/running+ // task went offline. Written by FailTasksForOfflineRuntimes.+ ReasonRuntimeOffline Reason = "runtime_offline"++ // ReasonRuntimeRecovery: the daemon restarted while the task was+ // in flight; the prior session is unrecoverable. Written by+ // RecoverOrphanedTasksForRuntime at daemon startup.+ ReasonRuntimeRecovery Reason = "runtime_recovery"++ // ReasonTimeout: server-side or runtime-side hard timeout.+ // Written by FailStaleTasks (server) and the daemon's per-task+ // agent timeout path.+ ReasonTimeout Reason = "timeout"++ // ReasonIterationLimit: the agent reached its per-run iteration+ // cap and emitted a fallback "I reached the iteration limit"+ // message. Treated as platform-side because it is a Multica-imposed+ // budget rather than an external API rejection.+ ReasonIterationLimit Reason = "iteration_limit"++ // ReasonAgentBlocked: the agent intentionally entered the+ // 'blocked' workflow state (e.g. requesting human input). Not a+ // system error.+ ReasonAgentBlocked Reason = "agent_blocked"++ // ReasonAPIInvalidRequest: the upstream LLM API rejected the+ // request body with a 400 invalid_request_error (oversized image,+ // malformed payload, etc.). The conversation history itself is+ // poisoned, so the next task on the same session would replay the+ // same 400 — GetLastTaskSession excludes this reason from the+ // resume lookup. Written by classifyPoisonedError in daemon/poisoned.go.+ ReasonAPIInvalidRequest Reason = "api_invalid_request"++ // Agent process side: failure surfaced by the agent CLI / SDK as+ // an error string. Classify(rawError) is responsible for picking+ // the right sub-reason from the string. IsAgentError returns true+ // for all of these.++ // ReasonAgentProviderAuthOrAccess: 401 / 403, "Not logged in",+ // invalid API key, no access to the model. Not retryable; user+ // must re-auth.+ ReasonAgentProviderAuthOrAccess Reason = "agent_error.provider_auth_or_access"++ // ReasonAgentProviderQuotaLimit: 402, insufficient_balance,+ // monthly usage limit, credits exhausted. Not retryable until the+ // account is topped up.+ ReasonAgentProviderQuotaLimit Reason = "agent_error.provider_quota_limit"++ // ReasonAgentProviderCapacityOrRateLimit: 429 / 529, rate-limited,+ // overloaded, no capacity available. Transient — backoff ++ // retry is appropriate.+ ReasonAgentProviderCapacityOrRateLimit Reason = "agent_error.provider_capacity_or_rate_limit"++ // ReasonAgentProviderServerError: provider 5xx, internal error,+ // service unavailable, bad gateway. Transient — short backoff.+ ReasonAgentProviderServerError Reason = "agent_error.provider_server_error"++ // ReasonAgentProviderNetwork: stream disconnected, dial tcp+ // failures, DNS failures, i/o timeout. Transient.+ ReasonAgentProviderNetwork Reason = "agent_error.provider_network"++ // ReasonAgentProcessFailure: agent subprocess exited non-zero,+ // crashed, or returned an unexpected signal. Runner / backend+ // quality issue.+ ReasonAgentProcessFailure Reason = "agent_error.process_failure"++ // ReasonAgentEmptyOrUnparseableOutput: the agent CLI returned+ // empty output or output we couldn't parse against its known+ // protocol. Wrapper / protocol robustness issue.+ ReasonAgentEmptyOrUnparseableOutput Reason = "agent_error.empty_or_unparseable_output"++ // ReasonAgentTimeout: the agent subprocess hit its hard timeout+ // (e.g. 2h) — distinct from ReasonTimeout, which is a+ // platform-side sweeper timeout.+ ReasonAgentTimeout Reason = "agent_error.agent_timeout"++ // ReasonAgentContextOverflow: prompt or context window exceeded+ // the model's limit. Not retryable on the same session; needs+ // compaction or a fresh session.+ ReasonAgentContextOverflow Reason = "agent_error.context_overflow"++ // ReasonAgentMissingConfig: the agent / runtime is missing a+ // required environment variable or API key, or no LLM provider+ // is configured.+ ReasonAgentMissingConfig Reason = "agent_error.missing_config"++ // ReasonAgentModelNotFoundOrUnavailable: the chosen model id+ // doesn't exist, isn't accessible to this account, or returned+ // HTTP 404 from the provider.+ ReasonAgentModelNotFoundOrUnavailable Reason = "agent_error.model_not_found_or_unavailable"++ // ReasonAgentRuntimeVersionUnsupported: the local runner CLI is+ // below the minimum supported version or the protocol isn't+ // compatible.+ ReasonAgentRuntimeVersionUnsupported Reason = "agent_error.runtime_version_unsupported"++ // ReasonAgentRuntimeMissingExecutable: the runner CLI binary+ // isn't installed / not on PATH.+ ReasonAgentRuntimeMissingExecutable Reason = "agent_error.runtime_missing_executable"++ // ReasonAgentUnknown: the classifier couldn't match any rule.+ // This bucket is expected to be small (<5% of failed tasks) — a+ // rising share is a signal that the classifier needs new rules.+ // Returned by Classify when no other rule fires (including for+ // empty input).+ ReasonAgentUnknown Reason = "agent_error.unknown"+)++// allReasons is the canonical ordered list of the 21 reasons. Order is+// stable so callers (e.g. Prometheus collectors that pre-warm series via+// AllReasons) can build deterministic label sets across restarts.+//+// Ordering:+// 1. Platform-side reasons in the same order they tend to fire in a+// task lifecycle (queue → dispatch → run → post-run).+// 2. Agent-side reasons grouped by responsibility area (provider /+// agent process / config / runtime), then unknown last.+var allReasons = []Reason{+ // Platform / scheduler side.+ ReasonQueuedExpired,+ ReasonRuntimeOffline,+ ReasonRuntimeRecovery,+ ReasonTimeout,+ ReasonIterationLimit,+ ReasonAgentBlocked,+ ReasonAPIInvalidRequest,++ // Agent process side: provider errors.+ ReasonAgentProviderAuthOrAccess,+ ReasonAgentProviderQuotaLimit,+ ReasonAgentProviderCapacityOrRateLimit,+ ReasonAgentProviderServerError,+ ReasonAgentProviderNetwork,++ // Agent process side: agent / runner errors.+ ReasonAgentProcessFailure,+ ReasonAgentEmptyOrUnparseableOutput,+ ReasonAgentTimeout,+ ReasonAgentContextOverflow,+ ReasonAgentMissingConfig,+ ReasonAgentModelNotFoundOrUnavailable,+ ReasonAgentRuntimeVersionUnsupported,+ ReasonAgentRuntimeMissingExecutable,++ // Catchall.+ ReasonAgentUnknown,+}++// String returns the wire form of the reason — what gets written to the+// failure_reason column and exposed as a Prometheus label value.+func (r Reason) String() string { return string(r) }++// IsAgentError reports whether the reason originates inside the agent+// process (provider error, runner crash, context overflow, etc.) as+// opposed to the platform/scheduler/runtime layer (queue expiry, runtime+// offline, sweeper timeout, etc.).+//+// The classification is intentionally based on a string prefix rather+// than an enum membership test: any future agent_error.* value+// automatically inherits the correct grouping without needing to update+// this method.+func (r Reason) IsAgentError() bool {+ return strings.HasPrefix(string(r), agentErrorPrefix)+}++// AllReasons returns the canonical 21 reasons in a stable order. The+// caller MUST NOT mutate the returned slice; a copy is returned so+// concurrent callers can append to their local copy without corrupting+// the package-level fixture.+//+// Primary use: Prometheus failure_reason label pre-warming, so a label+// the production process has not seen yet is still observable as a+// zero-valued series instead of appearing only after the first failure+// of that kind.+func AllReasons() []Reason {+ out := make([]Reason, len(allReasons))+ copy(out, allReasons)+ return out+}diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.gonew file mode 100644index 0000000000..35ad2bd3cc--- /dev/null+++ b/server/pkg/taskfailure/failure_test.go@@ -0,0 +1,184 @@+package taskfailure++import (+ "strings"+ "testing"+)++// TestReasonStringWireValues pins the on-the-wire string for every+// canonical reason. These strings are persisted into+// agent_task_queue.failure_reason and surfaced as Prometheus labels —+// renaming any of them is a breaking change. If this test fails because+// you intended to rename a value, also update the SQL classifier in+// MUL-1949 and ship a backfill migration before changing the constant.+func TestReasonStringWireValues(t *testing.T) {+ t.Parallel()++ cases := []struct {+ reason Reason+ want string+ }{+ // Platform-side.+ {ReasonQueuedExpired, "queued_expired"},+ {ReasonRuntimeOffline, "runtime_offline"},+ {ReasonRuntimeRecovery, "runtime_recovery"},+ {ReasonTimeout, "timeout"},+ {ReasonIterationLimit, "iteration_limit"},+ {ReasonAgentBlocked, "agent_blocked"},+ {ReasonAPIInvalidRequest, "api_invalid_request"},+ // Agent-side.+ {ReasonAgentProviderAuthOrAccess, "agent_error.provider_auth_or_access"},+ {ReasonAgentProviderQuotaLimit, "agent_error.provider_quota_limit"},+ {ReasonAgentProviderCapacityOrRateLimit, "agent_error.provider_capacity_or_rate_limit"},+ {ReasonAgentProviderServerError, "agent_error.provider_server_error"},+ {ReasonAgentProviderNetwork, "agent_error.provider_network"},+ {ReasonAgentProcessFailure, "agent_error.process_failure"},+ {ReasonAgentEmptyOrUnparseableOutput, "agent_error.empty_or_unparseable_output"},+ {ReasonAgentTimeout, "agent_error.agent_timeout"},+ {ReasonAgentContextOverflow, "agent_error.context_overflow"},+ {ReasonAgentMissingConfig, "agent_error.missing_config"},+ {ReasonAgentModelNotFoundOrUnavailable, "agent_error.model_not_found_or_unavailable"},+ {ReasonAgentRuntimeVersionUnsupported, "agent_error.runtime_version_unsupported"},+ {ReasonAgentRuntimeMissingExecutable, "agent_error.runtime_missing_executable"},+ {ReasonAgentUnknown, "agent_error.unknown"},+ }++ if got, want := len(cases), 21; got != want {+ t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)+ }++ for _, c := range cases {+ t.Run(c.want, func(t *testing.T) {+ if got := c.reason.String(); got != c.want {+ t.Errorf("Reason(%q).String() = %q, want %q", c.reason, got, c.want)+ }+ })+ }+}++// TestIsAgentError pins the platform-side vs agent-side split so a+// future Prometheus collector / retry policy can rely on the prefix+// rather than maintaining a parallel allow-list.+func TestIsAgentError(t *testing.T) {+ t.Parallel()++ platformSide := []Reason{+ ReasonQueuedExpired,+ ReasonRuntimeOffline,+ ReasonRuntimeRecovery,+ ReasonTimeout,+ ReasonIterationLimit,+ ReasonAgentBlocked,+ ReasonAPIInvalidRequest,+ }+ for _, r := range platformSide {+ if r.IsAgentError() {+ t.Errorf("%q.IsAgentError() = true, want false (platform-side)", r)+ }+ }++ agentSide := []Reason{+ ReasonAgentProviderAuthOrAccess,+ ReasonAgentProviderQuotaLimit,+ ReasonAgentProviderCapacityOrRateLimit,+ ReasonAgentProviderServerError,+ ReasonAgentProviderNetwork,+ ReasonAgentProcessFailure,+ ReasonAgentEmptyOrUnparseableOutput,+ ReasonAgentTimeout,+ ReasonAgentContextOverflow,+ ReasonAgentMissingConfig,+ ReasonAgentModelNotFoundOrUnavailable,+ ReasonAgentRuntimeVersionUnsupported,+ ReasonAgentRuntimeMissingExecutable,+ ReasonAgentUnknown,+ }+ for _, r := range agentSide {+ if !r.IsAgentError() {+ t.Errorf("%q.IsAgentError() = false, want true (agent-side)", r)+ }+ if !strings.HasPrefix(r.String(), "agent_error.") {+ t.Errorf("%q missing required agent_error. prefix", r)+ }+ }+}++// TestAllReasonsContents verifies that AllReasons() returns the+// complete canonical taxonomy with no duplicates and no surprise+// values. Prometheus pre-warming relies on this fixture being stable.+func TestAllReasonsContents(t *testing.T) {+ t.Parallel()++ got := AllReasons()+ if len(got) != 21 {+ t.Fatalf("AllReasons() returned %d entries, want 21", len(got))+ }++ seen := make(map[Reason]bool, len(got))+ var platformCount, agentCount int+ for _, r := range got {+ if seen[r] {+ t.Errorf("AllReasons() returned duplicate %q", r)+ }+ seen[r] = true+ if r.IsAgentError() {+ agentCount+++ } else {+ platformCount+++ }+ }++ if platformCount != 7 {+ t.Errorf("AllReasons(): platform-side count = %d, want 7", platformCount)+ }+ if agentCount != 14 {+ t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)+ }++ // Sanity-check that every constant declared at package level+ // shows up in AllReasons. This catches a future drift where+ // someone adds a constant but forgets to register it in the+ // allReasons slice.+ required := []Reason{+ ReasonQueuedExpired, ReasonRuntimeOffline, ReasonRuntimeRecovery,+ ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,+ ReasonAPIInvalidRequest,+ ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,+ ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,+ ReasonAgentProviderNetwork, ReasonAgentProcessFailure,+ ReasonAgentEmptyOrUnparseableOutput, ReasonAgentTimeout,+ ReasonAgentContextOverflow, ReasonAgentMissingConfig,+ ReasonAgentModelNotFoundOrUnavailable,+ ReasonAgentRuntimeVersionUnsupported,+ ReasonAgentRuntimeMissingExecutable,+ ReasonAgentUnknown,+ }+ for _, r := range required {+ if !seen[r] {+ t.Errorf("AllReasons() missing canonical reason %q", r)+ }+ }+}++// TestAllReasonsIsDefensiveCopy guards the contract that mutating the+// returned slice cannot corrupt the package-level fixture. Without+// this, two callers (e.g. two Prometheus collectors at startup) could+// race on a shared slice.+func TestAllReasonsIsDefensiveCopy(t *testing.T) {+ t.Parallel()++ first := AllReasons()+ if len(first) == 0 {+ t.Fatal("AllReasons() returned empty slice")+ }+ original := first[0]+ first[0] = "tampered"++ second := AllReasons()+ if second[0] == "tampered" {+ t.Fatalf("AllReasons() leaked package state: second call returned tampered value %q", second[0])+ }+ if second[0] != original {+ t.Fatalf("AllReasons()[0] = %q, want %q", second[0], original)+ }+}