Skip to content

Commit 6ba0868

Browse files
safishamsiclaude
andcommitted
fix(cli): surface four silent success-exit failures (#2534)
cluster-only warns when --backend/--model/--batch-size are ignored on the label-reuse path; the community-label prompt key no longer collides with the discard sentinel (an echoed key was silently dropped); tree --root exits non-zero when it matches no source file instead of flattening the tree; and cluster-only stamps built_at_commit from the analysed graph, not the shell cwd. Also folds in the cluster-only refused-write guard from PR #2522 (thanks @aniJani). Thanks @elecnix for the report. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 9f25a3a commit 6ba0868

6 files changed

Lines changed: 398 additions & 23 deletions

File tree

‎graphify/cli.py‎

Lines changed: 66 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1638,6 +1638,12 @@ def dispatch_command(cmd: str) -> None:
16381638
co_exclude_hubs: float | None = None
16391639
label_max_concurrency: int = 4
16401640
label_batch_size: int = 100
1641+
# #2534: defaults make presence undetectable for these, so track whether
1642+
# the user actually passed them — the label-reuse branch below warns when
1643+
# labeling flags are silently ignored. (--backend/--model default to None,
1644+
# so `is not None` already means "explicitly passed" for those.)
1645+
label_max_concurrency_explicit = False
1646+
label_batch_size_explicit = False
16411647
i_arg = 0
16421648
while i_arg < len(args):
16431649
a = args[i_arg]
@@ -1660,13 +1666,13 @@ def dispatch_command(cmd: str) -> None:
16601666
elif a.startswith("--exclude-hubs="):
16611667
co_exclude_hubs = float(a.split("=", 1)[1]); i_arg += 1
16621668
elif a == "--max-concurrency" and i_arg + 1 < len(args):
1663-
label_max_concurrency = int(args[i_arg + 1]); i_arg += 2
1669+
label_max_concurrency = int(args[i_arg + 1]); label_max_concurrency_explicit = True; i_arg += 2
16641670
elif a.startswith("--max-concurrency="):
1665-
label_max_concurrency = int(a.split("=", 1)[1]); i_arg += 1
1671+
label_max_concurrency = int(a.split("=", 1)[1]); label_max_concurrency_explicit = True; i_arg += 1
16661672
elif a == "--batch-size" and i_arg + 1 < len(args):
1667-
label_batch_size = int(args[i_arg + 1]); i_arg += 2
1673+
label_batch_size = int(args[i_arg + 1]); label_batch_size_explicit = True; i_arg += 2
16681674
elif a.startswith("--batch-size="):
1669-
label_batch_size = int(a.split("=", 1)[1]); i_arg += 1
1675+
label_batch_size = int(a.split("=", 1)[1]); label_batch_size_explicit = True; i_arg += 1
16701676
elif a in ("--no-viz", "--missing-only") or a.startswith("--min-community-size="):
16711677
i_arg += 1
16721678
elif a.startswith("--"):
@@ -1774,6 +1780,22 @@ def dispatch_command(cmd: str) -> None:
17741780
# as fresh forever, permanently blocking real labeling on later runs.
17751781
placeholder_only = False
17761782
if labels_path.exists() and not force_relabel:
1783+
# #2534: this branch never calls the LLM, so labeling flags would be
1784+
# silently ignored. Reuse is still the correct (exit 0) outcome — but
1785+
# say so, instead of letting `--backend openai` look like it relabeled.
1786+
_ignored_label_flags = [flag for flag, given in (
1787+
("--backend", label_backend is not None),
1788+
("--model", label_model is not None),
1789+
("--batch-size", label_batch_size_explicit),
1790+
("--max-concurrency", label_max_concurrency_explicit),
1791+
) if given]
1792+
if _ignored_label_flags:
1793+
print(
1794+
f"[graphify] warning: {'/'.join(_ignored_label_flags)} ignored: "
1795+
f"reusing saved labels at {labels_path}. "
1796+
f"Run `graphify label` to relabel, or delete the labels file.",
1797+
file=sys.stderr,
1798+
)
17771799
# Reuse saved labels, but don't blindly trust them: the graph may have
17781800
# been re-scoped/re-clustered since labeling, in which case a cid now
17791801
# covers a DIFFERENT community and its old (LLM) name is wrong (#label-stale).
@@ -1868,16 +1890,41 @@ def dispatch_command(cmd: str) -> None:
18681890
)
18691891
# Only let the LLM OVERRIDE where it produced a real name — its no-backend
18701892
# fallback returns "Community {cid}" placeholders, which must not clobber
1871-
# the deterministic hub labels.
1893+
# the deterministic hub labels. Also reject a model echoing the prompt
1894+
# key back ("5" for community 5) — that is an id, not a name (#2534).
18721895
labels.update({
18731896
cid: v for cid, v in generated_labels.items()
1874-
if v and v != f"Community {cid}"
1897+
if v and v != f"Community {cid}" and v != str(cid)
18751898
})
18761899
stages.mark("label")
18771900
questions = suggest_questions(G, communities, labels)
1901+
# cluster-only re-clusters an EXISTING graph: the code content is exactly
1902+
# what extract saw, so keep the extract-time commit stamp instead of
1903+
# re-deriving it from the shell's cwd — running from another repo used to
1904+
# re-stamp graph.json with THAT repo's HEAD (#2534). When the loaded
1905+
# graph predates the stamp, fall back to the analysed repo's HEAD via
1906+
# the cwd-aware helper (#2316).
1907+
_commit = _raw.get("built_at_commit")
1908+
if not _commit:
1909+
from graphify.watch import _git_head as _gh
1910+
_commit = _gh(cwd=watch_path)
1911+
# Snapshot BEFORE any artifact is replaced: GRAPH_REPORT.md was written
1912+
# first, so the dated folder held the NEW report, not the previous (#2402).
1913+
from graphify.export import backup_if_protected as _backup
1914+
_backup(out)
1915+
# The #479 guard can refuse this write, so it goes before the sidecars —
1916+
# a report and labels describing a clustering graph.json does not contain
1917+
# are worse than no run at all (#2436).
1918+
if not to_json(G, communities, str(out / "graph.json"),
1919+
community_labels=labels, built_at_commit=_commit):
1920+
print(
1921+
"graph.json NOT written: refusing to overwrite (see warning above). "
1922+
"GRAPH_REPORT.md, .graphify_labels.json and .graphify_analysis.json "
1923+
"left untouched.",
1924+
file=sys.stderr,
1925+
)
1926+
sys.exit(1)
18781927
tokens = label_token_usage
1879-
from graphify.export import _git_head as _gh
1880-
_commit = _gh()
18811928
from graphify.report import load_learning_for_report as _llfr
18821929
report = generate(G, communities, cohesion, labels, gods, surprises,
18831930
{"warning": "cluster-only mode — file stats not available"},
@@ -1886,8 +1933,6 @@ def dispatch_command(cmd: str) -> None:
18861933
learning=_llfr(out / "graph.json"))
18871934
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
18881935
stages.mark("report")
1889-
from graphify.export import backup_if_protected as _backup
1890-
_backup(out)
18911936
analysis = {
18921937
"communities": {str(k): v for k, v in communities.items()},
18931938
"cohesion": {str(k): v for k, v in cohesion.items()},
@@ -1899,7 +1944,6 @@ def dispatch_command(cmd: str) -> None:
18991944
json.dumps(analysis, indent=2, ensure_ascii=False),
19001945
encoding="utf-8",
19011946
)
1902-
to_json(G, communities, str(out / "graph.json"), community_labels=labels)
19031947
# Don't persist placeholder-only labels (or their .sig): leaving the
19041948
# sidecar absent lets a later run generate real labels instead of reading
19051949
# back "Community N" as authoritative (#2073).
@@ -2067,11 +2111,17 @@ def dispatch_command(cmd: str) -> None:
20672111
_enforce_graph_size_cap_or_exit(graph_path)
20682112
if output_path is None:
20692113
output_path = graph_path.parent / "GRAPH_TREE.html"
2070-
out = write_tree_html(
2071-
graph_path=graph_path, output_path=output_path,
2072-
root=root, max_children=max_children,
2073-
top_k_edges=top_k_edges, project_label=project_label,
2074-
)
2114+
try:
2115+
out = write_tree_html(
2116+
graph_path=graph_path, output_path=output_path,
2117+
root=root, max_children=max_children,
2118+
top_k_edges=top_k_edges, project_label=project_label,
2119+
)
2120+
except ValueError as exc:
2121+
# e.g. an explicit --root that matches no source_file — the tree
2122+
# would silently flatten, so fail loudly instead (#2534).
2123+
print(f"error: {exc}", file=sys.stderr)
2124+
sys.exit(1)
20752125
size_kb = out.stat().st_size / 1024
20762126
print(f"wrote {out} ({size_kb:.1f} KB)")
20772127
print(f"open with: xdg-open {out} (or file://{out.resolve()})")

