Skip to content
propstorePublic

About

Defeasible Datalog Python implementation

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

Gunray

(named for Donald Nute, by way of Nute Gunray)

A pure-Python engine for defeasible reasoning, stratified Datalog, and propositional default closure. Give it rules that conflict and it works out which conclusions survive — then lets you inspect the argument-and-defeater chain behind the result. MIT licensed; Python 3.11+.

Use Gunray when a plain true/false result is not enough: policy exceptions, conflicting evidence, defaults with explicit overrides, or Datalog rules that need a traceable result. It keeps unresolved conflicts visible rather than silently choosing a winner.

from gunray import DefeasibleTheory, GunrayEvaluator, MarkingPolicy, Rule

theory = DefeasibleTheory(
    facts={"bird": {("tweety",), ("opus",)}, "penguin": {("opus",)}},
    strict_rules=[Rule(id="s1", head="bird(X)", body=["penguin(X)"])],
    defeasible_rules=[
        Rule(id="r1", head="flies(X)",  body=["bird(X)"]),
        Rule(id="r2", head="~flies(X)", body=["penguin(X)"]),
    ],
)

model = GunrayEvaluator().evaluate(theory, marking_policy=MarkingPolicy.BLOCKING)
# `model.sections` records the four-valued result for each ground literal.

~flies(X) :- penguin(X) is a defeasible rule, not a strict one. It is strong enough to defeat flies(X) :- bird(X) for the penguin case without changing the strict conclusion that penguins are birds.

UNDECIDED is a first-class answer

Sometimes the evidence genuinely does not resolve. Nixon was a Quaker and a Republican; one defeasible rule says Quakers are pacifists, another says Republicans aren't. Neither argument out-specifies the other — so Gunray returns Answer.UNDECIDED rather than inventing a winner.

from gunray import (
    Answer, DefeasibleTheory, GeneralizedSpecificity, Rule, answer,
)
from gunray.types import GroundAtom

theory = DefeasibleTheory(
    facts={"republican": {("nixon",)}, "quaker": {("nixon",)}},
    defeasible_rules=[
        Rule(id="r1", head="~pacifist(X)", body=["republican(X)"]),
        Rule(id="r2", head="pacifist(X)",  body=["quaker(X)"]),
    ],
)

pacifist_nixon = GroundAtom(predicate="pacifist", arguments=("nixon",))
criterion      = GeneralizedSpecificity(theory)

assert answer(theory, pacifist_nixon, criterion) is Answer.UNDECIDED

Answer has four values: YES (the literal is warranted), NO (its complement is warranted), UNDECIDED (arguments exist on both sides and neither wins), UNKNOWN (the predicate is not in the language of the theory). This is García & Simari 2004 Def 5.3.

Install

Add it to an existing uv project:

uv add git+https://github.com/ctoth/gunray.git

For development:

git clone https://github.com/ctoth/gunray.git
cd gunray
uv sync --extra dev

CLI and REPL

gunray run evaluates a plain Datalog program written in YAML or JSON. Save this program as ancestry.gnr:

facts:
  parent: [[leaf, branch], [branch, root]]
rules:
  - 'above(X,Y) :- parent(X,Y).'
  - 'above(X,Z) :- parent(X,Y), above(Y,Z).'
  - 'answer(X) :- above("leaf",X).'

gunray run ancestry.gnr --query answer prints {"answer":[["branch"],["root"]]}. Omit --query to return the model. To add facts for a particular run, pass --facts more.yaml with a mapping such as parent: [[root, sky]]. From Python, evaluate_program_file("ancestry.gnr", facts={"parent": [("root", "sky")]}, query="answer").facts returns the relation as a set of tuples. Import the function from gunray. Additional rows apply only to that evaluation.

In YAML fact rows, leaf is a string. In rule terms, leaf and X are both variables. Write "leaf" for the literal string. Rule parsing and safety errors identify the file and the starting line of the rule.

To inspect how a Datalog result was derived, capture derivations explicitly:

from gunray import GroundAtom, TraceConfig, evaluate_program_file_with_trace

_, trace = evaluate_program_file_with_trace(
    "ancestry.gnr", query="answer", trace_config=TraceConfig(capture_derivations=True)
)
step = trace.derivation_for(GroundAtom("answer", ("root",)))
assert step is not None
print(step.rule_text)  # answer(X) :- above("leaf",X).
print(step.premises)   # (GroundAtom(predicate='above', arguments=('leaf', 'root')),)

