Files
gbrain/test/doctor-embedding-env-override.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

150 lines
5.8 KiB
TypeScript

// v0.41.2.1 — embedding_env_override doctor check (D9 #9).
//
// Pinned contracts:
// - env unset → ok
// - env+DB agree → ok
// - env model OR dim disagrees → warn with `details.mismatches[]`
// - getConfig throws → warn with "couldn't read DB config" message
// - Cross-surface parity: BOTH buildChecks() and doctorReportRemote()
// include the check (source-grep regression guard)
//
// Hermetic: PGLite + withEnv per CLAUDE.md R1/R3/R4.
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { readFileSync } from 'fs';
import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { buildChecks, doctorReportRemote, type Check } from '../src/commands/doctor.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
}, 60000);
afterAll(async () => {
await engine.disconnect();
});
beforeEach(async () => {
await resetPgliteState(engine);
});
function findCheck(checks: Check[], name: string): Check | undefined {
return checks.find((c) => c.name === name);
}
describe('embedding_env_override check (buildChecks seam)', () => {
test('env unset → ok', async () => {
await withEnv(
{ GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined },
async () => {
const checks = await buildChecks(engine, []);
const check = findCheck(checks, 'embedding_env_override');
expect(check).toBeDefined();
expect(check!.status).toBe('ok');
expect(check!.message).toContain('no embedding env overrides set');
},
);
});
test('env+DB agree → ok', async () => {
await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
await engine.setConfig('embedding_dimensions', '1280');
await withEnv(
{
GBRAIN_EMBEDDING_MODEL: 'zeroentropyai:zembed-1',
GBRAIN_EMBEDDING_DIMENSIONS: '1280',
},
async () => {
const checks = await buildChecks(engine, []);
const check = findCheck(checks, 'embedding_env_override');
expect(check!.status).toBe('ok');
expect(check!.message).toContain('agree with DB config');
},
);
});
test('env model disagrees with DB → warn with details.mismatches', async () => {
await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
await withEnv(
{ GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-large' },
async () => {
const checks = await buildChecks(engine, []);
const check = findCheck(checks, 'embedding_env_override');
expect(check!.status).toBe('warn');
const details = check!.details as { mismatches: Array<{ key: string; env: string; db: string }> };
expect(details.mismatches).toHaveLength(1);
expect(details.mismatches[0].key).toBe('GBRAIN_EMBEDDING_MODEL');
expect(details.mismatches[0].env).toBe('openai:text-embedding-3-large');
expect(details.mismatches[0].db).toBe('zeroentropyai:zembed-1');
// Message includes paste-ready unset
expect(check!.message).toContain('unset GBRAIN_EMBEDDING_MODEL');
},
);
});
test('env dim disagrees with DB → warn with details.mismatches', async () => {
await engine.setConfig('embedding_dimensions', '1280');
await withEnv(
{ GBRAIN_EMBEDDING_DIMENSIONS: '1536' },
async () => {
const checks = await buildChecks(engine, []);
const check = findCheck(checks, 'embedding_env_override');
expect(check!.status).toBe('warn');
const details = check!.details as { mismatches: Array<{ key: string; env: string; db: string }> };
expect(details.mismatches).toHaveLength(1);
expect(details.mismatches[0].key).toBe('GBRAIN_EMBEDDING_DIMENSIONS');
},
);
});
test('both disagree → 2 mismatches', async () => {
await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
await engine.setConfig('embedding_dimensions', '1280');
await withEnv(
{
GBRAIN_EMBEDDING_MODEL: 'openai:x',
GBRAIN_EMBEDDING_DIMENSIONS: '1536',
},
async () => {
const checks = await buildChecks(engine, []);
const check = findCheck(checks, 'embedding_env_override');
expect(check!.status).toBe('warn');
const details = check!.details as { mismatches: Array<{ key: string }> };
expect(details.mismatches).toHaveLength(2);
expect(check!.message).toContain('unset GBRAIN_EMBEDDING_MODEL GBRAIN_EMBEDDING_DIMENSIONS');
},
);
});
test('doctorReportRemote() includes the check (cross-surface parity)', async () => {
await withEnv({ GBRAIN_EMBEDDING_MODEL: 'openai:something' }, async () => {
await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
const report = await doctorReportRemote(engine);
const check = findCheck(report.checks, 'embedding_env_override');
expect(check).toBeDefined();
expect(check!.status).toBe('warn');
});
});
});
describe('cross-surface parity (source-grep regression guard)', () => {
test('doctor.ts wires checkEmbeddingEnvOverride into BOTH buildChecks and doctorReportRemote', () => {
// Static regression assertion: the helper must be called from BOTH surfaces.
// If a future maintainer removes the call from one surface, this test fails
// pointing at the asymmetry.
const src = readFileSync(
join(import.meta.dir, '../src/commands/doctor.ts'),
'utf-8',
);
// The helper is called as `await checkEmbeddingEnvOverride(engine)`
const matches = src.match(/await checkEmbeddingEnvOverride\(engine\)/g) ?? [];
expect(matches.length).toBeGreaterThanOrEqual(2);
});
});