Files
core/tests/rigor/multi-object-independence.test.js
T
John Dvorak ed34df4474
CI / benchmark (push) Successful in 48s
CI / test (push) Successful in 5m26s
CI / publish (push) Has been skipped
feat: intermediate chain condition steps, graph-version cache invalidation, rolling-hash chain keys; fix vacuous rigor invariants
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.
2026-08-03 13:26:42 -07:00

164 lines
5.3 KiB
JavaScript

/**
* rigor/multi-object-independence.test.js — js-rigor property tests for
* cross-object isolation.
*
* Shared groups connect multiple objects: alice is a member of group:eng,
* and BOTH doc:1 and doc:2 have owner tuples pointing at group:eng.
* Mutations affecting one object must never change another object's
* checks.
*
* Properties verified:
*
* - PER-OBJECT ORACLE PARITY: every check on every object equals the
* per-object oracle computed from the edge set (TTU:
* max over tuples of min(tupleP, memberP); chain: BFS per object).
* - MUTATION ISOLATION: after every mutation targeting one object, all
* OTHER objects' checks are unchanged (equal to their own oracles).
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { rigor } from '@rigor/core';
import { Arbiter } from '../../src/index.js';
const EPS = 1e-9;
const POS = [0, 0.25, 0.5, 0.75, 1];
const USERS = ['user:alice', 'user:bob'];
const DOCS = ['doc:1', 'doc:2', 'doc:3'];
const GROUPS = ['group:eng', 'group:design'];
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;
}
};
}
function buildArbiter() {
const arb = new Arbiter();
for (const k of [...USERS, ...DOCS, ...GROUPS]) {
arb.addNode(k, k.startsWith('user') ? 'user' : k.startsWith('doc') ? 'doc' : 'group');
}
arb.setRelationConfig('owner', { type: 'direct' });
arb.setRelationConfig('member_of', { type: 'direct' });
arb.setRelationConfig('can_edit', { type: 'tuple_to_userset', tuplesetRelation: 'owner', computedRelation: 'member_of' });
arb.setRelationConfig('viewer', { type: 'direct' });
arb.setRelationConfig('member_of2', { type: 'direct' });
return arb;
}
function randomState(rng) {
// Random membership + tuple edges
const edges = [];
for (const user of USERS) {
for (const grp of GROUPS) {
if (rng.next() < 0.6) {
const p = POS[Math.floor(rng.next() * POS.length)];
edges.push(['member_of', user, grp, p]);
}
}
}
for (const doc of DOCS) {
for (const grp of GROUPS) {
if (rng.next() < 0.6) {
const p = POS[Math.floor(rng.next() * POS.length)];
edges.push(['owner', doc, grp, p]);
}
}
}
return edges;
}
function applyEdges(arb, edges) {
for (const [rel, src, dst, p] of edges) arb.addRelation(src, rel, dst, { possibility: p });
}
function ttuOracle(user, doc, edges) {
let best = 0;
for (const [rel, src, dst, p] of edges) {
if (rel !== 'owner' || src !== doc) continue;
const member = edges.find(e => e[0] === 'member_of' && e[1] === user && e[2] === dst);
best = Math.max(best, Math.min(p, member ? member[3] : 0));
}
return best;
}
function checkAll(arb, edges) {
const results = {};
for (const user of USERS) {
for (const doc of DOCS) {
results[`${user}|${doc}`] = {
got: arb.check(user, 'can_edit', doc, {}).possibility,
oracle: ttuOracle(user, doc, edges)
};
}
}
return results;
}
describe('Multi-object independence (rigor)', () => {
it('PER-OBJECT ORACLE PARITY + MUTATION ISOLATION through random mutations', async () => {
async function check({ seed, mutations }) {
const rng = mulberry32(seed);
const edges = randomState(rng);
const arb = buildArbiter();
applyEdges(arb, edges);
const verify = (tag) => {
const results = checkAll(arb, edges);
for (const [key, r] of Object.entries(results)) {
if (Math.abs(r.got - r.oracle) > EPS) {
fail(`${tag} ${key}: got=${r.got} oracle=${r.oracle}`);
}
}
};
verify('initial');
for (let i = 0; i < mutations; i++) {
// Mutate a single edge; the target is one user/doc pair
const rel = rng.next() < 0.5 ? 'owner' : 'member_of';
const src = rel === 'owner' ? DOCS[Math.floor(rng.next() * DOCS.length)] : USERS[Math.floor(rng.next() * USERS.length)];
const dst = GROUPS[Math.floor(rng.next() * GROUPS.length)];
const idx = edges.findIndex(e => e[0] === rel && e[1] === src && 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([rel, src, dst, p]);
}
verify(`mutation ${i}`);
}
return { edges: edges.length };
}
const report = await rigor.campaign(
[
rigor.fn('check', check, rigor.args(
rigor.gen.object({
seed: rigor.gen.int(1, 80000),
mutations: rigor.gen.int(3, 10)
})
))
],
rigor.crucible([
rigor.invariant('multi-object-isolation', ({ actual }) => actual !== undefined)
])
).run({ effort: 1000, seed: 'multi-object-independence' , artifacts: { dir: '', persist: 'never' }});
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'multi-object-isolation');
assert.ok(inv, 'invariant missing');
assert.equal(inv.passed, true, `multi-object isolation violated in ${inv.failureCount} cases`);
});
});