Compare commits

..
Author SHA1 Message Date
d9834a7a15 feat(ai): add reranker touchpoint to LiteLLM proxy recipe (takeover of #2455)
LiteLLM normalizes Cohere/Voyage/Jina rerank backends to the wire shape
gateway.rerank() already speaks, so a reranker touchpoint on the litellm
recipe makes any proxied rerank model reachable via
`search.reranker.model litellm:<model>` with no adapter.

Repairs from the original PR:
- path is the LEAF '/rerank' (not '/v1/rerank'): LiteLLM serves both
  /rerank and /v1/rerank, and the recipe's setup_hint allows
  LITELLM_BASE_URL with or without the /v1 suffix — pinning '/v1/rerank'
  doubled to /v1/v1/rerank (404) on /v1-suffixed bases.
- setup_hint appends the rerank guidance to master's current line instead
  of replacing it with a stale pre-/v1-suffix version.
- cost_per_1m_tokens_usd stays undefined (pricing-unknown), matching the
  recipe's embedding/chat touchpoints and budget-tracker's deliberate
  litellm exclusion from the free-provider sets (a proxy can front a paid
  provider; the touchpoint field isn't consumed by rerank pricing anyway).

Test drives gateway.rerank()'s real URL builder via the stubbed transport
for both base-URL forms; the /v1-suffixed case fails with the original
PR's path.

Co-authored-by: ozp <ozp@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:28:27 -07:00
6 changed files with 127 additions and 178 deletions
+31 -1
View File
@@ -56,6 +56,36 @@ export const litellmProxy: Recipe = {
cost_per_1m_output_usd: undefined,
price_last_verified: '2026-06-14',
},
// LiteLLM normalizes Cohere / Voyage / Jina / etc. rerank backends to the
// same wire shape gbrain's gateway.rerank() already speaks (the
// ZeroEntropy/llama.cpp contract):
// { model, query, documents, top_n } → { results: [{ index, relevance_score }] }
// So any rerank model the user registers in their LiteLLM config is
// reachable via `gbrain config set search.reranker.model litellm:<model>`
// with no request/response adapter — same as embeddings ride the proxy.
reranker: {
models: [], // user-provided; whatever rerank models the proxy serves
// No canonical default — the proxy defines its own model ids. The user
// sets search.reranker.model explicitly (mirrors the embedding
// touchpoint's user_provided_models contract).
default_model: '',
// The proxied backend bills (Cohere/Voyage/…); pricing-unknown is the
// honest state — same stance as this recipe's embedding/chat
// touchpoints and budget-tracker's deliberate litellm exclusion from
// the free-provider sets.
cost_per_1m_tokens_usd: undefined,
price_last_verified: '2026-06-27',
max_payload_bytes: 5_000_000,
// LEAF path only (matches llama-server-reranker's convention). LiteLLM
// serves both `/rerank` and `/v1/rerank`, and LITELLM_BASE_URL may be
// set with or without the `/v1` suffix (the setup_hint allows both), so
// the leaf form yields a valid route either way:
// http://localhost:4000 + /rerank → /rerank ✓
// http://localhost:4000/v1 + /rerank → /v1/rerank ✓
// Pinning '/v1/rerank' here would double to /v1/v1/rerank → 404 on
// /v1-suffixed bases.
path: '/rerank',
},
},
setup_hint: 'Run LiteLLM (https://docs.litellm.ai) in front of any provider; set LITELLM_BASE_URL (include the /v1 suffix if your proxy serves the OpenAI route there, e.g. http://localhost:4000/v1) + pass --embedding-model litellm:<model> and --embedding-dimensions <N>.',
setup_hint: 'Run LiteLLM (https://docs.litellm.ai) in front of any provider; set LITELLM_BASE_URL (include the /v1 suffix if your proxy serves the OpenAI route there, e.g. http://localhost:4000/v1) + pass --embedding-model litellm:<model> and --embedding-dimensions <N>. For rerank: register a rerank model in LiteLLM and set search.reranker.model litellm:<model-name>.',
};
+7 -55
View File
@@ -5565,78 +5565,30 @@ export class PostgresEngine implements BrainEngine {
});
}
/**
* perf (#1694 by @Omerbahari): process-lifetime config cache. A single
* search fires ~85 getConfig() reads (loadConfigWithEngine x2, plus
* mode/cache/intent/rerank/graph-signals resolvers). On a remote pooler
* each read is a round-trip; serial they dominate query latency and can
* push the op handler past cli.ts's 10s disconnect force-exit, truncating
* stdout. First read batch-loads the whole `config` table into this Map
* (inside the same connRetry posture as the per-key read #1603/#1891);
* setConfig/unsetConfig write through. TTL bounds staleness for
* multi-writer processes; GBRAIN_CONFIG_CACHE_TTL_MS=0 disables.
* Only present keys are stored Map.has() distinguishes known-absent.
*/
private _configCache: Map<string, string> | null = null;
private _configCacheLoadedAt = 0;
private _configCacheLoad: Promise<void> | null = null;
private get _configCacheTtlMs(): number {
const raw = process.env.GBRAIN_CONFIG_CACHE_TTL_MS;
if (raw !== undefined) {
const n = parseInt(raw, 10);
if (Number.isFinite(n) && n >= 0) return n;
}
return 30_000;
}
async getConfig(key: string): Promise<string | null> {
// #1603: a transient pooler drop on this read used to throw / fall through
// to defaults silently — which on remote Postgres surfaces as the wrong
// search mode/knobs and empty-stdout queries. Both the batch load and the
// cache-off per-key read keep the connRetry reconnect posture.
const ttl = this._configCacheTtlMs;
if (ttl === 0) {
return this.connRetry(async () => {
const rows = await this.sql`SELECT value FROM config WHERE key = ${key}`;
return rows.length > 0 ? (rows[0].value as string) : null;
});
}
if (this._configCache === null || Date.now() - this._configCacheLoadedAt >= ttl) {
// Single-flight: concurrent cold reads share one batch load.
this._configCacheLoad ??= this.connRetry(async () => {
const rows = await this.sql`SELECT key, value FROM config` as unknown as
Array<{ key: string; value: string | null }>;
const map = new Map<string, string>();
for (const r of rows) if (r.value != null) map.set(r.key, r.value);
this._configCache = map;
this._configCacheLoadedAt = Date.now();
}).finally(() => {
this._configCacheLoad = null;
});
await this._configCacheLoad;
}
return this._configCache!.has(key) ? this._configCache!.get(key)! : null;
// search mode/knobs and empty-stdout queries.
return this.connRetry(async () => {
const rows = await this.sql`SELECT value FROM config WHERE key = ${key}`;
return rows.length > 0 ? (rows[0].value as string) : null;
});
}
async setConfig(key: string, value: string): Promise<void> {
await this.connRetry(async () => {
return this.connRetry(async () => {
await this.sql`
INSERT INTO config (key, value) VALUES (${key}, ${value})
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value
`;
});
// Write-through so a long-lived process never serves stale config.
this._configCache?.set(key, value);
}
async unsetConfig(key: string): Promise<number> {
const count = await this.connRetry(async () => {
return this.connRetry(async () => {
const result = await this.sql`DELETE FROM config WHERE key = ${key}` as unknown as { count: number };
return result.count ?? 0;
});
// Write-through: known-absent, so the cache doesn't serve a stale value.
this._configCache?.delete(key);
return count;
}
async listConfigKeys(prefix: string): Promise<string[]> {
+88
View File
@@ -0,0 +1,88 @@
/**
* litellm-proxy reranker touchpoint smoke.
*
* Sibling of recipe-llama-server-reranker.test.ts. Pins the reranker
* touchpoint on the LiteLLM proxy recipe so:
* - the touchpoint exists with the LEAF '/rerank' path (LiteLLM serves both
* /rerank and /v1/rerank, so the leaf form is valid whether or not the
* user's LITELLM_BASE_URL carries the /v1 suffix the setup_hint allows)
* - a /v1-suffixed base URL does NOT produce /v1/v1/rerank (the original
* community PR pinned '/v1/rerank' which 404s on /v1-suffixed bases)
* - models: [] (user-provided; proxy defines the model ids)
* - pricing stays undefined (proxy can front a paid provider — same honest
* pricing-unknown stance as the embedding/chat touchpoints)
*
* The gateway.rerank() URL tests drive the real URL builder via the stubbed
* transport (same seam as test/ai/rerank.test.ts).
*/
import { describe, expect, test, afterEach } from 'bun:test';
import { getRecipe } from '../../src/core/ai/recipes/index.ts';
import {
configureGateway,
resetGateway,
rerank,
__setRerankTransportForTests,
} from '../../src/core/ai/gateway.ts';
afterEach(() => {
__setRerankTransportForTests(null);
resetGateway();
});
describe('recipe: litellm reranker touchpoint', () => {
test('declares reranker touchpoint with leaf /rerank path', () => {
const r = getRecipe('litellm')!;
const tp = r.touchpoints.reranker;
expect(tp).toBeDefined();
expect(tp!.path).toBe('/rerank');
expect(tp!.max_payload_bytes).toBe(5_000_000);
});
test('reranker touchpoint uses empty models[] for user-provided model ids', () => {
const r = getRecipe('litellm')!;
expect(r.touchpoints.reranker!.models).toEqual([]);
});
test('pricing stays undefined — proxy can front a paid provider', () => {
const r = getRecipe('litellm')!;
expect(r.touchpoints.reranker!.cost_per_1m_tokens_usd).toBeUndefined();
});
test('setup_hint keeps the /v1-suffix guidance AND mentions rerank', () => {
const r = getRecipe('litellm')!;
expect(r.setup_hint).toMatch(/\/v1 suffix/);
expect(r.setup_hint).toMatch(/search\.reranker\.model litellm:/);
});
});
describe('gateway.rerank() URL via litellm recipe', () => {
async function capturedRerankUrl(baseUrl?: string): Promise<string> {
configureGateway({
reranker_model: 'litellm:my-reranker',
env: {},
...(baseUrl ? { base_urls: { litellm: baseUrl } } : {}),
});
let capturedUrl = '';
__setRerankTransportForTests(async (url) => {
capturedUrl = url;
return new Response(
JSON.stringify({ results: [{ index: 0, relevance_score: 0.9 }] }),
{ status: 200, headers: { 'content-type': 'application/json' } },
);
});
await rerank({ query: 'q', documents: ['d'] });
return capturedUrl;
}
test('default base (no /v1 suffix) → /rerank', async () => {
const url = await capturedRerankUrl();
expect(url).toBe('http://localhost:4000/rerank');
});
test('/v1-suffixed base → /v1/rerank, NOT /v1/v1/rerank', async () => {
const url = await capturedRerankUrl('http://localhost:4000/v1');
expect(url).toBe('http://localhost:4000/v1/rerank');
expect(url).not.toContain('/v1/v1/');
});
});
-7
View File
@@ -29,13 +29,6 @@ if (existsSync(envPath)) {
}
}
// E2E suites seed/rewrite the config table via raw SQL and expect engine
// reads to see it immediately; disable the process-lifetime config cache
// (#1694) so read semantics match pre-cache behavior. Spawned CLI
// subprocesses inherit this. Cache semantics are pinned by
// test/postgres-engine-config-cache.test.ts.
process.env.GBRAIN_CONFIG_CACHE_TTL_MS ??= '0';
const DATABASE_URL = process.env.DATABASE_URL;
const FIXTURES_DIR = resolve(import.meta.dir, 'fixtures');
-112
View File
@@ -1,112 +0,0 @@
/**
* Process-lifetime config cache (#1694 takeover, by @Omerbahari).
*
* A single search fires ~85 getConfig() reads; on a remote pooler each is a
* round-trip. The first read now batch-loads the whole `config` table into a
* Map; setConfig/unsetConfig write through; TTL bounds multi-writer
* staleness; GBRAIN_CONFIG_CACHE_TTL_MS=0 restores per-key reads.
*
* Pure: stubs `_sql` with a call-counting fake; no real DB.
*/
import { describe, it, expect } from 'bun:test';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
import { withEnv } from './helpers/with-env.ts';
const FAST_RETRY = { maxRetries: 3, delayMs: 1, delayMaxMs: 1, jitter: 'none' as const };
/** Engine whose `sql` records every query's template strings and returns `rows`. */
function makeEngine(rows: unknown[]) {
const e = new PostgresEngine();
const calls: string[] = [];
(e as unknown as { _connectionStyle: string })._connectionStyle = 'instance';
(e as unknown as { _bulkRetryOptsCache: unknown })._bulkRetryOptsCache = FAST_RETRY;
(e as unknown as { _sql: unknown })._sql = (strings: TemplateStringsArray) => {
calls.push(strings.join('?'));
return Promise.resolve(rows);
};
return { engine: e, calls };
}
/** Run `fn` with GBRAIN_CONFIG_CACHE_TTL_MS set (or cleared when undefined). */
const withTtl = (ttl: string | undefined, fn: () => Promise<void>) =>
withEnv({ GBRAIN_CONFIG_CACHE_TTL_MS: ttl }, fn);
describe('PostgresEngine config cache (#1694)', () => {
it('batch-loads once and serves repeat reads from the cache', () => withTtl(undefined, async () => {
const { engine, calls } = makeEngine([
{ key: 'search.mode', value: 'balanced' },
{ key: 'embedding_multimodal', value: 'true' },
]);
expect(await engine.getConfig('search.mode')).toBe('balanced');
expect(await engine.getConfig('embedding_multimodal')).toBe('true');
expect(await engine.getConfig('search.mode')).toBe('balanced');
// One SELECT total — this is the whole point of the fix.
expect(calls.length).toBe(1);
expect(calls[0]).toContain('SELECT key, value FROM config');
}));
it('returns null for a known-absent key without an extra round-trip', () => withTtl(undefined, async () => {
const { engine, calls } = makeEngine([{ key: 'a', value: '1' }]);
expect(await engine.getConfig('missing.key')).toBeNull();
expect(await engine.getConfig('missing.key')).toBeNull();
expect(calls.length).toBe(1);
}));
it('setConfig writes through so subsequent reads see the new value', () => withTtl(undefined, async () => {
const { engine, calls } = makeEngine([{ key: 'k', value: 'old' }]);
expect(await engine.getConfig('k')).toBe('old');
await engine.setConfig('k', 'new');
expect(await engine.getConfig('k')).toBe('new');
expect(calls.length).toBe(2); // batch load + upsert; no re-read
}));
it('unsetConfig writes through so subsequent reads see absence', () => withTtl(undefined, async () => {
const { engine } = makeEngine([{ key: 'k', value: 'v' }]);
expect(await engine.getConfig('k')).toBe('v');
await engine.unsetConfig('k');
expect(await engine.getConfig('k')).toBeNull();
}));
it('concurrent cold reads share a single batch load (single-flight)', () => withTtl(undefined, async () => {
const { engine, calls } = makeEngine([{ key: 'k', value: 'v' }]);
const [a, b, c] = await Promise.all([
engine.getConfig('k'),
engine.getConfig('k'),
engine.getConfig('other'),
]);
expect([a, b, c]).toEqual(['v', 'v', null]);
expect(calls.length).toBe(1);
}));
it('GBRAIN_CONFIG_CACHE_TTL_MS=0 disables the cache (per-key reads)', () => withTtl('0', async () => {
const { engine, calls } = makeEngine([{ value: 'v' }]);
expect(await engine.getConfig('k')).toBe('v');
expect(await engine.getConfig('k')).toBe('v');
expect(calls.length).toBe(2);
expect(calls[0]).toContain('SELECT value FROM config WHERE key =');
}));
it('an expired TTL reloads from the database', () => withTtl('1', async () => {
const { engine, calls } = makeEngine([{ key: 'k', value: 'v' }]);
expect(await engine.getConfig('k')).toBe('v');
await new Promise((r) => setTimeout(r, 5));
expect(await engine.getConfig('k')).toBe('v');
expect(calls.length).toBe(2); // two batch loads
}));
it('the batch load keeps the connRetry reconnect posture (#1603/#1891)', () => withTtl(undefined, async () => {
const e = new PostgresEngine();
(e as unknown as { _connectionStyle: string })._connectionStyle = 'instance';
(e as unknown as { _sql: unknown })._sql = null; // torn-down pool → retryable
(e as unknown as { _bulkRetryOptsCache: unknown })._bulkRetryOptsCache = FAST_RETRY;
let reconnects = 0;
(e as unknown as { reconnect: () => Promise<void> }).reconnect = async () => {
reconnects++;
(e as unknown as { _sql: unknown })._sql = () =>
Promise.resolve([{ key: 'k', value: 'v' }]);
};
expect(await e.getConfig('k')).toBe('v');
expect(reconnects).toBe(1);
}));
});
@@ -43,9 +43,7 @@ function makeTornDownEngine(poolResult: unknown): { engine: PostgresEngine; reco
describe('PostgresEngine non-batch config accessors self-heal (PR #1891 takeover)', () => {
it('getConfig reconnects + retries a null instance pool, then returns the value', async () => {
// Rows carry `key` too: getConfig's default cached path batch-loads
// `SELECT key, value FROM config` (#1694) through the same connRetry.
const { engine, reconnects } = makeTornDownEngine([{ key: 'some.key', value: 'live-value' }]);
const { engine, reconnects } = makeTornDownEngine([{ value: 'live-value' }]);
expect(await engine.getConfig('some.key')).toBe('live-value');
expect(reconnects()).toBe(1); // exactly one reconnect closed the gap
});