Build typed rules step by step

Start with Facts, Rules, and Explanations for facts, variables, rule bodies/heads and fixpoints. Use the typed API when a relation needs strict data values or more than two arguments. Every example here is independent and needs only the base install: no backend, serializer, solver or database source is involved.

Typed facts use predicate, argument-list order. Entity identifiers remain strings; literals carry an explicit kind. Arity is the number of arguments, not the number of facts. Keep a predicate’s arity consistent within a program. Generic names this general fact model, not a probabilistic or automatically optimized execution mode.

1. Bind data, then compare it

An atom binds Alice’s age to age. The comparison checks that already-bound literal; the rule derives a unary adult fact. It does not generate ages or coerce the entity string "30" into an integer.

Standalone example. Install with python -m pip install "gestaltdb".

 1from gestaltdb.reasoning import (
 2    Comparison, GenericEngine, GenericProgram, GenericRule, Literal,
 3    ReasoningLimits, TypedAtom, TypedFact, Variable,
 4)
 5
 6person, age = Variable("person"), Variable("age")
 7program = GenericProgram([GenericRule(
 8    "adult", [TypedAtom("age", [person, age])],
 9    [Comparison(">=", age, Literal("integer", 18))], TypedAtom("adult", [person]),
10)])
11facts = [TypedFact("age", ["alice", Literal("integer", 30)]),
12         TypedFact("age", ["bob", Literal("integer", 12)])]
13result = GenericEngine().evaluate(program, facts, limits=ReasoningLimits())
14assert TypedFact("adult", ["alice"]) in result
15assert TypedFact("adult", ["bob"]) not in result
16assert Literal("integer", 18) != Literal("text", "18")

Literal kinds are strict: Boolean True is not an integer literal and integer 18 is not float 18.0. Supported comparison operators require safely bound operands. Incomparable kinds filter a candidate out rather than inventing an ordering. See Typed Datalog: literals, filters, aggregates for null, NaN and lexical conversion details.

2. Let conclusions feed recursion

The direct rule copies each edge into reachability. The recursive rule extends known reachability by another edge. Shared variables force the middle endpoints to match. Set semantics stop repeated derivations from creating duplicate facts; the finite positive fixpoint includes a -> c even though that input edge is absent. This is logical reachability, not a shortest-path result or a physical edge.

Standalone example. Install with python -m pip install "gestaltdb".

 1from gestaltdb.reasoning import (
 2    GenericEngine, GenericProgram, GenericRule, ReasoningLimits,
 3    TypedAtom, TypedFact, Variable,
 4)
 5
 6x, y, z = Variable("x"), Variable("y"), Variable("z")
 7program = GenericProgram([
 8    GenericRule("direct", [TypedAtom("edge", [x, y])], [], TypedAtom("reach", [x, y])),
 9    GenericRule("extend", [TypedAtom("reach", [x, y]), TypedAtom("edge", [y, z])],
10                [], TypedAtom("reach", [x, z])),
11])
12result = GenericEngine().evaluate(
13    program, [TypedFact("edge", ["a", "b"]), TypedFact("edge", ["b", "c"])],
14    limits=ReasoningLimits(max_iterations=20, max_facts=100, max_candidate_rows=1000),
15)
16assert {fact for fact in result.facts if fact.predicate == "reach"} == {
17    TypedFact("reach", ["a", "b"]), TypedFact("reach", ["b", "c"]),
18    TypedFact("reach", ["a", "c"]),
19}

Iteration/fact/candidate limits fail closed; they are not wall-time or RSS caps. Head variables must be bound by positive body atoms, so rules cannot silently invent an unbounded population of new entities.

3. Declare absence and retain its witness

Declare banned complete for this evaluation’s selected inputs before testing its absence. Alice is eligible because she is a candidate and has no matching ban in that scope. Bob is blocked by a positive ban, not by a negative candidate claim. evaluate_stratified finishes dependencies before applying absence; undeclared negation or negative cycles reject explicitly.

Standalone example. Install with python -m pip install "gestaltdb".

 1from gestaltdb.reasoning import (
 2    GenericEngine, GenericProgram, GenericRule, ReasoningLimits,
 3    TypedAtom, TypedFact, Variable,
 4)
 5
 6person = Variable("person")
 7program = GenericProgram([GenericRule(
 8    "eligible", [TypedAtom("candidate", [person])], [], TypedAtom("eligible", [person]),
 9    negated=[TypedAtom("banned", [person])],
10)], closed=["banned"])
11facts = [TypedFact("candidate", ["alice"]), TypedFact("candidate", ["bob"]),
12         TypedFact("banned", ["bob"])]
13run = GenericEngine().evaluate_stratified(
14    program, facts, limits=ReasoningLimits(), collect_proofs=True,
15)
16conclusion = TypedFact("eligible", ["alice"])
17assert conclusion in run.result and TypedFact("eligible", ["bob"]) not in run.result
18explanation = run.proofs.explain(conclusion, max_nodes=10)
19assert not explanation.truncated
20witness = next(node for node in explanation.nodes if node.fact == conclusion)
21assert witness.absence[0].scope == ("banned",)
22assert run.proofs.is_current_for(program, facts)
23assert not run.proofs.is_current_for(program, [*facts, TypedFact("banned", ["alice"])])

A retained witness is tied to the program and input horizon. Reevaluate after facts or closed scopes change. Proof budgets can truncate retained evidence without truncating closure; inspect the trace/explanation flags. Successful absence proof records differ from collect_negation_trace why-not diagnostics, which record present blockers (Scoped closed-world negation). Neither authenticates arbitrary caller facts or proves the closed-world declaration justified.

4. Aggregate a completed group

An aggregate combines completed logical rows by grouping keys. Here it counts each team’s distinct member facts. The result is an integer literal, not an entity identifier. Duplicate copies of the same fact do not increase the count.

Standalone example. Install with python -m pip install "gestaltdb".

 1from gestaltdb.reasoning import (
 2    AggregateRule, Aggregation, GenericEngine, GenericProgram, Literal,
 3    ReasoningLimits, TypedAtom, TypedFact, Variable,
 4)
 5
 6team, person, count = Variable("team"), Variable("person"), Variable("count")
 7program = GenericProgram([], aggregates=[AggregateRule(
 8    "team-count", [TypedAtom("member", [team, person])], [team],
 9    [Aggregation("count", person, count)], TypedAtom("team_size", [team, count]),
10)])
11facts = [TypedFact("member", ["lab", "alice"]), TypedFact("member", ["lab", "bob"]),
12         TypedFact("member", ["lab", "alice"]), TypedFact("member", ["audit", "carol"])]
13result = GenericEngine().evaluate(program, facts, limits=ReasoningLimits(), collect_proofs=True)
14conclusion = TypedFact("team_size", ["lab", Literal("integer", 2)])
15assert conclusion in result
16assert TypedFact("team_size", ["audit", Literal("integer", 1)]) in result
17assert not result.proofs.explain(conclusion, max_nodes=10).truncated

Only the supported nonrecursive aggregation stratum is available: aggregate heads are sinks, aggregate bodies cannot read other aggregate heads, and head arguments must be group keys, constants or aggregate targets. Empty groups do not infer a zero-count fact. Numeric sum/min/max have strict kind/null rules; aggregation is not recursive arithmetic or an unrestricted SQL aggregate engine.

Continue beyond the first rules