‎graphify/llm.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2856,7 +2856,11 @@ def _community_label_lines(G, communities, gods, max_communities, top_k):
28562856
if len(names) >= top_k:
28572857
break
28582858
if names:
2859-
lines.append(f"Community {cid}: {', '.join(names)}")
2859+
# Bare id key, NOT "Community {cid}: ..." — that string doubles as the
2860+
# placeholder sentinel (_placeholder_community_labels), so a model that
2861+
# echoed the key back produced a "name" indistinguishable from the
2862+
# no-backend fallback and the caller's sentinel filter dropped it (#2534).
2863+
lines.append(f"{cid}: {', '.join(names)}")
28602864
labeled_cids.append(int(cid))
28612865
return lines, labeled_cids
28622866

@@ -2927,6 +2931,7 @@ def _label_batch_with_retry(
29272931
"You are naming clusters in a knowledge graph. For each community below, "
29282932
"return a concise 2-5 word plain-language name describing what it is about "
29292933
"(e.g. \"Order Management\", \"Payment Flow\", \"Auth Middleware\"). "
2934+
"Each input line is '<community id>: <representative member names>'. "
29302935
"Respond ONLY with a JSON object mapping the community id (as a string) to "
29312936
"its name - no prose, no markdown fences.\n\n" + "\n".join(batch_lines)
29322937
)

