mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-31 04:07:52 +00:00
* feat(dims): OpenAI text-embedding-3 Matryoshka range validation (D13) dimsProviderOptions now fail-loud at the embed boundary when the configured embedding_dimensions is outside the model's native range (1..1536 for -small, 1..3072 for -large). Paste-ready fix hint in the AIConfigError.fix field. Closes the silent-HTTP-400 path that would have bit OpenAI-fallback users on v0.36.0.0 ZE-default installs. 16 new test cases in test/ai/dims-openai.test.ts pinning the contract across native-openai and openai-compatible adapter paths. * feat(ai): flip defaults to ZeroEntropy zembed-1 1280d + zerank-2 reranker Default embedding model is now zeroentropyai:zembed-1 at 1280d via Matryoshka. Real-corpus benchmark: 2.2x faster than OpenAI, 2.6x cheaper at regular pricing, wins 11/20 head-to-head queries. 1280 is the closest valid ZE Matryoshka step to the prior OpenAI 1536d default (valid set: 2560/1280/640/320/160/80/40). 1024 (Voyage's step) is NOT on ZE's list — pinned by AIConfigError fail-loud in dims.ts. balanced mode bundle now defaults reranker_enabled=true. zerank-2 reshuffles 60% of top-1 results in benchmarks. Missing-key fail-open contract in src/core/search/rerank.ts handles unauthenticated cases. Opt out with: gbrain config set search.reranker.enabled false Existing tests updated (gateway.test.ts, search-mode.test.ts) and a new test/balanced-reranker-default.test.ts (10 cases) pins the fail- open invariants. * feat(retrieval-upgrade): RetrievalUpgradePlanner + interactive prompt UX New src/core/retrieval-upgrade-planner.ts is the consolidated planner that computes the brain's pending retrieval-upgrade work (chunker bumps + ZE switch) in one pass and applies the schema transition + config updates atomically. Tagged-union ApplyResult enum (D15): 'applied' | 'skipped_already_ applied' | 'skipped_no_work' | 'declined' | 'planned' | 'failed'. No string-parsing reasons. Three config keys (D12): ze_switch_prompt_shown (UI state), ze_switch_requested (user intent), ze_switch_applied (work done). Plus ze_switch_previous_snapshot (JSON, full prior config for --undo per D16) and ze_switch_declined_at (90-day re-ask window). Schema transition (D18) is atomic: DROP indexes + ALTER COLUMN + CREATE INDEX inside a single engine.transaction(). HNSW recreation is part of the same transaction — no silent slow-search window. C3 eligibility logic: ze_switch_offered iff NOT on ZE + NOT declined recently + NOT applied + (legacy default OR >100 pages). C4 cost math: MAX(chunker_pending, dim_pending) not SUM — one re-embed pass invalidates both surfaces simultaneously. New src/core/retrieval-upgrade-prompt.ts wires the planner to a TTY-only interactive prompt with two-line cost split (D10) and privacy callout for the reranker flip. Tests: test/retrieval-upgrade-planner.test.ts (24 cases) pins the state machine. test/asymmetric-encoding-contract.test.ts (6 cases) pins D17: search read path uses gateway.embedQuery() not embed(), asserted via __setEmbedTransportForTests mock. * feat(cli): gbrain ze-switch — manual lever for the ZE switch New gbrain ze-switch CLI with --dry-run, --json, --resume, --force, --undo, --non-interactive, --confirm-reembed, --ignore-missing-key flags. Mirrors the upgrade prompt's UX symmetry: --undo presents a cost-warning before re-embedding back to the prior width. src/cli.ts: dispatch case + CLI_ONLY entry. ze-switch owns its own engine lifecycle (mirrors the doctor pattern). test/ze-switch-cli.test.ts (11 cases): --help, --dry-run, --json, --non-interactive, --ignore-missing-key, --resume, --undo, --confirm-reembed. Uses captureExit harness to test process.exit() paths without breaking the test process. * feat(doctor): ze_embedding_health + embedding_width_consistency checks Two new doctor checks (D-A5): ze_embedding_health: when embedding_model starts with zeroentropyai:, verify ZEROENTROPY_API_KEY is set (env or config). Paste-ready setup hint with the signup URL on failure. embedding_width_consistency: cross-check that the configured embedding_dimensions matches the actual vector(N) column width on content_chunks.embedding. Catches the half-applied switch state (schema migrated but config write crashed) with a paste-ready gbrain ze-switch --resume hint. Wired into runDoctor between reranker_health and the existing sync_freshness checks. Both checks gracefully no-op on non-ZE embedding configs. test/doctor-ze-checks.test.ts (8 cases) pins both checks across happy + missing-key + missing-config + drift paths. Uses withEnv() helper to clear ZEROENTROPY_API_KEY for the no-key path so tests are hermetic against contributor env state. test/e2e/v0_28_5-fix-wave.test.ts + test/openai-compat-multimodal.test.ts: updated to explicit-configure the gateway when the test depends on specific dims that diverge from the v0.36.0.0 default (1280d). * docs: README zero-based rewrite (884 -> 139 lines) + new docs files Strip 4 months of accreted "New in v0.X.Y" hero blocks and reorganize around what gbrain does today. 33 H2s -> 8. The Commands section (136 lines duplicating gbrain --help) moved out; the 6-table skills enumeration collapsed to a one-paragraph capability description with a link to skills/RESOLVER.md. Hero retains load-bearing facts: OpenClaw + Hermes credit, production numbers (17,888 pages / 4,383 people / 723 companies), BrainBench numbers (P@5 49.1% / R@5 97.9% / +31.4 lift), ZE comparison numbers, 30-min install claim. Adds one paragraph announcing the v0.36.0.0 ZE default with the explicit gbrain config set escape for OpenAI/Voyage users. New files: - docs/INSTALL.md: every install path consolidated (agent platform, CLI standalone, MCP server). Thin-client mode covered. - docs/architecture/RETRIEVAL.md: why the hybrid + graph stack works. BrainBench numbers, why each strategy alone fails, the source-aware ranking + intent classification + multi-query expansion story. - docs/ethos/ORIGIN.md: origin story lifted from the old README so the front door stays factual + concrete. test/readme-hero-anchors.test.ts (5 cases) is the D9 regression guard. Five load-bearing strings: OpenClaw, Hermes, ZE, production-numbers regex, P@5/R@5. Light anchors that let voice/ structure evolve but block accidental loss of headline facts. scripts/check-test-real-names.sh: allowlist entries for OpenClaw + Hermes literals in the anchor test (it explicitly asserts those strings appear in README). * chore: bump version and changelog (v0.36.0.0) ZeroEntropy as the new default for embedding (zembed-1 at 1280d via Matryoshka) and reranker (zerank-2 cross-encoder, on by default in balanced mode bundle). README zero-based rewrite (884 -> 139 lines). 3 new docs files. Two new doctor checks. New gbrain ze-switch CLI with --undo for symmetric reversibility. skills/migrations/v0.36.0.0.md tells the agent how to surface the retrieval-upgrade prompt post-upgrade. llms-full.txt regenerated via bun run build:llms. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(docs): scrub Wintermute from RETRIEVAL.md per privacy rule * chore: rebump version 0.36.0.0 → 0.36.2.0 (queue collision) Three open PRs were claiming v0.36.0.0 (#1130 skillpack, #1139 hindsight, #1136 this PR). Ship-aware queue allocator says this branch lands at v0.36.2.0. Trio audit: VERSION 0.36.2.0 package.json 0.36.2.0 CHANGELOG ## [0.36.2.0] - 2026-05-17 Updates: VERSION, package.json, CHANGELOG header + body refs, README "New default in v0.36.2.0" announcement + credit line, skills/migrations/v0.36.0.0.md renamed to v0.36.2.0.md with frontmatter + body refs updated. llms-full.txt regenerated. * fix(test): pin gateway dim=1536 in cross-file-stateful PGLite tests CI shard 1 reported 10 failures across `query-cache.test.ts` (6) and `consolidate-valid-until.test.ts` (4). Both files hardcode 1536-dim vectors but rely on `PGLiteEngine.initSchema()` to size `vector(__EMBEDDING_DIMS__)` at the right width. Root cause: v0.36.2.0 flipped DEFAULT_EMBEDDING_DIMENSIONS from 1536 to 1280 (ZE Matryoshka step). The gateway module is process-singleton; when ANOTHER test file in the same shard's bun-test process configures the gateway before us, `pglite-engine.ts:216` reads `getEmbeddingDimensions() === 1280` and sizes the schema columns at vector(1280). The hardcoded 1536-dim INSERTs then fail with "expected 1280 dimensions, not 1536". Locally these tests pass in isolation because the gateway falls back through the try/catch at pglite-engine.ts:218 (1536 default). CI runs multiple test files in one process, so cross-file state poisons the schema width. Fix: explicit `resetGateway()` + `configureGateway({embedding_dimensions: 1536, ...})` at the top of `beforeAll`, plus `resetGateway()` in `afterAll`. Pins the schema width regardless of cross-file state. --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
455 lines
17 KiB
TypeScript
455 lines
17 KiB
TypeScript
import { describe, test, expect, beforeEach } from 'bun:test';
|
|
import {
|
|
configureGateway,
|
|
resetGateway,
|
|
isAvailable,
|
|
embed,
|
|
getEmbeddingModel,
|
|
getEmbeddingDimensions,
|
|
getExpansionModel,
|
|
VoyageResponseTooLargeError,
|
|
} from '../../src/core/ai/gateway.ts';
|
|
import { parseModelId, resolveRecipe } from '../../src/core/ai/model-resolver.ts';
|
|
import {
|
|
dimsProviderOptions,
|
|
VOYAGE_VALID_OUTPUT_DIMS,
|
|
isValidVoyageOutputDim,
|
|
} from '../../src/core/ai/dims.ts';
|
|
import { AIConfigError } from '../../src/core/ai/errors.ts';
|
|
|
|
describe('gateway configuration', () => {
|
|
beforeEach(() => resetGateway());
|
|
|
|
test('configureGateway sets current models and dims', () => {
|
|
configureGateway({
|
|
embedding_model: 'google:gemini-embedding-001',
|
|
embedding_dimensions: 768,
|
|
expansion_model: 'anthropic:claude-haiku-4-5-20251001',
|
|
env: { GOOGLE_GENERATIVE_AI_API_KEY: 'fake', ANTHROPIC_API_KEY: 'fake' },
|
|
});
|
|
expect(getEmbeddingModel()).toBe('google:gemini-embedding-001');
|
|
expect(getEmbeddingDimensions()).toBe(768);
|
|
expect(getExpansionModel()).toBe('anthropic:claude-haiku-4-5-20251001');
|
|
});
|
|
|
|
test('defaults are ZE 1280d as of v0.36.0.0 (D3)', () => {
|
|
// The default flipped from openai:text-embedding-3-large 1536d to
|
|
// zeroentropyai:zembed-1 1280d in v0.36.0.0. The cost story is in
|
|
// CHANGELOG.md; the rationale lives in src/core/ai/gateway.ts:45-54.
|
|
configureGateway({ env: {} });
|
|
expect(getEmbeddingModel()).toBe('zeroentropyai:zembed-1');
|
|
expect(getEmbeddingDimensions()).toBe(1280);
|
|
expect(getExpansionModel()).toBe('anthropic:claude-haiku-4-5-20251001');
|
|
});
|
|
});
|
|
|
|
describe('gateway.isAvailable (silent-drop regression surface)', () => {
|
|
beforeEach(() => resetGateway());
|
|
|
|
test('returns false when gateway not configured', () => {
|
|
expect(isAvailable('embedding')).toBe(false);
|
|
});
|
|
|
|
test('embedding available when OPENAI_API_KEY set and model is openai', () => {
|
|
configureGateway({
|
|
embedding_model: 'openai:text-embedding-3-large',
|
|
embedding_dimensions: 1536,
|
|
env: { OPENAI_API_KEY: 'sk-fake' },
|
|
});
|
|
expect(isAvailable('embedding')).toBe(true);
|
|
});
|
|
|
|
test('embedding UNAVAILABLE when OPENAI_API_KEY missing even if config names openai', () => {
|
|
configureGateway({
|
|
embedding_model: 'openai:text-embedding-3-large',
|
|
embedding_dimensions: 1536,
|
|
env: {},
|
|
});
|
|
expect(isAvailable('embedding')).toBe(false);
|
|
});
|
|
|
|
test('embedding AVAILABLE for google when GOOGLE_GENERATIVE_AI_API_KEY set even if OPENAI_API_KEY is NOT (Codex silent-drop regression)', () => {
|
|
configureGateway({
|
|
embedding_model: 'google:gemini-embedding-001',
|
|
embedding_dimensions: 768,
|
|
env: { GOOGLE_GENERATIVE_AI_API_KEY: 'fake-google' }, // NOTE: OPENAI_API_KEY deliberately absent
|
|
});
|
|
expect(isAvailable('embedding')).toBe(true);
|
|
});
|
|
|
|
test('embedding AVAILABLE for ollama with no API key (local)', () => {
|
|
configureGateway({
|
|
embedding_model: 'ollama:nomic-embed-text',
|
|
embedding_dimensions: 768,
|
|
env: {},
|
|
});
|
|
expect(isAvailable('embedding')).toBe(true);
|
|
});
|
|
|
|
test('anthropic rejects embedding touchpoint (has no embedding model)', () => {
|
|
configureGateway({
|
|
embedding_model: 'anthropic:claude-haiku-4-5-20251001',
|
|
embedding_dimensions: 1536,
|
|
env: { ANTHROPIC_API_KEY: 'fake' },
|
|
});
|
|
expect(isAvailable('embedding')).toBe(false);
|
|
});
|
|
|
|
test('expansion available when ANTHROPIC_API_KEY set', () => {
|
|
configureGateway({
|
|
expansion_model: 'anthropic:claude-haiku-4-5-20251001',
|
|
env: { ANTHROPIC_API_KEY: 'fake' },
|
|
});
|
|
expect(isAvailable('expansion')).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('model-resolver', () => {
|
|
test('parseModelId splits on first colon', () => {
|
|
expect(parseModelId('openai:text-embedding-3-large')).toEqual({
|
|
providerId: 'openai',
|
|
modelId: 'text-embedding-3-large',
|
|
});
|
|
});
|
|
|
|
test('parseModelId handles model ids with colons', () => {
|
|
expect(parseModelId('litellm:azure:gpt-4')).toEqual({
|
|
providerId: 'litellm',
|
|
modelId: 'azure:gpt-4',
|
|
});
|
|
});
|
|
|
|
test('parseModelId rejects missing colon', () => {
|
|
expect(() => parseModelId('openai-text-embedding-3-large')).toThrow(AIConfigError);
|
|
});
|
|
|
|
test('parseModelId rejects empty provider or model', () => {
|
|
expect(() => parseModelId(':model')).toThrow(AIConfigError);
|
|
expect(() => parseModelId('provider:')).toThrow(AIConfigError);
|
|
});
|
|
|
|
test('resolveRecipe finds known providers', () => {
|
|
const { recipe, parsed } = resolveRecipe('openai:text-embedding-3-large');
|
|
expect(recipe.id).toBe('openai');
|
|
expect(parsed.modelId).toBe('text-embedding-3-large');
|
|
});
|
|
|
|
test('resolveRecipe throws AIConfigError for unknown provider', () => {
|
|
expect(() => resolveRecipe('cohere:embed-v3')).toThrow(AIConfigError);
|
|
});
|
|
});
|
|
|
|
describe('dims.dimsProviderOptions', () => {
|
|
test('OpenAI text-embedding-3 returns dimensions param', () => {
|
|
const opts = dimsProviderOptions('native-openai', 'text-embedding-3-large', 1536);
|
|
expect(opts).toEqual({ openai: { dimensions: 1536 } });
|
|
});
|
|
|
|
test('OpenAI ada-002 returns undefined (no dim param)', () => {
|
|
const opts = dimsProviderOptions('native-openai', 'text-embedding-ada-002', 1536);
|
|
expect(opts).toBeUndefined();
|
|
});
|
|
|
|
test('Google gemini-embedding returns outputDimensionality', () => {
|
|
const opts = dimsProviderOptions('native-google', 'gemini-embedding-001', 768);
|
|
expect(opts).toEqual({ google: { outputDimensionality: 768 } });
|
|
});
|
|
|
|
test('Anthropic returns undefined (no embedding model)', () => {
|
|
const opts = dimsProviderOptions('native-anthropic', 'claude-haiku-4-5', 1536);
|
|
expect(opts).toBeUndefined();
|
|
});
|
|
|
|
test('openai-compatible returns undefined for providers without a dim param', () => {
|
|
const opts = dimsProviderOptions('openai-compatible', 'nomic-embed-text', 768);
|
|
expect(opts).toBeUndefined();
|
|
});
|
|
|
|
test('Voyage flexible-dim models return dimensions for the SDK shim', () => {
|
|
const opts = dimsProviderOptions('openai-compatible', 'voyage-3-large', 1024);
|
|
expect(opts).toEqual({ openaiCompatible: { dimensions: 1024 } });
|
|
const v4Opts = dimsProviderOptions('openai-compatible', 'voyage-4-large', 2048);
|
|
expect(v4Opts).toEqual({ openaiCompatible: { dimensions: 2048 } });
|
|
});
|
|
|
|
test('Voyage model without flexible dimensions returns undefined', () => {
|
|
const opts = dimsProviderOptions('openai-compatible', 'voyage-3-lite', 1024);
|
|
expect(opts).toBeUndefined();
|
|
});
|
|
|
|
// Negative regression pin: voyage-4-nano is an open-weight variant that
|
|
// Voyage's hosted API rejects `output_dimension` on (fixed 1024-dim).
|
|
// Don't re-add it to VOYAGE_OUTPUT_DIMENSION_MODELS without cross-checking
|
|
// Voyage's docs. See src/core/ai/dims.ts for the rationale.
|
|
test('voyage-4-nano returns undefined (open-weight, fixed-dim)', () => {
|
|
const opts = dimsProviderOptions('openai-compatible', 'voyage-4-nano', 512);
|
|
expect(opts).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('Voyage openai-compatible request shim', () => {
|
|
beforeEach(() => resetGateway());
|
|
|
|
test('sends output_dimension on the actual Voyage embedding request body', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
let requestBody: Record<string, unknown> | undefined;
|
|
globalThis.fetch = (async (_url: string | URL | Request, init?: RequestInit) => {
|
|
requestBody = JSON.parse(String(init?.body ?? '{}'));
|
|
return new Response(JSON.stringify({
|
|
object: 'list',
|
|
data: [
|
|
{
|
|
object: 'embedding',
|
|
index: 0,
|
|
embedding: new Array(2048).fill(0.01),
|
|
},
|
|
],
|
|
model: 'voyage-4-large',
|
|
usage: { total_tokens: 3 },
|
|
}), {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
}) as unknown as typeof fetch;
|
|
|
|
try {
|
|
configureGateway({
|
|
embedding_model: 'voyage:voyage-4-large',
|
|
embedding_dimensions: 2048,
|
|
env: { VOYAGE_API_KEY: 'voyage-fake' },
|
|
});
|
|
|
|
const vectors = await embed(['dimension probe']);
|
|
|
|
expect(vectors[0].length).toBe(2048);
|
|
expect(requestBody?.output_dimension).toBe(2048);
|
|
expect(requestBody?.encoding_format).toBe('base64');
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────
|
|
// Voyage OOM-cap rethrow regression (Codex P3 follow-up after PR #962).
|
|
// Pins the contract that VoyageResponseTooLargeError thrown from the
|
|
// inbound rewriter is NOT swallowed by the surrounding try/catch.
|
|
// ─────────────────────────────────────────────────────────────────────
|
|
describe('Voyage OOM-cap: too-large response throws (Codex P3 follow-up)', () => {
|
|
beforeEach(() => resetGateway());
|
|
|
|
test('Layer 1 — Content-Length above cap propagates as VoyageResponseTooLargeError', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
// 257 MB > 256 MB cap.
|
|
const oversized = String(257 * 1024 * 1024);
|
|
globalThis.fetch = (async () => {
|
|
return new Response('{"data": []}', {
|
|
status: 200,
|
|
headers: {
|
|
'content-type': 'application/json',
|
|
'content-length': oversized,
|
|
},
|
|
});
|
|
}) as unknown as typeof fetch;
|
|
try {
|
|
configureGateway({
|
|
embedding_model: 'voyage:voyage-4-large',
|
|
embedding_dimensions: 1024,
|
|
env: { VOYAGE_API_KEY: 'voyage-fake' },
|
|
});
|
|
let caught: unknown;
|
|
try {
|
|
await embed(['probe']);
|
|
} catch (e) {
|
|
caught = e;
|
|
}
|
|
// The OOM throw propagates. Provider plumbing may wrap it, but the
|
|
// VoyageResponseTooLargeError class name + characteristic message
|
|
// must survive.
|
|
const msg = caught instanceof Error ? caught.message : String(caught);
|
|
expect(msg).toContain('Content-Length=');
|
|
expect(msg).toContain('exceeds');
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test('Layer 2 — oversized base64 embedding string propagates (not swallowed)', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
// Build a JSON response with an `embedding` base64 string that decodes
|
|
// to > 256 MB. base64 ratio is ~0.75; 360 MB of base64 chars ≈ 270 MB
|
|
// decoded.
|
|
const oversizedBase64 = 'A'.repeat(360 * 1024 * 1024);
|
|
const respBody = `{"object":"list","data":[{"object":"embedding","index":0,"embedding":"${oversizedBase64}"}],"model":"voyage-4-large","usage":{"total_tokens":1}}`;
|
|
globalThis.fetch = (async () => {
|
|
// No Content-Length header → Layer 1 skipped, Layer 2 must fire.
|
|
return new Response(respBody, {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
}) as unknown as typeof fetch;
|
|
try {
|
|
configureGateway({
|
|
embedding_model: 'voyage:voyage-4-large',
|
|
embedding_dimensions: 1024,
|
|
env: { VOYAGE_API_KEY: 'voyage-fake' },
|
|
});
|
|
let caught: unknown;
|
|
try {
|
|
await embed(['probe']);
|
|
} catch (e) {
|
|
caught = e;
|
|
}
|
|
const msg = caught instanceof Error ? caught.message : String(caught);
|
|
// The Layer 2 throw fired and was not swallowed by the inbound
|
|
// try/catch (pre-fix bug: bare `catch {}` returned the original
|
|
// response and let the AI SDK OOM trying to parse it).
|
|
expect(msg).toContain('Voyage embedding base64 exceeds');
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
}, 15000);
|
|
|
|
test('VoyageResponseTooLargeError is exported as a tagged class', () => {
|
|
expect(VoyageResponseTooLargeError).toBeDefined();
|
|
const err = new VoyageResponseTooLargeError('test');
|
|
expect(err).toBeInstanceOf(Error);
|
|
expect(err).toBeInstanceOf(VoyageResponseTooLargeError);
|
|
expect(err.name).toBe('VoyageResponseTooLargeError');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────
|
|
// Voyage flexible-dim runtime validation (Codex P3 follow-up after PR #962).
|
|
// The bug class: brain configured for Voyage flexible-dim model without
|
|
// `embedding_dimensions` → gateway falls back to DEFAULT 1536 → Voyage
|
|
// HTTP 400. Catch it at the embed-call boundary with a clear AIConfigError.
|
|
// ─────────────────────────────────────────────────────────────────────
|
|
describe('Voyage flexible-dim runtime validation', () => {
|
|
test('rejects 1536 (the default that bites Voyage-first users) with AIConfigError', () => {
|
|
expect(() => dimsProviderOptions('openai-compatible', 'voyage-4-large', 1536))
|
|
.toThrow(AIConfigError);
|
|
expect(() => dimsProviderOptions('openai-compatible', 'voyage-4-large', 1536))
|
|
.toThrow(/embedding_dimensions|256.*512.*1024.*2048/);
|
|
});
|
|
|
|
test('rejects 3072 with AIConfigError', () => {
|
|
expect(() => dimsProviderOptions('openai-compatible', 'voyage-3-large', 3072))
|
|
.toThrow(AIConfigError);
|
|
});
|
|
|
|
test('accepts every Voyage-allowed flexible dim', () => {
|
|
for (const dim of VOYAGE_VALID_OUTPUT_DIMS) {
|
|
const opts = dimsProviderOptions('openai-compatible', 'voyage-4-large', dim);
|
|
expect(opts).toEqual({ openaiCompatible: { dimensions: dim } });
|
|
}
|
|
});
|
|
|
|
test('VOYAGE_VALID_OUTPUT_DIMS pins exactly the four Voyage values', () => {
|
|
expect([...VOYAGE_VALID_OUTPUT_DIMS]).toEqual([256, 512, 1024, 2048]);
|
|
});
|
|
|
|
test('isValidVoyageOutputDim returns true only for the four valid sizes', () => {
|
|
expect(isValidVoyageOutputDim(256)).toBe(true);
|
|
expect(isValidVoyageOutputDim(512)).toBe(true);
|
|
expect(isValidVoyageOutputDim(1024)).toBe(true);
|
|
expect(isValidVoyageOutputDim(2048)).toBe(true);
|
|
expect(isValidVoyageOutputDim(1536)).toBe(false);
|
|
expect(isValidVoyageOutputDim(3072)).toBe(false);
|
|
expect(isValidVoyageOutputDim(0)).toBe(false);
|
|
expect(isValidVoyageOutputDim(-1)).toBe(false);
|
|
});
|
|
|
|
test('voyage-3-lite (non-flexible-dim) bypasses the validator — still returns undefined', () => {
|
|
// Sanity: the validator only fires inside the flexible-dim branch, so
|
|
// a fixed-dim Voyage model with any dim value goes straight through to
|
|
// the `undefined` return path (no error, no providerOptions).
|
|
expect(dimsProviderOptions('openai-compatible', 'voyage-3-lite', 1536)).toBeUndefined();
|
|
expect(dimsProviderOptions('openai-compatible', 'voyage-4-nano', 1536)).toBeUndefined();
|
|
});
|
|
|
|
test('AIConfigError fix hint names the canonical recovery commands', () => {
|
|
let caught: AIConfigError | undefined;
|
|
try {
|
|
dimsProviderOptions('openai-compatible', 'voyage-4-large', 1536);
|
|
} catch (e) {
|
|
caught = e as AIConfigError;
|
|
}
|
|
expect(caught).toBeInstanceOf(AIConfigError);
|
|
expect(caught?.fix).toContain('embedding_dimensions');
|
|
expect(caught?.fix).toContain('256');
|
|
expect(caught?.fix).toContain('2048');
|
|
});
|
|
});
|
|
|
|
describe('embedding response integrity', () => {
|
|
beforeEach(() => resetGateway());
|
|
|
|
test('rejects partial embedding responses instead of silently dropping rows', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = (async () => new Response(JSON.stringify({
|
|
object: 'list',
|
|
data: [
|
|
{
|
|
object: 'embedding',
|
|
index: 0,
|
|
embedding: new Array(1536).fill(0.01),
|
|
},
|
|
],
|
|
model: 'text-embedding-3-large',
|
|
usage: { prompt_tokens: 3, total_tokens: 3 },
|
|
}), {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
})) as unknown as typeof fetch;
|
|
|
|
try {
|
|
configureGateway({
|
|
embedding_model: 'openai:text-embedding-3-large',
|
|
embedding_dimensions: 1536,
|
|
env: { OPENAI_API_KEY: 'openai-fake' },
|
|
});
|
|
|
|
await expect(embed(['first', 'second'])).rejects.toThrow('1 embedding(s) for 2 input(s)');
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test('checks every returned vector dimension, not just the first one', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = (async () => new Response(JSON.stringify({
|
|
object: 'list',
|
|
data: [
|
|
{
|
|
object: 'embedding',
|
|
index: 0,
|
|
embedding: new Array(1536).fill(0.01),
|
|
},
|
|
{
|
|
object: 'embedding',
|
|
index: 1,
|
|
embedding: new Array(768).fill(0.01),
|
|
},
|
|
],
|
|
model: 'text-embedding-3-large',
|
|
usage: { prompt_tokens: 3, total_tokens: 3 },
|
|
}), {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
})) as unknown as typeof fetch;
|
|
|
|
try {
|
|
configureGateway({
|
|
embedding_model: 'openai:text-embedding-3-large',
|
|
embedding_dimensions: 1536,
|
|
env: { OPENAI_API_KEY: 'openai-fake' },
|
|
});
|
|
|
|
await expect(embed(['first', 'second'])).rejects.toThrow('returned 768 but schema expects 1536');
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
});
|