Files
gbrain/test/search/knobs-hash-reranker.test.ts
T
5d42f3295e v0.41.22.0 feat: type-unification cathedral — 94 types → 15 canonical (closes #1479) (#1542)
* Merge branch 'master' into garrytan/type-taxonomy-unification

Resolve VERSION, package.json, CHANGELOG conflicts with v0.41.22.0
on top, preserving master's v0.41.19.0 entry below.

* feat: v0.41.22.0 type-unification cathedral — collapse 94 types to 15 (closes #1479)

Ships gbrain-base-v2 as the new install default (15 canonical types: 14
+ note catch-all) and the unify-types PROTECTED Minion handler that
runs the gbrain-base→v2 migration end-to-end on existing brains.

What this delivers:
- gbrain-base-v2.yaml standalone schema pack (no extends:) with 14
  canonical page_types + 9 cluster mapping_rules + catch-all sentinel
- 3 new schema-pack primitives: runRetypeCore (chunked UPDATE with
  legacy_type stamping), runPageToLinkCore (edge-shaped pages →
  link rows), runPageToAliasCore (concept-redirect → slug_aliases)
- rewriteLinksBatch for N-pair atomic FK rewrite
- Migration v104 slug_aliases table (forward-bootstrap probed on both
  engines for safe upgrade chain)
- New engine method resolveSlugWithAlias(slug, sourceOrSources) on
  both Postgres + PGLite with multi-source ambiguity warning
- inferTypeAndSubtypeFromPack overload + subtypes: + mapping_rules:
  + migration_from: schema-pack manifest extensions
- findPackSuccessors version-range walker (1.x / 1.0.x / exact match)
- expandTypeFilter for --type back-compat (D14): legacy aliases route
  through mapping_rules → canonical+subtype before the SQL filter fires
- 3 new onboard checks: pack_upgrade_available, type_proliferation,
  dangling_aliases (source-scoped per F12)
- unify-types Minion handler (PROTECTED, manual_only via render.ts
  allowlist per D17): retype-explicit → retype-catch-all →
  page-to-link → page-to-alias → final sync → active-pack flip
- alias_resolved 1.05x post-fusion search boost stage; KNOBS_HASH_VERSION
  bumped 5→6 (one-time cache miss on upgrade, self-healing in TTL)
- ELIGIBLE_TYPES for facts extraction extended with v2 canonicals
  (codex F-ELIGIBLE: blocker not v0.43 follow-up)

Tests: 79 new unit/integration cases + 3 E2E cases covering all 9
production clusters end-to-end. 124-case verification on the cache-key
+ build-llms fixes. KNOBS_HASH_VERSION assertions updated in 3 tests.

Plan: ~/.claude/plans/system-instruction-you-are-working-transient-elephant.md
(16 locked decisions D1-D17, 12 baseline fixes F7-F21 absorbed from
codex outside voice).

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

* fix: CI verify failures — system-of-record allow-comment + schema-unify manifest registration

Two CI failures on PR #1542:

1. check:system-of-record flagged page-to-link.ts:207 addLinksBatch as
   a direct write to a derived table. The call IS the reconcile surface
   for page_to_link mapping_rules — it converts edge-shaped pages into
   canonical link rows under the PROTECTED unify-types Minion handler,
   source-scoped, atomic per-rule. Added the canonical
   `// gbrain-allow-direct-insert: <reason>` comment on the same line.

2. check:resolver emitted 11 orphan_trigger warnings for `schema-unify`
   because the skill was added to skills/RESOLVER.md without a
   corresponding entry in skills/manifest.json. Added the registration
   under the existing skills[] array.

bun run verify: 28/28 checks pass locally.

* fix: CI test failures — schema-unify conformance + eligibility regression

Six test failures across shards 2 + 10 on PR #1542:

1. resolver.test.ts: round-trip parser requires frontmatter triggers to
   be quoted (`- "..."` or `- '...'`). schema-unify shipped with bare
   YAML strings; quoted the 10 triggers to round-trip correctly.

2. skills-conformance.test.ts (×3): schema-unify SKILL.md was missing
   the required Contract, Anti-Patterns, and Output Format sections
   that every conformant skill must declare. Added all three:
   - Contract: inputs / outputs / side effects / failure modes
   - Anti-Patterns: 5 DON'Ts including the autopilot trust boundary
   - Output Format: per-phase stderr lines + celebration summary +
     JSON envelope shape

3. facts-eligibility.test.ts (×2): the v0.41.22 ELIGIBLE_TYPES
   expansion added `concept` to the eligible list, but the existing
   test suite pins concept as rejected (it's `extractable: true` in
   the schema pack but the v0.41.11 contract documented this as
   "cosmetic on the backstop path because backstop uses hardcoded
   ELIGIBLE_TYPES"). Removed `concept` from the expansion; other v2
   canonicals (media, tweet, atom, analysis) stay. Comment updated
   to document the deliberate omission.

All 6 failing tests now pass locally (370/370 across the 3 affected
files). bun run verify: 28/28 checks green.

* fix: harden findPackSuccessors test against shard pollution

CI shard 8 reported 1 fail (1.00ms — too fast for any real loadActivePack
file I/O) on `finds gbrain-base-v2 as successor of gbrain-base@1.0.0`.
Local triple-run passes 9/9 in isolation.

Root cause: the existing afterEach reset clears the module-level pack
cache AFTER each test, but the FIRST test in the file inherits whatever
state sibling files in the same bun shard process left behind. With
24+ schema-pack tests in shard 8 (mutate, mutate-audit, best-effort,
registry-reload, manifest-v041_2, etc.) running before this file, the
first test can read a poisoned cache.

Fix: add `beforeEach(_resetPackCacheForTests)`. Two-sided reset
guarantees clean state regardless of file ordering within the shard.

bun run verify: 28/28 checks pass.

* fix: quarantine two flaky tests to serial runner

CI shard 1 + shard 8 each surfaced one intermittent failure:

shard 1: buildBrainTools > execute() on put_page with valid namespace
shard 8: findPackSuccessors > finds gbrain-base-v2 as successor

Both pass cleanly in isolation. Both are concurrency races against
shared in-shard state:

- brain-allowlist.test.ts shares a singleton PGLiteEngine across 18
  tests with a beforeEach DELETE FROM pages. With max-concurrency=4,
  two put_page tests can interleave their TRUNCATE + write phases,
  so the auto-link/extract sub-steps inside put_page race against
  the sibling test's DELETE.
- schema-pack-find-pack-successors.test.ts reads bundled YAML packs
  via loadActivePack. The module-level pack cache is shared across
  parallel tests in the same shard; the previous beforeEach reset
  helped but didn't fully isolate against concurrent file reads
  under CI load.

Fix per CLAUDE.md test-isolation lint rule R2 (concurrency-fragile
files belong in the .serial.test.ts quarantine): rename both files
to *.serial.test.ts. Serial runner picks them up at max-concurrency=1.
49/49 serial files pass locally. 28/28 verify checks pass.

* fix: quarantine embed-stale test to serial runner

CI shard 9 reported 6 failures, all from the embedStaleForSource describe
block, all ~120-150ms each — classic shared-engine concurrency race shape.
Passes 7/7 locally in isolation.

Root cause: embed-stale.test.ts shares a singleton PGLiteEngine across 7
tests with beforeEach resetPgliteState. Under bun's max-concurrency=4 in
the parallel shard, two tests can interleave their TRUNCATE + seedPage +
upsertChunks + embedStaleForSource flow, so one test's stale-chunk count
sees another test's mid-flight writes.

Same fix as brain-allowlist.serial.test.ts and
schema-pack-find-pack-successors.serial.test.ts: rename to *.serial.test.ts
so the serial runner picks it up at max-concurrency=1.

bun run verify: 28/28 checks pass. 7/7 embed-stale tests pass via serial.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 07:01:28 -07:00

205 lines
9.0 KiB
TypeScript

/**
* v0.35.0.0 — knobsHash reranker-field participation tests.
*
* Pins:
* - KNOBS_HASH_VERSION === 3 (bumped 1→2 v0.35.0.0 for reranker; 2→3 v0.35.6.0
* for floor_ratio — codex outside-voice T1 cross-floor cache contamination).
* - All 5 new reranker fields participate in the hash:
* reranker_enabled, reranker_model, reranker_top_n_in,
* reranker_top_n_out, reranker_timeout_ms.
* Each one flipping changes the hash → no two reranker configs share
* a cache row.
* - top_n_out=null vs unset shows up as 'none' in the hash (no NaN).
* - Append-only convention (CDX2-F13): the existing 9 fields hash
* identically under v=2 as they did under v=1 for the same input
* when the reranker section is held constant. Reordering them
* would silently rebuild the hash for every existing row.
* - Mid-deploy invariant (CDX2-F12): the v=1 prefix in the hash input
* differs from the v=2 prefix; a tokenmax v=1 process and a v=2
* process produce distinct row IDs for the same (source_id, query).
*/
import { describe, test, expect } from 'bun:test';
import {
knobsHash,
KNOBS_HASH_VERSION,
resolveSearchMode,
MODE_BUNDLES,
type ResolvedSearchKnobs,
} from '../../src/core/search/mode.ts';
/** Build a baseline resolved knob set with all reranker fields filled. */
function baseKnobs(): ResolvedSearchKnobs {
return {
...MODE_BUNDLES.balanced,
reranker_enabled: false,
reranker_model: 'zeroentropyai:zerank-2',
reranker_top_n_in: 30,
reranker_top_n_out: null,
reranker_timeout_ms: 5000,
resolved_mode: 'balanced',
mode_valid: true,
};
}
describe('KNOBS_HASH_VERSION + version invariants', () => {
test('version is 6 (1→2 reranker; 2→3 floor_ratio + cross-modal + column; 3→4 graph_signals + schema_pack; 4→5 contextual_retrieval; 5→6 v0.41.22 alias_resolved boost)', () => {
// v0.35.0.0: 1→2 to fold reranker fields. v0.35.6.0: 2→3 to fold
// floor_ratio. v0.36 wave: piggybacks on v=3 with 7 cross-modal knobs
// (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).
// v0.40.4 (salem) + v0.39 T21 (master): 3→4 to fold graph_signals AND
// schema_pack name + version (graph-on cache write cannot be served to
// graph-off; cross-pack contamination structurally impossible).
// v0.40.3.0 (D8): 4→5 to fold contextual_retrieval + kill switch,
// sequenced behind salem's v=4 graph-signals.
// v0.41.22.0 (type-unification): 5→6 to fold the alias_resolved
// post-fusion boost. Cache rows written before the boost stage
// cannot leak past the new stage.
expect(KNOBS_HASH_VERSION).toBe(6);
});
test('hash is 16 hex chars regardless of reranker config', () => {
const a = knobsHash(baseKnobs());
const b = knobsHash({ ...baseKnobs(), reranker_enabled: true });
expect(a).toMatch(/^[0-9a-f]{16}$/);
expect(b).toMatch(/^[0-9a-f]{16}$/);
});
});
describe('Each reranker field flips the hash (cache-row separation)', () => {
test('reranker_enabled false vs true → different hash', () => {
const off = knobsHash({ ...baseKnobs(), reranker_enabled: false });
const on = knobsHash({ ...baseKnobs(), reranker_enabled: true });
expect(off).not.toBe(on);
});
test('reranker_model differs → different hash', () => {
const z2 = knobsHash({ ...baseKnobs(), reranker_model: 'zeroentropyai:zerank-2' });
const z1 = knobsHash({ ...baseKnobs(), reranker_model: 'zeroentropyai:zerank-1' });
const z1s = knobsHash({ ...baseKnobs(), reranker_model: 'zeroentropyai:zerank-1-small' });
expect(new Set([z2, z1, z1s]).size).toBe(3);
});
test('reranker_top_n_in differs → different hash', () => {
const a = knobsHash({ ...baseKnobs(), reranker_top_n_in: 30 });
const b = knobsHash({ ...baseKnobs(), reranker_top_n_in: 50 });
expect(a).not.toBe(b);
});
test('reranker_top_n_out null vs 10 → different hash', () => {
const noTrunc = knobsHash({ ...baseKnobs(), reranker_top_n_out: null });
const trunc10 = knobsHash({ ...baseKnobs(), reranker_top_n_out: 10 });
expect(noTrunc).not.toBe(trunc10);
});
test('reranker_timeout_ms differs → different hash (CDX2-F14)', () => {
// CDX2-F14: a timeout change (5s → 100ms) changes search behavior
// (more fail-opens) so stale cache rows must invalidate. Without
// this field in parts[], the rows would silently match.
const t5 = knobsHash({ ...baseKnobs(), reranker_timeout_ms: 5000 });
const t1 = knobsHash({ ...baseKnobs(), reranker_timeout_ms: 1000 });
expect(t5).not.toBe(t1);
});
});
describe('mid-deploy invariant (CDX2-F12)', () => {
test('tokenmax-with-reranker vs tokenmax-without-reranker → distinct hashes', () => {
// tokenmax mode bundle has reranker on. An operator who flips it off
// via `gbrain config set search.reranker.enabled false` produces a
// different cache row, not a shared one.
const tokenmaxOn = knobsHash(resolveSearchMode({ mode: 'tokenmax' }));
const tokenmaxOff = knobsHash(resolveSearchMode({
mode: 'tokenmax',
overrides: { reranker_enabled: false },
}));
expect(tokenmaxOn).not.toBe(tokenmaxOff);
});
test('conservative vs balanced vs tokenmax → 3 distinct hashes', () => {
const c = knobsHash(resolveSearchMode({ mode: 'conservative' }));
const b = knobsHash(resolveSearchMode({ mode: 'balanced' }));
const t = knobsHash(resolveSearchMode({ mode: 'tokenmax' }));
expect(new Set([c, b, t]).size).toBe(3);
});
});
describe('determinism + stability', () => {
test('same input → same hash (re-call)', () => {
const k = baseKnobs();
expect(knobsHash(k)).toBe(knobsHash(k));
});
test('same mode bundle → same hash across resolveSearchMode calls', () => {
const a = knobsHash(resolveSearchMode({ mode: 'balanced' }));
const b = knobsHash(resolveSearchMode({ mode: 'balanced' }));
expect(a).toBe(b);
});
test('top_n_out=null renders as "none" in parts[] (no NaN)', () => {
// CDX2-F15 + F16 + F14 collide here. The parts[] line is
// `rro=${knobs.reranker_top_n_out ?? 'none'}` — null must produce a
// stable string token, never `NaN` or `null`.
const h1 = knobsHash({ ...baseKnobs(), reranker_top_n_out: null });
const h2 = knobsHash({ ...baseKnobs(), reranker_top_n_out: null });
expect(h1).toBe(h2);
expect(h1).toMatch(/^[0-9a-f]{16}$/);
});
});
describe('append-only convention (CDX2-F13)', () => {
test('parts[] order in source: reranker fields appear AFTER the existing 9', async () => {
const src = await Bun.file(
new URL('../../src/core/search/mode.ts', import.meta.url),
).text();
// Locate the parts[] declaration. The existing 9 fields end with
// `lim=${knobs.searchLimit}`. The 5 new fields must appear AFTER
// that line. Reordering would silently rebuild the hash for every
// existing v=2 cache row.
const limIdx = src.indexOf('lim=${knobs.searchLimit}');
const rrIdx = src.indexOf('rr=${knobs.reranker_enabled');
expect(limIdx).toBeGreaterThan(0);
expect(rrIdx).toBeGreaterThan(0);
expect(rrIdx).toBeGreaterThan(limIdx);
});
test('v=3 additions: col= and prov= appear AFTER the reranker block', async () => {
// v0.36 D8: cache-key contamination across embedding columns + providers.
// The two new tokens must sit at the bottom of parts[] so existing v=2
// hashes can only differ in those positions — keeping the append-only
// chain auditable for future v=4 readers.
const src = await Bun.file(
new URL('../../src/core/search/mode.ts', import.meta.url),
).text();
const rrtIdx = src.indexOf('rrt=${knobs.reranker_timeout_ms');
const colIdx = src.indexOf('col=${ctx?.embeddingColumn');
const provIdx = src.indexOf('prov=${ctx?.embeddingModel');
expect(rrtIdx).toBeGreaterThan(0);
expect(colIdx).toBeGreaterThan(rrtIdx);
expect(provIdx).toBeGreaterThan(colIdx);
});
test('v=3 fields participate: column flip changes the hash', () => {
const k = baseKnobs();
const defaultCol = knobsHash(k, { embeddingColumn: 'embedding', embeddingModel: 'openai:text-embedding-3-large' });
const voyageCol = knobsHash(k, { embeddingColumn: 'embedding_voyage', embeddingModel: 'voyage:voyage-3-large' });
expect(defaultCol).not.toBe(voyageCol);
});
test('v=3 fields participate: same column + different provider → different hash', () => {
const k = baseKnobs();
const a = knobsHash(k, { embeddingColumn: 'embedding', embeddingModel: 'openai:text-embedding-3-large' });
const b = knobsHash(k, { embeddingColumn: 'embedding', embeddingModel: 'openai:text-embedding-3-small' });
expect(a).not.toBe(b);
});
test('v=3 fields fall back to embedding/default when ctx undefined', () => {
// Backward-compat: callers that don't know the column (e.g. telemetry
// helpers) should still produce a stable hash matching the default
// 'embedding' + 'default' provider pair.
const k = baseKnobs();
const bare = knobsHash(k);
const explicit = knobsHash(k, { embeddingColumn: 'embedding', embeddingModel: 'default' });
expect(bare).toBe(explicit);
});
});