Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: route on enriched failure telemetry + latency split fallback (#2329)

Adam Eivy6cc782ca5bc5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f9c0bceea7..665bf87d47 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,6 +15,7 @@
## Added
- **[issue-2333] Untyped task executions are now auto-classified instead of piling up as `unknown`.** Task-learning's `extractTaskType` used to dump every execution it couldn't pattern-match into a single blind `unknown` bucket — those tasks bypassed routing logic, skipped outcome learning, and leaked unstructured failures. It now runs an execution-entry classification hook (`classifyUntypedTask`, pure/idempotent/<50ms) that, before giving up, infers a concrete domain from additional signals — a `selfImprovementType` metadata hint, an explicit `task.taskType` the primary extractor didn't special-case (e.g. `scheduled` → `scheduled-task`), and broader whole-word description keyword signatures (`fix`/`investigate`/`crash` → `auto-fix`, `refactor`/`optimize` → `self-improve:general`, `review`/`audit` → `idle-review`, `unit test`/`coverage` → `test-task`) — and only falls back to a new sandboxed `external/untyped` type when nothing matches. Newly-classified and fallback executions flow through the existing #2329 failure-signature harvesting so their failures are captured in the normalized telemetry schema. The `external/untyped` bucket is explicitly walled off from routing (it never drives a model-tier suggestion and is never globally skipped) so a heterogeneous grab-bag can't create a routing blind spot or loop. (Partial delivery of #2333; the spawn-time key mirror in `agentModelSelection.extractTaskTypeKey` and deeper self-improvement-loop consumption of the harvested `failureSignatures` remain.)
+- **[issue-2329] Model routing now consumes the enriched failure signatures, and the latency split derives a queue/compute breakdown when a source timestamp is missing.** The `failureSignatures` telemetry recorded per completion (provider/model/tier-attributed, recency-bounded) is now read by `suggestModelTier`: a new pure `deriveFailureSignalAvoidance` cross-references those recent failures against `routingAccuracy` and steers selection off a tier that is BOTH accumulating recent failures for a task type AND unproven (success rate < 80%, or no success data) — catching a freshly-degrading tier before its all-time rate crosses the hard misroute line, while a proven tier keeps its slot despite absolute failures (signatures record failures only, so counts alone can't condemn a tier). The dominant failing provider/model is surfaced as a `failureSignal` on the suggestion and named in the model-selection log, so the routing decision is legible rather than "avoid tier X". Separately, the queue/compute latency split now falls back to `wall − compute` (or `wall − queue`) when a run carries no `createdAt` or no runner duration, with a per-leg `source` marker (`measured`/`derived`/`null`) so a derived value is never confused with a measured one and a legitimate `0ms` is never confused with an absent leg. (Further #2329 work remains: success-criteria validation booleans on every completion path and the >0.8 correlation-quality measurement window.)
- **[issue-2329] Task-learning now records a structured telemetry context for every completed agent.** On each completion the learning system builds a `TaskTelemetryContext` — a failure signature (`{ category, messageSnippet, failurePosition }`, reusing the category `agentErrorAnalysis` already classified), execution context (`provider`, `model`, `modelTier`, `taskType`, `component`, input-size, and the routing decision rationale), and a latency breakdown (`wallMs` spawn→completion vs. `queueMs` wait vs. `executionMs` measured) — using explicit null sentinels for anything not cheaply derivable rather than fabricating values. Failure signatures are aggregated per error category into a new additive `failureSignatures` block in `learning.json` (older files without the key load unchanged), and the enriched context is surfaced on the single-line completion log. (Partial delivery of #2329; routing auto-adjustment that consumes these signals, success-criteria validation flags, the queue/compute split where spawn timestamps are missing, and correlation-quality measurement remain.)
## Fixed
diff --git a/server/services/agentModelSelection.js b/server/services/agentModelSelection.js
index 7932efe13d..36e3845559 100644
--- a/server/services/agentModelSelection.js
+++ b/server/services/agentModelSelection.js
@@ -112,7 +112,13 @@ export async function selectModelForTask(task, provider, agent = {}) {
const learningSuggestion = await suggestModelTier(taskTypeKey).catch(() => null);
if (learningSuggestion) {
- const { suggested, avoidTiers = [], reason: learningReason } = learningSuggestion;
+ const { suggested, avoidTiers = [], reason: learningReason, failureSignal } = learningSuggestion;
+ // Provider/model attribution from the enriched failure signatures (#2329):
+ // names WHICH provider/model recently failed for this task type so the
+ // routing decision is legible, not just "avoid tier X".
+ const failureNote = failureSignal
+ ? ` [recent failures: ${failureSignal.failures}× ${failureSignal.tier}${failureSignal.provider ? ` via ${failureSignal.provider}${failureSignal.model ? `/${failureSignal.model}` : ''}` : ''}]`
+ : '';
// Map tier names to provider model keys
const tierToModel = {
@@ -144,7 +150,7 @@ export async function selectModelForTask(task, provider, agent = {}) {
// If we have a specific tier suggestion, use it
const suggestedModel = suggested ? resolveTierModel(suggested) : null;
if (suggestedModel) {
- console.log(`📊 Learning-based selection: ${taskTypeKey} → ${suggested} (${learningReason})`);
+ console.log(`📊 Learning-based selection: ${taskTypeKey} → ${suggested} (${learningReason})${failureNote}`);
return {
model: suggestedModel,
tier: suggested,
@@ -161,7 +167,7 @@ export async function selectModelForTask(task, provider, agent = {}) {
const tierPreference = ['heavy', 'medium', 'default', 'light'];
for (const tier of tierPreference) {
if (!avoidTiers.includes(tier) && tierToModel[tier]) {
- console.log(`📊 Learning-based avoidance: ${taskTypeKey} → ${tier} (avoiding ${avoidTiers.join(', ')})`);
+ console.log(`📊 Learning-based avoidance: ${taskTypeKey} → ${tier} (avoiding ${avoidTiers.join(', ')})${failureNote}`);
return {
model: tierToModel[tier],
tier,
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 3aa6cca861..7cec3a0b46 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -586,6 +586,153 @@ describe('TaskLearning - suggestModelTier with routing signals', () => {
expect(result).toBeNull();
});
+ it('steers off a freshly-failing tier even below the completions threshold (#2329)', async () => {
+ // Only 4 completions — too few for a routingAccuracy-based tier suggestion —
+ // but 3 recent failures on 'heavy' meet the failure-signal bar, so routing
+ // still emits an avoidance-only suggestion instead of null.
+ const data = makeLearningData({
+ byTaskType: {
+ 'fresh-task': {
+ completed: 4, succeeded: 1, failed: 3,
+ totalDurationMs: 400000, avgDurationMs: 100000, successRate: 25
+ }
+ },
+ routingAccuracy: {},
+ failureSignatures: {
+ 'test-failure': {
+ count: 3,
+ recent: [
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'fresh-task' },
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'fresh-task' },
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'fresh-task' }
+ ]
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await suggestModelTier('fresh-task');
+ expect(result).not.toBeNull();
+ expect(result.suggested).toBeNull();
+ expect(result.avoidTiers).toContain('heavy');
+ expect(result.failureSignal).toMatchObject({ tier: 'heavy', failures: 3 });
+ });
+
+ it('still returns null below the completions threshold when there is no failure signal (#2329)', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData({
+ byTaskType: {
+ 'quiet-task': { completed: 3, succeeded: 2, failed: 1, successRate: 66 }
+ },
+ routingAccuracy: {},
+ failureSignatures: {}
+ })));
+ expect(await suggestModelTier('quiet-task')).toBeNull();
+ });
+
+ it('folds enriched failure signatures into avoidTiers even when routingAccuracy is quiet (#2329)', async () => {
+ // Overall success is healthy (75%) and routingAccuracy carries no failing
+ // tier — pre-#2329 this returned null. The failure signatures show three
+ // recent 'heavy'-tier failures for this task type, so routing now emits an
+ // avoidance-only suggestion that steers selection off 'heavy'.
+ const data = makeLearningData({
+ byTaskType: {
+ 'sig-task': {
+ completed: 12, succeeded: 9, failed: 3,
+ totalDurationMs: 1200000, avgDurationMs: 100000, successRate: 75
+ }
+ },
+ routingAccuracy: {},
+ failureSignatures: {
+ 'test-failure': {
+ count: 3,
+ recent: [
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'sig-task' },
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'sig-task' },
+ { modelTier: 'heavy', provider: 'codex', model: 'gpt', taskType: 'sig-task' }
+ ]
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await suggestModelTier('sig-task');
+ expect(result).not.toBeNull();
+ expect(result.suggested).toBeNull();
+ expect(result.avoidTiers).toContain('heavy');
+ expect(result.failureSignal).toMatchObject({ tier: 'heavy', failures: 3, provider: 'claude' });
+ });
+
+ it('drops to avoidance-only when the tier it would pick is itself failure-flagged (#2329)', async () => {
+ // routingAccuracy: heavy is failing (<40%) and 'medium' is the only 60-79%
+ // "successful" alternative — but the failure signatures show 3 recent medium
+ // failures too. Routing must NOT then suggest medium; it drops to avoidance-
+ // only (suggested: null) so selection steers off both heavy and medium.
+ const data = makeLearningData({
+ byTaskType: {
+ 'flap-task': {
+ completed: 20, succeeded: 9, failed: 11,
+ totalDurationMs: 2000000, avgDurationMs: 100000, successRate: 45
+ }
+ },
+ routingAccuracy: {
+ 'flap-task': {
+ heavy: { succeeded: 1, failed: 9, lastAttempt: '2026-01-26T00:00:00.000Z' }, // 10%
+ medium: { succeeded: 7, failed: 3, lastAttempt: '2026-01-26T00:00:00.000Z' } // 70% (unproven)
+ }
+ },
+ failureSignatures: {
+ 'test-failure': {
+ count: 3,
+ recent: [
+ { modelTier: 'medium', provider: 'claude', model: 'sonnet', taskType: 'flap-task' },
+ { modelTier: 'medium', provider: 'claude', model: 'sonnet', taskType: 'flap-task' },
+ { modelTier: 'medium', provider: 'claude', model: 'sonnet', taskType: 'flap-task' }
+ ]
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await suggestModelTier('flap-task');
+ expect(result.suggested).toBeNull();
+ expect(result.avoidTiers).toEqual(expect.arrayContaining(['heavy', 'medium']));
+ expect(result.failureSignal).toMatchObject({ tier: 'medium', provider: 'claude', model: 'sonnet' });
+ });
+
+ it('does not let failure signatures condemn a proven tier (#2329)', async () => {
+ // 'heavy' clears the high-success threshold in routingAccuracy, so the
+ // proven-tier suggestion stands and its absolute failures never add it to
+ // avoidTiers.
+ const data = makeLearningData({
+ byTaskType: {
+ 'proven-task': {
+ completed: 20, succeeded: 18, failed: 2,
+ totalDurationMs: 2000000, avgDurationMs: 100000, successRate: 90
+ }
+ },
+ routingAccuracy: {
+ 'proven-task': {
+ heavy: { succeeded: 18, failed: 2, lastAttempt: '2026-01-26T00:00:00.000Z' } // 90%
+ }
+ },
+ failureSignatures: {
+ 'test-failure': {
+ count: 3,
+ recent: [
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'proven-task' },
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'proven-task' },
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'proven-task' }
+ ]
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await suggestModelTier('proven-task');
+ expect(result.suggested).toBe('heavy');
+ expect(result.avoidTiers).not.toContain('heavy');
+ });
+
it('should prefer the lightest tier when several clear the high-success threshold', async () => {
// heavy has the marginally-higher success rate, but light also clears 80% —
// we should route to light to avoid spending a heavier model for the same outcome.
diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.js
index 0e258c1789..cd42393938 100644
--- a/server/services/taskLearning/index.js
+++ b/server/services/taskLearning/index.js
@@ -29,6 +29,7 @@ export {
export {
recordTaskCompletion,
buildTaskTelemetryContext,
+ computeLatencySplit,
recordFailureSignature,
resetTaskTypeLearning,
recalculateModelTierMetrics,
@@ -38,6 +39,7 @@ export {
export {
getTaskTypePriorityMultiplier,
suggestModelTier,
+ deriveFailureSignalAvoidance,
getRoutingAccuracy,
getPerformanceSummary,
getAdaptiveCooldownMultiplier,
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 14f1f2fa93..b5446804b1 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -38,6 +38,47 @@ function msBetween(startIso, endIso) {
return Math.max(0, end - start);
}
+/**
+ * Compute the queue/compute latency split for a completed run (issue #2329).
+ * Pure. Prefers measured values from source timestamps; where a source timestamp
+ * is missing, derives the missing leg from the wall/execution difference so a
+ * run without a `createdAt` (queue) or a runner `duration` (compute) still yields
+ * a usable split instead of a null.
+ *
+ * Sentinel discipline: every leg carries a `source` marker so a *derived* value
+ * is never confused with a *measured* one, and a legitimately-measured `0` is
+ * never confused with an *absent* leg (`null`). Derivation only fires when the
+ * other two legs are genuinely measured — an absent leg is never fabricated from
+ * two other absent/derived legs.
+ *
+ * @returns {{ wallMs:number|null, queueMs:number|null, executionMs:number|null,
+ * source:{ wall:'measured'|null, queue:'measured'|'derived'|null,
+ * execution:'measured'|'derived'|null } }}
+ */
+export function computeLatencySplit({ startedAt, completedAt, createdAt, durationMs }) {
+ const wallMs = msBetween(startedAt, completedAt);
+ let queueMs = msBetween(createdAt, startedAt);
+ let executionMs = Number.isFinite(durationMs) ? durationMs : null;
+
+ const source = {
+ wall: wallMs === null ? null : 'measured',
+ queue: queueMs === null ? null : 'measured',
+ execution: executionMs === null ? null : 'measured'
+ };
+
+ // Fallback: no createdAt but wall+compute measured → queue = wall − compute.
+ if (queueMs === null && wallMs !== null && executionMs !== null && executionMs <= wallMs) {
+ queueMs = wallMs - executionMs;
+ source.queue = 'derived';
+ } else if (executionMs === null && wallMs !== null && queueMs !== null && queueMs <= wallMs) {
+ // Fallback: no runner duration but wall+queue measured → compute = wall − queue.
+ executionMs = wallMs - queueMs;
+ source.execution = 'derived';
+ }
+
+ return { wallMs, queueMs, executionMs, source };
+}
+
/**
* Build a structured TaskTelemetryContext for a completed agent run (issue
* #2329). Pure — no I/O. Derives what is cheaply available from the agent/task
@@ -78,20 +119,21 @@ export function buildTaskTelemetryContext(agent, task) {
routingReason: meta.modelReason ?? null
};
- const executionMs = Number.isFinite(result.duration) ? result.duration : null;
+ // Queue/compute latency split with a wall-difference fallback when a source
+ // timestamp (task.createdAt or runner duration) is missing (issue #2329).
+ const latency = computeLatencySplit({
+ startedAt: agent?.startedAt,
+ completedAt: agent?.completedAt,
+ createdAt: task?.createdAt,
+ durationMs: result.duration
+ });
+
return {
taskType,
success,
failureSignature,
executionContext,
- latency: {
- // Wall time: spawn → completion (includes any in-agent waiting).
- wallMs: msBetween(agent?.startedAt, agent?.completedAt),
- // Queue/wait time only derivable when the source task carried a createdAt.
- queueMs: msBetween(task?.createdAt, agent?.startedAt),
- // Measured execution time reported by the runner.
- executionMs
- }
+ latency
};
}
diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.js
index 839c4c998f..e6647a90c3 100644
--- a/server/services/taskLearning/metrics.test.js
+++ b/server/services/taskLearning/metrics.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { buildTaskTelemetryContext, recordFailureSignature } from './metrics.js';
+import { buildTaskTelemetryContext, computeLatencySplit, recordFailureSignature } from './metrics.js';
// buildTaskTelemetryContext + recordFailureSignature are the pure telemetry
// enrichment core added for issue #2329. They take no I/O, so every branch is
@@ -44,7 +44,9 @@ describe('buildTaskTelemetryContext', () => {
expect(ctx.latency).toEqual({
wallMs: 300000, // 5 min
queueMs: 30000, // 30s
- executionMs: 250000
+ executionMs: 250000,
+ // All three legs measured from real timestamps/duration.
+ source: { wall: 'measured', queue: 'measured', execution: 'measured' }
});
});
@@ -95,7 +97,10 @@ describe('buildTaskTelemetryContext', () => {
inputChars: null, // null, not 0 — description absent, not empty
routingReason: null
});
- expect(ctx.latency).toEqual({ wallMs: null, queueMs: null, executionMs: null });
+ expect(ctx.latency).toEqual({
+ wallMs: null, queueMs: null, executionMs: null,
+ source: { wall: null, queue: null, execution: null }
+ });
expect(ctx.failureSignature).toEqual({
category: null,
messageSnippet: null,
@@ -111,10 +116,14 @@ describe('buildTaskTelemetryContext', () => {
expect(buildTaskTelemetryContext(noDescAgent, {}).executionContext.inputChars).toBeNull();
});
- it('leaves queueMs null when the task carries no createdAt', () => {
+ it('derives the queue leg from wall − compute when the task carries no createdAt (#2329)', () => {
+ // baseAgent: wall 300000, compute (duration) 250000, and NO createdAt.
+ // Rather than leaving queue null, the split falls back to wall − compute
+ // and marks it derived so it is never confused with a measured value.
const ctx = buildTaskTelemetryContext(baseAgent, { description: 'no createdAt', taskType: 'user' });
- expect(ctx.latency.queueMs).toBeNull();
expect(ctx.latency.wallMs).toBe(300000); // wall still derivable from agent timestamps
+ expect(ctx.latency.queueMs).toBe(50000); // 300000 − 250000
+ expect(ctx.latency.source).toEqual({ wall: 'measured', queue: 'derived', execution: 'measured' });
});
it('harvests a failure signature for a previously-untyped task via the classification hook (#2333)', () => {
@@ -215,3 +224,54 @@ describe('recordFailureSignature', () => {
expect(data.failureSignatures).toEqual({});
});
});
+
+describe('computeLatencySplit (#2329)', () => {
+ const S = '2026-07-09T10:00:00.000Z'; // startedAt
+ const C = '2026-07-09T10:05:00.000Z'; // completedAt (+5min)
+ const CREATED = '2026-07-09T09:59:30.000Z'; // 30s before start
+
+ it('reports all three legs as measured when every source is present', () => {
+ expect(computeLatencySplit({ startedAt: S, completedAt: C, createdAt: CREATED, durationMs: 250000 }))
+ .toEqual({
+ wallMs: 300000, queueMs: 30000, executionMs: 250000,
+ source: { wall: 'measured', queue: 'measured', execution: 'measured' }
+ });
+ });
+
+ it('derives the queue leg from wall − compute when createdAt is missing', () => {
+ const out = computeLatencySplit({ startedAt: S, completedAt: C, durationMs: 250000 });
+ expect(out.queueMs).toBe(50000);
+ expect(out.source.queue).toBe('derived');
+ expect(out.source.execution).toBe('measured');
+ });
+
+ it('derives the compute leg from wall − queue when the runner duration is missing', () => {
+ const out = computeLatencySplit({ startedAt: S, completedAt: C, createdAt: CREATED, durationMs: undefined });
+ expect(out.executionMs).toBe(270000); // 300000 − 30000
+ expect(out.source.execution).toBe('derived');
+ expect(out.source.queue).toBe('measured');
+ });
+
+ it('leaves a leg null (not fabricated) when wall itself is unmeasurable', () => {
+ // No completedAt → no wall → nothing to split from.
+ const out = computeLatencySplit({ startedAt: S, createdAt: CREATED, durationMs: 250000 });
+ expect(out.wallMs).toBeNull();
+ expect(out.executionMs).toBe(250000); // still measured directly
+ expect(out.queueMs).toBe(30000); // measured directly
+ expect(out.source).toEqual({ wall: null, queue: 'measured', execution: 'measured' });
+ });
+
+ it('does not derive a negative leg when compute exceeds wall', () => {
+ // duration (400000) > wall (300000): can't derive a sane queue leg.
+ const out = computeLatencySplit({ startedAt: S, completedAt: C, durationMs: 400000 });
+ expect(out.queueMs).toBeNull();
+ expect(out.source.queue).toBeNull();
+ });
+
+ it('keeps a measured 0 distinct from an absent leg', () => {
+ // createdAt === startedAt → genuine 0ms queue, measured (not null, not derived).
+ const out = computeLatencySplit({ startedAt: S, completedAt: C, createdAt: S, durationMs: 250000 });
+ expect(out.queueMs).toBe(0);
+ expect(out.source.queue).toBe('measured');
+ });
+});
diff --git a/server/services/taskLearning/routing.js b/server/services/taskLearning/routing.js
index e1084f6c21..1c87f45aed 100644
--- a/server/services/taskLearning/routing.js
+++ b/server/services/taskLearning/routing.js
@@ -58,6 +58,95 @@ const NON_ROUTABLE_LEARNED_TIERS = new Set(['minimal', 'low']);
/** Minimum success rate (%) for a tier to count as "proven" for a task type. */
const HIGH_SUCCESS_THRESHOLD = 80;
+/**
+ * Minimum recent failure samples on a single tier (scoped to a task type) before
+ * the enriched failure signatures can steer routing away from it. Matches the
+ * routingAccuracy "≥3 attempts" bar so a one-off failure never condemns a tier.
+ */
+const MIN_FAILURE_SAMPLES = 3;
+
+/** NUL separator joining provider+model into one tally key (safe: neither contains NUL). */
+const PAIR_SEP = '\x00';
+
+/** Key with the highest count in a `{ key: count }` tally (null when empty). */
+function topKey(counts) {
+ let best = null;
+ let bestCount = -1;
+ for (const [key, count] of Object.entries(counts)) {
+ if (count > bestCount) { best = key; bestCount = count; }
+ }
+ return best;
+}
+
+/**
+ * Consume the enriched failure signatures (issue #2329) to derive a
+ * recency-weighted tier avoidance for a task type. Pure — no I/O.
+ *
+ * `routingAccuracy` tracks per-tier success/failure counts but carries no
+ * provider/model attribution and is all-time (slow to react). The
+ * `failureSignatures.recent[]` samples (recorded by #2332) DO carry
+ * provider/model/tier attribution and are recency-bounded. This cross-references
+ * the two: a tier is steered away from only when it BOTH accumulates ≥
+ * MIN_FAILURE_SAMPLES recent failures for this task type AND is *unproven* in
+ * routingAccuracy (success rate < HIGH_SUCCESS_THRESHOLD, or no success data).
+ *
+ * Proven tiers (≥80% success) keep their slot despite a few absolute failures —
+ * failureSignatures records failures ONLY, so raw counts can never condemn a
+ * tier on their own (a tier with 100 successes + 3 failures is fine). The
+ * cross-check is what keeps this from starving a good tier.
+ *
+ * @returns {{ avoidTiers: string[], sampleCount: number,
+ * dominant: { tier, failures, provider, model }|null }}
+ */
+export function deriveFailureSignalAvoidance(data, taskType) {
+ const signatures = data?.failureSignatures || {};
+ const routing = data?.routingAccuracy?.[taskType] || {};
+
+ // Gather recent failure samples scoped to this task type across all categories.
+ const byTier = {};
+ let sampleCount = 0;
+ for (const bucket of Object.values(signatures)) {
+ for (const sample of bucket?.recent || []) {
+ if (sample?.taskType !== taskType || !sample.modelTier) continue;
+ if (NON_ROUTABLE_LEARNED_TIERS.has(sample.modelTier)) continue;
+ sampleCount++;
+ const tier = (byTier[sample.modelTier] ||= { failures: 0, pairs: {} });
+ tier.failures++;
+ // Tally provider+model as ONE pair so the reported attribution is a
+ // combination that actually failed together (not a top-provider crossed
+ // with an unrelated top-model). NUL-joined; '' encodes an absent side.
+ const pairKey = `${sample.provider ?? ''}${PAIR_SEP}${sample.model ?? ''}`;
+ tier.pairs[pairKey] = (tier.pairs[pairKey] || 0) + 1;
+ }
+ }
+
+ const avoidTiers = [];
+ let dominant = null;
+ for (const [tier, stats] of Object.entries(byTier)) {
+ const r = routing[tier];
+ const attempts = r ? (r.succeeded + r.failed) : 0;
+ // null = no success data (not "0% success") — an unproven tier by default.
+ const successRate = attempts > 0 ? Math.round((r.succeeded / attempts) * 100) : null;
+ const proven = successRate !== null && successRate >= HIGH_SUCCESS_THRESHOLD;
+ if (proven || stats.failures < MIN_FAILURE_SAMPLES) continue;
+ avoidTiers.push(tier);
+ // `dominant` is the AVOIDED tier with the most recent failures — the tier we
+ // actually steer away from — so the attribution surfaced in logs/reasons can
+ // never name a proven tier that isn't in avoidTiers. null when nothing avoided.
+ if (!dominant || stats.failures > dominant.failures) {
+ const [provider, model] = (topKey(stats.pairs) || PAIR_SEP).split(PAIR_SEP);
+ dominant = { tier, failures: stats.failures, provider: provider || null, model: model || null };
+ }
+ }
+
+ return { avoidTiers, sampleCount, dominant };
+}
+
+/** Union two tier lists, preserving order and dropping duplicates. */
+function mergeAvoidTiers(...lists) {
+ return [...new Set(lists.flat().filter(Boolean))];
+}
+
/**
* Get suggested priority boost for a task type based on historical success
* Returns a multiplier: >1 for boost, <1 for demotion
@@ -93,9 +182,46 @@ export async function suggestModelTier(taskType) {
const data = await loadLearningData();
+ // Recency-weighted, provider-attributed avoidance from the enriched failure
+ // signatures (#2329) — folded into every suggestion below so a tier that's
+ // freshly degrading is steered away from before its all-time routingAccuracy
+ // rate crosses the hard misroute line. Computed BEFORE the completions guard:
+ // the signal has its own MIN_FAILURE_SAMPLES bar, so 3-4 recent failures on a
+ // tier can steer selection even before routingAccuracy has enough data to
+ // suggest a tier at all.
+ const failureAvoidance = deriveFailureSignalAvoidance(data, taskType);
+ const withFailureSignal = (suggestion, existingAvoid = []) => {
+ const avoidTiers = mergeAvoidTiers(existingAvoid, failureAvoidance.avoidTiers);
+ // If the tier we were about to suggest is itself failure-flagged (a 60-79%
+ // "successful" tier, or the generic `heavy` fallback), don't route to it —
+ // drop to avoidance-only (suggested: null) so selection steers off it and
+ // picks the best non-avoided tier instead of the tier the signal condemned.
+ const suggested = avoidTiers.includes(suggestion.suggested) ? null : suggestion.suggested;
+ return {
+ ...suggestion,
+ suggested,
+ avoidTiers,
+ ...(failureAvoidance.dominant ? { failureSignal: failureAvoidance.dominant } : {})
+ };
+ };
+ // Avoidance-only suggestion (no positive tier pick) built purely from the
+ // failure signal — used both below the completions threshold and as the final
+ // fallback when routingAccuracy is quiet.
+ const avoidanceOnlySuggestion = () => {
+ const { dominant } = failureAvoidance;
+ return withFailureSignal({
+ suggested: null,
+ reason: `${taskType} shows ${dominant.failures} recent failure(s) on ${dominant.tier} tier`
+ + (dominant.provider ? ` via ${dominant.provider}${dominant.model ? `/${dominant.model}` : ''}` : '')
+ + ' — avoiding it'
+ });
+ };
+
const metrics = data.byTaskType[taskType];
if (!metrics || metrics.completed < 5) {
- return null; // Not enough data to suggest
+ // Not enough completions for a routingAccuracy-based tier suggestion, but a
+ // strong recency signal can still steer selection off a freshly-failing tier.
+ return failureAvoidance.avoidTiers.length > 0 ? avoidanceOnlySuggestion() : null;
}
// Check routing accuracy for tier-specific signals
@@ -122,31 +248,40 @@ export async function suggestModelTier(taskType) {
const reason = provenTiers.length > 1
? `${taskType} succeeds with ${lightest.tier} tier (${lightest.successRate}%) — using lightest of ${provenTiers.length} proven tiers`
: `${taskType} has ${lightest.successRate}% success with ${lightest.tier} tier`;
- return {
- suggested: lightest.tier,
- reason,
- avoidTiers: tierResults.filter(t => t.successRate < 40).map(t => t.tier)
- };
+ return withFailureSignal(
+ { suggested: lightest.tier, reason },
+ tierResults.filter(t => t.successRate < 40).map(t => t.tier)
+ );
}
// If current default tier is failing, find a better one
const failingTiers = tierResults.filter(t => t.successRate < 40);
if (failingTiers.length > 0) {
const successfulTier = tierResults.find(t => t.successRate >= 60);
- return {
- suggested: successfulTier?.tier || 'heavy',
- reason: `${taskType} fails with ${failingTiers.map(t => t.tier).join(', ')} (${failingTiers.map(t => `${t.successRate}%`).join(', ')})`,
- avoidTiers: failingTiers.map(t => t.tier)
- };
+ return withFailureSignal(
+ {
+ suggested: successfulTier?.tier || 'heavy',
+ reason: `${taskType} fails with ${failingTiers.map(t => t.tier).join(', ')} (${failingTiers.map(t => `${t.successRate}%`).join(', ')})`
+ },
+ failingTiers.map(t => t.tier)
+ );
}
}
// Fallback: if overall success rate is low, suggest heavier model
if (metrics.successRate < 60) {
- return {
+ return withFailureSignal({
suggested: 'heavy',
reason: `${taskType} has ${metrics.successRate}% success rate - heavier model may help`
- };
+ });
+ }
+
+ // No tier-level or overall signal, but the enriched failure signatures flagged
+ // a currently-degrading tier — emit an avoidance-only suggestion so selection
+ // steers off it (agentModelSelection picks the best non-avoided tier) even
+ // though the all-time routingAccuracy rate hasn't crossed the misroute line.
+ if (failureAvoidance.avoidTiers.length > 0) {
+ return avoidanceOnlySuggestion();
}
return null; // Current selection is working fine
diff --git a/server/services/taskLearning/routing.test.js b/server/services/taskLearning/routing.test.js
new file mode 100644
index 0000000000..b942bbd829
--- /dev/null
+++ b/server/services/taskLearning/routing.test.js
@@ -0,0 +1,87 @@
+import { describe, it, expect } from 'vitest';
+import { deriveFailureSignalAvoidance } from './routing.js';
+
+// deriveFailureSignalAvoidance is the pure "routing consumes the enriched
+// failure signatures" core added for issue #2329. It takes learning data + a
+// task type and returns a recency-weighted tier avoidance cross-referenced
+// against routingAccuracy — no I/O, so every branch is exercised directly.
+
+const sample = (over = {}) => ({
+ modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'user-task',
+ messageSnippet: 'boom', failurePosition: 'testing', wallMs: 1000, executionMs: 900,
+ ...over
+});
+
+const dataWith = (recent, routingAccuracy = {}) => ({
+ failureSignatures: { 'test-failure': { count: recent.length, recent } },
+ routingAccuracy
+});
+
+describe('deriveFailureSignalAvoidance (#2329)', () => {
+ it('returns no avoidance below the minimum sample bar', () => {
+ const data = dataWith([sample(), sample()]); // only 2 < MIN_FAILURE_SAMPLES(3)
+ const out = deriveFailureSignalAvoidance(data, 'user-task');
+ expect(out.avoidTiers).toEqual([]);
+ expect(out.sampleCount).toBe(2);
+ });
+
+ it('flags an unproven tier with enough recent failures and attributes provider/model', () => {
+ const data = dataWith([
+ sample({ modelTier: 'heavy', provider: 'claude', model: 'opus' }),
+ sample({ modelTier: 'heavy', provider: 'claude', model: 'opus' }),
+ sample({ modelTier: 'heavy', provider: 'codex', model: 'gpt' })
+ ]); // no routingAccuracy → tier is unproven (no success data)
+ const out = deriveFailureSignalAvoidance(data, 'user-task');
+ expect(out.avoidTiers).toContain('heavy');
+ expect(out.dominant).toMatchObject({ tier: 'heavy', failures: 3, provider: 'claude', model: 'opus' });
+ });
+
+ it('does NOT flag a proven tier (>=80% in routingAccuracy) despite absolute failures', () => {
+ // failureSignatures only records failures — a tier with 40 successes + 3
+ // failures is fine and must keep its slot.
+ const data = dataWith(
+ [sample(), sample(), sample()],
+ { 'user-task': { heavy: { succeeded: 40, failed: 3 } } } // ~93%
+ );
+ const out = deriveFailureSignalAvoidance(data, 'user-task');
+ expect(out.avoidTiers).toEqual([]);
+ // dominant is scoped to AVOIDED tiers only — a proven tier that isn't being
+ // steered away from must never be reported as the dominant "avoided" tier.
+ expect(out.dominant).toBeNull();
+ });
+
+ it('flags an unproven tier that is below the high-success threshold in routingAccuracy', () => {
+ const data = dataWith(
+ [sample(), sample(), sample()],
+ { 'user-task': { heavy: { succeeded: 3, failed: 7 } } } // 30% < 80%
+ );
+ expect(deriveFailureSignalAvoidance(data, 'user-task').avoidTiers).toContain('heavy');
+ });
+
+ it('scopes samples to the requested task type', () => {
+ const data = dataWith([
+ sample({ taskType: 'other-task' }),
+ sample({ taskType: 'other-task' }),
+ sample({ taskType: 'other-task' })
+ ]);
+ const out = deriveFailureSignalAvoidance(data, 'user-task');
+ expect(out.sampleCount).toBe(0);
+ expect(out.avoidTiers).toEqual([]);
+ });
+
+ it('ignores non-routable learned tiers (minimal/low)', () => {
+ const data = dataWith([
+ sample({ modelTier: 'minimal' }),
+ sample({ modelTier: 'low' }),
+ sample({ modelTier: 'minimal' })
+ ]);
+ const out = deriveFailureSignalAvoidance(data, 'user-task');
+ expect(out.sampleCount).toBe(0);
+ expect(out.avoidTiers).toEqual([]);
+ });
+
+ it('tolerates a pre-#2329 learning file with no failureSignatures key', () => {
+ const out = deriveFailureSignalAvoidance({ routingAccuracy: {} }, 'user-task');
+ expect(out).toEqual({ avoidTiers: [], sampleCount: 0, dominant: null });
+ });
+});