Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(cli): report a configured store whose backup path is missing (#2011)
Nilay Mallik7493b60a43a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex abf2849a..61c12f51 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,6 +26,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **`semantica backup create` reported success for an archive with no store data** (fixes #1820) by @costajohnt- With no file-based `graph_db` / `vector_store` / `triplet_store` path in the config, `backup create` wrote a manifest with `"files": []` and exited 0. It now fails with an error that points to `semantica backup info`, before asking for a passphrase or confirmation and before writing anything.+- **`semantica backup create` dropped a configured store whose path was missing** (fixes #2009) by @nilaymallikk+ - A configured `graph_db` or `vector_store` whose `path` / `data_path` / `index_path` did not exist on disk was left out of the archive with no warning, so a partial backup reported `✓ Backup created` and exited 0 — the remaining case from #1820, which only covered the archive that was empty of *every* store. Each skipped store is now named in a warning before the passphrase and confirmation prompts, including when every configured store is missing and the #1820 error follows, and recorded under `"skipped"` in `backup_manifest.json`. A backend with no local path key (Pinecone, Neo4j, ...) is not a skip and is not reported+ - The reported path is passed through the same credential redaction as `backup info`, so a connection string with a password never reaches the warning or the manifest, including with `--strip-config`+ - New `--fail-on-skip` turns that warning into a non-zero exit for scheduled and CI backups, which must never archive a partial store set. It runs before anything is written, so a failing run leaves no archive behind. The default stays exit 0, so a config that names a store path which has not been created yet keeps working unchanged+ - New cases in `tests/test_cli_commands.py::TestBackup` cover both directions of the skip, every store missing, the manifest entry, `--fail-on-skip`, credential redaction, and the cloud-backend no-false-positive case+- **`calculate_pagerank` rebuilt the adjacency once per node for a plain graph dictionary** (fixes #1842)- `_get_filtered_neighbors` called `build_adjacency(graph, directed=True)` for every node, making neighbour resolution O(N * (N + E)). `calculate_pagerank` now builds it once before the node loop and passes it in through a new optional `adjacency` argument; scores are unchanged. New `tests/kg/test_centrality_pagerank_adjacency_reuse.py`diff --git a/semantica/cli.py b/semantica/cli.pyindex e82bf8de..d8d9e0af 100644--- a/semantica/cli.py+++ b/semantica/cli.py@@ -5267,9 +5267,15 @@ def _collect_backup_sources(config_path: Optional[str],include: str,strip_config: bool,-) -> List[Tuple[str, Path]]:- """Return (arcname, local_path) pairs for local files to include in a backup."""+) -> Tuple[List[Tuple[str, Path]], List[Dict[str, str]]]:+ """Return (arcname, local_path) pairs for local files to include in a backup.++ Also returns each configured store whose local path does not exist, so the+ caller can report it instead of writing a partial archive with no sign that+ a store was dropped (#2009).+ """sources: List[Tuple[str, Path]] = []+ skipped: List[Dict[str, str]] = []if not strip_config and include in ("config", "all"):candidates: List[str] = [c for c in [config_path, "semantica.yaml", "semantica.yml"] if c]@@ -5302,6 +5308,8 @@ def _collect_backup_sources(_dp: Any = info.get("path") or info.get("data_path") or info.get("index_path")data_path: Optional[str] = str(_dp) if _dp else Noneif not data_path:+ # No local path key at all: a cloud/database backend, which+ # `backup info` reports as not file-copyable. Not a skip.continuep = Path(data_path)if p.is_dir():@@ -5310,8 +5318,16 @@ def _collect_backup_sources(sources.append((f"{store_type}/{f.relative_to(p)}", f))elif p.is_file():sources.append((f"{store_type}/{p.name}", p))+ else:+ # Redacted: this is shown in a warning and written to the+ # manifest, even with --strip-config.+ skipped.append({+ "store": store_type,+ "backend": str(info.get("backend", "unknown")),+ "path": _redact(data_path),+ })- return sources+ return sources, skippeddef _redact(uri: str) -> str:@@ -5379,13 +5395,15 @@ def backup_info(cli_ctx: CLIContext, local_json: bool) -> None:help="Read passphrase from file (must not be world-readable).")@click.option("--strip-config", is_flag=True, default=False,help="Exclude semantica.yaml to avoid storing credentials at rest.")[email protected]("--fail-on-skip", is_flag=True, default=False,+ help="Exit non-zero when a configured store path does not exist.")@click.option("--dry-run", "local_dry", is_flag=True, default=False)@click.option("--quiet", "local_quiet", is_flag=True, default=False)@click.pass_objdef backup_create(cli_ctx: CLIContext, destination: str, include: str, compress: bool,encrypt: bool, keyfile: Optional[str], strip_config: bool,- local_dry: bool, local_quiet: bool,+ fail_on_skip: bool, local_dry: bool, local_quiet: bool,) -> None:"""Create a full backup archive.@@ -5424,7 +5442,20 @@ def backup_create(passphrase = Nonecfg = cli_ctx.config.to_dict()- sources = _collect_backup_sources(cfg, cli_ctx.config_path, include, strip_config)+ sources, skipped = _collect_backup_sources(+ cfg, cli_ctx.config_path, include, strip_config,+ )+ # A configured store whose path is missing was dropped without a word,+ # so a partial archive was reported as a success (#2009). Report every+ # one before the prompts, and before the empty-archive check below so+ # the missing paths are named even when no store is left to back up.+ for entry in skipped:+ _warn(+ cli_ctx,+ f"Skipping {entry['store']} store ({entry['backend']}): "+ f"path does not exist: {entry['path']}",+ )+# Fail before any prompt instead of writing an archive with no# store data in it (#1820).if include in ("graph", "vector", "triplet", "all") and not any(@@ -5439,6 +5470,14 @@ def backup_create("to see how to back up other backends.")+ if skipped and fail_on_skip:+ missing = ", ".join(f"{e['store']} ({e['path']})" for e in skipped)+ raise click.ClickException(+ f"Configured store path does not exist: {missing}. Nothing from "+ "those stores would be in the archive; create the path, drop it "+ "from the config, or omit --fail-on-skip to back up the rest."+ )+if encrypt and passphrase is None:passphrase = click.prompt("Backup passphrase", hide_input=True,confirmation_prompt=True)@@ -5461,6 +5500,7 @@ def backup_create("include": include,"version": str(__version__),"files": [arcname for arcname, _ in sources],+ "skipped": skipped,}(tmp_path / "backup_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8",@@ -5546,7 +5586,9 @@ def backup_sync(cli_ctx: CLIContext, destination: str, include: str,import shutildest = Path(destination)cfg = cli_ctx.config.to_dict()- sources = _collect_backup_sources(cfg, cli_ctx.config_path, include, strip_config=False)+ sources, _skipped = _collect_backup_sources(+ cfg, cli_ctx.config_path, include, strip_config=False,+ )if _is_dry(cli_ctx, local_dry):_dry(cli_ctx, "sync backup", destination=str(dest), include=include,files=[a for a, _ in sources])diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.pyindex b12c1da3..6cabeb2e 100644--- a/tests/test_cli_commands.py+++ b/tests/test_cli_commands.py@@ -3150,6 +3150,234 @@ class TestBackup:names = tar.getnames()assert "semantica-backup/graph/graph.db" in names+ def test_create_reports_a_store_whose_path_is_missing(self, runner):+ # Regression for #2009: a configured store whose path does not exist was+ # dropped without a word, so the archive was partial and still reported+ # success. The skip must be named, and recorded in the manifest.+ with runner.isolated_filesystem():+ os.makedirs("vecs")+ with open("vecs/index.json", "w") as f:+ f.write("{}")+ with open("cfg.yaml", "w") as f:+ f.write(+ "graph_db:\n"+ " backend: local\n"+ " path: missing_graph.json\n"+ "vector_store:\n"+ " backend: local\n"+ " path: vecs\n"+ )+ result = runner.invoke(+ cli_module.main,+ ["--config", "cfg.yaml", "backup", "create", "out.tar.gz",+ "--strip-config"],+ )+ _ok(result)+ flat = _flatten(result.output)+ assert "Skipping graph store" in flat+ assert "missing_graph.json" in flat+ with tarfile.open("out.tar.gz") as tar:+ names = tar.getnames()+ manifest = json.loads(+ tar.extractfile("semantica-backup/backup_manifest.json").read()+ )+ assert "semantica-backup/vector/index.json" in names+ assert not any(n.startswith("semantica-backup/graph/") for n in names)+ assert manifest["skipped"] == [+ {"store": "graph", "backend": "local", "path": "missing_graph.json"}+ ]++ def test_create_fail_on_skip_exits_nonzero_without_writing(self, runner):+ with runner.isolated_filesystem():+ os.makedirs("vecs")+ with open("vecs/index.json", "w") as f:+ f.write("{}")+ with open("cfg.yaml", "w") as f:+ f.write(+ "graph_db:\n"+ " backend: local\n"+ " path: missing_graph.json\n"+ "vector_store:\n"+ " backend: local\n"+ " path: vecs\n"+ )+ result = runner.invoke(+ cli_module.main,+ ["--config", "cfg.yaml", "backup", "create", "out.tar.gz",+ "--strip-config", "--fail-on-skip"],+ )+ assert result.exit_code != 0+ assert "Configured store path does not exist" in _flatten(result.output)+ assert not os.path.exists("out.tar.gz")++ def test_create_records_no_skipped_entries_when_paths_exist(self, runner):+ # A store the caller simply has not configured is not a skip, and a+ # backend with no local path key (cloud) must not be reported either.+ with runner.isolated_filesystem():+ os.makedirs("kg")+ with open("kg/graph.db", "w") as f:+ f.write("data")+ with open("cfg.yaml", "w") as f:+ f.write(+ "graph_db:\n"+ " backend: sqlite\n"+ " path: kg\n"+ "vector_store:\n"+ " backend: pinecone\n"+ " index: demo\n"+ )+ result = runner.invoke(+ cli_module.main,+ ["--config", "cfg.yaml", "backup", "create", "out.tar.gz",+ "--strip-config"],+ )+ _ok(result)+ assert "Skipping" not in _flatten(result.output)+ with tarfile.open("out.tar.gz") as tar:+ manifest = json.loads(+ tar.extractfile("semantica-backup/backup_manifest.json").read()+ )+ assert manifest["skipped"] == []++ def test_collect_backup_sources_separates_missing_paths(self, runner):+ with runner.isolated_filesystem():+ os.makedirs("vecs")+ with open("vecs/index.json", "w") as f:+ f.write("{}")+ cfg = {+ "graph_db": {"backend": "local", "path": "gone.json"},+ "vector_store": {"backend": "local", "path": "vecs"},+ "triplet_store": {"backend": "pinecone", "index": "demo"},+ }+ sources, skipped = cli_module._collect_backup_sources(+ cfg, None, "all", strip_config=True,+ )+ assert [arcname for arcname, _ in sources] == ["vector/index.json"]+ assert skipped == [+ {"store": "graph", "backend": "local", "path": "gone.json"}+ ]++ @pytest.mark.parametrize("extra_args", [[], ["--fail-on-skip"]])+ def test_create_names_every_missing_store_when_none_exist(self, runner, extra_args):+ # When every configured store path is missing, the empty-archive error+ # (#1820) still fires, but each missing path must be named first.+ with runner.isolated_filesystem():+ with open("cfg.yaml", "w") as f:+ f.write(+ "graph_db:\n"+ " backend: local\n"+ " path: missing_graph.json\n"+ "vector_store:\n"+ " backend: local\n"+ " path: missing_vecs\n"+ )+ result = runner.invoke(+ cli_module.main,+ ["--config", "cfg.yaml", "backup", "create", "out.tar.gz",+ "--strip-config", *extra_args],+ )+ assert result.exit_code != 0+ flat = _flatten(result.output)+ assert "Skipping graph store" in flat+ assert "missing_graph.json" in flat+ assert "Skipping vector store" in flat+ assert "missing_vecs" in flat+ assert "No store data to back up" in flat+ assert not os.path.exists("out.tar.gz")++ def test_create_without_store_config_reports_no_skip(self, runner):+ # No store configured at all is the #1820 case, not a skip.+ with runner.isolated_filesystem():+ with open("cfg.yaml", "w") as f:+ f.write("processing:\n batch_size: 8\n")+ result = runner.invoke(+ cli_module.main,+ ["--config", "cfg.yaml", "backup", "create", "out.tar.gz",+ "--strip-config"],+ )+ assert result.exit_code != 0+ flat = _flatten(result.output)+ assert "No store data to back up" in flat+ assert "Skipping" not in flat++ def test_create_redacts_credentials_in_skipped_path(self, runner):+ # A credential-bearing path must not reach the warning or the+ # manifest, even with --strip-config.+ with runner.isolated_filesystem():+ os.makedirs("vecs")+ with open("vecs/index.json", "w") as f:+ f.write("{}")+ with open("cfg.yaml", "w") as f:+ f.write(+ "graph_db:\n"+ " backend: sqlite\n"+ " path: 'postgresql://user:[email protected]/kg'\n"+ "vector_store:\n"+ " backend: local\n"+ " path: vecs\n"+ )+ result = runner.invoke(+ cli_module.main,+ ["--config", "cfg.yaml", "backup", "create", "out.tar.gz",+ "--strip-config"],+ )+ _ok(result)+ assert "s3cretpw" not in result.output+ assert "Skipping graph store" in _flatten(result.output)+ with tarfile.open("out.tar.gz") as tar:+ raw = tar.extractfile(+ "semantica-backup/backup_manifest.json"+ ).read().decode("utf-8")+ assert "s3cretpw" not in raw+ manifest = json.loads(raw)+ assert len(manifest["skipped"]) == 1+ assert manifest["skipped"][0]["path"].startswith("postgresql://user:")+ assert manifest["skipped"][0]["path"].endswith("@db.example/kg")++ def test_create_fail_on_skip_redacts_credentials(self, runner):+ with runner.isolated_filesystem():+ os.makedirs("vecs")+ with open("vecs/index.json", "w") as f:+ f.write("{}")+ with open("cfg.yaml", "w") as f:+ f.write(+ "graph_db:\n"+ " backend: sqlite\n"+ " path: 'postgresql://user:[email protected]/kg'\n"+ "vector_store:\n"+ " backend: local\n"+ " path: vecs\n"+ )+ result = runner.invoke(+ cli_module.main,+ ["--config", "cfg.yaml", "backup", "create", "out.tar.gz",+ "--strip-config", "--fail-on-skip"],+ )+ assert result.exit_code != 0+ assert "Configured store path does not exist" in _flatten(result.output)+ assert "s3cretpw" not in result.output+ assert not os.path.exists("out.tar.gz")++ def test_collect_backup_sources_redacts_but_checks_the_real_path(self, runner):+ # The redacted form is only for reporting; an existing path containing+ # ":...@" must still be found and archived under its real name.+ with runner.isolated_filesystem():+ os.makedirs("a:b@c")+ with open("a:b@c/index.json", "w") as f:+ f.write("{}")+ cfg = {+ "graph_db": {"backend": "sqlite",+ "path": "postgresql://user:[email protected]/kg"},+ "vector_store": {"backend": "local", "path": "a:b@c"},+ }+ sources, skipped = cli_module._collect_backup_sources(+ cfg, None, "all", strip_config=True,+ )+ assert [arcname for arcname, _ in sources] == ["vector/index.json"]+ assert [str(p) for _, p in sources] == [os.path.join("a:b@c", "index.json")]+ assert len(skipped) == 1+ assert "s3cretpw" not in skipped[0]["path"]+def test_create_dry_run_json(self, runner):# backup create has no per-command --json; use global --jsonresult = runner.invoke(cli_module.main, ["--json", "backup", "create", "backup.tar.gz",