open-brainy/tests/unit/brainy/relate-duplicate-optimization.test.ts
David Snelling 780fb6444b feat(8.0)!: flip requireSubtype default to true (BRAINY-8.0-SUBTYPE-CONTRACT § C-1)
Brainy 8.0 makes subtype required by default on every public write path
(`add`, `addMany`, `update`, `relate`, `relateMany`, `updateRelation`,
import). Per the locked C-1 contract, every entity and relation gets a
non-empty subtype string by the time the storage layer sees it.

OPT-OUT REMAINS FULLY SUPPORTED

The runtime flag is still consumer-controlled. Three opt-out paths
cover migration / legacy fixtures / typed escape:

- `new Brainy({ requireSubtype: false })` — last-resort: turn off the
  contract entirely. Recommended only for migration windows or test
  fixtures that legitimately can't supply a subtype.
- `new Brainy({ requireSubtype: { except: [NounType.Thing, ...] } })` —
  per-type allowlist: strict everywhere except the listed types.
- `brain.requireSubtype(type, options)` — per-type registration with
  optional vocabulary. Composes with the brain-wide flag.

Default is now `true`. Opt-out is explicit and documented; nothing
silently degrades.

TEST SWEEP

Bulk-applied `requireSubtype: false` to every `new Brainy({...})` call
site across 120 test files. Three sed patterns covered the shapes:
  - `new Brainy({` → `new Brainy({ requireSubtype: false,`
  - `new Brainy<T>({` → `new Brainy<T>({ requireSubtype: false,`
  - `new Brainy()` → `new Brainy({ requireSubtype: false })`

tests/helpers/test-factory.ts → createTestConfig() defaults
`requireSubtype: false` so test files using the helper inherit the
opt-out without per-site edits.

The test sites that DO exercise subtype semantics (the
subtype-and-facets suite, the strict-mode-self-test suite, the verb-
subtype-and-enforcement suite, etc.) already pass real subtypes — they
were the 7.30.x acceptance tests for this contract. Those tests
continue to pass unchanged.

CHANGES

src/brainy.ts
- normalizeConfig() — `requireSubtype` default `false` → `true`.
  Comment refreshed to document the three opt-out paths.

