mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-17 02:12:40 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa45398d83 |
@@ -1743,15 +1743,7 @@ async function extractStaleFromDB(
|
||||
// `page.updated_at.toISOString()` — the JS Date is ms-truncated, so the
|
||||
// µs-precision DB updated_at stayed strictly greater and the page never
|
||||
// cleared on Postgres. Stamping the exact value makes them equal.
|
||||
//
|
||||
// Version-arm floor: a page last edited BEFORE LINK_EXTRACTOR_VERSION_TS
|
||||
// would otherwise be stamped below the version watermark and stay
|
||||
// permanently stale (`links_extracted_at < versionTs` re-fires every run).
|
||||
// Stamp max(updated_at, versionTs) — versionTs is always a past release
|
||||
// date, so a concurrent edit's now() still exceeds the stamp and D4 holds.
|
||||
// Tie at ms precision picks updated_at_iso (its µs ≥ versionTs's .000000).
|
||||
const stampTs = new Date(page.updated_at_iso) >= new Date(versionTs) ? page.updated_at_iso : versionTs;
|
||||
processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: stampTs });
|
||||
processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: page.updated_at_iso });
|
||||
}
|
||||
|
||||
// Flush NON-swallowing (CDX-4): a throw here propagates out of the sweep so
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import { ensureWellFormed } from './text-safe.ts';
|
||||
* OR updated_at > links_extracted_at`. It is an ISO-8601 string (NOT a number) —
|
||||
* the column is TIMESTAMPTZ and the predicate binds it as `::timestamptz`.
|
||||
*/
|
||||
export const LINK_EXTRACTOR_VERSION_TS = '2026-07-21T00:00:00Z';
|
||||
export const LINK_EXTRACTOR_VERSION_TS = '2026-05-31T00:00:00Z';
|
||||
|
||||
// ─── Entity references ──────────────────────────────────────────
|
||||
|
||||
@@ -80,10 +80,10 @@ export type LinkResolutionType = 'qualified' | 'unqualified';
|
||||
* Directory prefix whitelist. These are the top-level slug dirs the extractor
|
||||
* recognizes as entity references. Upstream canonical + our extensions:
|
||||
* - Gbrain canonical: people, companies, meetings, concepts, deal, civic, project, source, media, yc, projects
|
||||
* - Our domain extensions: tech, finance, personal, openclaw, ops (domain-organized wikis)
|
||||
* - Our domain extensions: tech, finance, personal, openclaw (domain-organized wikis)
|
||||
* - Our entity prefix: entities (we kept some legacy entities/projects/ pages)
|
||||
*/
|
||||
const DIR_PATTERN = '(?:people|companies|meetings|concepts|deal|civic|project|projects|source|media|yc|tech|finance|personal|openclaw|entities|ops)';
|
||||
const DIR_PATTERN = '(?:people|companies|meetings|concepts|deal|civic|project|projects|source|media|yc|tech|finance|personal|openclaw|entities)';
|
||||
|
||||
/**
|
||||
* Match `[Name](path)` markdown links pointing to entity directories.
|
||||
@@ -865,16 +865,7 @@ export function queryBasenameIndex(idx: Map<string, string[]>, name: string): st
|
||||
if (!name || typeof name !== 'string') return [];
|
||||
const trimmed = name.trim();
|
||||
if (!trimmed) return [];
|
||||
let hit = idx.get(trimmed) ?? idx.get(trimmed.toLowerCase()) ?? idx.get(normalizeBasename(trimmed));
|
||||
// Issue #2576 bug 2: path-style refs (`runbooks/2026-05-01-x`) from dirs
|
||||
// outside DIR_PATTERN reach here, but normalizeBasename strips slashes
|
||||
// into a garbage key (`runbooks2026-05-01-x`) that can never hit the
|
||||
// tail-keyed index. Fall back to the path tail so qualified refs resolve
|
||||
// by basename like everything else.
|
||||
if (!hit && trimmed.includes('/')) {
|
||||
const tail = trimmed.slice(trimmed.lastIndexOf('/') + 1).trim();
|
||||
if (tail) hit = idx.get(tail) ?? idx.get(tail.toLowerCase()) ?? idx.get(normalizeBasename(tail));
|
||||
}
|
||||
const hit = idx.get(trimmed) ?? idx.get(trimmed.toLowerCase()) ?? idx.get(normalizeBasename(trimmed));
|
||||
return hit ? [...hit].sort(basenameSort) : [];
|
||||
}
|
||||
|
||||
|
||||
+21
-8
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -209,24 +209,6 @@ describe('gbrain extract --stale', () => {
|
||||
expect(usRows[0]?.eq).toBe(true);
|
||||
});
|
||||
|
||||
test('version-arm floor: page edited BEFORE LINK_EXTRACTOR_VERSION_TS clears after --stale (issue #2576 bug 3)', async () => {
|
||||
// A page whose updated_at predates the version watermark used to be
|
||||
// stamped at its updated_at (< versionTs), so the version arm re-fired
|
||||
// every run — permanently stale. The sweep now floors the stamp at
|
||||
// versionTs. (The #1768 test above also covers this since the v0.42.x
|
||||
// VERSION_TS bump moved its date below the watermark, but this pins the
|
||||
// behavior explicitly so a date "repair" there can't drop coverage.)
|
||||
await engine.putPage('people/alice', personPage('Alice'));
|
||||
await engine.executeRaw(`UPDATE pages SET updated_at = '2000-01-01T00:00:00Z' WHERE slug = 'people/alice'`);
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(1);
|
||||
|
||||
await runExtract(engine, ['--stale']);
|
||||
// Pre-floor this stayed 1 forever (stamp < versionTs → version arm re-fires).
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);
|
||||
await runExtract(engine, ['--stale']);
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);
|
||||
});
|
||||
|
||||
test('CDX-4 (D2): a link-flush throw aborts the sweep and leaves pages UNSTAMPED', async () => {
|
||||
await engine.putPage('people/alice', personPage('Alice'));
|
||||
await engine.putPage('companies/acme', companyPage('Acme', '[Alice](people/alice) founded [Acme](companies/acme).'));
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -140,15 +140,6 @@ describe('extractEntityRefs', () => {
|
||||
expect(wikiRefs[0].needsResolution).toBe(true);
|
||||
});
|
||||
|
||||
test('recognizes ops/ qualified wikilinks (issue #2576 bug 2)', () => {
|
||||
// `ops` was missing from DIR_PATTERN, so [[ops/...]] fell through to
|
||||
// the generic 2c pass (needsResolution) instead of being a real ref.
|
||||
const refs = extractEntityRefs('Deployed via [[ops/services/pointer-agent]].');
|
||||
expect(refs.length).toBe(1);
|
||||
expect(refs[0].slug).toBe('ops/services/pointer-agent');
|
||||
expect(refs[0].needsResolution).toBeUndefined();
|
||||
});
|
||||
|
||||
test('skips qualified-syntax tokens (those belong to 2a)', () => {
|
||||
// [[wiki:topics/ai]] looks like 2a's qualified shape — even though
|
||||
// it wouldn't satisfy DIR_PATTERN, 2c must not claim it either
|
||||
@@ -1078,15 +1069,6 @@ describe('makeResolver — fallback chain', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('resolveBasenameMatches: path-style ref falls back to the tail (issue #2576 bug 2)', async () => {
|
||||
// normalizeBasename strips slashes, so `runbooks/2026-05-01-pointer-agent`
|
||||
// used to normalize to a garbage key that never hit the tail-keyed index.
|
||||
const engine = makeFakeEngineWithSlugs(['ops/changes/2026-05-01-pointer-agent']);
|
||||
const r = makeResolver(engine);
|
||||
expect(await r.resolveBasenameMatches!('runbooks/2026-05-01-pointer-agent'))
|
||||
.toEqual(['ops/changes/2026-05-01-pointer-agent']);
|
||||
});
|
||||
|
||||
test('resolveBasenameMatches: case-insensitive fallback', async () => {
|
||||
const engine = makeFakeEngineWithSlugs(['companies/fast-weigh']);
|
||||
const r = makeResolver(engine);
|
||||
|
||||
Reference in New Issue
Block a user