Files
gbrain/test/extract-fs.test.ts
T
699db50a3d fix(extract+migrate): kill N+1 hang + v0.12.0 migration timeout (v0.12.1) (#198)
* feat(engine): add addLinksBatch + addTimelineEntriesBatch via unnest()

Multi-row INSERT...SELECT FROM unnest() JOIN pages ON CONFLICT DO NOTHING
RETURNING 1. 4 array-typed bound parameters (links) or 5 (timeline)
regardless of batch size, sidesteps Postgres's 65535-parameter cap.

Returns count of rows actually inserted (excluding ON CONFLICT no-ops
and JOIN-dropped rows whose slugs don't exist).

Per-row addLink / addTimelineEntry signatures and SQL behavior unchanged.
All 10 existing call sites compile and behave identically.

Tests: 11 PGLite cases (empty batch, missing optionals, within-batch dedup,
JOIN drops missing slug, half-existing batch, batch of 100) + 9 E2E
postgres-engine cases against real Postgres+pgvector.

* fix(migrate): pre-create btree helper in v8 + v9 dedup; bump phaseASchema timeout

Production bug: v0.12.0 schema migration timed out at Supabase Management API's
60s ceiling on brains with 80K+ duplicate timeline rows. The DELETE...USING
self-join was O(n²) without an index on the dedup columns.

Fix: pre-create idx_links_dedup_helper / idx_timeline_dedup_helper on the
dedup columns BEFORE the DELETE, drop after. Turns O(n²) into O(n log n).
On 80K+ rows the migration completes in <1s instead of timing out.

Also bumps the v0.12.0 orchestrator's phaseASchema timeout 60s -> 600s as
belt-and-suspenders for unforeseen slowness.

Exports MIGRATIONS for structural test assertions.

Tests: 2 structural assertions (helper-index DDL must appear in v8/v9 SQL
in the right order — catches regression even at 0-row scale) + 2 behavioral
regression tests (1000-row dedup completes <5s).

* perf(extract): kill N+1 dedup pre-load; switch to batched writes

Production bug: gbrain extract hung 10+ minutes producing zero output on
47K-page brains. The pre-load loop called engine.getLinks(slug) (or
getTimeline) once per page across engine.listPages({limit: 100000}) — 47K
serial round-trips over the Supabase pooler before the first file was read.

Both engines already enforced uniqueness at the SQL layer
(UNIQUE(from, to, link_type) on links, idx_timeline_dedup on timeline_entries).
The in-memory dedup Set was redundant insurance that became the bottleneck.

Fix: delete the pre-load entirely. Buffer 100 candidates per file walk,
flush via engine.addLinksBatch / engine.addTimelineEntriesBatch. ~99% fewer
DB round-trips per re-extract.

Also fixes counter accuracy: 'created' now counts rows actually inserted
(via batch RETURNING 1 row count). Re-run on a fully-extracted brain
prints 'Done: 0 links' instead of lying.

Dry-run mode keeps a per-run dedup Set so duplicate candidates from N
markdown files print exactly once, not N times.

Batch errors are visible in BOTH json and human modes — silent loss of
100 rows is worse than per-row error visibility.

Tests: extract-fs.test.ts (idempotency + truthful counter + dry-run dedup
+ perf regression guard <2s).

* chore: bump version + changelog (v0.12.1)

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

* docs: update CLAUDE.md for v0.12.1 (batch engine API, test counts)

Reflect what shipped in v0.12.1:
- New engine methods addLinksBatch + addTimelineEntriesBatch (PGLite via
  unnest() + manual $N, postgres-engine via INSERT...SELECT FROM
  unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING).
- extract.ts no longer pre-loads dedup set; candidates are buffered 100
  at a time and flushed via the new batch methods.
- v0.12.0 orchestrator phaseASchema timeout bumped 60s to 600s.
- Test counts 1297 unit / 105 E2E to 1412 unit / 119 E2E.
- New test/extract-fs.test.ts covers the N+1 regression guard.
- BrainEngine method count 37/38 to 40.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 05:26:39 +08:00

162 lines
6.1 KiB
TypeScript

/**
* Tests for `gbrain extract --source fs` (the default, FS-walking path).
*
* Companion to test/extract-db.test.ts. Specifically guards against the
* v0.12.0 N+1 hang: extractLinksFromDir / extractTimelineFromDir used to
* pre-load the entire dedup set with one engine.getLinks() per page across
* engine.listPages(), which on a 47K-page brain meant 47K sequential
* round-trips before any work happened.
*
* Verifies:
* 1. Single run extracts the expected links + timeline entries.
* 2. Second run reports `created: 0` (proves DO NOTHING in batch + accurate
* counter via RETURNING).
* 3. --dry-run prints the same link found across multiple files exactly
* once (proves the dry-run-only dedup Set works).
* 4. Second run wall-clock < 2s (regression guard against any future change
* that re-introduces the N+1 read pre-load).
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runExtract } from '../src/commands/extract.ts';
import type { PageInput } from '../src/core/types.ts';
let engine: PGLiteEngine;
let brainDir: string;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
});
afterAll(async () => {
await engine.disconnect();
});
async function truncateAll() {
for (const t of ['content_chunks', 'links', 'tags', 'raw_data', 'timeline_entries', 'page_versions', 'ingest_log', 'pages']) {
await (engine as any).db.exec(`DELETE FROM ${t}`);
}
}
const personPage = (title: string, body = ''): PageInput => ({
type: 'person', title, compiled_truth: body, timeline: '',
});
const companyPage = (title: string, body = ''): PageInput => ({
type: 'company', title, compiled_truth: body, timeline: '',
});
beforeEach(async () => {
await truncateAll();
brainDir = mkdtempSync(join(tmpdir(), 'gbrain-extract-fs-'));
});
function writeFile(rel: string, content: string) {
const full = join(brainDir, rel);
mkdirSync(join(full, '..'), { recursive: true });
writeFileSync(full, content);
}
describe('gbrain extract links --source fs', () => {
test('first run inserts links, second run reports 0 (idempotent + truthful counter)', async () => {
// Set up brain in DB matching the file structure
await engine.putPage('people/alice', personPage('Alice'));
await engine.putPage('people/bob', personPage('Bob'));
await engine.putPage('companies/acme', companyPage('Acme'));
// Set up matching markdown files on disk
writeFile('people/alice.md', '---\ntitle: Alice\n---\n\n[Bob](../people/bob.md) is a friend.\n');
writeFile('people/bob.md', '---\ntitle: Bob\n---\n\nWorks at [Acme](../companies/acme.md).\n');
writeFile('companies/acme.md', '---\ntitle: Acme\n---\n\nFounded by [Alice](../people/alice.md).\n');
// First run — write batch path
await runExtract(engine, ['links', '--dir', brainDir]);
const linksAfter1 = (await engine.getLinks('people/alice'))
.concat(await engine.getLinks('people/bob'))
.concat(await engine.getLinks('companies/acme'));
expect(linksAfter1.length).toBeGreaterThanOrEqual(3);
// Second run — must dedup via ON CONFLICT and report 0 new (truthful counter)
const start = Date.now();
await runExtract(engine, ['links', '--dir', brainDir]);
const elapsedMs = Date.now() - start;
const linksAfter2 = (await engine.getLinks('people/alice'))
.concat(await engine.getLinks('people/bob'))
.concat(await engine.getLinks('companies/acme'));
expect(linksAfter2.length).toBe(linksAfter1.length);
// Perf regression guard: re-run on tiny fixture must not loop through
// listPages + per-page getLinks. ~10 files should complete in well under
// 2s even on a slow CI box.
expect(elapsedMs).toBeLessThan(2000);
});
test('--dry-run dedups duplicate candidates across files (printed once, not N times)', async () => {
await engine.putPage('people/alice', personPage('Alice'));
await engine.putPage('companies/acme', companyPage('Acme'));
// Same link target appears in 3 different files. The target file must
// exist on disk so the FS extractor's allSlugs Set includes it.
writeFile('companies/acme.md', '---\ntitle: Acme\n---\n');
writeFile('a.md', '[Acme](companies/acme.md)\n');
writeFile('b.md', '[Acme](companies/acme.md)\n');
writeFile('c.md', '[Acme](companies/acme.md)\n');
// Capture stdout to check print frequency
const lines: string[] = [];
const origLog = console.log;
console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
try {
await runExtract(engine, ['links', '--dry-run', '--dir', brainDir]);
} finally {
console.log = origLog;
}
// Each (from, to, link_type) tuple should print at most once.
// Three distinct from_slugs (a, b, c) all link to companies/acme, so
// we expect 3 link lines (one per source file), not 9.
const linkLines = lines.filter(l => l.includes('→') && l.includes('companies/acme'));
expect(linkLines.length).toBe(3);
// No actual writes happened
const links = await engine.getLinks('companies/acme');
expect(links.length).toBe(0);
});
});
describe('gbrain extract timeline --source fs', () => {
test('first run inserts entries, second run reports 0 (idempotent + truthful counter)', async () => {
await engine.putPage('people/alice', personPage('Alice'));
writeFile('people/alice.md', `---
title: Alice
---
## Timeline
- **2024-01-15** | source — Founded NovaMind
- **2024-06-01** | source — Raised seed round
`);
await runExtract(engine, ['timeline', '--dir', brainDir]);
const after1 = await engine.getTimeline('people/alice');
expect(after1.length).toBe(2);
const start = Date.now();
await runExtract(engine, ['timeline', '--dir', brainDir]);
const elapsedMs = Date.now() - start;
const after2 = await engine.getTimeline('people/alice');
expect(after2.length).toBe(2);
expect(elapsedMs).toBeLessThan(2000);
});
});