brainy/tests/unit/neural/signals/ExactMatchSignal.test.ts
David Snelling 9e307e457f fix: recalibrate find({ limit }) cap + two-tier enforcement + caller location
Brainy 7.30.0 introduced a memory-derived synchronous cap on `find({ limit })`
to prevent OOM. The cap was sound in intent but ~4x too conservative in
calibration: assumed 100 KB per result while typical entity footprint is 7-10 KB
(384-dim float32 vector ≈ 1.5 KB + standard fields + metadata). On a 900 MB
free-memory box the cap derived to 9000 — breaking common safety-cap patterns
like `find({ type, where, limit: 10_000 })` that typically return 10-500
entities. Surfaced as a runtime regression with cascading 500s degrading
production dashboards.

Three concurrent fixes:

A. RECALIBRATE THE FORMULA
- src/utils/paramValidation.ts:175,196,212 — the three memory-derived priorities
  (reservedQueryMemory / containerMemory / freeMemory) all divided by
  100 * 1024 * 1024 (100 KB per result, ~10-15x over conservative). Replaced
  with a new MAX_LIMIT_KB_PER_RESULT = 25 constant that matches observed
  entity size.
- Result: 4 GB container cap goes 10_000 → 40_000; 2 GB cap goes 5_000 →
  20_000; 900 MB free-memory cap goes 9_000 → ~36_000. 100k hard ceiling
  unchanged. `maxQueryLimit` / `reservedQueryMemory` constructor overrides
  unchanged in behavior.

B. TWO-TIER ENFORCEMENT (warn-then-throw)
- Below cap (limit <= maxLimit): silent pass, unchanged.
- Soft tier (maxLimit < limit <= 2 * maxLimit): NEW — one-time warning per
  call site (dedup keyed on caller stack frame + limit value), query
  proceeds. Pre-7.30.2 code that relied on the cap silently allowing typical
  safety-cap limits keeps working; the warning teaches the recipe so consumers
  can fix it intentionally.
- Hard tier (limit > 2 * maxLimit): throw with the same teaching message
  format. Real OOM territory; the cap stops being a recommendation and becomes
  a guardrail.
- The 2x soft margin absorbs typical safety-cap patterns (limit: 10_000
  against a 9 K-cap box) without disabling OOM protection. Real OOM territory
  on a JS in-memory brain is hundreds of thousands of results, not 10x the
  safety cap.

C. IMPROVED ERROR / WARNING MESSAGE
- Same shape as the 7.30.1 enforcement-error messages: state the problem,
  name the three escape valves (maxQueryLimit / reservedQueryMemory /
  pagination), include caller location, link to docs.
- Extracted findCallerLocation() helper from brainy.ts to a new
  src/utils/callerLocation.ts so both the subtype enforcement (7.30.1) and
  the limit enforcement (7.30.2) share one implementation without circular
  imports.

DOCS
- New docs/guides/find-limits.md (public: true) — full reference: why the cap
  exists, the four memory sources the auto-config considers, the three escape
  valves with when-to-use-which guidance, and an explicit "pagination is the
  future-proof pattern" callout (8.0 may tighten the cap further; pagination
  keeps working unchanged).
- docs/api/README.md find() entry gets a one-paragraph `limit` tip + pointer
  to the new guide.
- RELEASES.md v7.30.2 entry.

TESTS
- New tests/integration/find-limits.test.ts (9 tests): below-cap silent pass;
  soft-tier warns once per call site (dedup verified by exercising same vs.
  different source lines via wrapper closures); soft-tier message format
  (names all three escape valves + docs link); soft-tier message includes
  caller location; hard-tier throws; hard-tier message format same as
  soft-tier; consumer maxQueryLimit override raises the cap and shifts both
  tiers accordingly; pre-7.30.2 regression scenario explicitly covered.
- tests/unit/utils/memoryLimits.test.ts — 4 tests updated for the recalibrated
  cap values (hardcoded expected numbers bumped 4x to match new 25 KB/result
  assumption).
- tests/unit/utils/paramValidation.test.ts — auto-limit test extended to cover
  the three-tier semantics (below-cap pass / soft-tier silent / hard-tier
  throw).
- Existing suites unchanged: subtype-and-facets 26/26, verb-subtype-and-
  enforcement 30/30, strict-mode-self-test 13/13. Unit 1468/1468.

