Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(cli): report stores dropped by an empty directory or backup sync (#2014) (#2036)

Aldrin Joseph1f89df3e338d
diff --git a/semantica/cli.py b/semantica/cli.py
index 12173341..54dcea5f 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -5479,9 +5479,9 @@ def _collect_backup_sources(
) -> 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).
+ Also returns each configured store whose local path does not exist or holds
+ no files, so the caller can report it instead of writing a partial archive
+ with no sign that a store was dropped (#2009, #2014).
"""
sources: List[Tuple[str, Path]] = []
skipped: List[Dict[str, str]] = []
@@ -5500,11 +5500,26 @@ def _collect_backup_sources(
if ont_path:
p = Path(ont_path)
if p.is_dir():
+ before = len(sources)
for f in p.rglob("*"):
if f.is_file():
sources.append((f"ontology/{f.relative_to(p)}", f))
+ if len(sources) == before:
+ # An existing-but-empty directory contributed nothing; report
+ # it instead of dropping it silently (#2014).
+ skipped.append({
+ "store": "ontology",
+ "backend": "file",
+ "path": _redact(ont_path),
+ })
elif p.is_file():
sources.append((f"ontology/{p.name}", p))
+ else:
+ skipped.append({
+ "store": "ontology",
+ "backend": "file",
+ "path": _redact(ont_path),
+ })
store_map = {"graph": "graph_db", "vector": "vector_store", "triplet": "triplet_store"}
for store_type, cfg_key in store_map.items():
@@ -5522,9 +5537,19 @@ def _collect_backup_sources(
continue
p = Path(data_path)
if p.is_dir():
+ before = len(sources)
for f in p.rglob("*"):
if f.is_file():
sources.append((f"{store_type}/{f.relative_to(p)}", f))
+ if len(sources) == before:
+ # Same reporting rule as a missing path: an empty directory
+ # yields no files, so the store would vanish from the archive
+ # with no sign of it (#2014).
+ skipped.append({
+ "store": store_type,
+ "backend": str(info.get("backend", "unknown")),
+ "path": _redact(data_path),
+ })
elif p.is_file():
sources.append((f"{store_type}/{p.name}", p))
else:
@@ -5539,6 +5564,33 @@ def _collect_backup_sources(
return sources, skipped
+def _skip_label(store: str) -> str:
+ """Human label for a skipped entry, without calling ontology a 'store'."""
+ return "ontology" if store == "ontology" else f"{store} store"
+
+
+def _warn_skipped(cli_ctx: CLIContext, skipped: List[Dict[str, str]]) -> None:
+ """Name every configured path that contributed no files (#2009, #2014)."""
+ for entry in skipped:
+ _warn(
+ cli_ctx,
+ f"Skipping {_skip_label(entry['store'])} ({entry['backend']}): "
+ f"path does not exist or contains no files: {entry['path']}",
+ )
+
+
+def _raise_on_skipped(skipped: List[Dict[str, str]], *, target: str) -> None:
+ """Raise the --fail-on-skip error naming every skipped path."""
+ if not skipped:
+ return
+ missing = ", ".join(f"{e['store']} ({e['path']})" for e in skipped)
+ raise click.ClickException(
+ f"Configured store path does not exist or contains no files: {missing}. "
+ f"Nothing from those stores would be {target}; create the path, drop it "
+ "from the config, or omit --fail-on-skip to continue with the rest."
+ )
+
+
def _redact(uri: str) -> str:
"""Redact passwords/tokens from a connection URI."""
import re
@@ -5658,12 +5710,7 @@ def backup_create(
# 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']}",
- )
+ _warn_skipped(cli_ctx, skipped)
# Fail before any prompt instead of writing an archive with no
# store data in it (#1820).
@@ -5679,13 +5726,8 @@ 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 fail_on_skip:
+ _raise_on_skipped(skipped, target="in the archive")
if encrypt and passphrase is None:
passphrase = click.prompt("Backup passphrase", hide_input=True,
@@ -5777,11 +5819,13 @@ def backup_create(
@click.option("--include",
type=click.Choice(["graph", "vector", "triplet", "config", "ontology", "all"]),
default="all", show_default=True)
[email protected]("--fail-on-skip", is_flag=True, default=False,
+ help="Exit non-zero when a configured store path is missing or empty.")
@click.option("--dry-run", "local_dry", is_flag=True, default=False)
@click.option("--quiet", "local_quiet", is_flag=True, default=False)
@click.pass_obj
def backup_sync(cli_ctx: CLIContext, destination: str, include: str,
- local_dry: bool, local_quiet: bool) -> None:
+ fail_on_skip: bool, local_dry: bool, local_quiet: bool) -> None:
"""Incremental folder sync (idempotent, copies only changed files).
\b
@@ -5795,13 +5839,18 @@ def backup_sync(cli_ctx: CLIContext, destination: str, include: str,
import shutil
dest = Path(destination)
cfg = cli_ctx.config.to_dict()
- sources, _skipped = _collect_backup_sources(
+ 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])
return
+ # A skipped store used to be discarded here, so a sync after a partial
+ # create reported success for an incomplete store set (#2014).
+ _warn_skipped(cli_ctx, skipped)
+ if fail_on_skip:
+ _raise_on_skipped(skipped, target="included in the sync")
dest.mkdir(parents=True, exist_ok=True)
try:
os.chmod(str(dest), 0o700)
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index 7470b652..43c6993e 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -3543,6 +3543,167 @@ class TestBackup:
{"store": "graph", "backend": "local", "path": "gone.json"}
]
+ def test_create_reports_a_store_whose_directory_is_empty(self, runner):
+ # Regression for #2014: a configured store whose path exists but holds
+ # no files took the is_dir() branch, contributed nothing, and never
+ # reached `skipped`, so the manifest reported "skipped": [] and the
+ # command exited 0.
+ with runner.isolated_filesystem():
+ os.makedirs("empty_graph")
+ 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: empty_graph\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 "empty_graph" in flat
+ with tarfile.open("out.tar.gz") as tar:
+ manifest = json.loads(
+ tar.extractfile("semantica-backup/backup_manifest.json").read()
+ )
+ assert manifest["skipped"] == [
+ {"store": "graph", "backend": "local", "path": "empty_graph"}
+ ]
+
+ def test_create_empty_dir_fail_on_skip_exits_nonzero(self, runner):
+ with runner.isolated_filesystem():
+ os.makedirs("empty_graph")
+ 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: empty_graph\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_collect_backup_sources_marks_empty_directories_as_skipped(self, runner):
+ with runner.isolated_filesystem():
+ os.makedirs("empty_graph")
+ os.makedirs("vecs")
+ with open("vecs/index.json", "w") as f:
+ f.write("{}")
+ cfg = {
+ "graph_db": {"backend": "local", "path": "empty_graph"},
+ "vector_store": {"backend": "local", "path": "vecs"},
+ }
+ 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": "empty_graph"}
+ ]
+
+ def test_collect_backup_sources_reports_empty_ontology_directory(self, runner):
+ # #2014 also flagged the ontology branch: an existing-but-empty (or
+ # absent) ontology path produced no sources and no skip entry.
+ with runner.isolated_filesystem():
+ os.makedirs("empty_onto")
+ os.makedirs("vecs")
+ with open("vecs/index.json", "w") as f:
+ f.write("{}")
+ cfg = {
+ "ontology_path": "empty_onto",
+ "vector_store": {"backend": "local", "path": "vecs"},
+ }
+ 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": "ontology", "backend": "file", "path": "empty_onto"}
+ ]
+
+ def test_sync_names_a_skipped_store(self, runner):
+ with runner.isolated_filesystem():
+ os.makedirs("empty_graph")
+ 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: empty_graph\n"
+ "vector_store:\n"
+ " backend: local\n"
+ " path: vecs\n"
+ )
+ result = runner.invoke(
+ cli_module.main,
+ ["--config", "cfg.yaml", "backup", "sync", "sync_dest"],
+ )
+ _ok(result)
+ flat = _flatten(result.output)
+ assert "Skipping graph store" in flat
+ assert "empty_graph" in flat
+ assert os.path.isfile(os.path.join("sync_dest", "vector", "index.json"))
+
+ def test_sync_fail_on_skip_exits_nonzero(self, runner):
+ with runner.isolated_filesystem():
+ os.makedirs("empty_graph")
+ 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: empty_graph\n"
+ "vector_store:\n"
+ " backend: local\n"
+ " path: vecs\n"
+ )
+ result = runner.invoke(
+ cli_module.main,
+ ["--config", "cfg.yaml", "backup", "sync", "sync_dest",
+ "--fail-on-skip"],
+ )
+ assert result.exit_code != 0
+ assert "Configured store path does not exist" in _flatten(result.output)
+ assert not os.path.exists("sync_dest")
+
+ def test_sync_without_skips_does_not_warn(self, runner):
+ 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")
+ result = runner.invoke(
+ cli_module.main,
+ ["--config", "cfg.yaml", "backup", "sync", "sync_dest"],
+ )
+ _ok(result)
+ assert "Skipping" not in _flatten(result.output)
+
@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