Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(sniper): routing watchdog detects fallbacks by answered_by mismatch, not prefix

nirholas0c8609d6dbc4
diff --git a/api/_lib/sniper-loops-health.js b/api/_lib/sniper-loops-health.js
index ca2dd62aa..00e097f5c 100644
--- a/api/_lib/sniper-loops-health.js
+++ b/api/_lib/sniper-loops-health.js
@@ -120,13 +120,40 @@ export function findWalletlessArms(rows) {
return out;
}
+/**
+ * Is one verdict row a fallback answer? The ledger stores the REQUESTED model
+ * in `model` (the experiment arm's identity, also the on-conflict key), so a
+ * `fallback:` prefix never reaches that column. What the worker's judge writes
+ * on the two paths (workers/agent-sniper/llm-judge.js):
+ * OpenRouter answered -> answered_by === model (same string, same variable)
+ * free-chain fallback -> answered_by = the raw free model name ("llama-3.1-8b-instant")
+ * So the truth test is a MISMATCH between answered_by and model, not a prefix.
+ * The first probe shipped prefix-only and read 0/225 fallbacks during a full
+ * OpenRouter outage: a false negative from exactly the silence class this
+ * watchdog exists to catch. Pure.
+ *
+ * @param {string|null|undefined} model requested model recorded on the row
+ * @param {string|null|undefined} answeredBy who actually replied (null on pre-column rows)
+ * @returns {boolean}
+ */
+export function isFallbackAnswer(model, answeredBy) {
+ const req = String(model || '').trim().toLowerCase();
+ const ans = String(answeredBy || '').trim().toLowerCase();
+ if (req.startsWith('fallback:') || ans.startsWith('fallback:')) return true;
+ // No answered_by (legacy row) = unknown; never count unknowns as fallbacks,
+ // a false page teaches operators to ignore the real one.
+ if (!ans) return false;
+ return ans !== req;
+}
+
/**
* Named-model routing health. The July 2026 audit note "the failover chain
* answering most calls muddied the model-vs-model comparison" turned out to be
* an OpenRouter account sitting at zero credits for weeks: the key stayed
* valid, every completion 402'd, the free chain silently absorbed the traffic,
* and no check anywhere measured it. This one does: given the last hour's
- * verdict counts, alarm when fallbacks answered nearly everything. Pure.
+ * verdict counts (fallbacks classified per isFallbackAnswer), alarm when
+ * fallbacks answered nearly everything. Pure.
*
* @param {{ total:number, fallback:number }} counts verdicts in the window
* @param {{ minSample?:number, maxShare?:number }} [opts]
@@ -137,11 +164,14 @@ export function classifyLlmRouting(counts, { minSample = 20, maxShare = 0.9 } =
const fallback = Number(counts?.fallback) || 0;
if (total < minSample) return { degraded: false, share: null, detail: `only ${total} verdicts in window (need ${minSample})` };
const share = fallback / total;
+ const degraded = share >= maxShare;
return {
- degraded: share >= maxShare,
+ degraded,
share: Number(share.toFixed(3)),
detail: `${fallback}/${total} verdicts answered by fallback models (${Math.round(share * 100)}%). ` +
- 'The named models are not answering: check OpenRouter credits/keys. Strict arms are paused until this clears; verdicts still record for calibration.',
+ (degraded
+ ? 'The named models are not answering: check OpenRouter credits/keys. Strict arms are paused until this clears; verdicts still record for calibration.'
+ : 'Named-model routing is healthy.'),
};
}
diff --git a/api/cron/sniper-loops-health.js b/api/cron/sniper-loops-health.js
index 173bb7674..d0d5b9ab0 100644
--- a/api/cron/sniper-loops-health.js
+++ b/api/cron/sniper-loops-health.js
@@ -18,7 +18,7 @@ import { env } from '../_lib/env.js';
import { constantTimeEquals } from '../_lib/crypto.js';
import { sql } from '../_lib/db.js';
import { sendOpsAlert } from '../_lib/alerts.js';
-import { LOOPS, classifyLlmRouting, classifyLoopHealth, describeStale, findWalletlessArms } from '../_lib/sniper-loops-health.js';
+import { LOOPS, classifyLlmRouting, classifyLoopHealth, describeStale, findWalletlessArms, isFallbackAnswer } from '../_lib/sniper-loops-health.js';
const NETWORK = 'mainnet';
@@ -83,17 +83,25 @@ export default wrapCron(async (req, res) => {
// Named-model routing: are the arms' named models actually answering, or is
// the free fallback chain absorbing everything (as it silently did for weeks
- // on a zero-credit OpenRouter account)? answered_by records who really
- // replied; the fallback tag is set by the judge at answer time.
+ // on a zero-credit OpenRouter account)? The ledger keys rows by the REQUESTED
+ // model, so fallback detection is answered_by vs model mismatch, classified
+ // in JS by the tested isFallbackAnswer (a prefix-only SQL filter read 0%
+ // during a real outage).
let routing = { degraded: false, share: null, detail: 'not probed' };
try {
- const [row] = await sql`
- select count(*)::int as total,
- count(*) filter (where answered_by ilike 'fallback:%' or model ilike 'fallback:%')::int as fallback
+ const rows = await sql`
+ select model, answered_by, count(*)::int as n
from sniper_llm_verdicts
where network = ${NETWORK} and created_at > now() - interval '1 hour'
+ group by model, answered_by
`;
- routing = classifyLlmRouting(row || {});
+ let total = 0;
+ let fallback = 0;
+ for (const r of rows) {
+ total += r.n;
+ if (isFallbackAnswer(r.model, r.answered_by)) fallback += r.n;
+ }
+ routing = classifyLlmRouting({ total, fallback });
} catch (err) {
broken.push({ name: 'llm-routing', probeError: err?.message || 'query failed' });
}
diff --git a/tests/sniper-postmortem-fixes.test.js b/tests/sniper-postmortem-fixes.test.js
index 275fe4dcc..32f033cdf 100644
--- a/tests/sniper-postmortem-fixes.test.js
+++ b/tests/sniper-postmortem-fixes.test.js
@@ -14,7 +14,7 @@
import { describe, expect, it } from 'vitest';
import { llmVerdictGate } from '../workers/agent-sniper/llm-judge.js';
import { decideLiquidityDecay, updateStaleClock } from '../workers/agent-sniper/exit-logic.js';
-import { LOOPS, classifyLlmRouting, classifyLoopHealth, describeStale, findWalletlessArms } from '../api/_lib/sniper-loops-health.js';
+import { LOOPS, classifyLlmRouting, classifyLoopHealth, describeStale, findWalletlessArms, isFallbackAnswer } from '../api/_lib/sniper-loops-health.js';
describe('llmVerdictGate', () => {
const strat = { llm_min_confidence: 0.65, llm_max_confidence: 0.9, llm_strict_model: false };
@@ -144,6 +144,30 @@ describe('classifyLoopHealth (count rows, not status codes)', () => {
});
});
+describe('isFallbackAnswer (the ledger keys rows by REQUESTED model)', () => {
+ it('flags the real outage shape: named model answered by a free-chain model', () => {
+ // The exact rows observed live on 2026-07-25 while the prefix-only SQL read 0%.
+ expect(isFallbackAnswer('moonshotai/kimi-k3', 'Meta-Llama-3_3-70B-Instruct')).toBe(true);
+ expect(isFallbackAnswer('anthropic/claude-haiku-4.5', 'llama-3.1-8b-instant')).toBe(true);
+ expect(isFallbackAnswer('openrouter/auto', 'llama-3.3-70b-versatile')).toBe(true);
+ });
+
+ it('passes when the requested model itself replied', () => {
+ expect(isFallbackAnswer('x-ai/grok-4.3', 'x-ai/grok-4.3')).toBe(false);
+ expect(isFallbackAnswer('moonshotai/kimi-k3', ' Moonshotai/Kimi-K3 ')).toBe(false); // case/space tolerant
+ });
+
+ it('still honors an explicit fallback: prefix on either side', () => {
+ expect(isFallbackAnswer('fallback:ovh', 'ovh')).toBe(true);
+ expect(isFallbackAnswer('moonshotai/kimi-k3', 'fallback:groq#instant')).toBe(true);
+ });
+
+ it('never counts a legacy row with no answered_by as a fallback', () => {
+ expect(isFallbackAnswer('moonshotai/kimi-k3', null)).toBe(false);
+ expect(isFallbackAnswer('moonshotai/kimi-k3', '')).toBe(false);
+ });
+});
+
describe('classifyLlmRouting (the zero-credit OpenRouter outage class)', () => {
it('alarms when fallbacks absorb nearly all verdicts', () => {
const r = classifyLlmRouting({ total: 100, fallback: 98 });