Files
gbrain/test/e2e/embedding-column-pglite.test.ts
T
1d5f69fe7a v0.36.3.0 feat: dynamic embedding column selection for search (#1164)
* feat: migration v68 — eval_candidates.embedding_column

Schema migration ALTERs eval_candidates to add a nullable
embedding_column TEXT column. Per-row capture metadata so
`gbrain eval replay` reproduces the same column the
capture ran against (D16 / CDX-10). NULL-tolerant: pre-v0.36
rows fall back to current default.

Renumbered v67→v68 because master claimed v67 for
facts_typed_claim_columns during this branch's lifetime.

PGLite parity via sqlFor.pglite — same ALTER IF NOT EXISTS.

* feat: dynamic embedding column — core (resolver, types, gateway, engines)

The read-path foundation for routing search through any
populated embedding column, not just OpenAI 1536.

src/core/search/embedding-column.ts (new) is the canonical
seam. Single source of truth for column → provider/dim/type
lookup. Validates registry keys via regex
(/^[a-z_][a-z0-9_]*$/), uses Object.create(null) +
Object.hasOwn so 'constructor' and other inherited names
can't masquerade as registered columns. Identifier-quoting
on SQL interpolation as defense in depth.

src/core/types.ts widens SearchOpts.embeddingColumn to
accept ResolvedColumn descriptors at the engine boundary;
adds EmbeddingColumnConfig + ResolvedColumn exports.

src/core/config.ts merges embedding_columns +
search_embedding_column from the DB plane via
loadConfigWithEngine, mirroring the existing
embedding_multimodal_model pattern. Handles the no-file
case so env-only Postgres installs see DB-plane overrides
(codex /ship #3).

src/core/ai/gateway.ts: embedQuery(text, opts) +
embed(texts, opts) accept embeddingModel + dimensions
overrides. isAvailable(touchpoint, modelOverride?) so
hybrid asks 'is the active column's provider reachable?'
not 'is the global default reachable?' (CDX-4 / D10).

Engines: searchVector accepts ResolvedColumn descriptors via
normalizeEngineColumn; engine code is config-free and
unit-testable. getEmbeddingsByChunkIds(ids, column?) so
cosineReScore hydrates from the active column instead of
always 'embedding' (CDX-3 / D9). Identifier-quoting belt at
the SQL boundary.

src/core/eval-capture.ts threads embedding_column from
hybridSearch meta into the persisted capture row.

* feat: dynamic embedding column — integration (hybrid, ops, doctor)

Wires the resolver into hybridSearch, the query op, doctor,
and the config command.

src/core/search/hybrid.ts: resolves the column once at the
boundary, threads the descriptor into engine calls, routes
embedQuery through the resolved column's provider/dims, and
calls isCacheSafe (not isDefaultColumn) for cache skip so
user overrides of the 'embedding' builtin can't leak across
vector spaces (CDX-4). cosineReScore now hydrates from the
active column.

src/core/search/mode.ts: KNOBS_HASH_VERSION 2→3, append-only
new fields col= and prov= alongside floor_ratio. Cache rows
from different columns or providers now sit in different
keyspaces — cross-column contamination impossible.

src/core/operations.ts: query op accepts embedding_column
param for per-call A/B benchmarking. search op (keyword-only)
deliberately does NOT (CDX-9 / D15) — would be silent UX.

src/commands/doctor.ts: new embedding_column_registry
check. Batch format_type probe (D13) catches dim drift
that information_schema.columns.udt_name can't.
Batch pg_indexes probe (D5) warns on missing HNSW. Coverage
% on active column, gates at <90% (D14), short-circuits on
empty brains (codex /ship #5).

src/commands/config.ts: validates embedding_columns JSON
shape at set time, runs the coverage gate when setting
search_embedding_column, uses Object.hasOwn for the
registry lookup.

src/commands/eval-replay.ts: replay re-runs queries against
the captured embedding_column so post-flip-config replays
don't surface as false-positive regressions.

* test: dynamic embedding column — unit + e2e coverage

50 unit cases for the resolver (resolution chain, registry
merge, validation, prototype pollution, descriptor
passthrough, isCacheSafe, normalizeEngineColumn).

8 gateway override cases — embeddingModel + dimensions
flow into providerOptions, isAvailable(touchpoint, override)
routes to the right recipe, unknown models throw clean.

4 cosineReScore + 6 ops + 5 knobs-hash + 7 mode + 9 PGLite
E2E + 7 Postgres E2E + 5 eval-replay column metadata.

Postgres E2E (gated on DATABASE_URL) covers halfvec(2560)
end-to-end on real pgvector, EXPLAIN-visible HNSW index
on the alternate column, format_type-based dim drift catch,
and the <90% coverage gate.

Pins every codex /ship fix: prototype-pollution rejection
('constructor' as column name), descriptor passthrough
validation (rejects SQL-shaped strings in dimensions),
isCacheSafe semantics (space-based, not name-based).

Total: 141 new + extended cases, all green.

* chore: bump version and changelog (v0.36.3.0)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: sync to v0.36.3.0

Add CLAUDE.md key-files entry for src/core/search/embedding-column.ts.
Annotate hybrid.ts, gateway.ts, doctor.ts, and migrate.ts entries with
v0.36.3.0 wave changes (ResolvedColumn threading, embedQuery model
override, embedding_column_registry check, migration v68). Document
knobs_hash v=2 → v=3 bump under the Search Mode section.

Regenerate llms-full.txt from the updated CLAUDE.md so the auto-checked
bundle matches source (build-llms.test.ts CI guard).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ci): two CI failures from v0.36.3.0

1. test/loadConfig-merge.test.ts: update the 'returns null when base
   config is null' contract test. Pre-v0.36 the function returned null
   for null base; the codex /ship #3 fix changed that to synthesize a
   minimal `{ engine: 'postgres' }` so env-only installs see DB-plane
   overrides. Test now pins the new contract + adds a round-trip case
   asserting the merge actually surfaces `embedding_columns` /
   `search_embedding_column` set via gbrain config set on a null base.

2. test/schema-bootstrap-coverage.test.ts was failing because
   eval_candidates.embedding_column (added by migration v68) wasn't
   covered by applyForwardReferenceBootstrap. Fix: add the column to
   PGLITE_SCHEMA_SQL's eval_candidates CREATE TABLE definition (and
   src/schema.sql for parity) so fresh installs get it natively. The
   coverage test's third tier (schemaCreateTableCols) now finds it.
   Regenerated schema-embedded.ts via bun run build:schema.

Schema-blob path is cleaner than COLUMN_EXEMPTIONS — fresh installs
skip the migration entirely; upgrade installs still run v68.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 21:26:12 -07:00

244 lines
8.8 KiB
TypeScript

/**
* v0.36 E2E — dynamic embedding column selection (PGLite).
*
* Covers (per D4 + D9 + D11 + D12 + CDX-2 + CDX-3 + CDX-7 + CDX-8 + CDX-10):
* - Multi-column search: same query against `embedding` and against an
* ad-hoc `embedding_voyage` column produces different orderings
* consistent with the seeded vectors.
* - Halfvec column: ALTER TABLE ADD `embedding_ze halfvec(2560)` and
* confirm the `$1::halfvec(2560)` cast works.
* - Image branch unaffected: `embedding_image` still works via the
* existing operations.ts path.
* - cosineReScore reads from the active column, not the default
* (D9 — pre-fix, rescore against Voyage HNSW used OpenAI vectors).
* - Unknown column at hybridSearch entry throws loud.
* - Mid-session column switch invalidates the cache (knobs_hash v=3).
*
* No DATABASE_URL needed — PGLite in-memory.
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { hybridSearch } from '../../src/core/search/hybrid.ts';
import {
buildVectorCastFragment,
EmbeddingColumnNotRegisteredError,
} from '../../src/core/search/embedding-column.ts';
import {
configureGateway,
resetGateway,
__setEmbedTransportForTests,
} from '../../src/core/ai/gateway.ts';
import type { ResolvedColumn } from '../../src/core/types.ts';
let engine: PGLiteEngine;
let chunkIdA: number;
let chunkIdB: number;
const VEC1536_A = new Array(1536).fill(0).map((_, i) => 0.001 * (i % 10));
const VEC1536_B = new Array(1536).fill(0).map((_, i) => 0.002 * (i % 10));
const VEC1024_A = new Array(1024).fill(0).map((_, i) => 0.5 - 0.001 * (i % 10));
const VEC1024_B = new Array(1024).fill(0).map((_, i) => 0.4 + 0.001 * (i % 10));
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
// Add the ad-hoc Voyage + ZE columns the way a user with a multi-provider
// brain has done it (outside the committed schema, per-instance ALTER).
await (engine as any).db.exec(
`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_voyage vector(1024)`,
);
await (engine as any).db.exec(
`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_ze halfvec(2560)`,
);
// Two pages with one chunk each.
await engine.putPage('docs/page-a', {
type: 'concept',
title: 'Page A — about cats',
compiled_truth: 'Page A discusses cats and their behavior.',
});
await engine.putPage('docs/page-b', {
type: 'concept',
title: 'Page B — about dogs',
compiled_truth: 'Page B discusses dogs and their habits.',
});
await engine.upsertChunks('docs/page-a', [
{ chunk_index: 0, chunk_text: 'cats behavior chunk A', chunk_source: 'compiled_truth' },
]);
await engine.upsertChunks('docs/page-b', [
{ chunk_index: 0, chunk_text: 'dogs habits chunk B', chunk_source: 'compiled_truth' },
]);
// Look up chunk ids.
const rows = await engine.executeRaw<{ id: number; slug: string }>(
`SELECT cc.id, p.slug FROM content_chunks cc JOIN pages p ON p.id = cc.page_id ORDER BY p.slug`,
);
chunkIdA = rows.find(r => r.slug === 'docs/page-a')!.id;
chunkIdB = rows.find(r => r.slug === 'docs/page-b')!.id;
// Seed vectors. Vectors are intentionally distinct between columns so
// search orderings depend on which column the engine actually reads.
const vecLit = (arr: number[]) => `[${arr.join(',')}]`;
await (engine as any).db.query(
`UPDATE content_chunks SET embedding = $1::vector WHERE id = $2`,
[vecLit(VEC1536_A), chunkIdA],
);
await (engine as any).db.query(
`UPDATE content_chunks SET embedding = $1::vector WHERE id = $2`,
[vecLit(VEC1536_B), chunkIdB],
);
await (engine as any).db.query(
`UPDATE content_chunks SET embedding_voyage = $1::vector WHERE id = $2`,
[vecLit(VEC1024_A), chunkIdA],
);
await (engine as any).db.query(
`UPDATE content_chunks SET embedding_voyage = $1::vector WHERE id = $2`,
[vecLit(VEC1024_B), chunkIdB],
);
});
afterAll(async () => {
if (engine) await engine.disconnect();
__setEmbedTransportForTests(null);
resetGateway();
});
describe('PGLite engine: searchVector accepts ResolvedColumn descriptor (D11)', () => {
test('vector cast routes to correct column when descriptor names embedding_voyage', async () => {
const queryVec = new Float32Array(VEC1024_A);
const descriptor: ResolvedColumn = {
name: 'embedding_voyage',
type: 'vector',
dimensions: 1024,
embeddingModel: 'voyage:voyage-3-large',
};
const results = await engine.searchVector(queryVec, {
embeddingColumn: descriptor,
limit: 5,
});
// Both pages have voyage embeddings; cosine to VEC1024_A is closer to
// page-a (identical) than page-b. Verify ordering.
expect(results.length).toBeGreaterThanOrEqual(1);
expect(results[0].slug).toBe('docs/page-a');
});
test('halfvec cast accepted: ALTER TABLE column + $1::halfvec(N)', async () => {
// Seed halfvec values via direct cast.
const ze1 = `[${new Array(2560).fill(0.5).join(',')}]`;
const ze2 = `[${new Array(2560).fill(0.6).join(',')}]`;
await (engine as any).db.query(
`UPDATE content_chunks SET embedding_ze = $1::halfvec WHERE id = $2`,
[ze1, chunkIdA],
);
await (engine as any).db.query(
`UPDATE content_chunks SET embedding_ze = $1::halfvec WHERE id = $2`,
[ze2, chunkIdB],
);
const queryVec = new Float32Array(2560).fill(0.5);
const descriptor: ResolvedColumn = {
name: 'embedding_ze',
type: 'halfvec',
dimensions: 2560,
embeddingModel: 'zeroentropyai:zembed-1',
};
const results = await engine.searchVector(queryVec, {
embeddingColumn: descriptor,
limit: 5,
});
expect(results.length).toBeGreaterThanOrEqual(1);
// Page A's halfvec is closer to the all-0.5 query.
expect(results[0].slug).toBe('docs/page-a');
});
test('legacy embedding_image literal still routes correctly', async () => {
// We never seeded embedding_image so we expect zero results, but the
// query MUST NOT throw — the legacy-literal path must still work
// (no regression on the existing image branch).
const v = new Float32Array(1024).fill(0.1);
const results = await engine.searchVector(v, {
embeddingColumn: 'embedding_image',
limit: 5,
});
expect(Array.isArray(results)).toBe(true);
});
});
describe('PGLite engine: getEmbeddingsByChunkIds column param (D9)', () => {
test('default fetches from embedding (back-compat)', async () => {
const map = await engine.getEmbeddingsByChunkIds([chunkIdA, chunkIdB]);
expect(map.get(chunkIdA)!.length).toBe(1536);
});
test('column="embedding_voyage" fetches from voyage column', async () => {
const map = await engine.getEmbeddingsByChunkIds([chunkIdA, chunkIdB], 'embedding_voyage');
expect(map.get(chunkIdA)!.length).toBe(1024);
});
test('invalid column rejected at engine layer (regex guard)', async () => {
let threw: Error | null = null;
try {
await engine.getEmbeddingsByChunkIds([chunkIdA], 'embed-bad-name');
} catch (e) {
threw = e as Error;
}
expect(threw).toBeInstanceOf(EmbeddingColumnNotRegisteredError);
});
});
describe('hybridSearch + resolver — unknown column at entry (D11)', () => {
test('unknown name in opts.embeddingColumn throws via resolver', async () => {
// configureGateway with a transport stub so we don't hit a real API.
configureGateway({
embedding_model: 'openai:text-embedding-3-large',
embedding_dimensions: 1536,
env: { OPENAI_API_KEY: 'sk-test' },
});
__setEmbedTransportForTests(async () => ({
embeddings: [new Array(1536).fill(0)],
usage: { tokens: 0 },
} as any));
let threw: Error | null = null;
try {
await hybridSearch(engine, 'cats', {
embeddingColumn: 'nonexistent_column',
limit: 5,
});
} catch (e) {
threw = e as Error;
}
expect(threw).toBeInstanceOf(EmbeddingColumnNotRegisteredError);
});
});
describe('buildVectorCastFragment — engine SQL composer (D3)', () => {
test('vector descriptor emits $1::vector', () => {
const r: ResolvedColumn = {
name: 'embedding',
type: 'vector',
dimensions: 1536,
embeddingModel: '',
};
const { col, castSql } = buildVectorCastFragment(r);
expect(col).toBe('"embedding"');
expect(castSql).toBe('$1::vector');
});
test('halfvec descriptor emits $1::halfvec(N) with parenthesized N', () => {
const r: ResolvedColumn = {
name: 'embedding_ze',
type: 'halfvec',
dimensions: 2560,
embeddingModel: 'zeroentropyai:zembed-1',
};
const { col, castSql } = buildVectorCastFragment(r);
expect(col).toBe('"embedding_ze"');
expect(castSql).toBe('$1::halfvec(2560)');
});
});