ed34df4474
Chain intermediates (rule-based reachability):
- ChainRule: a condition step ({ rule, conditionStep }) at an INTERMEDIATE
position is now EXPANDED from the current node — the rule's base edges'
destinations, filtered by its defeaters/requirements — and traversal
continues from each discovered node. Adds _expandRuleFromSrc / direct /
logical(union/intersection) / defeasible / nested-chain expansion.
- RuleEvaluator: _subjectIsObject flag for unary predicate calls whose subject
entity IS the object parameter (trusted(other) inside peer_trusted(user,
other)); previously only subject-var unary calls (_subjectAsObject) were
handled, so object-var unary defeaters never fired.
Graph-version cache invalidation:
- Arbiter gains a monotonic _graphVersion, incremented on every relation
mutation. ChainRule result cache, RuleEvaluator rule-result cache, and
DecisionCache rule cache now stamp entries with the graph version and treat
any mismatch as a miss — graph mutations can no longer serve stale
chain/authorization results.
Rolling-hash cache keys:
- UnifiedKeyManager.createChainKey now builds a 53-bit rolling hash (dual
FNV-1a lanes, exact for ints/floats/strings/nested configs) instead of
JSON.stringify — no string allocation or serialization on the chain-cache
hot path. Composite keys stay structured strings because the direct-check
cache pattern-invalidates by relation ID.
Rigor invariant migration (correctness):
- All 43 rigor test files' throw-based invariants ({ error, errorMessage } =>
!error && !errorMessage) never saw fn throws — vacuous. Migrated to
({ actual }) => actual !== undefined, which fails on any thrown violation
while passing legitimate null-skips. The migration immediately surfaced
two latent bugs, now fixed:
* node-manager/graph-indices skip paths returned bare undefined (falsy
sentinel) — return { skipped: true }.
* complex-graph-values-crucible expiry section rewrote values equal to the
mutation loop's last write; the engine (by design) keeps the old
timestamp on same-value rewrites so the pre-expiry grant never
materialized. Now writes guaranteed-different values.
175 lines
5.9 KiB
JavaScript
175 lines
5.9 KiB
JavaScript
/**
|
|
* rigor/manager-index-parity.test.js — js-rigor property tests for the
|
|
* RelationManager lookup layer vs the GraphIndices ground truth.
|
|
*
|
|
* RelationManager.getRelationsFromSrc/ToDst consult the RF-08 lookup
|
|
* caches (relationLookupCache/valueLookupCache); GraphIndices holds the
|
|
* ground truth. The two must agree after every mutation — a divergence
|
|
* means a lookup cache went stale.
|
|
*
|
|
* Properties verified:
|
|
*
|
|
* - LOOKUP PARITY: after every add/remove/overwrite, both layers return
|
|
* identical (src, dst, possibility) sets for every node/relation pair.
|
|
* - COUNT CONSISTENCY: relations.length equals the number of distinct
|
|
* tuples across all index lookups.
|
|
*/
|
|
import { describe, it } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { rigor } from '@rigor/core';
|
|
import { Arbiter } from '../../src/index.js';
|
|
|
|
const POS = [0, 0.25, 0.5, 0.75, 1];
|
|
const NODES = ['user:alice', 'mid:1', 'mid:2', 'doc:1'];
|
|
const RELS = ['r1', 'r2'];
|
|
|
|
function fail(message) {
|
|
throw new Error(message);
|
|
}
|
|
|
|
function mulberry32(seed) {
|
|
let a = seed >>> 0;
|
|
return {
|
|
next() {
|
|
a |= 0; a = (a + 0x6D2B79F5) | 0;
|
|
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
}
|
|
};
|
|
}
|
|
|
|
const EDGE_UNIVERSE = {
|
|
r1: [
|
|
['user:alice', 'mid:1'],
|
|
['mid:1', 'user:alice'],
|
|
['mid:1', 'mid:2'],
|
|
['doc:1', 'mid:2'],
|
|
['mid:2', 'doc:1']
|
|
],
|
|
r2: [
|
|
['mid:1', 'doc:1'],
|
|
['doc:1', 'mid:1'],
|
|
['mid:2', 'user:alice'],
|
|
['user:alice', 'mid:2'],
|
|
['user:alice', 'doc:1'],
|
|
['mid:2', 'mid:1']
|
|
]
|
|
};
|
|
|
|
function sig(rels) {
|
|
return rels.map(r => [r.src, r.dst, r.possibility]).sort((x, y) => x[0] - y[0] || x[1] - y[1]).map(x => x.join('|')).join(';');
|
|
}
|
|
|
|
function verifyAllLookups(arb, tag) {
|
|
for (const rel of RELS) {
|
|
for (const node of NODES) {
|
|
const srcId = arb.resolveNodeId(node);
|
|
if (srcId === undefined) continue;
|
|
const managerFrom = arb.relationManager.getRelationsFromSrc(srcId, rel);
|
|
const indexFrom = arb.indices.getRelationsFromSrc(srcId, rel);
|
|
const s1 = sig(managerFrom);
|
|
const s2 = sig(indexFrom);
|
|
if (s1 !== s2) {
|
|
fail(`${tag} fromSrc(${node}, ${rel}) mismatch: manager=[${s1}] index=[${s2}]`);
|
|
}
|
|
const managerTo = arb.relationManager.getRelationsToDst(srcId, rel);
|
|
const indexTo = arb.indices.getRelationsToDst(srcId, rel);
|
|
const t1 = sig(managerTo);
|
|
const t2 = sig(indexTo);
|
|
if (t1 !== t2) {
|
|
fail(`${tag} toDst(${node}, ${rel}) mismatch: manager=[${t1}] index=[${t2}]`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function verifyCount(arb, edges, tag) {
|
|
const n = arb.relations.length;
|
|
if (n !== edges.length) {
|
|
fail(`${tag} relations.length=${n} expected=${edges.length}`);
|
|
}
|
|
}
|
|
|
|
function buildArbiter() {
|
|
const arb = new Arbiter();
|
|
for (const k of NODES) arb.addNode(k, k.startsWith('user') ? 'user' : k.startsWith('mid') ? 'mid' : 'doc');
|
|
for (const r of RELS) arb.setRelationConfig(r, { type: 'direct' });
|
|
return arb;
|
|
}
|
|
|
|
describe('Manager vs index lookup parity (rigor)', () => {
|
|
it('LOOKUP PARITY + COUNT CONSISTENCY through random mutation sequences', async () => {
|
|
async function check({ seed, mutations }) {
|
|
const rng = mulberry32(seed);
|
|
const edges = [];
|
|
const arb = buildArbiter();
|
|
|
|
// Initial random edges
|
|
for (const rel of RELS) {
|
|
for (const [src, dst] of EDGE_UNIVERSE[rel]) {
|
|
if (rng.next() < 0.5) {
|
|
const p = POS[Math.floor(rng.next() * POS.length)];
|
|
arb.addRelation(src, rel, dst, { possibility: p });
|
|
edges.push([src, rel, dst, p]);
|
|
}
|
|
}
|
|
}
|
|
verifyAllLookups(arb, 'initial');
|
|
verifyCount(arb, edges, 'initial');
|
|
|
|
for (let i = 0; i < mutations; i++) {
|
|
const rel = RELS[Math.floor(rng.next() * 2)];
|
|
const [src, dst] = EDGE_UNIVERSE[rel][Math.floor(rng.next() * EDGE_UNIVERSE[rel].length)];
|
|
const idx = edges.findIndex(e => e[0] === src && e[1] === rel && e[2] === dst);
|
|
if (idx !== -1) {
|
|
arb.removeRelation(src, rel, dst);
|
|
edges.splice(idx, 1);
|
|
} else {
|
|
const p = POS[Math.floor(rng.next() * POS.length)];
|
|
arb.addRelation(src, rel, dst, { possibility: p });
|
|
edges.push([src, rel, dst, p]);
|
|
}
|
|
verifyAllLookups(arb, `mutation ${i}`);
|
|
verifyCount(arb, edges, `mutation ${i}`);
|
|
}
|
|
|
|
// Overwrite storm: same tuple 5 times, then lookups must show the last value once
|
|
const [src, dst] = ['user:alice', 'mid:1'];
|
|
for (let i = 0; i < 5; i++) {
|
|
const p = POS[Math.floor(rng.next() * POS.length)];
|
|
arb.addRelation(src, 'r1', dst, { possibility: p });
|
|
}
|
|
const uid = arb.resolveNodeId(src);
|
|
const fromManager = arb.relationManager.getRelationsFromSrc(uid, 'r1');
|
|
const fromIndex = arb.indices.getRelationsFromSrc(uid, 'r1');
|
|
const count = fromIndex.filter(r => r.dst === arb.resolveNodeId(dst)).length;
|
|
if (count !== 1) {
|
|
fail(`overwrite storm left ${count} tuples in index`);
|
|
}
|
|
if (sig(fromManager) !== sig(fromIndex)) {
|
|
fail(`overwrite storm desynced manager vs index`);
|
|
}
|
|
return { edges: edges.length };
|
|
}
|
|
|
|
const report = await rigor.campaign(
|
|
[
|
|
rigor.fn('check', check, rigor.args(
|
|
rigor.gen.object({
|
|
seed: rigor.gen.int(1, 100000),
|
|
mutations: rigor.gen.int(3, 10)
|
|
})
|
|
))
|
|
],
|
|
rigor.crucible([
|
|
rigor.invariant('lookup-parity', ({ actual }) => actual !== undefined)
|
|
])
|
|
).run({ effort: 1200, seed: 'manager-index-parity' , artifacts: { dir: '', persist: 'never' }});
|
|
|
|
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'lookup-parity');
|
|
assert.ok(inv, 'invariant missing');
|
|
assert.equal(inv.passed, true, `lookup parity violated in ${inv.failureCount} cases`);
|
|
});
|
|
});
|