Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: address Qodo review findings on ingest graph-store guard

KaifAhmad1c97fb5d948b2
diff --git a/semantica/cli.py b/semantica/cli.py
index eb875430..d78d2ba7 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -1452,8 +1452,13 @@ def _configured_ingest_graph_backend(
@click.option("--watch", is_flag=True, default=False, help="Re-ingest on file changes.")
@click.option("--batch-size", default=500, type=int, show_default=True)
@click.option("--store", "store_override", default=None,
- help="Target graph backend: neo4j falkordb age neptune")
[email protected]("--output", default=None, type=click.Path(), help="Write to file instead of graph store.")
+ help="Target graph backend: neo4j falkordb age neptune. "
+ "Not yet implemented — ingest cannot persist to a graph "
+ "store, so this only determines whether the command "
+ "refuses to report false success; use --output instead.")
[email protected]("--output", default=None, type=click.Path(),
+ help="Write ingested content to a .json/.jsonl/.csv file "
+ "instead of the (unimplemented) graph store.")
@click.option("--dry-run", "local_dry", is_flag=True, default=False)
@click.option("--json", "local_json", is_flag=True, default=False)
@click.pass_obj
@@ -1480,9 +1485,16 @@ def ingest(
graph_backend = _configured_ingest_graph_backend(cli_ctx, store_override)
if graph_backend and graph_backend.lower() != "memory" and not output:
raise click.ClickException(
- "semantica ingest does not write to graph stores yet; use "
- f"'semantica kg build --source {source}' to build the graph."
+ f"A graph backend is configured ({graph_backend}), but "
+ "semantica ingest does not write to graph stores yet — no CLI "
+ "command currently does (tracked in issues #1351, #1352). "
+ "Pass --output <file>.json to save the ingested content "
+ "instead, or build a GraphStore/GraphBuilder directly in "
+ "Python."
)
+ # NOTE: --store/GRAPH_STORE_DEFAULT_BACKEND are read only to decide
+ # whether to raise the error above — nothing downstream of this point
+ # writes to a graph store, so neither is forwarded as an ingest kwarg.
kwargs: Dict[str, Any] = {"batch_size": batch_size}
if ingestor_type:
kwargs["source_type"] = ingestor_type
@@ -1492,10 +1504,6 @@ def ingest(
kwargs["recursive"] = True
if watch:
kwargs["watch"] = True
- if store_override or cli_ctx.store_backend:
- kwargs["store"] = store_override or cli_ctx.store_backend
- if output:
- kwargs["output"] = output
try:
from .ingest import ingest as _ingest
label = Path(source).name if Path(source).exists() else source
@@ -1509,7 +1517,10 @@ def ingest(
result = _ingest(source, **kwargs)
except ImportError as exc:
raise click.ClickException(f"Ingest module not available: {exc}") from exc
- if _is_json(cli_ctx, local_json):
+ if output:
+ _write_result_output(Path(output), result)
+ _ok(cli_ctx, f"Wrote {output}")
+ elif _is_json(cli_ctx, local_json):
_jecho(result if isinstance(result, dict) else {"status": "ok"})
else:
_ok(cli_ctx, f"Ingested: {source}")
@@ -1766,9 +1777,19 @@ def embed(ctx: click.Context) -> None:
def _json_default(obj) -> object:
"""JSON serialiser that converts NumPy scalars/arrays to native Python types.
+ Also expands dataclasses (e.g. ``FileObject`` from ``ingest``) to plain
+ dicts and decodes ``bytes`` as UTF-8 text where possible, so a domain
+ object round-trips through ``--output`` as data instead of a repr string.
Falls back to ``str()`` for everything else so the writer never crashes on
- unexpected types (e.g. ``datetime``, custom domain objects).
+ unexpected types (e.g. ``datetime``).
"""
+ if is_dataclass(obj) and not isinstance(obj, type):
+ return asdict(obj)
+ if isinstance(obj, bytes):
+ try:
+ return obj.decode("utf-8")
+ except UnicodeDecodeError:
+ return obj.hex()
try:
import numpy as np # local import — only needed when result contains numpy
if isinstance(obj, np.ndarray):
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index 9b3318e8..48905d05 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -69,6 +69,19 @@ def _json_output(result) -> Any:
return json.loads(result.output.strip())
+def _flatten(output: str) -> str:
+ """Undo Rich panel wrapping for substring assertions on error text.
+
+ Rich wraps long messages across multiple bordered lines (each with its
+ own leading/trailing "│"), so a naive whitespace join still leaves those
+ border characters between words that were split across lines. Strip the
+ box-drawing characters first, then collapse whitespace.
+ """
+ for ch in "┌┐└┘│─":
+ output = output.replace(ch, " ")
+ return " ".join(output.split())
+
+
# ─── Global flags ─────────────────────────────────────────────────────────────
@@ -346,10 +359,68 @@ class TestIngest:
)
result = runner.invoke(cli_module.main, ["ingest", "README.md"])
+ output = _flatten(result.output)
+
+ assert result.exit_code != 0
+ assert "does not write to graph stores" in output
+ assert "Ingested:" not in output
+
+ def test_configured_graph_backend_error_does_not_recommend_broken_kg_build(
+ self, runner, monkeypatch
+ ):
+ # kg build also does not persist to a configured graph store
+ # (tracked separately as #1352), so the error must not send users to
+ # a command that will silently no-op the same way.
+ monkeypatch.setenv("GRAPH_STORE_DEFAULT_BACKEND", "neo4j")
+ monkeypatch.setattr(
+ "semantica.ingest.methods.ingest_file",
+ lambda sources, **kwargs: [{"path": sources}],
+ )
+
+ result = runner.invoke(cli_module.main, ["ingest", "README.md"])
+ output = _flatten(result.output)
assert result.exit_code != 0
- assert "does not write to graph stores" in result.output
- assert "Ingested" not in result.output
+ assert "kg build" not in output
+
+ def test_output_flag_writes_real_content_and_bypasses_graph_error(
+ self, runner, monkeypatch, tmp_path
+ ):
+ monkeypatch.setenv("GRAPH_STORE_DEFAULT_BACKEND", "neo4j")
+ monkeypatch.setattr(
+ "semantica.ingest.methods.ingest_file",
+ lambda sources, **kwargs: [{"path": sources}],
+ )
+ out_path = tmp_path / "out.json"
+
+ result = runner.invoke(
+ cli_module.main, ["ingest", "README.md", "--output", str(out_path)]
+ )
+
+ _ok(result, substr="Wrote")
+ written = json.loads(out_path.read_text(encoding="utf-8"))
+ assert written == {"files": [{"path": "README.md"}]}
+
+ def test_store_and_output_are_not_forwarded_to_ingest_backend(
+ self, runner, monkeypatch, tmp_path
+ ):
+ captured = {}
+
+ def fake_ingest_file(sources, **kwargs):
+ captured["kwargs"] = kwargs
+ return [{"path": sources}]
+
+ monkeypatch.setattr("semantica.ingest.methods.ingest_file", fake_ingest_file)
+ out_path = tmp_path / "out.json"
+
+ result = runner.invoke(
+ cli_module.main,
+ ["ingest", "README.md", "--store", "neo4j", "--output", str(out_path)],
+ )
+
+ _ok(result)
+ assert "store" not in captured["kwargs"]
+ assert "output" not in captured["kwargs"]
def test_import_error_is_clean(self, runner, monkeypatch):
monkeypatch.setattr(cli_module, "__import__", _import_side_effect, raising=False)