Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(cli): dispatch reason run to real deductive and abductive reasoning APIs (#1632)

Sakshi Jain23c15bd0d5bc
diff --git a/semantica/cli.py b/semantica/cli.py
index af8c2f63..28d36e64 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -7,6 +7,7 @@ enabling users to interact with the framework via terminal commands.
import json
import os
+import re
import sys
import time
@@ -1238,6 +1239,120 @@ def _load_rule_definitions(path: str) -> List[str]:
if line.strip() and not line.lstrip().startswith("#")]
+def _load_premises(path: str) -> List[Any]:
+ """Load DeductiveReasoner ``Premise`` objects from a YAML file.
+
+ Mirrors _load_rule_definitions()'s format conventions: a YAML list of
+ plain statement strings, a list of ``{statement, confidence}`` mappings,
+ a top-level ``{"premises": [...]}`` mapping, or plain-text lines.
+
+ ``confidence`` is accepted and parsed onto the Premise (the dataclass
+ has the field, so a doc-shaped input shouldn't be rejected), but
+ DeductiveReasoner.apply_logic() never reads premise.confidence -- every
+ derived Conclusion's confidence comes from the firing rule's confidence
+ instead. Setting it currently has no effect on the result.
+ """
+ from .reasoning.deductive_reasoner import Premise
+ text = Path(path).read_text(encoding="utf-8")
+ try:
+ data = yaml.safe_load(text)
+ except yaml.YAMLError:
+ data = None
+ if isinstance(data, dict):
+ if "premises" not in data:
+ raise click.ClickException(
+ f"Premises file '{path}' is a YAML mapping but has no 'premises' key. "
+ "Expected either a YAML list or a mapping with a 'premises' list."
+ )
+ premises_value = data["premises"]
+ # A present-but-non-list value (e.g. "premises: null") must be a
+ # clear error, not silently fall through to reinterpreting the raw
+ # file text as one-statement-per-line plain text.
+ if not isinstance(premises_value, list):
+ raise click.ClickException(
+ f"Premises file '{path}' has a 'premises' key that is not a list."
+ )
+ data = premises_value
+ elif not isinstance(data, list):
+ data = [line.strip() for line in text.splitlines()
+ if line.strip() and not line.lstrip().startswith("#")]
+ premises = []
+ for i, item in enumerate(data):
+ if isinstance(item, dict):
+ statement = item.get("statement")
+ if not statement:
+ raise click.ClickException(
+ f"Premise entry {i} in '{path}' is missing 'statement'.")
+ premises.append(Premise(
+ premise_id=str(item.get("id", f"premise_{i}")),
+ statement=str(statement),
+ confidence=float(item.get("confidence", 1.0)),
+ ))
+ else:
+ premises.append(Premise(premise_id=f"premise_{i}", statement=str(item)))
+ if not premises:
+ raise click.ClickException(f"Premises file '{path}' contains no premises.")
+ return premises
+
+
+def _load_observations(path: str) -> List[Any]:
+ """Load AbductiveReasoner ``Observation`` objects from a YAML file.
+
+ Mirrors _load_rule_definitions()'s format conventions: a YAML list of
+ plain description strings, a list of ``{description, facts}`` mappings,
+ a top-level ``{"observations": [...]}`` mapping, or plain-text lines.
+
+ ``facts`` is accepted and parsed onto the Observation (the dataclass
+ has the field), but nothing in abductive_reasoner.py currently reads
+ observation.facts -- hypothesis generation only matches a rule's
+ conclusion against observation.description. Setting it currently has
+ no effect on the result.
+ """
+ from .reasoning.abductive_reasoner import Observation
+ text = Path(path).read_text(encoding="utf-8")
+ try:
+ data = yaml.safe_load(text)
+ except yaml.YAMLError:
+ data = None
+ if isinstance(data, dict):
+ if "observations" not in data:
+ raise click.ClickException(
+ f"Observations file '{path}' is a YAML mapping but has no 'observations' key. "
+ "Expected either a YAML list or a mapping with an 'observations' list."
+ )
+ obs_value = data["observations"]
+ # A present-but-non-list value (e.g. "observations: null") must be
+ # a clear error, not silently fall through to reinterpreting the
+ # raw file text as one-description-per-line plain text -- that
+ # path could otherwise hand find_explanations() a single bogus
+ # observation and report a misleading "success".
+ if not isinstance(obs_value, list):
+ raise click.ClickException(
+ f"Observations file '{path}' has an 'observations' key that is not a list."
+ )
+ data = obs_value
+ elif not isinstance(data, list):
+ data = [line.strip() for line in text.splitlines()
+ if line.strip() and not line.lstrip().startswith("#")]
+ observations = []
+ for i, item in enumerate(data):
+ if isinstance(item, dict):
+ description = item.get("description")
+ if not description:
+ raise click.ClickException(
+ f"Observation entry {i} in '{path}' is missing 'description'.")
+ observations.append(Observation(
+ observation_id=str(item.get("id", f"obs_{i}")),
+ description=str(description),
+ facts=item.get("facts", []),
+ ))
+ else:
+ observations.append(Observation(observation_id=f"obs_{i}", description=str(item)))
+ if not observations:
+ raise click.ClickException(f"Observations file '{path}' contains no observations.")
+ return observations
+
+
def _graph_store_facts(cli_ctx: CLIContext) -> List[str]:
"""Read the configured graph store into Reasoner fact strings.
@@ -1263,6 +1378,80 @@ def _graph_store_facts(cli_ctx: CLIContext) -> List[str]:
return facts
+def _graph_store_as_context(cli_ctx: CLIContext) -> Dict[str, List[Dict[str, Any]]]:
+ """Read the configured graph store into GraphReasoner's expected shape.
+
+ GraphReasoner._prepare_graph_context() reads a plain
+ ``{"entities": [...], "relationships": [...]}`` dict -- distinct from
+ both the raw GraphStore rows and the ``Label(arg)`` fact strings
+ ``_graph_store_facts()`` builds for the other engines.
+ """
+ gs = _get_graph_store(cli_ctx)
+ nodes = gs.get_nodes(limit=sys.maxsize)
+ relationships = gs.get_relationships(limit=sys.maxsize)
+ names: Dict[Any, Any] = {}
+ entities = []
+ for node in nodes:
+ props = node.get("properties") or {}
+ name = props.get("name") or props.get("id") or node.get("id")
+ names[node.get("id")] = name
+ labels = node.get("labels") or ["Entity"]
+ # Multiple labels are all real classifications (mirrors the one
+ # fact-per-label convention _graph_store_facts() uses); joining them
+ # keeps a node with e.g. ["Person", "Employee"] fully described
+ # instead of silently dropping every label but the first.
+ entities.append({
+ "id": name, "name": name, "type": "/".join(labels), "properties": props,
+ })
+ rel_out = []
+ for rel in relationships:
+ source = names.get(rel.get("start_node_id"), rel.get("start_node_id"))
+ target = names.get(rel.get("end_node_id"), rel.get("end_node_id"))
+ rel_out.append({
+ "source": source, "target": target,
+ "type": rel.get("type", "RELATED_TO"),
+ "properties": rel.get("properties") or {},
+ })
+ return {"entities": entities, "relationships": rel_out}
+
+
+def _lowercase_datalog_args(fact_str: str) -> str:
+ """Lowercase only a fact string's arguments, keeping the predicate's
+ case untouched.
+
+ DatalogReasoner reads a leading-uppercase *argument* as a variable
+ (constants must be lowercase), but places no such constraint on the
+ predicate. Lowercasing the whole string would still satisfy the
+ constant check but would break matching against Datalog rules written
+ against the graph's own label spelling, e.g. "Human(X) :- Person(X)."
+ expects a "Person(...)" fact, not "person(...)".
+ """
+ match = re.match(r'^([a-zA-Z0-9_]+)\((.*)\)$', fact_str.strip())
+ if not match:
+ return fact_str
+ predicate, args_str = match.groups()
+ args = [arg.strip().lower() for arg in args_str.split(',')]
+ return f"{predicate}({', '.join(args)})"
+
+
+def _run_reasoning_with_status(
+ cli_ctx: CLIContext, engine: str, local_json: bool, fn: Callable[[], Dict[str, Any]]
+) -> Dict[str, Any]:
+ """Run a reasoning computation, showing a spinner unless output is quiet/JSON.
+
+ Checks _is_json() (global --json OR the command's own --json flag), not
+ just cli_ctx.json_output -- otherwise `reason run --json` (the local
+ flag, global --json omitted) would still print spinner status text to
+ stdout ahead of the JSON payload, corrupting it for a parser.
+ """
+ if cli_ctx.quiet or _is_json(cli_ctx, local_json):
+ return fn()
+ with console.status(
+ f"[{_DIM}]Running {engine} reasoning engine…[/{_DIM}]", spinner="dots"
+ ):
+ return fn()
+
+
# ─── Output helpers ──────────────────────────────────────────────────────────
@@ -2306,59 +2495,220 @@ def reason(ctx: click.Context) -> None:
"datalog", "sparql", "graph"]),
default="rete", show_default=True)
@click.option("--rules", default=None, type=click.Path(exists=True),
- help="Custom rules file (YAML/Datalog/SPARQL).")
+ help="Custom rules file (YAML for rete, Datalog Horn clauses for datalog).")
[email protected]("--query", "query_text", default=None,
+ help="Natural-language question, required for --engine graph.")
[email protected]("--premises", "premises_file", default=None, type=click.Path(exists=True),
+ help="Premises file for --engine deductive (YAML list of statements; "
+ "falls back to graph-store facts if omitted).")
[email protected]("--observations", "observations_file", default=None, type=click.Path(exists=True),
+ help="Observations file for --engine abductive (required).")
@click.option("--json", "local_json", is_flag=True, default=False)
@click.pass_obj
def reason_run(cli_ctx: CLIContext, engine: str, rules: Optional[str],
- local_json: bool) -> None:
+ query_text: Optional[str], premises_file: Optional[str],
+ observations_file: Optional[str], local_json: bool) -> None:
"""Execute a reasoning engine against the knowledge graph.
\b
Example:
semantica reason run --engine rete --rules business-rules.yaml
+ semantica reason run --engine datalog --rules facts.dl
+ semantica reason run --engine graph --query "Who manages Bob?"
+ semantica reason run --engine deductive --premises premises.yaml --rules rules.yaml
+ semantica reason run --engine abductive --observations observations.yaml --rules rules.yaml
"""
cli_ctx = _require_ctx(cli_ctx)
def _action() -> None:
- # Only the forward-chaining production-rule engines run through
- # Reasoner.infer_facts(); the other engines take different inputs
- # (SPARQL/Datalog queries, observations, premises) and are not wired
- # to this command yet. Fail honestly instead of silently
- # forward-chaining under another engine's name.
- if engine not in ("rete", "forward-chain"):
- hint = (" Use 'semantica reason query' for SPARQL/Datalog queries."
- if engine in ("sparql", "datalog") else "")
+ if engine in ("rete", "forward-chain"):
+ try:
+ from .reasoning import Reasoner
+ # Reasoner has no run() method (#1354); dispatch to its real
+ # API: facts from the configured graph store + rules from the
+ # optional --rules file into infer_facts().
+ r = Reasoner(engine=engine, config=cli_ctx.config.to_dict())
+ rule_defs = _load_rule_definitions(rules) if rules else None
+ facts = _graph_store_facts(cli_ctx)
+
+ def _infer() -> Dict[str, Any]:
+ inferred = r.infer_facts(facts, rule_defs)
+ return {
+ "engine": engine,
+ "facts": len(facts),
+ "inferred_count": len(inferred),
+ "inferred_facts": inferred,
+ }
+
+ result = _run_reasoning_with_status(cli_ctx, engine, local_json, _infer)
+ except ImportError as exc:
+ raise click.ClickException(f"Reasoning module not available: {exc}") from exc
+
+ elif engine == "datalog":
+ try:
+ from .reasoning import DatalogReasoner
+ dr = DatalogReasoner(config=cli_ctx.config.to_dict())
+ for rule_def in (_load_rule_definitions(rules) if rules else []):
+ dr.add_rule(rule_def)
+ # Datalog reads a leading-uppercase *argument* as a variable
+ # (see datalog_reasoner.py _is_variable(); predicate case is
+ # unconstrained), so graph-store facts like "Person(Alice)"
+ # need their arguments -- not the predicate -- lowercased to
+ # read as ground constants. Lowercasing the whole string
+ # would also break matching against rules written against
+ # the graph's own (typically title-case) label spelling,
+ # e.g. "Human(X) :- Person(X)."
+ fact_strings = [_lowercase_datalog_args(f) for f in _graph_store_facts(cli_ctx)]
+ for fact_str in fact_strings:
+ dr.add_fact(fact_str)
+
+ def _infer() -> Dict[str, Any]:
+ before = set(fact_strings)
+ derived = dr.derive_all()
+ inferred = [f for f in derived if f not in before]
+ return {
+ "engine": engine,
+ "facts": len(fact_strings),
+ "inferred_count": len(inferred),
+ "inferred_facts": inferred,
+ }
+
+ result = _run_reasoning_with_status(cli_ctx, engine, local_json, _infer)
+ except ImportError as exc:
+ raise click.ClickException(f"Reasoning module not available: {exc}") from exc
+
+ elif engine == "graph":
+ if not query_text:
+ raise click.ClickException(
+ "Engine 'graph' requires --query \"<question>\".")
+ try:
+ from .reasoning import GraphReasoner
+ gr = GraphReasoner(config=cli_ctx.config.to_dict())
+ graph = _graph_store_as_context(cli_ctx)
+
+ def _infer() -> Dict[str, Any]:
+ answer = gr.reason(graph, query_text)
+ # GraphReasoner.reason() never raises on an LLM-side
+ # failure (no provider configured, generation error) --
+ # it returns a string starting with "Error" instead.
+ # Surface that as a real command failure (non-zero exit)
+ # rather than a successful result an automated caller
+ # would read as a real answer.
+ if answer.startswith("Error: LLM provider not initialized") or \
+ answer.startswith("Error during reasoning:"):
+ raise click.ClickException(answer)
+ return {
+ "engine": engine,
+ "query": query_text,
+ "facts": len(graph["entities"]) + len(graph["relationships"]),
+ "answer": answer,
+ }
+
+ result = _run_reasoning_with_status(cli_ctx, engine, local_json, _infer)
+ except ImportError as exc:
+ raise click.ClickException(f"Reasoning module not available: {exc}") from exc
+
+ elif engine == "deductive":
+ try:
+ # DeductiveReasoner/Premise aren't re-exported from
+ # semantica.reasoning's __init__ (unlike DatalogReasoner/
+ # GraphReasoner) -- import from the submodule directly.
+ from .reasoning.deductive_reasoner import DeductiveReasoner, Premise
+ dr = DeductiveReasoner(config=cli_ctx.config.to_dict())
+ for rule_def in (_load_rule_definitions(rules) if rules else []):
+ dr.reasoner.add_rule(rule_def)
+ # DeductiveReasoner uses the same "IF X THEN Y" / "?x"
+ # syntax as rete (both go through Reasoner.add_rule()), so
+ # --rules files are shared across the two engines unchanged.
+ if premises_file:
+ premises = _load_premises(premises_file)
+ else:
+ premises = [Premise(premise_id=f"fact_{i}", statement=fact)
+ for i, fact in enumerate(_graph_store_facts(cli_ctx))]
+
+ def _infer() -> Dict[str, Any]:
+ # apply_logic() scans self.reasoner.rules once, not to a
+ # fixpoint -- a conclusion whose prerequisite premise is
+ # itself a *later* rule's conclusion would be silently
+ # dropped from a single call. known_facts persists on
+ # the DeductiveReasoner instance across calls (premises
+ # are just re-added, which is a no-op on a set), so
+ # looping until a call yields nothing new reaches the
+ # same fixpoint infer_facts()/derive_all() reach for
+ # the other engines.
+ conclusions: List[Any] = []
+ while True:
+ new_conclusions = dr.apply_logic(premises)
+ if not new_conclusions:
+ break
+ conclusions.extend(new_conclusions)
+ return {
+ "engine": engine,
+ "facts": len(premises),
+ "inferred_count": len(conclusions),
+ "inferred_facts": [c.statement for c in conclusions],
+ }
+
+ result = _run_reasoning_with_status(cli_ctx, engine, local_json, _infer)
+ except ImportError as exc:
+ raise click.ClickException(f"Reasoning module not available: {exc}") from exc
+
+ elif engine == "abductive":
+ if not observations_file:
+ raise click.ClickException(
+ "Engine 'abductive' requires --observations <file>.")
+ try:
+ from .reasoning.abductive_reasoner import AbductiveReasoner
+ ab = AbductiveReasoner(config=cli_ctx.config.to_dict())
+ for rule_def in (_load_rule_definitions(rules) if rules else []):
+ ab.reasoner.add_rule(rule_def)
+ # Deliberately not calling _graph_store_facts()/
+ # add_knowledge() here: AbductiveReasoner's current
+ # generate_hypotheses()/find_explanations() never reads
+ # knowledge_base, so it would have no effect on the result
+ # while forcing every abductive run to depend on the
+ # configured graph store being reachable -- even a fully
+ # self-contained --rules + --observations run would fail if
+ # the graph backend is down. Revisit once knowledge_base is
+ # actually consumed by the ranking/generation algorithm.
+ observations = _load_observations(observations_file)
+
+ def _infer() -> Dict[str, Any]:
+ explanations = ab.find_explanations(observations)
+ return {
+ "engine": engine,
+ "observations": len(observations),
+ "explanations": [
+ {
+ "observation": exp.observation.description,
+ "best_hypothesis": (
+ exp.best_hypothesis.explanation
+ if exp.best_hypothesis else None
+ ),
+ "confidence": exp.confidence,
+ "hypotheses_considered": len(exp.hypotheses),
+ }
+ for exp in explanations
+ ],
+ }
+
+ result = _run_reasoning_with_status(cli_ctx, engine, local_json, _infer)
+ except ImportError as exc:
+ raise click.ClickException(f"Reasoning module not available: {exc}") from exc
+
+ else:
+ # sparql is the only remaining engine choice, and it has no
+ # execution path to dispatch to at all: SPARQLReasoner.
+ # execute_query() raises NotImplementedError unconditionally
+ # and the class has no .query() method either. Fail honestly
+ # instead of silently forward-chaining under another engine's
+ # name.
raise click.ClickException(
- f"Engine '{engine}' is not wired to 'reason run' yet; "
- f"supported engines: rete, forward-chain.{hint}")
- try:
- from .reasoning import Reasoner
- # Reasoner has no run() method (#1354); dispatch to its real
- # API: facts from the configured graph store + rules from the
- # optional --rules file into infer_facts().
- r = Reasoner(engine=engine, config=cli_ctx.config.to_dict())
- rule_defs = _load_rule_definitions(rules) if rules else None
- facts = _graph_store_facts(cli_ctx)
-
- def _infer() -> Dict[str, Any]:
- inferred = r.infer_facts(facts, rule_defs)
- return {
- "engine": engine,
- "facts": len(facts),
- "inferred_count": len(inferred),
- "inferred_facts": inferred,
- }
+ "Engine 'sparql' is not wired to 'reason run' yet; "
+ "supported engines: rete, forward-chain, datalog, graph, "
+ "deductive, abductive. Use 'semantica reason query' for "
+ "SPARQL queries.")
- if cli_ctx.quiet or cli_ctx.json_output:
- result = _infer()
- else:
- with console.status(
- f"[{_DIM}]Running {engine} reasoning engine…[/{_DIM}]",
- spinner="dots",
- ):
- result = _infer()
- except ImportError as exc:
- raise click.ClickException(f"Reasoning module not available: {exc}") from exc
if _is_json(cli_ctx, local_json):
_jecho(result if isinstance(result, dict) else {"result": str(result)})
else:
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index a78c32a3..a7d5525e 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -15,6 +15,7 @@ Strategy:
import json
import os
+import re
import stat
import types
from typing import Any
@@ -902,8 +903,392 @@ class TestReason:
result = runner.invoke(cli_module.main,
["reason", "run", "--engine", "sparql"])
assert result.exit_code != 0
- assert "not wired" in result.output
- assert "reason query" in result.output
+ # _flatten() undoes the Rich panel's line-wrap borders, which would
+ # otherwise split "reason query" mid-word and break a raw substring
+ # check.
+ normalized = _flatten(result.output)
+ assert "not wired" in normalized
+ assert "reason query" in normalized
+ assert "Traceback" not in result.output
+
+ def test_run_reasoning_local_json_flag_suppresses_spinner(self, runner, monkeypatch):
+ """`reason run --json` (the command's own flag, not the global one)
+ must not enter the Rich status spinner. console.status() writes to
+ stdout; entering it under the local-only flag would put status text
+ ahead of the JSON payload in the same stream."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+ status_calls = []
+ real_status = cli_module.console.status
+
+ def _spy_status(*a, **kw):
+ status_calls.append((a, kw))
+ return real_status(*a, **kw)
+
+ monkeypatch.setattr(cli_module.console, "status", _spy_status)
+ result = runner.invoke(cli_module.main, ["reason", "run", "--json"])
+ _ok(result)
+ assert status_calls == []
+
+ def test_run_deductive_falls_back_to_graph_store_facts(self, runner, monkeypatch, tmp_path):
+ """--engine deductive without --premises should build Premises from
+ the graph store, matching the rete/datalog fallback convention."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text(
+ "- IF Person(?x) THEN Human(?x)\n"
+ "- IF MANAGES(?x, ?y) THEN Manager(?x)\n",
+ encoding="utf-8")
+
+ class _FakeStore:
+ def get_nodes(self, limit=None):
+ return [{"id": 1, "labels": ["Person"], "properties": {"name": "Alice"}},
+ {"id": 2, "labels": ["Person", "Employee"], "properties": {"name": "Bob"}}]
+
+ def get_relationships(self, limit=None):
+ return [{"id": 9, "type": "MANAGES", "start_node_id": 1, "end_node_id": 2}]
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _FakeStore())
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "deductive", "--rules", str(rules_file)],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["engine"] == "deductive"
+ assert data["facts"] == 4
+ assert "Human(Alice)" in data["inferred_facts"]
+ assert "Human(Bob)" in data["inferred_facts"]
+ assert "Manager(Alice)" in data["inferred_facts"]
+ assert data["inferred_count"] == len(data["inferred_facts"])
+
+ def test_run_deductive_uses_premises_file(self, runner, monkeypatch, tmp_path):
+ """--premises should be used instead of the graph store when given,
+ and accept both plain strings and {statement, confidence} entries."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text("- IF Person(?x) THEN Human(?x)\n", encoding="utf-8")
+ premises_file = tmp_path / "premises.yaml"
+ premises_file.write_text(
+ "- Person(Alice)\n"
+ "- {statement: 'Person(Bob)', confidence: 0.7}\n",
+ encoding="utf-8")
+
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "deductive",
+ "--rules", str(rules_file), "--premises", str(premises_file)],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["facts"] == 2
+ assert "Human(Alice)" in data["inferred_facts"]
+ assert "Human(Bob)" in data["inferred_facts"]
+
+ def test_run_deductive_reaches_fixpoint_across_rule_order(self, runner, monkeypatch, tmp_path):
+ """DeductiveReasoner.apply_logic() scans its rules once, not to a
+ fixpoint -- a single call would miss Human(Bob) here since the rule
+ deriving it needs Employee(Bob), which is itself only derived by a
+ *later* rule in this same call. reason run must loop apply_logic()
+ until no new conclusions appear so rule order doesn't silently drop
+ valid transitive conclusions."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text(
+ "- IF Employee(?x) THEN Human(?x)\n"
+ "- IF Manager(?x) THEN Employee(?x)\n",
+ encoding="utf-8")
+ premises_file = tmp_path / "premises.yaml"
+ premises_file.write_text("- Manager(Bob)\n", encoding="utf-8")
+
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "deductive",
+ "--rules", str(rules_file), "--premises", str(premises_file)],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert "Employee(Bob)" in data["inferred_facts"]
+ assert "Human(Bob)" in data["inferred_facts"]
+
+ def test_run_abductive_requires_observations(self, runner, monkeypatch):
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+ result = runner.invoke(cli_module.main, ["reason", "run", "--engine", "abductive"])
+ assert result.exit_code != 0
+ assert "--observations" in result.output
+ assert "Traceback" not in result.output
+
+ def test_run_abductive_finds_explanations(self, runner, monkeypatch, tmp_path):
+ """--engine abductive should find rules whose conclusion explains
+ each observation, not force everything through infer_facts()."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text("- IF Person(?x) THEN Human(?x)\n", encoding="utf-8")
+ obs_file = tmp_path / "observations.yaml"
+ obs_file.write_text("- Human(Alice)\n", encoding="utf-8")
+
+ class _FakeStore:
+ def get_nodes(self, limit=None):
+ return [{"id": 1, "labels": ["Person"], "properties": {"name": "Alice"}}]
+
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _FakeStore())
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "abductive",
+ "--rules", str(rules_file), "--observations", str(obs_file)],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["engine"] == "abductive"
+ assert data["observations"] == 1
+ assert len(data["explanations"]) == 1
+ exp = data["explanations"][0]
+ assert exp["observation"] == "Human(Alice)"
+ assert exp["best_hypothesis"] is not None
+ assert exp["hypotheses_considered"] == 1
+
+ def test_run_abductive_no_matching_rule_returns_empty_explanation(
+ self, runner, monkeypatch, tmp_path
+ ):
+ """An observation no loaded rule can explain must report cleanly
+ (no hypotheses), not crash or fabricate an explanation."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text("- IF Person(?x) THEN Human(?x)\n", encoding="utf-8")
+ obs_file = tmp_path / "observations.yaml"
+ obs_file.write_text("- Unicorn(Alice)\n", encoding="utf-8")
+
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "abductive",
+ "--rules", str(rules_file), "--observations", str(obs_file)],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ exp = data["explanations"][0]
+ assert exp["best_hypothesis"] is None
+ assert exp["hypotheses_considered"] == 0
+
+ def test_run_abductive_does_not_require_graph_store(self, runner, monkeypatch, tmp_path):
+ """A fully self-contained abductive run (--rules + --observations)
+ must not depend on the configured graph store being reachable.
+ AbductiveReasoner doesn't currently consume knowledge_base at all,
+ so calling _graph_store_facts() here would only add a failure mode
+ with no corresponding benefit."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text("- IF Person(?x) THEN Human(?x)\n", encoding="utf-8")
+ obs_file = tmp_path / "observations.yaml"
+ obs_file.write_text("- Human(Alice)\n", encoding="utf-8")
+
+ def _unreachable_store(ctx):
+ raise RuntimeError("graph store should not be contacted")
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", _unreachable_store)
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "abductive",
+ "--rules", str(rules_file), "--observations", str(obs_file)],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["explanations"][0]["best_hypothesis"] is not None
+
+ def test_run_datalog_derives_facts_from_graph_store(self, runner, monkeypatch, tmp_path):
+ """--engine datalog should run DatalogReasoner.derive_all(), not infer_facts()."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ # Predicate case matches the graph's own label/relationship-type
+ # spelling (title-case "Person", upper-case "MANAGES") -- only
+ # arguments get lowercased into Datalog constants, not predicates.
+ rules_file = tmp_path / "rules.dl"
+ rules_file.write_text(
+ "Human(X) :- Person(X).\n"
+ "Manager(X) :- MANAGES(X, Y).\n",
+ encoding="utf-8")
+
+ class _FakeStore:
+ def get_nodes(self, limit=None):
+ return [{"id": 1, "labels": ["Person"], "properties": {"name": "Alice"}},
+ {"id": 2, "labels": ["Person", "Employee"], "properties": {"name": "Bob"}}]
+
+ def get_relationships(self, limit=None):
+ return [{"id": 9, "type": "MANAGES", "start_node_id": 1, "end_node_id": 2}]
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _FakeStore())
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "datalog", "--rules", str(rules_file)],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["engine"] == "datalog"
+ # Person(alice), Person(bob), Employee(bob), MANAGES(alice, bob)
+ assert data["facts"] == 4
+ assert "Human(alice)" in data["inferred_facts"]
+ assert "Human(bob)" in data["inferred_facts"]
+ assert "Manager(alice)" in data["inferred_facts"]
+ # Base facts must not be reported back as "inferred".
+ assert "Person(alice)" not in data["inferred_facts"]
+ assert data["inferred_count"] == len(data["inferred_facts"])
+
+ def test_run_datalog_lowercases_args_only_not_predicate(self):
+ """Regression for a case-mismatch bug: lowercasing the whole fact
+ string (not just its arguments) made facts like "person(alice)"
+ unmatchable by rules written against the graph's real label
+ spelling, e.g. "Human(X) :- Person(X)."."""
+ assert cli_module._lowercase_datalog_args("Person(Alice)") == "Person(alice)"
+ assert cli_module._lowercase_datalog_args(
+ "MANAGES(Alice, Bob)") == "MANAGES(alice, bob)"
+
+ def test_run_datalog_rejects_ifthen_rules_cleanly(self, runner, monkeypatch, tmp_path):
+ """A rete-style '--rules' file (IF/THEN) is not valid Datalog syntax;
+ it must surface as a clean error, not a Traceback."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text("- IF Person(?x) THEN Human(?x)\n", encoding="utf-8")
+
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+ result = runner.invoke(
+ cli_module.main,
+ ["reason", "run", "--engine", "datalog", "--rules", str(rules_file)],
+ )
+ assert result.exit_code != 0
+ assert "Traceback" not in result.output
+
+ def test_run_datalog_no_rules_uses_empty_ruleset(self, runner, monkeypatch):
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+
+ class _FakeStore:
+ def get_nodes(self, limit=None):
+ return [{"id": 1, "labels": ["Person"], "properties": {"name": "Alice"}}]
+
+ def get_relationships(self, limit=None):
+ return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _FakeStore())
+ result = runner.invoke(
+ cli_module.main, ["--json", "reason", "run", "--engine", "datalog"])
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["facts"] == 1
+ assert data["inferred_count"] == 0
+ assert data["inferred_facts"] == []
+
+ def test_run_graph_requires_query(self, runner, monkeypatch):
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+ result = runner.invoke(cli_module.main, ["reason", "run", "--engine", "graph"])
+ assert result.exit_code != 0
+ assert "--query" in result.output
+ assert "Traceback" not in result.output
+
+ def test_run_graph_dispatches_to_graph_reasoner(self, runner, monkeypatch, tmp_path):
+ """--engine graph should call GraphReasoner.reason(graph, query) and
+ surface its natural-language answer, not the facts-count shape.
+
+ Also regression-guards two context-building gaps: a node with
+ multiple labels must keep all of them (not just labels[0]), and a
+ relationship's properties must reach GraphReasoner, not just its
+ source/target/type.
+ """
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+
+ class _FakeStore:
+ def get_nodes(self, limit=None):
+ return [{"id": 1, "labels": ["Person", "Manager"], "properties": {"name": "Alice"}},
+ {"id": 2, "labels": ["Person"], "properties": {"name": "Bob"}}]
+
+ def get_relationships(self, limit=None):
+ return [{"id": 9, "type": "MANAGES", "start_node_id": 1, "end_node_id": 2,
+ "properties": {"since": "2020"}}]
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _FakeStore())
+
+ class _FakeGraphReasoner:
+ def __init__(self, config=None, **kwargs):
+ pass
+
+ def reason(self, graph, query, **options):
+ assert graph["entities"][0]["name"] == "Alice"
+ assert graph["entities"][0]["type"] == "Person/Manager"
+ assert graph["relationships"][0]["type"] == "MANAGES"
+ assert graph["relationships"][0]["properties"] == {"since": "2020"}
+ assert query == "Who manages Bob?"
+ return "Alice manages Bob."
+
+ monkeypatch.setattr(
+ "semantica.reasoning.GraphReasoner", _FakeGraphReasoner, raising=False)
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "reason", "run", "--engine", "graph",
+ "--query", "Who manages Bob?"],
+ )
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["engine"] == "graph"
+ assert data["query"] == "Who manages Bob?"
+ assert data["answer"] == "Alice manages Bob."
+ assert data["facts"] == 3
+
+ def test_run_graph_surfaces_reasoner_failure_as_error(self, runner, monkeypatch):
+ """GraphReasoner.reason() never raises on an LLM-side failure -- it
+ returns a string starting with "Error" instead. reason run must
+ surface that as a real command failure, not exit 0 with a fake
+ "answer"."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+
+ class _EmptyStore:
+ def get_nodes(self, limit=None): return []
+ def get_relationships(self, limit=None): return []
+
+ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
+
+ class _FailingGraphReasoner:
+ def __init__(self, config=None, **kwargs):
+ pass
+
+ def reason(self, graph, query, **options):
+ return "Error: LLM provider not initialized for GraphReasoner. Check your configuration."
+
+ monkeypatch.setattr(
+ "semantica.reasoning.GraphReasoner", _FailingGraphReasoner, raising=False)
+ result = runner.invoke(
+ cli_module.main, ["reason", "run", "--engine", "graph", "--query", "anything?"])
+ assert result.exit_code != 0
+ assert "LLM provider not initialized" in result.output
assert "Traceback" not in result.output
def test_load_rule_definitions_formats(self, tmp_path):
@@ -994,18 +1379,120 @@ class TestReason:
# Plain-text fallback: the non-comment, non-blank line becomes a rule.
assert result == ["rules: null"]
- def test_run_rejects_deductive_engine(self, runner, monkeypatch):
- """Engines other than rete/forward-chain must be rejected with a helpful message."""
+ def test_load_premises_formats(self, tmp_path):
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ plain = tmp_path / "plain.yaml"
+ plain.write_text("- Person(Alice)\n- Person(Bob)\n", encoding="utf-8")
+ premises = cli_module._load_premises(str(plain))
+ assert [p.statement for p in premises] == ["Person(Alice)", "Person(Bob)"]
+ assert [p.confidence for p in premises] == [1.0, 1.0]
+
+ with_confidence = tmp_path / "confidence.yaml"
+ with_confidence.write_text(
+ "- {statement: 'Person(Alice)', confidence: 0.5}\n", encoding="utf-8")
+ premises = cli_module._load_premises(str(with_confidence))
+ assert premises[0].statement == "Person(Alice)"
+ assert premises[0].confidence == 0.5
+
+ mapping = tmp_path / "mapping.yaml"
+ mapping.write_text("premises:\n - Person(Alice)\n", encoding="utf-8")
+ premises = cli_module._load_premises(str(mapping))
+ assert [p.statement for p in premises] == ["Person(Alice)"]
+
+ def test_load_premises_missing_statement_raises(self, tmp_path):
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ bad = tmp_path / "bad.yaml"
+ bad.write_text("- {confidence: 0.5}\n", encoding="utf-8")
+ import click as _click
+ with pytest.raises(_click.ClickException, match="missing 'statement'"):
+ cli_module._load_premises(str(bad))
+
+ def test_load_premises_null_key_value_raises(self, tmp_path):
+ """A 'premises' key present but not a list (e.g. YAML null) must be
+ a clear error, not silently reinterpreted as one raw-text line
+ ("premises: null" itself becoming a bogus premise)."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ bad = tmp_path / "bad.yaml"
+ bad.write_text("premises: null\n", encoding="utf-8")
+ import click as _click
+ with pytest.raises(_click.ClickException, match="not a list"):
+ cli_module._load_premises(str(bad))
+
+ def test_load_premises_empty_list_raises(self, tmp_path):
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ empty = tmp_path / "empty.yaml"
+ empty.write_text("premises: []\n", encoding="utf-8")
+ import click as _click
+ with pytest.raises(_click.ClickException, match="no premises"):
+ cli_module._load_premises(str(empty))
+
+ def test_load_observations_formats(self, tmp_path):
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ plain = tmp_path / "plain.yaml"
+ plain.write_text("- Human(Alice)\n", encoding="utf-8")
+ observations = cli_module._load_observations(str(plain))
+ assert [o.description for o in observations] == ["Human(Alice)"]
+
+ with_facts = tmp_path / "with_facts.yaml"
+ with_facts.write_text(
+ "- {description: 'Human(Alice)', facts: ['Person(Alice)']}\n", encoding="utf-8")
+ observations = cli_module._load_observations(str(with_facts))
+ assert observations[0].description == "Human(Alice)"
+ assert observations[0].facts == ["Person(Alice)"]
+
+ mapping = tmp_path / "mapping.yaml"
+ mapping.write_text("observations:\n - Human(Alice)\n", encoding="utf-8")
+ observations = cli_module._load_observations(str(mapping))
+ assert [o.description for o in observations] == ["Human(Alice)"]
+
+ def test_load_observations_missing_description_raises(self, tmp_path):
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ bad = tmp_path / "bad.yaml"
+ bad.write_text("- {facts: []}\n", encoding="utf-8")
+ import click as _click
+ with pytest.raises(_click.ClickException, match="missing 'description'"):
+ cli_module._load_observations(str(bad))
+
+ def test_load_observations_null_key_value_raises(self, tmp_path):
+ """A 'observations' key present but not a list (e.g. YAML null)
+ must be a clear error. Previously this fell through to
+ reinterpreting the raw file text as plain lines, turning
+ "observations: null" itself into one bogus Observation and letting
+ `reason run --engine abductive` report a misleading success."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ bad = tmp_path / "bad.yaml"
+ bad.write_text("observations: null\n", encoding="utf-8")
+ import click as _click
+ with pytest.raises(_click.ClickException, match="not a list"):
+ cli_module._load_observations(str(bad))
+
+ def test_load_observations_empty_list_raises(self, tmp_path):
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
+ empty = tmp_path / "empty.yaml"
+ empty.write_text("observations: []\n", encoding="utf-8")
+ import click as _click
+ with pytest.raises(_click.ClickException, match="no observations"):
+ cli_module._load_observations(str(empty))
+
+ def test_run_deductive_no_rules_uses_empty_ruleset(self, runner, monkeypatch):
+ """--engine deductive is wired to DeductiveReasoner.apply_logic() (#1478);
+ it must no longer be rejected -- zero rules just means zero conclusions,
+ matching the rete/datalog no-op-ruleset convention."""
+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")
class _EmptyStore:
def get_nodes(self, limit=None): return []
def get_relationships(self, limit=None): return []
monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())
- result = runner.invoke(cli_module.main, ["reason", "run", "--engine", "deductive"])
- assert result.exit_code != 0
- assert "not wired" in result.output
- assert "Traceback" not in result.output
+ result = runner.invoke(
+ cli_module.main, ["--json", "reason", "run", "--engine", "deductive"])
+ _ok(result)
+ data = json.loads(result.output.strip())
+ assert data["engine"] == "deductive"
+ assert data["facts"] == 0
+ assert data["inferred_count"] == 0
+ assert data["inferred_facts"] == []
def test_explain_requires_conclusion(self, runner):
result = runner.invoke(cli_module.main, ["reason", "explain"])