datalog-structural-model 3.2.2

Typed Datalog rule IR, validation, and stratification
Documentation
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
# datalog-structural-model

[![Crates.io](https://img.shields.io/crates/v/datalog-structural-model.svg?cacheSeconds=300)](https://crates.io/crates/datalog-structural-model)
[![Documentation](https://docs.rs/datalog-structural-model/badge.svg?cacheSeconds=300)](https://docs.rs/datalog-structural-model)
[![CI](https://github.com/legra-ai/datalog-structural-model/actions/workflows/ci.yml/badge.svg?branch=main&cacheSeconds=300)](https://github.com/legra-ai/datalog-structural-model/actions/workflows/ci.yml)
[![Downloads](https://img.shields.io/crates/d/datalog-structural-model.svg?cacheSeconds=300)](https://crates.io/crates/datalog-structural-model)
[![License](https://img.shields.io/crates/l/datalog-structural-model.svg?cacheSeconds=300)](LICENSE-APACHE)

Typed Datalog rule programs, validation, and stratification analysis.

`datalog-structural-model` is the finite rule-program layer between a rule authoring or
compiler front-end and an evaluator. It models predicates, variables, terms,
atoms, rules, filters, bindings, and aggregates, then validates safety and
computes rule strata over complete tuple patterns for programs with negation.

It does not read input data, execute rules, retain a fact store, or collect
solutions. Evaluation engines can consume a validated `Program` while keeping
facts and derived results in their own asynchronous, backpressured, and
spill-capable data paths.

## A small rule program

```rust
use datalog_structural_model::{
    Atom,
    ConstantSymbol,
    Literal,
    PredicateSymbol,
    Program,
    Rule,
    Term,
    VariableSymbol,
};

let person = PredicateSymbol::new("person");
let ancestor = PredicateSymbol::new("ancestor");
let x = VariableSymbol::new("x");
let y = VariableSymbol::new("y");
let z = VariableSymbol::new("z");

let parent_xy = Atom {
    predicate: PredicateSymbol::new("parent"),
    terms: vec![Term::Variable(x.clone()), Term::Variable(y.clone())],
};
let ancestor_yz = Atom {
    predicate: ancestor.clone(),
    terms: vec![Term::Variable(y), Term::Variable(z.clone())],
};
let ancestor_xz = Atom {
    predicate: ancestor,
    terms: vec![Term::Variable(x), Term::Variable(z)],
};

let program = Program {
    rules: vec![Rule::new(
        ancestor_xz,
        vec![Literal::Positive(parent_xy), Literal::Positive(ancestor_yz)],
    )],
};

program.validate().expect("the rule is safe and stratifiable");
assert_eq!(person.as_str(), "person");
assert_eq!(ConstantSymbol::new("example").as_str(), "example");
```

The rule model is deliberately separate from execution. A caller may build a
program in memory because a rule program is a finite description, but the
facts matched by that program are not part of this crate and must not be
materialized here.

## Rule heads

`Rule::head` is a `RuleHead`:

- `Atom` — one atom, plain Datalog;
- `Conjunction(HeadConjunction)` — several atoms derived from one body match;
- `Existential { variables, conjunction }` — `∃ variables . conjunction`;
- `Disjunction(HeadDisjunction)` — at least one conjunction holds;
- `Falsum` — `false`, an inconsistency constraint: the body must not match.

`HeadConjunction`, `HeadDisjunction` and `ExistentialVariables` are non-empty
by construction and by deserialization (`EmptyHeadCollection`, code
`empty-head-collection`); existential variables form a sorted set.
`Rule::new` and `Rule::positive` accept anything convertible into a
`RuleHead`, including an `Atom`.

`Rule::head_form()` returns a `HeadForm` (`Atomic`, `Conjunctive`,
`Existential`, `Disjunctive`, `Inconsistency`), a pure function of the head
with fixed precedence: falsum, then existential, then more than one disjunct,
then more than one atom, else atomic. A one-atom conjunction is therefore
atomic. There is no no-output head: an operational rule that runs its body but
emits nothing has meaning only to an evaluator, and this crate never executes
rules, so `Falsum` is the only empty head.

Every head reads as disjuncts of atoms; `HeadAtomPath` (a `HeadDisjunctIndex`
and a `HeadAtomIndex`) addresses one atom, and an atomic head is disjunct 0,
atom 0. Range restriction exempts existential variables, which must occur in
the head (`unused-existential-variable`) and must not be bound by the body
(`existential-variable-bound-in-body`). Every atom of a conjunctive,
existential or disjunctive head is a producer for stratification; `Falsum`
produces nothing.

```rust
use datalog_structural_model::{
    Atom, DatalogCapabilities, DatalogFeature, DatalogProfile, EqualityMode,
    ExistentialVariables, HeadConjunction, HeadForm, PredicateSymbol, ProfileCheckError,
    Program, Rule, RuleHead, RuleIndex, Term, VariableSymbol,
};

let x = || Term::Variable(VariableSymbol::new("x"));
let y = || Term::Variable(VariableSymbol::new("y"));
let atom = |p: &str, terms| Atom { predicate: PredicateSymbol::new(p), terms };
let head = RuleHead::Existential {
    variables: ExistentialVariables::try_new([VariableSymbol::new("y")])?,
    conjunction: HeadConjunction::try_new(vec![atom("owns", vec![x(), y()])])?,
};
let program = Program::try_new(vec![Rule::positive(head, vec![atom("person", vec![x()])])])?;
assert_eq!(program.rules[0].head_form(), HeadForm::Existential);
assert_eq!(
    program.validate_for(&DatalogProfile::positive()),
    Err(ProfileCheckError::UnsupportedHeadForm {
        rule: RuleIndex::new(0),
        form: HeadForm::Existential,
    })
);
let chase = DatalogProfile::new(
    DatalogCapabilities::positive().with(DatalogFeature::ExistentialHeads),
    EqualityMode::Default,
);
program.validate_for(&chase)?;
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Validation and stratification

`Program::validate` checks range restriction, variable safety, supported
expression structure, and the absence of cycles through negation. A valid
program can be passed to a forward or backward evaluator. `Program::stratify`
exposes the calculated strata when an evaluator needs to schedule them.

The dependency graph uses strongly connected components and preserves the
distinction between positive and negative dependencies. A recursive positive
cycle is valid; a cycle that contains a negated dependency is rejected.


### Error locations and codes

Every validation error that concerns a location names it with typed
positions: a `RuleIndex`, a `RuleSite` (a head atom's `HeadAtomPath`, or
the body), a `LiteralPath` (the
body literal, then one step per enclosing aggregate), and a `TermPath` (an
`AtomSlot` or `ExpressionTermIndex`, then one argument slot per nested triple
term or Skolem call). A cycle through negation or aggregation reports an
`UnstratifiableCycle`: the rules and predicates of the component plus the
offending `StrictDependency` — producer rule, consumer rule, consumer literal,
and whether the edge is negation or aggregation.

Each error variant has a stable kebab-case `ErrorCode` (`error.code()`, also
available as `CODE_*` associated constants), such as `unsafe-negation` or
`unstratifiable-cycle`. Codes are pinned by a census test and do not change
when a variant is renamed.

```rust
use datalog_structural_model::{
    Atom, Literal, LiteralIndex, LiteralPath, PredicateSymbol, Program,
    ProgramValidationError, Rule, RuleIndex, Term, VariableSymbol,
};

let x = Term::Variable(VariableSymbol::new("x"));
let y = Term::Variable(VariableSymbol::new("y"));
let atom = |p: &str, terms: Vec<Term>| Atom { predicate: PredicateSymbol::new(p), terms };
let error = Program::try_new(vec![Rule::new(
    atom("lonely", vec![x.clone()]),
    vec![
        Literal::Positive(atom("person", vec![x.clone()])),
        Literal::Negative(atom("knows", vec![x, y])),
    ],
)])
.unwrap_err();
assert_eq!(error.code().as_str(), "unsafe-negation");
let ProgramValidationError::UnsafeNegation { rule, literal, .. } = error else {
    unreachable!()
};
assert_eq!(rule, RuleIndex::new(0));
assert_eq!(literal, LiteralPath::top(LiteralIndex::new(1)));
```

## Serialization and checked loading

All public semantic data supports Serde directly, including symbols, nested
terms, expressions, aggregates, rules, programs, profiles and diagnostics.
JSON and Postcard are exercised; the model does not use a JSON intermediate.
Symbols serialize as exact text. Cached hashes and allocation identity are
rebuilt through the symbol constructors and never appear in serialized data.

`Program::try_new` and `Rule::try_new` validate checked construction. Their
Serde inputs use those same paths: unsafe variables, invalid Skolem placement,
excessive term nesting and cycles through negation fail on input. Standalone
`Term` and `GroundTerm` decoding checks context-free structure; rule position
and variable binding still require program validation. Raw public fields remain
available for authoring invalid source descriptions and reporting their errors;
those descriptions cannot bypass checked loading into executable programs.
Unknown semantic fields and enum variants are rejected.

```rust
use datalog_structural_model::{
    Atom, ConstantSymbol, DatalogProfile, PredicateSymbol, Program, Rule, Term,
};

let atom = Atom {
    predicate: PredicateSymbol::new("person"),
    terms: vec![Term::Constant(ConstantSymbol::new("alice"))],
};
let program = Program::try_new(vec![Rule::positive(atom, vec![])])?;
let profile = DatalogProfile::positive();
program.validate_for(&profile)?;
let bytes = postcard::to_allocvec(&program)?;
let loaded: Program = postcard::from_bytes(&bytes)?;
loaded.validate_for(&profile)?;
assert_eq!(program, loaded);
# Ok::<(), Box<dyn std::error::Error>>(())
```

Serialized forms are pinned by exact JSON and Postcard golden files under
`tests/golden`; regenerate them deliberately with
`UPDATE_GOLDEN=1 cargo test --test golden_corpus`.

Stratification results serialize as reports. Recompute stratification from the
validated program when scheduling execution; loading a report does not certify
an executable plan. Serde encodings are neither canonical hashes (see `ProgramDigest`) nor RDF
concrete syntaxes. Callers own decoding resource budgets; this crate owns structural and
program-safety validation. Structural ceilings are typed `ValidationLimits`
(see below).

## Termination: weak acyclicity

Skolem terms, head triple terms, `BIND` and aggregates invent values, so a
recursive program can derive facts forever. `Program::check_weak_acyclicity`
builds the position graph and returns `Result<WeakAcyclicity,
TerminationViolation>`. Nodes are argument slots of atom occurrences
(`ArgumentPosition`: predicate, `AtomSlot`, `RuleIndex`, `RuleSite`). A head
variable copied from a body slot adds an ordinary edge; a value invented in the
head adds a special edge from every body slot feeding it. An existential head
variable is treated like a Skolem term over the frontier: its slot receives an
`InventionKind::Existential` special edge from every body slot binding a
non-existential head variable. Every head atom is its own occurrence. A head
slot feeds a
body slot only when the two atoms can match the same fact, so constants that
keep patterns apart also break cycles. The analysis reads only the program,
reuses the stratifier's Tarjan traversal, and is bounded by program size, never
by data.

A program is weakly acyclic when no special edge lies on a strongly connected
component. The certificate reports `skolem_depth()`, the most special edges on
any path. A violation carries the first cyclic `SpecialEdge` in canonical
order, its sorted component, and the stable code `not-weakly-acyclic`. The
criterion is a versioned `#[non_exhaustive]` `TerminationCriterion`
(`WeaklyAcyclic`, `label()` `weakly-acyclic`, `law_version()` 1). It is
sufficient, not necessary: a violation is not a proof of divergence.

```rust
use datalog_structural_model::{
    Atom, ConstantSymbol, InventionKind, PredicateSymbol, Program, Rule, Term, VariableSymbol,
};

let x = Term::Variable(VariableSymbol::new("x"));
let next = Term::Skolem { name: ConstantSymbol::new("next"), args: vec![x.clone()] };
let node = |term| Atom { predicate: PredicateSymbol::new("node"), terms: vec![term] };
let program = Program { rules: vec![Rule::positive(node(next), vec![node(x)])] };
let violation = program.check_weak_acyclicity().unwrap_err();
assert_eq!(violation.code().as_str(), "not-weakly-acyclic");
assert_eq!(violation.edge().kind, InventionKind::Skolem);
```

## Validation limits

`ValidationLimits` bounds triple-term nesting depth (standard 4), rule count
(65,536), literals per rule including aggregate bodies (1,024) and Skolem depth
(64). `Program::validate` uses the standard limits; `Program::validate_within`
takes explicit ones. Each `DatalogProfile` owns its limits (`with_limits`,
`limits`), and `Program::validate_for` enforces them. It also requires weak
acyclicity (`ProfileCheckError::TerminationUncertified`) and a certified Skolem
depth within the limit. Limit errors (`rule-count-exceeded`,
`body-length-exceeded`, `triple-term-nesting-exceeded`, `skolem-depth-exceeded`)
report the limit and the value reached.

## Program and contract digests

`Program::digest` returns a `ProgramDigest`: a 32-byte BLAKE3 content identity
of the program as authored. It is computed from a canonical preimage, never
from a Serde encoding, so JSON, Postcard and in-memory construction of the same
program give the same digest.

The preimage starts with the versioned domain tag
`datalog-structural-model/program-digest/v1`, then writes fields in a fixed
order. Every text field and every sequence is prefixed with its length as a
`u64` little-endian value, and every enum variant writes its own tag byte. As a
result:

- rule order, body literal order, argument order, group-by order and
  aggregate inner-body order are significant;
- variables, constants, triple terms and Skolem terms are distinct, so a
  variable `x` never collides with a constant `x`;
- positive, negative, filter, bind and aggregate literals and every filter,
  expression and aggregator operator are distinct;
- an atomic head writes its atom exactly as the original encoding did, so
  existing digests are unchanged; every other head form writes the count
  `u64::MAX` (never a valid text length, so never the start of an atom) and a
  form tag, then its existential variables, conjunction or disjuncts. A
  one-atom conjunction and an atom are different authored programs with
  different digests.

`ValidationContract` pairs an `EqualityMode`, `ValidationLimits` and a
`TerminationCriterion` (with its law version). `ValidationContract::digest_for`
returns a `ContractDigest` over the program digest and those parameters under
the tag `datalog-structural-model/contract-digest/v1`. The program digest
excludes them on purpose: the same program checked under different limits or
termination laws is still the same program, while a cache of validation
outcomes keys on the contract digest.

Both digests display as 64 lowercase hex characters and parse back with
`FromStr`. Digests are published identities, frozen by
`tests/digest_golden.rs`. Any change to the preimage introduces a new
domain-tag version; it never silently moves an existing digest.

```rust
use datalog_structural_model::{
    Atom, EqualityMode, PredicateSymbol, Program, ProgramDigest, Rule, Term,
    TerminationCriterion, ValidationContract, ValidationLimits, VariableSymbol,
};

let x = Term::Variable(VariableSymbol::new("x"));
let atom = |name: &str| Atom { predicate: PredicateSymbol::new(name), terms: vec![x.clone()] };
let program = Program::try_new(vec![Rule::positive(atom("q"), vec![atom("p")])])?;
let digest = program.digest();
assert_eq!(digest.to_string().parse::<ProgramDigest>()?, digest);

let contract = ValidationContract::new(
    EqualityMode::Default,
    ValidationLimits::standard(),
    TerminationCriterion::WeaklyAcyclic,
);
assert_ne!(contract.digest_for(&program).as_bytes(), digest.as_bytes());
# Ok::<(), Box<dyn std::error::Error>>(())
```

The required test job also executes fixed head and grounded-value digest vectors
on `wasm32-wasip1`, using Node 26.13.1's WASI runtime, from both the checkout and
packaged archive. This checks the same identities on a real 32-bit target;
native Linux and Windows checks cover 64-bit targets. From a checkout with the
pinned compiler, that target and Node installed, run
`python3 scripts/test-portable-digests.py`.

## Grounded value digests

`GroundTerm::digest` returns a typed `GroundTermDigest` over the exact grounded
value. Constant text is not normalized. Constants and structured values remain
distinct, including when their display text is identical. Predicates, argument
counts, argument order and nested structure participate in the identity.

The preimage uses the same length-framed BLAKE3 pipeline as program identities,
under `datalog-structural-model/ground-term-digest/v1`. A constant writes tag `0`
and its length-prefixed text. A structured value writes tag `1`, its
length-prefixed predicate, its argument count, then the grounded arguments in
order. Text lengths and counts are `u64` little-endian values. Embedded delimiter
bytes cannot merge argument boundaries. Identity does not select structural
admission limits; use the checked constructors or structural validation for that.

All three digest types support format-neutral Serde as fixed 32-byte arrays,
including inside nested JSON and binary values. This transport is separate from
the canonical hash preimage and from the lowercase hexadecimal display/parse
API. Grounded v1 identities are frozen in `tests/ground_digest.rs`; changing their
encoding requires a new domain version.

```rust
use datalog_structural_model::{ConstantSymbol, GroundAtom, GroundTerm, PredicateSymbol};

let value = GroundTerm::try_triple_term(GroundAtom {
    predicate: PredicateSymbol::new("related"),
    args: vec![GroundTerm::constant(ConstantSymbol::new("alice"))],
})?;
assert_eq!(value.digest(), value.clone().digest());
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Triple-term adapter conventions

`Term::TripleTerm` contains a generic structured `Atom`. The RDF reasoning
catalogue's convention uses a fixed `urn:rdf-reasoning:triple` relation with
three ordered operands `[subject, predicate, object]`, recursively. The RDF
predicate can be a bound variable because it is an operand, distinct from the
fixed Datalog relation symbol. A two-operand atom with its RDF predicate in the
relation symbol is a different structure; the model does not translate it.

Checked construction and nested JSON/Postcard preserve all three operands and
reject unbound variables, including a nested predicate variable. Programs need
the explicit `TripleTerms` capability. These checks do not implement term
construction or unification, validate RDF term domains/scope, or certify an
entailment regime. Adapters own those contracts. Display text is not identity.

## Explicit Datalog language profiles

`DatalogProfile::positive()` describes positive flat Datalog without extension
operators. `DatalogProfile::stratified()` adds stratified negation. Custom profiles
pair an explicit `DatalogCapabilities` set with an equality validation regime.

`Program::required_capabilities()` inspects the entire program, including nested
bindings, filters, triple terms, Skolem terms, aggregate inner bodies and head
forms. Filter,
binding and aggregate requirements identify exact operations, rather than broad
"supports expressions" flags. `Program::validate_for` rejects unsupported
features with a typed missing-capability set, and retains the existing rejection
of negation/aggregation under equality rewriting.

Non-atomic heads need `ConjunctiveHeads`, `ExistentialHeads`,
`DisjunctiveHeads` or `InconsistencyConstraints`. `Program::validate_for`
checks head forms first and refuses the first rule whose form is not declared
with `ProfileCheckError::UnsupportedHeadForm { rule, form }` (code
`unsupported-head-form`), never folded into the generic missing-capability
error.

A capability declaration describes a contract, not proof of engine support.
`DatalogCapabilities::all_model_features()` lists what the IR can represent;
an engine must independently declare and test what it implements. Forward and
backward execution remain separate from the language profile.

RDFS, OWL 2 RL/RDF, Horst and vendor-compatible entailment presets belong in
RDF reasoning rule packages. They can consume this model without adding OWL or
backend dependencies to the generic Datalog layer. This crate does not yet
provide those RDF rules or enable new inference modes in Python packages.

## Scope

This crate contains rule-program data structures and pure validation only. It
does not provide a parser or CST for a Datalog source language, and it does not
define an execution runtime. Those are separate layers so that parsers can
stream source tokens and evaluators can stream facts and results without
turning this IR crate into an in-memory data engine.

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or <https://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT]LICENSE-MIT or <https://opensource.org/licenses/MIT>)

at your option.