Demo: Inferring Contradictions¶
This notebook walks through the engine path when OWL 2 RL contradiction rules fire: we assert triples, forward chaining evaluates the bundled contradiction profile, and the active rule records a contradiction diagnostic (rather than silently treating the situation as ordinary entailment). We then inspect the structured record and reconstruct an explanation suitable for tooling or review.
What this adds relative to demo-rdfs-inference.ipynb and demo-owl2-rl-inference.ipynb? Those notebooks focus on positive entailments and derivation logs (RDFS and OWL 2 RL respectively). Here we keep production RDFS rules and add
OWL2_RL_CONTRADICTION_RULESso the reasoner can surface logical tensions explicitly.What stays subjective? Whether a recorded contradiction is “wrong” for your application depends on ruleset semantics, your ontology choices, and asserted data. The library does not resolve that interpretation; it exposes configurable handling when a
ContradictionConsequentfires.
Implementation patterns for contradiction rules live in owl2_rl_contradictions.py.
Where does this notebook fit?¶
Topic |
Notebook |
|---|---|
RDFS inference + derivation inspection |
|
OWL 2 RL inference + derivation inspection |
|
RDFS inference retraction after graph updates |
|
Contradiction diagnostics + explanation |
this notebook |
1. Policy configuration¶
Passing contradiction_recorder into RETEEngineFactory threads that object through context_template: every engine the RETEStore creates for a named graph receives the same recorder instance unless you use separate factories.
Default if you omit contradiction_recorder in RETEEngineFactory: each RETEEngine gets its own RaiseOnContradictionRecorder() — append one diagnostic row, then raise ContradictionDetectedError. Substitution is always via context_template (explicit opt-in).
Implementations:
RaiseOnContradictionRecorder— unbounded retention;ContradictionDetectedErrorafter append (exception exposesrecord).InMemoryContradictionRecorder(warn=True)— unbounded retention; optionalContradictionWarningper contradiction (warn=Falsefor accumulation-only miners).DropContradictionRecorder(warn=True)— zero retention (contradiction_records()empty); same warning knob asInMemory.
The next cell assigns RaiseOnContradictionRecorder() explicitly so the policy is visible; you could omit it on the factory and get the same default. Raising does not discard the appended row; §§4–5 use records and raised_error.record when an exception was caught.
from rdflib_reasoning.engine import (
# DropContradictionRecorder,
# InMemoryContradictionRecorder,
RaiseOnContradictionRecorder,
)
# Engine default matches RaiseOnContradictionRecorder(); pass explicitly here for clarity:
contradiction_recorder = RaiseOnContradictionRecorder()
# contradiction_recorder = InMemoryContradictionRecorder() # warn=True default
# contradiction_recorder = InMemoryContradictionRecorder(warn=False)
# contradiction_recorder = DropContradictionRecorder(warn=False) # zero retention, contradiction mining
2. Reasoner setup¶
We mirror the stack from demo-rdfs-inference.ipynb: an RDFLib Memory store wrapped by RETEStore, a RETEEngineFactory carrying the rule list, and a Dataset whose default graph we mutate.
These are all configured by way of a reasoner specification that we customize for our use case.
Differences for this demo:
Rules:
PRODUCTION_RDFS_RULESplusOWL2_RL_CONTRADICTION_RULESso contradiction consequents are compiled alongside ordinary RDFS materialization.Hooks: an
InMemoryDerivationLogger(optional but familiar from the RDFS demo) plus thecontradiction_recorderfrom §1.
You do not need middleware or LangChain to follow this notebook—only the engine package and RDFLib. If you later wire inference behind agent tools, the same factory arguments apply; see the demo-*-middleware*.ipynb series for dataset and vocabulary tooling on top of RDF state.
from dataclasses import replace
from typing import cast
from rdflib import Dataset, Graph, URIRef
from rdflib.namespace import OWL, RDF
from rdflib_reasoning.engine import (
OWL2_RL_CONTRADICTION_RULES,
RDFS_RETE_MATERIALIZED,
ContradictionClaim,
DerivationProofReconstructor,
InMemoryDerivationLogger,
TripleFact,
)
from rdflib_reasoning.engine.rete_store import RETEStore
derivation_logger = InMemoryDerivationLogger()
reasoner_spec = replace(
RDFS_RETE_MATERIALIZED,
derivation_logger_factory=lambda _context: derivation_logger,
contradiction_recorder_factory=lambda _context: contradiction_recorder,
).extend(more_rules=OWL2_RL_CONTRADICTION_RULES)
dataset: Dataset = reasoner_spec.dataset()
graph: Graph = dataset.default_graph
store = cast(RETEStore, dataset.store)
3. Asserting a contradictory pattern¶
We now add triples that are individually plausible but jointly inconsistent under the OWL 2 RL contradiction rule prp-irp.
Informally: we declare a binary relation parentOf, mark it irreflexive (nothing may relate to itself via that property—no self-loop), and then assert exactly such a self-loop for alice.
With InMemoryContradictionRecorder (warnings on by default) or DropContradictionRecorder, prp-irp does not raise. Execution continues.
With RaiseOnContradictionRecorder (factory default), the second assertion triggers inside graph.add; uncaught, execution stops there. We demonstrate catching and inspecting the exception, because understanding the contradiction is the first step in debugging.
from rdflib_reasoning.engine.derivation import ContradictionDetectedError
raised_error: ContradictionDetectedError | None = None
p = URIRef("urn:demo:parentOf")
x = URIRef("urn:demo:alice")
_ = graph.add((p, RDF.type, OWL.IrreflexiveProperty))
try:
_ = graph.add((x, p, x))
except ContradictionDetectedError as e:
# NOTE: Both the raised error and the recorder contain the contradiction record.
raised_error = e
4. Inspecting contradiction records¶
RETEStore lazily creates one RETEEngine per named graph; we resolve the engine for this graph via store.engines[graph.identifier].
Even when RaiseOnContradictionRecorder raised ContradictionDetectedError, the recorder had already stored the row—you should see the same contradiction as raised_error.record below.
Contradiction records carry:
premises: grounded triple facts that matched the rule body (here:ptyped as irreflexive, and the reflexive edge(alice parentOf alice)).witness: the focal triple the rule treats as exhibiting the clash (often the offending edge; aligned withprp-irpmessaging).
We pass context=graph.identifier again when listing records because contradiction_records reads from the recorder attached to this engine—and when that recorder is shared across contexts, filtering by context selects rows for this graph only. With a per-engine default recorder the filter is redundant but keeps the intent explicit and matches shared-recorder setups.
The formatted dump below is suitable for logs or UI; it is not a full proof tree until §5.
from rdflib_reasoning.engine.derivation import format_contradiction_record
engine = store.engines[graph.identifier]
records = engine.contradiction_records(context=graph.identifier)
print(f"Contradiction records: {len(records)}")
for record in records:
print(format_contradiction_record(record))
Contradiction records: 1
[prp-irp] Irreflexive property used reflexively. (rule=owl2-rl-contradiction:prp-irp, seq=1)
premises:
('<urn:demo:parentOf>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://www.w3.org/2002/07/owl#IrreflexiveProperty>')
('<urn:demo:alice>', '<urn:demo:parentOf>', '<urn:demo:alice>')
witness: ('<urn:demo:alice>', '<urn:demo:parentOf>', '<urn:demo:alice>')
if raised_error:
print("ContradictionDetectedError was raised")
print(raised_error)
else:
print("No ContradictionDetectedError was raised")
ContradictionDetectedError was raised
[prp-irp] Irreflexive property used reflexively. (rule=owl2-rl-contradiction:prp-irp, seq=1)
premises:
('<urn:demo:parentOf>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://www.w3.org/2002/07/owl#IrreflexiveProperty>')
('<urn:demo:alice>', '<urn:demo:parentOf>', '<urn:demo:alice>')
witness: ('<urn:demo:alice>', '<urn:demo:parentOf>', '<urn:demo:alice>')
5. Explaining contradiction records¶
Raw records are diagnostics. To connect them to the same derivation-style explanation machinery used elsewhere, we build a ContradictionClaim for the witness triple (fallback premise when no witness is stored) and call DerivationProofReconstructor.reconstruct.
The resulting DirectProof reports verdict="contradiction" and exposes a rule_application node naming prp-irp, with premise facts aligned to the record—useful when an agent or reviewer must justify “why this was flagged” without hand-writing the trace.
record = raised_error.record if raised_error is not None else records[0]
goal = ContradictionClaim(
context=record.context,
witness=record.witness
if record.witness is not None
else TripleFact(context=record.context, triple=record.premises[0].triple),
)
proof = DerivationProofReconstructor().reconstruct(goal, records)
print("Verdict:", proof.verdict)
print("Goal witness:", goal.witness.triple)
print("Explanation node kind:", proof.proof.node_kind)
if proof.proof.node_kind == "rule_application":
print("Rule:", proof.proof.rule_id)
print("Premise count:", len(proof.proof.premises))
Verdict: contradiction
Goal witness: (rdflib.term.URIRef('urn:demo:alice'), rdflib.term.URIRef('urn:demo:parentOf'), rdflib.term.URIRef('urn:demo:alice'))
Explanation node kind: rule_application
Rule: ruleset='owl2-rl-contradiction' rule_id='prp-irp'
Premise count: 2
from rdflib_reasoning.engine.proof_notebook import display_proof_markdown
display_proof_markdown(proof, namespace_manager=graph.namespace_manager)
Direct Proof
Context:
<urn:x-rdflib:default>Goal:
contradiction witness (<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)Verdict:
contradiction
Steps
Rule Application:
owl2-rl-contradiction:prp-irpConclusions:
contradiction witness (<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)
Premises:
Leaf:
(<urn:demo:parentOf>, rdf:type, owl:IrreflexiveProperty)Leaf:
(<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)
from rdflib_reasoning.engine.proof_notebook import display_proof_mermaid
display_proof_mermaid(proof, namespace_manager=graph.namespace_manager)
flowchart TD
n2[["owl2-rl-contradiction:prp-irp"]]
n3("contradiction witness (<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)")
n3 -->|entailed_by| n2
n4["(<urn:demo:parentOf>, rdf:type, owl:IrreflexiveProperty)"]
n2 -->|had_premise| n4
n5["(<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)"]
n2 -->|had_premise| n5
n1>"contradiction witness (<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)"]
n1 -->|justified_by| n3
Notes¶
Contradiction records are diagnostics, not ordinary entailed triples.
Recorder policy is explicit and configurable: raise, retain with warnings, or drop retained records while still warning.
The explanation path mirrors the positive inference notebook by turning a recorded event into a proof-shaped object.
Portfolio tie-in: hybrid symbolic-agent workflows (see the portfolio project plan) need structured inconsistency signals that agents can branch on, repair, retract, or escalate instead of burying in unconstrained text.