‎graphify/tree_html.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,17 @@ def build_tree(
7777
Each leaf is either a code symbol (class / top-level function) or
7878
a synthetic "(+N more)" placeholder for truncated wide directories.
7979
Each interior node carries ``total_count = sum of leaf counts``.
80+
81+
Raises ``ValueError`` when an explicit ``root`` matches none of the
82+
graph's ``source_file`` paths — every file would silently attach flat
83+
to the root and the hierarchy would be lost (#2534).
8084
"""
8185
nodes: List[Dict[str, Any]] = list(graph.get("nodes", []))
8286
file_nodes = [n for n in nodes if n.get("source_file")]
8387
if not file_nodes:
8488
return {"name": "(empty graph)", "total_count": 0, "children": []}
8589

90+
explicit_root = root is not None
8691
if root is None:
8792
root = _common_root([n["source_file"] for n in file_nodes])
8893
root_path = Path(root)
@@ -112,11 +117,13 @@ def _ensure_dir(abs_path: Path) -> Dict[str, Any]:
112117
parent["children"].append(node)
113118
return node
114119

120+
matched_files = 0
115121
for src_file, syms in sorted(by_file.items()):
116122
src_path = Path(src_file)
117123
try:
118124
rel = src_path.relative_to(root_path)
119125
parent_path = (root_path / rel).parent
126+
matched_files += 1
120127
except ValueError:
121128
parent_path = root_path
122129
parent_dir = _ensure_dir(parent_path)
@@ -153,6 +160,17 @@ def _ensure_dir(abs_path: Path) -> Dict[str, Any]:
153160
}
154161
parent_dir["children"].append(file_node)
155162

163+
# An explicit --root that matches NOTHING would silently flatten the whole
164+
# hierarchy (every file attaches to the root); the common case is passing an
165+
# absolute checkout path while source_file is stored repo-relative (#2534).
166+
# A PARTIAL match stays fine — files outside the root legitimately attach flat.
167+
if explicit_root and matched_files == 0:
168+
sample = min(by_file)
169+
raise ValueError(
170+
f"--root {root} matched 0 of {len(by_file)} source files "
171+
f"(source_file paths are stored repo-relative, e.g. {sample!r})"
172+
)
173+
156174
# Sort each dir's children + propagate total_count up.
157175
def _finalise(d: Dict[str, Any]) -> int:
158176
kids = d.get("children") or []

‎tests/test_cli_export.py‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,3 +650,128 @@ def _build(root: Path):
650650
leak = {"alice_home", "bob_elsewhere", "checkout", "tmp", "private", "users", "home", "var"}
651651
assert not any(part in leak for ident in a for part in ident.split("_")), \
652652
f"node id embeds an absolute-path component: {a}"
653+
654+
655+
# ── cluster-only silent failures (#2534) + refused-write exit code (#2522) ───
656+
657+
658+
def test_cluster_only_reports_failure_when_write_is_refused(tmp_path):
659+
"""The #479 shrink guard can refuse to overwrite graph.json. cluster-only
660+
still printed "graph.json updated" and exited 0, and it had already written
661+
GRAPH_REPORT.md and the labels for the clustering it then discarded (#2436).
662+
Contributed by @aniJani (#2522)."""
663+
out = _make_graph(tmp_path)
664+
graph_json = out / "graph.json"
665+
666+
# Duplicate node ids make the file look larger than the graph it loads into,
667+
# which is what trips the guard on a real re-cluster.
668+
data = json.loads(graph_json.read_text(encoding="utf-8"))
669+
data["nodes"] = data["nodes"] + data["nodes"][:3]
670+
graph_json.write_text(json.dumps(data), encoding="utf-8")
671+
672+
report = out / "GRAPH_REPORT.md"
673+
report.write_text("PREVIOUS REPORT\n", encoding="utf-8")
674+
before = graph_json.read_text(encoding="utf-8")
675+
676+
r = _run(["cluster-only", ".", "--no-viz", "--no-label"], tmp_path)
677+
678+
assert r.returncode != 0, r.stdout
679+
assert "graph.json NOT written" in r.stderr, r.stderr
680+
assert "graph.json updated" not in r.stdout, r.stdout
681+
assert graph_json.read_text(encoding="utf-8") == before
682+
assert report.read_text(encoding="utf-8") == "PREVIOUS REPORT\n"
683+
684+
685+
def test_cluster_only_happy_path_exits_zero(tmp_path):
686+
"""Guard for the #2522 reordering: the normal re-cluster still succeeds."""
687+
_make_graph(tmp_path)
688+
r = _run(["cluster-only", ".", "--no-viz"], tmp_path)
689+
assert r.returncode == 0, r.stderr
690+
assert "Done -" in r.stdout, r.stdout
691+
assert "communities" in r.stdout
692+
693+
694+
def test_cluster_only_warns_when_labeling_flags_are_ignored(tmp_path):
695+
"""#2534 case 1: with a saved .graphify_labels.json the reuse branch never
696+
calls the LLM, so --backend/--model/--batch-size used to be silently
697+
ignored while exiting 0. Reuse stays a success (exit 0), but the ignored
698+
flags must be named on stderr."""
699+
_make_graph(tmp_path) # persists .graphify_labels.json -> reuse branch
700+
701+
r = _run(["cluster-only", ".", "--backend", "openai", "--no-viz"], tmp_path)
702+
assert r.returncode == 0, r.stderr
703+
assert "--backend" in r.stderr and "ignored" in r.stderr, r.stderr
704+
assert "reusing saved labels" in r.stderr, r.stderr
705+
# the reuse branch must NOT have gone through the LLM labeling path
706+
assert "Labeling communities" not in r.stdout, r.stdout
707+
708+
709+
def test_cluster_only_reuse_without_labeling_flags_stays_quiet(tmp_path):
710+
"""Control for the #2534 case-1 warning: plain reuse prints no flag warning."""
711+
_make_graph(tmp_path)
712+
r = _run(["cluster-only", ".", "--no-viz"], tmp_path)
713+
assert r.returncode == 0, r.stderr
714+
assert "ignored" not in r.stderr, r.stderr
715+
assert "reusing saved labels" not in r.stderr, r.stderr
716+
717+
718+
# ── cluster-only must not re-stamp built_at_commit from the shell's cwd ──────
719+
720+
721+
def _init_git_repo(path: Path, message: str) -> str:
722+
"""git init + one empty commit; returns the HEAD sha."""
723+
path.mkdir(parents=True, exist_ok=True)
724+
subprocess.run(["git", "init", "-q", str(path)], check=True, capture_output=True)
725+
subprocess.run(
726+
["git", "-C", str(path), "-c", "user.email=t@test", "-c", "user.name=t",
727+
"-c", "commit.gpgsign=false", "commit", "--allow-empty", "-q", "-m", message],
728+
check=True, capture_output=True,
729+
)
730+
return subprocess.run(
731+
["git", "-C", str(path), "rev-parse", "HEAD"],
732+
check=True, capture_output=True, text=True,
733+
).stdout.strip()
734+
735+
736+
def test_cluster_only_preserves_built_at_commit_from_other_repo_cwd(tmp_path):
737+
"""#2534 case 4: cluster-only re-clusters an EXISTING graph, so the
738+
extract-time built_at_commit must survive — running it from a DIFFERENT
739+
repo used to re-stamp graph.json with that repo's HEAD."""
740+
target = tmp_path / "target"
741+
commit_x = _init_git_repo(target, "init target")
742+
out = _make_graph(target)
743+
graph_json = out / "graph.json"
744+
data = json.loads(graph_json.read_text(encoding="utf-8"))
745+
data["built_at_commit"] = commit_x
746+
graph_json.write_text(json.dumps(data), encoding="utf-8")
747+
748+
other = tmp_path / "other"
749+
commit_y = _init_git_repo(other, "init other")
750+
assert commit_x != commit_y
751+
752+
r = _run(["cluster-only", str(target), "--no-viz"], other)
753+
assert r.returncode == 0, r.stderr
754+
final = json.loads(graph_json.read_text(encoding="utf-8"))
755+
assert final.get("built_at_commit") == commit_x, (
756+
f"built_at_commit re-stamped from the shell's cwd: expected {commit_x}, "
757+
f"got {final.get('built_at_commit')} (other repo HEAD is {commit_y})"
758+
)
759+
760+
761+
def test_cluster_only_preserves_built_at_commit_from_non_repo_cwd(tmp_path):
762+
"""#2534 case 4: from a cwd that is not a git repo at all, the stamp must
763+
still be preserved — not dropped."""
764+
target = tmp_path / "target"
765+
commit_x = _init_git_repo(target, "init target")
766+
out = _make_graph(target)
767+
graph_json = out / "graph.json"
768+
data = json.loads(graph_json.read_text(encoding="utf-8"))
769+
data["built_at_commit"] = commit_x
770+
graph_json.write_text(json.dumps(data), encoding="utf-8")
771+
772+
plain = tmp_path / "plain"
773+
plain.mkdir()
774+
r = _run(["cluster-only", str(target), "--no-viz"], plain)
775+
assert r.returncode == 0, r.stderr
776+
final = json.loads(graph_json.read_text(encoding="utf-8"))
777+
assert final.get("built_at_commit") == commit_x

0 commit comments

Comments
 (0)