CORTEX COMPATIBILITY
- Zero Cortex changes required. Every change is JS-side: formula recalibration
  runs in ValidationConfig.constructor(), two-tier enforcement runs in
  validateFindParams(), both fire before any storage / index / Cortex call.
- The new guide notes that Brainy 8.0's Datomic-style Db.find() may tighten
  per-call limits to keep snapshot semantics cheap; pagination remains the
  pattern that's guaranteed to keep working.

REPO-WIDE CLEANUP
Brainy is the only Soulcraft project that is open source. This commit also
scrubs closed-source product names and product-specific class/field references
from every tracked file in the repo (src/, docs/, tests/, RELEASES.md,
CHANGELOG.md). Consumer-reported bugs, regression scenarios, and release
notes now refer to "a consumer", "a downstream application", "a production
deployment", or "an internal report" — never to the named product. Two
product-named test files renamed to neutral diagnostic names. CLAUDE.md gains
a project-level guard rule documenting the policy and an example list of the
identifiers that may not appear in tracked code.

Verification
- npx tsc --noEmit: clean
- npm test: 1468 / 1468 unit
- All four integration subtype + verb + strict + find-limits suites: 78/78
- npm run build: clean
- Closed-source product reference audit: clean
2026-06-08 12:49:43 -07:00

647 lines
19 KiB
TypeScript

