Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 | 9x 9x 38940x 194x 194x 194x 194x 194x 948x 193x 14250x 193x 193x 948x 193x 14250x 193x 427x 427x 24624x 4661x 4661x 1657x 1657x 1657x 1x 1x 24624x 1x 427x 1x 426x 33147x 33147x 7777x 7777x 7777x 2x 2x 426x 193x 9434x 13x 1161x 18x 18x 1143x 387x 13x 13x 13x 13x 17x 21x 21x 13x 16x 16x 15x 15x 15x 10x 154x 154x 153x 153x 153x 8x 8x 11x 8x 152x 8x 10x 10x 165x 18x 18x 12x 12x 12x 12x 12x 2x 10x 8x 7x 7x 5x 5x 5x 5x 5x 3x 2x 5x 3x 8x 3297x 10x 10x 3287x 1099x 8x 246x 464x 464x 8x 14x 14x 13x 8x 377x 377x 376x 8x 8x 14x 8x 377x 8x 8x 17x 17x 637x 154x 154x 37x 37x 37x 37x 37x 17x 950x 950x 209x 209x 209x 209x 209x 17x 8x 4x 4x 4x 1x 3x 4x 1x 1x 49x 6x 1x 7x 1x 52x 51x 1x | import * as rdfjs from '@rdfjs/types';
import DataFactory from '@rdfjs/data-model';
import { TripleIndex } from './triple-index.js';
export { TripleIndex };
const createQuad = DataFactory.quad.bind(DataFactory);
const defaultGraphTerm = DataFactory.defaultGraph();
/**
* A reasoner that derives new triples from an RDF graph via forward-chaining inference.
*/
export interface Reasoner {
/**
* Apply inference over the source graph and yield all inferred triples.
* The caller is responsible for adding the yielded quads to a graph.
*
* @param store The source dataset to reason over.
* @param sourceGraph The named graph (or default graph) to read triples from.
* @param options Optional controls for inference workflows (e.g. early stopping).
* @returns An iterable of inferred quads (with graph term normalized to defaultGraph).
*/
infer(store: rdfjs.DatasetCore, sourceGraph: rdfjs.Quad_Graph, options?: InferenceOptions): Iterable<rdfjs.Quad>;
}
/**
* A single inference step: the derived quad, the OWL RL rule that produced it,
* and the direct antecedent quads that triggered it.
*/
export interface InferenceResult {
quad: rdfjs.Quad;
rule: string;
antecedents: rdfjs.Quad[];
}
/** A source triple that came directly from the input dataset. */
export interface SourceRecord {
origin: 'source';
triple: rdfjs.Quad;
}
/** A profile axiom seeded into the index before inference began. */
export interface AxiomRecord {
origin: 'axiom';
triple: rdfjs.Quad;
}
/** A triple produced by applying a named OWL RL rule to its premises. */
export interface InferredRecord {
origin: 'inferred';
triple: rdfjs.Quad;
rule: string;
ruleDescription?: string;
premises: ProvenanceRecord[];
}
/**
* A node in a provenance explanation tree.
*
* - `SourceRecord` — leaf: the triple came directly from the input dataset.
* - `AxiomRecord` — leaf: the triple is a profile axiom.
* - `InferredRecord` — branch: the triple was derived by a named OWL RL rule from its premises.
*/
export type ProvenanceRecord = SourceRecord | AxiomRecord | InferredRecord;
/** Predicate used to match inferred quads of interest (e.g. inconsistency markers). */
export type InferredQuadMatcher = (quad: rdfjs.Quad) => boolean;
/** Optional controls for inference workflows. */
export interface InferenceOptions {
stopWhen?: InferredQuadMatcher;
}
/** SHACL-like severity levels for reasoner report entries. */
export type ReportSeverity = 'Violation' | 'Warning' | 'Info';
/** Optional controls for report workflows. */
export interface ReportOptions {
/** Graph where inferred triples are intended to be written by the caller. */
targetGraph?: rdfjs.Quad_Graph;
}
/**
* A SHACL-inspired report result entry for one reasoning outcome.
*
* Compact top-level fields keep graph context and severity.
* Triple/rule/message details are contained in `detail`.
*/
export interface ReasoningReportResult {
sourceGraph: rdfjs.Quad_Graph;
targetGraph: rdfjs.Quad_Graph;
severity: ReportSeverity;
detail: ProvenanceRecord;
}
/** A SHACL-inspired report wrapper for reasoning outcomes. */
export interface ReasoningReport {
consistent: boolean;
results: ReasoningReportResult[];
}
/**
* Factory for creating an `InferenceResult`. Used by rule functions to annotate
* each derived quad with its rule name and direct antecedent quads.
*/
export function infer(quad: rdfjs.Quad, rule: string, ...antecedents: rdfjs.Quad[]): InferenceResult {
return { quad, rule, antecedents };
}
/**
* Abstract base for semi-naive fixpoint reasoners.
*
* Subclasses implement inferFromQuad() (single-quad rules) and
* inferFromIndex() (join rules that need multi-quad lookups).
*
* The engine:
* 1. Seeds a TripleIndex with all source triples.
* 2. Runs single-quad rules over every quad in the current delta.
* 3. Runs join rules over the full index once per round.
* 4. Adds newly derived triples to the index and the next delta.
* 5. Repeats until the delta is empty (fixpoint).
* 6. Yields every inferred triple that was not in the source graph.
*
* This is semi-naive because each round only processes the *new* triples
* added in the previous round, not the entire working set.
*/
export abstract class ReasonerBase implements Reasoner {
*infer(store: rdfjs.DatasetCore, sourceGraph: rdfjs.Quad_Graph, options?: InferenceOptions,): Iterable<rdfjs.Quad> {
let shouldStop = false;
const stopWhen = options?.stopWhen;
const inferredQuads: rdfjs.Quad[] = [];
const index = new TripleIndex();
// Seed the index with source triples.
// Source triples are always in the index before any inference, so derived
// triples that duplicate source triples will be rejected by index.add() and
// will never reach inferredQuads — making a separate sourceKeys check redundant.
for (const q of store.match(null, null, null, sourceGraph)) {
index.add(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
// Pre-load profile axioms (not yielded as inferred).
for (const q of this.axioms()) {
index.add(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
// Build the initial delta from all source + axiomatic quads.
let delta: rdfjs.Quad[] = [];
for (const q of store.match(null, null, null, sourceGraph)) {
delta.push(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
for (const q of this.axioms()) {
delta.push(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
// Semi-naive fixpoint loop.
while (delta.length > 0 && !shouldStop) {
const nextDelta: rdfjs.Quad[] = [];
// Single-quad rules: run only over the new delta.
for (const q of delta) {
for (const result of this.inferFromQuad(q, index)) {
const n = createQuad(result.quad.subject, result.quad.predicate, result.quad.object, defaultGraphTerm);
if (index.add(n)) {
inferredQuads.push(n);
nextDelta.push(n);
if (stopWhen?.(n)) {
shouldStop = true;
break;
}
}
}
if (shouldStop) {
break;
}
}
if (shouldStop) {
break;
}
// Join rules: run over the full index; only new triples advance.
for (const result of this.inferFromIndex(index)) {
const n = createQuad(result.quad.subject, result.quad.predicate, result.quad.object, defaultGraphTerm);
if (index.add(n)) {
inferredQuads.push(n);
nextDelta.push(n);
if (stopWhen?.(n)) {
shouldStop = true;
break;
}
}
}
delta = nextDelta;
}
// Yield all inferred triples.
for (const q of inferredQuads) {
yield createQuad(q.subject, q.predicate, q.object);
}
}
/**
* Compute provenance for a specific inferred quad.
* @param store The source dataset to reason over.
* @param sourceGraph The named graph (or default graph) to read triples from.
* @param target The inferred quad to compute provenance for (only subject, predicate, object are considered; graph is ignored).
* @return A provenance record containing the derivation chain for the target quad, or undefined if the target quad is not derivable.
*/
provenanceFor(store: rdfjs.DatasetCore, sourceGraph: rdfjs.Quad_Graph, target: rdfjs.Quad): ProvenanceRecord | undefined {
const index = new TripleIndex();
function termKey(t: rdfjs.Term): string {
if (t.termType === 'Literal') {
const lit = t as rdfjs.Literal;
return `L\x00${lit.value}\x00${lit.language || (lit.datatype?.value ?? '')}`;
} else {
return `${t.termType[0]}\x00${t.value}`;
}
}
function quadKey(q: rdfjs.Quad): string {
return `${termKey(q.subject)}\x01${termKey(q.predicate)}\x01${termKey(q.object)}`;
}
const normalizedTarget = createQuad(target.subject, target.predicate, target.object, defaultGraphTerm);
const targetKey = quadKey(normalizedTarget);
const provenanceMap = new Map<string, ProvenanceRecord>();
const resolvePremises = (antecedents: rdfjs.Quad[]): ProvenanceRecord[] => {
return antecedents.map(ant => {
const key = quadKey(createQuad(ant.subject, ant.predicate, ant.object, defaultGraphTerm));
return provenanceMap.get(key) ?? { origin: 'source', triple: ant };
});
};
for (const q of store.match(null, null, null, sourceGraph)) {
const n = createQuad(q.subject, q.predicate, q.object, defaultGraphTerm);
if (index.add(n)) {
const record: ProvenanceRecord = { origin: 'source', triple: n };
provenanceMap.set(quadKey(n), record);
if (quadKey(n) === targetKey) return record;
}
}
for (const q of this.axioms()) {
const n = createQuad(q.subject, q.predicate, q.object, defaultGraphTerm);
if (index.add(n)) {
const record: ProvenanceRecord = { origin: 'axiom', triple: n };
provenanceMap.set(quadKey(n), record);
if (quadKey(n) === targetKey) return record;
}
}
let delta: rdfjs.Quad[] = [];
for (const q of store.match(null, null, null, sourceGraph)) {
delta.push(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
for (const q of this.axioms()) {
delta.push(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
while (delta.length > 0) {
const nextDelta: rdfjs.Quad[] = [];
for (const q of delta) {
for (const result of this.inferFromQuad(q, index)) {
const n = createQuad(result.quad.subject, result.quad.predicate, result.quad.object, defaultGraphTerm);
if (index.add(n)) {
const key = quadKey(n);
const ruleDescription = this.getRuleDescription(result.rule);
const record: ProvenanceRecord = {
origin: 'inferred',
triple: n,
rule: result.rule,
...(ruleDescription ? { ruleDescription } : {}),
premises: resolvePremises(result.antecedents),
};
provenanceMap.set(key, record);
if (key === targetKey) {
return record;
}
nextDelta.push(n);
}
}
}
for (const result of this.inferFromIndex(index)) {
const n = createQuad(result.quad.subject, result.quad.predicate, result.quad.object, defaultGraphTerm);
if (index.add(n)) {
const key = quadKey(n);
const ruleDescription = this.getRuleDescription(result.rule);
const record: ProvenanceRecord = {
origin: 'inferred',
triple: n,
rule: result.rule,
...(ruleDescription ? { ruleDescription } : {}),
premises: resolvePremises(result.antecedents),
};
provenanceMap.set(key, record);
if (key === targetKey) {
return record;
}
nextDelta.push(n);
}
}
delta = nextDelta;
}
return undefined;
}
/**
* Compute provenance for all inferred quads.
*
* Prefer `provenanceFor()` for editor workflows that need explanation for
* a specific detected issue.
*/
provenanceForAll(store: rdfjs.DatasetCore, sourceGraph: rdfjs.Quad_Graph): ProvenanceRecord[] {
const index = new TripleIndex();
// Stable key for an RDF term that preserves term type.
function termKey(t: rdfjs.Term): string {
if (t.termType === 'Literal') {
const lit = t as rdfjs.Literal;
return `L\x00${lit.value}\x00${lit.language || (lit.datatype?.value ?? '')}`;
}
return `${t.termType[0]}\x00${t.value}`;
}
function quadKey(q: rdfjs.Quad): string {
return `${termKey(q.subject)}\x01${termKey(q.predicate)}\x01${termKey(q.object)}`;
}
const provenanceMap = new Map<string, ProvenanceRecord>();
function resolvePremises(antecedents: rdfjs.Quad[]): ProvenanceRecord[] {
return antecedents.map(ant => {
const key = quadKey(createQuad(ant.subject, ant.predicate, ant.object, defaultGraphTerm));
return provenanceMap.get(key) ?? { origin: 'source', triple: ant };
});
}
// Seed index and provenance map with source triples.
for (const q of store.match(null, null, null, sourceGraph)) {
const n = createQuad(q.subject, q.predicate, q.object, defaultGraphTerm);
if (index.add(n)) {
provenanceMap.set(quadKey(n), { origin: 'source', triple: n });
}
}
// Seed with profile axioms.
for (const q of this.axioms()) {
const n = createQuad(q.subject, q.predicate, q.object, defaultGraphTerm);
if (index.add(n)) {
provenanceMap.set(quadKey(n), { origin: 'axiom', triple: n });
}
}
// Build the initial delta from all source + axiomatic quads.
let delta: rdfjs.Quad[] = [];
for (const q of store.match(null, null, null, sourceGraph)) {
delta.push(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
for (const q of this.axioms()) {
delta.push(createQuad(q.subject, q.predicate, q.object, defaultGraphTerm));
}
const inferredRecords: ProvenanceRecord[] = [];
// Semi-naive fixpoint loop.
while (delta.length > 0) {
const nextDelta: rdfjs.Quad[] = [];
for (const q of delta) {
for (const result of this.inferFromQuad(q, index)) {
const n = createQuad(result.quad.subject, result.quad.predicate, result.quad.object, defaultGraphTerm);
if (index.add(n)) {
const ruleDescription = this.getRuleDescription(result.rule);
const record: ProvenanceRecord = {
origin: 'inferred',
triple: n,
rule: result.rule,
...(ruleDescription ? { ruleDescription } : {}),
premises: resolvePremises(result.antecedents),
};
provenanceMap.set(quadKey(n), record);
inferredRecords.push(record);
nextDelta.push(n);
}
}
}
for (const result of this.inferFromIndex(index)) {
const n = createQuad(result.quad.subject, result.quad.predicate, result.quad.object, defaultGraphTerm);
if (index.add(n)) {
const ruleDescription = this.getRuleDescription(result.rule);
const record: ProvenanceRecord = {
origin: 'inferred',
triple: n,
rule: result.rule,
...(ruleDescription ? { ruleDescription } : {}),
premises: resolvePremises(result.antecedents),
};
provenanceMap.set(quadKey(n), record);
inferredRecords.push(record);
nextDelta.push(n);
}
}
delta = nextDelta;
}
return inferredRecords;
}
/**
* Apply inference over the source graph and return a provenance record for
* every inferred triple. Each inferred record contains the derived triple,
* the rule id, an optional human-readable ruleDescription, and recursively
* resolved premises that chain back to source and axiom leaf records.
*
* When the same quad is derivable by multiple paths only the first derivation
* (earliest fixpoint round) is recorded.
*/
expandWithProvenance(store: rdfjs.DatasetCore, sourceGraph: rdfjs.Quad_Graph): ProvenanceRecord[] {
return this.provenanceForAll(store, sourceGraph);
}
/**
* Build one SHACL-inspired report result for a specific target quad.
*
* The result contains source/target graph context, severity, and a detailed
* provenance record for explainability.
*/
reportFor(
store: rdfjs.DatasetCore,
sourceGraph: rdfjs.Quad_Graph,
target: rdfjs.Quad,
options?: ReportOptions,
): ReasoningReportResult | undefined {
const detail = this.provenanceFor(store, sourceGraph, target);
if (!detail) {
return undefined;
}
const targetGraph = options?.targetGraph ?? sourceGraph;
return this.toReportResult(detail, sourceGraph, targetGraph);
}
/**
* Build a SHACL-inspired report for all inferred outcomes.
*
* `consistent` is true when no result has severity `Violation`.
*/
reportForAll(
store: rdfjs.DatasetCore,
sourceGraph: rdfjs.Quad_Graph,
options?: ReportOptions,
): ReasoningReport {
const targetGraph = options?.targetGraph ?? sourceGraph;
const results = this.provenanceForAll(store, sourceGraph).map(record =>
this.toReportResult(record, sourceGraph, targetGraph),
);
const consistent = !results.some(r => r.severity === 'Violation');
return { consistent, results };
}
/** Optional short human-readable text for a rule id (e.g. from profile specs). */
protected getRuleDescription(_rule: string): string | undefined {
return undefined;
}
/** Severity policy for inferred provenance nodes. Override in subclasses. */
protected getSeverity(_record: InferredRecord): ReportSeverity {
return 'Info';
}
private toReportResult(
detail: ProvenanceRecord,
sourceGraph: rdfjs.Quad_Graph,
targetGraph: rdfjs.Quad_Graph,
): ReasoningReportResult {
if (detail.origin === 'inferred') {
return {
sourceGraph,
targetGraph,
severity: this.getSeverity(detail),
detail,
};
}
return {
sourceGraph,
targetGraph,
severity: 'Info',
detail,
};
}
/**
* Axiomatic triples pre-loaded into the working index before inference begins.
* Override to provide profile-specific axioms (e.g. owl:Thing a owl:Class).
*/
protected *axioms(): Iterable<rdfjs.Quad> { }
/**
* Single-quad rules. Called once per quad in the current delta.
* Yield any triples derivable from this quad (optionally using the index for lookups).
*/
protected abstract inferFromQuad(quad: rdfjs.Quad, index: TripleIndex): Iterable<InferenceResult>;
/**
* Join rules requiring patterns across multiple quads.
* Called once per fixpoint round over the full index.
*/
protected abstract inferFromIndex(index: TripleIndex): Iterable<InferenceResult>;
}
|