{ "cells": [ { "cell_type": "markdown", "id": "55771aba", "metadata": {}, "source": [ "# Demo: Inferring Contradictions\n", "\n", "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.\n", "\n", "---\n", "\n", "- _What this adds relative to [demo-rdfs-inference.ipynb](demo-rdfs-inference.ipynb) and [demo-owl2-rl-inference.ipynb](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_RULES` so the reasoner can surface logical tensions explicitly.\n", "- _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 `ContradictionConsequent` fires.\n", "\n", "Implementation patterns for contradiction rules live in [`owl2_rl_contradictions.py`](https://github.com/kvjrhall/rdflib-reasoning/blob/main/rdflib-reasoning-engine/src/rdflib_reasoning/engine/rulesets/owl2_rl_contradictions.py).\n", "\n", "## Where does this notebook fit?\n", "\n", "| Topic | Notebook |\n", "|-------|----------|\n", "| RDFS inference + derivation inspection | [demo-rdfs-inference.ipynb](demo-rdfs-inference.ipynb) |\n", "| OWL 2 RL inference + derivation inspection | [demo-owl2-rl-inference.ipynb](demo-owl2-rl-inference.ipynb) |\n", "| RDFS inference retraction after graph updates | [demo-rdfs-retraction.ipynb](demo-rdfs-retraction.ipynb) |\n", "| Contradiction diagnostics + explanation | **this notebook** |\n", "\n", "## 1. Policy configuration\n", "\n", "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.\n", "\n", "_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).\n", "\n", "Implementations:\n", "\n", "- `RaiseOnContradictionRecorder` — unbounded retention; `ContradictionDetectedError` after append (exception exposes `record`).\n", "- `InMemoryContradictionRecorder(warn=True)` — unbounded retention; optional `ContradictionWarning` per contradiction (`warn=False` for accumulation-only miners).\n", "- `DropContradictionRecorder(warn=True)` — zero retention (`contradiction_records()` empty); same warning knob as `InMemory`.\n", "\n", "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.\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "2f71844c", "metadata": { "execution": { "iopub.execute_input": "2026-04-29T14:26:23.772861Z", "iopub.status.busy": "2026-04-29T14:26:23.772598Z", "iopub.status.idle": "2026-04-29T14:26:23.970871Z", "shell.execute_reply": "2026-04-29T14:26:23.970420Z" } }, "outputs": [], "source": [ "from rdflib_reasoning.engine import (\n", " # DropContradictionRecorder,\n", " # InMemoryContradictionRecorder,\n", " RaiseOnContradictionRecorder,\n", ")\n", "\n", "# Engine default matches RaiseOnContradictionRecorder(); pass explicitly here for clarity:\n", "contradiction_recorder = RaiseOnContradictionRecorder()\n", "# contradiction_recorder = InMemoryContradictionRecorder() # warn=True default\n", "# contradiction_recorder = InMemoryContradictionRecorder(warn=False)\n", "# contradiction_recorder = DropContradictionRecorder(warn=False) # zero retention, contradiction mining" ] }, { "cell_type": "markdown", "id": "72dee033", "metadata": {}, "source": [ "## 2. Reasoner setup\n", "\n", "We mirror the stack from [demo-rdfs-inference.ipynb](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.\n", "These are all configured by way of a reasoner specification that we customize for our use case.\n", "\n", "Differences for this demo:\n", "\n", "- _Rules:_ `PRODUCTION_RDFS_RULES` plus `OWL2_RL_CONTRADICTION_RULES` so contradiction consequents are compiled alongside ordinary RDFS materialization.\n", "- _Hooks:_ an `InMemoryDerivationLogger` (optional but familiar from the RDFS demo) plus the `contradiction_recorder` from §1.\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 2, "id": "a347b4c5", "metadata": { "execution": { "iopub.execute_input": "2026-04-29T14:26:23.972559Z", "iopub.status.busy": "2026-04-29T14:26:23.972449Z", "iopub.status.idle": "2026-04-29T14:26:23.975502Z", "shell.execute_reply": "2026-04-29T14:26:23.975168Z" } }, "outputs": [], "source": [ "from dataclasses import replace\n", "from typing import cast\n", "\n", "from rdflib import Dataset, Graph, URIRef\n", "from rdflib.namespace import OWL, RDF\n", "from rdflib_reasoning.engine import (\n", " OWL2_RL_CONTRADICTION_RULES,\n", " RDFS_RETE_MATERIALIZED,\n", " ContradictionClaim,\n", " DerivationProofReconstructor,\n", " InMemoryDerivationLogger,\n", " TripleFact,\n", ")\n", "from rdflib_reasoning.engine.rete_store import RETEStore\n", "\n", "derivation_logger = InMemoryDerivationLogger()\n", "\n", "reasoner_spec = replace(\n", " RDFS_RETE_MATERIALIZED,\n", " derivation_logger_factory=lambda _context: derivation_logger,\n", " contradiction_recorder_factory=lambda _context: contradiction_recorder,\n", ").extend(more_rules=OWL2_RL_CONTRADICTION_RULES)\n", "\n", "dataset: Dataset = reasoner_spec.dataset()\n", "graph: Graph = dataset.default_graph\n", "store = cast(RETEStore, dataset.store)" ] }, { "cell_type": "markdown", "id": "ac7d2617", "metadata": {}, "source": [ "## 3. Asserting a contradictory pattern\n", "\n", "We now add triples that are individually plausible but jointly inconsistent under the OWL 2 RL contradiction rule `prp-irp`.\n", "\n", "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`. \n", "\n", "With `InMemoryContradictionRecorder` (warnings on by default) or `DropContradictionRecorder`, `prp-irp` does not raise. Execution continues.\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 3, "id": "0816342c", "metadata": { "execution": { "iopub.execute_input": "2026-04-29T14:26:23.976673Z", "iopub.status.busy": "2026-04-29T14:26:23.976609Z", "iopub.status.idle": "2026-04-29T14:26:23.998808Z", "shell.execute_reply": "2026-04-29T14:26:23.998438Z" } }, "outputs": [], "source": [ "from rdflib_reasoning.engine.derivation import ContradictionDetectedError\n", "\n", "raised_error: ContradictionDetectedError | None = None\n", "\n", "p = URIRef(\"urn:demo:parentOf\")\n", "x = URIRef(\"urn:demo:alice\")\n", "\n", "_ = graph.add((p, RDF.type, OWL.IrreflexiveProperty))\n", "try:\n", " _ = graph.add((x, p, x))\n", "except ContradictionDetectedError as e:\n", " # NOTE: Both the raised error and the recorder contain the contradiction record.\n", " raised_error = e" ] }, { "cell_type": "markdown", "id": "9c28634c", "metadata": {}, "source": [ "## 4. Inspecting contradiction records\n", "\n", "`RETEStore` lazily creates one `RETEEngine` per named graph; we resolve the engine for this graph via `store.engines[graph.identifier]`.\n", "\n", "Even when `RaiseOnContradictionRecorder` raised `ContradictionDetectedError`, the recorder had already stored the row—you should see the same contradiction as `raised_error.record` below.\n", "\n", "Contradiction records carry:\n", "\n", "- `premises`: grounded triple facts that matched the rule body (here: `p` typed as irreflexive, and the reflexive edge `(alice parentOf alice)`).\n", "- `witness`: the focal triple the rule treats as exhibiting the clash (often the offending edge; aligned with `prp-irp` messaging).\n", "\n", "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.\n", "\n", "The formatted dump below is suitable for logs or UI; it is not a full proof tree until §5." ] }, { "cell_type": "code", "execution_count": 4, "id": "a3bca1b8", "metadata": { "execution": { "iopub.execute_input": "2026-04-29T14:26:24.000018Z", "iopub.status.busy": "2026-04-29T14:26:23.999946Z", "iopub.status.idle": "2026-04-29T14:26:24.002145Z", "shell.execute_reply": "2026-04-29T14:26:24.001809Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Contradiction records: 1\n", "[prp-irp] Irreflexive property used reflexively. (rule=owl2-rl-contradiction:prp-irp, seq=1)\n", " premises:\n", " ('', '', '')\n", " ('', '', '')\n", " witness: ('', '', '')\n", "\n" ] } ], "source": [ "from rdflib_reasoning.engine.derivation import format_contradiction_record\n", "\n", "engine = store.engines[graph.identifier]\n", "records = engine.contradiction_records(context=graph.identifier)\n", "\n", "print(f\"Contradiction records: {len(records)}\")\n", "for record in records:\n", " print(format_contradiction_record(record))" ] }, { "cell_type": "code", "execution_count": 5, "id": "19642ed2", "metadata": { "execution": { "iopub.execute_input": "2026-04-29T14:26:24.003316Z", "iopub.status.busy": "2026-04-29T14:26:24.003246Z", "iopub.status.idle": "2026-04-29T14:26:24.005018Z", "shell.execute_reply": "2026-04-29T14:26:24.004709Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ContradictionDetectedError was raised\n", "[prp-irp] Irreflexive property used reflexively. (rule=owl2-rl-contradiction:prp-irp, seq=1)\n", " premises:\n", " ('', '', '')\n", " ('', '', '')\n", " witness: ('', '', '')\n", "\n" ] } ], "source": [ "if raised_error:\n", " print(\"ContradictionDetectedError was raised\")\n", " print(raised_error)\n", "else:\n", " print(\"No ContradictionDetectedError was raised\")" ] }, { "cell_type": "markdown", "id": "f841172b", "metadata": {}, "source": [ "## 5. Explaining contradiction records\n", "\n", "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`.\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 6, "id": "9a6f2e68", "metadata": { "execution": { "iopub.execute_input": "2026-04-29T14:26:24.006053Z", "iopub.status.busy": "2026-04-29T14:26:24.005993Z", "iopub.status.idle": "2026-04-29T14:26:24.008602Z", "shell.execute_reply": "2026-04-29T14:26:24.008253Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Verdict: contradiction\n", "Goal witness: (rdflib.term.URIRef('urn:demo:alice'), rdflib.term.URIRef('urn:demo:parentOf'), rdflib.term.URIRef('urn:demo:alice'))\n", "Explanation node kind: rule_application\n", "Rule: ruleset='owl2-rl-contradiction' rule_id='prp-irp'\n", "Premise count: 2\n" ] } ], "source": [ "record = raised_error.record if raised_error is not None else records[0]\n", "\n", "goal = ContradictionClaim(\n", " context=record.context,\n", " witness=record.witness\n", " if record.witness is not None\n", " else TripleFact(context=record.context, triple=record.premises[0].triple),\n", ")\n", "\n", "proof = DerivationProofReconstructor().reconstruct(goal, records)\n", "print(\"Verdict:\", proof.verdict)\n", "print(\"Goal witness:\", goal.witness.triple)\n", "print(\"Explanation node kind:\", proof.proof.node_kind)\n", "if proof.proof.node_kind == \"rule_application\":\n", " print(\"Rule:\", proof.proof.rule_id)\n", " print(\"Premise count:\", len(proof.proof.premises))" ] }, { "cell_type": "code", "execution_count": 7, "id": "2e58d0f0", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "## Direct Proof\n", "\n", "- Context: ``\n", "- Goal: `contradiction witness (, , )`\n", "- Verdict: `contradiction`\n", "\n", "### Steps\n", "\n", "- Rule Application: `owl2-rl-contradiction:prp-irp`\n", " - Conclusions:\n", " - `contradiction witness (, , )`\n", " - Premises:\n", " - Leaf: `(, rdf:type, owl:IrreflexiveProperty)`\n", " - Leaf: `(, , )`" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from rdflib_reasoning.engine.proof_notebook import display_proof_markdown\n", "\n", "display_proof_markdown(proof, namespace_manager=graph.namespace_manager)" ] }, { "cell_type": "code", "execution_count": 8, "id": "cea81448", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "```mermaid\n", "flowchart TD\n", "n2[[\"owl2-rl-contradiction:prp-irp\"]]\n", "n3(\"contradiction witness (<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)\")\n", "n3 -->|entailed_by| n2\n", "n4[\"(<urn:demo:parentOf>, rdf:type, owl:IrreflexiveProperty)\"]\n", "n2 -->|had_premise| n4\n", "n5[\"(<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)\"]\n", "n2 -->|had_premise| n5\n", "n1>\"contradiction witness (<urn:demo:alice>, <urn:demo:parentOf>, <urn:demo:alice>)\"]\n", "n1 -->|justified_by| n3\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from rdflib_reasoning.engine.proof_notebook import display_proof_mermaid\n", "\n", "display_proof_mermaid(proof, namespace_manager=graph.namespace_manager)" ] }, { "cell_type": "markdown", "id": "65241369", "metadata": {}, "source": [ "## Notes\n", "\n", "- Contradiction records are diagnostics, not ordinary entailed triples.\n", "- Recorder policy is explicit and configurable: raise, retain with warnings, or drop retained records while still warning.\n", "- The explanation path mirrors the positive inference notebook by turning a recorded event into a proof-shaped object.\n", "- Portfolio tie-in: hybrid symbolic-agent workflows (see the [portfolio project plan](https://github.com/kvjrhall/rdflib-reasoning/blob/main/docs/portfolio/portfolio-project-plan.md)) need structured inconsistency signals that agents can branch on, repair, retract, or escalate instead of burying in unconstrained text." ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.3" } }, "nbformat": 4, "nbformat_minor": 5 }