tests/* (120 files)
- Bulk-edited brain construction sites. No functional test changes; the
  opt-out preserves the test author's original intent.

tests/helpers/test-factory.ts
- createTestConfig() base config gains `requireSubtype: false`.

NO-OP for consumers who were already passing subtype on every write.

For consumers who weren't, the upgrade path is one of the three opt-out
forms above. Migration recipe documented in 8.0 release notes (next
commit).

VERIFICATION

- npx tsc --noEmit: clean
- npm test: 1408 / 1409 (same pre-existing race-condition outstanding;
  no other regressions from the flip)
2026-06-09 14:58:25 -07:00

220 lines
6.2 KiB
TypeScript

/**
* Duplicate Relationship Check Optimization Tests
*
* Tests for v5.8.0 optimization that uses GraphAdjacencyIndex
* for O(log n) duplicate detection instead of O(n) storage scan.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { Brainy } from '../../../src/brainy.js'
import { NounType, VerbType } from '../../../src/types/graphTypes.js'
describe('Duplicate Check Optimization', () => {
let brain: Brainy
beforeEach(async () => {
brain = new Brainy({ requireSubtype: false })
await brain.init()
})
afterEach(async () => {
// Cleanup is automatic with memory storage
})
it('should detect duplicate relationships using GraphAdjacencyIndex', async () => {
// Create two entities
const personId = await brain.add({
data: { name: 'Alice' },
type: NounType.Person
})
const orgId = await brain.add({
data: { name: 'Acme Corp' },
type: NounType.Organization
})
// Create first relationship
const relationId1 = await brain.relate({
from: personId,
to: orgId,
type: VerbType.ParticipatesIn
})
// Attempt to create duplicate relationship
const relationId2 = await brain.relate({
from: personId,
to: orgId,
type: VerbType.ParticipatesIn
})
// Should return the same ID (duplicate detected)
expect(relationId2).toBe(relationId1)
// Verify only one relationship exists
const relations = await brain.getRelations({ from: personId })
expect(relations).toHaveLength(1)
expect(relations[0].id).toBe(relationId1)
})
it('should allow different relationship types between same entities', async () => {
const personId = await brain.add({
data: { name: 'Bob' },
type: NounType.Person
})
const projectId = await brain.add({
data: { name: 'Project X' },
type: NounType.Thing
})
// Create first relationship
const relationId1 = await brain.relate({
from: personId,
to: projectId,
type: VerbType.Creates
})
// Create second relationship with different type (not a duplicate)
const relationId2 = await brain.relate({
from: personId,
to: projectId,
type: VerbType.Modifies
})
// Should be different IDs (different verb types)
expect(relationId2).not.toBe(relationId1)
// Verify both relationships exist
const relations = await brain.getRelations({ from: personId })
expect(relations).toHaveLength(2)
// Both relations should exist with different IDs
const relationIds = relations.map(r => r.id)
expect(relationIds).toContain(relationId1)
expect(relationIds).toContain(relationId2)
})
it('should handle duplicate check with many relationships (performance)', async () => {
// Create source entity
const sourceId = await brain.add({
data: { name: 'Hub Entity' },
type: NounType.Thing
})
// Create 50 target entities and relationships
const targetIds: string[] = []
for (let i = 0; i < 50; i++) {
const targetId = await brain.add({
data: { name: `Target ${i}` },
type: NounType.Thing
})
targetIds.push(targetId)
await brain.relate({
from: sourceId,
to: targetId,
type: VerbType.RelatesTo
})
}
// Now attempt to create duplicate with first target (should be fast with GraphIndex)
const startTime = performance.now()
const duplicateId = await brain.relate({
from: sourceId,
to: targetIds[0],
type: VerbType.RelatesTo
})
const elapsed = performance.now() - startTime
// Should be fast with O(log n) GraphIndex lookup (< 10ms even with 50 relationships)
expect(elapsed).toBeLessThan(10)
// Verify duplicate was detected
const relations = await brain.getRelations({ from: sourceId })
expect(relations).toHaveLength(50) // No duplicate created
})
it('should use cached verb data for duplicate check', async () => {
const entityA = await brain.add({
data: { name: 'Entity A' },
type: NounType.Thing
})
const entityB = await brain.add({
data: { name: 'Entity B' },
type: NounType.Thing
})
// Create relationship
const relationId1 = await brain.relate({
from: entityA,
to: entityB,
type: VerbType.RelatesTo
})
// Access GraphIndex to ensure verb is cached
const verbIds = await (brain as any).graphIndex.getVerbIdsBySource(entityA)
expect(verbIds).toContain(relationId1)
// Attempt duplicate (should use cached verb)
const startTime = performance.now()
const relationId2 = await brain.relate({
from: entityA,
to: entityB,
type: VerbType.RelatesTo
})
const elapsed = performance.now() - startTime
// Should be very fast with cached verb (< 5ms)
expect(elapsed).toBeLessThan(5)
expect(relationId2).toBe(relationId1)
})
it('should handle duplicate check across multiple verb types efficiently', async () => {
const person = await brain.add({
data: { name: 'Charlie' },
type: NounType.Person
})
const org = await brain.add({
data: { name: 'BigCorp' },
type: NounType.Organization
})
// Create different relationship types
const rel1 = await brain.relate({
from: person,
to: org,
type: VerbType.Affects
})
const rel2 = await brain.relate({
from: person,
to: org,
type: VerbType.Owns
})
// Verify both relationships exist
let relations = await brain.getRelations({ from: person })
expect(relations).toHaveLength(2)
const relationIds = relations.map(r => r.id)
expect(relationIds).toContain(rel1)
expect(relationIds).toContain(rel2)
// Attempt duplicate of first relationship type
const startTime = performance.now()
const duplicate = await brain.relate({
from: person,
to: org,
type: VerbType.Affects
})
const elapsed = performance.now() - startTime
// Should detect duplicate efficiently (< 20ms)
expect(elapsed).toBeLessThan(20)
expect(duplicate).toBe(rel1)
// Verify still same number of relationships (no duplicate added)
const finalRelations = await brain.getRelations({ from: person })
expect(finalRelations.length).toBe(relations.length)
})
})