import { describe, it, expect, beforeEach } from 'vitest'
import { ExactMatchSignal } from '../../../../src/neural/signals/ExactMatchSignal.js'
import { NounType } from '../../../../src/types/graphTypes.js'
import type { Brainy } from '../../../../src/brainy.js'
// Mock minimal Brainy instance for testing
function createMockBrain(): Brainy {
return {
embed: async (text: string) => {
// Return simple deterministic vector
const hash = text.split('').reduce((acc, c) => acc + c.charCodeAt(0), 0)
return Array(384).fill(0).map((_, i) => (hash + i) % 100 / 100)
}
} as any
}
describe('ExactMatchSignal', () => {
let brain: Brainy
let signal: ExactMatchSignal
beforeEach(() => {
brain = createMockBrain()
signal = new ExactMatchSignal(brain)
})
describe('initialization', () => {
it('should initialize with default options', () => {
const defaultSignal = new ExactMatchSignal(brain)
const stats = defaultSignal.getStats()
expect(stats).toBeDefined()
expect(stats.calls).toBe(0)
expect(stats.termMatches).toBe(0)
expect(stats.cacheHitRate).toBe(0)
})
it('should initialize with custom options', () => {
const customSignal = new ExactMatchSignal(brain, {
minConfidence: 0.75,
cacheSize: 10000
})
expect(customSignal).toBeDefined()
const stats = customSignal.getStats()
expect(stats.cacheSize).toBe(0)
})
it('should start with empty index', () => {
const stats = signal.getStats()
expect(stats.indexSize).toBe(0)
})
})
describe('buildIndex', () => {
it('should build index from terms', () => {
signal.buildIndex([
{ text: 'Paris', type: NounType.Location },
{ text: 'London', type: NounType.Location },
{ text: 'Microsoft', type: NounType.Organization }
])
const stats = signal.getStats()
// Index includes both full terms and tokens
expect(stats.indexSize).toBeGreaterThanOrEqual(3)
})
it('should handle duplicate terms (last wins)', () => {
signal.buildIndex([
{ text: 'Java', type: NounType.Technology },
{ text: 'Java', type: NounType.Location } // Java island
])
const stats = signal.getStats()
expect(stats.indexSize).toBeGreaterThanOrEqual(1)
})
it('should normalize terms when building index', () => {
signal.buildIndex([
{ text: 'Paris', type: NounType.Location },
{ text: 'PARIS', type: NounType.Location },
{ text: 'paris', type: NounType.Location }
])
const stats = signal.getStats()
// All normalize to same key, but may have tokens
expect(stats.indexSize).toBeGreaterThanOrEqual(1)
})
it('should clear previous index on rebuild', () => {
signal.buildIndex([
{ text: 'Term1', type: NounType.Concept }
])
const size1 = signal.getStats().indexSize
signal.buildIndex([
{ text: 'Term2', type: NounType.Concept },
{ text: 'Term3', type: NounType.Concept }
])
const size2 = signal.getStats().indexSize
expect(size2).toBeGreaterThanOrEqual(2)
})
it('should handle empty term list', () => {
signal.buildIndex([])
expect(signal.getStats().indexSize).toBe(0)
})
it('should handle large index efficiently', () => {
const terms = Array.from({ length: 10000 }, (_, i) => ({
text: `Term${i}`,
type: NounType.Concept
}))
const start = Date.now()
signal.buildIndex(terms)
const elapsed = Date.now() - start
expect(signal.getStats().indexSize).toBeGreaterThanOrEqual(10000)
expect(elapsed).toBeLessThan(200) // Should be fast (< 200ms)
})
it('should index tokens from multi-word terms', () => {
signal.buildIndex([
{ text: 'Microsoft Corporation', type: NounType.Organization }
])
// Should index both full term and individual tokens
const stats = signal.getStats()
expect(stats.indexSize).toBeGreaterThan(1)
})
})
describe('exact matching', () => {
beforeEach(() => {
signal.buildIndex([
{ text: 'Paris', type: NounType.Location },
{ text: 'Microsoft Corporation', type: NounType.Organization },
{ text: 'JavaScript', type: NounType.Technology },
{ text: 'Albert Einstein', type: NounType.Person }
])
})
it('should match exact term', async () => {
const result = await signal.classify('Paris')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Location)
expect(result?.source).toBe('exact-term')
expect(result?.confidence).toBeGreaterThanOrEqual(0.85)
expect(result?.evidence).toContain('Exact match')
})
it('should match case-insensitive', async () => {
const result = await signal.classify('paris')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Location)
})
it('should match with different casing', async () => {
const result = await signal.classify('PARIS')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Location)
})
it('should match multi-word terms', async () => {
const result = await signal.classify('Microsoft Corporation')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Organization)
})
it('should return null for non-matching term', async () => {
const result = await signal.classify('NonExistentTerm')
expect(result).toBeNull()
})
it('should track statistics on exact matches', async () => {
await signal.classify('Paris')
await signal.classify('Microsoft Corporation')
await signal.classify('Unknown')
const stats = signal.getStats()
expect(stats.calls).toBe(3)
expect(stats.termMatches).toBe(2)
expect(stats.termMatchRate).toBeCloseTo(2/3, 2)
})
it('should handle terms with leading/trailing whitespace', async () => {
const result = await signal.classify(' Paris ')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Location)
})
})
describe('metadata hints', () => {
it('should detect person from column name', async () => {
const result = await signal.classify('John Doe', {
columnName: 'author'
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Person)
expect(result?.source).toBe('exact-metadata')
})
it('should detect location from column name', async () => {
const result = await signal.classify('Unknown City', {
columnName: 'location'
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Location)
})
it('should detect organization from column name', async () => {
const result = await signal.classify('Unknown Corp', {
columnName: 'organization'
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Organization)
})
it('should use explicit type metadata', async () => {
const result = await signal.classify('Unknown Entity', {
metadata: { type: 'person' }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Person)
expect(result?.source).toBe('exact-metadata')
})
})
describe('format-specific patterns - Excel', () => {
it('should detect sheet name patterns - People', async () => {
// Use lower minConfidence to allow sheet hints through
const lenientSignal = new ExactMatchSignal(brain, {
minConfidence: 0.70
})
const result = await lenientSignal.classify('Frodo Baggins', {
fileFormat: 'excel',
metadata: { sheetName: 'Characters' }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Person)
expect(result?.source).toBe('exact-format')
})
it('should detect sheet name patterns - Locations', async () => {
const lenientSignal = new ExactMatchSignal(brain, {
minConfidence: 0.70
})
const result = await lenientSignal.classify('Rivendell', {
fileFormat: 'excel',
metadata: { sheetName: 'Locations' }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Location)
})
it('should detect sheet name patterns - Glossary', async () => {
const lenientSignal = new ExactMatchSignal(brain, {
minConfidence: 0.70
})
const result = await lenientSignal.classify('Aethermancy', {
fileFormat: 'excel',
metadata: { sheetName: 'Glossary' }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Concept)
})
})
describe('format-specific patterns - PDF', () => {
it('should detect TOC entries', async () => {
const result = await signal.classify('Chapter 1: Introduction', {
fileFormat: 'pdf',
metadata: { isTOCEntry: true }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Concept)
expect(result?.evidence).toContain('table of contents')
})
})
describe('format-specific patterns - YAML', () => {
it('should detect user/author keys as Person', async () => {
const result = await signal.classify('john_doe', {
fileFormat: 'yaml',
metadata: { yamlKey: 'author' }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Person)
})
it('should detect organization keys', async () => {
const result = await signal.classify('Acme Inc', {
fileFormat: 'yaml',
metadata: { yamlKey: 'organization' }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Organization)
})
})
describe('format-specific patterns - DOCX', () => {
it('should detect heading levels as concept hierarchy', async () => {
const result = await signal.classify('Introduction', {
fileFormat: 'docx',
metadata: {
headingLevel: 1
}
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Concept)
})
})
describe('caching', () => {
beforeEach(() => {
signal.buildIndex([
{ text: 'Paris', type: NounType.Location }
])
})
it('should cache successful lookups', async () => {
const result1 = await signal.classify('Paris')
const result2 = await signal.classify('Paris')
expect(result1).toEqual(result2)
const stats = signal.getStats()
expect(stats.cacheHits).toBe(1) // Second call is cached
expect(stats.cacheHitRate).toBe(0.5) // 1 hit out of 2 calls
})
it('should cache null results', async () => {
const result1 = await signal.classify('Unknown')
const result2 = await signal.classify('Unknown')
expect(result1).toBeNull()
expect(result2).toBeNull()
const stats = signal.getStats()
expect(stats.cacheHits).toBe(1)
})
it('should respect cache size limit', async () => {
const smallCacheSignal = new ExactMatchSignal(brain, {
cacheSize: 2
})
smallCacheSignal.buildIndex([
{ text: 'Term1', type: NounType.Concept },
{ text: 'Term2', type: NounType.Concept },
{ text: 'Term3', type: NounType.Concept }
])
await smallCacheSignal.classify('Term1')
await smallCacheSignal.classify('Term2')
await smallCacheSignal.classify('Term3') // Evicts Term1
const stats = smallCacheSignal.getStats()
expect(stats.cacheSize).toBeLessThanOrEqual(2)
})
it('should clear cache on demand', async () => {
await signal.classify('Paris')
expect(signal.getStats().cacheSize).toBe(1)
signal.clearCache()
expect(signal.getStats().cacheSize).toBe(0)
})
})
describe('statistics', () => {
it('should track all statistics', async () => {
signal.buildIndex([
{ text: 'Paris', type: NounType.Location }
])
await signal.classify('Paris') // Term hit
await signal.classify('Paris') // Cache hit
await signal.classify('Unknown') // Miss
const stats = signal.getStats()
expect(stats.calls).toBe(3)
expect(stats.termMatches).toBe(1)
expect(stats.cacheHits).toBe(1)
expect(stats.metadataMatches).toBe(0)
expect(stats.formatMatches).toBe(0)
expect(stats.cacheSize).toBe(2)
expect(stats.indexSize).toBeGreaterThanOrEqual(1)
expect(stats.termMatchRate).toBeCloseTo(1/3, 2)
expect(stats.cacheHitRate).toBeCloseTo(1/3, 2)
})
it('should track metadata match usage', async () => {
await signal.classify('Unknown', {
columnName: 'author'
})
const stats = signal.getStats()
expect(stats.metadataMatches).toBe(1)
})
it('should track format match usage', async () => {
const lenientSignal = new ExactMatchSignal(brain, {
minConfidence: 0.70
})
await lenientSignal.classify('Test', {
fileFormat: 'excel',
metadata: { sheetName: 'Locations' }
})
const stats = lenientSignal.getStats()
expect(stats.formatMatches).toBe(1)
})
it('should reset statistics', async () => {
signal.buildIndex([{ text: 'Test', type: NounType.Concept }])
await signal.classify('Test')
signal.resetStats()
const stats = signal.getStats()
expect(stats.calls).toBe(0)
expect(stats.termMatches).toBe(0)
expect(stats.cacheHits).toBe(0)
expect(stats.indexSize).toBeGreaterThanOrEqual(1) // Index not cleared
})
})
describe('edge cases', () => {
it('should handle empty string', async () => {
signal.buildIndex([{ text: 'Test', type: NounType.Concept }])
const result = await signal.classify('')
expect(result).toBeNull()
})
it('should handle whitespace-only string', async () => {
const result = await signal.classify(' ')
expect(result).toBeNull()
})
it('should handle very long strings', async () => {
const longString = 'A'.repeat(10000)
const result = await signal.classify(longString)
expect(result).toBeNull()
})
it('should handle special characters', async () => {
signal.buildIndex([
{ text: 'C++', type: NounType.Technology }
])
const result = await signal.classify('C++')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Technology)
})
it('should handle Unicode characters', async () => {
signal.buildIndex([
{ text: 'Café', type: NounType.Location }
])
const result = await signal.classify('Café')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Location)
})
it('should handle numbers in terms', async () => {
signal.buildIndex([
{ text: 'Windows 11', type: NounType.Technology }
])
const result = await signal.classify('Windows 11')
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Technology)
})
})
describe('real-world scenarios', () => {
it('should handle glossary import', async () => {
// Simulate glossary with 567 terms
const terms = [
{ text: 'Eldoria', type: NounType.Location },
{ text: 'Shadowfen', type: NounType.Location },
{ text: 'Aethermancer', type: NounType.Concept },
{ text: 'Crystal of Eternity', type: NounType.Object }
]
signal.buildIndex(terms)
// Test exact matches
const result1 = await signal.classify('Eldoria')
expect(result1?.type).toBe(NounType.Location)
expect(result1?.confidence).toBeGreaterThanOrEqual(0.85)
// Test with "Related Terms" column hint
const result2 = await signal.classify('Aethermancer', {
fileFormat: 'excel',
columnName: 'Related Terms'
})
expect(result2?.type).toBe(NounType.Concept)
})
it('should handle large enterprise glossary', async () => {
const terms = Array.from({ length: 5000 }, (_, i) => ({
text: `Term${i}`,
type: i % 2 === 0 ? NounType.Concept : NounType.Object
}))
signal.buildIndex(terms)
const result = await signal.classify('Term42')
expect(result?.type).toBe(NounType.Concept) // 42 % 2 === 0 is true
expect(result?.confidence).toBeGreaterThanOrEqual(0.85)
})
it('should handle PDF technical documentation', async () => {
signal.buildIndex([
{ text: 'REST API', type: NounType.Technology },
{ text: 'Authentication', type: NounType.Concept }
])
const result = await signal.classify('Chapter 3: REST API', {
fileFormat: 'pdf',
metadata: { isTOCEntry: true }
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Concept) // TOC entries are concepts
})
it('should handle YAML configuration file', async () => {
const result = await signal.classify('admin_user', {
fileFormat: 'yaml',
metadata: {
yamlKey: 'author', // Changed from 'owner' to 'author'
context: 'project configuration'
}
})
expect(result).toBeDefined()
expect(result?.type).toBe(NounType.Person)
})
it('should handle CSV with mixed content', async () => {
signal.buildIndex([
{ text: 'John Doe', type: NounType.Person },
{ text: 'Acme Corp', type: NounType.Organization }
])
const result1 = await signal.classify('John Doe', {
fileFormat: 'csv',
columnName: 'author'
})
const result2 = await signal.classify('Acme Corp', {
fileFormat: 'csv',
columnName: 'company'
})
expect(result1?.type).toBe(NounType.Person)
expect(result2?.type).toBe(NounType.Organization)
})
})
describe('performance', () => {
it('should handle 10K lookups in reasonable time', async () => {
const terms = Array.from({ length: 1000 }, (_, i) => ({
text: `Term${i}`,
type: NounType.Concept
}))
signal.buildIndex(terms)
const start = Date.now()
for (let i = 0; i < 10000; i++) {
await signal.classify(`Term${i % 1000}`)
}
const elapsed = Date.now() - start
// Log for informational purposes; no hard assertion since timing
// is machine-dependent and causes flaky failures under parallel load
console.log(` 10K ExactMatch lookups: ${elapsed}ms`)
})
it('should have O(1) lookup time', async () => {
// Test with increasing index sizes
const sizes = [100, 1000, 10000]
const times: number[] = []
for (const size of sizes) {
const terms = Array.from({ length: size }, (_, i) => ({
text: `Term${i}`,
type: NounType.Concept
}))
const testSignal = new ExactMatchSignal(brain)
testSignal.buildIndex(terms)
const start = Date.now()
for (let i = 0; i < 100; i++) {
await testSignal.classify('Term50') // Middle term
}
const elapsed = Date.now() - start
times.push(elapsed)
}
// Time should not scale with index size (O(1))
// Both times should be very fast (< 50ms) or similar
expect(times[2]).toBeLessThan(50)
expect(times[0]).toBeLessThan(50)
})
})
})