inference-engine 0.1.0a1__tar.gz → 0.1.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.github/workflows/ci.yml +6 -6
  2. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.github/workflows/conventional-commits.yml +1 -1
  3. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.github/workflows/dependabot-merge.yml +1 -1
  4. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.github/workflows/release-health.yml +1 -1
  5. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/Cargo.lock +4 -3
  6. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/Cargo.toml +3 -2
  7. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/PKG-INFO +10 -4
  8. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/README.md +9 -3
  9. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/docs/publication.md +5 -3
  10. inference_engine-0.1.0a2/docs/rdfs-subclass.md +118 -0
  11. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/package-lock.json +2 -2
  12. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/package.json +1 -1
  13. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/src/lib.rs +2 -0
  14. inference_engine-0.1.0a2/src/reasoning/engine.rs +145 -0
  15. inference_engine-0.1.0a2/src/reasoning/mod.rs +89 -0
  16. inference_engine-0.1.0a2/src/reasoning/plan.rs +111 -0
  17. inference_engine-0.1.0a2/src/reasoning/types.rs +146 -0
  18. inference_engine-0.1.0a2/tests/send_future.rs +11 -0
  19. inference_engine-0.1.0a2/tests/subclass.rs +285 -0
  20. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.githooks/commit-msg +0 -0
  21. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.githooks/post-commit +0 -0
  22. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.githooks/pre-commit +0 -0
  23. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.github/CODEOWNERS +0 -0
  24. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.github/dependabot.yml +0 -0
  25. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.github/release-health.json +0 -0
  26. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/.gitignore +0 -0
  27. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/AGENTS.md +0 -0
  28. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/LICENSE-APACHE +0 -0
  29. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/LICENSE-MIT +0 -0
  30. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/bindings/node/Cargo.toml +0 -0
  31. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/bindings/node/build.rs +0 -0
  32. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/bindings/node/src/lib.rs +0 -0
  33. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/bindings/python/Cargo.toml +0 -0
  34. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/bindings/python/src/lib.rs +0 -0
  35. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/build.rs +0 -0
  36. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/index.cjs +0 -0
  37. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/index.d.ts +0 -0
  38. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/pyproject.toml +0 -0
  39. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/python/inference_engine/__init__.py +0 -0
  40. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/python/inference_engine/__init__.pyi +0 -0
  41. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/python/inference_engine/py.typed +0 -0
  42. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/rust-toolchain.toml +0 -0
  43. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/rustfmt-toolchain +0 -0
  44. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/build-node.py +0 -0
  45. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/check-package.py +0 -0
  46. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/fmt.sh +0 -0
  47. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/release-packages.py +0 -0
  48. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/release-version.py +0 -0
  49. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/sync-version.py +0 -0
  50. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/test-node.cjs +0 -0
  51. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/test-npm-package.py +0 -0
  52. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/test-python.py +0 -0
  53. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/test-release.py +0 -0
  54. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/test-wheel.py +0 -0
  55. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/scripts/test-workflow.py +0 -0
  56. {inference_engine-0.1.0a1 → inference_engine-0.1.0a2}/tests/public_api.rs +0 -0
@@ -33,7 +33,7 @@ jobs:
33
33
  private-key: ${{ secrets.RELEASE_WRITER_APP_KEY }}
34
34
  owner: ${{ github.repository_owner }}
35
35
  repositories: ${{ github.event.repository.name }}
36
- - uses: legra-ai/github-actions/.github/actions/prepare-cargo-release@436340e7d6c2b6d71921145415690b2518f1901d
36
+ - uses: legra-ai/github-actions/.github/actions/prepare-cargo-release@3ace81c4ac6d64eb18bc1df4dd7248d8ff87b6e0
37
37
  id: release
38
38
  with:
39
39
  token: ${{ steps.writer.outputs.token || github.token }}
@@ -73,7 +73,7 @@ jobs:
73
73
  - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
74
74
  - run: cargo test --locked --doc
75
75
  - run: cargo doc --locked --no-deps
76
- - uses: legra-ai/github-actions/.github/actions/test-cargo-package@436340e7d6c2b6d71921145415690b2518f1901d
76
+ - uses: legra-ai/github-actions/.github/actions/test-cargo-package@3ace81c4ac6d64eb18bc1df4dd7248d8ff87b6e0
77
77
 
78
78
  sdist:
79
79
  needs: prepare
@@ -240,7 +240,7 @@ jobs:
240
240
  node-version: '24'
241
241
  registry-url: https://registry.npmjs.org
242
242
  - run: python3 scripts/release-version.py
243
- - uses: legra-ai/github-actions/.github/actions/tag-tested-release@436340e7d6c2b6d71921145415690b2518f1901d
243
+ - uses: legra-ai/github-actions/.github/actions/tag-tested-release@3ace81c4ac6d64eb18bc1df4dd7248d8ff87b6e0
244
244
  with:
245
245
  version: ${{ needs.prepare.outputs.version }}
246
246
  revision: ${{ needs.prepare.outputs.revision }}
@@ -261,7 +261,7 @@ jobs:
261
261
  env:
262
262
  GH_TOKEN: ${{ steps.writer.outputs.token }}
263
263
  run: python3 scripts/release-packages.py stage
264
- - uses: legra-ai/github-actions/.github/actions/publish-tested-crate@436340e7d6c2b6d71921145415690b2518f1901d
264
+ - uses: legra-ai/github-actions/.github/actions/publish-tested-crate@3ace81c4ac6d64eb18bc1df4dd7248d8ff87b6e0
265
265
  with:
266
266
  crate: inference-engine
267
267
  version: ${{ needs.prepare.outputs.version }}
@@ -275,7 +275,7 @@ jobs:
275
275
  env:
276
276
  NPM_ARCHIVE: ${{ steps.npm.outputs.npm_archive }}
277
277
  run: npm publish "$GITHUB_WORKSPACE/$NPM_ARCHIVE" --tag alpha --access public --provenance --ignore-scripts
278
- - uses: legra-ai/github-actions/.github/actions/verify-registry-publication@436340e7d6c2b6d71921145415690b2518f1901d
278
+ - uses: legra-ai/github-actions/.github/actions/verify-registry-publication@156c41f73b7331b9c70280a6b215a96c49a2d8fd
279
279
  with:
280
280
  registry: npm
281
281
  package: inference-engine
@@ -288,7 +288,7 @@ jobs:
288
288
  uses: pypa/gh-action-pypi-publish@release/v1
289
289
  with:
290
290
  packages-dir: pending-packages/
291
- - uses: legra-ai/github-actions/.github/actions/verify-registry-publication@436340e7d6c2b6d71921145415690b2518f1901d
291
+ - uses: legra-ai/github-actions/.github/actions/verify-registry-publication@156c41f73b7331b9c70280a6b215a96c49a2d8fd
292
292
  with:
293
293
  registry: pypi
294
294
  package: inference-engine
@@ -9,4 +9,4 @@ jobs:
9
9
  name: Conventional Commit
10
10
  runs-on: ubuntu-24.04
11
11
  steps:
12
- - uses: legra-ai/github-actions/.github/actions/conventional-commit@436340e7d6c2b6d71921145415690b2518f1901d
12
+ - uses: legra-ai/github-actions/.github/actions/conventional-commit@7161b3b0fb80eb36ff9d92faccfced2a8001fe40
@@ -18,7 +18,7 @@ jobs:
18
18
  private-key: ${{ secrets.RELEASE_MERGER_APP_KEY }}
19
19
  owner: ${{ github.repository_owner }}
20
20
  repositories: ${{ github.event.repository.name }}
21
- - uses: legra-ai/github-actions/.github/actions/merge-tested-dependabot@436340e7d6c2b6d71921145415690b2518f1901d
21
+ - uses: legra-ai/github-actions/.github/actions/merge-tested-dependabot@3ace81c4ac6d64eb18bc1df4dd7248d8ff87b6e0
22
22
  with:
23
23
  token: ${{ steps.merger.outputs.token }}
24
24
  app-id: ${{ secrets.RELEASE_MERGER_APP_ID }}
@@ -15,7 +15,7 @@ jobs:
15
15
  timeout-minutes: 15
16
16
  steps:
17
17
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
18
- - uses: legra-ai/github-actions/.github/actions/monitor-release@436340e7d6c2b6d71921145415690b2518f1901d
18
+ - uses: legra-ai/github-actions/.github/actions/monitor-release@156c41f73b7331b9c70280a6b215a96c49a2d8fd
19
19
  with:
20
20
  config: .github/release-health.json
21
21
  token: ${{ github.token }}
@@ -252,7 +252,7 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
252
252
 
253
253
  [[package]]
254
254
  name = "inference-engine"
255
- version = "0.1.0-alpha.1"
255
+ version = "0.1.0-alpha.2"
256
256
  dependencies = [
257
257
  "datalog-structural-model",
258
258
  "postcard",
@@ -260,11 +260,12 @@ dependencies = [
260
260
  "rhusky 2.0.6",
261
261
  "serde",
262
262
  "serde_json",
263
+ "tokio",
263
264
  ]
264
265
 
265
266
  [[package]]
266
267
  name = "inference-engine-node"
267
- version = "0.1.0-alpha.1"
268
+ version = "0.1.0-alpha.2"
268
269
  dependencies = [
269
270
  "inference-engine",
270
271
  "napi",
@@ -275,7 +276,7 @@ dependencies = [
275
276
 
276
277
  [[package]]
277
278
  name = "inference-engine-python"
278
- version = "0.1.0-alpha.1"
279
+ version = "0.1.0-alpha.2"
279
280
  dependencies = [
280
281
  "inference-engine",
281
282
  "pyo3",
@@ -4,7 +4,7 @@ default-members = ["."]
4
4
  resolver = "3"
5
5
 
6
6
  [workspace.package]
7
- version = "0.1.0-alpha.1"
7
+ version = "0.1.0-alpha.2"
8
8
  edition = "2024"
9
9
  rust-version = "1.99.1"
10
10
  license = "MIT OR Apache-2.0"
@@ -24,7 +24,7 @@ documentation = "https://docs.rs/inference-engine"
24
24
  keywords = ["rdf", "rdfs", "owl", "datalog", "reasoning"]
25
25
  categories = ["science", "data-structures"]
26
26
  build = "build.rs"
27
- include = ["Cargo.toml", "Cargo.lock", "README.md", "LICENSE-APACHE", "LICENSE-MIT", "src/**/*.rs", "tests/*.rs"]
27
+ include = ["Cargo.toml", "Cargo.lock", "README.md", "LICENSE-APACHE", "LICENSE-MIT", "src/**/*.rs", "tests/*.rs", "docs/rdfs-subclass.md"]
28
28
 
29
29
  [dependencies]
30
30
  datalog-structural-model = "=3.0.0"
@@ -37,6 +37,7 @@ rhusky = "=2.0.6"
37
37
  [dev-dependencies]
38
38
  serde_json = "1"
39
39
  postcard = { version = "1", features = ["alloc"] }
40
+ tokio = { version = "1.54.1", features = ["macros", "rt"] }
40
41
 
41
42
  [package.metadata.version-info]
42
43
  pre_bump_hooks = ["python3 scripts/sync-version.py {{version}}"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: inference-engine
3
- Version: 0.1.0a1
3
+ Version: 0.1.0a2
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Programming Language :: Python :: 3
@@ -30,9 +30,15 @@ The first alpha compiles named `rdf-reasoning` profiles into checked portable
30
30
  Datalog programs and reports their explicit exclusions. Rust, Python and Node.js
31
31
  use the same Rust implementation and published semantic dependencies.
32
32
 
33
- **Graph evaluation, materialization, Oxigraph integration and SHACL inference are
34
- not implemented in this alpha.** A compiled rule profile is not a claim of engine
35
- capability, complete RDFS/OWL-RL support or consistency checking.
33
+ Rust also provides bounded forward execution of the explicit `rdfs-subclass`
34
+ profile: subclass transitivity (`rdfs11`) and inherited membership (`rdfs9`).
35
+ The executor evaluates the definitions from `rdf-reasoning`; callers supply
36
+ asynchronous database scans, indexed membership probes and scratch storage.
37
+ See [the storage adapter contract](docs/rdfs-subclass.md).
38
+
39
+ The other named profiles are **compile-only**. Full RDFS/OWL-RL, arbitrary Datalog
40
+ execution and SHACL inference are not implemented. Python and Node currently
41
+ expose profile inspection; executable storage adapters use the Rust API.
36
42
 
37
43
  ```rust
38
44
  let profile = inference_engine::compile_profile("rdfs-core")?;
@@ -14,9 +14,15 @@ The first alpha compiles named `rdf-reasoning` profiles into checked portable
14
14
  Datalog programs and reports their explicit exclusions. Rust, Python and Node.js
15
15
  use the same Rust implementation and published semantic dependencies.
16
16
 
17
- **Graph evaluation, materialization, Oxigraph integration and SHACL inference are
18
- not implemented in this alpha.** A compiled rule profile is not a claim of engine
19
- capability, complete RDFS/OWL-RL support or consistency checking.
17
+ Rust also provides bounded forward execution of the explicit `rdfs-subclass`
18
+ profile: subclass transitivity (`rdfs11`) and inherited membership (`rdfs9`).
19
+ The executor evaluates the definitions from `rdf-reasoning`; callers supply
20
+ asynchronous database scans, indexed membership probes and scratch storage.
21
+ See [the storage adapter contract](docs/rdfs-subclass.md).
22
+
23
+ The other named profiles are **compile-only**. Full RDFS/OWL-RL, arbitrary Datalog
24
+ execution and SHACL inference are not implemented. Python and Node currently
25
+ expose profile inspection; executable storage adapters use the Rust API.
20
26
 
21
27
  ```rust
22
28
  let profile = inference_engine::compile_profile("rdfs-core")?;
@@ -1,8 +1,10 @@
1
1
  # Alpha publication
2
2
 
3
- The first release provides native checked rule-profile compilation and inspection.
4
- It does not execute graph reasoning. Do not publish placeholders, advertise full
5
- standards support, or make a stable release from this alpha pipeline.
3
+ The first release provided native checked rule-profile compilation and inspection.
4
+ The next alpha adds the Rust `rdfs-subclass` storage-adapter executor, limited to
5
+ shared rules `rdfs9` and `rdfs11`. Python and Node remain profile-inspection APIs.
6
+ Do not publish placeholders, advertise full standards support, or make a stable
7
+ release from this alpha pipeline.
6
8
 
7
9
  ## Version authority
8
10
 
@@ -0,0 +1,118 @@
1
+ # Executable subclass profile
2
+
3
+ `reasoning::ExecutionProfile::RdfsSubclass` selects exactly `rdfs9` and `rdfs11`
4
+ from the pinned `rdf-reasoning` catalogue. Its selector is `rdfs-subclass`,
5
+ profile revision is `1`, and its rule definitions are evaluated as Datalog
6
+ patterns rather than reimplemented in the storage adapter.
7
+
8
+ Given:
9
+
10
+ ```turtle
11
+ ex:Person rdfs:subClassOf ex:Agent .
12
+ ex:Agent rdfs:subClassOf ex:Thing .
13
+ ex:alice rdf:type ex:Person .
14
+ ```
15
+
16
+ the inferred additions are:
17
+
18
+ ```turtle
19
+ ex:Person rdfs:subClassOf ex:Thing .
20
+ ex:alice rdf:type ex:Agent, ex:Thing .
21
+ ```
22
+
23
+ No reverse subclass implication is made. Cycles can imply self-subclass
24
+ relationships and terminate through exact set membership. Asserted triples are
25
+ not copied into inferred output, even when a rule can also prove them.
26
+
27
+ This profile excludes **every other rule**, axiomatic triples, datatype
28
+ reasoning, subproperty/domain/range reasoning, OWL reasoning, contradiction
29
+ detection and SHACL. It does not claim complete RDFS entailment. Existing
30
+ `compile_profile("rdfs-core")` remains compilation only; the executor rejects
31
+ `rdfs-core`, `rdfs`, `owl2-rl` and unknown selectors instead of weakening them.
32
+
33
+ ## Rust use
34
+
35
+ ```rust
36
+ use inference_engine::reasoning::{
37
+ ExecutionProfile, Reasoner, ReasoningError, ReasoningStore, RunLimits, RunReport,
38
+ };
39
+ use std::num::{NonZeroU32, NonZeroU64};
40
+
41
+ async fn infer<S: ReasoningStore>(store: &mut S)
42
+ -> Result<RunReport, ReasoningError<S::Error>>
43
+ {
44
+ let limits = RunLimits::new(
45
+ NonZeroU32::new(128).unwrap(),
46
+ NonZeroU64::new(1_000_000).unwrap(),
47
+ NonZeroU64::new(100_000_000).unwrap(),
48
+ );
49
+ Reasoner::new(ExecutionProfile::RdfsSubclass, limits).run(store).await
50
+ }
51
+ ```
52
+
53
+ These limits are examples; select explicit budgets appropriate to the input.
54
+ `rounds` includes the final round that proves no additions remain. `matches`
55
+ counts cursor rows examined across all scans, not just successful rule matches.
56
+ Output-budget failure occurs before staging a tuple beyond the configured cap.
57
+
58
+ ## Database adapter
59
+
60
+ Implement `ReasoningStore`, `TripleSource` and `TripleCursor`. Their exact Rust
61
+ signatures live in `src/reasoning/mod.rs`; the public regression fixture
62
+ `tests/subclass.rs` is a small, capped test adapter, not a production graph store.
63
+
64
+ - `Term: Clone + Eq + Send + Sync` can be a database ID or an exact backend RDF
65
+ term. `Copy`, strings and whole-dictionary conversion are not required.
66
+ - Tuples are `[Term; 3]` in subject/predicate/object order. Patterns are
67
+ `[Option<Term>; 3]`, where `None` means wildcard. Match bound terms exactly.
68
+ - `resolve_iri` resolves full shared-rule constants as **IRI terms**. Preserve
69
+ blank-node scope, literal lexical identity, language/datatype metadata and
70
+ any backend term identity; the engine does not parse or normalize these.
71
+ - Start a fresh attempt containing the immutable selected **asserted** input
72
+ and empty inferred scratch. Never seed it with a previous inferred closure.
73
+ - `snapshot` returns an **owned immutable round view** of selected assertions
74
+ plus staged inference at that moment. Its cursors must survive later writes
75
+ to the separate store. New insertions join only in subsequent rounds.
76
+ - `scan` opens a bounded fallible cursor with indexed probes. Two cursors can
77
+ be active per rule join. `next` returns one tuple, `None` only at successful
78
+ EOF, and a typed backend error on read/cancellation failure. Dropping a cursor
79
+ releases/cancels the read. Backend futures and the executor future are `Send`.
80
+ - `contains` probes the **current** asserted-plus-staged union, including facts
81
+ inserted since the round snapshot. `insert_inferred` deduplicates atomically,
82
+ gives assertions precedence, and returns true only for a novel inferred fact.
83
+ - `Inference<T>` includes the shared `RuleId` and both matching premise tuples.
84
+ A premise can itself be inferred. This is a first witness, not every proof.
85
+ Scan order can change that witness; exact inferred set closure is independent
86
+ of order. Do not treat the witness as a canonical provenance hash.
87
+ - Keep graph-sized scratch relations and deduplication indexes in disk-backed
88
+ storage. No engine method returns a closure `Vec`. The caller separately
89
+ budgets scratch space, term payloads, I/O and backend queues.
90
+ - Preserve generalized tuples in scratch; do not hide an unsupported term or
91
+ backend operation by silently dropping it. A standard RDF output adapter must
92
+ validate its representational support before beginning the attempt.
93
+
94
+ The engine does not select graph scope. A caller can explicitly choose a union
95
+ of selected logical source graphs, or run separate stores for graph-local
96
+ reasoning. Do not expose unrelated/control/document/inferred graphs, or mistake
97
+ physical contribution graph IRIs for logical source graph identities.
98
+
99
+ ## Completion and provenance
100
+
101
+ `run` returns `RunReport` only after a fixpoint. Cancellation, a read/write error,
102
+ unsupported rule shape or any limit returns an error. Some staged facts can
103
+ exist on failure; **abort them and never publish a partial closure**.
104
+
105
+ The caller owns promotion. Record selected input snapshot/graph identities,
106
+ `profile().name()`, `profile().revision()`, `profile().rules()`,
107
+ `implementation_version()`, `rule_catalogue()` and configured limits. Check that
108
+ the selected input is still current, then atomically promote the owned inference
109
+ contribution. A success report alone is not a currentness or publication guard.
110
+
111
+ On asserted-input deletion/change, profile change or implementation change,
112
+ recompute from a new asserted snapshot and atomically replace the contribution.
113
+ Keep assertions separate. Render inferred relationships with explicit origin,
114
+ preserve asserted precedence on duplicates, and retain inference/provenance in
115
+ KG export so restored source-free rendering does not rerun inference.
116
+
117
+ Python and Node distribution packages currently expose profile inspection;
118
+ this storage-adapter execution API is Rust-only.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "inference-engine",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "inference-engine",
9
- "version": "0.1.0-alpha.1",
9
+ "version": "0.1.0-alpha.2",
10
10
  "license": "MIT OR Apache-2.0",
11
11
  "engines": {
12
12
  "node": ">=22"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inference-engine",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.2",
4
4
  "description": "Native Rust inference foundation with checked RDF rule-profile compilation",
5
5
  "main": "index.cjs",
6
6
  "types": "index.d.ts",
@@ -4,6 +4,8 @@ use datalog_structural_model::Program;
4
4
  use rdf_reasoning::{Exclusion, Preset, PresetParseError};
5
5
  use serde::Serialize;
6
6
 
7
+ pub mod reasoning;
8
+
7
9
  /// An exact shared RDF profile, compiled into portable checked Datalog rules.
8
10
  ///
9
11
  /// This is a program description, not an evaluated closure or engine capability claim.
@@ -0,0 +1,145 @@
1
+ use super::{
2
+ ExecutionProfile, Inference, Limit, ReasoningError, ReasoningStore, RunLimits, RunReport,
3
+ TripleCursor, TripleSource, plan::Clause,
4
+ };
5
+
6
+ /// One native, storage-independent executor for the named two-rule profile.
7
+ pub struct Reasoner {
8
+ profile: ExecutionProfile,
9
+ limits: RunLimits,
10
+ }
11
+
12
+ impl Reasoner {
13
+ /// Select an exact supported profile and explicit resource limits.
14
+ pub const fn new(profile: ExecutionProfile, limits: RunLimits) -> Self {
15
+ Self { profile, limits }
16
+ }
17
+ /// Exact selected execution contract.
18
+ pub const fn profile(&self) -> ExecutionProfile {
19
+ self.profile
20
+ }
21
+ /// Implementation package version to record alongside input/profile identity.
22
+ pub const fn implementation_version(&self) -> &'static str {
23
+ env!("CARGO_PKG_VERSION")
24
+ }
25
+ /// Pinned semantic rule catalogue identity for inference provenance.
26
+ pub const fn rule_catalogue(&self) -> &'static str {
27
+ "rdf-reasoning/2.6.0"
28
+ }
29
+
30
+ /// Derive into caller-owned scratch until a fixpoint, retaining bounded state.
31
+ ///
32
+ /// Memory is two compiled clauses, fixed-size bindings and two active cursors
33
+ /// per join. Each round reads an immutable view; inserted tuples become
34
+ /// join inputs next round. Stores must implement indexed probes and disk spill.
35
+ ///
36
+ /// # Errors
37
+ /// Cancellation, resource exhaustion, unsupported shared rule shapes or any
38
+ /// storage failure abort the run. Staged output must then be discarded.
39
+ pub async fn run<S: ReasoningStore>(
40
+ &self,
41
+ store: &mut S,
42
+ ) -> Result<RunReport, ReasoningError<S::Error>> {
43
+ Self::check_cancelled(store)?;
44
+ let [first, second] = *self.profile.rules();
45
+ let clauses = [
46
+ Clause::compile(first, store).await?,
47
+ Clause::compile(second, store).await?,
48
+ ];
49
+ let mut report = RunReport::default();
50
+ loop {
51
+ Self::check_cancelled(store)?;
52
+ if report.rounds == self.limits.rounds.get() {
53
+ return Err(ReasoningError::LimitExceeded(Limit::Rounds));
54
+ }
55
+ report.rounds += 1;
56
+ let snapshot = store.snapshot().await.map_err(ReasoningError::Storage)?;
57
+ let before = report.inferred;
58
+ for clause in &clauses {
59
+ self.evaluate(clause, &snapshot, store, &mut report).await?;
60
+ }
61
+ Self::check_cancelled(store)?;
62
+ if report.inferred == before {
63
+ return Ok(report);
64
+ }
65
+ }
66
+ }
67
+
68
+ async fn evaluate<S: ReasoningStore>(
69
+ &self,
70
+ clause: &Clause<S::Term>,
71
+ source: &S::Snapshot,
72
+ store: &mut S,
73
+ report: &mut RunReport,
74
+ ) -> Result<(), ReasoningError<S::Error>> {
75
+ let empty = std::array::from_fn(|_| None);
76
+ let mut outer = source
77
+ .scan(clause.body[0].probe(&empty))
78
+ .await
79
+ .map_err(ReasoningError::Storage)?;
80
+ while let Some(first) = self.next(&mut outer, store, report).await? {
81
+ let Some(bindings) = clause.body[0].bind(&first, empty.clone()) else {
82
+ continue;
83
+ };
84
+ let mut inner = source
85
+ .scan(clause.body[1].probe(&bindings))
86
+ .await
87
+ .map_err(ReasoningError::Storage)?;
88
+ while let Some(second) = self.next(&mut inner, store, report).await? {
89
+ let Some(bindings) = clause.body[1].bind(&second, bindings.clone()) else {
90
+ continue;
91
+ };
92
+ let triple = clause.head.ground(&bindings, clause.id)?;
93
+ if store
94
+ .contains(&triple)
95
+ .await
96
+ .map_err(ReasoningError::Storage)?
97
+ {
98
+ continue;
99
+ }
100
+ Self::check_cancelled(store)?;
101
+ if report.inferred == self.limits.inferred.get() {
102
+ return Err(ReasoningError::LimitExceeded(Limit::Inferred));
103
+ }
104
+ let inference = Inference {
105
+ triple,
106
+ rule: clause.id,
107
+ premises: [first.clone(), second],
108
+ };
109
+ if store
110
+ .insert_inferred(inference)
111
+ .await
112
+ .map_err(ReasoningError::Storage)?
113
+ {
114
+ report.inferred += 1;
115
+ }
116
+ }
117
+ }
118
+ Ok(())
119
+ }
120
+
121
+ async fn next<S: ReasoningStore, C: TripleCursor<Term = S::Term, Error = S::Error>>(
122
+ &self,
123
+ cursor: &mut C,
124
+ store: &mut S,
125
+ report: &mut RunReport,
126
+ ) -> Result<Option<[S::Term; 3]>, ReasoningError<S::Error>> {
127
+ Self::check_cancelled(store)?;
128
+ let tuple = cursor.next().await.map_err(ReasoningError::Storage)?;
129
+ if tuple.is_some() {
130
+ if report.matches == self.limits.matches.get() {
131
+ return Err(ReasoningError::LimitExceeded(Limit::Matches));
132
+ }
133
+ report.matches += 1;
134
+ }
135
+ Ok(tuple)
136
+ }
137
+
138
+ fn check_cancelled<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
139
+ if store.is_cancelled() {
140
+ Err(ReasoningError::Cancelled)
141
+ } else {
142
+ Ok(())
143
+ }
144
+ }
145
+ }
@@ -0,0 +1,89 @@
1
+ //! Bounded forward execution of the shared `rdfs9` and `rdfs11` clauses.
2
+ //!
3
+ //! Callers own immutable selected input, indexed scratch storage and publication.
4
+ //! This module never collects a graph, chooses graphs, or promotes partial output.
5
+
6
+ mod engine;
7
+ mod plan;
8
+ mod types;
9
+
10
+ pub use engine::Reasoner;
11
+ pub use types::{
12
+ ExecutionProfile, Inference, Limit, ProfileError, ReasoningError, RunLimits, RunReport,
13
+ };
14
+
15
+ use std::{error::Error, future::Future};
16
+
17
+ /// A fallible, bounded cursor over an immutable snapshot's matching tuples.
18
+ pub trait TripleCursor: Send {
19
+ /// Caller-owned exact RDF term identity; scoped blanks must remain distinct.
20
+ type Term: Clone + Eq + Send + Sync;
21
+ /// Read failures, including cancellation, must never become end of stream.
22
+ type Error: Error + Send + Sync + 'static;
23
+ /// Read at most one tuple. Drop must release/cancel the underlying read.
24
+ fn next(&mut self)
25
+ -> impl Future<Output = Result<Option<[Self::Term; 3]>, Self::Error>> + Send;
26
+ }
27
+
28
+ /// One immutable round view of selected assertions plus staged consequences.
29
+ ///
30
+ /// Scans must be bounded and match every supplied term exactly. The view and
31
+ /// its cursors remain valid while the caller inserts into the separate store.
32
+ /// No ordering is required; set closure is independent of scan order. The first
33
+ /// retained proof can differ between orders and is not a canonical explanation.
34
+ pub trait TripleSource: Send + Sync {
35
+ /// Exact term type, without lexical/value normalization by the executor.
36
+ type Term: Clone + Eq + Send + Sync;
37
+ /// Backend read error.
38
+ type Error: Error + Send + Sync + 'static;
39
+ /// Owned cursor, independent of subsequent store writes.
40
+ type Cursor: TripleCursor<Term = Self::Term, Error = Self::Error>;
41
+ /// Open a scan/probe; `None` is a wildcard in subject/predicate/object order.
42
+ fn scan(
43
+ &self,
44
+ pattern: [Option<Self::Term>; 3],
45
+ ) -> impl Future<Output = Result<Self::Cursor, Self::Error>> + Send;
46
+ }
47
+
48
+ /// Backend capabilities for one fresh, isolated inference attempt.
49
+ ///
50
+ /// Initially expose only the caller's selected asserted snapshot, never earlier
51
+ /// inferred output. Scratch facts must spill to caller-owned indexed storage;
52
+ /// no method may buffer a graph-sized relation. Each snapshot freezes the union
53
+ /// as of its creation; subsequent insertions are visible in the next snapshot.
54
+ ///
55
+ /// On any error the caller must discard/abort staged output. A successful run
56
+ /// grants no publication authority: callers still check input currentness and
57
+ /// atomically promote their owned inference contribution. Recompute from fresh
58
+ /// assertions after deletion. The executor never mutates asserted input.
59
+ pub trait ReasoningStore: Send {
60
+ /// Exact RDF term identity; database IDs and backend RDF terms both work.
61
+ type Term: Clone + Eq + Send + Sync;
62
+ /// Backend failure propagated without substituting an empty relation.
63
+ type Error: Error + Send + Sync + 'static;
64
+ /// Owned immutable view supporting concurrent outer/inner read cursors.
65
+ type Snapshot: TripleSource<Term = Self::Term, Error = Self::Error>;
66
+ /// Resolve a full rule-constant IRI as an IRI, never as a plain string literal.
67
+ fn resolve_iri(
68
+ &mut self,
69
+ iri: &str,
70
+ ) -> impl Future<Output = Result<Self::Term, Self::Error>> + Send;
71
+ /// Freeze selected assertions plus all currently staged inferred tuples.
72
+ fn snapshot(&mut self) -> impl Future<Output = Result<Self::Snapshot, Self::Error>> + Send;
73
+ /// Indexed membership in the current asserted-plus-staged union.
74
+ fn contains(
75
+ &mut self,
76
+ triple: &[Self::Term; 3],
77
+ ) -> impl Future<Output = Result<bool, Self::Error>> + Send;
78
+ /// Stage a novel inferred tuple with its first proof; assertions win duplicates.
79
+ ///
80
+ /// Return `true` only for a new inferred tuple. Preserve generalized tuples
81
+ /// in scratch; do not silently drop terms or normalize literal lexical forms.
82
+ fn insert_inferred(
83
+ &mut self,
84
+ inference: Inference<Self::Term>,
85
+ ) -> impl Future<Output = Result<bool, Self::Error>> + Send;
86
+ /// Whether this attempt is cancelled/superseded. Awaited operations must also
87
+ /// support cancellation through the backend's own error/control boundary.
88
+ fn is_cancelled(&self) -> bool;
89
+ }
@@ -0,0 +1,111 @@
1
+ use super::{ReasoningError, ReasoningStore};
2
+ use datalog_structural_model::{Atom, Literal, Term, VariableSymbol};
3
+ use rdf_reasoning::{RuleId, TRIPLE_RELATION};
4
+
5
+ const VARIABLES: usize = 6;
6
+ pub(super) type Bindings<T> = [Option<T>; VARIABLES];
7
+
8
+ pub(super) enum Slot<T> {
9
+ Constant(T),
10
+ Variable(usize),
11
+ }
12
+ pub(super) struct Pattern<T>([Slot<T>; 3]);
13
+ pub(super) struct Clause<T> {
14
+ pub id: RuleId,
15
+ pub head: Pattern<T>,
16
+ pub body: [Pattern<T>; 2],
17
+ }
18
+
19
+ impl<T: Clone + Eq> Pattern<T> {
20
+ pub fn probe(&self, bindings: &Bindings<T>) -> [Option<T>; 3] {
21
+ std::array::from_fn(|i| match &self.0[i] {
22
+ Slot::Constant(value) => Some(value.clone()),
23
+ Slot::Variable(index) => bindings[*index].clone(),
24
+ })
25
+ }
26
+
27
+ pub fn bind(&self, tuple: &[T; 3], mut bindings: Bindings<T>) -> Option<Bindings<T>> {
28
+ for (slot, term) in self.0.iter().zip(tuple) {
29
+ match slot {
30
+ Slot::Constant(value) if value != term => return None,
31
+ Slot::Variable(index) => match &bindings[*index] {
32
+ Some(value) if value != term => return None,
33
+ None => bindings[*index] = Some(term.clone()),
34
+ Some(_) => {}
35
+ },
36
+ Slot::Constant(_) => {}
37
+ }
38
+ }
39
+ Some(bindings)
40
+ }
41
+
42
+ pub fn ground<E>(
43
+ &self,
44
+ bindings: &Bindings<T>,
45
+ id: RuleId,
46
+ ) -> Result<[T; 3], ReasoningError<E>> {
47
+ let [s, p, o] = self.probe(bindings);
48
+ match (s, p, o) {
49
+ (Some(s), Some(p), Some(o)) => Ok([s, p, o]),
50
+ _ => Err(ReasoningError::UnsupportedRule(id)),
51
+ }
52
+ }
53
+ }
54
+
55
+ impl<T: Clone + Eq + Send + Sync> Clause<T> {
56
+ pub async fn compile<S: ReasoningStore<Term = T>>(
57
+ id: RuleId,
58
+ store: &mut S,
59
+ ) -> Result<Self, ReasoningError<S::Error>> {
60
+ let rule = id.definition();
61
+ let [Literal::Positive(first), Literal::Positive(second)] = rule.body.as_slice() else {
62
+ return Err(ReasoningError::UnsupportedRule(id));
63
+ };
64
+ // bounded: two three-term body atoms bind at most six variables.
65
+ let mut variables = Vec::with_capacity(VARIABLES);
66
+ let first = Self::pattern(first, id, &mut variables, store).await?;
67
+ let second = Self::pattern(second, id, &mut variables, store).await?;
68
+ let head = Self::pattern(&rule.head, id, &mut variables, store).await?;
69
+ Ok(Self {
70
+ id,
71
+ head,
72
+ body: [first, second],
73
+ })
74
+ }
75
+
76
+ async fn pattern<S: ReasoningStore<Term = T>>(
77
+ atom: &Atom,
78
+ id: RuleId,
79
+ variables: &mut Vec<VariableSymbol>,
80
+ store: &mut S,
81
+ ) -> Result<Pattern<T>, ReasoningError<S::Error>> {
82
+ if atom.predicate.as_str() != TRIPLE_RELATION || atom.terms.len() != 3 {
83
+ return Err(ReasoningError::UnsupportedRule(id));
84
+ }
85
+ let mut result = std::array::from_fn(|_| Slot::Variable(0));
86
+ for (index, term) in atom.terms.iter().enumerate() {
87
+ result[index] = match term {
88
+ Term::Constant(iri) => Slot::Constant(
89
+ store
90
+ .resolve_iri(iri.as_str())
91
+ .await
92
+ .map_err(ReasoningError::Storage)?,
93
+ ),
94
+ Term::Variable(variable) => {
95
+ let slot = if let Some(slot) = variables.iter().position(|v| v == variable) {
96
+ slot
97
+ } else {
98
+ if variables.len() == VARIABLES {
99
+ return Err(ReasoningError::UnsupportedRule(id));
100
+ }
101
+ variables.push(variable.clone());
102
+ variables.len() - 1
103
+ };
104
+ Slot::Variable(slot)
105
+ }
106
+ _ => return Err(ReasoningError::UnsupportedRule(id)),
107
+ };
108
+ }
109
+ Ok(Pattern(result))
110
+ }
111
+ }
@@ -0,0 +1,146 @@
1
+ use rdf_reasoning::RuleId;
2
+ use serde::{Deserialize, Serialize};
3
+ use std::{
4
+ error::Error,
5
+ fmt,
6
+ num::{NonZeroU32, NonZeroU64},
7
+ str::FromStr,
8
+ };
9
+
10
+ /// Precisely supported executable profile; distinct from compile-only presets.
11
+ #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
12
+ pub enum ExecutionProfile {
13
+ /// Only subclass transitivity and inherited membership, no axioms or other rules.
14
+ #[serde(rename = "rdfs-subclass")]
15
+ RdfsSubclass,
16
+ }
17
+
18
+ impl ExecutionProfile {
19
+ /// Stable profile name; this is not full RDFS support.
20
+ pub const fn name(self) -> &'static str {
21
+ "rdfs-subclass"
22
+ }
23
+ /// Profile definition revision, independent of package implementation version.
24
+ pub const fn revision(self) -> u32 {
25
+ 1
26
+ }
27
+ /// Exact rule identities from `rdf-reasoning` 2.6.0, in execution order.
28
+ pub const fn rules(self) -> &'static [RuleId; 2] {
29
+ &[RuleId::Rdfs9, RuleId::Rdfs11]
30
+ }
31
+ }
32
+
33
+ impl FromStr for ExecutionProfile {
34
+ type Err = ProfileError;
35
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
36
+ match value {
37
+ "rdfs-subclass" => Ok(Self::RdfsSubclass),
38
+ _ => Err(ProfileError(value.to_owned())),
39
+ }
40
+ }
41
+ }
42
+
43
+ /// Requested profile is not executable; no weaker profile was substituted.
44
+ #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
45
+ pub struct ProfileError(String);
46
+ impl fmt::Display for ProfileError {
47
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48
+ write!(f, "unsupported executable profile: {}", self.0)
49
+ }
50
+ }
51
+ impl Error for ProfileError {}
52
+
53
+ /// Explicit finite work/output limits; reaching a limit fails the attempt.
54
+ #[derive(Clone, Copy, Debug, Serialize, Deserialize)]
55
+ #[serde(deny_unknown_fields)]
56
+ pub struct RunLimits {
57
+ pub(super) rounds: NonZeroU32,
58
+ pub(super) inferred: NonZeroU64,
59
+ pub(super) matches: NonZeroU64,
60
+ }
61
+ impl RunLimits {
62
+ /// Set maximum rounds (including the final empty round), novel tuples and
63
+ /// examined cursor rows. The caller separately budgets scratch disk/I/O.
64
+ pub const fn new(rounds: NonZeroU32, inferred: NonZeroU64, matches: NonZeroU64) -> Self {
65
+ Self {
66
+ rounds,
67
+ inferred,
68
+ matches,
69
+ }
70
+ }
71
+ }
72
+
73
+ /// One novel tuple and a two-premise witness from the selected shared rule.
74
+ #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
75
+ #[serde(deny_unknown_fields)]
76
+ pub struct Inference<T> {
77
+ /// Derived subject, predicate and object, preserving caller term identity.
78
+ pub triple: [T; 3],
79
+ /// Rule that produced this witness.
80
+ pub rule: RuleId,
81
+ /// Matching body tuples in shared rule order; either can itself be inferred.
82
+ pub premises: [[T; 3]; 2],
83
+ }
84
+
85
+ /// Completed work counters; returned only after successful fixpoint detection.
86
+ #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
87
+ pub struct RunReport {
88
+ /// Completed rounds, including the final round with no additions.
89
+ pub rounds: u32,
90
+ /// Examined cursor rows, including repeated probes across rounds.
91
+ pub matches: u64,
92
+ /// Novel inferred tuples, excluding asserted and inferred duplicates.
93
+ pub inferred: u64,
94
+ }
95
+
96
+ /// Resource budget that prevented complete inference.
97
+ #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
98
+ pub enum Limit {
99
+ /// Round count reached before proving a fixpoint.
100
+ Rounds,
101
+ /// Maximum number of novel inferred tuples.
102
+ Inferred,
103
+ /// Maximum examined cursor rows.
104
+ Matches,
105
+ }
106
+
107
+ /// Failure of the entire attempt; any staged output must remain unpublished.
108
+ #[derive(Debug)]
109
+ pub enum ReasoningError<E> {
110
+ /// Fallible backend read, resolution or write failed.
111
+ Storage(E),
112
+ /// Caller cancelled or superseded the attempt.
113
+ Cancelled,
114
+ /// Explicit budget prevented complete closure.
115
+ LimitExceeded(Limit),
116
+ /// Pinned shared rule no longer has the supported flat two-body form.
117
+ UnsupportedRule(RuleId),
118
+ }
119
+ impl<E: fmt::Display> fmt::Display for ReasoningError<E> {
120
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121
+ match self {
122
+ Self::Storage(error) => write!(f, "reasoning storage failed: {error}"),
123
+ Self::Cancelled => f.write_str("reasoning cancelled"),
124
+ Self::LimitExceeded(limit) => write!(
125
+ f,
126
+ "reasoning {} limit exceeded",
127
+ match limit {
128
+ Limit::Rounds => "rounds",
129
+ Limit::Inferred => "inferred",
130
+ Limit::Matches => "matches",
131
+ }
132
+ ),
133
+ Self::UnsupportedRule(rule) => {
134
+ write!(f, "unsupported shared rule definition: {rule:?}")
135
+ }
136
+ }
137
+ }
138
+ }
139
+ impl<E: Error + 'static> Error for ReasoningError<E> {
140
+ fn source(&self) -> Option<&(dyn Error + 'static)> {
141
+ match self {
142
+ Self::Storage(error) => Some(error),
143
+ _ => None,
144
+ }
145
+ }
146
+ }
@@ -0,0 +1,11 @@
1
+ //! Backend stores need not be Sync to execute on a multithreaded runtime.
2
+
3
+ use inference_engine::reasoning::{Reasoner, ReasoningStore};
4
+ use std::future::Future;
5
+
6
+ fn require_send(_: impl Future + Send) {}
7
+
8
+ #[allow(dead_code)]
9
+ fn executor_future_is_send<S: ReasoningStore>(reasoner: &Reasoner, store: &mut S) {
10
+ require_send(reasoner.run(store));
11
+ }
@@ -0,0 +1,285 @@
1
+ //! Executable two-rule RDFS contract against a bounded test-only store.
2
+
3
+ use inference_engine::reasoning::{
4
+ ExecutionProfile, Inference, Reasoner, ReasoningStore, RunLimits, TripleCursor, TripleSource,
5
+ };
6
+ use std::{
7
+ collections::BTreeSet,
8
+ io,
9
+ num::{NonZeroU32, NonZeroU64},
10
+ };
11
+
12
+ const TYPE: u64 = 1;
13
+ const SUBCLASS: u64 = 2;
14
+ type Triple = [u64; 3];
15
+
16
+ struct Cursor(std::vec::IntoIter<Triple>, bool);
17
+
18
+ impl TripleCursor for Cursor {
19
+ type Term = u64;
20
+ type Error = io::Error;
21
+ async fn next(&mut self) -> io::Result<Option<Triple>> {
22
+ let next = self.0.next();
23
+ if next.is_none() && self.1 {
24
+ return Err(io::Error::other("cursor failed after rows"));
25
+ }
26
+ Ok(next)
27
+ }
28
+ }
29
+
30
+ struct Snapshot(BTreeSet<Triple>, bool);
31
+
32
+ impl TripleSource for Snapshot {
33
+ type Term = u64;
34
+ type Error = io::Error;
35
+ type Cursor = Cursor;
36
+ async fn scan(&self, pattern: [Option<u64>; 3]) -> io::Result<Cursor> {
37
+ // bounded: these test fixtures contain fewer than thirty triples.
38
+ Ok(Cursor(
39
+ self.0
40
+ .iter()
41
+ .filter(|triple| {
42
+ pattern
43
+ .iter()
44
+ .zip(triple.iter())
45
+ .all(|(p, t)| p.is_none_or(|p| p == *t))
46
+ })
47
+ .copied()
48
+ .collect::<Vec<_>>()
49
+ .into_iter(),
50
+ self.1,
51
+ ))
52
+ }
53
+ }
54
+
55
+ #[derive(Default)]
56
+ struct Store {
57
+ asserted: BTreeSet<Triple>,
58
+ inferred: BTreeSet<Triple>,
59
+ evidence: Vec<Inference<u64>>,
60
+ cancelled: bool,
61
+ fail_read: bool,
62
+ fail_write: bool,
63
+ fail_cursor: bool,
64
+ fail_after_writes: Option<usize>,
65
+ }
66
+
67
+ impl Store {
68
+ fn new(asserted: impl IntoIterator<Item = Triple>) -> Self {
69
+ // bounded: these test fixtures contain fewer than thirty triples.
70
+ Self {
71
+ asserted: asserted.into_iter().collect(),
72
+ ..Self::default()
73
+ }
74
+ }
75
+ }
76
+
77
+ impl ReasoningStore for Store {
78
+ type Term = u64;
79
+ type Error = io::Error;
80
+ type Snapshot = Snapshot;
81
+ async fn resolve_iri(&mut self, iri: &str) -> io::Result<u64> {
82
+ match iri {
83
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" => Ok(TYPE),
84
+ "http://www.w3.org/2000/01/rdf-schema#subClassOf" => Ok(SUBCLASS),
85
+ _ => Err(io::Error::other("unexpected rule constant")),
86
+ }
87
+ }
88
+ async fn snapshot(&mut self) -> io::Result<Snapshot> {
89
+ if self.fail_read {
90
+ return Err(io::Error::other("read failed"));
91
+ }
92
+ // bounded: these test fixtures contain fewer than thirty triples.
93
+ Ok(Snapshot(
94
+ self.asserted.union(&self.inferred).copied().collect(),
95
+ self.fail_cursor,
96
+ ))
97
+ }
98
+ async fn contains(&mut self, triple: &Triple) -> io::Result<bool> {
99
+ Ok(self.asserted.contains(triple) || self.inferred.contains(triple))
100
+ }
101
+ async fn insert_inferred(&mut self, inference: Inference<u64>) -> io::Result<bool> {
102
+ if self.fail_write || self.fail_after_writes == Some(self.evidence.len()) {
103
+ return Err(io::Error::other("write failed"));
104
+ }
105
+ if self.asserted.contains(&inference.triple) {
106
+ return Ok(false);
107
+ }
108
+ let inserted = self.inferred.insert(inference.triple);
109
+ if inserted {
110
+ // bounded: these test fixtures contain fewer than thirty consequences.
111
+ self.evidence.push(inference);
112
+ }
113
+ Ok(inserted)
114
+ }
115
+ fn is_cancelled(&self) -> bool {
116
+ self.cancelled
117
+ }
118
+ }
119
+
120
+ fn limits(inferred: u64, rounds: u32, matches: u64) -> RunLimits {
121
+ RunLimits::new(
122
+ NonZeroU32::new(rounds).unwrap(),
123
+ NonZeroU64::new(inferred).unwrap(),
124
+ NonZeroU64::new(matches).unwrap(),
125
+ )
126
+ }
127
+
128
+ fn reasoner() -> Reasoner {
129
+ Reasoner::new(ExecutionProfile::RdfsSubclass, limits(100, 20, 10_000))
130
+ }
131
+
132
+ #[tokio::test]
133
+ async fn derives_transitive_subclasses_and_inherited_membership() {
134
+ let mut store = Store::new([[10, SUBCLASS, 11], [11, SUBCLASS, 12], [20, TYPE, 10]]);
135
+ let report = reasoner().run(&mut store).await.unwrap();
136
+ assert_eq!(
137
+ store.inferred,
138
+ BTreeSet::from([[10, SUBCLASS, 12], [20, TYPE, 11], [20, TYPE, 12]])
139
+ );
140
+ assert_eq!(report.inferred, 3);
141
+ assert_eq!(store.asserted.len(), 3);
142
+ assert!(store.evidence.iter().all(|evidence| {
143
+ evidence
144
+ .premises
145
+ .iter()
146
+ .all(|p| store.asserted.contains(p) || store.inferred.contains(p))
147
+ }));
148
+ }
149
+
150
+ #[tokio::test]
151
+ async fn cycles_terminate_and_assertions_win_duplicates() {
152
+ let mut store = Store::new([
153
+ [10, SUBCLASS, 11],
154
+ [11, SUBCLASS, 10],
155
+ [20, TYPE, 10],
156
+ [20, TYPE, 11],
157
+ ]);
158
+ reasoner().run(&mut store).await.unwrap();
159
+ assert_eq!(
160
+ store.inferred,
161
+ BTreeSet::from([[10, SUBCLASS, 10], [11, SUBCLASS, 11]])
162
+ );
163
+ }
164
+
165
+ #[tokio::test]
166
+ async fn never_reverses_subclass_membership() {
167
+ let mut store = Store::new([[10, SUBCLASS, 11], [20, TYPE, 11]]);
168
+ reasoner().run(&mut store).await.unwrap();
169
+ assert!(store.inferred.is_empty());
170
+ }
171
+
172
+ #[tokio::test]
173
+ async fn late_cursor_and_write_failures_leave_only_unpublished_staging() {
174
+ let mut store = Store::new([[10, SUBCLASS, 11], [20, TYPE, 10]]);
175
+ store.fail_cursor = true;
176
+ let error = reasoner().run(&mut store).await.unwrap_err();
177
+ assert!(error.to_string().contains("cursor failed"));
178
+ assert_eq!(store.inferred.len(), 1);
179
+
180
+ let mut store = Store::new([[10, SUBCLASS, 11], [11, SUBCLASS, 12], [20, TYPE, 10]]);
181
+ store.fail_after_writes = Some(1);
182
+ let error = reasoner().run(&mut store).await.unwrap_err();
183
+ assert!(error.to_string().contains("write failed"));
184
+ assert_eq!(store.inferred.len(), 1);
185
+ }
186
+
187
+ #[tokio::test]
188
+ async fn exact_output_limit_can_still_prove_fixpoint_and_empty_input_is_valid() {
189
+ let mut store = Store::new([[10, SUBCLASS, 11], [11, SUBCLASS, 12], [20, TYPE, 10]]);
190
+ let report = Reasoner::new(ExecutionProfile::RdfsSubclass, limits(3, 20, 10_000))
191
+ .run(&mut store)
192
+ .await
193
+ .unwrap();
194
+ assert_eq!(report.inferred, 3);
195
+ let report = reasoner().run(&mut Store::default()).await.unwrap();
196
+ assert_eq!((report.rounds, report.inferred), (1, 0));
197
+ }
198
+
199
+ #[test]
200
+ fn portable_execution_values_round_trip_without_a_json_intermediate() {
201
+ let evidence = Inference {
202
+ triple: [10, SUBCLASS, 12],
203
+ rule: rdf_reasoning::RuleId::Rdfs11,
204
+ premises: [[10, SUBCLASS, 11], [11, SUBCLASS, 12]],
205
+ };
206
+ let json = serde_json::to_vec(&evidence).unwrap();
207
+ assert_eq!(
208
+ serde_json::from_slice::<Inference<u64>>(&json).unwrap(),
209
+ evidence
210
+ );
211
+ let binary = postcard::to_allocvec(&evidence).unwrap();
212
+ assert_eq!(
213
+ postcard::from_bytes::<Inference<u64>>(&binary).unwrap(),
214
+ evidence
215
+ );
216
+ assert!(serde_json::from_str::<RunLimits>(r#"{"rounds":0,"inferred":1,"matches":1}"#).is_err());
217
+ assert!(postcard::from_bytes::<RunLimits>(&[0, 1, 1]).is_err());
218
+ assert!(
219
+ serde_json::from_str::<RunLimits>(
220
+ r#"{"rounds":1,"inferred":1,"matches":1,"fallback":true}"#
221
+ )
222
+ .is_err()
223
+ );
224
+ assert!(serde_json::from_str::<Inference<u64>>(r#"{"triple":[10,2,12],"rule":"rdfs11","premises":[[10,2,11],[11,2,12]],"source":"ignored"}"#).is_err());
225
+ }
226
+
227
+ #[tokio::test]
228
+ async fn recomputation_after_deletion_does_not_seed_old_inference() {
229
+ let mut before = Store::new([[10, SUBCLASS, 11], [11, SUBCLASS, 12], [20, TYPE, 10]]);
230
+ reasoner().run(&mut before).await.unwrap();
231
+ assert!(before.inferred.contains(&[20, TYPE, 12]));
232
+ let mut after = Store::new([[10, SUBCLASS, 11], [20, TYPE, 10]]);
233
+ reasoner().run(&mut after).await.unwrap();
234
+ assert_eq!(after.inferred, BTreeSet::from([[20, TYPE, 11]]));
235
+ }
236
+
237
+ #[tokio::test]
238
+ async fn budgets_fail_without_inserting_beyond_the_limit() {
239
+ let mut store = Store::new([[10, SUBCLASS, 11], [11, SUBCLASS, 12], [20, TYPE, 10]]);
240
+ let error = Reasoner::new(ExecutionProfile::RdfsSubclass, limits(1, 20, 10_000))
241
+ .run(&mut store)
242
+ .await
243
+ .unwrap_err();
244
+ assert!(error.to_string().contains("inferred"));
245
+ assert_eq!(store.inferred.len(), 1);
246
+ for (rounds, matches) in [(1, 10_000), (20, 1)] {
247
+ let mut store = Store::new([[10, SUBCLASS, 11], [11, SUBCLASS, 12], [20, TYPE, 10]]);
248
+ assert!(
249
+ Reasoner::new(ExecutionProfile::RdfsSubclass, limits(100, rounds, matches))
250
+ .run(&mut store)
251
+ .await
252
+ .is_err()
253
+ );
254
+ }
255
+ }
256
+
257
+ #[tokio::test]
258
+ async fn cancellation_and_storage_errors_are_not_success() {
259
+ for (cancelled, fail_read, fail_write) in [
260
+ (true, false, false),
261
+ (false, true, false),
262
+ (false, false, true),
263
+ ] {
264
+ let mut store = Store::new([[10, SUBCLASS, 11], [20, TYPE, 10]]);
265
+ store.cancelled = cancelled;
266
+ store.fail_read = fail_read;
267
+ store.fail_write = fail_write;
268
+ assert!(reasoner().run(&mut store).await.is_err());
269
+ }
270
+ }
271
+
272
+ #[test]
273
+ fn unsupported_profiles_are_not_silently_weakened() {
274
+ assert_eq!(
275
+ "rdfs-subclass".parse::<ExecutionProfile>().unwrap(),
276
+ ExecutionProfile::RdfsSubclass
277
+ );
278
+ for name in ["rdfs-core", "rdfs", "owl2-rl", "isSubclassOf"] {
279
+ assert!(name.parse::<ExecutionProfile>().is_err());
280
+ }
281
+ assert_eq!(
282
+ ExecutionProfile::RdfsSubclass.rules(),
283
+ &[rdf_reasoning::RuleId::Rdfs9, rdf_reasoning::RuleId::Rdfs11]
284
+ );
285
+ }