Files
gbrain/test/e2e/extract-atoms-discovery-sql.test.ts
T
d036a97f9c v0.41.10.1 fix-wave: dream.* config + batch retry + extract_atoms idempotency + ze-switch env-gate (#1445)
* fix-wave: dream.* DB merge + batch retry + extract_atoms idempotency + ze-switch env-gate + doctor check

Closes PRs #1414, #1416, #1421 (rebuilt from designs by @garrytan-agents
with structural improvements from /plan-eng-review + codex outside-voice).

Three production reliability fixes in one wave:

1. dream.* DB-config merge (closes PR #1416 silent-config gap)
   - loadConfigWithEngine() sparse-merge extends with 7 dream.* keys
   - File > DB > defaults precedence (no GBRAIN_DREAM_* env vars)
   - extract-atoms switches to loadConfigWithEngine() so DB-plane keys reach it

2. Batch retry on transient connection drops (closes PR #1416 ~30%-loss bug)
   - withRetry() pure primitive exported from src/commands/extract.ts
   - 6 flush() sites snapshot-before-clear with onRetry callback
   - Reuses isRetryableConnError from src/core/retry-matcher.ts
   - retry-matcher extended with GBrainError{problem:'No database connection'}

3. extract_atoms source-hash idempotency + page-based discovery (closes #1414)
   - One raw SQL with NOT EXISTS subquery replaces 6 listPages + N atom checks
   - sourceId threaded through every putPage call (codex caught real bug)
   - NULL content_hash filter + dream_generated exclusion + transcript-side idempotency
   - cycle.ts passes union of syncPagesAffected + synthesizeWrittenSlugs

4. ze-switch pre-apply + pre-resume env-override gate (closes PR #1421)
   - Gate fires FIRST in apply AND resume; zero setConfig calls on refusal
   - ASCII warning box (no Unicode per repo D10)
   - --ignore-env-override escape hatch for power users
   - ApplyResult extended with refused variant

5. doctor embedding_env_override check (defense-in-depth for #1421)
   - Cross-surface parity: buildChecks() + doctorReportRemote()
   - Uses Check.details (not Check.issues per codex schema review)

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

* chore: bump version and changelog (v0.41.10.0)

Adds 61 new tests across 5 new files pinning the fix-wave contracts:
- test/extract-batch-retry.test.ts (16 cases) — withRetry primitive + snapshot contract
- test/extract-atoms-page-discovery.test.ts (17 cases) — discovery SQL + dual-source idempotency
- test/ze-switch-env-override.test.ts (17 cases) — env-gate apply + resume + ZERO-setConfig assertion
- test/doctor-embedding-env-override.test.ts (7 cases) — cross-surface parity
- test/e2e/extract-atoms-discovery-sql.test.ts (4 cases) — real-Postgres parity for raw SQL

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

* fix(test): pin gateway to 1536-dim in 2 PGLite tests that hardcode 1536-vector inserts

CI shards 1 + 4 failed persistently (not flake — confirmed via retry) after the
v0.41.6.0 merge with this error:

  error: expected 1280 dimensions, not 1536
  file: "vector.c", routine: "CheckExpectedDim"

Two test files insert 1536-dim Float32Array vectors into `content_chunks.embedding`
/ `facts.embedding`, but v0.41.5.0 flipped `DEFAULT_EMBEDDING_DIMENSIONS` from
1536 to 1280 (ZE Matryoshka default). On a fresh CI bun process where no prior
test pre-configured the gateway, `initSchema()` sizes the vector column at
vector(1280) and the inserts throw.

Locally this is hidden when an earlier test file in the shard happens to have
called `configureGateway({embedding_dimensions: 1536})` — that state leaks
forward through bun's shared process. The v0.41.6.0 LPT shard re-balancing
reordered files so these two ran cold, surfacing the latent bug.

Fix follows the canonical hermetic pattern from
test/consolidate-valid-until.test.ts:23-34: pin the gateway to 1536d in
beforeAll, reset in afterAll. Test is now isolated from shard ordering.

  test/search-types-filter.test.ts     — shard 1 fail
  test/operations-find-trajectory.test.ts — shard 4 (6 fails)

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

* chore: empty commit to trigger CI

* chore: trigger CI again

* chore: renumber v0.41.10.0 -> v0.41.10.1

Per request — version slot moved to .1 micro tier to leave .0 available
for unrelated wave landing on master.

---------

Co-authored-by: garrytan-agents <garrytan-agents@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 15:10:23 -07:00

136 lines
5.4 KiB
TypeScript

/**
* v0.41.2.1 — D10 reversal: real-Postgres parity for the new
* extract-atoms discovery SQL. Closes the D5 gap codex flagged: the
* raw SQL uses ANY($::text[]) binding, JSONB ->>, substring(... from N
* for M), and NOT EXISTS subquery — features PGLite parses but the
* real Postgres wire binding through `postgres.unsafe` is subtly
* different. PGLite-only tests are not proof.
*
* Asserts:
* 1. discoverExtractablePages returns rows on a seeded federated brain
* 2. NOT EXISTS subquery skips already-extracted source pages
* 3. sourceId scoping isolates between two seeded sources (no leak)
* 4. ANY($2::text[]) binding actually filters by type set
*
* ~4 structural assertions; ~3-5s wallclock budget.
* Skips gracefully when DATABASE_URL is unset.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { setupDB, teardownDB, hasDatabase } from './helpers.ts';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { discoverExtractablePages } from '../../src/core/cycle/extract-atoms.ts';
const skip = !hasDatabase();
const describeIfDB = skip ? describe.skip : describe;
let engine: PostgresEngine;
beforeAll(async () => {
if (skip) return;
engine = (await setupDB()) as PostgresEngine;
});
afterAll(async () => {
if (skip) return;
await teardownDB();
});
beforeEach(async () => {
if (skip) return;
// Clean test-source rows + atoms + meeting pages between tests
await engine.executeRaw(`DELETE FROM pages WHERE source_id IN ('default', 'dept-x') AND (type = 'atom' OR type IN ('meeting', 'source', 'article', 'video', 'book', 'original'))`);
await engine.executeRaw(`DELETE FROM sources WHERE id = 'dept-x'`);
});
const LONG = 'a'.repeat(800);
async function seedPage(opts: {
slug: string;
type: string;
content_hash?: string;
frontmatter?: Record<string, unknown>;
source_id?: string;
}) {
await engine.putPage(
opts.slug,
{
type: opts.type as never,
title: opts.slug,
compiled_truth: LONG,
timeline: '',
frontmatter: opts.frontmatter ?? {},
},
{ sourceId: opts.source_id ?? 'default' },
);
if (opts.content_hash) {
await engine.executeRaw(
`UPDATE pages SET content_hash = $1 WHERE slug = $2 AND source_id = $3`,
[opts.content_hash, opts.slug, opts.source_id ?? 'default'],
);
}
}
describeIfDB('v0.41.2.1 D10 — discoverExtractablePages on real Postgres', () => {
test('returns extractable rows when seeded', async () => {
await seedPage({ slug: 'meeting/a', type: 'meeting', content_hash: 'hash-A-1234567890abc' });
await seedPage({ slug: 'source/b', type: 'source', content_hash: 'hash-B-1234567890abc' });
await seedPage({ slug: 'notes/skip', type: 'note', content_hash: 'hash-N-1234567890abc' });
const discovered = await discoverExtractablePages(engine, 'default');
const slugs = discovered.map((d) => d.slug).sort();
expect(slugs).toContain('meeting/a');
expect(slugs).toContain('source/b');
expect(slugs).not.toContain('notes/skip');
});
test('ANY($::text[]) bind works through postgres.unsafe (PGLite parity proof)', async () => {
// Seed all 6 extractable types + one non-extractable. The SQL uses
// type = ANY($2::text[]) — if the binding shape differs between
// PGLite and postgres.js's unsafe(), this catches it.
for (const type of ['meeting', 'source', 'article', 'video', 'book', 'original']) {
await seedPage({ slug: `${type}/x`, type, content_hash: `hash-${type}-1234567890ab` });
}
await seedPage({ slug: 'note/skip', type: 'note', content_hash: 'hash-note-1234567890' });
const discovered = await discoverExtractablePages(engine, 'default');
const slugs = discovered.map((d) => d.slug).sort();
expect(slugs).toEqual([
'article/x', 'book/x', 'meeting/x', 'original/x', 'source/x', 'video/x',
]);
});
test('NOT EXISTS subquery skips pages with existing atoms', async () => {
await seedPage({ slug: 'meeting/old', type: 'meeting', content_hash: 'oldhash1234567890abc' });
await seedPage({ slug: 'meeting/new', type: 'meeting', content_hash: 'newhash1234567890abc' });
// Seed atom with frontmatter.source_hash = first 16 chars of oldhash
await engine.putPage(
'atoms/seeded/old-insight',
{
type: 'atom' as never,
title: 'old',
compiled_truth: 'b',
timeline: '',
frontmatter: { source_hash: 'oldhash123456789' }, // first 16 chars of seed
},
{ sourceId: 'default' },
);
const discovered = await discoverExtractablePages(engine, 'default');
expect(discovered.map((d) => d.slug)).toEqual(['meeting/new']);
});
test('sourceId scopes both candidate AND atom-existence subquery — no cross-source leak', async () => {
await engine.executeRaw(
`INSERT INTO sources (id, name) VALUES ('dept-x', 'dept-x') ON CONFLICT DO NOTHING`,
);
await seedPage({ slug: 'meeting/a-default', type: 'meeting', content_hash: 'hash-default-A-12345' });
await seedPage({ slug: 'meeting/a-dept-x', type: 'meeting', content_hash: 'hash-dept-x-A-12345', source_id: 'dept-x' });
const fromDefault = await discoverExtractablePages(engine, 'default');
const fromDeptX = await discoverExtractablePages(engine, 'dept-x');
expect(fromDefault.map((d) => d.slug)).toEqual(['meeting/a-default']);
expect(fromDeptX.map((d) => d.slug)).toEqual(['meeting/a-dept-x']);
});
});