Skip to content

Commit a058755

Browse files
SrijanSrivsafishamsi
authored andcommitted
fix(cluster): keep a community label when membership overlap stays a majority (#2298)
A one-node membership change failed the exact signature check and replaced the saved name with the hub label. Keep the name when the shared nodes are a strict majority of both the saved set and the current set. Related to #2298 (cherry picked from commit 62e83ea)
1 parent f48425e commit a058755

5 files changed

Lines changed: 293 additions & 22 deletions

File tree

‎graphify/cli.py‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2523,12 +2523,19 @@ def dispatch_command(cmd: str) -> None:
25232523
# been re-scoped/re-clustered since labeling, in which case a cid now
25242524
# covers a DIFFERENT community and its old (LLM) name is wrong (#label-stale).
25252525
# Validate each community against the membership signature saved beside the
2526-
# labels; any community that changed (or has no saved label) is renamed by
2527-
# its current hub — deterministic and correct-by-construction — and the user
2526+
# labels; a community whose overlap is not a strict majority of both
2527+
# the saved members and the current members (or that has no saved
2528+
# label) is renamed by its current hub — deterministic and
2529+
# correct-by-construction — and the user
25282530
# is told to `graphify label` for fresh LLM names. Unchanged communities keep
25292531
# their saved label. When no signature sidecar exists (labels predate this),
2530-
# fall back to hub-filling only the communities missing a label.
2531-
from graphify.cluster import community_member_sigs, label_communities_by_hub
2532+
# an equal community count still hub-fills only communities missing a
2533+
# label; a changed count keeps a label only on majority overlap.
2534+
from graphify.cluster import (
2535+
community_member_sigs,
2536+
label_communities_by_hub,
2537+
label_still_applies,
2538+
)
25322539
sig_path = labels_path.parent / (labels_path.name + ".sig")
25332540
saved_sigs: dict[int, str] = {}
25342541
if sig_path.exists():
@@ -2555,14 +2562,29 @@ def dispatch_command(cmd: str) -> None:
25552562
and existing_labels[cid] != f"Community {cid}"
25562563
)
25572564
if saved_sigs:
2558-
# Precise: the membership signature tells us if this exact
2559-
# community changed since it was labeled.
2560-
fresh = have_label and saved_sigs.get(cid) == cur_sigs.get(cid)
2565+
# Equal signature, or a strict majority of both the saved
2566+
# members and the current members (#2298).
2567+
fresh = have_label and label_still_applies(
2568+
cid,
2569+
communities[cid],
2570+
previous_node_community,
2571+
saved_sigs.get(cid),
2572+
cur_sigs.get(cid),
2573+
)
2574+
elif count_mismatch:
2575+
# No signature sidecar. A changed count used to drop every
2576+
# label; keep one only on that same majority overlap.
2577+
fresh = have_label and label_still_applies(
2578+
cid,
2579+
communities[cid],
2580+
previous_node_community,
2581+
None,
2582+
None,
2583+
)
25612584
else:
2562-
# No signature sidecar (labels predate it). A differing community
2563-
# COUNT means the labels describe a different clustering, so a cid's
2564-
# old label can't be trusted; equal count is the best "same" signal.
2565-
fresh = have_label and not count_mismatch
2585+
# No signature sidecar and an equal community count: that
2586+
# count is still the best available "unchanged" signal.
2587+
fresh = have_label
25662588
if fresh:
25672589
labels[cid] = existing_labels[cid]
25682590
else:

‎graphify/cluster.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,3 +480,28 @@ def remap_communities_to_previous(
480480
for new_cid, nodes in communities.items():
481481
remapped[new_to_final[new_cid]] = sorted(nodes)
482482
return dict(sorted(remapped.items(), key=lambda kv: kv[0]))
483+
484+
485+
def label_still_applies(
486+
cid: int,
487+
current_members: list[str],
488+
previous_node_community: dict[str, int],
489+
saved_sig: str | None,
490+
current_sig: str | None,
491+
) -> bool:
492+
"""Whether a saved label still names this community (#2298).
493+
494+
An equal membership signature keeps the label. Otherwise the label stays
495+
only when the nodes shared with the previous assignment are a strict
496+
majority of both the previous set and the current set. A one-node fragment
497+
of a large community fails that test, so remap reusing the old id is not
498+
enough to keep the name.
499+
"""
500+
if saved_sig is not None and current_sig is not None and saved_sig == current_sig:
501+
return True
502+
saved = {str(node) for node, old in previous_node_community.items() if old == cid}
503+
current = {str(node) for node in current_members}
504+
if not saved or not current:
505+
return False
506+
overlap = len(saved & current)
507+
return overlap * 2 > len(saved) and overlap * 2 > len(current)

‎graphify/watch.py‎

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2439,11 +2439,12 @@ def _failed(f: str) -> bool:
24392439
# rebuild that adds nodes, cid 30 can cover a completely different community
24402440
# and its old name is then simply wrong. Validate every reused label against
24412441
# the membership signature saved beside the labels — the same guard the
2442-
# cluster-only path applies — and drop any whose community changed so the
2442+
# cluster-only path applies — and drop any whose overlap is not a strict
2443+
# majority of both the saved members and the current members so the
24432444
# hub-fill below renames it, deterministically and correct-by-construction.
24442445
# Without this, an incremental `graphify update` launders stale names into
24452446
# labels.json as though they were current (#label-stale).
2446-
from graphify.cluster import community_member_sigs
2447+
from graphify.cluster import community_member_sigs, label_still_applies
24472448
cur_sigs = community_member_sigs(communities)
24482449
saved_sigs: dict[int, str] = {}
24492450
if sig_file.exists():
@@ -2456,16 +2457,36 @@ def _failed(f: str) -> bool:
24562457
except Exception:
24572458
saved_sigs = {}
24582459
if saved_sigs:
2459-
# Precise: the signature tells us exactly which communities changed.
2460-
stale = {cid for cid in labels if saved_sigs.get(cid) != cur_sigs.get(cid)}
2460+
# Equal signature, or a strict majority of both the saved members
2461+
# and the current members (#2298).
2462+
stale = {
2463+
cid for cid in labels
2464+
if not label_still_applies(
2465+
cid,
2466+
communities.get(cid, []),
2467+
previous_node_community,
2468+
saved_sigs.get(cid),
2469+
cur_sigs.get(cid),
2470+
)
2471+
}
2472+
elif len(raw) != len(communities):
2473+
# No sidecar (labels predate it). A differing community count used
2474+
# to drop every label; keep one only on that same majority overlap.
2475+
# Compare against the tracked file alone (`raw`), not the
2476+
# pending-merged `labels` -- a from-empty rebuild's fresh pending
2477+
# entries must not count toward "how many labels were saved".
2478+
stale = {
2479+
cid for cid in labels
2480+
if not label_still_applies(
2481+
cid,
2482+
communities.get(cid, []),
2483+
previous_node_community,
2484+
None,
2485+
None,
2486+
)
2487+
}
24612488
else:
2462-
# No sidecar (labels predate it). A differing community COUNT means the
2463-
# labels describe a different clustering, so no cid's label is trustworthy;
2464-
# an equal count is the best available "unchanged" signal. Compare
2465-
# against the tracked file alone (`raw`), not the pending-merged
2466-
# `labels` -- a from-empty rebuild's fresh pending entries must not
2467-
# count toward "how many labels were saved".
2468-
stale = set(labels) if len(raw) != len(communities) else set()
2489+
stale = set()
24692490
for cid in stale:
24702491
del labels[cid]
24712492
pending_cids.discard(cid)

‎tests/test_labeling.py‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,150 @@ def _fail_generate(*a, **k):
841841
assert saved["1"] == "Payment Flow", "genuine label was not reused"
842842

843843

844+
def _auth_billing_graph(out: Path) -> None:
845+
"""Two saved communities plus one unclustered node (#2298)."""
846+
graph = {
847+
"directed": False,
848+
"multigraph": False,
849+
"nodes": [
850+
{"id": "a1", "label": "auth_hub", "community": 0},
851+
{"id": "a2", "label": "auth_a", "community": 0},
852+
{"id": "a3", "label": "auth_b", "community": 0},
853+
{"id": "a4", "label": "auth_c", "community": 0},
854+
{"id": "b1", "label": "bill_hub", "community": 1},
855+
{"id": "b2", "label": "bill_a", "community": 1},
856+
{"id": "b3", "label": "bill_b", "community": 1},
857+
{"id": "b4", "label": "bill_c", "community": 1},
858+
{"id": "a_new", "label": "auth_new"},
859+
],
860+
"links": [
861+
{"source": "a1", "target": "a2", "relation": "calls"},
862+
{"source": "a1", "target": "a3", "relation": "calls"},
863+
{"source": "a1", "target": "a4", "relation": "calls"},
864+
{"source": "b1", "target": "b2", "relation": "calls"},
865+
{"source": "b1", "target": "b3", "relation": "calls"},
866+
{"source": "b1", "target": "b4", "relation": "calls"},
867+
],
868+
}
869+
(out / "graph.json").write_text(json.dumps(graph), encoding="utf-8")
870+
871+
872+
def _patch_cluster_only_reuse(monkeypatch):
873+
# `graphify.cluster` is a lazy function on the package until the submodule
874+
# is imported. cluster-only does `from graphify.cluster import cluster`.
875+
import graphify.cluster # noqa: F401
876+
import graphify.__main__ as cli
877+
878+
monkeypatch.setattr(cli, "_check_skill_version", lambda _: None)
879+
monkeypatch.setattr("graphify.export.to_html", lambda *a, **k: None)
880+
881+
def _fail_generate(*a, **k):
882+
raise AssertionError("generate_community_labels must not be called on the reuse path")
883+
884+
monkeypatch.setattr("graphify.llm.generate_community_labels", _fail_generate)
885+
return cli
886+
887+
888+
def test_cluster_only_keeps_label_on_majority_membership_overlap(tmp_path, monkeypatch):
889+
"""#2298: one added node must not replace a saved name when the shared
890+
members are a strict majority of both the saved set and the current set.
891+
A one-node fragment of a large community must not keep that name."""
892+
from graphify.cluster import community_member_sigs
893+
894+
cli = _patch_cluster_only_reuse(monkeypatch)
895+
896+
root = tmp_path / "add-one"
897+
out = root / "graphify-out"
898+
out.mkdir(parents=True)
899+
_auth_billing_graph(out)
900+
labels_path = out / ".graphify_labels.json"
901+
labels_path.write_text(
902+
json.dumps({"0": "Auth Engine", "1": "Billing Desk"}), encoding="utf-8"
903+
)
904+
old_members = {
905+
0: ["a1", "a2", "a3", "a4"],
906+
1: ["b1", "b2", "b3", "b4"],
907+
}
908+
(out / ".graphify_labels.json.sig").write_text(
909+
json.dumps({str(k): v for k, v in community_member_sigs(old_members).items()}),
910+
encoding="utf-8",
911+
)
912+
913+
def _cluster_with_new(G, *args, **kwargs):
914+
return {
915+
0: ["a1", "a2", "a3", "a4", "a_new"],
916+
1: ["b1", "b2", "b3", "b4"],
917+
}
918+
919+
monkeypatch.setattr("graphify.cluster.cluster", _cluster_with_new)
920+
monkeypatch.setattr(sys, "argv", ["graphify", "cluster-only", str(root), "--no-viz"])
921+
cli.main()
922+
labels = json.loads(labels_path.read_text(encoding="utf-8"))
923+
assert labels["0"] == "Auth Engine"
924+
assert labels["1"] == "Billing Desk"
925+
926+
fragment = tmp_path / "fragment"
927+
fragment_out = fragment / "graphify-out"
928+
fragment_out.mkdir(parents=True)
929+
member_ids = [f"n{i:03d}" for i in range(200)]
930+
fragment_graph = {
931+
"directed": False,
932+
"multigraph": False,
933+
"nodes": [
934+
{"id": nid, "label": nid, "community": 0}
935+
for nid in member_ids
936+
],
937+
"links": [],
938+
}
939+
(fragment_out / "graph.json").write_text(json.dumps(fragment_graph), encoding="utf-8")
940+
(fragment_out / ".graphify_labels.json").write_text(
941+
json.dumps({"0": "Big Service"}), encoding="utf-8"
942+
)
943+
(fragment_out / ".graphify_labels.json.sig").write_text(
944+
json.dumps({str(k): v for k, v in community_member_sigs({0: member_ids}).items()}),
945+
encoding="utf-8",
946+
)
947+
948+
def _cluster_singletons(G, *args, **kwargs):
949+
return {i: [f"n{i:03d}"] for i in range(200)}
950+
951+
monkeypatch.setattr("graphify.cluster.cluster", _cluster_singletons)
952+
monkeypatch.setattr(sys, "argv", ["graphify", "cluster-only", str(fragment), "--no-viz"])
953+
cli.main()
954+
fragment_labels = json.loads(
955+
(fragment_out / ".graphify_labels.json").read_text(encoding="utf-8")
956+
)
957+
assert "Big Service" not in fragment_labels.values()
958+
959+
960+
def test_cluster_only_keeps_unchanged_label_when_count_changes(tmp_path, monkeypatch):
961+
"""#2298: with no signature file, a new singleton community must not hub-rename
962+
communities whose membership did not shrink."""
963+
cli = _patch_cluster_only_reuse(monkeypatch)
964+
965+
out = tmp_path / "graphify-out"
966+
out.mkdir()
967+
_auth_billing_graph(out)
968+
labels_path = out / ".graphify_labels.json"
969+
labels_path.write_text(
970+
json.dumps({"0": "Auth Engine", "1": "Billing Desk"}), encoding="utf-8"
971+
)
972+
973+
def _cluster_plus_singleton(G, *args, **kwargs):
974+
return {
975+
0: ["a1", "a2", "a3", "a4"],
976+
1: ["b1", "b2", "b3", "b4"],
977+
2: ["a_new"],
978+
}
979+
980+
monkeypatch.setattr("graphify.cluster.cluster", _cluster_plus_singleton)
981+
monkeypatch.setattr(sys, "argv", ["graphify", "cluster-only", str(tmp_path), "--no-viz"])
982+
cli.main()
983+
labels = json.loads(labels_path.read_text(encoding="utf-8"))
984+
assert labels["0"] == "Auth Engine"
985+
assert labels["1"] == "Billing Desk"
986+
987+
844988
# ── #2534 case 2: prompt key must not collide with the placeholder sentinel ──
845989

846990

‎tests/test_watch.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,65 @@ def test_rebuild_code_drops_labels_whose_community_changed(tmp_path):
493493
)
494494

495495

496+
def test_rebuild_keeps_label_on_majority_overlap(tmp_path, monkeypatch):
497+
"""#2298: an update that adds one node to a community keeps the saved name
498+
when the previous members are still a strict majority of the new set."""
499+
import json
500+
from graphify.watch import _rebuild_code
501+
502+
corpus = tmp_path / "corpus"
503+
corpus.mkdir()
504+
source = (
505+
"def alpha():\n return beta()\n\n"
506+
"def beta():\n return gamma()\n\n"
507+
"def gamma():\n return 1\n"
508+
)
509+
(corpus / "a.py").write_text(source, encoding="utf-8")
510+
assert _rebuild_code(corpus, acquire_lock=False) is True
511+
512+
out = corpus / "graphify-out"
513+
labels_file = out / ".graphify_labels.json"
514+
graph = json.loads((out / "graph.json").read_text(encoding="utf-8"))
515+
communities: dict[int, list[str]] = {}
516+
previous: dict[str, int] = {}
517+
for node in graph["nodes"]:
518+
cid = node.get("community")
519+
node_id = node.get("id")
520+
if cid is None or node_id is None:
521+
continue
522+
communities.setdefault(int(cid), []).append(str(node_id))
523+
previous[str(node_id)] = int(cid)
524+
assert communities, "expected the first rebuild to cluster at least one community"
525+
largest = max(communities, key=lambda cid: (len(communities[cid]), -cid))
526+
assert len(communities[largest]) >= 2, (
527+
f"largest community {largest} has {communities[largest]}; need at least 2 nodes"
528+
)
529+
530+
distinctive = "Kept Majority Name"
531+
labels_file.write_text(json.dumps({str(largest): distinctive}), encoding="utf-8")
532+
533+
(corpus / "a.py").write_text(
534+
source + "\ndef delta():\n return alpha()\n",
535+
encoding="utf-8",
536+
)
537+
538+
def _cluster_extend_largest(G, *args, **kwargs):
539+
grouped: dict[int, list[str]] = {}
540+
for node in G.nodes:
541+
nid = str(node)
542+
cid = previous.get(nid, largest)
543+
grouped.setdefault(cid, []).append(nid)
544+
return grouped
545+
546+
import graphify.cluster # bind the submodule; the package attribute is lazy
547+
548+
monkeypatch.setattr(graphify.cluster, "cluster", _cluster_extend_largest)
549+
assert _rebuild_code(corpus, acquire_lock=False) is True
550+
551+
saved = json.loads(labels_file.read_text(encoding="utf-8"))
552+
assert distinctive in saved.values()
553+
554+
496555
def test_rebuild_code_keeps_hub_fallback_labels_out_of_the_tracked_file(tmp_path):
497556
"""#3334: a from-empty rebuild (a fresh clone, a new worktree, any CI job
498557
with no prior graphify-out/) names every community by its deterministic

0 commit comments

Comments
 (0)