Compare commits

..
Author SHA1 Message Date
aa45398d83 fix(schema): skip unsupported large-dim HNSW indexes (#1734)
Takeover of #2510: migrations v40 (facts) and v55 (query_cache)
unconditionally created HNSW indexes with the configured embedding
dimension, so `gbrain init` with embedding_dimensions above pgvector's
per-type HNSW caps (vector 2000 / halfvec 4000) failed with
"column cannot have more than 4000 dimensions for hnsw index".

- vector-index.ts: add PGVECTOR_HNSW_HALFVEC_MAX_DIMS + hnswMaxDimsForType
- migrate.ts v40/v55: emit the HNSW index only when dims fit the cap,
  otherwise a comment noting exact scans remain available
- embedding-dim-check.ts: buildFactsAlterRecipe skips the reindex step
  above the cap for the same reason
- tests: 4096d init round-trip on PGLite (columns exist, indexes
  skipped) + recipe-skip unit test

Drops the unrelated context-engine.ts interface change and the
tsconfig.json strictFunctionTypes=false hunk from #2510; typecheck is
clean without them.

Co-authored-by: javieraldape <javieraldape@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:20:06 -07:00
7 changed files with 109 additions and 105 deletions
+2 -50
View File
@@ -3,11 +3,7 @@
*
* Usage:
* gbrain migrate --to supabase [--url <connection_string>]
* (--url is persisted to config.json, mode 0600, so the migrated brain
* works without env — #1271)
* gbrain migrate --to pglite [--path <db_path>]
* (an explicit --path destination is bootstrapped with its own
* <path>/.gbrain/config.json so GBRAIN_HOME=<path> just works — #1271)
* gbrain migrate --to <engine> --force (overwrite non-empty target)
*/
@@ -15,9 +11,9 @@ import { createEngine } from '../core/engine-factory.ts';
import { loadConfig, saveConfig, toEngineConfig, gbrainPath, effectiveEnvDatabaseUrl, type GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
import type { EngineConfig } from '../core/types.ts';
import { writeFileSync, readFileSync, existsSync, unlinkSync, mkdirSync, chmodSync } from 'fs';
import { writeFileSync, readFileSync, existsSync, unlinkSync } from 'fs';
import { createHash } from 'crypto';
import { resolve, join } from 'path';
import { resolve } from 'path';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -63,31 +59,6 @@ export interface MigrateManifest {
started_at: string;
}
/**
* #1271 Finding 1: make an explicit `--to pglite --path P` destination usable
* as a standalone brain. Writes `P/.gbrain/config.json` (mode 0600, plus a
* `*` .gitignore) so `GBRAIN_HOME=P` resolves without a manual `gbrain init`.
* Never clobbers an existing config at the destination. Returns the written
* config path, or null when skipped.
*/
export function bootstrapDestinationConfig(dbPath: string): string | null {
const abs = resolve(dbPath);
const dir = join(abs, '.gbrain');
const file = join(dir, 'config.json');
if (existsSync(file)) return null;
mkdirSync(dir, { recursive: true });
const cfg: GBrainConfig = { engine: 'pglite', database_path: abs };
writeFileSync(file, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 });
try { chmodSync(file, 0o600); } catch { /* platform-specific */ }
// Same worktree-safety pattern as saveConfig()'s ensureGitignore, scoped
// to the destination home. Don't clobber a user-customized .gitignore.
const gitignore = join(dir, '.gitignore');
if (!existsSync(gitignore)) {
writeFileSync(gitignore, '*\n', { mode: 0o600 });
}
return file;
}
export function migrationTargetId(config: EngineConfig): string {
const locator = config.engine === 'postgres'
? config.database_url ?? ''
@@ -381,25 +352,6 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]
};
saveConfig(newConfig);
// #1271 Finding 2 (by design, but say it out loud): the connection string
// is persisted so the migrated brain works without env. Mode 0600.
if (opts.targetEngine === 'postgres' && opts.targetUrl) {
console.error('Note: the --url connection string (including credentials) is persisted to config.json (mode 0600).');
}
// #1271 Finding 1: an explicit --path destination doubles as a standalone
// GBRAIN_HOME. Best-effort — never fail a completed migration over it.
if (opts.targetEngine === 'pglite' && opts.targetPath) {
try {
const written = bootstrapDestinationConfig(opts.targetPath);
if (written) {
console.log(`Destination bootstrapped: ${written} (usable via GBRAIN_HOME=${resolve(opts.targetPath)})`);
}
} catch (e) {
console.warn(` WARN could not bootstrap destination config: ${e instanceof Error ? e.message : String(e)}`);
}
}
// Clean up
clearManifest();
+13 -4
View File
@@ -14,7 +14,7 @@
*/
import type { BrainEngine } from './engine.ts';
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS } from './vector-index.ts';
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS, hnswMaxDimsForType } from './vector-index.ts';
import { gbrainPath } from './config.ts';
import { resolveRecipe } from './ai/model-resolver.ts';
import type { Recipe } from './ai/types.ts';
@@ -609,6 +609,17 @@ export function buildFactsAlterRecipe(
const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
const targetType = columnType === 'halfvec' ? `halfvec(${configuredDims})` : `vector(${configuredDims})`;
const dimsChanged = columnDims !== configuredDims;
const hnswMaxDims = hnswMaxDimsForType(columnType);
const indexLines = configuredDims <= hnswMaxDims
? [
`CREATE INDEX idx_facts_embedding_hnsw`,
` ON facts USING hnsw (embedding ${opclass})`,
` WHERE embedding IS NOT NULL AND expired_at IS NULL;`,
]
: [
`-- Skip reindex. ${columnType}(${configuredDims}) exceeds pgvector's HNSW cap of ${hnswMaxDims};`,
`-- fact similarity falls back to exact scans.`,
];
return [
`-- ALTER ${columnType}(${columnDims}) → ${columnType}(${configuredDims}) on indexed column.`,
`-- HOLD a maintenance window: this rewrites every row's embedding.`,
@@ -629,9 +640,7 @@ export function buildFactsAlterRecipe(
: []),
`ALTER TABLE facts ALTER COLUMN embedding TYPE ${targetType}`,
` USING embedding::${targetType};`,
`CREATE INDEX idx_facts_embedding_hnsw`,
` ON facts USING hnsw (embedding ${opclass})`,
` WHERE embedding IS NOT NULL AND expired_at IS NULL;`,
...indexLines,
].join('\n');
}
+21 -8
View File
@@ -1,6 +1,7 @@
import type { BrainEngine } from './engine.ts';
import { slugifyPath } from './sync.ts';
import { getFtsLanguage } from './fts-language.ts';
import { hnswMaxDimsForType } from './vector-index.ts';
/**
* Schema migrations run automatically on initSchema().
@@ -2276,11 +2277,19 @@ export const MIGRATIONS: Migration[] = [
useHalfvec = true;
}
const vecType = useHalfvec ? 'HALFVEC' : 'VECTOR';
const columnType = useHalfvec ? 'halfvec' : 'vector';
const vecType = columnType.toUpperCase();
// HNSW operator class must match the column type:
// VECTOR(n) → vector_cosine_ops
// HALFVEC(n) → halfvec_cosine_ops
const opclass = useHalfvec ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
const hnswMaxDims = hnswMaxDimsForType(columnType);
const factsEmbeddingIndexSql = embeddingDim <= hnswMaxDims
? `CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw
ON facts USING hnsw (embedding ${opclass})
WHERE embedding IS NOT NULL AND expired_at IS NULL;`
: `-- idx_facts_embedding_hnsw skipped: pgvector HNSW ${columnType} indexes support
-- at most ${hnswMaxDims} dimensions; exact vector scans remain available.`;
// FK to sources is added in a separate ALTER TABLE rather than inline
// on the column. Inline `REFERENCES` worked on PGLite but silently
// got dropped by postgres.js's `unsafe()` multi-statement path on
@@ -2354,9 +2363,7 @@ export const MIGRATIONS: Migration[] = [
ON facts(source_id, entity_slug)
WHERE consolidated_at IS NULL AND expired_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw
ON facts USING hnsw (embedding ${opclass})
WHERE embedding IS NOT NULL AND expired_at IS NULL;
${factsEmbeddingIndexSql}
`;
await engine.runMigration(40, factsDDL);
@@ -2870,8 +2877,16 @@ export const MIGRATIONS: Migration[] = [
useHalfvec = true;
}
const vecType = useHalfvec ? 'HALFVEC' : 'VECTOR';
const columnType = useHalfvec ? 'halfvec' : 'vector';
const vecType = columnType.toUpperCase();
const opclass = useHalfvec ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
const hnswMaxDims = hnswMaxDimsForType(columnType);
const queryCacheEmbeddingIndexSql = embeddingDim <= hnswMaxDims
? `CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw
ON query_cache USING hnsw (embedding ${opclass})
WHERE embedding IS NOT NULL;`
: `-- idx_query_cache_embedding_hnsw skipped: pgvector HNSW ${columnType} indexes support
-- at most ${hnswMaxDims} dimensions; exact vector scans remain available.`;
const ddl = `
CREATE TABLE IF NOT EXISTS query_cache (
@@ -2890,9 +2905,7 @@ export const MIGRATIONS: Migration[] = [
CREATE INDEX IF NOT EXISTS idx_query_cache_source_created
ON query_cache(source_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw
ON query_cache USING hnsw (embedding ${opclass})
WHERE embedding IS NOT NULL;
${queryCacheEmbeddingIndexSql}
`;
await engine.runMigration(55, ddl);
+5
View File
@@ -17,6 +17,7 @@
import type { BrainEngine } from './engine.ts';
export const PGVECTOR_HNSW_VECTOR_MAX_DIMS = 2000;
export const PGVECTOR_HNSW_HALFVEC_MAX_DIMS = 4000;
const CHUNK_EMBEDDING_HNSW_INDEX =
'CREATE INDEX IF NOT EXISTS idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops);';
@@ -29,6 +30,10 @@ export function chunkEmbeddingIndexSql(dims: number): string {
].join('\n');
}
export function hnswMaxDimsForType(columnType: 'vector' | 'halfvec'): number {
return columnType === 'halfvec' ? PGVECTOR_HNSW_HALFVEC_MAX_DIMS : PGVECTOR_HNSW_VECTOR_MAX_DIMS;
}
export function applyChunkEmbeddingIndexPolicy(sql: string, dims: number): string {
return sql.replaceAll(CHUNK_EMBEDDING_HNSW_INDEX, chunkEmbeddingIndexSql(dims));
}
+11 -3
View File
@@ -122,9 +122,9 @@ describe('buildFactsAlterRecipe', () => {
});
test('vector recipe uses vector_cosine_ops + vector(N) USING cast', () => {
const recipe = buildFactsAlterRecipe(1024, 2048, 'vector');
expect(recipe).toContain('vector(2048)');
expect(recipe).toContain('USING embedding::vector(2048)');
const recipe = buildFactsAlterRecipe(1024, 1536, 'vector');
expect(recipe).toContain('vector(1536)');
expect(recipe).toContain('USING embedding::vector(1536)');
expect(recipe).toContain('vector_cosine_ops');
expect(recipe).not.toContain('halfvec_cosine_ops');
});
@@ -163,6 +163,14 @@ describe('buildFactsAlterRecipe', () => {
expect(recipe).not.toContain('UPDATE facts SET embedding = NULL');
expect(recipe).toContain('USING embedding::vector(1536)');
});
test('halfvec recipe skips HNSW rebuild above pgvector cap', () => {
const recipe = buildFactsAlterRecipe(1536, 4096, 'halfvec');
expect(recipe).toContain('halfvec(4096)');
expect(recipe).toContain('Skip reindex');
expect(recipe).toContain("exceeds pgvector's HNSW cap of 4000");
expect(recipe).not.toMatch(/CREATE INDEX idx_facts_embedding_hnsw[\s\S]*USING hnsw/);
});
});
describe('FactsEmbeddingDimMismatchError', () => {
+57
View File
@@ -11,6 +11,7 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
let engine: PGLiteEngine;
@@ -93,4 +94,60 @@ describe('migration v45 facts column shape', () => {
);
expect(after[0].udt_name).toBe(before[0].udt_name);
});
});
describe('migration v45/v55 large-dim HNSW policy', () => {
let largeDimEngine: PGLiteEngine;
beforeAll(async () => {
configureGateway({
embedding_model: 'litellm:custom-4096d',
embedding_dimensions: 4096,
env: { ...process.env },
});
largeDimEngine = new PGLiteEngine();
await largeDimEngine.connect({});
await largeDimEngine.initSchema();
});
afterAll(async () => {
await largeDimEngine.disconnect();
resetGateway();
});
test('4096d init skips unsupported HNSW indexes but keeps vector columns', async () => {
const formatRows = await largeDimEngine.executeRaw<{ format_type: string }>(
`SELECT format_type(atttypid, atttypmod) AS format_type
FROM pg_attribute
WHERE attrelid = 'facts'::regclass AND attname = 'embedding'`,
);
expect(formatRows[0]?.format_type).toMatch(/(halfvec|vector)\(4096\)/);
const indexRows = await largeDimEngine.executeRaw<{ exists: boolean }>(
`SELECT EXISTS (
SELECT 1 FROM pg_indexes
WHERE tablename = 'facts'
AND indexname = 'idx_facts_embedding_hnsw'
) AS exists`,
);
expect(indexRows[0]?.exists).toBe(false);
const queryCacheFormatRows = await largeDimEngine.executeRaw<{ format_type: string }>(
`SELECT format_type(atttypid, atttypmod) AS format_type
FROM pg_attribute
WHERE attrelid = 'query_cache'::regclass AND attname = 'embedding'`,
);
expect(queryCacheFormatRows[0]?.format_type).toMatch(/(halfvec|vector)\(4096\)/);
const queryCacheIndexRows = await largeDimEngine.executeRaw<{ exists: boolean }>(
`SELECT EXISTS (
SELECT 1 FROM pg_indexes
WHERE tablename = 'query_cache'
AND indexname = 'idx_query_cache_embedding_hnsw'
) AS exists`,
);
expect(queryCacheIndexRows[0]?.exists).toBe(false);
}, 60000);
});
@@ -1,40 +0,0 @@
import { describe, expect, test } from 'bun:test';
import { mkdtempSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join, resolve } from 'path';
import { bootstrapDestinationConfig } from '../src/commands/migrate-engine.ts';
import { loadConfigFileOnly } from '../src/core/config.ts';
import { withEnv } from './helpers/with-env.ts';
describe('migrate --to pglite destination bootstrap (#1271)', () => {
test('writes <path>/.gbrain/config.json so GBRAIN_HOME=<path> resolves a brain', async () => {
const dest = mkdtempSync(join(tmpdir(), 'gbrain-dest-'));
const written = bootstrapDestinationConfig(dest);
const file = join(dest, '.gbrain', 'config.json');
expect(written).toBe(file);
const cfg = JSON.parse(readFileSync(file, 'utf-8'));
expect(cfg.engine).toBe('pglite');
expect(cfg.database_path).toBe(resolve(dest));
expect(statSync(file).mode & 0o777).toBe(0o600);
// worktree safety: destination home is git-ignored like saveConfig()'s home
expect(readFileSync(join(dest, '.gbrain', '.gitignore'), 'utf-8')).toBe('*\n');
// The exact failure mode from #1271: config resolution under
// GBRAIN_HOME=<path> used to find nothing ("No brain configured").
await withEnv({ GBRAIN_HOME: dest }, () => {
const loaded = loadConfigFileOnly();
expect(loaded?.engine).toBe('pglite');
expect(loaded?.database_path).toBe(resolve(dest));
});
});
test('never clobbers an existing destination config', () => {
const dest = mkdtempSync(join(tmpdir(), 'gbrain-dest-'));
mkdirSync(join(dest, '.gbrain'), { recursive: true });
writeFileSync(join(dest, '.gbrain', 'config.json'), '{"engine":"postgres"}\n');
expect(bootstrapDestinationConfig(dest)).toBe(null);
expect(JSON.parse(readFileSync(join(dest, '.gbrain', 'config.json'), 'utf-8')).engine).toBe('postgres');
});
});