diff --git a/tests/unit/python/utils/cache/test_files.py b/tests/unit/python/utils/cache/test_files.py index 3465e7a4eb..3fe77ee695 100644 --- a/tests/unit/python/utils/cache/test_files.py +++ b/tests/unit/python/utils/cache/test_files.py @@ -72,6 +72,21 @@ class TestReadText(_ProjectRootFixture, unittest.TestCase): with self.assertRaises(FileNotFoundError): read_text(str(self.root / "nope.txt")) + def test_file_above_the_cache_bound_is_never_cached(self) -> None: + path = _touch(self.root / "catalog.po", "first") + with patch.object(files_module, "READ_TEXT_CACHE_MAX_BYTES", 4): + self.assertEqual(read_text(str(path)), "first") + path.write_text("second", encoding="utf-8") + self.assertEqual(read_text(str(path)), "second") + self.assertEqual(files_module._read_cached.cache_info().currsize, 0) + + def test_file_at_the_cache_bound_stays_cached(self) -> None: + path = _touch(self.root / "a.txt", "four") + with patch.object(files_module, "READ_TEXT_CACHE_MAX_BYTES", 4): + self.assertEqual(read_text(str(path)), "four") + path.write_text("zero", encoding="utf-8") + self.assertEqual(read_text(str(path)), "four") + class TestIterProjectFiles(_ProjectRootFixture, unittest.TestCase): def setUp(self) -> None: diff --git a/utils/cache/files.py b/utils/cache/files.py index b63d906344..ba7965a49c 100644 --- a/utils/cache/files.py +++ b/utils/cache/files.py @@ -140,15 +140,42 @@ def iter_project_files( yield path +READ_TEXT_CACHE_MAX_BYTES = 1 << 20 + + +def _read(path: str) -> str: + with Path(path).open(encoding="utf-8") as f: + return f.read() + + @lru_cache(maxsize=8192) +def _read_cached(path: str) -> str: + return _read(path) + + def read_text(path: str) -> str: """Return the UTF-8 text content of a file; cached process-wide. - Raises OSError / UnicodeDecodeError unchanged — callers that scan arbitrary - files can wrap this in try/except if non-UTF-8 blobs may appear. + A file larger than ``READ_TEXT_CACHE_MAX_BYTES`` on disk is read again on + every call and never cached. The ``locale/*/LC_MESSAGES/docs.po`` + catalogs hold 1.2 GiB, which Python keeps as about 4 GiB of str, and a + whole-tree content scan pinned that in every pytest-xdist worker that + ran one until the 16 GiB CI runner swapped to death. + + Args: + path: absolute path of the file to read. + + Returns: + The decoded content of the file. + + Raises: + OSError: the file cannot be stat'ed or read. + UnicodeDecodeError: the file is not UTF-8; callers that scan + arbitrary files catch it when non-UTF-8 blobs may appear. """ - with Path(path).open(encoding="utf-8") as f: - return f.read() + if Path(path).stat().st_size > READ_TEXT_CACHE_MAX_BYTES: + return _read(path) + return _read_cached(path) def iter_project_files_with_content( @@ -261,6 +288,6 @@ def _reset() -> None: """ _all_project_files.cache_clear() _local_exclude_dirs.cache_clear() - read_text.cache_clear() + _read_cached.cache_clear() repository_files.cache_clear() untracked_files.cache_clear()