vomebook commited on
Commit
3c9cfda
·
1 Parent(s): c4bced1

Gate incremental Reader index mutations

Browse files
mutation-equivalent-reader-index.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tool": "mutmut 3.8.1",
3
+ "source": "backend/reader_index.py",
4
+ "source_sha256": "902ac199cc253397475e6fef002b9e718e7b7b92d312847d1bbdd702eb197308",
5
+ "equivalent": {
6
+ "backend.reader_index.x_advance_build__mutmut_32": {
7
+ "sha256": "10641363a41f95af50a475e53becf474d745d68f583593978af469471d750006",
8
+ "rationale": "typing.cast returns the current URL unchanged; replacing the type argument str with None does not affect source ID lookup or publication."
9
+ },
10
+ "backend.reader_index.x_advance_build__mutmut_91": {
11
+ "sha256": "c230d4a9712f56f289f0514c83f6dea4c5be77aab117b985af023d6e3af8cb73",
12
+ "rationale": "typing.cast returns the folder list unchanged; replacing list[object] with None does not affect the list validation or alias eligibility."
13
+ },
14
+ "backend.reader_index.x_advance_build__mutmut_98": {
15
+ "sha256": "ea2c50f7c0f50d328ca21ff4701ce56d4800223decedd7038b5c294427b948fd",
16
+ "rationale": "typing.cast returns the folder list unchanged; replacing list[str] with None does not affect the joined legacy path."
17
+ },
18
+ "backend.reader_index.x_advance_build__mutmut_140": {
19
+ "sha256": "68ba945e857c5ab1086218cd3928c4a6ce285e212cb9d1a3ce410f0749f36e81",
20
+ "rationale": "typing.cast returns the repository unchanged; replacing str with None does not affect the repository index key."
21
+ }
22
+ }
23
+ }
scripts/check_search_words_mutation.py CHANGED
@@ -41,10 +41,23 @@ SPECS: dict[str, tuple[str, list[str], list[str]]] = {
41
  "search_indexes": ("test_native_search_indexes.py", [], []),
42
  "reader_identity": ("test_reader_identity_contract.py", [], []),
43
  "cache_core": ("test_cache_core_contract.py", [], []),
 
44
  }
45
  EMPTY_STATUSES = ("no_tests", "skipped", "suspicious", "timeout", "check_was_interrupted_by_user", "segfault")
46
 
47
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def mutation_errors(stats: dict[str, int], outcomes: dict[str, int],
49
  current_hashes: dict[str, str], reviewed: dict[str, dict[str, str]]) -> list[str]:
50
  errors: list[str] = []
@@ -113,12 +126,12 @@ def main() -> int:
113
  stats = json.loads((temp / "mutants/mutmut-cicd-stats.json").read_text())
114
  meta = json.loads((temp / "mutants/backend" / f"{module}.py.meta").read_text())
115
  generated = (temp / "mutants/backend" / f"{module}.py").read_text()
116
- functions = {node.name: node for node in ast.parse(generated).body if isinstance(node, ast.FunctionDef)}
117
- generated_keys = {f"backend.{module}.{name}" for name in functions if re.search(r"__mutmut_\d+$", name)}
118
  hashes = {}
119
  for key, code in meta["exit_code_by_key"].items():
120
- if code == 0:
121
- segment = ast.get_source_segment(generated, functions[key.rsplit(".", 1)[-1]])
122
  if segment is None:
123
  raise RuntimeError(f"missing generated source for {key}")
124
  hashes[key] = hashlib.sha256(segment.encode()).hexdigest()
 
41
  "search_indexes": ("test_native_search_indexes.py", [], []),
42
  "reader_identity": ("test_reader_identity_contract.py", [], []),
43
  "cache_core": ("test_cache_core_contract.py", [], []),
44
+ "reader_index": ("test_reader_index_contract.py", [], []),
45
  }
46
  EMPTY_STATUSES = ("no_tests", "skipped", "suspicious", "timeout", "check_was_interrupted_by_user", "segfault")
47
 
48
 
49
+ def generated_mutations(module: str, generated: str) -> dict[str, ast.FunctionDef | ast.AsyncFunctionDef]:
50
+ """Inventory generated functions, including async methods inside classes."""
51
+ result: dict[str, ast.FunctionDef | ast.AsyncFunctionDef] = {}
52
+ for node in ast.walk(ast.parse(generated)):
53
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and re.search(r"__mutmut_\d+$", node.name):
54
+ key = f"backend.{module}.{node.name}"
55
+ if key in result:
56
+ raise ValueError(f"duplicate generated mutation: {key}")
57
+ result[key] = node
58
+ return result
59
+
60
+
61
  def mutation_errors(stats: dict[str, int], outcomes: dict[str, int],
62
  current_hashes: dict[str, str], reviewed: dict[str, dict[str, str]]) -> list[str]:
63
  errors: list[str] = []
 
126
  stats = json.loads((temp / "mutants/mutmut-cicd-stats.json").read_text())
127
  meta = json.loads((temp / "mutants/backend" / f"{module}.py.meta").read_text())
128
  generated = (temp / "mutants/backend" / f"{module}.py").read_text()
129
+ functions = generated_mutations(module, generated)
130
+ generated_keys = set(functions)
131
  hashes = {}
132
  for key, code in meta["exit_code_by_key"].items():
133
+ if code == 0 and key in functions:
134
+ segment = ast.get_source_segment(generated, functions[key])
135
  if segment is None:
136
  raise RuntimeError(f"missing generated source for {key}")
137
  hashes[key] = hashlib.sha256(segment.encode()).hexdigest()
tests/test_quality_inventory.py CHANGED
@@ -5,7 +5,7 @@ import tempfile
5
  import unittest
6
 
7
  from scripts.check_backend_coverage import coverage_errors
8
- from scripts.check_search_words_mutation import EMPTY_STATUSES, mutation_errors
9
  from scripts.check_strict_inventory import inventory_errors
10
 
11
 
@@ -169,6 +169,31 @@ class QualityInventoryTests(unittest.TestCase):
169
  self.assertIn("mutation statistics are missing or invalid",
170
  mutation_errors(missing_status, {"a": 1}, {}, {}))
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
  if __name__ == "__main__":
174
  unittest.main()
 
5
  import unittest
6
 
7
  from scripts.check_backend_coverage import coverage_errors
8
+ from scripts.check_search_words_mutation import EMPTY_STATUSES, generated_mutations, mutation_errors
9
  from scripts.check_strict_inventory import inventory_errors
10
 
11
 
 
169
  self.assertIn("mutation statistics are missing or invalid",
170
  mutation_errors(missing_status, {"a": 1}, {}, {}))
171
 
172
+ def test_mutation_inventory_includes_async_and_class_methods(self):
173
+ source = '''
174
+ def x_top__mutmut_1(): pass
175
+ async def x_async__mutmut_2(): pass
176
+ class Example:
177
+ def x_method__mutmut_3(self): pass
178
+ async def x_async_method__mutmut_4(self): pass
179
+ def x_method__mutmut_orig(self): pass
180
+ '''
181
+ nodes = generated_mutations("example", source)
182
+ self.assertEqual(set(nodes), {"backend.example.x_top__mutmut_1", "backend.example.x_async__mutmut_2",
183
+ "backend.example.x_method__mutmut_3", "backend.example.x_async_method__mutmut_4"})
184
+ self.assertEqual(type(nodes["backend.example.x_async_method__mutmut_4"]).__name__, "AsyncFunctionDef")
185
+ with self.assertRaisesRegex(ValueError, "duplicate generated mutation"):
186
+ generated_mutations("example", source + "\ndef x_top__mutmut_1(): pass\n")
187
+
188
+ def test_mutation_inventory_detects_missing_async_outcomes(self):
189
+ nodes = generated_mutations("example", '''
190
+ class Example:
191
+ def x_Example_sync__mutmut_1(self): pass
192
+ async def x_Example_async__mutmut_1(self): pass
193
+ ''')
194
+ recorded = {"backend.example.x_Example_sync__mutmut_1": 1}
195
+ self.assertEqual(set(nodes) - set(recorded), {"backend.example.x_Example_async__mutmut_1"})
196
+
197
 
198
  if __name__ == "__main__":
199
  unittest.main()
tests/test_reader_index_contract.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure incremental Reader index: snapshot ownership, aliases and budgets."""
2
+ import unittest
3
+
4
+ from backend.reader_index import advance_build, new_build
5
+
6
+
7
+ class ReaderIndexTests(unittest.TestCase):
8
+ @staticmethod
9
+ def options(clock=None):
10
+ if clock is None:
11
+ # Preserve a fixed, pre-deadline time while bounding accidental
12
+ # non-advancing loops; each valid fixture has at most five rows.
13
+ calls = iter(range(16))
14
+
15
+ def clock():
16
+ next(calls)
17
+ return 0
18
+
19
+ return {"now": clock, "source_id": lambda url: "id:" + url,
20
+ "asset_key": lambda rec: rec["Repo"] + ":" + rec["File"],
21
+ "record_link": lambda rec: "canonical:" + rec["File"] + "." + rec["Extension"],
22
+ "dataset_url": lambda repo, path: repo + "/" + path,
23
+ "reader_extensions": frozenset({"pdf", "txt"})}
24
+
25
+ def test_batches_keep_snapshot_keys_ids_and_only_reader_repos(self):
26
+ records = [{"Repo": "VoiceOfML/A", "File": "book", "Extension": "pdf", "Folder": [], "_ext_lower": "pdf"},
27
+ {"Repo": "VoiceOfML/A", "File": "photo.jpg", "Extension": "jpg", "Folder": ["docs"],
28
+ "Link": "custom:image", "_ext_lower": "jpg"},
29
+ {"Repo": "VoiceOfML/B", "File": "note", "Extension": "txt", "Folder": [], "_ext_lower": "txt"}]
30
+ build = new_build(7, records)
31
+ self.assertIs(build["records"], records)
32
+ self.assertFalse(advance_build(build, 2, 10, **self.options()))
33
+ self.assertEqual(build["next"], 2)
34
+ self.assertEqual(build["indices"], [0])
35
+ self.assertEqual(build["repos"], {"VoiceOfML/A": [0]})
36
+ self.assertEqual(build["ids"], {"id:canonical:book.pdf": [0], "id:custom:image": [1]})
37
+ self.assertEqual(build["legacy_ids"], {"id:VoiceOfML/A/docs/photo.jpg": [1]})
38
+ self.assertTrue(advance_build(build, 2, 10, **self.options()))
39
+ self.assertEqual(build["indices"], [0, 2])
40
+ self.assertEqual(build["repos"], {"VoiceOfML/A": [0], "VoiceOfML/B": [2]})
41
+ self.assertEqual(build["keys"], {"VoiceOfML/A:book": 0, "VoiceOfML/A:photo.jpg": 1, "VoiceOfML/B:note": 2})
42
+ self.assertEqual(build["generation"], 7)
43
+
44
+ def test_repeated_batches_are_bounded_and_move_forward(self):
45
+ records = [{"Repo": "VoiceOfML/A", "File": str(i), "Extension": "pdf", "_ext_lower": "pdf"}
46
+ for i in range(3)]
47
+ build = new_build(1, records)
48
+ # A clock that advances every call bounds a broken loop without waiting
49
+ # for the mutation runner's timeout.
50
+ tick = iter(range(20))
51
+ self.assertFalse(advance_build(build, 2, 2, **self.options(lambda: next(tick))))
52
+ self.assertEqual(build["next"], 2)
53
+ self.assertEqual(build["indices"], [0, 1])
54
+ self.assertEqual(build["repos"], {"VoiceOfML/A": [0, 1]})
55
+
56
+ def test_missing_metadata_uses_empty_defaults_without_creating_aliases(self):
57
+ records = [{"File": "book", "Extension": "pdf", "_ext_lower": "pdf"},
58
+ {"Repo": "VoiceOfML/A", "Extension": "pdf", "_ext_lower": "pdf"},
59
+ {"Repo": "VoiceOfML/A", "File": "book", "_ext_lower": "pdf"},
60
+ {"Repo": "VoiceOfML/A", "File": "photo.jpg", "Extension": "jpg", "_ext_lower": "jpg"},
61
+ {"Repo": "VoiceOfML/A", "File": "other", "Extension": "pdf"}]
62
+ options = self.options()
63
+ options.update(asset_key=lambda rec: repr(sorted(rec.items())),
64
+ record_link=lambda rec: "url:" + rec.get("File", "") + "." + rec.get("Extension", ""),
65
+ reader_extensions=frozenset({"pdf", "XXXX"}))
66
+ build = new_build(0, records)
67
+ self.assertTrue(advance_build(build, len(records), 10, **options))
68
+ self.assertEqual(build["repos"][""], [0])
69
+ self.assertEqual(build["indices"], [0, 1, 2])
70
+ self.assertEqual(build["legacy_ids"], {"id:VoiceOfML/A/photo.jpg": [3]})
71
+
72
+ def test_legacy_alias_uses_original_record_for_computed_source(self):
73
+ record = {"Repo": "VoiceOfML/A", "File": "x.pdf", "Extension": "pdf", "Folder": []}
74
+ calls = []
75
+ options = self.options()
76
+ options["record_link"] = lambda rec: calls.append(rec) or "canonical"
77
+ build = new_build(0, [record])
78
+ self.assertTrue(advance_build(build, 1, 10, **options))
79
+ self.assertEqual(calls, [record, record])
80
+ self.assertEqual(build["legacy_ids"], {"id:VoiceOfML/A/x.pdf": [0]})
81
+
82
+ def test_alias_equality_limits_and_time_budget(self):
83
+ same = "VoiceOfML/A/docs/photo.jpg"
84
+ records = [{"Repo": "VoiceOfML/A", "File": "photo.jpg", "Extension": "jpg", "Folder": ["docs"],
85
+ "Link": same, "_ext_lower": "jpg"},
86
+ {"Repo": "VoiceOfML/A", "File": "x", "Extension": "pdf", "Folder": [], "_ext_lower": "pdf"}]
87
+ build = new_build(2, records)
88
+ self.assertFalse(advance_build(build, 0, 10, **self.options()))
89
+ self.assertEqual(build["next"], 0)
90
+ self.assertFalse(advance_build(build, 5, 10, **self.options(lambda: 10)))
91
+ self.assertEqual(build["next"], 1)
92
+ self.assertEqual(build["legacy_ids"], {})
93
+ self.assertTrue(advance_build(build, 5, 10, **self.options()))
94
+ self.assertEqual(build["indices"], [1])
95
+
96
+ def test_last_record_completes_even_when_deadline_is_reached(self):
97
+ record = {"Repo": "VoiceOfML/A", "File": "x", "Extension": "pdf", "_ext_lower": "pdf"}
98
+ build = new_build(5, [record])
99
+ self.assertTrue(advance_build(build, 1, 10, **self.options(lambda: 10)))
100
+ self.assertEqual(build["next"], 1)
101
+ self.assertEqual(build["indices"], [0])
102
+
103
+ def test_mapping_defaults_are_explicit_even_with_custom_fallbacks(self):
104
+ class FallbackRecord(dict):
105
+ def get(self, key, default=None):
106
+ if key not in self and default is None:
107
+ return {"File": "other.pdf", "Extension": "pdf", "_ext_lower": "pdf"}.get(key)
108
+ return super().get(key, default)
109
+
110
+ records = [FallbackRecord({"Repo": "VoiceOfML/A", "Extension": "pdf"}),
111
+ FallbackRecord({"Repo": "VoiceOfML/A", "File": "other.pdf"})]
112
+ options = self.options()
113
+ options.update(asset_key=lambda rec: str(len(rec)), record_link=lambda rec: "original",
114
+ reader_extensions=frozenset({"pdf"}))
115
+ build = new_build(0, records)
116
+ self.assertTrue(advance_build(build, 2, 10, **options))
117
+ self.assertEqual(build["indices"], [])
118
+ self.assertEqual(build["legacy_ids"], {})
119
+
120
+ def test_missing_file_and_extension_cannot_make_invented_legacy_alias(self):
121
+ records = [{"Repo": "VoiceOfML/A", "Extension": "XXXX"},
122
+ {"Repo": "VoiceOfML/A", "File": "file.XXXX"}]
123
+ options = self.options()
124
+ options.update(asset_key=lambda rec: repr(rec), record_link=lambda rec: "canonical")
125
+ build = new_build(0, records)
126
+ self.assertTrue(advance_build(build, 2, 10, **options))
127
+ self.assertEqual(build["legacy_ids"], {})
128
+ self.assertEqual(build["ids"], {"id:canonical": [0, 1]})
129
+
130
+ def test_mapping_cannot_invent_missing_filename_from_a_default(self):
131
+ class DefaultAwareRecord(dict):
132
+ def get(self, key, default=None):
133
+ if key == "File" and key not in self:
134
+ # An adapter may decorate a nonempty fallback filename.
135
+ return f"{default}.pdf" if default else default
136
+ return super().get(key, default)
137
+
138
+ record = DefaultAwareRecord({"Repo": "VoiceOfML/A", "Extension": "pdf"})
139
+ options = self.options()
140
+ options.update(asset_key=lambda _: "key", record_link=lambda _: "canonical")
141
+ build = new_build(0, [record])
142
+ self.assertTrue(advance_build(build, 1, 10, **options))
143
+ self.assertEqual(build["ids"], {"id:canonical": [0]})
144
+ self.assertEqual(build["legacy_ids"], {})
145
+
146
+
147
+ if __name__ == "__main__":
148
+ unittest.main()