Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4d498b07e8 | |||
| 9111c4b20d | |||
| aa38fbfd8c | |||
| ad365a65a9 |
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.7.0",
|
"version": "1.11.0",
|
||||||
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
|
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
+2
-2
@@ -7,10 +7,10 @@ import { validateDslText } from './validation/DSLValidation.js';
|
|||||||
* Compiles DSL text into rule configurations for the zanzibar-graph system
|
* Compiles DSL text into rule configurations for the zanzibar-graph system
|
||||||
*/
|
*/
|
||||||
export class DSLCompiler {
|
export class DSLCompiler {
|
||||||
constructor(arbiter) {
|
constructor(arbiter, options = {}) {
|
||||||
this.arbiter = arbiter;
|
this.arbiter = arbiter;
|
||||||
this.parser = parse;
|
this.parser = parse;
|
||||||
this.generator = new RuleGenerator(arbiter);
|
this.generator = new RuleGenerator(arbiter, options);
|
||||||
this.compiledPrograms = new Map();
|
this.compiledPrograms = new Map();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,12 +5,14 @@ import { ProgramNode, DefinitionNode, FactNode, EvidenceNode, MeasureNode, Direc
|
|||||||
* Generates rule configurations that interface with the existing rule system
|
* Generates rule configurations that interface with the existing rule system
|
||||||
*/
|
*/
|
||||||
export class RuleGenerator {
|
export class RuleGenerator {
|
||||||
constructor(arbiter) {
|
constructor(arbiter, options = {}) {
|
||||||
this.arbiter = arbiter;
|
this.arbiter = arbiter;
|
||||||
this.generatedRules = new Map();
|
this.generatedRules = new Map();
|
||||||
this.errors = [];
|
this.errors = [];
|
||||||
this.dependencyIndex = new Map();
|
this.dependencyIndex = new Map();
|
||||||
this.evidenceNames = new Set();
|
this.evidenceNames = new Set();
|
||||||
|
// Default depth for bounded self-recursion when the DSL `limit N` is absent.
|
||||||
|
this.maxRecursionDepth = options.maxRecursionDepth ?? 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -629,7 +631,8 @@ export class RuleGenerator {
|
|||||||
type: 'chain',
|
type: 'chain',
|
||||||
steps,
|
steps,
|
||||||
aggregator: 'max',
|
aggregator: 'max',
|
||||||
collectValues: true
|
collectValues: true,
|
||||||
|
maxDepth: patternMatch.limit || null
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -670,7 +673,10 @@ export class RuleGenerator {
|
|||||||
type: 'chain',
|
type: 'chain',
|
||||||
steps,
|
steps,
|
||||||
aggregator: 'max',
|
aggregator: 'max',
|
||||||
collectValues: true
|
collectValues: true,
|
||||||
|
// Carry the pattern's `limit N` as a max depth so a self-referential
|
||||||
|
// chain step can be unrolled into bounded transitive closure.
|
||||||
|
maxDepth: patternMatch.limit || null
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -990,13 +996,113 @@ export class RuleGenerator {
|
|||||||
resolveEvidenceReferences() {
|
resolveEvidenceReferences() {
|
||||||
for (const name of this.evidenceNames) {
|
for (const name of this.evidenceNames) {
|
||||||
if (!this.generatedRules.has(name)) continue;
|
if (!this.generatedRules.has(name)) continue;
|
||||||
|
let config = this.generatedRules.get(name);
|
||||||
|
// Bounded self-recursion (transitive closure): an evidence whose config
|
||||||
|
// contains a chain step referencing ITSELF is unrolled into a union of
|
||||||
|
// bounded paths — base, hop+base, hop²+base, …, hop^N+base — where `hop`
|
||||||
|
// is the recursive chain's steps before the self-reference and the depth
|
||||||
|
// N comes from the pattern's `limit N` (or the compiler default).
|
||||||
|
const selfRef = this._findSelfReference(config, name);
|
||||||
|
if (selfRef) {
|
||||||
|
const depth = selfRef.limit ?? this.maxRecursionDepth;
|
||||||
|
const unrolled = this._unrollRecursiveEvidence(name, config, selfRef.hop, depth);
|
||||||
|
if (unrolled) {
|
||||||
|
config = unrolled;
|
||||||
|
this.generatedRules.set(name, config);
|
||||||
|
}
|
||||||
|
}
|
||||||
const stack = new Set([name]);
|
const stack = new Set([name]);
|
||||||
const resolved = this._resolveRule(this.generatedRules.get(name), stack);
|
const resolved = this._resolveRule(config, stack);
|
||||||
this.generatedRules.set(name, resolved);
|
this.generatedRules.set(name, resolved);
|
||||||
this._annotateDependencies(name, resolved);
|
this._annotateDependencies(name, resolved);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the first chain step within `config` that references `name` (a
|
||||||
|
* self-reference). Returns { hop, limit } where hop is the chain's steps
|
||||||
|
* before the self-reference and limit is the chain's declared max depth.
|
||||||
|
* Returns null when there is no self-reference.
|
||||||
|
*/
|
||||||
|
_findSelfReference(config, name) {
|
||||||
|
let found = null;
|
||||||
|
const walk = (rule) => {
|
||||||
|
if (!rule || typeof rule !== 'object' || found) return;
|
||||||
|
if (rule.type === 'chain' && Array.isArray(rule.steps)) {
|
||||||
|
const idx = rule.steps.findIndex(s => (typeof s === 'string' ? s : s && s.relation) === name);
|
||||||
|
if (idx >= 0) {
|
||||||
|
const lim = rule.maxDepth;
|
||||||
|
const limit = lim && typeof lim === 'object' ? lim.value : lim;
|
||||||
|
found = { hop: rule.steps.slice(0, idx), limit: Number.isFinite(limit) ? limit : null };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const key of ['union', 'intersection', 'exclusion', 'never', 'always', 'requires', 'when', 'unless']) {
|
||||||
|
const node = rule[key];
|
||||||
|
if (!node) continue;
|
||||||
|
if (Array.isArray(node.rules)) for (const c of node.rules) walk(c);
|
||||||
|
if (Array.isArray(node.union?.rules)) for (const c of node.union.rules) walk(c);
|
||||||
|
if (Array.isArray(node.intersection?.rules)) for (const c of node.intersection.rules) walk(c);
|
||||||
|
if (node.direct) walk(node.direct);
|
||||||
|
if (node.rule) walk(node.rule);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(config);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unroll a self-recursive evidence into a bounded transitive closure.
|
||||||
|
* The recursive chain is removed from the config; the remainder is the base.
|
||||||
|
* Result: union([base, hop+base, hop²+base, …, hop^depth+base]) where the
|
||||||
|
* base is verified as a condition step at each path's terminal node.
|
||||||
|
*/
|
||||||
|
_unrollRecursiveEvidence(name, config, hop, depth) {
|
||||||
|
if (hop.length === 0) {
|
||||||
|
this.errors.push(`Recursive evidence '${name}' has an empty recursion hop (no steps before the self-reference).`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const base = this._extractBase(config, name);
|
||||||
|
if (!base) {
|
||||||
|
this.errors.push(`Recursive evidence '${name}' has no base case — pure recursion cannot grant. Add a non-recursive statement.`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const rules = [this._deepCloneRule(base)];
|
||||||
|
for (let d = 1; d <= depth; d++) {
|
||||||
|
const steps = [];
|
||||||
|
for (let h = 0; h < d; h++) steps.push(...hop.map(s => this._deepCloneRule(s)));
|
||||||
|
steps.push({ rule: this._deepCloneRule(base), conditionStep: true });
|
||||||
|
rules.push({ type: 'chain', steps, aggregator: 'max', collectValues: true });
|
||||||
|
}
|
||||||
|
return { type: 'logical', union: { rules, aggregator: 'max' } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the recursive chain (the chain containing a self-reference) from an
|
||||||
|
* evidence config and return the remainder as the base case. Returns null if
|
||||||
|
* there is no base (pure recursion).
|
||||||
|
*/
|
||||||
|
_extractBase(config, name) {
|
||||||
|
if (config.type === 'chain') {
|
||||||
|
const hasSelf = (config.steps || []).some(s => (typeof s === 'string' ? s : s && s.relation) === name);
|
||||||
|
return hasSelf ? null : this._deepCloneRule(config);
|
||||||
|
}
|
||||||
|
if (config.type === 'logical' && config.intersection) {
|
||||||
|
const remaining = (config.intersection.rules || []).filter(r => {
|
||||||
|
// keep rules that are not (or do not contain) the recursive chain
|
||||||
|
return !this._containsSelfReference(r, name);
|
||||||
|
});
|
||||||
|
if (remaining.length === 0) return null;
|
||||||
|
if (remaining.length === 1) return this._deepCloneRule(remaining[0]);
|
||||||
|
return { type: 'logical', intersection: { rules: remaining.map(r => this._deepCloneRule(r)), aggregator: config.intersection.aggregator || 'min' } };
|
||||||
|
}
|
||||||
|
return this._containsSelfReference(config, name) ? null : this._deepCloneRule(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
_containsSelfReference(rule, name) {
|
||||||
|
return this._findSelfReference(rule, name) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recursively rewrite a rule tree, inlining references to derived evidence
|
* Recursively rewrite a rule tree, inlining references to derived evidence
|
||||||
* configs. `stack` holds the evidence names currently being expanded so a
|
* configs. `stack` holds the evidence names currently being expanded so a
|
||||||
@@ -1111,6 +1217,15 @@ export class RuleGenerator {
|
|||||||
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (resolved.type === 'relational_comparator' && idx !== steps.length - 1) {
|
||||||
|
// A comparator compares values at (src, candidate) but provides no
|
||||||
|
// candidate set — it cannot enumerate intermediate nodes, so only
|
||||||
|
// a FINAL comparator step (verified at the known object) lowers.
|
||||||
|
this.errors.push(`Chain step '${stepName}' references a comparator evidence at a non-final position. ` +
|
||||||
|
'Comparators can only be the final chain step (the object is known); intermediate positions are not enumerable.');
|
||||||
|
out.push(step);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
// Condition step: inline the evidence's config as a rule step. As the
|
// Condition step: inline the evidence's config as a rule step. As the
|
||||||
// FINAL step the engine verifies it at (intermediate, object); as an
|
// FINAL step the engine verifies it at (intermediate, object); as an
|
||||||
// INTERMEDIATE step the engine EXPANDS it from the current node
|
// INTERMEDIATE step the engine EXPANDS it from the current node
|
||||||
|
|||||||
@@ -54,11 +54,14 @@ Definition "A type definition"
|
|||||||
}
|
}
|
||||||
|
|
||||||
Field
|
Field
|
||||||
= name:Identifier _ ":" _ fieldType:Type _ isArray:("[]")? _ behavior:Behavior? _ cache:CacheDirective? {
|
= name:Identifier _ ":" _ fieldType:Type optional:("?")? _ isArray:("[]")? _ behavior:Behavior? _ cache:CacheDirective? {
|
||||||
return {
|
return {
|
||||||
type: "Field",
|
type: "Field",
|
||||||
name,
|
name,
|
||||||
fieldType,
|
fieldType,
|
||||||
|
// `field: type` is REQUIRED on node insert; `field: type?` is optional.
|
||||||
|
// Presence is enforced by the DSLRuntime when a node is created.
|
||||||
|
required: !optional,
|
||||||
isArray: !!isArray,
|
isArray: !!isArray,
|
||||||
behavior: behavior || null,
|
behavior: behavior || null,
|
||||||
cache: cache || null
|
cache: cache || null
|
||||||
@@ -392,7 +395,7 @@ Boolean "A boolean literal"
|
|||||||
= value:("true" / "false") { return { type: "Literal", value: value === "true" }; }
|
= value:("true" / "false") { return { type: "Literal", value: value === "true" }; }
|
||||||
|
|
||||||
Duration "A time duration literal"
|
Duration "A time duration literal"
|
||||||
= value:([0-9]+ ("h" / "d" / "w" / "m")) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
|
= value:([0-9]+ ("s" / "m" / "h" / "d" / "w")) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
|
||||||
|
|
||||||
|
|
||||||
// -- Core Tokens & Whitespace --
|
// -- Core Tokens & Whitespace --
|
||||||
|
|||||||
+684
-669
File diff suppressed because it is too large
Load Diff
+72
-22
@@ -60,6 +60,12 @@ export class DSLRuntime {
|
|||||||
this.clock = typeof options.clock === 'function' ? options.clock : (() => Date.now());
|
this.clock = typeof options.clock === 'function' ? options.clock : (() => Date.now());
|
||||||
// Default provider-result TTL in ms (0 disables caching).
|
// Default provider-result TTL in ms (0 disables caching).
|
||||||
this.defaultProviderCacheTTL = options.policy?.providerCacheTTL ?? options.providerCacheTTL ?? 30_000;
|
this.defaultProviderCacheTTL = options.policy?.providerCacheTTL ?? options.providerCacheTTL ?? 30_000;
|
||||||
|
// Provider caching is a STORE-RETRIEVAL cache (wall-clock), deliberately
|
||||||
|
// independent of the caller's decision `{ now }` — a provider returns the
|
||||||
|
// store's current data, not a time-travel snapshot. Callers who pin time
|
||||||
|
// or otherwise want fresh retrieval can disable it per-check
|
||||||
|
// (options.cacheProviderResults: false) or globally (policy).
|
||||||
|
this.cacheProviderResults = options.policy?.cacheProviderResults ?? options.cacheProviderResults ?? true;
|
||||||
// Per-fact overrides (ms). DSL-declared ttl behaviors are indexed here too.
|
// Per-fact overrides (ms). DSL-declared ttl behaviors are indexed here too.
|
||||||
this.factTTLs = new Map(Object.entries(options.factTTLs || {}));
|
this.factTTLs = new Map(Object.entries(options.factTTLs || {}));
|
||||||
}
|
}
|
||||||
@@ -97,7 +103,8 @@ export class DSLRuntime {
|
|||||||
fields: [...fields.entries()].map(([fieldName, f]) => ({
|
fields: [...fields.entries()].map(([fieldName, f]) => ({
|
||||||
name: fieldName,
|
name: fieldName,
|
||||||
type: f.type,
|
type: f.type,
|
||||||
isArray: f.isArray
|
isArray: f.isArray,
|
||||||
|
required: f.required !== false
|
||||||
}))
|
}))
|
||||||
}));
|
}));
|
||||||
const facts = [...this.relations.entries()]
|
const facts = [...this.relations.entries()]
|
||||||
@@ -126,7 +133,7 @@ export class DSLRuntime {
|
|||||||
for (const def of this.program.definitions || []) {
|
for (const def of this.program.definitions || []) {
|
||||||
const fields = new Map();
|
const fields = new Map();
|
||||||
for (const field of def.fields || []) {
|
for (const field of def.fields || []) {
|
||||||
fields.set(field.name, { type: field.fieldType, isArray: !!field.isArray });
|
fields.set(field.name, { type: field.fieldType, isArray: !!field.isArray, required: field.required !== false });
|
||||||
}
|
}
|
||||||
this.types.set(def.name, { fields });
|
this.types.set(def.name, { fields });
|
||||||
}
|
}
|
||||||
@@ -296,7 +303,7 @@ export class DSLRuntime {
|
|||||||
const b = behavior.behavior || behavior;
|
const b = behavior.behavior || behavior;
|
||||||
if (b && b.behaviorType === 'ttl' && b.duration) {
|
if (b && b.behaviorType === 'ttl' && b.duration) {
|
||||||
const n = parseInt(String(b.duration.value), 10);
|
const n = parseInt(String(b.duration.value), 10);
|
||||||
const mult = { h: 3600_000, d: 86_400_000, w: 604_800_000, m: 60_000 }[b.duration.unit];
|
const mult = { s: 1000, m: 60_000, h: 3600_000, d: 86_400_000, w: 604_800_000 }[b.duration.unit];
|
||||||
if (!Number.isNaN(n) && mult) return n * mult;
|
if (!Number.isNaN(n) && mult) return n * mult;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -307,30 +314,59 @@ export class DSLRuntime {
|
|||||||
* array of edge objects) into an array of partial-graph edge objects. The
|
* array of edge objects) into an array of partial-graph edge objects. The
|
||||||
* destination follows the DSL fact's declared shape: unary and value-carrying
|
* destination follows the DSL fact's declared shape: unary and value-carrying
|
||||||
* facts are self-edges on the subject; binary entity facts go subject → object.
|
* facts are self-edges on the subject; binary entity facts go subject → object.
|
||||||
|
* Provider-returned edges are validated against the fact's declared typing:
|
||||||
|
* a value-carrying fact must return an object with a value of the declared
|
||||||
|
* type, and possibilities must be in [0, 1]. A violation throws — it is a
|
||||||
|
* provider-authoring error, not a denial.
|
||||||
*/
|
*/
|
||||||
_normalizeProviderEdges(result, factMeta, user, object) {
|
_normalizeProviderEdges(result, factMeta, fact, user, object) {
|
||||||
const edges = Array.isArray(result) ? result : [result];
|
const edges = Array.isArray(result) ? result : [result];
|
||||||
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
||||||
const defaultDst = factMeta.params.length >= 2 && this._isValueType(secondParamType)
|
const isValueFact = factMeta.params.length >= 2 && this._isValueType(secondParamType);
|
||||||
? user
|
const defaultDst = isValueFact ? user : (factMeta.params.length >= 2 ? object : user);
|
||||||
: (factMeta.params.length >= 2 ? object : user);
|
const label = `provider for '${fact}'`;
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const edge of edges) {
|
for (const edge of edges) {
|
||||||
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
||||||
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
? (() => {
|
||||||
: {
|
if (isValueFact) {
|
||||||
...(edge.relation ? { relation: edge.relation } : {}),
|
throw new Error(`DSLRuntime: ${label} is a value-carrying fact — return { value, possibility } (got a bare ${typeof edge === 'number' ? 'number' : 'boolean'})`);
|
||||||
src: edge.src ?? user,
|
}
|
||||||
dst: edge.dst ?? defaultDst,
|
const possibility = edge === true ? 1 : edge;
|
||||||
possibility: edge.possibility ?? 1,
|
this._checkPossibility(possibility, label);
|
||||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
return { src: user, dst: defaultDst, possibility };
|
||||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
})()
|
||||||
};
|
: (() => {
|
||||||
|
const possibility = edge.possibility ?? 1;
|
||||||
|
this._checkPossibility(possibility, label);
|
||||||
|
if (edge.value !== undefined) {
|
||||||
|
if (!isValueFact) {
|
||||||
|
throw new Error(`DSLRuntime: ${label} returned a value for a non-value fact '${fact}'`);
|
||||||
|
}
|
||||||
|
this._checkScalarValue(secondParamType, edge.value, `${label}.value`);
|
||||||
|
} else if (isValueFact) {
|
||||||
|
throw new Error(`DSLRuntime: ${label} must supply a 'value' of type ${secondParamType}`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...(edge.relation ? { relation: edge.relation } : {}),
|
||||||
|
src: edge.src ?? user,
|
||||||
|
dst: edge.dst ?? defaultDst,
|
||||||
|
possibility,
|
||||||
|
...(edge.value !== undefined ? { value: edge.value } : {}),
|
||||||
|
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
||||||
|
};
|
||||||
|
})();
|
||||||
out.push(normalized);
|
out.push(normalized);
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_checkPossibility(possibility, label) {
|
||||||
|
if (typeof possibility !== 'number' || !Number.isFinite(possibility) || possibility < 0 || possibility > 1) {
|
||||||
|
throw new Error(`DSLRuntime: ${label} returned invalid possibility ${possibility} (expected a number in [0, 1])`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Schema validation helpers
|
// Schema validation helpers
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -399,6 +435,11 @@ export class DSLRuntime {
|
|||||||
if (this.types.has(typeName)) {
|
if (this.types.has(typeName)) {
|
||||||
const { fields } = this.types.get(typeName);
|
const { fields } = this.types.get(typeName);
|
||||||
for (const [name, field] of fields) {
|
for (const [name, field] of fields) {
|
||||||
|
// Required fields must be present on insert (`field: type` in the DSL;
|
||||||
|
// `field?: type` marks a field optional).
|
||||||
|
if (field.required && data[name] === undefined) {
|
||||||
|
throw new Error(`DSLRuntime: missing required field '${typeName}.${name}' on node insert`);
|
||||||
|
}
|
||||||
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
||||||
}
|
}
|
||||||
} else if (this.strictTypes) {
|
} else if (this.strictTypes) {
|
||||||
@@ -559,7 +600,13 @@ export class DSLRuntime {
|
|||||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||||
}
|
}
|
||||||
|
|
||||||
const required = this.requiredFacts(relation);
|
// Retrieval set: for an evidence, the injectable facts it depends on; for
|
||||||
|
// a direct FACT check, the fact itself is the retrieval target (its
|
||||||
|
// provider, if registered, supplies the edge — checking `owns` directly
|
||||||
|
// must consult the `owns` provider, not only evidence-mediated checks).
|
||||||
|
const required = new Set(this.requiredFacts(relation));
|
||||||
|
if (meta && meta.kind === 'fact') required.add(relation);
|
||||||
|
const requiredList = [...required];
|
||||||
const providers = { ...this.factProviders, ...(options.factProviders || {}) };
|
const providers = { ...this.factProviders, ...(options.factProviders || {}) };
|
||||||
const maxRounds = options.maxProviderRounds ?? 3;
|
const maxRounds = options.maxProviderRounds ?? 3;
|
||||||
const partialRelations = [];
|
const partialRelations = [];
|
||||||
@@ -577,7 +624,7 @@ export class DSLRuntime {
|
|||||||
// Fixed-point provider retrieval loop.
|
// Fixed-point provider retrieval loop.
|
||||||
for (let round = 1; round <= maxRounds; round++) {
|
for (let round = 1; round <= maxRounds; round++) {
|
||||||
let newRelationsThisRound = 0;
|
let newRelationsThisRound = 0;
|
||||||
for (const fact of required) {
|
for (const fact of requiredList) {
|
||||||
if (satisfied.has(fact)) continue;
|
if (satisfied.has(fact)) continue;
|
||||||
const factMeta = this.relations.get(fact);
|
const factMeta = this.relations.get(fact);
|
||||||
const provider = providers[fact];
|
const provider = providers[fact];
|
||||||
@@ -587,8 +634,11 @@ export class DSLRuntime {
|
|||||||
// provider overrides are one-off observations — they bypass the cache
|
// provider overrides are one-off observations — they bypass the cache
|
||||||
// entirely (no read, no write) so a fresh override is never masked by
|
// entirely (no read, no write) so a fresh override is never masked by
|
||||||
// a cached registered-provider result, nor does it pollute the cache.
|
// a cached registered-provider result, nor does it pollute the cache.
|
||||||
|
// options.cacheProviderResults:false (or the policy default) disables
|
||||||
|
// the cache for this check.
|
||||||
|
const cachingEnabled = options.cacheProviderResults ?? this.cacheProviderResults;
|
||||||
const isPerCheckOverride = !!(options.factProviders && fact in options.factProviders);
|
const isPerCheckOverride = !!(options.factProviders && fact in options.factProviders);
|
||||||
const cacheHit = isPerCheckOverride ? null : this._providerCacheGet(fact, user, object);
|
const cacheHit = (cachingEnabled && !isPerCheckOverride) ? this._providerCacheGet(fact, user, object) : null;
|
||||||
let edges = null;
|
let edges = null;
|
||||||
let fromCache = false;
|
let fromCache = false;
|
||||||
if (cacheHit) {
|
if (cacheHit) {
|
||||||
@@ -619,8 +669,8 @@ export class DSLRuntime {
|
|||||||
satisfied.add(fact);
|
satisfied.add(fact);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
edges = this._normalizeProviderEdges(result, factMeta, user, object);
|
edges = this._normalizeProviderEdges(result, factMeta, fact, user, object);
|
||||||
if (!isPerCheckOverride) this._providerCacheSet(fact, user, object, edges);
|
if (cachingEnabled && !isPerCheckOverride) this._providerCacheSet(fact, user, object, edges);
|
||||||
} else {
|
} else {
|
||||||
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
||||||
satisfied.add(fact);
|
satisfied.add(fact);
|
||||||
@@ -653,7 +703,7 @@ export class DSLRuntime {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...result,
|
...result,
|
||||||
requiredFacts: required,
|
requiredFacts: requiredList,
|
||||||
providedFacts: injectedRelations.map(r => r.relation),
|
providedFacts: injectedRelations.map(r => r.relation),
|
||||||
missingFacts
|
missingFacts
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ import { Arbiter } from '@arbiter/core';
|
|||||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||||
|
|
||||||
const BASE_DSL = `
|
const BASE_DSL = `
|
||||||
definition Employee { id: string level: number active: boolean }
|
definition Employee { id: string? level: number? active: boolean? }
|
||||||
definition Group { id: string }
|
definition Group { id: string? }
|
||||||
definition Doc { id: string }
|
definition Doc { id: string? }
|
||||||
fact member_of(user: Employee, group: Group)
|
fact member_of(user: Employee, group: Group)
|
||||||
fact *owns(user: Employee, doc: Doc)
|
fact *owns(user: Employee, doc: Doc)
|
||||||
fact *user_score(user: Employee, value: number)
|
fact *user_score(user: Employee, value: number)
|
||||||
@@ -164,8 +164,8 @@ describe('DSLRuntime', () => {
|
|||||||
|
|
||||||
it('derives transitive required facts through evidence composition', async () => {
|
it('derives transitive required facts through evidence composition', async () => {
|
||||||
const dsl = `
|
const dsl = `
|
||||||
definition Employee { id: string }
|
definition Employee { id: string? }
|
||||||
definition Doc { id: string }
|
definition Doc { id: string? }
|
||||||
fact *owns(user: Employee, doc: Doc)
|
fact *owns(user: Employee, doc: Doc)
|
||||||
fact *banned(user: Employee)
|
fact *banned(user: Employee)
|
||||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
@@ -191,9 +191,9 @@ describe('DSLRuntime', () => {
|
|||||||
|
|
||||||
it('derives transitive required facts through a condition-step chain', () => {
|
it('derives transitive required facts through a condition-step chain', () => {
|
||||||
const dsl = `
|
const dsl = `
|
||||||
definition Employee { id: string }
|
definition Employee { id: string? }
|
||||||
definition Group { id: string }
|
definition Group { id: string? }
|
||||||
definition Doc { id: string }
|
definition Doc { id: string? }
|
||||||
fact *member_of(user: Employee, group: Group)
|
fact *member_of(user: Employee, group: Group)
|
||||||
fact *can_view(group: Group, doc: Doc)
|
fact *can_view(group: Group, doc: Doc)
|
||||||
fact *banned(group: Group)
|
fact *banned(group: Group)
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ import { Arbiter } from '@arbiter/core';
|
|||||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||||
|
|
||||||
const BASE_DSL = `
|
const BASE_DSL = `
|
||||||
definition Employee { id: string }
|
definition Employee { id: string? }
|
||||||
definition Doc { id: string }
|
definition Doc { id: string? }
|
||||||
fact *owns(user: Employee, doc: Doc)
|
fact *owns(user: Employee, doc: Doc)
|
||||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
`;
|
`;
|
||||||
@@ -102,8 +102,8 @@ describe('DSLRuntime provider-result caching', () => {
|
|||||||
|
|
||||||
it('invalidateProviderCache() clears all or per relation', async () => {
|
it('invalidateProviderCache() clears all or per relation', async () => {
|
||||||
const dsl = `
|
const dsl = `
|
||||||
definition Employee { id: string }
|
definition Employee { id: string? }
|
||||||
definition Doc { id: string }
|
definition Doc { id: string? }
|
||||||
fact *owns(user: Employee, doc: Doc)
|
fact *owns(user: Employee, doc: Doc)
|
||||||
fact *banned(user: Employee)
|
fact *banned(user: Employee)
|
||||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
@@ -151,8 +151,8 @@ describe('DSLRuntime provider-result caching', () => {
|
|||||||
|
|
||||||
it('uses the DSL-declared fact TTL (BEHAVES { ttl X })', async () => {
|
it('uses the DSL-declared fact TTL (BEHAVES { ttl X })', async () => {
|
||||||
const dsl = `
|
const dsl = `
|
||||||
definition Employee { id: string }
|
definition Employee { id: string? }
|
||||||
definition Doc { id: string }
|
definition Doc { id: string? }
|
||||||
fact *balance(user: Employee, amount: number) BEHAVES { ttl 1h }
|
fact *balance(user: Employee, amount: number) BEHAVES { ttl 1h }
|
||||||
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
||||||
`;
|
`;
|
||||||
@@ -173,4 +173,31 @@ describe('DSLRuntime provider-result caching', () => {
|
|||||||
await rt.check('u:1', 'can_spend', 'doc:9');
|
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||||
assert.equal(calls, 2, 're-invoked past the DSL-declared 1h TTL');
|
assert.equal(calls, 2, 're-invoked past the DSL-declared 1h TTL');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('cacheProviderResults:false bypasses the cache per check', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
let calls = 0;
|
||||||
|
rt.registerFact('owns', async () => { calls++; return 0.9; });
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
// Bypass forces a fresh retrieval without clearing the cache.
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9', { cacheProviderResults: false });
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
// Cache still intact for the next default check.
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('policy.cacheProviderResults:false disables caching globally', async () => {
|
||||||
|
const rt = makeRuntime({ policy: { cacheProviderResults: false } });
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
let calls = 0;
|
||||||
|
rt.registerFact('owns', async () => { calls++; return 0.9; });
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 2, 'no caching when disabled globally');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ import { Arbiter } from '@arbiter/core';
|
|||||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||||
|
|
||||||
const BASE_DSL = `
|
const BASE_DSL = `
|
||||||
definition Employee { id: string level: number active: boolean }
|
definition Employee { id: string? level: number? active: boolean? }
|
||||||
definition Doc { id: string created: timestamp }
|
definition Doc { id: string? created: timestamp? }
|
||||||
fact *owns(user: Employee, doc: Doc)
|
fact *owns(user: Employee, doc: Doc)
|
||||||
fact *banned(user: Employee)
|
fact *banned(user: Employee)
|
||||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
@@ -73,8 +73,8 @@ describe('DSLRuntime extended', () => {
|
|||||||
// edge for a DIFFERENT injectable fact that can_open also requires via
|
// edge for a DIFFERENT injectable fact that can_open also requires via
|
||||||
// composition — here we add a transitive requirement to prove the loop.
|
// composition — here we add a transitive requirement to prove the loop.
|
||||||
const dsl = `
|
const dsl = `
|
||||||
definition Employee { id: string }
|
definition Employee { id: string? }
|
||||||
definition Doc { id: string }
|
definition Doc { id: string? }
|
||||||
fact *owns(user: Employee, doc: Doc)
|
fact *owns(user: Employee, doc: Doc)
|
||||||
fact *granted(user: Employee, doc: Doc)
|
fact *granted(user: Employee, doc: Doc)
|
||||||
evidence base_read(user: Employee, doc: Doc) { owns(user, doc) }
|
evidence base_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
@@ -144,4 +144,25 @@ describe('DSLRuntime extended', () => {
|
|||||||
rt.updateNodeData('doc:9', { created: '2026-08-03T00:00:00Z' });
|
rt.updateNodeData('doc:9', { created: '2026-08-03T00:00:00Z' });
|
||||||
assert.throws(() => rt.addNode('doc:8', 'Doc', { created: {} }), /must be timestamp/);
|
assert.throws(() => rt.addNode('doc:8', 'Doc', { created: {} }), /must be timestamp/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('direct FACT checks consult the registered provider', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
let calls = 0;
|
||||||
|
rt.registerFact('owns', async () => { calls++; return 0.9; });
|
||||||
|
// Checking the fact directly (not via an evidence) must retrieve it.
|
||||||
|
const res = await rt.check('u:1', 'owns', 'doc:9');
|
||||||
|
assert.equal(res.possibility, 0.9);
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
assert.deepEqual(res.requiredFacts, ['owns']);
|
||||||
|
assert.deepEqual(res.providedFacts, ['owns']);
|
||||||
|
// Without a provider and without an edge, it reports the missing fact.
|
||||||
|
const rt2 = new DSLRuntime(new Arbiter()).compile(BASE_DSL, 'rt-fact-miss');
|
||||||
|
rt2.addNode('u:1', 'Employee', {});
|
||||||
|
rt2.addNode('doc:9', 'Doc', {});
|
||||||
|
const missed = await rt2.check('u:1', 'owns', 'doc:9');
|
||||||
|
assert.equal(missed.possibility, 0);
|
||||||
|
assert.deepEqual(missed.missingFacts, [{ relation: 'owns', reason: 'no_provider' }]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
/**
|
||||||
|
* tests/DSLRuntimeTyping.test.js — duration seconds, required fields, and
|
||||||
|
* type validation of insertions / updates / provider retrievals.
|
||||||
|
*
|
||||||
|
* - Duration literals now accept s/m/h/d/w: `BEHAVES { ttl 30s }` is 30s.
|
||||||
|
* - Definition fields are REQUIRED by default (`field: type`); `field: type?`
|
||||||
|
* marks a field optional. addNode enforces presence on insert.
|
||||||
|
* - Provider-returned edges are validated against the fact's declared typing:
|
||||||
|
* a value-carrying fact must return { value, possibility } with a value of
|
||||||
|
* the declared type, and possibilities must lie in [0, 1].
|
||||||
|
*/
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Arbiter } from '@arbiter/core';
|
||||||
|
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||||
|
|
||||||
|
describe('DSLRuntime typing', () => {
|
||||||
|
it('accepts seconds/minutes/hours/days/weeks in duration literals', async () => {
|
||||||
|
const dsl = `
|
||||||
|
definition Employee { id: string? }
|
||||||
|
definition Doc { id: string? }
|
||||||
|
fact *a(user: Employee, amount: number) BEHAVES { ttl 30s }
|
||||||
|
fact *b(user: Employee, amount: number) BEHAVES { ttl 2m }
|
||||||
|
fact *c(user: Employee, amount: number) BEHAVES { ttl 1h }
|
||||||
|
fact *d(user: Employee, amount: number) BEHAVES { ttl 3d }
|
||||||
|
fact *e(user: Employee, amount: number) BEHAVES { ttl 1w }
|
||||||
|
`;
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-units');
|
||||||
|
assert.equal(rt.relations.get('a').ttlMs, 30_000);
|
||||||
|
assert.equal(rt.relations.get('b').ttlMs, 120_000);
|
||||||
|
assert.equal(rt.relations.get('c').ttlMs, 3_600_000);
|
||||||
|
assert.equal(rt.relations.get('d').ttlMs, 259_200_000);
|
||||||
|
assert.equal(rt.relations.get('e').ttlMs, 604_800_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enforces required definition fields on node insert', () => {
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||||
|
definition Employee { id: string level: number active: boolean? }
|
||||||
|
`, 'rt-req');
|
||||||
|
// id and level are required (no `?`); active is optional.
|
||||||
|
assert.throws(() => rt.addNode('u:1', 'Employee', { level: 3 }), /missing required field 'Employee.id'/);
|
||||||
|
assert.throws(() => rt.addNode('u:2', 'Employee', { id: 'u:2' }), /missing required field 'Employee.level'/);
|
||||||
|
rt.addNode('u:3', 'Employee', { id: 'u:3', level: 5 }); // both required, no active -> ok
|
||||||
|
rt.addNode('u:4', 'Employee', { id: 'u:4', level: 5, active: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exposes requiredness in the schema snapshot', () => {
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||||
|
definition Employee { id: string level: number? }
|
||||||
|
`, 'rt-schema-req');
|
||||||
|
const employee = rt.getSchema().types.find(t => t.name === 'Employee');
|
||||||
|
assert.equal(employee.fields.find(f => f.name === 'id').required, true);
|
||||||
|
assert.equal(employee.fields.find(f => f.name === 'level').required, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates a provider-returned value against the declared value type', async () => {
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||||
|
definition Employee { id: string? }
|
||||||
|
definition Doc { id: string? }
|
||||||
|
fact *balance(user: Employee, amount: number)
|
||||||
|
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
||||||
|
`, 'rt-valuetype');
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.registerFact('balance', async () => ({ possibility: 1.0, value: 'high' }));
|
||||||
|
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /must be number/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires a value for a value-carrying fact (no bare-number shorthand)', async () => {
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||||
|
definition Employee { id: string? }
|
||||||
|
definition Doc { id: string? }
|
||||||
|
fact *balance(user: Employee, amount: number)
|
||||||
|
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
||||||
|
`, 'rt-valshape');
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.registerFact('balance', async () => 0.9);
|
||||||
|
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /value-carrying fact/);
|
||||||
|
rt.registerFact('balance', async () => ({ possibility: 1.0 })); // missing value
|
||||||
|
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /must supply a 'value'/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a provider-returned possibility outside [0, 1]', async () => {
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||||
|
definition Employee { id: string? }
|
||||||
|
definition Doc { id: string? }
|
||||||
|
fact *owns(user: Employee, doc: Doc)
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
`, 'rt-poss');
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.registerFact('owns', async () => ({ possibility: 2.0 }));
|
||||||
|
await assert.rejects(() => rt.check('u:1', 'can_read', 'doc:9'), /invalid possibility/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
/**
|
||||||
|
* tests/Recursion.test.js — bounded self-recursion (transitive closure).
|
||||||
|
*
|
||||||
|
* An evidence whose config contains a chain step referencing ITSELF is
|
||||||
|
* unrolled at compile time into a bounded transitive closure: a union of
|
||||||
|
* paths — base, hop+base, hop²+base, … — where `hop` is the recursive chain's
|
||||||
|
* steps before the self-reference and the depth N comes from the pattern's
|
||||||
|
* `limit N` (or the compiler's maxRecursionDepth default). The base (the
|
||||||
|
* evidence's non-recursive statements) is verified as a condition step at each
|
||||||
|
* path's terminal node.
|
||||||
|
*
|
||||||
|
* A pure recursion (no base case) cannot grant and is a compile-time error.
|
||||||
|
*/
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Arbiter } from '@arbiter/core';
|
||||||
|
import { DSLCompiler } from '../src/DSLCompiler.js';
|
||||||
|
|
||||||
|
const BASE = `
|
||||||
|
definition Employee { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact can_access(user: Employee, doc: Doc)
|
||||||
|
fact reports_to(user: Employee, manager: Employee)
|
||||||
|
`;
|
||||||
|
|
||||||
|
const RECURSIVE = `
|
||||||
|
evidence can_access_via(user: Employee, doc: Doc) {
|
||||||
|
can_access(user, doc)
|
||||||
|
reports_to(user, *m) { can_access_via(m, doc) } limit 3
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
function compile(dsl, name = 'rec') {
|
||||||
|
const arb = new Arbiter();
|
||||||
|
const result = new DSLCompiler(arb).compile(dsl, name);
|
||||||
|
return { arb, result };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Bounded self-recursion', () => {
|
||||||
|
it('unrolls into a union of base + bounded hop chains', () => {
|
||||||
|
const { arb, result } = compile(BASE + RECURSIVE);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
const cfg = arb.relationConfigs.get('can_access_via');
|
||||||
|
assert.equal(cfg.type, 'logical');
|
||||||
|
assert.ok(cfg.union, 'recursion should compile to a union of paths');
|
||||||
|
// base + 3 hops (limit 3)
|
||||||
|
assert.equal(cfg.union.rules.length, 4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('grants through the base case and through multi-hop chains', () => {
|
||||||
|
const { arb, result } = compile(BASE + RECURSIVE);
|
||||||
|
assert.ok(result.success);
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
// base
|
||||||
|
arb.addRelation('u:1', 'can_access', 'doc:9', { possibility: 1.0 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 1.0);
|
||||||
|
// 1-hop: u -> m -> doc
|
||||||
|
arb.removeRelation('u:1', 'can_access', 'doc:9');
|
||||||
|
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m:1', 'can_access', 'doc:9', { possibility: 0.7 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.7);
|
||||||
|
// 2-hop: u -> m -> m2 -> doc
|
||||||
|
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m2:1', 'can_access', 'doc:9', { possibility: 0.5 });
|
||||||
|
// union takes the best path: max(0.7, 0.5) = 0.7
|
||||||
|
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.7);
|
||||||
|
// 2-hop alone (remove the 1-hop can_access)
|
||||||
|
arb.removeRelation('m:1', 'can_access', 'doc:9');
|
||||||
|
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enforces the recursion depth limit', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${BASE}
|
||||||
|
evidence can_access_via(user: Employee, doc: Doc) {
|
||||||
|
can_access(user, doc)
|
||||||
|
reports_to(user, *m) { can_access_via(m, doc) } limit 2
|
||||||
|
}
|
||||||
|
`);
|
||||||
|
assert.ok(result.success);
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('m3:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m2:1', 'reports_to', 'm3:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m2:1', 'can_access', 'doc:9', { possibility: 0.5 }); // 2 hops
|
||||||
|
arb.addRelation('m3:1', 'can_access', 'doc:9', { possibility: 0.9 }); // 3 hops
|
||||||
|
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.5);
|
||||||
|
arb.removeRelation('m2:1', 'can_access', 'doc:9');
|
||||||
|
// only the 3-hop path remains — beyond the limit -> denied
|
||||||
|
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the compiler maxRecursionDepth default when no limit is given', () => {
|
||||||
|
const dsl = `
|
||||||
|
${BASE}
|
||||||
|
evidence can_access_via(user: Employee, doc: Doc) {
|
||||||
|
can_access(user, doc)
|
||||||
|
reports_to(user, *m) { can_access_via(m, doc) }
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const { arb, result } = compile(dsl);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
// default depth 3 -> base + 3 hops
|
||||||
|
assert.equal(arb.relationConfigs.get('can_access_via').union.rules.length, 4);
|
||||||
|
// a deeper path (4 hops) is not granted
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('m3:1', 'Employee'); arb.addNode('m4:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m2:1', 'reports_to', 'm3:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m3:1', 'reports_to', 'm4:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('m4:1', 'can_access', 'doc:9', { possibility: 1.0 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0, '4-hop path exceeds default depth');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a pure recursion with no base case', () => {
|
||||||
|
const { result } = compile(`
|
||||||
|
${BASE}
|
||||||
|
evidence can_access_via(user: Employee, doc: Doc) {
|
||||||
|
reports_to(user, *m) { can_access_via(m, doc) } limit 3
|
||||||
|
}
|
||||||
|
`);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /no base case/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps mutual (non-self) cycles a compile error', () => {
|
||||||
|
const { result } = compile(`
|
||||||
|
${BASE}
|
||||||
|
fact peer(user: Employee, other: Employee)
|
||||||
|
evidence a(user: Employee, doc: Doc) { peer(user, *p) { b(p, doc) } }
|
||||||
|
evidence b(user: Employee, doc: Doc) { peer(user, *p) { a(p, doc) } }
|
||||||
|
`);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user