vomebook commited on
Commit ·
dee4552
1
Parent(s): e2f469f
Gate Reader identity and cache core mutations
Browse filesFiles changed (5)
123456{ "tool": "mutmut 3.8.1", "source": "backend/cache_core.py", "source_sha256": "59e791dcc6f7283c8076b4e3b22fca020ac7b6cc913686f3f3aa2bf6ed19cc49", "equivalent": {}}12345678910111213141516171819{ "tool": "mutmut 3.8.1", "source": "backend/reader_identity.py", "source_sha256": "594876fdb822ee4be8fe13c0fbe4b260fa56615f4fe8bf789fdf583ba426472d", "equivalent": { "backend.reader_identity.x_canonical_reader_source_url__mutmut_15": { "sha256": "ab88a0f186c4be2baf6b5bc8aac012086ce9e911cebf478f1b3d249330e3e36a", "rationale": "The mutant adds only X characters to the literal membership string; X was already present. Consequently the set of accepted characters is identical." }, "backend.reader_identity.x_canonical_reader_source_url__mutmut_26": { "sha256": "0fd327c6ec031d778aa463633fd9cb70e60655fe05f6100374697684052791d1", "rationale": "urllib.parse.quote always leaves ASCII letters including X unescaped independently of safe. Adding X to safe changes no output, while / and % remain explicitly safe." }, "backend.reader_identity.x_reader_short_id__mutmut_6": { "sha256": "6ff9820d4470a0c12b16a1e43371287dfc511cb313cdcd959e66322aa076d5f4", "rationale": "Python codec names are case-insensitive; UTF-8 and utf-8 select the same encoder and error handling." } }}38 unmodified lines39404142434447 unmodified lines92939495969738 unmodified lines"search_matching": ("test_search_words_contract.py", MATCHING_TESTS, ["search_words.py"]),"data_formats": ("test_data_formats_contract.py", [], []),"search_indexes": ("test_native_search_indexes.py", [], []),}EMPTY_STATUSES = ("no_tests", "skipped", "suspicious", "timeout", "check_was_interrupted_by_user", "segfault")47 unmodified linesfor dependency in dependencies:shutil.copyfile(ROOT / "backend" / dependency, temp / "backend" / dependency)shutil.copyfile(test, temp / "tests" / test_name)(temp / "tests/__init__.py").write_text("")selections = ([f"tests/{test_name}::SearchWordsContractTests::{name}" for name in selected]if selected else [f"tests/{test_name}::PythonSearchIndexTests"38 unmodified lines394041424344454647 unmodified lines94959697989910010138 unmodified lines"search_matching": ("test_search_words_contract.py", MATCHING_TESTS, ["search_words.py"]),"data_formats": ("test_data_formats_contract.py", [], []),"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")47 unmodified linesfor dependency in dependencies:shutil.copyfile(ROOT / "backend" / dependency, temp / "backend" / dependency)shutil.copyfile(test, temp / "tests" / test_name)if module == "reader_identity":shutil.copyfile(ROOT / "tests/reader-contract-vectors.json", temp / "tests/reader-contract-vectors.json")(temp / "tests/__init__.py").write_text("")selections = ([f"tests/{test_name}::SearchWordsContractTests::{name}" for name in selected]if selected else [f"tests/{test_name}::PythonSearchIndexTests"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Response-cache lifetime, ordering and byte-budget contracts."""import unittestfrom unittest.mock import patch
from backend.cache_core import cached
class CacheCoreTests(unittest.TestCase): def test_hit_preserves_object_and_updates_lru_without_rebuilding(self): first, second = {"text": "书"}, {"text": "other"} store = {} with patch("backend.cache_core.time.monotonic", return_value=10): self.assertIs(cached(store, "a", lambda: first, 20, 5, max_entry_bytes=100, max_total_bytes=200), first) cached(store, "b", lambda: second, 20, 5, max_entry_bytes=100, max_total_bytes=200) with patch("backend.cache_core.time.monotonic", return_value=29): result = cached(store, "a", lambda: self.fail("cache hit rebuilt"), 20, 5, max_entry_bytes=100, max_total_bytes=200) self.assertIs(result, first) self.assertEqual(list(store), ["b", "a"]) self.assertEqual(store["a"][0], 10, "a hit must not extend the entry TTL")
def test_expiration_boundary_and_builder_failure_preserve_old_cache(self): store = {"old": (10, "old"), "other": (0, "expired")} with patch("backend.cache_core.time.monotonic", return_value=20): with self.assertRaisesRegex(RuntimeError, "build failed"): cached(store, "old", lambda: (_ for _ in ()).throw(RuntimeError("build failed")), 10, 5, max_entry_bytes=100, max_total_bytes=100) self.assertEqual(store, {"old": (10, "old"), "other": (0, "expired")}) self.assertEqual(cached(store, "old", lambda: "new", 10, 5, max_entry_bytes=100, max_total_bytes=100), "new") self.assertEqual(list(store), ["old"]) self.assertEqual(store["old"], (20, "new", len(b'"new"') + len(b"old")))
def test_entry_and_total_budgets_include_key_and_actual_utf8(self): store = {} with patch("backend.cache_core.time.monotonic", return_value=10): body = "书" size = len('"书"'.encode()) + len("键".encode()) self.assertEqual(cached(store, "键", lambda: body, 10, 5, max_entry_bytes=size, max_total_bytes=size), body) self.assertEqual(store["键"], (10, body, size)) cached(store, "oversize", lambda: "x" * 30, 10, 5, max_entry_bytes=size, max_total_bytes=100) self.assertNotIn("oversize", store) self.assertEqual(list(store), ["键"]) cached(store, "b", lambda: b"12", 10, 5, max_entry_bytes=100, max_total_bytes=2) self.assertNotIn("b", store) self.assertEqual(store, {}, "old entries are evicted before a value larger than total budget is bypassed")
def test_lru_count_and_legacy_two_field_entries_are_accounted(self): store = {"legacy": (10, "x" * 20)} with patch("backend.cache_core.time.monotonic", return_value=11): data = b"12345678901234567890" self.assertIs(cached(store, "fresh", lambda: data, 100, 5, max_entry_bytes=35, max_total_bytes=35), data) self.assertEqual(list(store), ["fresh"]) cached(store, "next", lambda: b"abc", 100, 1, max_entry_bytes=35, max_total_bytes=35) self.assertEqual(list(store), ["next"])
def test_rebuild_does_not_remove_an_unrelated_none_key(self): store = {None: (10, "keep", 4)} with patch("backend.cache_core.time.monotonic", return_value=11): cached(store, "new", lambda: b"x", 100, 5, max_entry_bytes=100, max_total_bytes=100) self.assertEqual(list(store), [None, "new"]) self.assertEqual(store[None], (10, "keep", 4))
def test_other_entry_expires_exactly_at_ttl(self): store = {"boundary": (10, "old", 5), "live": (11, "fresh", 5)} with patch("backend.cache_core.time.monotonic", return_value=20): cached(store, "new", lambda: b"x", 10, 5, max_entry_bytes=100, max_total_bytes=100) self.assertEqual(list(store), ["live", "new"])
def test_total_budget_allows_exact_fit_and_evicts_only_necessary_entries(self): store = {"a": (10, b"a", 5)} with patch("backend.cache_core.time.monotonic", return_value=11): cached(store, "b", lambda: b"1234", 100, 5, max_entry_bytes=100, max_total_bytes=10) self.assertEqual(list(store), ["a", "b"]) cached(store, "c", lambda: b"12", 100, 5, max_entry_bytes=100, max_total_bytes=10) self.assertEqual(list(store), ["b", "c"]) self.assertEqual(sum(entry[2] for entry in store.values()), 8)
def test_multiple_evictions_subtract_each_actual_entry_size(self): store = {"a": (10, b"a", 5), "b": (10, b"b", 5), "c": (10, b"c", 5)} with patch("backend.cache_core.time.monotonic", return_value=11): cached(store, "n", lambda: b"1234567", 100, 10, max_entry_bytes=20, max_total_bytes=13) self.assertEqual(list(store), ["c", "n"]) self.assertEqual(sum(entry[2] for entry in store.values()), 13)
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Reader source identity: path byte normalization and stable short IDs."""import jsonfrom pathlib import Pathimport randomimport reimport unittestfrom urllib.parse import quote
from backend import reader_identity
class ReaderIdentityTests(unittest.TestCase): def test_canonicalization_matches_independent_encoder(self): prefix = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/"
def reference(path): def replace(match): token = match.group() if re.fullmatch(r"%[0-9a-fA-F]{2}", token): char = chr(int(token[1:], 16)) return char if re.fullmatch(r"[A-Za-z0-9._~-]", char) else token.upper() return quote(token, safe="") return prefix + re.sub(r"%[0-9a-fA-F]{2}|[^A-Za-z0-9._~/-]", replace, path)
rng = random.Random(20260927) tokens = [chr(i) for i in range(128) if chr(i) not in "?#"] tokens += ["书", "é", "😀", "%2f", "%25", "%41", "%7e", "%G0", "%"] paths = [f"%{value:02x}" for value in range(256)] paths += [f"%{value:02X}" for value in range(256)] paths += ["".join(rng.choices(tokens, k=40)) for _ in range(256)] for path in paths: with self.subTest(path=path): self.assertEqual(reader_identity.canonical_reader_source_url(prefix + path), reference(path)) for value in ("https://example.com/%ab", prefix + "a?raw=%ab#fragment"): self.assertEqual(reader_identity.canonical_reader_source_url(value), value)
def test_cross_site_vectors_and_base36(self): for value, expected in ((0, "0"), (35, "z"), (36, "10"), (72, "20"), (1296, "100"), (2**64 - 1, "3w5e11264sgsf")): self.assertEqual(reader_identity._base36(value), expected) vectors = json.loads(Path(__file__).with_name("reader-contract-vectors.json").read_text()) for value, expected in vectors["ids"]: self.assertEqual(reader_identity.reader_short_id(value), expected) prefix = "https://huggingface.co/datasets/VoiceOfML/VOMEBOOK/resolve/main/" for value, expected in vectors["canonicalPaths"]: self.assertEqual(reader_identity.canonical_reader_source_url(prefix + value), prefix + expected) self.assertEqual(reader_identity.reader_short_id(prefix + value), reader_identity.reader_short_id(prefix + expected)) self.assertEqual(reader_identity.reader_short_id(prefix + vectors["reportedBook"]["path"]), vectors["reportedBook"]["id"])
if __name__ == "__main__": unittest.main()mutation-equivalent-cache-core.jsonAdded+6
mutation-equivalent-reader-identity.jsonAdded+19
scripts/check_search_words_mutation.py+4
tests/test_cache_core_contract.pyAdded+90
tests/test_reader_identity_contract.pyAdded+54