fix(export): report a partial backup as no backup and retry it (#3769)

backup_if_protected swallowed per-artifact copy2 failures, so a dated
snapshot whose graph.json never landed still printed the success line
and returned the path — a stale backup surviving the next overwrite
unwarned. The same-day early return also trusted graph.json alone, so
a snapshot missing a sidecar counted as complete forever.

Track failed artifact names, warn on stderr naming them, and return
None when any copy fails. Only early-return when graph.json matches AND
every present source artifact exists in the snapshot, so a partial
snapshot is retried on the next call. The never-raise, never-block
contract is unchanged; the hash check also moves inside the try so an
unreadable snapshot degrades to a warning instead of an exception.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 4eaaa6747c)
This commit is contained in:
angus joseph barlow authored and safishamsi committed 2026-11-01 00:21:03 +00:00
1 parent 35bfdd6166
commit 00920b222f
2 files changed
+86 -11

No files matched your search

+27 -11
View File
@@ -75,18 +75,25 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
backup_dir = out / today
graph_src = out / "graph.json"
# Skip re-copying if today's backup already has identical graph.json content.
# If content differs (graph changed since the last backup today), overwrite
# the backup in place — one folder per day, always the latest pre-overwrite state.
if backup_dir.exists() and (backup_dir / "graph.json").exists():
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
if src_hash == bak_hash:
return backup_dir # identical content, nothing to do
try:
# Skip re-copying if today's backup already holds every artifact with an
# identical graph.json. graph.json alone is not proof of completeness: a
# snapshot missing a sidecar (an earlier copy attempt failed part-way)
# must fall through and retry the copy instead of reporting itself
# complete forever (#3769). If content differs, overwrite the backup in
# place — one folder per day, always the latest pre-overwrite state.
if backup_dir.exists() and (backup_dir / "graph.json").exists():
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
if src_hash == bak_hash and all(
(backup_dir / name).exists()
for name in _BACKUP_ARTIFACTS
if (out / name).exists()
):
return backup_dir # identical content, nothing to do
backup_dir.mkdir(parents=True, exist_ok=True)
copied = 0
failed: list[str] = []
for name in _BACKUP_ARTIFACTS:
src = out / name
if src.exists():
@@ -94,12 +101,21 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
shutil.copy2(src, backup_dir / name)
copied += 1
except Exception:
pass
failed.append(name)
if failed:
# A partial snapshot reported as a successful backup lets a stale
# graph.json survive the next overwrite unnoticed (#3769). Best-effort
# is unchanged: warn, report no backup, do not block the write.
print(
f"[graphify] warning: backup incomplete - could not copy "
f"{', '.join(failed)} -> {backup_dir.name}/ - continuing with overwrite",
file=sys.stderr,
)
return None
if copied:
print(f"[graphify] backed up {reason} graph ({copied} files) -> {backup_dir.name}/")
return backup_dir
except Exception as exc:
import sys
print(f"[graphify] warning: backup failed ({exc}) - continuing with overwrite", file=sys.stderr)
return None
+59
View File
@@ -1061,6 +1061,65 @@ def test_backup_env_disable(tmp_path, monkeypatch):
assert backup_if_protected(tmp_path) is None
# ── Issue #3769: incomplete backups reported as successful ──────────────────
def test_backup_failed_copy_warns_and_returns_none(tmp_path, monkeypatch, capsys):
"""A copy that fails part-way leaves a stale snapshot; it must be warned
and reported as no backup, not printed as a success (#3769)."""
import shutil
from datetime import date
from graphify.export import backup_if_protected
(tmp_path / "graph.json").write_text('{"nodes":[{"id":"new"}],"links":[]}')
(tmp_path / ".graphify_semantic_marker").write_text("{}")
# A same-day snapshot holding the pre-overwrite graph: its graph.json is
# stale but readable, so the copy attempt fails rather than the hash check.
backup_dir = tmp_path / date.today().isoformat()
backup_dir.mkdir()
stale = backup_dir / "graph.json"
stale.write_text('{"nodes":[{"id":"old"}],"links":[]}')
real_copy2 = shutil.copy2
def failing_copy2(src, dst):
if Path(src).name == "graph.json":
raise PermissionError("denied")
return real_copy2(src, dst)
monkeypatch.setattr(shutil, "copy2", failing_copy2)
result = backup_if_protected(tmp_path)
assert result is None
assert "graph.json" in capsys.readouterr().err
# The stale snapshot must not have been silently kept.
assert stale.read_text() == '{"nodes":[{"id":"old"}],"links":[]}'
def test_backup_same_day_retries_missing_sidecar(tmp_path, monkeypatch, capsys):
"""A snapshot missing a sidecar is retried on the next call, not treated
as complete because graph.json already matches (#3769)."""
import shutil
from graphify.export import backup_if_protected
(tmp_path / "graph.json").write_text('{"nodes":[],"links":[]}')
(tmp_path / ".graphify_semantic_marker").write_text("{}")
(tmp_path / "cost.json").write_text('{"input_tokens": 5}')
real_copy2 = shutil.copy2
def failing_copy2(src, dst):
if Path(src).name == "cost.json":
raise PermissionError("denied")
return real_copy2(src, dst)
monkeypatch.setattr(shutil, "copy2", failing_copy2)
assert backup_if_protected(tmp_path) is None
assert "cost.json" in capsys.readouterr().err
monkeypatch.setattr(shutil, "copy2", real_copy2)
result = backup_if_protected(tmp_path)
assert result is not None
assert (result / "graph.json").exists()
assert (result / "cost.json").read_text() == '{"input_tokens": 5}'
def _mkG(n):
import networkx as nx
G = nx.Graph()