From daa34961cb70cbcf74f1176a4f0db484f2b7d82c Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:32:06 -0800 Subject: [PATCH] Chore: compare export JSON files in chunks instead of reading them into memory --- src/documents/export/sinks.py | 25 +++++--- src/documents/tests/export/test_sinks.py | 78 ++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 9 deletions(-) diff --git a/src/documents/export/sinks.py b/src/documents/export/sinks.py index bc605d1bf..1660473ed 100644 --- a/src/documents/export/sinks.py +++ b/src/documents/export/sinks.py @@ -1,6 +1,7 @@ from __future__ import annotations import abc +import filecmp import hashlib import json import os @@ -166,11 +167,18 @@ class DirectoryExportSink(ExportSink): @staticmethod def _content_unchanged(target: Path, new_bytes: bytes) -> bool: - """True if ``target`` already holds byte-identical content (BLAKE2b).""" - return ( - hashlib.blake2b(target.read_bytes()).hexdigest() - == hashlib.blake2b(new_bytes).hexdigest() - ) + """ + True if ``target`` already holds byte-identical content (BLAKE2b). + + The existing file is hashed in chunks rather than read into memory. + """ + if target.stat().st_size != len(new_bytes): + return False + with target.open("rb") as handle: + return ( + hashlib.file_digest(handle, "blake2b").hexdigest() + == hashlib.blake2b(new_bytes).hexdigest() + ) def add_json(self, content: list | dict, arcname: str) -> None: target = (self._target / arcname).resolve() @@ -214,10 +222,9 @@ class DirectoryExportSink(ExportSink): def _commit_streamed_file(self, target: Path, tmp: Path) -> None: if target in self._snapshot: self._snapshot.discard(target) - if self._compare_json and self._content_unchanged( - target, - tmp.read_bytes(), - ): + # A streamed manifest can be very large, so compare the two files + # in chunks instead of reading them into memory + if self._compare_json and filecmp.cmp(target, tmp, shallow=False): tmp.unlink() return tmp.rename(target) diff --git a/src/documents/tests/export/test_sinks.py b/src/documents/tests/export/test_sinks.py index 5c54051b9..15861df46 100644 --- a/src/documents/tests/export/test_sinks.py +++ b/src/documents/tests/export/test_sinks.py @@ -91,6 +91,84 @@ class TestDirectoryExportSink: writer.close() assert json.loads((target / "manifest.json").read_text()) == [{"pk": 1}] + @pytest.mark.parametrize( + ("existing", "unchanged"), + [ + pytest.param(_dumps({"version": "x"}), True, id="identical"), + pytest.param(_dumps({"version": "y"}), False, id="same-size-different"), + ], + ) + def test_add_json_compare_json( + self, + tmp_path: Path, + *, + existing: str, + unchanged: bool, + ) -> None: + target: Path = tmp_path / "out" + target.mkdir() + (target / "metadata.json").write_text(existing) + os.utime(target / "metadata.json", (1, 1)) + with DirectoryExportSink( + target, + compare_checksums=False, + compare_json=True, + delete=False, + ) as sink: + sink.add_json({"version": "x"}, "metadata.json") + assert json.loads((target / "metadata.json").read_text()) == ( + json.loads(existing) if unchanged else {"version": "x"} + ) + # An unchanged file is not rewritten, so its mtime is left alone + assert ((target / "metadata.json").stat().st_mtime == 1) is unchanged + + @pytest.mark.parametrize( + ("existing", "unchanged"), + [ + pytest.param([{"pk": 1}], True, id="identical"), + pytest.param([{"pk": 2}], False, id="changed"), + ], + ) + def test_stream_compare_json( + self, + tmp_path: Path, + *, + existing: list[dict], + unchanged: bool, + ) -> None: + target: Path = tmp_path / "out" + target.mkdir() + # Write the existing manifest the same way the sink does + with DirectoryExportSink( + target, + compare_checksums=False, + compare_json=False, + delete=False, + ) as sink: + with sink.stream("manifest.json") as handle: + writer: StreamingManifestWriter = StreamingManifestWriter(handle) + for record in existing: + writer.write_record(record) + writer.close() + os.utime(target / "manifest.json", (1, 1)) + + with DirectoryExportSink( + target, + compare_checksums=False, + compare_json=True, + delete=False, + ) as sink: + with sink.stream("manifest.json") as handle: + writer = StreamingManifestWriter(handle) + writer.write_record({"pk": 1}) + writer.close() + + assert json.loads((target / "manifest.json").read_text()) == ( + existing if unchanged else [{"pk": 1}] + ) + assert ((target / "manifest.json").stat().st_mtime == 1) is unchanged + assert not (target / "manifest.json.tmp").exists() + def test_add_file_skips_when_size_and_mtime_match( self, tmp_path: Path,