Skip to content

Commit 6d31872

Browse files
committed
fix(hooks): read the post-commit cooldown as UTF-8, and name UTF-8 in the remaining test text I/O (#692, class 3)
gated_files.write_json writes the cooldown JSON as UTF-8; post_commit_reindex read it back with a bare read_text(), which uses the locale code page (cp1252 on Windows). Both reads now name UTF-8. The test files that still opened, read or wrote text without an encoding (ruff PLW1514, preview) now name UTF-8. The new test runs the cooldown round trip under -X warn_default_encoding with EncodingWarning made an error; it fails on main and passes here. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018kyZYqX8MAbhBTCuP8EXYc
1 parent b65030b commit 6d31872

10 files changed

Lines changed: 164 additions & 12 deletions

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,15 @@ adheres to [Semantic Versioning](https://semver.org/).
4444

4545
### Fixed
4646

47+
- The post-commit reindex hook reads its cooldown file as UTF-8, the encoding
48+
`gated_files.write_json` writes it in, instead of the locale code page (cp1252 on
49+
Windows). The test files that still wrote or read text in the locale code page
50+
now name UTF-8 (#692, class 3).
51+
- The mutation sandbox copies `.claude-plugin` and `plugins`: the hook tests
52+
selected for `post_commit_reindex.py` read both, so mutmut's clean run failed
53+
before any mutant ran. New tests pin the cooldown window, the unknown-root
54+
default and the pruning of a full cooldown file, which the diff-scoped gate
55+
(ADR-1122) mutates whole.
4756
- The benchmark machine-load snapshot records no load average on Windows
4857
instead of raising: `os.getloadavg` does not exist there, and the
4958
`AttributeError` escaped the `except OSError` (#692 class 4, 13 tests).

‎mcp_server/hooks/post_commit_reindex.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ def _check_cooldown(root: str) -> bool:
169169
"""True when this repo was re-analysed within the cooldown window."""
170170
try:
171171
if _COOLDOWN_FILE.exists():
172-
data = json.loads(_COOLDOWN_FILE.read_text())
172+
data = json.loads(_COOLDOWN_FILE.read_text(encoding="utf-8"))
173173
last = data.get(root, 0)
174174
return (time.time() - last) < _cooldown_seconds()
175175
except (OSError, ValueError, TypeError):
@@ -187,7 +187,7 @@ def _update_cooldown(root: str) -> None:
187187
try:
188188
data = {}
189189
if _COOLDOWN_FILE.exists():
190-
data = json.loads(_COOLDOWN_FILE.read_text())
190+
data = json.loads(_COOLDOWN_FILE.read_text(encoding="utf-8"))
191191
data[root] = time.time()
192192
if len(data) > _MAX_COOLDOWN_ENTRIES:
193193
newest = sorted(data.items(), key=lambda kv: kv[1], reverse=True)

‎pyproject.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -799,6 +799,8 @@ only_mutate = ["mcp_server/shared/json_native.py"]
799799
#
800800
also_copy = [
801801
".github",
802+
".claude-plugin",
803+
"plugins",
802804
"tests_py",
803805
# source: tests_py/handlers/test_beam_anticheat.py imports benchmarks.
804806
"benchmarks",

‎tests_py/benchmarks/test_beam_standard_rag.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030

3131

3232
def _source() -> str:
33-
return SOURCE_PATH.read_text()
33+
return SOURCE_PATH.read_text(encoding="utf-8")
3434

3535

3636
def test_no_recall_handler_import():

‎tests_py/core/test_wiki_stub_detector.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def _make_stub_pages(self, root, n):
132132
for i in range(n):
133133
path = os.path.join(root, "lessons", "p", f"stub-{i:03d}.md")
134134
os.makedirs(os.path.dirname(path), exist_ok=True)
135-
with open(path, "w") as f:
135+
with open(path, "w", encoding="utf-8") as f:
136136
f.write(f"---\ntitle: stub {i}\nkind: lesson\n---\n\n{body}")
137137

138138
def test_cap_limits_per_cycle_purges(self, tmp_path, monkeypatch):

‎tests_py/handlers/test_import_sessions.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def tmp_claude_dir(tmp_path):
5858
]
5959

6060
jsonl_path = proj / "session-001.jsonl"
61-
with open(jsonl_path, "w") as f:
61+
with open(jsonl_path, "w", encoding="utf-8") as f:
6262
for rec in records:
6363
f.write(json.dumps(rec) + "\n")
6464

@@ -73,7 +73,7 @@ def tmp_claude_dir(tmp_path):
7373
"sessionId": "session-002",
7474
},
7575
]
76-
with open(proj2 / "session-002.jsonl", "w") as f:
76+
with open(proj2 / "session-002.jsonl", "w", encoding="utf-8") as f:
7777
for rec in records2:
7878
f.write(json.dumps(rec) + "\n")
7979

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
"""The post-commit cooldown file: its encoding, its window and its pruning (#692).
2+
3+
``gated_files.write_json`` encodes the cooldown JSON as UTF-8, and the hook read it
4+
back with a bare ``read_text()``, which uses the locale code page (cp1252 on
5+
Windows). ``-X warn_default_encoding`` turns each default-encoding file open into an
6+
``EncodingWarning``, made an error in the subprocess test, so that proof holds on
7+
any platform. The in-process tests pin the rest of ``_check_cooldown`` and
8+
``_update_cooldown``, which the diff-scoped mutation gate (ADR-1122) mutates whole.
9+
"""
10+
11+
from __future__ import annotations
12+
13+
import json
14+
import subprocess
15+
import sys
16+
from pathlib import Path
17+
18+
import pytest
19+
20+
from mcp_server.hooks import post_commit_reindex as hook
21+
22+
ROOT = Path(__file__).resolve().parents[2]
23+
REPO = "C:/Users/Clément/projets/日本語"
24+
CHILD = f"""
25+
import sys
26+
from pathlib import Path
27+
from mcp_server.hooks import post_commit_reindex as hook
28+
29+
hook._COOLDOWN_FILE = Path(sys.argv[1]) / "cooldown.json"
30+
hook._update_cooldown({REPO!r})
31+
hook._update_cooldown("/second/repo")
32+
assert hook._check_cooldown({REPO!r}), "the cooldown entry was not read back"
33+
"""
34+
# source: CORTEX_REINDEX_COOLDOWN_SECONDS, set by each test to a round window.
35+
WINDOW = 10
36+
37+
38+
class _RecordingPath(type(Path())):
39+
"""A real path that records the encoding of every ``read_text`` call."""
40+
41+
encodings: list[str | None] = []
42+
43+
def read_text(self, encoding=None, errors=None, **kwargs):
44+
type(self).encodings.append(encoding)
45+
return super().read_text(encoding=encoding, errors=errors, **kwargs)
46+
47+
48+
@pytest.fixture
49+
def cooldown(tmp_path, monkeypatch):
50+
path = _RecordingPath(tmp_path / "cooldown.json")
51+
_RecordingPath.encodings = []
52+
monkeypatch.setattr(hook, "_COOLDOWN_FILE", path)
53+
monkeypatch.setenv("CORTEX_REINDEX_COOLDOWN_SECONDS", str(WINDOW))
54+
return path
55+
56+
57+
def _at(monkeypatch, now: float) -> None:
58+
monkeypatch.setattr(hook.time, "time", lambda: now)
59+
60+
61+
def test_cooldown_round_trip_does_no_default_encoding_io(tmp_path: Path) -> None:
62+
done = subprocess.run(
63+
[
64+
sys.executable,
65+
"-X",
66+
"warn_default_encoding",
67+
"-W",
68+
"error::EncodingWarning",
69+
"-c",
70+
CHILD,
71+
str(tmp_path),
72+
],
73+
capture_output=True,
74+
env={"CORTEX_CLAUDE_DIR": str(tmp_path / "claude"), "PYTHONPATH": str(ROOT)},
75+
cwd=ROOT,
76+
)
77+
assert done.returncode == 0, done.stderr.decode("utf-8", "backslashreplace")
78+
stored = (tmp_path / "cooldown.json").read_bytes().decode("utf-8")
79+
assert "/second/repo" in stored
80+
81+
82+
def test_both_reads_name_utf8(cooldown, monkeypatch) -> None:
83+
_at(monkeypatch, 100.0)
84+
cooldown.write_text(json.dumps({"/a": 100.0}), encoding="utf-8")
85+
hook._update_cooldown("/b")
86+
assert hook._check_cooldown("/a")
87+
assert _RecordingPath.encodings == ["utf-8", "utf-8"]
88+
89+
90+
def test_an_unknown_root_counts_from_the_epoch(cooldown, monkeypatch) -> None:
91+
cooldown.write_text(json.dumps({"/other": 1.0}), encoding="utf-8")
92+
_at(monkeypatch, WINDOW - 5)
93+
assert hook._check_cooldown("/unknown")
94+
_at(monkeypatch, WINDOW)
95+
assert not hook._check_cooldown("/unknown")
96+
97+
98+
def test_the_window_end_is_outside_the_cooldown(cooldown, monkeypatch) -> None:
99+
cooldown.write_text(json.dumps({"/a": 50.0}), encoding="utf-8")
100+
_at(monkeypatch, 50.0 + WINDOW - 1)
101+
assert hook._check_cooldown("/a")
102+
_at(monkeypatch, 50.0 + WINDOW)
103+
assert not hook._check_cooldown("/a")
104+
105+
106+
def test_an_update_keeps_the_other_repositories(cooldown, monkeypatch) -> None:
107+
cooldown.write_text(json.dumps({"/a": 1.0}), encoding="utf-8")
108+
_at(monkeypatch, 2.0)
109+
hook._update_cooldown("/b")
110+
assert json.loads(cooldown.read_text(encoding="utf-8")) == {"/a": 1.0, "/b": 2.0}
111+
112+
113+
def _full_history(count: int) -> dict[str, float]:
114+
# The oldest entry has the lexically largest name, so neither a sort by name
115+
# nor insertion order agrees with a sort by time.
116+
return {f"/r{count - 1 - i:02d}": float(i + 1) for i in range(count)}
117+
118+
119+
def test_a_full_file_drops_only_the_oldest_entry(cooldown, monkeypatch) -> None:
120+
cap = hook._MAX_COOLDOWN_ENTRIES
121+
history = _full_history(cap)
122+
cooldown.write_text(json.dumps(history), encoding="utf-8")
123+
_at(monkeypatch, 1000.0)
124+
hook._update_cooldown("/new")
125+
stored = json.loads(cooldown.read_text(encoding="utf-8"))
126+
oldest = min(history, key=history.__getitem__)
127+
assert len(stored) == cap
128+
assert "/new" in stored and oldest not in stored
129+
130+
131+
def test_a_file_at_the_cap_is_not_pruned(cooldown, monkeypatch) -> None:
132+
history = _full_history(hook._MAX_COOLDOWN_ENTRIES - 1)
133+
cooldown.write_text(json.dumps(history), encoding="utf-8")
134+
_at(monkeypatch, 1000.0)
135+
hook._update_cooldown("/new")
136+
stored = json.loads(cooldown.read_text(encoding="utf-8"))
137+
assert list(stored) == [*history, "/new"]

‎tests_py/scripts/test_launcher_deps_lock.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ def fake_install(deps_dir_arg, set_args):
6262

6363

6464
def _stamp(deps_mod, deps_dir: Path, kind: str) -> dict:
65-
return json.loads(Path(deps_mod._stamp_path(str(deps_dir), kind)).read_text())
65+
return json.loads(
66+
Path(deps_mod._stamp_path(str(deps_dir), kind)).read_text(encoding="utf-8")
67+
)
6668

6769

6870
def test_lock_key_is_the_set_key_of_the_repository_uv_lock(deps_mod):
@@ -92,11 +94,11 @@ def test_stamp_misses_on_another_lock_python_or_corrupt_file(deps_mod, deps_dir)
9294
assert deps_mod._stamp_matches(str(deps_dir), "base", "e" * 64) is False
9395
assert deps_mod._stamp_matches(str(deps_dir), "ml", DIGEST) is False
9496
path = Path(deps_mod._stamp_path(str(deps_dir), "base"))
95-
path.write_text(json.dumps({"python": "0.0", "lock": DIGEST}))
97+
path.write_text(json.dumps({"python": "0.0", "lock": DIGEST}), encoding="utf-8")
9698
assert deps_mod._stamp_matches(str(deps_dir), "base", DIGEST) is False
9799
assert deps_mod._stamp(str(deps_dir), "base") == {}
98100
for corrupt in ("not json{", json.dumps(["lock", DIGEST])):
99-
path.write_text(corrupt)
101+
path.write_text(corrupt, encoding="utf-8")
100102
assert deps_mod._stamp_matches(str(deps_dir), "base", DIGEST) is False
101103

102104

‎tests_py/scripts/test_launcher_setup.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,9 @@ def test_setup_installs_both_sets_stamps_them_and_downloads_the_model(
6969
assert setup.run(deps, "launcher.py") == 0
7070
assert installed == [tuple(deps_mod._sets.BASE), tuple(deps_mod._sets.ML)]
7171
assert deps_mod.set_ready(deps, "base") and deps_mod.set_ready(deps, "ml")
72-
stamp = json.loads(Path(deps_mod._stamp_path(deps, "ml")).read_text())
72+
stamp = json.loads(
73+
Path(deps_mod._stamp_path(deps, "ml")).read_text(encoding="utf-8")
74+
)
7375
assert stamp["lock"] == deps_mod.lock_key()
7476
assert warmed == [deps]
7577
assert setup.outcome(deps) == {"status": "ready", "error": ""}
@@ -131,7 +133,7 @@ def test_a_successful_setup_clears_the_base_job_failure(setup_env, monkeypatch):
131133
_warm(monkeypatch, setup)
132134
stamp = Path(f"{deps}.base-job.failed")
133135
stamp.parent.mkdir(parents=True)
134-
stamp.write_text("{}")
136+
stamp.write_text("{}", encoding="utf-8")
135137
setup.run(deps, "launcher.py")
136138
assert not stamp.exists()
137139

‎tests_py/test_migrate.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def test_migrate_imports_the_servers_url_resolver(self):
5353

5454
source = Path(
5555
__import__("mcp_server.migrate", fromlist=["__file__"]).__file__
56-
).read_text()
56+
).read_text(encoding="utf-8")
5757
tree = ast.parse(source)
5858
imported_names = {
5959
alias.name

0 commit comments

Comments
 (0)