Call derivation_for on any premise to follow the derivation back to supplied facts. Each step records one successful rule application, with the matched premises in rule order and the instantiated comparisons and negated patterns that held. For a supplied fact, the step's rule_text is None. An absent tuple returns None; asking a trace that has no derivations raises ValueError. The same trace option works with GunrayEvaluator.evaluate_with_trace. It records the first successful application, which can depend on evaluation order.

See Zhao, Subotić, and Scholz, Debugging Large-scale Datalog, Def. 2.1 and §3.3, pp. 7:7 and 7:16–17.

The answer, model, explain and tree commands accept the existing DefeasibleTheory schema in YAML or JSON.

For example, save this as theory.yaml:

facts:
  bird:
    - [tweety]
  penguin:
    - [opus]
defeasible_rules:
  - id: r1
    head: flies(X)
    body: [bird(X)]
  - id: r2
    head: ~flies(X)
    body: [penguin(X)]
uv run gunray answer theory.yaml 'flies("tweety")'
uv run gunray explain theory.yaml 'flies("tweety")'
uv run gunray tree theory.yaml 'flies("tweety")' --format text
uv run gunray model theory.yaml --format json

String constants in CLI queries must be quoted; flies(opus) is rejected, while flies("opus") is valid. Pass --input-format json when a JSON input does not use a .json filename.

The default tree format is indented text. Use --format unicode for the box-drawing renderer, --format mermaid for a flowchart, or --format json for structured output. Pass - instead of a file path to read a theory from standard input.

Start the interactive shell with uv run python -m gunray. It can load and save YAML/JSON theories, inspect schema sections, answer queries, render explanations and trees, and incrementally add or remove schema-backed rules.

Four evaluators, one dispatcher

GunrayEvaluator.evaluate dispatches on the input type.

  • DefeasibleTheory → the DeLP pipeline: arguments, dialectical trees, Procedure 5.1 marking, four-valued answers. The main event.
  • Program → stratified Datalog with Apt-Blair-Walker safety and a choice of negation semantics (see below).
  • Propositional defaults → KLM rational / lexicographic / relevant closure via gunray.closure.ClosureEvaluator.
  • AnnotatedProgram with semiring=... → positive Datalog over semiring-annotated facts (see the next section).
from gunray import GunrayEvaluator, Program

model = GunrayEvaluator().evaluate(Program(
    facts={"edge": {("a", "b"), ("b", "c")}},
    rules=[
        "path(X, Y) :- edge(X, Y).",
        "path(X, Z) :- edge(X, Y), path(Y, Z).",
    ],
))
# model.facts["path"] == {("a", "b"), ("b", "c"), ("a", "c")}

DefeasibleEvaluator, SemiNaiveEvaluator, ClosureEvaluator, and AnnotatedEvaluator are exported directly if you'd rather skip the dispatcher.

Annotated Datalog: stakes, counts, provenance

AnnotatedEvaluator reads the same rule text over facts that carry a value from a commutative semiring. A rule body multiplies the values of the facts it joins, and every derivation of a tuple adds its product to that tuple's value (Green, Karvounarakis, Tannen 2007, Definition 3.2, p. 2). Five semirings ship: BOOLEAN (ordinary sets), NATURAL (number of derivations), RATIONAL (exact non-negative Fractions), PROVENANCE (provenance polynomials) and WHY (minimal witness sets), the last two from provenance-semiring.

Indirect stakes along a chain of holdings, exactly:

from fractions import Fraction

from gunray import RATIONAL, AnnotatedEvaluator, AnnotatedProgram

ownership = [
    "own(X, Y) :- stake(X, Y).",
    "own(X, Y) :- stake(X, Z), own(Z, Y).",
]
stakes = {
    ("a", "b"): Fraction(1, 2),
    ("b", "c"): Fraction(2, 5),
    ("a", "c"): Fraction(1, 10),
}
model = AnnotatedEvaluator().evaluate(
    AnnotatedProgram(facts={"stake": stakes}, rules=ownership),
    semiring=RATIONAL,
)
# model.facts["own"][("a", "c")] == Fraction(3, 10)   # 1/10 + 1/2 * 2/5

Which facts each answer rests on, and in how many ways: give every input fact its own source variable and evaluate in PROVENANCE.

from provenance_semiring import ProvenancePolynomial, derive_source_variable_id

from gunray import PROVENANCE

