Files
core/tests/rigor/pltc-reachability-parity.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

174 lines
6.5 KiB
JavaScript

/**
* rigor/pltc-reachability-parity.test.js — js-rigor property tests for the
* PLTC reachability gate.
*
* ChainRule consults a reachability index (PLTC) when
* enableReachabilityCheck is on: a FALSE verdict fast-fails the chain with
* 0 ('not_reachable'); TRUE/null falls through to full evaluation. The
* engine documents PLTC as "100% accurate", so the parity contract is:
*
* - ACTIVE/BYPASS PARITY: with PLTC enabled, check(user, chain, obj)
* equals check(..., { bypassPLTC: true }) on the same graph — for
* every graph shape and after every mutation. A divergence means the
* reachability index disagrees with the actual edge set (stale
* add/remove maintenance).
*/
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 NODES = ['user:alice', 'mid:1', 'mid:2', 'doc:1'];
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 randomEdges(rng) {
const edges = [];
for (const rel of ['r1', 'r2']) {
for (const [src, dst] of EDGE_UNIVERSE[rel]) {
if (rng.next() < 0.5) {
edges.push([src, rel, dst, POS[Math.floor(rng.next() * POS.length)]]);
}
}
}
return edges;
}
function buildArbiter(withPLTC) {
const arb = new Arbiter(withPLTC ? { enableReachabilityCheck: true } : {});
for (const k of NODES) arb.addNode(k, k.startsWith('user') ? 'user' : k.startsWith('mid') ? 'mid' : 'doc');
arb.setRelationConfig('r1', { type: 'direct' });
arb.setRelationConfig('r2', { type: 'direct' });
arb.setRelationConfig('target', { type: 'chain', steps: [{ relation: 'r1', direction: 'out' }, { relation: 'r2', direction: 'out' }] });
arb.setRelationConfig('target_rev', { type: 'chain', steps: [{ relation: 'r1', direction: 'in' }, { relation: 'r2', direction: 'in' }] });
return arb;
}
describe('PLTC reachability parity (rigor)', () => {
it('ACTIVE/BYPASS PARITY: PLTC verdicts agree with ground truth through mutations', async () => {
async function check({ seed, mutations }) {
const rng = mulberry32(seed);
const edges = randomEdges(rng);
const arb = buildArbiter(true);
for (const [src, rel, dst, p] of edges) arb.addRelation(src, rel, dst, { possibility: p });
const verify = (tag) => {
for (const cfg of ['target', 'target_rev']) {
const active = arb.check('user:alice', cfg, 'doc:1', {});
const bypass = arb.check('user:alice', cfg, 'doc:1', { bypassPLTC: true });
if (Math.abs(active.possibility - bypass.possibility) > EPS) {
fail(`${tag} ${cfg}: PLTC active=${active.possibility} bypass=${bypass.possibility} (reason ${active.reason} vs ${bypass.reason})`);
}
}
};
verify('initial');
const rels = ['r1', 'r2'];
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]);
}
verify(`mutation ${i}`);
}
return { mutations };
}
const report = await rigor.campaign(
[
rigor.fn('check', check, rigor.args(
rigor.gen.object({
seed: rigor.gen.int(1, 100000),
mutations: rigor.gen.int(2, 8)
})
))
],
rigor.crucible([
rigor.invariant('pltc-active-bypass-parity', ({ actual }) => actual !== undefined)
])
).run({ effort: 1500, seed: 'pltc-parity-active-bypass' , artifacts: { dir: '', persist: 'never' }});
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'pltc-active-bypass-parity');
assert.ok(inv, 'invariant missing');
assert.equal(inv.passed, true, `PLTC parity violated in ${inv.failureCount} cases`);
});
it('PLTC FAST-FAIL SOUNDNESS: a PLTC false verdict only fires when ground truth is 0', async () => {
async function check({ seed }) {
const rng = mulberry32(seed);
const edges = randomEdges(rng);
const arb = buildArbiter(true);
for (const [src, rel, dst, p] of edges) arb.addRelation(src, rel, dst, { possibility: p });
const active = arb.check('user:alice', 'target', 'doc:1', { includeMeta: true });
const bypass = arb.check('user:alice', 'target', 'doc:1', { bypassPLTC: true, includeMeta: true });
if (active.reason === 'not_reachable') {
// Fast-failed: ground truth must be exactly 0
if (Math.abs(bypass.possibility) > EPS) {
fail(`fast-fail on reachable graph: active=${active.possibility} bypass=${bypass.possibility} edges=${JSON.stringify(edges)}`);
}
} else if (Math.abs(active.possibility - bypass.possibility) > EPS) {
fail(`non-fast-fail mismatch: active=${active.possibility} bypass=${bypass.possibility}`);
}
return { active: active.reason };
}
const report = await rigor.campaign(
[
rigor.fn('check', check, rigor.args(
rigor.gen.object({ seed: rigor.gen.int(1, 100000) })
))
],
rigor.crucible([
rigor.invariant('pltc-fastfail-soundness', ({ actual }) => actual !== undefined)
])
).run({ effort: 1000, seed: 'pltc-parity-fastfail' , artifacts: { dir: '', persist: 'never' }});
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'pltc-fastfail-soundness');
assert.ok(inv, 'invariant missing');
assert.equal(inv.passed, true, `PLTC fast-fail soundness violated in ${inv.failureCount} cases`);
});
});