feat(contract): declare contract 1, serve three operators, refuse four by name
Open Brainy's side of the API contract the accelerated engine published.
DECLARED: package.json carries "brainyContract": 1 and the engine states its
own via contractVersion() / BRAINY_CONTRACT_VERSION — two engines compare an
integer instead of probing prototypes, and a tool reads the package field
without importing the engine. Pinned so the two can never drift apart.
SERVED: hasAll, noneOf and excludes now work on the index path. The defect
underneath was worse than the reported divergence — the metadata index's
operator switch had NO DEFAULT CASE, so any operator without a case left the
field's match set at its initial [] and find() returned an empty page.
Documented, validator-accepted, matcher-implemented operators answering
silently wrong. hasAll intersects each element's posting set (an empty operand
is vacuously true of every row that has the field), noneOf complements their
union, excludes complements contains.
REFUSED BY NAME: startsWith, endsWith, matches and length raise
INVALID_QUERY naming the operator, the field and the reason. An equality/range
posting index cannot evaluate a substring, a pattern or an array length without
reading every row — which is the cost this path exists to avoid — so it refuses
rather than answering an empty page. Both engines now agree on all 25 tokens
and contract 1 has no remaining operator divergence. This is a visible change
for a consumer calling those four through find({ where }): an empty page
becomes a typed refusal.
EMITTED: scripts/emit-contract-manifest.mjs generates docs/api-contract.json
from the BUILT surface — prototype doors, exported error classes, the operator
sets read out of their single definitions, the field-addressing vocabulary, the
health verdicts. Nothing hand-maintained, so a diff between two manifests is a
diff between two engines. `--check` fails on a stale manifest, which makes the
announce-every-addition duty mechanical rather than remembered.
RATIFIED in docs/contract-1-ratification.md: the 41-of-57 required split with
the promise spelled out (a refusal is part of a door; deprecation is not
removal), the serving-withholding list confirmed exhaustive and identical, the
minor/major rule adopted with the announcement duty, the 30 storage seam
methods committed as supported surface until Stage 2, and a finding filed
against the spec — is / isNot / greaterEqual / lessEqual are listed there as
served aliases and have never existed in this engine, which throws
INVALID_QUERY on all four.
This commit is contained in:
parent
50676c02f4
commit
48802ba385
9 changed files with 1943 additions and 3 deletions
151
tests/integration/filter-operator-conformance.test.ts
Normal file
151
tests/integration/filter-operator-conformance.test.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
/**
|
||||
* @module tests/integration/filter-operator-conformance
|
||||
* @description THE OPERATOR SET, AND WHAT EACH TOKEN DOES ON THE INDEX PATH.
|
||||
*
|
||||
* The contract-1 manifest splits this engine's `where` operators three ways —
|
||||
* served, served-beyond-baseline, refused-by-name — and two engines must agree
|
||||
* token for token. This lane is the machine-checkable side of that agreement:
|
||||
* it asserts the EXACT accepted set (so a manifest can be diffed against a run
|
||||
* rather than against prose), and it pins each of the three classes.
|
||||
*
|
||||
* The defect it closes: the metadata index's operator switch had no default
|
||||
* case, so an operator it does not implement — `hasAll`, `noneOf`, `excludes`,
|
||||
* `startsWith`, `endsWith`, `matches`, `length` — left the field's match set at
|
||||
* its initial `[]` and `find()` returned an empty page. A documented operator,
|
||||
* implemented in the in-memory matcher, answering silently wrong. Three of the
|
||||
* seven are now SERVED on the index path; the other four are REFUSED BY NAME,
|
||||
* because an equality/range posting index cannot evaluate a substring, a
|
||||
* pattern or an array length without reading every row.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { mkdtempSync, rmSync, readFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { Brainy } from '../../src/brainy.js'
|
||||
import { NounType } from '../../src/types/graphTypes.js'
|
||||
import { contractVersion, BRAINY_CONTRACT_VERSION } from '../../src/utils/version.js'
|
||||
|
||||
/** The accepted `where` value-operator tokens, as a sorted list. */
|
||||
const ACCEPTED_OPERATORS = [
|
||||
'between', 'contains', 'endsWith', 'eq', 'equals', 'excludes', 'exists',
|
||||
'greaterThan', 'greaterThanOrEqual', 'gt', 'gte', 'hasAll', 'in', 'length',
|
||||
'lessThan', 'lessThanOrEqual', 'lt', 'lte', 'matches', 'missing', 'ne',
|
||||
'noneOf', 'notEquals', 'oneOf', 'startsWith'
|
||||
] as const
|
||||
|
||||
/** Served on the index path with exact posting-set semantics. */
|
||||
const SERVED_ON_INDEX = [
|
||||
'between', 'contains', 'eq', 'equals', 'exists', 'greaterThan',
|
||||
'greaterThanOrEqual', 'gt', 'gte', 'in', 'lessThan', 'lessThanOrEqual',
|
||||
'lt', 'lte', 'missing', 'ne', 'notEquals', 'oneOf',
|
||||
'excludes', 'hasAll', 'noneOf'
|
||||
] as const
|
||||
|
||||
/** Accepted by name, refused by the index path — never answered empty. */
|
||||
const REFUSED_BY_INDEX = ['endsWith', 'length', 'matches', 'startsWith'] as const
|
||||
|
||||
describe('filter operator conformance', () => {
|
||||
const dirs: string[] = []
|
||||
const brains: Brainy[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const b of brains.splice(0)) {
|
||||
try { await b.close() } catch { /* already closed */ }
|
||||
}
|
||||
for (const d of dirs.splice(0)) {
|
||||
try { rmSync(d, { recursive: true, force: true }) } catch { /* ignore */ }
|
||||
}
|
||||
})
|
||||
|
||||
async function seeded(): Promise<Brainy> {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'brainy-operators-'))
|
||||
dirs.push(dir)
|
||||
const brain = new Brainy({ requireSubtype: false, storage: { type: 'filesystem', path: dir } })
|
||||
brains.push(brain)
|
||||
await brain.init()
|
||||
await brain.add({
|
||||
data: 'a document about ferrets',
|
||||
type: NounType.Document,
|
||||
metadata: { tags: ['ferret', 'small', 'furry'], team: 'alpha' }
|
||||
})
|
||||
await brain.add({
|
||||
data: 'a document about whales',
|
||||
type: NounType.Document,
|
||||
metadata: { tags: ['whale', 'large'], team: 'beta' }
|
||||
})
|
||||
await brain.flush()
|
||||
return brain
|
||||
}
|
||||
|
||||
it('the accepted operator set is exactly these 25 tokens', async () => {
|
||||
const brain = await seeded()
|
||||
// The engine names its own valid set in the refusal it raises for an
|
||||
// unknown token — the honest place to read it from.
|
||||
let message = ''
|
||||
try {
|
||||
await brain.find({ where: { team: { notIn: ['alpha'] } } } as never)
|
||||
} catch (err) {
|
||||
message = (err as Error).message
|
||||
}
|
||||
expect(message).toMatch(/Unknown filter operator "notIn"/)
|
||||
const listed = (message.match(/Valid operators: ([^.]+)\./)?.[1] ?? '')
|
||||
.split(',')
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean)
|
||||
.sort()
|
||||
expect(listed).toEqual([...ACCEPTED_OPERATORS].sort())
|
||||
expect(listed.length).toBe(25)
|
||||
// Four tokens a sibling manifest listed as served aliases are NOT in this
|
||||
// engine's set and never have been — they raise INVALID_QUERY.
|
||||
for (const absent of ['is', 'isNot', 'greaterEqual', 'lessEqual']) {
|
||||
expect(listed).not.toContain(absent)
|
||||
await expect(
|
||||
brain.find({ where: { team: { [absent]: 'alpha' } } } as never)
|
||||
).rejects.toThrow(/Unknown filter operator/)
|
||||
}
|
||||
}, 120_000)
|
||||
|
||||
it('serves hasAll, noneOf and excludes on the index path — never an empty page', async () => {
|
||||
const brain = await seeded()
|
||||
|
||||
const hasAll = await brain.find({ where: { tags: { hasAll: ['ferret', 'furry'] } } } as never)
|
||||
expect(hasAll.length).toBe(1)
|
||||
expect((hasAll[0] as { metadata?: Record<string, unknown> }).metadata?.team).toBe('alpha')
|
||||
|
||||
const noneOf = await brain.find({ where: { team: { noneOf: ['alpha'] } } } as never)
|
||||
expect(noneOf.length).toBe(1)
|
||||
expect((noneOf[0] as { metadata?: Record<string, unknown> }).metadata?.team).toBe('beta')
|
||||
|
||||
const excludes = await brain.find({ where: { tags: { excludes: 'whale' } } } as never)
|
||||
expect(excludes.length).toBe(1)
|
||||
expect((excludes[0] as { metadata?: Record<string, unknown> }).metadata?.team).toBe('alpha')
|
||||
|
||||
// hasAll with an operand nothing carries is EMPTY because it is empty —
|
||||
// the honest zero, reached by evaluating the operator.
|
||||
const none = await brain.find({ where: { tags: { hasAll: ['ferret', 'whale'] } } } as never)
|
||||
expect(none.length).toBe(0)
|
||||
}, 120_000)
|
||||
|
||||
it('refuses the four index-unserveable operators BY NAME', async () => {
|
||||
const brain = await seeded()
|
||||
for (const op of REFUSED_BY_INDEX) {
|
||||
const operand = op === 'length' ? 3 : 'a'
|
||||
await expect(
|
||||
brain.find({ where: { team: { [op]: operand } } } as never),
|
||||
`${op} must refuse, never answer an empty page`
|
||||
).rejects.toThrow(new RegExp(`Filter operator "${op}".*cannot be served by the metadata index`, 's'))
|
||||
}
|
||||
}, 120_000)
|
||||
|
||||
it('declares its contract version in code and in package.json', async () => {
|
||||
expect(contractVersion()).toBe(1)
|
||||
expect(BRAINY_CONTRACT_VERSION).toBe(1)
|
||||
const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf-8'))
|
||||
expect(pkg.brainyContract).toBe(contractVersion())
|
||||
})
|
||||
|
||||
it('the three classes partition the accepted set', () => {
|
||||
expect([...SERVED_ON_INDEX, ...REFUSED_BY_INDEX].sort()).toEqual([...ACCEPTED_OPERATORS].sort())
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue