Files
gbrain/test/e2e/integrity-batch.test.ts
T
e493d5f44b v0.32.8 fix: multi-source bug class extermination — embed, extract, takes, patterns, integrity, migrate-engine (#860)
* fix: thread source_id through embed --stale to fix silent discard of non-default source embeddings

listStaleChunks correctly finds chunks across all sources, but
embedOneSlug called getChunks(slug) and upsertChunks(slug, merged)
without passing sourceId. Both default to source_id='default', so
for non-default sources (e.g. media-corpus):

1. getChunks returns empty (wrong source)
2. merged array has no existing chunks to merge into
3. upsertChunks writes nothing (or errors silently)
4. Embeddings generated by the API are silently discarded

Fix:
- Add source_id to StaleChunkRow type
- Add p.source_id to listStaleChunks SQL in both postgres + pglite engines
- Extract sourceId from stale row in embed command
- Pass { sourceId } to getChunks and upsertChunks
- Group stale chunks by composite key (source_id::slug) instead of bare slug
  to handle same-slug pages across multiple sources

Verified: 97 chunks embedded across 35 pages in first run after fix.
Previously 0 non-default-source chunks were embedded across 3 full runs.

* fix: comprehensive multi-source threading for embed, listPages, and migrate-engine

Multi-source brains (e.g. with a 'media-corpus' source alongside
'default') have a pervasive bug: operations that iterate pages across
all sources then call engine methods (getChunks, upsertChunks,
getChunksWithEmbeddings) without passing sourceId. These methods all
default to source_id='default', silently operating on the wrong page
(or no page at all) for non-default sources.

Changes:

1. Page type + rowToPage: add optional source_id field so downstream
   callers can read the source from page objects returned by listPages.

2. PageFilters: add sourceId filter so listPages can scope to a single
   source (used by embed --source and future extract --source).

3. listPages (postgres + pglite): wire the sourceId filter into SQL.

4. embed command — three paths fixed:
   a. embedPage (single-slug): accepts sourceId, threads to getPage +
      getChunks + upsertChunks.
   b. embedAll (--all): reads page.source_id from listPages results,
      threads to getChunks + upsertChunks per page.
   c. embedAllStale (--stale): reads source_id from StaleChunkRow,
      groups by composite key (source_id::slug) instead of bare slug,
      threads to getChunks + upsertChunks per key.

5. embed CLI: add --source <id> flag, threaded through all paths.

6. migrate-engine: thread page.source_id through
   getChunksWithEmbeddings + upsertChunks so engine migrations don't
   lose non-default-source chunks.

7. getChunksWithEmbeddings (postgres + pglite + BrainEngine interface):
   accept optional { sourceId } to scope the chunk lookup.

8. StaleChunkRow type: add source_id field.

9. listStaleChunks SQL (postgres + pglite): add p.source_id to SELECT.

Verified: embed --stale correctly embeds 97 chunks across 35 pages
(previously 0 non-default-source chunks across 3 full runs).
embed --source media-corpus --dry-run correctly scopes to that source.

* v0.32.4 fix: multi-source threading for embed, listPages, and migrate-engine

Bump VERSION + package.json + CHANGELOG for the comprehensive multi-source
fix. Embed now threads source_id through every page → chunk handoff so
non-default sources stop silently dropping out (~22k chunks recovered on
the brain that surfaced this).

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

* fix: complete slugs→keys rename in embedAllStale

The composite-key rename in the prior commit missed 4 references in the
worker loop and trailing console.log, so the file failed typecheck
(`Cannot find name 'slugs'`). The author's "Verified compiling + running"
claim was false at the time of the PR.

Also drop the dead `const bySlug = byKey` alias — unused after rename.

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

* ci: add check-source-id-projection.sh + fix getPage/putPage projections

Two SELECT projections fed `rowToPage` without including `source_id`:
- postgres-engine.ts:562 (getPage), :609 (putPage RETURNING)
- pglite-engine.ts:505 (getPage), :548 (putPage RETURNING)

After the type-tightening in the next commit makes `Page.source_id`
required, those projections would silently produce `Page` rows with
source_id=undefined while TypeScript claims `: string`. Codex's plan
review (F2) caught this; this commit closes it.

The new `scripts/check-source-id-projection.sh` greps for the rowToPage
feeder shape (`SELECT id, slug, type, title, ...`) and fails the build
if any projection lacks `source_id`. Wired into `bun run verify`.

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

* feat(engine): Page.source_id required + listAllPageRefs + validateSourceId

Three coordinated changes that unlock the Phase 3 bug-site fixes:

1. `Page.source_id` is now required (was optional, v0.31.12). The DB column
   is `NOT NULL DEFAULT 'default'` so every row has it; the type now matches.
   `rowToPage` always emits it (falls back to 'default' if a stale projection
   somehow misses the column, but `scripts/check-source-id-projection.sh` is
   the primary guard).

2. `BrainEngine.listAllPageRefs()` returns `Array<{slug, source_id}>` ordered
   by `(source_id, slug)`. Cheap cross-source enumeration for hot loops in
   extract-takes / extract / integrity that previously used
   `getAllSlugs() → getPage(slug)` (N+1 query AND silently defaulted to
   'default'). PGLite + Postgres parity.

3. `validateSourceId(id)` in utils. Allows `[a-z0-9_-]+` only. Used by the
   per-source disk-layout fix coming in Phase 3 before any
   `join(brainDir, source_id, ...)` call so source_id can't traverse out
   of brainDir.

Deferred to v0.33 follow-up:
- D2 strict tightening of BrainEngine slug-method signatures (the compile-
  time guard for "future getPage calls must pass sourceId")
- F3 OperationContext.sourceId required at MCP boundary
- F4 LinkBatchInput / TimelineBatchInput required source_id fields
- D6 forEachPage / listPagesAfter helpers (use listPages directly for now)

Those are nice-to-have guardrails for future regressions. Current commit's
correctness via D7 + listAllPageRefs is what blocks the Phase 3 bug-site
fixes from working multi-source.

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

* fix: thread source_id through cycle phases, extract, integrity, migrate-engine

Five bug sites that previously called slug-only engine methods inside a
loop over pages, silently defaulting to source_id='default' for every
non-default-source page. Now all five use listAllPageRefs to enumerate
(slug, source_id) pairs and thread sourceId through to engine.getPage,
getTags, addLink, addTimelineEntry, getRawData, getVersions, etc.

Site-by-site:

- src/core/cycle/extract-takes.ts: listAllPageRefs replaces N+1
  getAllSlugs+getPage. Takes for non-default-source pages now extract.

- src/core/cycle/patterns.ts + synthesize.ts: reverseWriteSlugs renamed
  to reverseWriteRefs with Array<{slug, source_id}> contract. Disk
  layout (F6): non-default sources land at brainDir/.sources/<id>/<slug>.md
  so same-slug-different-source pages don't collide. Default-source
  pages stay at brainDir/<slug>.md so single-source brains see no
  change. source_id validated against [a-z0-9_-]+ at write time to
  prevent path traversal.

- src/commands/extract.ts: extractLinksFromDB + extractTimelineFromDB
  use listAllPageRefs. Cross-source link resolution rule (F10): origin's
  source wins, fall back to default, else skip (don't silently push a
  wrong-source edge). addLinksBatch / addTimelineEntriesBatch now fill
  from_source_id / to_source_id / origin_source_id / source_id so
  multi-source JOINs target the correct page row.

- src/commands/integrity.ts: same listAllPageRefs pattern in both the
  primary scan loop and the auto-repair loop.

- src/commands/migrate-engine.ts: end-to-end source_id threading
  (page + tags + timeline + raw + versions + links). Resume manifest
  keyed on `${source_id}::${slug}` so multi-source resumes don't
  collide on same-slug rows (pre-fix entries treated as default for
  back-compat).

test/cycle-synthesize-slug-collection.test.ts updated for the new
collectChildPutPageSlugs return shape (Array<{slug, source_id}>
instead of string[]).

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

* test(e2e): multi-source bug class regression + CHANGELOG + e2e-test-map wire-up

test/e2e/multi-source-bug-class.test.ts — 7-case PGLite regression suite
pinning every bug site fixed in this PR:
  - listAllPageRefs ordering by (source_id, slug) [F11]
  - getPage with sourceId picks the right (source, slug) row [F2]
  - extract-takes processes both alice pages independently
  - listPages filters correctly with PageFilters.sourceId
  - addLinksBatch with from/to_source_id targets the right rows [F4]
  - validateSourceId rejects path traversal [F6]
  - reverse-write disk layout uses .sources/<id>/<slug>.md [F6]

No DATABASE_URL needed (PGLite in-memory + canonical R3+R4 pattern).

Wire into scripts/e2e-test-map.ts so changes to any of the 6 touched
source files automatically trigger this test.

CHANGELOG expanded from the embed-only narrative to cover the full
bug-class extermination — extract, takes, patterns, integrity,
migrate-engine, plus the per-source disk layout, the CI gate, and
the new listAllPageRefs primitive. Voice: lead with what users can
DO that they couldn't before; real numbers from the production brain
that surfaced it.

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

* fix(integrity): batch path scans (source_id, slug) pairs too

The batch-load fast path in scanIntegrity used `SELECT DISTINCT ON (slug)`,
which silently collapsed multi-source duplicate slugs into a single scan —
the same bug class this PR fixes. test/e2e/integrity-batch.test.ts had a
case pinning the broken behavior ("scan once, not once-per-source") that
asserted batchResult.pagesScanned===1 for two real (source, slug) rows.

Switching the projection from `DISTINCT ON (slug)` to a plain `SELECT ...
ORDER BY source_id, slug` makes batch + sequential paths report the same
count (2) and matches the v0.32.4 listAllPageRefs walk.

Test renamed + assertion flipped to lock in the correct multi-source-aware
behavior: both paths now report 2, not 1.

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

* docs: sync CLAUDE.md + llms bundles for v0.32.4

CLAUDE.md annotations updated on the 4 files that materially changed in
this PR's bug-class extermination:

- src/core/engine.ts — new listAllPageRefs() method
- src/core/utils.ts — new validateSourceId() helper + Page.source_id
  required field plumbing
- src/commands/integrity.ts — batch projection switched from DISTINCT ON
  (slug) to ORDER BY (source_id, slug) so multi-source scans aren't
  collapsed
- scripts/check-source-id-projection.sh (NEW entry) — CI guard against
  SELECT projections that drop source_id

Plus a new test inventory entry for test/e2e/multi-source-bug-class.test.ts
in the E2E section.

llms-full.txt regenerated per CLAUDE.md's iron rule. llms.txt is unchanged
(just an index).

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

* chore: bump version slot v0.32.4 → v0.32.8

VERSION + package.json + CHANGELOG header only. Annotation
sweep across src/tests/scripts and the CLAUDE.md + llms bundle
regen land in the two follow-up commits so each step bisects
independently.

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

* chore: retag v0.32.4 → v0.32.8 across src/scripts/tests

Inline "introduced in" annotations follow the version slot bump
in the prior commit. No behavior change.

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

* docs: retag CLAUDE.md v0.32.4 → v0.32.8 + regen llms-full.txt

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

* Merge remote-tracking branch 'origin/master' into fix/multi-source-threading

---------

Co-authored-by: Wintermute <wintermute@garrytan.com>
Co-authored-by: Garry Tan <garrytan@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 23:02:03 -07:00

170 lines
6.1 KiB
TypeScript

/**
* E2E parity tests — scanIntegrity batch path vs sequential path.
*
* The batch path (Postgres-only fast path added in v0.20.x) and the sequential
* path (engine.getAllSlugs + getPage loop) MUST return the same result for
* every supported case, otherwise gbrain doctor reports different numbers
* depending on engine type or whether batch was attempted.
*
* Codex review of the original perf commit caught a multi-source dedup
* regression: the batch SQL scanned raw (source_id, slug) rows while
* sequential's getAllSlugs() returned a Set<string>. v0.22.7 adds
* SELECT DISTINCT ON (slug) to the batch SQL; these tests prove parity.
*
* Run: DATABASE_URL=... bun test test/e2e/integrity-batch.test.ts
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { hasDatabase, setupDB, teardownDB, getEngine, getConn } from './helpers.ts';
import { scanIntegrity } from '../../src/commands/integrity.ts';
const skip = !hasDatabase();
const describeE2E = skip ? describe.skip : describe;
if (skip) {
console.log('Skipping E2E integrity batch parity tests (DATABASE_URL not set)');
}
describeE2E('scanIntegrity batch parity (E2E, Postgres-only)', () => {
beforeAll(async () => {
await setupDB();
}, 30_000);
afterAll(async () => {
await teardownDB();
});
beforeEach(async () => {
// Clean slate per case so fixtures don't leak across describes.
const conn = getConn();
await conn.unsafe(`TRUNCATE pages CASCADE`);
});
describe('dedup', () => {
test('multi-source duplicate slugs scan ONE PER (source, slug) PAIR (v0.32.8 bug-class fix)', async () => {
const engine = getEngine();
const conn = getConn();
// Seed default-source page via the engine.
await engine.putPage('people/alice', {
type: 'person',
title: 'Alice',
compiled_truth: 'Alice writes about AI safety.',
timeline: '',
frontmatter: {},
});
// Seed alt-source row via raw SQL — engine.putPage's sourceId opt sets
// it but the test reads engine.putPage(slug, page) signature without
// it. Direct INSERT proves we have two real (source, slug) rows.
await conn.unsafe(`
INSERT INTO sources (id, name) VALUES ('test-source-2', 'test-source-2')
ON CONFLICT DO NOTHING
`);
await conn.unsafe(`
INSERT INTO pages (source_id, slug, type, title, compiled_truth, timeline, frontmatter)
VALUES ('test-source-2', 'people/alice', 'person', 'Alice (alt source)',
'Alice from another source.', '', '{}'::jsonb)
`);
const batchResult = await scanIntegrity(engine, { limit: 100, batchLoad: true });
const seqResult = await scanIntegrity(engine, { limit: 100, batchLoad: false });
// v0.32.8: both paths now scan EACH (source, slug) row independently.
// Pre-fix the test pinned dedup-to-1 — that hid the bug where alt-source
// rows were silently dropped. Now batch + sequential both report 2.
expect(batchResult.pagesScanned).toBe(seqResult.pagesScanned);
expect(batchResult.pagesScanned).toBe(2);
});
});
describe('hits', () => {
test('bareHits and externalHits arrays match between paths', async () => {
const engine = getEngine();
await engine.putPage('people/alice', {
type: 'person',
title: 'Alice',
compiled_truth: 'Alice tweeted about AI safety last week.',
timeline: '',
frontmatter: {},
});
await engine.putPage('people/bob', {
type: 'person',
title: 'Bob',
compiled_truth: 'Bob wrote at [example](https://example.com/bob).',
timeline: '',
frontmatter: {},
});
const batchResult = await scanIntegrity(engine, { limit: 100, batchLoad: true });
const seqResult = await scanIntegrity(engine, { limit: 100, batchLoad: false });
expect(batchResult.bareHits.length).toBe(seqResult.bareHits.length);
expect(batchResult.externalHits.length).toBe(seqResult.externalHits.length);
expect(batchResult.bareHits.map(h => h.slug).sort()).toEqual(
seqResult.bareHits.map(h => h.slug).sort(),
);
expect(batchResult.externalHits.map(h => h.slug).sort()).toEqual(
seqResult.externalHits.map(h => h.slug).sort(),
);
});
});
describe('validate', () => {
test('validate:false (boolean) page is skipped on both paths', async () => {
const engine = getEngine();
await engine.putPage('people/alice', {
type: 'person',
title: 'Alice',
compiled_truth: 'Alice tweeted about something.',
timeline: '',
frontmatter: {},
});
await engine.putPage('people/legacy', {
type: 'person',
title: 'Legacy',
compiled_truth: 'Legacy tweeted about old stuff.',
timeline: '',
frontmatter: { validate: false },
});
const batchResult = await scanIntegrity(engine, { limit: 100, batchLoad: true });
const seqResult = await scanIntegrity(engine, { limit: 100, batchLoad: false });
expect(batchResult.pagesScanned).toBe(seqResult.pagesScanned);
expect(batchResult.pagesScanned).toBe(1);
expect(batchResult.bareHits.map(h => h.slug)).not.toContain('people/legacy');
expect(seqResult.bareHits.map(h => h.slug)).not.toContain('people/legacy');
});
});
describe('topPages', () => {
test('topPages ordering matches between paths', async () => {
const engine = getEngine();
// Alice has 2 bare-tweet hits; Bob has 1.
await engine.putPage('people/alice', {
type: 'person',
title: 'Alice',
compiled_truth: 'Alice tweeted today. Alice tweeted yesterday too.',
timeline: '',
frontmatter: {},
});
await engine.putPage('people/bob', {
type: 'person',
title: 'Bob',
compiled_truth: 'Bob tweeted once.',
timeline: '',
frontmatter: {},
});
const batchResult = await scanIntegrity(engine, { limit: 100, batchLoad: true });
const seqResult = await scanIntegrity(engine, { limit: 100, batchLoad: false });
expect(batchResult.topPages).toEqual(seqResult.topPages);
});
});
});