* fix(sync): remove nested transaction that deadlocks > 10 file syncs sync.ts wraps the add/modify loop in engine.transaction(), and each importFromContent inside opens another one. PGLite's _runExclusiveTransaction is a non-reentrant mutex — the second call queues on the mutex the first is holding, and the process hangs forever in ep_poll. Reproduced with a 15-file commit: unpatched hangs, patched runs in 3.4s. Fix drops the outer wrap; per-file atomicity is correct anyway (one file's failure should not roll back the others). (cherry picked from commit 4a1ac00105226695d16fb343b44e55a52f44b95b) * test(sync): regression guard for #132 top-level engine.transaction wrap Reads src/commands/sync.ts verbatim and asserts no uncommented engine.transaction() call appears above the add/modify loop. Protects against silent reintroduction of the nested-mutex deadlock that hung > 10-file syncs forever in ep_poll. * feat(utils): tryParseEmbedding() skip+warn sibling for availability path parseEmbedding() throws on structural corruption — right call for ingest/ migrate paths where silent skips would be data loss. Wrong call for search/rescore paths where one corrupt row in 10K would kill every query that touches it. tryParseEmbedding() wraps parseEmbedding in try/catch: returns null on any shape that would throw, warns once per session so the bad row is visible in logs. Use it anywhere we'd rather degrade ranking than blow up the whole query. Retrofit postgres-engine.getEmbeddingsByChunkIds (the #175 slice call site) — the 5-line rescore loop was the direct motivator. Keep the throwing parseEmbedding() for everything else (pglite-engine rowToChunk, migrate-engine round-trips, ingest). * postgres-engine: scope search statement_timeout to the transaction searchKeyword and searchVector run on a pooled postgres.js client (max: 10 by default). The original code bounded each search with await sql`SET statement_timeout = '8s'` try { await sql`<query>` } finally { await sql`SET statement_timeout = '0'` } but every tagged template is an independent round-trip that picks an arbitrary connection from the pool. The SET, the query, and the reset could all land on DIFFERENT connections. In practice the GUC sticks to whichever connection ran the SET and then gets returned to the pool — the next unrelated caller on that connection inherits the 8s timeout (clipping legitimate long queries) or the reset-to-0 (disabling the guard for whoever expected it). A crash in the middle leaves the state set permanently. Wrap each search in sql.begin(async sql => …). postgres.js reserves a single connection for the transaction body, so the SET LOCAL, the query, and the implicit COMMIT all run on the same connection. SET LOCAL scopes the GUC to the transaction — COMMIT or ROLLBACK restores the previous value automatically, regardless of the code path out. Error paths can no longer leak the GUC. No API change. Timeout value and semantics are identical (8s cap on search queries, no effect on embed --all / bulk import which runs outside these methods). Only one transaction per search — BEGIN + COMMIT round-trips are negligible next to a ranked FTS or pgvector query. Also closes the earlier audit finding R4-F002 which reported the same pattern on searchKeyword. This PR covers both searchKeyword and searchVector so the pool-leak class is fully closed. Tests (test/postgres-engine.test.ts, new file): - No bare SET statement_timeout remains after stripping comments. - searchKeyword and searchVector each wrap their query in sql.begin. - Both use SET LOCAL. - Neither explicitly clears the timeout with SET statement_timeout=0. Source-level guardrails keep the fast unit suite DB-free. Live Postgres coverage of the search path is in test/e2e/search-quality.test.ts, which continues to exercise these methods end-to-end against pgvector when DATABASE_URL is set. (cherry picked from commit 6146c3b470dce7380da024a238eab9e6b2174296) * feat(orphans): add gbrain orphans command for finding under-connected pages Surfaces pages with zero inbound wikilinks. Essential for content enrichment cycles in KBs with 1000+ pages. By default filters out auto-generated pages, raw sources, and pseudo-pages where no inbound links is expected; --include-pseudo to disable. Supports text (grouped by domain), --json, --count outputs. Also exposed as find_orphans MCP operation. Tests cover basic detection, filtering, all output modes. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> (cherry picked from commit f50954f8e03f85803c6133c85c530bd45e9aceaa) * feat(extract): support Obsidian wikilinks + wiki-style domain slugs in canonical extractor extractEntityRefs now recognizes both syntaxes equally: [Name](people/slug) -- upstream original [[people/slug|Name]] -- Obsidian wikilink (new) Extends DIR_PATTERN to include domain-organized wiki slugs used by Karpathy-style knowledge bases: - entities (legacy prefix some brains keep during migration) - projects (gbrain canonical, was missing from regex) - tech, finance, personal, openclaw (domain-organized wiki roots) Before this change, a 2,100-page brain with wikilinks throughout extracted zero auto-links on put_page because the regex only matched markdown-style [name](path). After: 1,377 new typed edges on a single extract --source db pass over the same corpus. Matches the behavior of the extract.ts filesystem walker (which already handled wikilinks as of the wiki-markdown-compat fix wave), so the db and fs sources now produce the same link graph from the same content. Both patterns share the DIR_PATTERN constant so adding a new entity dir only requires updating one string. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> (cherry picked from commit 1cfb15679a684e94bec5a48c537a0a40a85f57ab) * feat(doctor): jsonb_integrity + markdown_body_completeness detection Add two v0.12.1-era reliability checks to `gbrain doctor`: - `jsonb_integrity` scans the 4 known write sites from the v0.12.0 double-encode bug (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata) and reports rows where jsonb_typeof(col) = 'string'. The fix hint points at `gbrain repair-jsonb` (the standalone repair command shipped in v0.12.1). - `markdown_body_completeness` flags pages whose compiled_truth is <30% of the raw source content length when raw has multiple H2/H3 boundaries. Heuristic only; suggests `gbrain sync --force` or `gbrain import --force <slug>`. Also adds test/e2e/jsonb-roundtrip.test.ts — the regression coverage that should have caught the original double-encode bug. Hits all four write sites against real Postgres and asserts jsonb_typeof='object' plus `->>'key'` returns the expected scalar. Detection only: doctor diagnoses, `gbrain repair-jsonb` treats. No overlap with the standalone repair path. * chore: bump to v0.12.3 + changelog (reliability wave) Master shipped v0.12.1 (extract N+1 + migration timeout) and v0.12.2 (JSONB double-encode + splitBody + wiki types + parseEmbedding) while this wave was mid-flight. Ships the remaining pieces as v0.12.3: - sync deadlock (#132, @sunnnybala) - statement_timeout scoping (#158, @garagon) - Obsidian wikilinks + domain patterns (#187 slice, @knee5) - gbrain orphans command (#187 slice, @knee5) - tryParseEmbedding() availability helper - doctor detection for jsonb_integrity + markdown_body_completeness No schema, no migration, no data touch. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs: update project documentation for v0.12.3 CLAUDE.md: - Add src/commands/orphans.ts entry - Expand src/commands/doctor.ts with v0.12.3 jsonb_integrity + markdown_body_completeness check descriptions - Update src/core/link-extraction.ts to mention Obsidian wikilinks + extended DIR_PATTERN (entities/projects/tech/finance/personal/openclaw) - Update src/core/utils.ts to mention tryParseEmbedding sibling - Update src/core/postgres-engine.ts to note statement_timeout scoping + tryParseEmbedding usage in getEmbeddingsByChunkIds - Add Key commands added in v0.12.3 section (orphans, doctor checks) - Add test/orphans.test.ts, test/postgres-engine.test.ts, updated descriptions for test/sync.test.ts, test/doctor.test.ts, test/utils.test.ts - Add test/e2e/jsonb-roundtrip.test.ts with note on intentional overlap - Bump operation count from ~36 to ~41 (find_orphans shipped in v0.12.3) README.md: - Add gbrain orphans to ADMIN commands block Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: sunnnybala <dhruvagarwal5018@gmail.com> Co-authored-by: Gustavo Aragon <gustavoraularagon@gmail.com> Co-authored-by: Clevin Canales <clevin@Clevins-MacBook-Pro.local> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Clevin Canales <clev.canales@gmail.com>
187 lines
6.5 KiB
TypeScript
187 lines
6.5 KiB
TypeScript
import { describe, test, expect } from 'bun:test';
|
|
import { validateSlug, contentHash, parseEmbedding, tryParseEmbedding, rowToPage, rowToChunk, rowToSearchResult } from '../src/core/utils.ts';
|
|
|
|
describe('validateSlug', () => {
|
|
test('accepts valid slugs', () => {
|
|
expect(validateSlug('people/sarah-chen')).toBe('people/sarah-chen');
|
|
expect(validateSlug('concepts/rag')).toBe('concepts/rag');
|
|
expect(validateSlug('simple')).toBe('simple');
|
|
});
|
|
|
|
test('normalizes to lowercase', () => {
|
|
expect(validateSlug('People/Sarah-Chen')).toBe('people/sarah-chen');
|
|
expect(validateSlug('UPPER')).toBe('upper');
|
|
});
|
|
|
|
test('rejects empty slug', () => {
|
|
expect(() => validateSlug('')).toThrow('Invalid slug');
|
|
});
|
|
|
|
test('rejects path traversal', () => {
|
|
expect(() => validateSlug('../etc/passwd')).toThrow('path traversal');
|
|
expect(() => validateSlug('test/../hack')).toThrow('path traversal');
|
|
});
|
|
|
|
test('rejects leading slash', () => {
|
|
expect(() => validateSlug('/absolute/path')).toThrow('start with /');
|
|
});
|
|
});
|
|
|
|
describe('contentHash', () => {
|
|
test('returns deterministic hash', () => {
|
|
const page = { title: 'Test', type: 'concept' as const, compiled_truth: 'hello', timeline: 'world' };
|
|
const h1 = contentHash(page);
|
|
const h2 = contentHash(page);
|
|
expect(h1).toBe(h2);
|
|
});
|
|
|
|
test('changes when content changes', () => {
|
|
const h1 = contentHash({ title: 'Test', type: 'concept' as const, compiled_truth: 'hello', timeline: 'world' });
|
|
const h2 = contentHash({ title: 'Test', type: 'concept' as const, compiled_truth: 'hello', timeline: 'changed' });
|
|
expect(h1).not.toBe(h2);
|
|
});
|
|
|
|
test('returns hex string', () => {
|
|
const h = contentHash({ title: 'Test', type: 'concept' as const, compiled_truth: 'test', timeline: '' });
|
|
expect(h).toMatch(/^[a-f0-9]{64}$/);
|
|
});
|
|
});
|
|
|
|
describe('rowToPage', () => {
|
|
test('parses string frontmatter', () => {
|
|
const page = rowToPage({
|
|
id: 1, slug: 'test', type: 'concept', title: 'Test',
|
|
compiled_truth: 'body', timeline: '',
|
|
frontmatter: '{"key":"val"}',
|
|
content_hash: 'abc', created_at: '2024-01-01', updated_at: '2024-01-01',
|
|
});
|
|
expect(page.frontmatter.key).toBe('val');
|
|
});
|
|
|
|
test('handles object frontmatter', () => {
|
|
const page = rowToPage({
|
|
id: 1, slug: 'test', type: 'concept', title: 'Test',
|
|
compiled_truth: 'body', timeline: '',
|
|
frontmatter: { key: 'val' },
|
|
content_hash: 'abc', created_at: '2024-01-01', updated_at: '2024-01-01',
|
|
});
|
|
expect(page.frontmatter.key).toBe('val');
|
|
});
|
|
|
|
test('creates Date objects', () => {
|
|
const page = rowToPage({
|
|
id: 1, slug: 'test', type: 'concept', title: 'Test',
|
|
compiled_truth: '', timeline: '', frontmatter: '{}',
|
|
content_hash: null, created_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z',
|
|
});
|
|
expect(page.created_at).toBeInstanceOf(Date);
|
|
expect(page.updated_at).toBeInstanceOf(Date);
|
|
});
|
|
});
|
|
|
|
describe('rowToChunk', () => {
|
|
test('nulls embedding by default', () => {
|
|
const chunk = rowToChunk({
|
|
id: 1, page_id: 1, chunk_index: 0, chunk_text: 'text',
|
|
chunk_source: 'compiled_truth', embedding: new Float32Array(10),
|
|
model: 'test', token_count: 5, embedded_at: '2024-01-01',
|
|
});
|
|
expect(chunk.embedding).toBeNull();
|
|
});
|
|
|
|
test('includes embedding when requested', () => {
|
|
const emb = new Float32Array(10).fill(0.5);
|
|
const chunk = rowToChunk({
|
|
id: 1, page_id: 1, chunk_index: 0, chunk_text: 'text',
|
|
chunk_source: 'compiled_truth', embedding: emb,
|
|
model: 'test', token_count: 5, embedded_at: '2024-01-01',
|
|
}, true);
|
|
expect(chunk.embedding).not.toBeNull();
|
|
});
|
|
|
|
test('parses pgvector string embeddings when requested', () => {
|
|
const chunk = rowToChunk({
|
|
id: 1, page_id: 1, chunk_index: 0, chunk_text: 'text',
|
|
chunk_source: 'compiled_truth', embedding: '[0.1, 0.2, 0.3]',
|
|
model: 'test', token_count: 5, embedded_at: '2024-01-01',
|
|
}, true);
|
|
expect(chunk.embedding).toBeInstanceOf(Float32Array);
|
|
expect(Array.from(chunk.embedding || [])).toHaveLength(3);
|
|
expect(chunk.embedding?.[0]).toBeCloseTo(0.1, 6);
|
|
expect(chunk.embedding?.[1]).toBeCloseTo(0.2, 6);
|
|
expect(chunk.embedding?.[2]).toBeCloseTo(0.3, 6);
|
|
});
|
|
});
|
|
|
|
describe('parseEmbedding', () => {
|
|
test('returns Float32Array unchanged', () => {
|
|
const emb = new Float32Array([0.1, 0.2]);
|
|
expect(parseEmbedding(emb)).toBe(emb);
|
|
});
|
|
|
|
test('parses pgvector text into Float32Array', () => {
|
|
const parsed = parseEmbedding('[0.1, 0.2, 0.3]');
|
|
expect(parsed).toBeInstanceOf(Float32Array);
|
|
expect(Array.from(parsed || [])).toHaveLength(3);
|
|
expect(parsed?.[0]).toBeCloseTo(0.1, 6);
|
|
expect(parsed?.[1]).toBeCloseTo(0.2, 6);
|
|
expect(parsed?.[2]).toBeCloseTo(0.3, 6);
|
|
});
|
|
|
|
test('returns null for unsupported embedding values', () => {
|
|
expect(parseEmbedding(null)).toBeNull();
|
|
expect(parseEmbedding(undefined)).toBeNull();
|
|
expect(parseEmbedding('not-a-vector')).toBeNull();
|
|
});
|
|
|
|
test('parses numeric array into Float32Array', () => {
|
|
const parsed = parseEmbedding([0.5, 0.25, 0.125]);
|
|
expect(parsed).toBeInstanceOf(Float32Array);
|
|
expect(parsed?.[0]).toBeCloseTo(0.5, 6);
|
|
});
|
|
|
|
test('throws on vector-like string with non-numeric content (no silent NaN)', () => {
|
|
expect(() => parseEmbedding('[abc, def]')).toThrow();
|
|
expect(() => parseEmbedding('[1, NaN, 3]')).toThrow();
|
|
});
|
|
});
|
|
|
|
describe('tryParseEmbedding', () => {
|
|
test('returns null on corrupt embedding instead of throwing', () => {
|
|
expect(tryParseEmbedding('[0.1,NaN,0.3]')).toBeNull();
|
|
expect(tryParseEmbedding(['bad' as unknown as number, 1])).toBeNull();
|
|
});
|
|
|
|
test('delegates happy path to parseEmbedding', () => {
|
|
const out = tryParseEmbedding('[0.1, 0.2]');
|
|
expect(out).toBeInstanceOf(Float32Array);
|
|
expect(out?.length).toBe(2);
|
|
});
|
|
|
|
test('warns once per session on corrupt rows', () => {
|
|
const orig = console.warn;
|
|
let warnCount = 0;
|
|
console.warn = () => { warnCount++; };
|
|
try {
|
|
tryParseEmbedding('[NaN]');
|
|
tryParseEmbedding('[NaN]');
|
|
tryParseEmbedding('[NaN]');
|
|
} finally {
|
|
console.warn = orig;
|
|
}
|
|
expect(warnCount).toBeLessThanOrEqual(1);
|
|
});
|
|
});
|
|
|
|
describe('rowToSearchResult', () => {
|
|
test('coerces score to number', () => {
|
|
const r = rowToSearchResult({
|
|
slug: 'test', page_id: 1, title: 'Test', type: 'concept',
|
|
chunk_text: 'text', chunk_source: 'compiled_truth',
|
|
score: '0.95', stale: false,
|
|
});
|
|
expect(typeof r.score).toBe('number');
|
|
expect(r.score).toBe(0.95);
|
|
});
|
|
});
|