fix(wiki): fold slugs with casefold so the orphan sweep keeps current articles

to_wiki allocated unique slugs with str.lower() while the orphan sweep
indexed produced filenames with str.casefold(). For labels whose lower()
spellings differ but whose case folds agree ("Straße" / "STRASSE",
"Σ" / "ς"), both slugs were allocated, the folded map kept one, and the
sweep unlinked the other freshly written article. The export reported
both and index.md linked to the deleted page.

Dedup slugs on casefold(), the same relation the sweep uses, keeping the
existing ASCII filename behavior. Also skip any file whose exact name is
in produced before consulting the folded map, so "never delete a file
this run wrote" holds even if the two rules drift again, and build the
map from sorted(produced) so the survivor is deterministic.

Regressions cover community/community, community/hub and hub/hub
collisions for German sharp-s and Greek sigma, verify every link and
article body, and require repeated exports to be a byte-identical
fixpoint. The relabel test guards against turning the cleanup into a
no-op.

Fixes #5087

(cherry picked from commit 914f70d3fa)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-11-09 14:09:19 +00:00
1 parent 43e1d4650a
commit 1de3f09607
2 files changed
+128 -11

No files matched your search

+21 -6
View File
@@ -383,16 +383,22 @@ def to_wiki(
_slug_limit = stem_filename_budget(out, reserve=_SLUG_SUFFIX_RESERVE)
def _unique_slug(base: str) -> str:
# Fold case in the collision check: two labels differing only by case
# (e.g. "Parser" vs "parser") resolve to one path on case-insensitive
# Fold with casefold(), the SAME rule the orphan sweep below indexes
# produced filenames with - not lower(). Two labels differing only by
# case (e.g. "Parser" vs "parser") resolve to one path on case-insensitive
# filesystems (macOS/APFS, Windows/NTFS), so they must dedup against each
# other while still emitting the original-case filename.
# other while still emitting the original-case filename. lower() is not
# enough for Unicode: "Straße".lower() != "STRASSE".lower(), yet both
# casefold to "strasse", so both slugs were allocated and the sweep's
# folded map kept one and unlinked the other current article (#5087).
# Same fold on both sides keeps every produced name distinct here, so a
# name the sweep sees is always one it produced.
slug = base
n = 2
while slug.lower() in used_slugs:
while slug.casefold() in used_slugs:
slug = f"{base}_{n}"
n += 1
used_slugs.add(slug.lower())
used_slugs.add(slug.casefold())
return slug
# First pass: assign every article its slug before rendering any body, so the
@@ -458,8 +464,17 @@ def to_wiki(
# check then saw `"groups.md" not in {"Groups.md"}`, unlinked the file this run
# had just written, and left `index.md` pointing at `Groups.md` with nothing
# behind it (#4508).
produced_by_fold = {name.casefold(): name for name in produced}
#
# _unique_slug dedups on casefold(), so this map is one-to-one. sorted()
# keeps the survivor deterministic (not set-iteration order) if it ever is not.
produced_by_fold = {name.casefold(): name for name in sorted(produced)}
for old_article in out.glob("*.md"):
# Never delete a file this run produced. The fold map is one-to-one only
# because _unique_slug dedups on casefold(); this exact-name check keeps
# that promise even if a future slug rule drifts from the fold rule again
# (#5087: two current Unicode labels, only one fold key, one article lost).
if old_article.name in produced:
continue
wanted = produced_by_fold.get(old_article.name.casefold())
if wanted is None:
old_article.unlink()
+107 -5
View File
@@ -287,8 +287,8 @@ def test_to_wiki_case_only_distinct_labels_dont_overwrite(tmp_path):
# both communities survive as separate files on disk (no silent overwrite)
assert len(articles) == n == 2, [p.name for p in articles]
# filenames are distinct even when compared case-insensitively
lowered = [p.stem.lower() for p in articles]
assert len(set(lowered)) == len(lowered), [p.name for p in articles]
folded = [p.stem.casefold() for p in articles]
assert len(set(folded)) == len(folded), [p.name for p in articles]
def test_to_wiki_god_node_label_case_collides_with_community(tmp_path):
@@ -305,8 +305,8 @@ def test_to_wiki_god_node_label_case_collides_with_community(tmp_path):
n = to_wiki(G, communities, tmp_path, community_labels=labels, god_nodes_data=god_nodes)
articles = [p for p in tmp_path.glob("*.md") if p.name != "index.md"]
assert len(articles) == n == 2, [p.name for p in articles]
lowered = [p.stem.lower() for p in articles]
assert len(set(lowered)) == len(lowered), [p.name for p in articles]
folded = [p.stem.casefold() for p in articles]
assert len(set(folded)) == len(folded), [p.name for p in articles]
def test_to_wiki_article_labelled_index_does_not_overwrite_index_md(tmp_path):
@@ -327,7 +327,7 @@ def test_to_wiki_article_labelled_index_does_not_overwrite_index_md(tmp_path):
labels = {0: "index", 1: "Search"}
god_nodes = [{"id": "n3", "label": "Index", "degree": 1}]
n = to_wiki(G, communities, tmp_path, community_labels=labels, god_nodes_data=god_nodes)
articles = [p for p in tmp_path.glob("*.md") if p.stem.lower() != "index"]
articles = [p for p in tmp_path.glob("*.md") if p.stem.casefold() != "index"]
# every article survives as its own file next to the catalog
assert len(articles) == n == 3, sorted(p.name for p in tmp_path.glob("*.md"))
index_text = (tmp_path / "index.md").read_text(encoding="utf-8")
@@ -336,6 +336,108 @@ def test_to_wiki_article_labelled_index_does_not_overwrite_index_md(tmp_path):
assert "(index.md)" not in index_text, index_text
# Unicode labels that share a case fold but not a lower() spelling. On 0.9.104,
# lower()-based slug dedup allocated a distinct slug for each, while the
# casefold()-based orphan sweep mapped both filenames to the same key and
# unlinked whichever current article it did not keep (#5087).
_UNICODE_FOLD_PAIRS = [
("Straße", "STRASSE"),
("Σ", "ς"),
]
def _assert_wiki_complete(root: Path, expected_headings: set[str]) -> None:
"""Every expected article survives under a distinct folded slug, its body is
the one generated for it, and every inline link target exists on disk."""
files = sorted(p.name for p in root.glob("*.md"))
articles = [p for p in root.glob("*.md") if p.name != "index.md"]
assert len(articles) == len(expected_headings), files
assert len({p.stem.casefold() for p in articles}) == len(articles), files
headings = {p.read_text(encoding="utf-8").splitlines()[0] for p in articles}
assert headings == {f"# {label}" for label in expected_headings}, headings
for md in root.glob("*.md"):
for display, target in _inline_links(md.read_text(encoding="utf-8")):
assert (root / target).exists(), f"{md.name}: [{display}] -> {target} is dead"
@pytest.mark.parametrize("labels", _UNICODE_FOLD_PAIRS, ids=["german-sharp-s", "greek-sigma"])
@pytest.mark.parametrize("kind", ["community-community", "community-hub", "hub-hub"])
def test_to_wiki_unicode_case_fold_collision_keeps_both_articles(tmp_path, kind, labels):
"""Two simultaneously produced Unicode labels with the same case fold must
both survive. Allocating slugs with lower() while the orphan sweep folds with
casefold() let both slugs through and then deleted one as if it were a stale
spelling, leaving index.md linking to a file that no longer existed (#5087)."""
first, second = labels
G = nx.Graph()
G.add_node("n1", label=first, file_type="code", source_file="a.py")
G.add_node("n2", label=second, file_type="code", source_file="b.py")
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", weight=1.0)
if kind == "community-community":
communities = {0: ["n1"], 1: ["n2"]}
community_labels = {0: first, 1: second}
god_nodes = []
expected = {first, second}
elif kind == "community-hub":
communities = {0: ["n1"]}
community_labels = {0: first}
god_nodes = [{"id": "n2", "label": second, "degree": 1}]
expected = {first, second}
else:
communities = {0: ["n1", "n2"]}
community_labels = {0: "Core"}
god_nodes = [
{"id": "n1", "label": first, "degree": 1},
{"id": "n2", "label": second, "degree": 1},
]
expected = {"Core", first, second}
count = to_wiki(
G, communities, tmp_path,
community_labels=community_labels, god_nodes_data=god_nodes,
)
assert count == len(expected)
_assert_wiki_complete(tmp_path, expected)
def test_to_wiki_unicode_case_fold_repeat_export_is_stable(tmp_path):
"""Re-exporting the same graph must not delete an article the first export
wrote, and must leave the wiki byte-identical (#5087)."""
first, second = _UNICODE_FOLD_PAIRS[0]
G = nx.Graph()
G.add_node("n1", label=first, file_type="code", source_file="a.py")
G.add_node("n2", label=second, file_type="code", source_file="b.py")
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", weight=1.0)
communities = {0: ["n1"], 1: ["n2"]}
labels = {0: first, 1: second}
to_wiki(G, communities, tmp_path, community_labels=labels)
after_first = {p.name: p.read_text(encoding="utf-8") for p in tmp_path.glob("*.md")}
_assert_wiki_complete(tmp_path, {first, second})
to_wiki(G, communities, tmp_path, community_labels=labels)
after_second = {p.name: p.read_text(encoding="utf-8") for p in tmp_path.glob("*.md")}
assert after_second == after_first
_assert_wiki_complete(tmp_path, {first, second})
def test_to_wiki_unicode_case_fold_relabel_removes_stale_twin(tmp_path):
"""The fold-aware sweep must still remove a genuinely stale spelling when a
community is relabelled from one fold-equal form to the other. Keeping both
current articles must not turn the cleanup into a no-op (#4508, #5087)."""
first, second = _UNICODE_FOLD_PAIRS[0]
G = nx.Graph()
G.add_node("n1", label="parse", file_type="code", source_file="a.py")
to_wiki(G, {0: ["n1"]}, tmp_path, community_labels={0: first})
assert (tmp_path / f"{first}.md").exists()
to_wiki(G, {0: ["n1"]}, tmp_path, community_labels={0: second})
articles = [p.name for p in tmp_path.glob("*.md") if p.name != "index.md"]
assert articles == [f"{second}.md"], articles
_assert_wiki_complete(tmp_path, {second})
# Regression tests for portable wiki links - Obsidian [[wikilinks]] break in
# every non-Obsidian renderer (VS Code preview, GitHub, GitLab, plain browsers).