x = {
    row: ProvenancePolynomial.variable(derive_source_variable_id("stake", repr(row), "filing"))
    for row in stakes
}
model = AnnotatedEvaluator().evaluate(
    AnnotatedProgram(facts={"stake": x}, rules=ownership),
    semiring=PROVENANCE,
)
# model.facts["own"][("a", "c")] == x[("a", "c")] + x[("a", "b")] * x[("b", "c")]

Mapping that polynomial through any semiring homomorphism (provenance_semiring.evaluate) gives the same answer as evaluating in the target semiring directly (Green et al. 2007, Proposition 3.5, p. 3).

Which sets of input facts suffice, on any data, cycles included: annotate each fact with its own source variable as a MinimalWitnessBasis and evaluate in WHY. Each derived tuple gets the minimal sets of input facts from which it is derived; counts and repeated use are dropped.

from provenance_semiring import MinimalWitnessBasis, derive_source_variable_id

from gunray import WHY

w = {
    row: MinimalWitnessBasis.variable(derive_source_variable_id("stake", repr(row), "filing"))
    for row in [("a", "b"), ("b", "a")]  # a holds a stake in b, and b in a
}
model = AnnotatedEvaluator().evaluate(
    AnnotatedProgram(facts={"stake": w}, rules=ownership),
    semiring=WHY,
)
# model.facts["own"][("a", "a")] == w[("a", "b")] * w[("b", "a")]
# model.facts["own"][("a", "b")] == w[("a", "b")]

When ground tuples depend on each other in a loop, as in two companies holding stakes in each other, naive evaluation over NATURAL, RATIONAL or PROVENANCE never reaches a fixpoint (Abo Khamis et al. 2021, Theorem 1.2, p. 5; Example 4.2, p. 22). What happens then depends on the semiring:

  • BOOLEAN and WHY are absorptive (1 + a = 1, p. 25) and iterate to their fixpoint, within as many rounds as the loop has tuples (Theorem 1.2, p. 5).

  • RATIONAL solves the loop exactly when every rule instance has at most one body tuple inside it. The loop's equations are then x = A x + b, and the answer is (I - A)^-1 b, computed in exact Fractions:

    stakes = {("a", "b"): Fraction(3, 5), ("b", "a"): Fraction(3, 10)}
    model = AnnotatedEvaluator().evaluate(
        AnnotatedProgram(facts={"stake": stakes}, rules=ownership),
        semiring=RATIONAL,
    )
    # own(a, b) == 30/41, own(a, a) == 9/41, own(b, a) == 15/41, own(b, b) == 9/41

    The solve checks, before answering, that every coefficient is non-negative and that elimination of I - A without row exchanges meets only positive pivots. For I minus a non-negative matrix that is necessary and sufficient for (I - A)^-1 to be non-negative (Fujimoto and Ranade 2004, Corollary 3.2, p. 62), and by the Hawkins-Simon theorem as Caravelli 2025 states it (pp. 141-142) the series then converges to that inverse; Caravelli gives the step from a failed pivot to a divergent series only as a proof sketch (p. 142). A zero or negative pivot raises NonConvergentAnnotationError saying the sum does not converge. A loop with two body tuples inside it in one rule instance (path(X, Y) :- path(X, Z), path(Z, Y). on cyclic data) is not linear and is refused. A loop of more than max_solve_size ground tuples (default 100; the cost grows faster than the cube of the size) raises AnnotationSolveLimitError; pass a larger max_solve_size to AnnotatedEvaluator.evaluate to allow it.

  • NATURAL and PROVENANCE raise NonConvergentAnnotationError naming the tuples of the loop.

What the RATIONAL answer on a loop is: the sum over all derivation paths. In ownership terms that is what Vitali, Glattfelder and Battiston 2011 call integrated ownership (SI p. 17), and they say it overestimates control when there are cycles (p. 18): own(a, a) = 9/41 above is a's stake in itself through the loop. They give a corrected figure that removes those self-loops (Eq. 12-15, p. 21); Gunray does not compute it. The values are not claimed to sum to any total.

A semiring opts in to the exact solve by implementing OrderedFieldSemiring, which adds the field's sub, div and positive to the Semiring protocol.

Negated atoms must name a lower stratum and only filter matches. Comparisons read key columns only, since a value is not a column.

Compare marking policies

Use GunrayEvaluator.compare_marking_policies to see how the answer to a ground query changes across selected marking policies on the same theory.

from gunray import GroundAtom, GunrayEvaluator, MarkingPolicy

