Expand description
§datalog-structural-model
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
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.
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)?;§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.
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.
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);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.
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
xnever collides with a constantx; - 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.
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());§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.
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());§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 or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option. Typed Datalog rule programs and stratification analysis.
Structs§
- Aggregate
Body - An aggregation sub-query inside a rule body.
- Argument
Position - One argument slot of one atom occurrence: a node of the position graph.
- Atom
- Datalog atom:
predicate(term_1, ..., term_n). - Atom
Slot - Position of a term in an atom, triple term, or Skolem argument list.
- Constant
Symbol - Constant symbol used in Datalog terms.
- Contract
Digest - Identity of a
crate::Programchecked under onecrate::ValidationContract: equality mode, limits and termination law. - Datalog
Capabilities - Language feature set. This describes a contract; it does not certify an engine.
- Datalog
Profile - Explicit language features, equality regime and structural limits selected for a program. This is neither an RDF entailment profile nor an execution strategy.
- Empty
Head Collection - A head collection was constructed without elements.
- Error
Code - Stable machine-readable identifier of an error variant.
- Existential
Variables - A non-empty set of existentially quantified head variables, kept in symbol order without duplicates so equal sets have one encoding.
- Expression
Term Index - Position of a top-level term inside a filter or BIND expression, in left-to-right source order.
- Ground
Atom - Ground form of an
Atom— the value form with no variables anywhere in the argument tree. Used insideGroundTerm::TripleTermso quoted-triple facts can be stored alongside flat facts in a fact set (TT1). - Ground
Term Digest - Canonical content identity of an exact
crate::GroundTerm. - Head
Atom Index - Position of an atom inside one head disjunct (conjunction).
- Head
Atom Path - Path from a rule head to one atom: the disjunct, then the atom inside that disjunct’s conjunction. An atomic head is disjunct 0, atom 0.
- Head
Conjunction - A non-empty conjunction of head atoms, in authored order.
- Head
Disjunct Index - Position of a disjunct in a rule head. Every non-disjunctive head has exactly one disjunct, at position zero.
- Head
Disjunction - A non-empty disjunction of head conjunctions, in authored order.
- LawVersion
- Version of the evidence law a
TerminationCriterionproves. A change to what a criterion accepts or how it reports bumps the version. - Literal
Index - Position of a literal in a rule body or an aggregate’s inner body.
- Literal
Path - Path from a rule body to one literal: the outer body position, then one inner-body position per enclosing aggregate.
- Predicate
Symbol - Predicate symbol in a Datalog atom.
- Program
- Datalog program as an ordered set of rules.
- Program
Digest - Canonical content identity of an authored
crate::Program. - Rule
- Datalog rule:
head :- body_1, ..., body_n. - Rule
Index - Position of a rule in
Program::rules. - Special
Edge - A special (value-inventing) edge of the position graph: a value bound at
body position
fromfeeds a value invented at head positiontoof the same rule. - Stratification
- Rule-level stratification of a finite Datalog program.
- Stratum
- A set of rules evaluated together to a fixed point.
- Strict
Dependency - A producer-to-consumer dependency that requires a strictly earlier producer stratum.
- Term
Path - Path to a term: its root, then one argument slot per nested triple term or Skolem call descended into.
- Termination
Violation - A value-inventing edge whose endpoints share a strongly connected component of the position graph, so a recursive program can keep inventing values. This defeats the criterion; it does not prove that every evaluation diverges.
- Unstratifiable
Cycle - A strongly connected rule component containing a strict dependency.
- Unsupported
Capabilities - Features required by the program and absent from the selected profile.
- Validation
Contract - The parameters a program is checked under, separate from the program.
- Validation
Limits - Structural ceilings checked during validation. Every ceiling is inclusive: a value equal to its limit is accepted.
- Variable
Symbol - Variable symbol used in Datalog terms.
- Weak
Acyclicity - Evidence that a program satisfies
TerminationCriterion::WeaklyAcyclic.
Enums§
- Aggregator
- SQL/SPARQL aggregator vocabulary supported in rule bodies.
- Bind
Expr - Expression carried by a
Literal::Bindbody literal. - Binding
Kind - An operation represented by
BindExpr, independent of evaluator support. - Builtin
Filter - Built-in filter expression.
- Datalog
Feature - A language feature required by a rule program. Positive flat atoms require no extension capabilities.
- Digest
Parse Error - Why a digest text could not be parsed.
- Equality
Mode - Equality-reasoning mode under which a Datalog program is validated.
- Filter
Kind - An operation represented by
BuiltinFilter, independent of evaluator support. - Ground
Term - Ground term — the value form of a
Termwith all variables substituted. Used as the cell type inside tuples so an evaluator can store both flat constant-only facts and quoted-triple facts (TT1). - Head
Collection Kind - Which head collection was given no elements.
- Head
Form - Which logical form a
RuleHeadhas. - Invention
Kind - How a rule head builds a value that need not occur in its body.
- Literal
- Datalog body literal — a positive or negated atom, a built-in
filter expression, or a built-in
BIND(expr AS ?var)form. - Profile
Check Error - An invalid program or an explicitly unsupported language feature.
- Program
Validation Error - Program validation failures. Every failure tied to a location names the rule and, where narrower, the literal and term inside it.
- Rule
Head - The head of a
Rule. - Rule
Site - The part of a rule a location falls in.
- Stratification
Error - Stratification failure.
- Strict
Dependency Kind - Why a dependency must cross strata.
- Term
- Datalog term (
variable,constant,quoted-triple term, orSKOLEM(name, args...)function call). - Term
Root - Where the outermost term of a
TermPathsits. - Term
Shape Error - Invalid term structure, independent of variable binding or rule position.
- Termination
Criterion - A sufficient criterion for the termination of bottom-up evaluation.