Files
core/tests/rigor/overlay-precedence.test.js
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

148 lines
5.3 KiB
JavaScript

/**
* rigor/overlay-precedence.test.js — js-rigor property tests for partial
* graph overlay semantics.
*
* Properties verified:
*
* - PERSISTENT OVER PARTIAL: when both a persistent fact and a partial
* graph fact describe the same triple, the persistent fact wins by
* trust precedence — the check reflects the persistent possibility
* (even when it is 0).
* - SURFACING: removing the persistent fact lets the partial fact
* surface; the check then reflects the partial possibility.
* - RE-ESTABLISHMENT: re-adding the persistent fact re-asserts its
* precedence immediately (no stale partial-only state).
* - LAYER PRECEDENCE: two partial facts for the same triple at
* different layers resolve to the higher-trust layer.
*/
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];
function fail(message) {
throw new Error(message);
}
function buildArbiter() {
const arbiter = new Arbiter();
arbiter.addNode('user:1', 'user');
arbiter.addNode('doc:1', 'doc');
arbiter.setRelationConfig('can_read', { type: 'direct' });
return arbiter;
}
function partialGraphWith(relation, possibility, layer = null) {
const fact = {
src: 'user:1',
relation,
dst: 'doc:1',
possibility
};
if (layer) fact.layer_name = layer;
return { relations: [fact] };
}
describe('Partial graph overlay precedence (rigor)', () => {
it('PERSISTENT OVER PARTIAL: persistent facts win by trust precedence; partial surfaces on removal', async () => {
async function check({ pPersistent, pPartial }) {
const arbiter = buildArbiter();
arbiter.addRelation('user:1', 'can_read', 'doc:1', { possibility: pPersistent });
const partialGraph = partialGraphWith('can_read', pPartial);
// Persistent present: persistent wins regardless of partial strength
const withBoth = arbiter.check('user:1', 'can_read', 'doc:1', { partialGraph });
if (Math.abs(withBoth.possibility - pPersistent) > EPS) {
fail(`persistent+partial: expected persistent ${pPersistent}, got ${withBoth.possibility}`);
}
// Remove persistent: partial surfaces
arbiter.removeRelation('user:1', 'can_read', 'doc:1');
const partialOnly = arbiter.check('user:1', 'can_read', 'doc:1', { partialGraph });
if (Math.abs(partialOnly.possibility - pPartial) > EPS) {
fail(`partial-only: expected ${pPartial}, got ${partialOnly.possibility}`);
}
// Re-add persistent: precedence re-asserts immediately
arbiter.addRelation('user:1', 'can_read', 'doc:1', { possibility: pPersistent });
const reasserted = arbiter.check('user:1', 'can_read', 'doc:1', { partialGraph });
if (Math.abs(reasserted.possibility - pPersistent) > EPS) {
fail(`re-asserted: expected ${pPersistent}, got ${reasserted.possibility}`);
}
return { withBoth, partialOnly, reasserted };
}
const report = await rigor.campaign(
[
rigor.fn('check', check, rigor.args(
rigor.gen.object({
pPersistent: rigor.gen.oneOf(POS),
pPartial: rigor.gen.oneOf(POS)
})
))
],
rigor.crucible([
rigor.invariant('persistent-precedence', ({ actual }) => actual !== undefined)
])
).run({ effort: 500, seed: 'overlay-persistent-precedence' , artifacts: { dir: '', persist: 'never' }});
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'persistent-precedence');
assert.ok(inv);
assert.equal(inv.passed, true, `PERSISTENT OVER PARTIAL violated in ${inv.failureCount} cases`);
});
it('LAYER PRECEDENCE: higher-trust layer wins between partial facts', async () => {
async function check({ pHigh, pLow }) {
const arbiter = buildArbiter();
// Two partial facts, same triple, different layers:
// token_projection (trust 70) > request_observed (trust 50)
const partialGraph = {
relations: [
{
src: 'user:1',
relation: 'can_read',
dst: 'doc:1',
possibility: pHigh,
layer_name: 'token_projection'
},
{
src: 'user:1',
relation: 'can_read',
dst: 'doc:1',
possibility: pLow,
layer_name: 'request_observed'
}
]
};
const result = arbiter.check('user:1', 'can_read', 'doc:1', { partialGraph });
if (Math.abs(result.possibility - pHigh) > EPS) {
fail(`layer precedence: expected high-trust ${pHigh}, got ${result.possibility}`);
}
return result;
}
const report = await rigor.campaign(
[
rigor.fn('check', check, rigor.args(
rigor.gen.object({
pHigh: rigor.gen.oneOf(POS),
pLow: rigor.gen.oneOf(POS)
})
))
],
rigor.crucible([
rigor.invariant('layer-precedence', ({ actual }) => actual !== undefined)
])
).run({ effort: 400, seed: 'overlay-layer-precedence' , artifacts: { dir: '', persist: 'never' }});
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'layer-precedence');
assert.ok(inv);
assert.equal(inv.passed, true, `LAYER PRECEDENCE violated in ${inv.failureCount} cases`);
});
});