support = GunrayEvaluator().compare_marking_policies(
    theory,
    GroundAtom("q", ()),
    policies=(MarkingPolicy.ANTONIOU_BLOCKING, MarkingPolicy.ANTONIOU_PROPAGATING),
)

Each key is an observed Answer. Its value is the set of selected policies that returned it. One key means the selected policies agree. As with the CLI, a literal omitted from a policy's model counts as Answer.UNKNOWN. The selection must contain at least one policy. Each distinct policy runs once, and evaluation errors propagate to the caller.

In the Antoniou example, q has support for YES under ambiguity blocking and for UNDECIDED under ambiguity propagation. Support here follows Hellerstein 2026, Definition 3.2, p. 6.

Explanations — why did the engine decide that?

What was concluded is usually less interesting than why. For any conclusion, Gunray gives you the dialectical tree, a marking, and a prose transcript of the argument-and-defeater chain. Using the Tweety theory from the opening example:

from gunray import (
    GeneralizedSpecificity, build_arguments, build_tree,
    explain, mark, render_tree,
)
from gunray.types import GroundAtom

flies_opus = GroundAtom(predicate="flies", arguments=("opus",))
criterion  = GeneralizedSpecificity(theory)

for arg in build_arguments(theory):
    if arg.conclusion == flies_opus and arg.rules:
        tree = build_tree(arg, criterion, theory)
        print(render_tree(tree))          # Unicode tree diagram
        print(mark(tree))                 # "U" (warranted) or "D" (defeated)
        print(explain(tree, criterion))   # prose transcript
        break
flies(opus)  [r1]  (D)
└─ ~flies(opus)  [r2]  (U)
D
flies(opus) is NO.
An argument supports flies(opus) from {bird(opus)} via r1.
It is defeated by an argument for ~flies(opus) from {penguin(opus)} via r2, which is strictly more specific.

Trees also render to Mermaid via render_tree_mermaid. Here is the peer-review conflict-of-interest case from examples/reviewer_assignment.py — a disqualification waiver (df1) is specific enough to lift institutional COI (d3), but an explicit superiority pair keeps advisor COI (d4) above the waiver:

flowchart TD
    n0["eligible(dave, author_d) [d1] D"]
    n1["~eligible(dave, author_d) [d3] U"]
    n2["eligible(dave, author_d) [df1] D"]
    n3["~eligible(dave, author_d) [d4] U"]
    n4["~eligible(dave, author_d) [d4] U"]
    n2 --> n3
    n1 --> n2
    n0 --> n1
    n0 --> n4
Loading

The [d1] D / [d3] U markings are the Procedure 5.1 verdicts at each node. The tree is how a contested conclusion becomes legible when the answer disagrees with your intuition.

For the full evaluate_with_trace API — stratum-by-stratum rule-fire logs for Datalog, tree_for / marking_for / arguments_for_conclusion lookups for defeasible theories — see ARCHITECTURE.md.

SAFE vs NEMO — negation semantics

Rules with variables in negated body literals have two competing readings in the literature. Gunray ships both.

  • NegationSemantics.SAFE (default) — Apt, Blair & Walker 1988 stratified-Datalog safety. Every variable in a negated body literal must be bound by a positive body literal. Unsafe programs raise SafetyViolationError.
  • NegationSemantics.NEMO — Ivliev et al. 2024 (KR 2024, doi:10.24963/kr.2024/70): variables in negated literals are interpreted existentially over the active Herbrand universe. Used by the conformance suite's Nemo fixtures.

Same theory, different answers. See examples/safe_vs_nemo.py.

Tests

uv run pytest tests -q
uv run pytest tests/test_conformance.py \
  --datalog-evaluator=gunray.conformance_adapter.GunrayConformanceEvaluator -q
uv run pyright
uv run ruff check
uv run ruff format --check

The conformance suite is ctoth/datalog-conformance-suite. A handful of fixtures are explicitly out-of-contract and marked skip — see ARCHITECTURE.md for the list and the reasons.

More

  • examples/ — the full catalogue. Showcase cases, domain depth (clinical, GDPR, data fusion, access control), engine breadth (Datalog, KLM closure, SAFE vs NEMO), and Mermaid visuals.
  • ARCHITECTURE.md — module layout, DeLP pipeline internals, preference composition, strict-only fast path, pitfalls.
  • CITATIONS.md — the paper trail.

About

Defeasible Datalog Python implementation

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages