From 97189e6116091cb97e563dcafa37f40023b104d1 Mon Sep 17 00:00:00 2001 From: eyal-benatav Date: Wed, 18 Nov 2026 17:53:50 +0200 Subject: [PATCH] Close the scan archive before releasing its buffer --- .../files_collector/models/in_memory_zip.py | 3 ++- .../cli/files_collector/test_in_memory_zip.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/cycode/cli/files_collector/models/in_memory_zip.py b/cycode/cli/files_collector/models/in_memory_zip.py index 9b6fe2ad..8e88e132 100644 --- a/cycode/cli/files_collector/models/in_memory_zip.py +++ b/cycode/cli/files_collector/models/in_memory_zip.py @@ -63,7 +63,8 @@ def close(self) -> None: self.zip.close() def cleanup(self) -> None: - """Release the buffer, deleting the spilled temp file if there is one.""" + """Close the archive and release the buffer, deleting the spilled temp file if there is one.""" + self.zip.close() self._buffer.close() def __enter__(self) -> 'InMemoryZip': # noqa: PYI034 # typing.Self needs Python 3.11 diff --git a/tests/cli/files_collector/test_in_memory_zip.py b/tests/cli/files_collector/test_in_memory_zip.py index f81acebb..2603306d 100644 --- a/tests/cli/files_collector/test_in_memory_zip.py +++ b/tests/cli/files_collector/test_in_memory_zip.py @@ -1,5 +1,7 @@ """Tests for InMemoryZip class, specifically for handling surrogate characters and encoding issues.""" +import gc +import sys import zipfile from io import BytesIO from pathlib import Path @@ -158,6 +160,22 @@ def test_cleanup_is_idempotent() -> None: zip_file.cleanup() +def test_cleanup_closes_an_archive_that_was_never_closed(monkeypatch: 'MonkeyPatch') -> None: + """A commit range with nothing to scan releases its placeholder archive without closing it first. + + ZipFile.__del__ must not then try to finalize the archive into the released buffer. + """ + unraisable_exceptions = [] + monkeypatch.setattr(sys, 'unraisablehook', unraisable_exceptions.append) + + zip_file = InMemoryZip() + zip_file.cleanup() + del zip_file + gc.collect() + + assert unraisable_exceptions == [] + + def test_used_as_a_context_manager() -> None: zip_file = InMemoryZip() with zip_file as managed: