vomebook commited on
Commit ·
3c9cfda
1
Parent(s): c4bced1
Gate incremental Reader index mutations
Browse filesFiles changed (4)
1234567891011121314151617181920212223{ "tool": "mutmut 3.8.1", "source": "backend/reader_index.py", "source_sha256": "902ac199cc253397475e6fef002b9e718e7b7b92d312847d1bbdd702eb197308", "equivalent": { "backend.reader_index.x_advance_build__mutmut_32": { "sha256": "10641363a41f95af50a475e53becf474d745d68f583593978af469471d750006", "rationale": "typing.cast returns the current URL unchanged; replacing the type argument str with None does not affect source ID lookup or publication." }, "backend.reader_index.x_advance_build__mutmut_91": { "sha256": "c230d4a9712f56f289f0514c83f6dea4c5be77aab117b985af023d6e3af8cb73", "rationale": "typing.cast returns the folder list unchanged; replacing list[object] with None does not affect the list validation or alias eligibility." }, "backend.reader_index.x_advance_build__mutmut_98": { "sha256": "ea2c50f7c0f50d328ca21ff4701ce56d4800223decedd7038b5c294427b948fd", "rationale": "typing.cast returns the folder list unchanged; replacing list[str] with None does not affect the joined legacy path." }, "backend.reader_index.x_advance_build__mutmut_140": { "sha256": "68ba945e857c5ab1086218cd3928c4a6ce285e212cb9d1a3ce410f0749f36e81", "rationale": "typing.cast returns the repository unchanged; replacing str with None does not affect the repository index key." } }}40 unmodified lines4142434445464748495062 unmodified lines11311411511611711811912012112212312440 unmodified lines"search_indexes": ("test_native_search_indexes.py", [], []),"reader_identity": ("test_reader_identity_contract.py", [], []),"cache_core": ("test_cache_core_contract.py", [], []),}EMPTY_STATUSES = ("no_tests", "skipped", "suspicious", "timeout", "check_was_interrupted_by_user", "segfault")def mutation_errors(stats: dict[str, int], outcomes: dict[str, int],current_hashes: dict[str, str], reviewed: dict[str, dict[str, str]]) -> list[str]:errors: list[str] = []62 unmodified linesstats = json.loads((temp / "mutants/mutmut-cicd-stats.json").read_text())meta = json.loads((temp / "mutants/backend" / f"{module}.py.meta").read_text())generated = (temp / "mutants/backend" / f"{module}.py").read_text()functions = {node.name: node for node in ast.parse(generated).body if isinstance(node, ast.FunctionDef)}generated_keys = {f"backend.{module}.{name}" for name in functions if re.search(r"__mutmut_\d+$", name)}hashes = {}for key, code in meta["exit_code_by_key"].items():if code == 0:segment = ast.get_source_segment(generated, functions[key.rsplit(".", 1)[-1]])if segment is None:raise RuntimeError(f"missing generated source for {key}")hashes[key] = hashlib.sha256(segment.encode()).hexdigest()40 unmodified lines414243444546474849505152535455565758596061626362 unmodified lines12612712812913013113213313413513613740 unmodified lines"search_indexes": ("test_native_search_indexes.py", [], []),"reader_identity": ("test_reader_identity_contract.py", [], []),"cache_core": ("test_cache_core_contract.py", [], []),"reader_index": ("test_reader_index_contract.py", [], []),}EMPTY_STATUSES = ("no_tests", "skipped", "suspicious", "timeout", "check_was_interrupted_by_user", "segfault")def generated_mutations(module: str, generated: str) -> dict[str, ast.FunctionDef | ast.AsyncFunctionDef]:"""Inventory generated functions, including async methods inside classes."""result: dict[str, ast.FunctionDef | ast.AsyncFunctionDef] = {}for node in ast.walk(ast.parse(generated)):if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and re.search(r"__mutmut_\d+$", node.name):key = f"backend.{module}.{node.name}"if key in result:raise ValueError(f"duplicate generated mutation: {key}")result[key] = nodereturn resultdef mutation_errors(stats: dict[str, int], outcomes: dict[str, int],current_hashes: dict[str, str], reviewed: dict[str, dict[str, str]]) -> list[str]:errors: list[str] = []62 unmodified linesstats = json.loads((temp / "mutants/mutmut-cicd-stats.json").read_text())meta = json.loads((temp / "mutants/backend" / f"{module}.py.meta").read_text())generated = (temp / "mutants/backend" / f"{module}.py").read_text()functions = generated_mutations(module, generated)generated_keys = set(functions)hashes = {}for key, code in meta["exit_code_by_key"].items():if code == 0 and key in functions:segment = ast.get_source_segment(generated, functions[key])if segment is None:raise RuntimeError(f"missing generated source for {key}")hashes[key] = hashlib.sha256(segment.encode()).hexdigest()
4 unmodified lines567891011157 unmodified lines1691701711721731744 unmodified linesimport unittestfrom scripts.check_backend_coverage import coverage_errorsfrom scripts.check_search_words_mutation import EMPTY_STATUSES, mutation_errorsfrom scripts.check_strict_inventory import inventory_errors157 unmodified linesself.assertIn("mutation statistics are missing or invalid",mutation_errors(missing_status, {"a": 1}, {}, {}))if __name__ == "__main__":unittest.main()4 unmodified lines567891011157 unmodified lines1691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981994 unmodified linesimport unittestfrom scripts.check_backend_coverage import coverage_errorsfrom scripts.check_search_words_mutation import EMPTY_STATUSES, generated_mutations, mutation_errorsfrom scripts.check_strict_inventory import inventory_errors157 unmodified linesself.assertIn("mutation statistics are missing or invalid",mutation_errors(missing_status, {"a": 1}, {}, {}))def test_mutation_inventory_includes_async_and_class_methods(self):source = '''def x_top__mutmut_1(): passasync def x_async__mutmut_2(): passclass Example:def x_method__mutmut_3(self): passasync def x_async_method__mutmut_4(self): passdef x_method__mutmut_orig(self): pass'''nodes = generated_mutations("example", source)self.assertEqual(set(nodes), {"backend.example.x_top__mutmut_1", "backend.example.x_async__mutmut_2","backend.example.x_method__mutmut_3", "backend.example.x_async_method__mutmut_4"})self.assertEqual(type(nodes["backend.example.x_async_method__mutmut_4"]).__name__, "AsyncFunctionDef")with self.assertRaisesRegex(ValueError, "duplicate generated mutation"):generated_mutations("example", source + "\ndef x_top__mutmut_1(): pass\n")def test_mutation_inventory_detects_missing_async_outcomes(self):nodes = generated_mutations("example", '''class Example:def x_Example_sync__mutmut_1(self): passasync def x_Example_async__mutmut_1(self): pass''')recorded = {"backend.example.x_Example_sync__mutmut_1": 1}self.assertEqual(set(nodes) - set(recorded), {"backend.example.x_Example_async__mutmut_1"})if __name__ == "__main__":unittest.main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Pure incremental Reader index: snapshot ownership, aliases and budgets."""import unittest
from backend.reader_index import advance_build, new_build
class ReaderIndexTests(unittest.TestCase): @staticmethod def options(clock=None): if clock is None: # Preserve a fixed, pre-deadline time while bounding accidental # non-advancing loops; each valid fixture has at most five rows. calls = iter(range(16))
def clock(): next(calls) return 0
return {"now": clock, "source_id": lambda url: "id:" + url, "asset_key": lambda rec: rec["Repo"] + ":" + rec["File"], "record_link": lambda rec: "canonical:" + rec["File"] + "." + rec["Extension"], "dataset_url": lambda repo, path: repo + "/" + path, "reader_extensions": frozenset({"pdf", "txt"})}
def test_batches_keep_snapshot_keys_ids_and_only_reader_repos(self): records = [{"Repo": "VoiceOfML/A", "File": "book", "Extension": "pdf", "Folder": [], "_ext_lower": "pdf"}, {"Repo": "VoiceOfML/A", "File": "photo.jpg", "Extension": "jpg", "Folder": ["docs"], "Link": "custom:image", "_ext_lower": "jpg"}, {"Repo": "VoiceOfML/B", "File": "note", "Extension": "txt", "Folder": [], "_ext_lower": "txt"}] build = new_build(7, records) self.assertIs(build["records"], records) self.assertFalse(advance_build(build, 2, 10, **self.options())) self.assertEqual(build["next"], 2) self.assertEqual(build["indices"], [0]) self.assertEqual(build["repos"], {"VoiceOfML/A": [0]}) self.assertEqual(build["ids"], {"id:canonical:book.pdf": [0], "id:custom:image": [1]}) self.assertEqual(build["legacy_ids"], {"id:VoiceOfML/A/docs/photo.jpg": [1]}) self.assertTrue(advance_build(build, 2, 10, **self.options())) self.assertEqual(build["indices"], [0, 2]) self.assertEqual(build["repos"], {"VoiceOfML/A": [0], "VoiceOfML/B": [2]}) self.assertEqual(build["keys"], {"VoiceOfML/A:book": 0, "VoiceOfML/A:photo.jpg": 1, "VoiceOfML/B:note": 2}) self.assertEqual(build["generation"], 7)
def test_repeated_batches_are_bounded_and_move_forward(self): records = [{"Repo": "VoiceOfML/A", "File": str(i), "Extension": "pdf", "_ext_lower": "pdf"} for i in range(3)] build = new_build(1, records) # A clock that advances every call bounds a broken loop without waiting # for the mutation runner's timeout. tick = iter(range(20)) self.assertFalse(advance_build(build, 2, 2, **self.options(lambda: next(tick)))) self.assertEqual(build["next"], 2) self.assertEqual(build["indices"], [0, 1]) self.assertEqual(build["repos"], {"VoiceOfML/A": [0, 1]})
def test_missing_metadata_uses_empty_defaults_without_creating_aliases(self): records = [{"File": "book", "Extension": "pdf", "_ext_lower": "pdf"}, {"Repo": "VoiceOfML/A", "Extension": "pdf", "_ext_lower": "pdf"}, {"Repo": "VoiceOfML/A", "File": "book", "_ext_lower": "pdf"}, {"Repo": "VoiceOfML/A", "File": "photo.jpg", "Extension": "jpg", "_ext_lower": "jpg"}, {"Repo": "VoiceOfML/A", "File": "other", "Extension": "pdf"}] options = self.options() options.update(asset_key=lambda rec: repr(sorted(rec.items())), record_link=lambda rec: "url:" + rec.get("File", "") + "." + rec.get("Extension", ""), reader_extensions=frozenset({"pdf", "XXXX"})) build = new_build(0, records) self.assertTrue(advance_build(build, len(records), 10, **options)) self.assertEqual(build["repos"][""], [0]) self.assertEqual(build["indices"], [0, 1, 2]) self.assertEqual(build["legacy_ids"], {"id:VoiceOfML/A/photo.jpg": [3]})
def test_legacy_alias_uses_original_record_for_computed_source(self): record = {"Repo": "VoiceOfML/A", "File": "x.pdf", "Extension": "pdf", "Folder": []} calls = [] options = self.options() options["record_link"] = lambda rec: calls.append(rec) or "canonical" build = new_build(0, [record]) self.assertTrue(advance_build(build, 1, 10, **options)) self.assertEqual(calls, [record, record]) self.assertEqual(build["legacy_ids"], {"id:VoiceOfML/A/x.pdf": [0]})
def test_alias_equality_limits_and_time_budget(self): same = "VoiceOfML/A/docs/photo.jpg" records = [{"Repo": "VoiceOfML/A", "File": "photo.jpg", "Extension": "jpg", "Folder": ["docs"], "Link": same, "_ext_lower": "jpg"}, {"Repo": "VoiceOfML/A", "File": "x", "Extension": "pdf", "Folder": [], "_ext_lower": "pdf"}] build = new_build(2, records) self.assertFalse(advance_build(build, 0, 10, **self.options())) self.assertEqual(build["next"], 0) self.assertFalse(advance_build(build, 5, 10, **self.options(lambda: 10))) self.assertEqual(build["next"], 1) self.assertEqual(build["legacy_ids"], {}) self.assertTrue(advance_build(build, 5, 10, **self.options())) self.assertEqual(build["indices"], [1])
def test_last_record_completes_even_when_deadline_is_reached(self): record = {"Repo": "VoiceOfML/A", "File": "x", "Extension": "pdf", "_ext_lower": "pdf"} build = new_build(5, [record]) self.assertTrue(advance_build(build, 1, 10, **self.options(lambda: 10))) self.assertEqual(build["next"], 1) self.assertEqual(build["indices"], [0])
def test_mapping_defaults_are_explicit_even_with_custom_fallbacks(self): class FallbackRecord(dict): def get(self, key, default=None): if key not in self and default is None: return {"File": "other.pdf", "Extension": "pdf", "_ext_lower": "pdf"}.get(key) return super().get(key, default)
records = [FallbackRecord({"Repo": "VoiceOfML/A", "Extension": "pdf"}), FallbackRecord({"Repo": "VoiceOfML/A", "File": "other.pdf"})] options = self.options() options.update(asset_key=lambda rec: str(len(rec)), record_link=lambda rec: "original", reader_extensions=frozenset({"pdf"})) build = new_build(0, records) self.assertTrue(advance_build(build, 2, 10, **options)) self.assertEqual(build["indices"], []) self.assertEqual(build["legacy_ids"], {})
def test_missing_file_and_extension_cannot_make_invented_legacy_alias(self): records = [{"Repo": "VoiceOfML/A", "Extension": "XXXX"}, {"Repo": "VoiceOfML/A", "File": "file.XXXX"}] options = self.options() options.update(asset_key=lambda rec: repr(rec), record_link=lambda rec: "canonical") build = new_build(0, records) self.assertTrue(advance_build(build, 2, 10, **options)) self.assertEqual(build["legacy_ids"], {}) self.assertEqual(build["ids"], {"id:canonical": [0, 1]})
def test_mapping_cannot_invent_missing_filename_from_a_default(self): class DefaultAwareRecord(dict): def get(self, key, default=None): if key == "File" and key not in self: # An adapter may decorate a nonempty fallback filename. return f"{default}.pdf" if default else default return super().get(key, default)
record = DefaultAwareRecord({"Repo": "VoiceOfML/A", "Extension": "pdf"}) options = self.options() options.update(asset_key=lambda _: "key", record_link=lambda _: "canonical") build = new_build(0, [record]) self.assertTrue(advance_build(build, 1, 10, **options)) self.assertEqual(build["ids"], {"id:canonical": [0]}) self.assertEqual(build["legacy_ids"], {})
if __name__ == "__main__": unittest.main()mutation-equivalent-reader-index.jsonAdded+23
scripts/check_search_words_mutation.py+17-4
tests/test_quality_inventory.py+26-1
tests/test_reader_index_contract.pyAdded+148