Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): bucket rerank budget failures (#3628) (#4002)
Javier Aldapeb92cc967df65
diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex a9d580436f..9a284737bb 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -1746,6 +1746,8 @@ export async function checkVoiceGateHealth(engine: BrainEngine): Promise<Check>* Below that they're noise; reranker fails open anyway.* 5) Payload-too-large failures: warn at >=1 (indicates a workload* mismatch that the operator should know about).+ * 6) Budget/pricing failures: warn at >=1 with the rerank pricing surface+ * and --max-cost escape hatch.** Engine-agnostic (file-based + one config-key read).*/@@ -1784,6 +1786,15 @@ export async function checkRerankerHealth(engine: BrainEngine): Promise<Check> {};}+ const budgetFails = failures.filter((f) => f.reason === 'budget');+ if (budgetFails.length > 0) {+ return {+ name: 'reranker_health',+ status: 'warn',+ message: `${budgetFails.length} reranker budget/pricing failure(s) in last 7 days. Fix: add rerank pricing to src/core/embedding-pricing.ts or drop --max-cost.`,+ };+ }+const transientFails = failures.filter((f) => f.reason === 'network' || f.reason === 'timeout' || f.reason === 'rate_limit',);diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.tsindex 2bc8f9f1f3..6736ccf48c 100644--- a/src/core/budget/budget-tracker.ts+++ b/src/core/budget/budget-tracker.ts@@ -332,7 +332,7 @@ export class BudgetTracker {// pricing we can't enforce the cap, and silently ignoring it would// void the contract.const msg = `${this.opts.label}: no pricing entry for model "${estimate.modelId}" (kind=${estimate.kind}). ` +- `Add it to src/core/${estimate.kind === 'embed' ? 'embedding-pricing.ts' : 'anthropic-pricing.ts'} or drop --max-cost.`;+ `Add it to src/core/${estimate.kind === 'embed' || estimate.kind === 'rerank' ? 'embedding-pricing.ts' : 'anthropic-pricing.ts'} or drop --max-cost.`;this.fireExhausted();throw new BudgetExhausted(msg, {reason: 'no_pricing',diff --git a/src/core/rerank-audit.ts b/src/core/rerank-audit.tsindex 87847c0eff..5b9026dfb9 100644--- a/src/core/rerank-audit.ts+++ b/src/core/rerank-audit.ts@@ -27,12 +27,13 @@import { createAuditWriter, computeIsoWeekFilename } from './audit/audit-writer.ts';-/** Stable error-classification union; matches RerankError.reason. */+/** Stable error-classification union for reranker fail-open audit rows. */export type RerankFailureReason =| 'auth'| 'rate_limit'| 'network'| 'timeout'+ | 'budget'| 'payload_too_large'| 'unknown';diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.tsindex 8634080263..9600d6e642 100644--- a/src/core/search/rerank.ts+++ b/src/core/search/rerank.ts@@ -20,6 +20,7 @@import { createHash } from 'crypto';import type { SearchResult } from '../types.ts';import { rerank as gatewayRerank, RerankError, type RerankInput, type RerankResult } from '../ai/gateway.ts';+import { BudgetExhausted } from '../budget/budget-tracker.ts';import { logRerankFailure, type RerankFailureReason } from '../rerank-audit.ts';export interface RerankerOpts {@@ -44,6 +45,17 @@ function hashQuery(query: string): string {return createHash('sha256').update(query, 'utf8').digest('hex').slice(0, 8);}+function classifyRerankFailure(err: unknown): RerankFailureReason {+ if (err instanceof RerankError) return err.reason;+ if (+ err instanceof BudgetExhausted ||+ (err && typeof err === 'object' && (err as { tag?: unknown }).tag === 'BUDGET_EXHAUSTED')+ ) {+ return 'budget';+ }+ return 'unknown';+}+/*** Reorder the top `topNIn` results by reranker relevance score. The* un-reranked tail (any rows past topNIn) preserves its original RRF@@ -83,8 +95,7 @@ export async function applyReranker(...(opts.model ? { model: opts.model } : {}),});} catch (err) {- const reason: RerankFailureReason =- err instanceof RerankError ? err.reason : 'unknown';+ const reason = classifyRerankFailure(err);const errorSummary = err instanceof Error ? err.message : String(err);try {logRerankFailure({diff --git a/test/core/budget/budget-tracker.test.ts b/test/core/budget/budget-tracker.test.tsindex 163c3256f3..b85acc5fab 100644--- a/test/core/budget/budget-tracker.test.ts+++ b/test/core/budget/budget-tracker.test.ts@@ -305,6 +305,25 @@ describe('BudgetTracker.reserve', () => {expect((caught as BudgetExhausted).reason).toBe('no_pricing');});+ test('#3628: unknown hosted rerank provider points no-pricing guidance at embedding-pricing', () => {+ const t = new BudgetTracker({ maxCostUsd: 1.0, label: 'test', auditPath });+ let caught: unknown = null;+ try {+ t.reserve({+ modelId: 'acmecorp:unpriced-reranker-v9',+ estimatedInputTokens: 100,+ maxOutputTokens: 0,+ kind: 'rerank',+ });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(BudgetExhausted);+ expect((caught as BudgetExhausted).reason).toBe('no_pricing');+ expect((caught as Error).message).toContain('embedding-pricing.ts');+ expect((caught as Error).message).not.toContain('anthropic-pricing.ts');+ });+test('v0.40.x REGRESSION: known hosted embed (openai) still real-priced (trips a tiny cap)', () => {// 3-small is $0.02/1M tokens. 1M tokens projects $0.02 > $0.0001 cap, so a// real (nonzero) price trips the cost gate — proving it's NOT on the $0diff --git a/test/doctor.test.ts b/test/doctor.test.tsindex 89097400e2..6cef46c379 100644--- a/test/doctor.test.ts+++ b/test/doctor.test.ts@@ -127,6 +127,33 @@ describe('doctor command', () => {}});+ test('#3628: reranker_health surfaces budget failures with pricing guidance', async () => {+ const { checkRerankerHealth } = await import('../src/commands/doctor.ts');+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-rerank-budget-doctor-'));+ try {+ await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {+ logRerankFailure({+ model: 'acmecorp:unpriced-reranker-v9',+ reason: 'budget',+ query_hash: 'budget01',+ doc_count: 30,+ error_summary: 'no pricing entry for model "acmecorp:unpriced-reranker-v9" (kind=rerank)',+ });+ const check = await checkRerankerHealth({+ async getConfig(key: string): Promise<string | null> {+ return key === 'search.reranker.enabled' ? 'true' : null;+ },+ } as any);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('budget/pricing');+ expect(check.message).toContain('embedding-pricing.ts');+ expect(check.message).toContain('--max-cost');+ });+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ });+test('runDoctor accepts null engine for filesystem-only mode', async () => {const { runDoctor } = await import('../src/commands/doctor.ts');// runDoctor should accept null engine — it runs filesystem checks only.diff --git a/test/e2e/doctor-progress.test.ts b/test/e2e/doctor-progress.test.tsindex f318f52e88..39d943c729 100644--- a/test/e2e/doctor-progress.test.ts+++ b/test/e2e/doctor-progress.test.ts@@ -25,6 +25,7 @@ if (skip) {}const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');+const DOCTOR_PROGRESS_TIMEOUT_MS = 60_000;describeE2E('gbrain doctor --progress-json (E2E)', () => {beforeAll(async () => {@@ -41,7 +42,7 @@ describeE2E('gbrain doctor --progress-json (E2E)', () => {const res = spawnSync('bun', [CLI, '--progress-json', 'doctor', '--json'], {encoding: 'utf-8',env: { ...process.env, NO_COLOR: '1' },- timeout: 30_000,+ timeout: DOCTOR_PROGRESS_TIMEOUT_MS,});// Even if some checks warn, doctor runs to completion. Failures would@@ -85,13 +86,13 @@ describeE2E('gbrain doctor --progress-json (E2E)', () => {// progress-line pollution on stdout.const parsed = JSON.parse(res.stdout);expect(Array.isArray(parsed.checks) || Array.isArray(parsed)).toBe(true);- });+ }, DOCTOR_PROGRESS_TIMEOUT_MS + 5_000);test('default (no --progress-json) writes human-plain progress to stderr only', () => {const res = spawnSync('bun', [CLI, 'doctor'], {encoding: 'utf-8',env: { ...process.env, NO_COLOR: '1' },- timeout: 30_000,+ timeout: DOCTOR_PROGRESS_TIMEOUT_MS,});// Stdout may contain the check summary (human-readable) but should NOT@@ -103,13 +104,13 @@ describeE2E('gbrain doctor --progress-json (E2E)', () => {if (res.stderr.length > 0) {expect(res.stderr).toContain('doctor.db_checks');}- });+ }, DOCTOR_PROGRESS_TIMEOUT_MS + 5_000);test('--quiet suppresses progress entirely', () => {const res = spawnSync('bun', [CLI, '--quiet', 'doctor'], {encoding: 'utf-8',env: { ...process.env, NO_COLOR: '1' },- timeout: 30_000,+ timeout: DOCTOR_PROGRESS_TIMEOUT_MS,});// With --quiet the reporter emits no start/finish/tick lines on stderr.@@ -117,5 +118,5 @@ describeE2E('gbrain doctor --progress-json (E2E)', () => {// just no progress phases.expect(res.stderr).not.toContain('[doctor.db_checks]');expect(res.stderr).not.toContain('"event":"start"');- });+ }, DOCTOR_PROGRESS_TIMEOUT_MS + 5_000);});diff --git a/test/search/rerank.test.ts b/test/search/rerank.test.tsindex 29a2962d14..3d8baef7cc 100644--- a/test/search/rerank.test.ts+++ b/test/search/rerank.test.ts@@ -17,6 +17,7 @@ import * as os from 'node:os';import * as path from 'node:path';import { applyReranker, type RerankerOpts } from '../../src/core/search/rerank.ts';import { RerankError, type RerankResult } from '../../src/core/ai/gateway.ts';+import { BudgetExhausted } from '../../src/core/budget/budget-tracker.ts';import { readRecentRerankFailures } from '../../src/core/rerank-audit.ts';import type { SearchResult } from '../../src/core/types.ts';import { withEnv } from '../helpers/with-env.ts';@@ -209,6 +210,37 @@ describe('applyReranker — fail-open on every RerankError reason', () => {expect(out).toEqual(results);});+ test('#3628: BudgetExhausted fail-opens and audits budget instead of unknown', async () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-rerank-budget-'));+ try {+ await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {+ const results = [makeResult('a', 1.0, 'a')];+ const out = await applyReranker('q', results, {+ enabled: true,+ topNIn: 1,+ topNOut: null,+ model: 'acmecorp:unpriced-reranker-v9',+ rerankerFn: async () => {+ throw new BudgetExhausted('rerank budget missing pricing', {+ reason: 'no_pricing',+ spent: 0,+ cap: 1,+ modelId: 'acmecorp:unpriced-reranker-v9',+ });+ },+ });++ expect(out).toEqual(results);+ const failures = readRecentRerankFailures(1);+ expect(failures).toHaveLength(1);+ expect(failures[0]!.reason).toBe('budget');+ expect(failures[0]!.error_summary).toContain('missing pricing');+ });+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ });+test('fail-open on malformed reranker response (empty results array)', async () => {const results = [makeResult('a', 1.0, 'a')];const opts: RerankerOpts = {