Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9111c4b20d | |||
| aa38fbfd8c | |||
| ad365a65a9 | |||
| 6214780244 | |||
| 3ace783a59 |
Generated
+6
-6
@@ -1,15 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.4.0",
|
"version": "1.6.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.4.0",
|
"version": "1.6.0",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arbiter/core": "^1.0.3"
|
"@arbiter/core": "^1.0.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rigor/core": "^3.1.0",
|
"@rigor/core": "^3.1.0",
|
||||||
@@ -17,9 +17,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@arbiter/core": {
|
"node_modules/@arbiter/core": {
|
||||||
"version": "1.0.3",
|
"version": "1.0.4",
|
||||||
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.3/core-1.0.3.tgz",
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.4/core-1.0.4.tgz",
|
||||||
"integrity": "sha512-MCXxyeWBoYjEJMrdO8N8q9uEdX7JgDvwRH39D+8x65zFz+JCNWIQ8H4DgsP2rgF+yzv/cdVH4BX9PfFt6i0ftQ==",
|
"integrity": "sha512-1zXy3mZACjwELptsV8QpYvZJmMU7BhUQ4FsKNfp3/oJDwjfMqAImcAF3mJ+HNZpQnLQXScmELTwow5VduvN27g==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tenere/pltc-core": "^0.6.3",
|
"@tenere/pltc-core": "^0.6.3",
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.5.0",
|
"version": "1.10.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",
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
"generate:parser": "node scripts/generate-parser.js"
|
"generate:parser": "node scripts/generate-parser.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arbiter/core": "^1.0.3"
|
"@arbiter/core": "^1.0.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rigor/core": "^3.1.0",
|
"@rigor/core": "^3.1.0",
|
||||||
|
|||||||
@@ -486,15 +486,22 @@ export class RuleGenerator {
|
|||||||
reverse: false
|
reverse: false
|
||||||
};
|
};
|
||||||
|
|
||||||
// Subject-scoped (unary) call: the predicate call's args omit the
|
// Unary predicate calls check the relation as a self-edge on the call's
|
||||||
// evidence's object parameter (user_risk(user, 1) inside a binary
|
// subject entity (the graph stores unary facts as self-edges). The subject
|
||||||
// evidence) → check the relation on the subject itself.
|
// entity may be the evidence's SUBJECT or its OBJECT parameter — mark the
|
||||||
|
// matching rewrite flag.
|
||||||
const evidenceParams = (evidence && evidence.params) || [];
|
const evidenceParams = (evidence && evidence.params) || [];
|
||||||
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||||
const argName = a => a && (a.name !== undefined ? a.name : a.value);
|
const argName = a => a && (a.name !== undefined ? a.name : a.value);
|
||||||
if (objectVar !== undefined && !(predicate.arguments || []).some(a => argName(a) === objectVar)) {
|
const args = predicate.arguments || [];
|
||||||
|
if (objectVar !== undefined) {
|
||||||
|
const hasObjectArg = args.some(a => argName(a) === objectVar);
|
||||||
|
if (args.length === 1 && argName(args[0]) === objectVar) {
|
||||||
|
rule._subjectIsObject = true;
|
||||||
|
} else if (!hasObjectArg) {
|
||||||
rule._subjectAsObject = true;
|
rule._subjectAsObject = true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return rule;
|
return rule;
|
||||||
}
|
}
|
||||||
@@ -1082,7 +1089,6 @@ export class RuleGenerator {
|
|||||||
const out = [];
|
const out = [];
|
||||||
for (let idx = 0; idx < steps.length; idx++) {
|
for (let idx = 0; idx < steps.length; idx++) {
|
||||||
const step = steps[idx];
|
const step = steps[idx];
|
||||||
const isLast = idx === steps.length - 1;
|
|
||||||
const stepName = typeof step === 'string' ? step : step.relation;
|
const stepName = typeof step === 'string' ? step : step.relation;
|
||||||
if (stepName && this.evidenceNames.has(stepName)) {
|
if (stepName && this.evidenceNames.has(stepName)) {
|
||||||
if (stack.has(stepName)) {
|
if (stack.has(stepName)) {
|
||||||
@@ -1105,15 +1111,20 @@ export class RuleGenerator {
|
|||||||
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (isLast) {
|
if (resolved.type === 'relational_comparator' && idx !== steps.length - 1) {
|
||||||
// Condition-gated final hop: inline the evidence's config as a
|
// A comparator compares values at (src, candidate) but provides no
|
||||||
// rule step the engine evaluates at (intermediate, object).
|
// candidate set — it cannot enumerate intermediate nodes, so only
|
||||||
out.push({ rule: this._deepCloneRule(resolved), conditionStep: true });
|
// 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;
|
continue;
|
||||||
}
|
}
|
||||||
this.errors.push(`Chain step '${stepName}' references an evidence with type '${resolved.type || 'logical'}'. ` +
|
// Condition step: inline the evidence's config as a rule step. As the
|
||||||
'Only the final chain step may reference a defeasible/logical evidence (a condition-gated hop); intermediate steps must be edge traversals.');
|
// FINAL step the engine verifies it at (intermediate, object); as an
|
||||||
out.push(step);
|
// INTERMEDIATE step the engine EXPANDS it from the current node
|
||||||
|
// (rule-based reachability) and continues from each discovered node.
|
||||||
|
out.push({ rule: this._deepCloneRule(resolved), conditionStep: true });
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1280,16 +1291,23 @@ export class RuleGenerator {
|
|||||||
reverse: false
|
reverse: false
|
||||||
};
|
};
|
||||||
|
|
||||||
// Subject-scoped (unary) predicate call: the call's variable args omit the
|
// Unary predicate calls check the relation as a self-edge on the call's
|
||||||
// evidence's object parameter (banned(user) inside can_open(user, doc)).
|
// subject entity (the graph stores unary facts as self-edges). The subject
|
||||||
// Mark _subjectAsObject so the engine checks the relation on the subject
|
// entity may be the evidence's SUBJECT or its OBJECT parameter:
|
||||||
// itself — the unary fact's self-edge — instead of (subject, object).
|
// banned(user) in can_open(user, doc) -> self-edge on the user
|
||||||
|
// trusted(other) in peer_trusted(user, other) -> self-edge on the other
|
||||||
|
// Mark _subjectAsObject (subject-as-object on the subject entity) or
|
||||||
|
// _subjectIsObject (the subject entity IS the object parameter) so the
|
||||||
|
// engine rewrites the pair accordingly.
|
||||||
const evidenceParams = (evidence && evidence.params) || [];
|
const evidenceParams = (evidence && evidence.params) || [];
|
||||||
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||||
|
const argName = a => a && (a.name !== undefined ? a.name : a.value);
|
||||||
if (objectVar !== undefined) {
|
if (objectVar !== undefined) {
|
||||||
const hasObjectArg = (expression.args || []).some(a =>
|
const args = expression.args || [];
|
||||||
a && a.type === 'Variable' && a.name === objectVar);
|
const hasObjectArg = args.some(a => a && a.type === 'Variable' && a.name === objectVar);
|
||||||
if (!hasObjectArg) {
|
if (args.length === 1 && argName(args[0]) === objectVar) {
|
||||||
|
rule._subjectIsObject = true;
|
||||||
|
} else if (!hasObjectArg) {
|
||||||
rule._subjectAsObject = true;
|
rule._subjectAsObject = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-2
@@ -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
|
||||||
@@ -248,6 +251,13 @@ BehaviorAnnotation
|
|||||||
= "BEHAVES" __ "AS" __ behavior:("edge" / "transitive" / "hierarchical" / "symmetrical_graph") {
|
= "BEHAVES" __ "AS" __ behavior:("edge" / "transitive" / "hierarchical" / "symmetrical_graph") {
|
||||||
return { type: "BehaviorAnnotation", behavior };
|
return { type: "BehaviorAnnotation", behavior };
|
||||||
}
|
}
|
||||||
|
/ "BEHAVES" __ "{" _ behavior:(TTLBehavior) _ "}" {
|
||||||
|
// Fact-level freshness: `fact balance(user, amount) BEHAVES { ttl 1h }`
|
||||||
|
// declares the relation's value-freshness window, which the runtime uses
|
||||||
|
// as the provider-result cache TTL. The behavior is wrapped like the
|
||||||
|
// `BEHAVES AS` form so consumers read `behavior.behaviorType`.
|
||||||
|
return { type: "BehaviorAnnotation", behavior };
|
||||||
|
}
|
||||||
|
|
||||||
FactProperty
|
FactProperty
|
||||||
= "transitive" { return "transitive"; }
|
= "transitive" { return "transitive"; }
|
||||||
@@ -385,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 --
|
||||||
|
|||||||
+1057
-980
File diff suppressed because it is too large
Load Diff
+209
-33
@@ -47,8 +47,27 @@ export class DSLRuntime {
|
|||||||
this.strictTypes = options.policy?.strictTypes !== false;
|
this.strictTypes = options.policy?.strictTypes !== false;
|
||||||
this.program = null;
|
this.program = null;
|
||||||
this.types = new Map(); // typeName -> { fields: Map(field -> {type,isArray}) }
|
this.types = new Map(); // typeName -> { fields: Map(field -> {type,isArray}) }
|
||||||
this.relations = new Map(); // relation -> { kind: 'fact'|'evidence', params, injectable }
|
this.relations = new Map(); // relation -> { kind: 'fact'|'evidence', params, injectable, ttlMs }
|
||||||
this.dependsOn = new Map(); // evidence relation -> Set(fact relations)
|
this.dependsOn = new Map(); // evidence relation -> Set(fact relations)
|
||||||
|
|
||||||
|
// Provider-result cache: relation|subject|object -> { edges, fetchedAt }.
|
||||||
|
// Provider retrieval is a data-store read (balance lookups, session
|
||||||
|
// checks, etc.) — caching results with a time expiry avoids hammering the
|
||||||
|
// underlying store on every check. The clock is injectable (default wall
|
||||||
|
// clock) and drives cache freshness, mirroring the core's unpinned-clock
|
||||||
|
// contract.
|
||||||
|
this.providerCache = new Map();
|
||||||
|
this.clock = typeof options.clock === 'function' ? options.clock : (() => Date.now());
|
||||||
|
// Default provider-result TTL in ms (0 disables caching).
|
||||||
|
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.
|
||||||
|
this.factTTLs = new Map(Object.entries(options.factTTLs || {}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -84,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()]
|
||||||
@@ -113,16 +133,18 @@ 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 });
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const fact of this.program.facts || []) {
|
for (const fact of this.program.facts || []) {
|
||||||
|
const ttlMs = this._ttlFromBehavior(fact.behavior);
|
||||||
this.relations.set(fact.name, {
|
this.relations.set(fact.name, {
|
||||||
kind: 'fact',
|
kind: 'fact',
|
||||||
params: (fact.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
|
params: (fact.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
|
||||||
injectable: !!fact.injectable
|
injectable: !!fact.injectable,
|
||||||
|
ttlMs
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,12 +218,15 @@ export class DSLRuntime {
|
|||||||
throw new Error(`DSLRuntime: provider for '${relation}' must be a function`);
|
throw new Error(`DSLRuntime: provider for '${relation}' must be a function`);
|
||||||
}
|
}
|
||||||
this.factProviders[relation] = provider;
|
this.factProviders[relation] = provider;
|
||||||
|
// A new provider supersedes any cached retrieval for this fact.
|
||||||
|
this.invalidateProviderCache(relation);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove a registered provider. */
|
/** Remove a registered provider. */
|
||||||
unregisterFact(relation) {
|
unregisterFact(relation) {
|
||||||
delete this.factProviders[relation];
|
delete this.factProviders[relation];
|
||||||
|
this.invalidateProviderCache(relation);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,6 +235,138 @@ export class DSLRuntime {
|
|||||||
return Object.keys(this.factProviders);
|
return Object.keys(this.factProviders);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Provider-result caching
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set a per-fact provider-result TTL (ms). Overrides the policy default and
|
||||||
|
* the DSL-declared ttl behavior for that fact.
|
||||||
|
*/
|
||||||
|
setFactTTL(relation, ms) {
|
||||||
|
this.factTTLs.set(relation, ms);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The effective provider-result TTL (ms) for a fact: DSL > per-fact > policy default. */
|
||||||
|
_ttlFor(relation) {
|
||||||
|
if (this.factTTLs.has(relation)) return this.factTTLs.get(relation);
|
||||||
|
const meta = this.relations.get(relation);
|
||||||
|
if (meta && meta.ttlMs != null) return meta.ttlMs;
|
||||||
|
return this.defaultProviderCacheTTL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invalidate cached provider results — all, or for a single relation.
|
||||||
|
* Callers use this when the underlying data store changes out-of-band.
|
||||||
|
*/
|
||||||
|
invalidateProviderCache(relation) {
|
||||||
|
if (relation === undefined) {
|
||||||
|
this.providerCache.clear();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
const prefix = `${relation}\u0000`;
|
||||||
|
for (const key of [...this.providerCache.keys()]) {
|
||||||
|
if (key.startsWith(prefix)) this.providerCache.delete(key);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
_providerCacheKey(relation, subject, object) {
|
||||||
|
return `${relation}\u0000${subject}\u0000${object}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
_providerCacheGet(relation, subject, object) {
|
||||||
|
const ttl = this._ttlFor(relation);
|
||||||
|
if (ttl <= 0) return null;
|
||||||
|
const entry = this.providerCache.get(this._providerCacheKey(relation, subject, object));
|
||||||
|
if (!entry) return null;
|
||||||
|
if (this.clock() - entry.fetchedAt >= ttl) {
|
||||||
|
this.providerCache.delete(this._providerCacheKey(relation, subject, object));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
_providerCacheSet(relation, subject, object, edges) {
|
||||||
|
const ttl = this._ttlFor(relation);
|
||||||
|
if (ttl <= 0) return;
|
||||||
|
this.providerCache.set(this._providerCacheKey(relation, subject, object), {
|
||||||
|
edges,
|
||||||
|
fetchedAt: this.clock()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convert a DSL `BEHAVES { ttl <duration> }` behavior (or `BEHAVES AS`) into ms. */
|
||||||
|
_ttlFromBehavior(behavior) {
|
||||||
|
if (!behavior || typeof behavior !== 'object') return null;
|
||||||
|
const b = behavior.behavior || behavior;
|
||||||
|
if (b && b.behaviorType === 'ttl' && b.duration) {
|
||||||
|
const n = parseInt(String(b.duration.value), 10);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize a provider result (boolean / number / { possibility, value } /
|
||||||
|
* 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
|
||||||
|
* 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, fact, user, object) {
|
||||||
|
const edges = Array.isArray(result) ? result : [result];
|
||||||
|
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
||||||
|
const isValueFact = factMeta.params.length >= 2 && this._isValueType(secondParamType);
|
||||||
|
const defaultDst = isValueFact ? user : (factMeta.params.length >= 2 ? object : user);
|
||||||
|
const label = `provider for '${fact}'`;
|
||||||
|
const out = [];
|
||||||
|
for (const edge of edges) {
|
||||||
|
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
||||||
|
? (() => {
|
||||||
|
if (isValueFact) {
|
||||||
|
throw new Error(`DSLRuntime: ${label} is a value-carrying fact — return { value, possibility } (got a bare ${typeof edge === 'number' ? 'number' : 'boolean'})`);
|
||||||
|
}
|
||||||
|
const possibility = edge === true ? 1 : edge;
|
||||||
|
this._checkPossibility(possibility, label);
|
||||||
|
return { src: user, dst: defaultDst, possibility };
|
||||||
|
})()
|
||||||
|
: (() => {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
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
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -278,11 +435,18 @@ 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) {
|
||||||
throw new Error(`DSLRuntime: unknown type '${typeName}'`);
|
throw new Error(`DSLRuntime: unknown type '${typeName}'`);
|
||||||
}
|
}
|
||||||
|
// A graph mutation can make previously-retrieved facts stale.
|
||||||
|
this.invalidateProviderCache();
|
||||||
return this.arbiter.addNode(key, typeName, data);
|
return this.arbiter.addNode(key, typeName, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,11 +461,13 @@ export class DSLRuntime {
|
|||||||
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
this.invalidateProviderCache();
|
||||||
return this.arbiter.updateNodeData(key, data);
|
return this.arbiter.updateNodeData(key, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove a node (passthrough to the arbiter's node manager). */
|
/** Remove a node (passthrough to the arbiter's node manager). */
|
||||||
removeNode(key) {
|
removeNode(key) {
|
||||||
|
this.invalidateProviderCache();
|
||||||
if (this.arbiter.nodeManager && typeof this.arbiter.nodeManager.removeNode === 'function') {
|
if (this.arbiter.nodeManager && typeof this.arbiter.nodeManager.removeNode === 'function') {
|
||||||
return this.arbiter.nodeManager.removeNode(key);
|
return this.arbiter.nodeManager.removeNode(key);
|
||||||
}
|
}
|
||||||
@@ -327,6 +493,7 @@ export class DSLRuntime {
|
|||||||
if (meta) {
|
if (meta) {
|
||||||
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
||||||
}
|
}
|
||||||
|
this.invalidateProviderCache();
|
||||||
return this.arbiter.addRelation(src, relation, dst, attrs);
|
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,12 +505,14 @@ export class DSLRuntime {
|
|||||||
if (meta) {
|
if (meta) {
|
||||||
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
||||||
}
|
}
|
||||||
|
this.invalidateProviderCache();
|
||||||
this.arbiter.removeRelation(src, relation, dst);
|
this.arbiter.removeRelation(src, relation, dst);
|
||||||
return this.arbiter.addRelation(src, relation, dst, attrs);
|
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove a relation edge (passthrough to the arbiter). */
|
/** Remove a relation edge (passthrough to the arbiter). */
|
||||||
removeRelation(src, relation, dst) {
|
removeRelation(src, relation, dst) {
|
||||||
|
this.invalidateProviderCache();
|
||||||
return this.arbiter.removeRelation(src, relation, dst);
|
return this.arbiter.removeRelation(src, relation, dst);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -431,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 = [];
|
||||||
@@ -449,15 +624,27 @@ 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];
|
||||||
if (typeof provider !== 'function') {
|
|
||||||
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
// Provider-result cache: reuse fresh edges without re-invoking the
|
||||||
satisfied.add(fact);
|
// data store. A cached entry stores the NORMALIZED edges. Per-check
|
||||||
continue;
|
// provider overrides are one-off observations — they bypass the cache
|
||||||
}
|
// entirely (no read, no write) so a fresh override is never masked by
|
||||||
|
// 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 cacheHit = (cachingEnabled && !isPerCheckOverride) ? this._providerCacheGet(fact, user, object) : null;
|
||||||
|
let edges = null;
|
||||||
|
let fromCache = false;
|
||||||
|
if (cacheHit) {
|
||||||
|
edges = cacheHit.edges;
|
||||||
|
fromCache = true;
|
||||||
|
} else if (typeof provider === 'function') {
|
||||||
let result = null;
|
let result = null;
|
||||||
let error = null;
|
let error = null;
|
||||||
try {
|
try {
|
||||||
@@ -482,33 +669,22 @@ export class DSLRuntime {
|
|||||||
satisfied.add(fact);
|
satisfied.add(fact);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const edges = Array.isArray(result) ? result : [result];
|
edges = this._normalizeProviderEdges(result, factMeta, fact, user, object);
|
||||||
// Resolve the edge destination the same way the DSL declares the fact:
|
if (cachingEnabled && !isPerCheckOverride) this._providerCacheSet(fact, user, object, edges);
|
||||||
// - unary fact (1 param) -> self-edge on the subject
|
} else {
|
||||||
// - value fact (2nd param value) -> self-edge on the subject carrying the value
|
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
||||||
// - binary entity fact -> subject → object
|
satisfied.add(fact);
|
||||||
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
continue;
|
||||||
const defaultDst = factMeta.params.length >= 2 && this._isValueType(secondParamType)
|
}
|
||||||
? user
|
|
||||||
: (factMeta.params.length >= 2 ? object : user);
|
|
||||||
for (const edge of edges) {
|
|
||||||
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
|
||||||
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
|
||||||
: {
|
|
||||||
...(edge.relation ? { relation: edge.relation } : {}),
|
|
||||||
src: edge.src ?? user,
|
|
||||||
dst: edge.dst ?? defaultDst,
|
|
||||||
possibility: edge.possibility ?? 1,
|
|
||||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
|
||||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
|
||||||
};
|
|
||||||
// A provider may return edges for relations other than its own; the
|
// A provider may return edges for relations other than its own; the
|
||||||
// injected relation names satisfy those facts too (fixed point).
|
// injected relation names satisfy those facts too (fixed point).
|
||||||
|
for (const normalized of edges) {
|
||||||
const injectedRelation = normalized.relation ?? fact;
|
const injectedRelation = normalized.relation ?? fact;
|
||||||
partialRelations.push({ relation: injectedRelation, ...normalized });
|
partialRelations.push({ relation: injectedRelation, ...normalized });
|
||||||
satisfied.add(injectedRelation);
|
satisfied.add(injectedRelation);
|
||||||
}
|
}
|
||||||
injectedRelations.push({ relation: fact, edges: edges.length, round });
|
injectedRelations.push({ relation: fact, edges: edges.length, round, cacheHit: fromCache });
|
||||||
newRelationsThisRound += edges.length;
|
newRelationsThisRound += edges.length;
|
||||||
satisfied.add(fact);
|
satisfied.add(fact);
|
||||||
}
|
}
|
||||||
@@ -527,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
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -98,4 +98,32 @@ describe('Chain condition step (logical evidence as final hop)', () => {
|
|||||||
// max over paths: min(0.5,0.7)=0.5, min(1.0,0.8)=0.8 -> 0.8
|
// max over paths: min(0.5,0.7)=0.5, min(1.0,0.8)=0.8 -> 0.8
|
||||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.8);
|
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.8);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('expands an INTERMEDIATE condition step via rule-based reachability', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
definition Employee { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact peer(user: Employee, other: Employee)
|
||||||
|
fact trusted(other: Employee)
|
||||||
|
fact can_read(user: Employee, doc: Doc)
|
||||||
|
evidence peer_trusted(user: Employee, other: Employee) { WHEN peer(user, other) UNLESS trusted(other) }
|
||||||
|
evidence can_access(user: Employee, doc: Doc) { peer_trusted(user, *p) { can_read(p, doc) } }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
const steps = arb.relationConfigs.get('can_access').steps;
|
||||||
|
assert.equal(steps[0].conditionStep, true);
|
||||||
|
assert.equal(steps[0].rule.type, 'logical');
|
||||||
|
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('p:1', 'Employee'); arb.addNode('p:2', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'peer', 'p:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('u:1', 'peer', 'p:2', { possibility: 1.0 });
|
||||||
|
arb.addRelation('p:1', 'trusted', 'p:1', { possibility: 1.0 }); // p:1 filtered
|
||||||
|
arb.addRelation('p:1', 'can_read', 'doc:9', { possibility: 0.9 });
|
||||||
|
arb.addRelation('p:2', 'can_read', 'doc:9', { possibility: 0.7 });
|
||||||
|
// only untrusted peer p:2 survives the intermediate condition -> 0.7
|
||||||
|
assert.equal(arb.check('u:1', 'can_access', 'doc:9').possibility, 0.7);
|
||||||
|
// trusting p:2 too removes all intermediates -> 0
|
||||||
|
arb.addRelation('p:2', 'trusted', 'p:2', { possibility: 1.0 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_access', 'doc:9').possibility, 0);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
/**
|
||||||
|
* tests/DSLRuntimeCache.test.js — provider-result caching with time expiry.
|
||||||
|
*
|
||||||
|
* Registered providers retrieve missing facts from a data store; caching the
|
||||||
|
* retrieval avoids hammering the store on repeated checks. TTL resolution:
|
||||||
|
* DSL-declared `BEHAVES { ttl <duration> }` on a fact > per-fact setFactTTL >
|
||||||
|
* policy default (30s). Per-check factProviders are cache-transparent (one-off
|
||||||
|
* observations: no cache read, no cache write). Registering a provider or
|
||||||
|
* mutating the graph invalidates the cache.
|
||||||
|
*/
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Arbiter } from '@arbiter/core';
|
||||||
|
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||||
|
|
||||||
|
const BASE_DSL = `
|
||||||
|
definition Employee { id: string? }
|
||||||
|
definition Doc { id: string? }
|
||||||
|
fact *owns(user: Employee, doc: Doc)
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
`;
|
||||||
|
|
||||||
|
function makeRuntime(options = {}) {
|
||||||
|
let t = 0;
|
||||||
|
const clock = () => t;
|
||||||
|
const rt = new DSLRuntime(new Arbiter(), { clock, ...options }).compile(BASE_DSL, 'rt-cache');
|
||||||
|
rt._test_advance = (ms) => { t += ms; };
|
||||||
|
return rt;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('DSLRuntime provider-result caching', () => {
|
||||||
|
it('reuses a registered provider result within the TTL', 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');
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 1, 'provider should be invoked once within TTL');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('re-invokes the provider after the TTL expires', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.setFactTTL('owns', 100);
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
let calls = 0;
|
||||||
|
let value = 0.9;
|
||||||
|
rt.registerFact('owns', async () => { calls++; return value; });
|
||||||
|
const first = await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(first.possibility, 0.9);
|
||||||
|
rt._test_advance(50);
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9'); // within TTL -> cached
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
rt._test_advance(60); // past TTL (110 total)
|
||||||
|
value = 0.4;
|
||||||
|
const after = await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
assert.equal(after.possibility, 0.4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('per-check factProviders override the cache (fresh observation)', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.registerFact('owns', async () => 0.9);
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
// Per-check override is cache-transparent: it must NOT be masked by the
|
||||||
|
// cached 0.9, and it must NOT overwrite the cached value.
|
||||||
|
const over = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||||
|
factProviders: { owns: async () => 0.2 }
|
||||||
|
});
|
||||||
|
assert.equal(over.possibility, 0.2);
|
||||||
|
const next = await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(next.possibility, 0.9, 'registered provider cache untouched by per-check override');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('registerFact invalidates the cached result for that relation', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.registerFact('owns', async () => 0.9);
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
rt.registerFact('owns', async () => 0.3); // re-register -> cache invalidated
|
||||||
|
const res = await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(res.possibility, 0.3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates cached results on graph mutations', 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);
|
||||||
|
rt.addRelation('u:1', 'owns', 'doc:9', { possibility: 1.0 }); // mutation clears cache
|
||||||
|
const res = await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 2, 'graph mutation should invalidate the provider cache');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidateProviderCache() clears all or per relation', async () => {
|
||||||
|
const dsl = `
|
||||||
|
definition Employee { id: string? }
|
||||||
|
definition Doc { id: string? }
|
||||||
|
fact *owns(user: Employee, doc: Doc)
|
||||||
|
fact *banned(user: Employee)
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS banned(user) }
|
||||||
|
`;
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-cache2');
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
let ownsCalls = 0, bannedCalls = 0;
|
||||||
|
rt.registerFact('owns', async () => { ownsCalls++; return 0.9; });
|
||||||
|
rt.registerFact('banned', async () => { bannedCalls++; return 0; });
|
||||||
|
await rt.check('u:1', 'can_open', 'doc:9');
|
||||||
|
assert.equal(ownsCalls, 1);
|
||||||
|
assert.equal(bannedCalls, 1);
|
||||||
|
// Invalidate a non-dependency relation: can_open's cache (owns+banned) survives.
|
||||||
|
rt.invalidateProviderCache('does_not_exist');
|
||||||
|
await rt.check('u:1', 'can_open', 'doc:9');
|
||||||
|
assert.equal(ownsCalls, 1);
|
||||||
|
assert.equal(bannedCalls, 1);
|
||||||
|
// Invalidate owns only: banned survives, owns re-fetched.
|
||||||
|
rt.invalidateProviderCache('owns');
|
||||||
|
await rt.check('u:1', 'can_open', 'doc:9');
|
||||||
|
assert.equal(ownsCalls, 2, 'owns cache cleared by per-relation invalidation');
|
||||||
|
assert.equal(bannedCalls, 1, 'banned cache survives per-relation invalidation');
|
||||||
|
// Clear all.
|
||||||
|
rt.invalidateProviderCache();
|
||||||
|
await rt.check('u:1', 'can_open', 'doc:9');
|
||||||
|
assert.equal(bannedCalls, 2, 'full invalidation clears every relation');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('policy default TTL applies when no per-fact TTL is set', async () => {
|
||||||
|
const rt = makeRuntime({ policy: { providerCacheTTL: 50 } });
|
||||||
|
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');
|
||||||
|
rt._test_advance(40);
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 1, 'within 50ms policy TTL -> cached');
|
||||||
|
rt._test_advance(20);
|
||||||
|
await rt.check('u:1', 'can_read', 'doc:9');
|
||||||
|
assert.equal(calls, 2, 'past 50ms policy TTL -> re-invoked');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the DSL-declared fact TTL (BEHAVES { ttl X })', async () => {
|
||||||
|
const dsl = `
|
||||||
|
definition Employee { id: string? }
|
||||||
|
definition Doc { id: string? }
|
||||||
|
fact *balance(user: Employee, amount: number) BEHAVES { ttl 1h }
|
||||||
|
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
||||||
|
`;
|
||||||
|
let t = 0;
|
||||||
|
const rt = new DSLRuntime(new Arbiter(), { clock: () => t }).compile(dsl, 'rt-dsl-ttl');
|
||||||
|
// The DSL declares a 1h TTL for the balance fact.
|
||||||
|
assert.equal(rt.relations.get('balance').ttlMs, 3600_000);
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
let calls = 0;
|
||||||
|
rt.registerFact('balance', async () => { calls++; return { possibility: 1.0, value: 50 }; });
|
||||||
|
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
t += 60 * 60 * 1000 - 1; // just under 1h
|
||||||
|
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||||
|
assert.equal(calls, 1, 'cached within DSL-declared 1h TTL');
|
||||||
|
t += 2;
|
||||||
|
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||||
|
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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -33,8 +33,11 @@ const FACTS = `
|
|||||||
fact owner(group: Group, doc: Doc)
|
fact owner(group: Group, doc: Doc)
|
||||||
fact granted(user: Employee, doc: Doc)
|
fact granted(user: Employee, doc: Doc)
|
||||||
fact group_perm(group: Group, doc: Doc)
|
fact group_perm(group: Group, doc: Doc)
|
||||||
fact banned(user: Employee)
|
|
||||||
fact group_banned(group: Group)
|
fact group_banned(group: Group)
|
||||||
|
fact banned(user: Employee)
|
||||||
|
fact peer(user: Employee, other: Employee)
|
||||||
|
fact trusted(other: Employee)
|
||||||
|
fact doc_read(user: Employee, doc: Doc)
|
||||||
fact mfa(user: Employee)
|
fact mfa(user: Employee)
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -142,6 +145,20 @@ function buildProgram(kind, ps) {
|
|||||||
oracle = Math.min(pm, pv * (1 - pb));
|
oracle = Math.min(pm, pv * (1 - pb));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case 'chain_intermediate_condition': {
|
||||||
|
// peer_trusted (a defeasible evidence) as an INTERMEDIATE chain step:
|
||||||
|
// the engine expands it from the source (peer edges filtered by the
|
||||||
|
// trusted defeater) then continues to can_read. Oracle = min of the
|
||||||
|
// surviving peer leg and the read leg.
|
||||||
|
const [pp, pt, pr] = ps;
|
||||||
|
evidence = `evidence peer_trusted(user: Employee, other: Employee) { WHEN peer(user, other) UNLESS trusted(other) }
|
||||||
|
evidence can_via(user: Employee, doc: Doc) { peer_trusted(user, *p) { doc_read(p, doc) } }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'peer', dst: 'p:1', possibility: pp });
|
||||||
|
edges.push({ src: 'p:1', relation: 'trusted', dst: 'p:1', possibility: pt });
|
||||||
|
edges.push({ src: 'p:1', relation: 'doc_read', dst: 'doc:9', possibility: pr });
|
||||||
|
oracle = Math.min(pp * (1 - pt), pr);
|
||||||
|
break;
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
throw new Error(`unknown construct: ${kind}`);
|
throw new Error(`unknown construct: ${kind}`);
|
||||||
}
|
}
|
||||||
@@ -162,6 +179,10 @@ function runCheck({ kind, ps }) {
|
|||||||
arbiter.addNode('u:1', 'Employee');
|
arbiter.addNode('u:1', 'Employee');
|
||||||
arbiter.addNode('g:1', 'Group');
|
arbiter.addNode('g:1', 'Group');
|
||||||
arbiter.addNode('doc:9', 'Doc');
|
arbiter.addNode('doc:9', 'Doc');
|
||||||
|
for (const e of edges) {
|
||||||
|
arbiter.addNode(e.src, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||||
|
arbiter.addNode(e.dst, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||||
|
}
|
||||||
const compiler = new DSLCompiler(arbiter);
|
const compiler = new DSLCompiler(arbiter);
|
||||||
const compiled = compiler.compile(dsl, 'oracle');
|
const compiled = compiler.compile(dsl, 'oracle');
|
||||||
if (!compiled.success) {
|
if (!compiled.success) {
|
||||||
@@ -178,7 +199,7 @@ function runCheck({ kind, ps }) {
|
|||||||
|
|
||||||
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
||||||
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition',
|
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition',
|
||||||
'chain_condition_step'];
|
'chain_condition_step', 'chain_intermediate_condition'];
|
||||||
|
|
||||||
describe('DSL generative oracle parity (rigor)', () => {
|
describe('DSL generative oracle parity (rigor)', () => {
|
||||||
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
||||||
@@ -220,6 +241,10 @@ describe('DSL generative oracle parity (rigor)', () => {
|
|||||||
arbiter.addNode('u:1', 'Employee');
|
arbiter.addNode('u:1', 'Employee');
|
||||||
arbiter.addNode('g:1', 'Group');
|
arbiter.addNode('g:1', 'Group');
|
||||||
arbiter.addNode('doc:9', 'Doc');
|
arbiter.addNode('doc:9', 'Doc');
|
||||||
|
for (const e of edges) {
|
||||||
|
arbiter.addNode(e.src, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||||
|
arbiter.addNode(e.dst, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||||
|
}
|
||||||
const compiled = new DSLCompiler(arbiter).compile(dsl, 'sweep');
|
const compiled = new DSLCompiler(arbiter).compile(dsl, 'sweep');
|
||||||
assert.ok(compiled.success, `${kind} compile failed: ${(compiled.errors || []).join('; ')}`);
|
assert.ok(compiled.success, `${kind} compile failed: ${(compiled.errors || []).join('; ')}`);
|
||||||
for (const e of edges) arbiter.addRelation(e.src, e.relation, e.dst, { possibility: e.possibility });
|
for (const e of edges) arbiter.addRelation(e.src, e.relation, e.dst, { possibility: e.possibility });
|
||||||
|
|||||||
Reference in New Issue
Block a user