From 5b5545ba0ce34e8291254db972503a0a55e0b551 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 9 Sep 2026 13:16:50 -0400 Subject: [PATCH 1/2] feat(aggregator): opt-in temporary extraction for zipped search outputs (#1584) `Aggregator.from_directory` extracts every `.zip` it meets into a sibling directory beside the zip and leaves it there, so aggregating a results tree that holds only zips (an HPC run, or any run with `output: remove_files`) permanently doubles the disk and file count. On a three-result zip-only tree the scan grew the directory 1.85x in bytes and 10x in files. `unzip_temporary=True` extracts into a temporary directory instead, mirroring the scanned layout so same-named zips in different directories cannot collide. The scanned tree is left byte-identical. Every search output read out of the extraction holds a reference to it, so the files live exactly as long as something can still read them and are removed once the last such object is collected; `close()` and the context manager remove them eagerly. `TemporaryExtraction` uses `weakref.finalize` rather than `tempfile.TemporaryDirectory` because the latter emits a `ResourceWarning` whenever it is cleaned up implicitly, which is the normal path here. The default is unchanged: extraction beside the zip, skipped when the extracted directory already exists. That short-cut still wins in temporary mode, so a tree that is already unpacked is never re-extracted. The cost of the new mode is re-extracting on every call rather than once: 0.33s vs 0.04s for a 200-result tree, against ~45ms per result to parse samples. Reading members straight from the zip was assessed and not taken: ~20 path-based loader and enumeration call sites, plus lazy per-query re-reads that would re-open the archive repeatedly and regress the 2026-07 aggregator speed-up. Full PyAutoFit suite green: 2552 passed, 2 skipped. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01EwQS9x9Ls1NBUpbASL7n1s --- autofit/aggregator/aggregator.py | 139 ++++++++++++++++-- autofit/aggregator/search_output.py | 63 +++++++- .../aggregator/test_from_directory.py | 85 +++++++++++ 3 files changed, 275 insertions(+), 12 deletions(-) diff --git a/autofit/aggregator/aggregator.py b/autofit/aggregator/aggregator.py index 7258dbafb..1451a1587 100755 --- a/autofit/aggregator/aggregator.py +++ b/autofit/aggregator/aggregator.py @@ -22,7 +22,12 @@ from autonerves.test_mode import is_test_mode from .predicate import AttributePredicate -from .search_output import SearchOutput, GridSearchOutput, GridSearch +from .search_output import ( + SearchOutput, + GridSearchOutput, + GridSearch, + TemporaryExtraction, +) class AggregatorGroup: @@ -122,6 +127,7 @@ def __init__( self, search_outputs: List[SearchOutput], grid_search_outputs: List[GridSearchOutput], + temporary_directory: Optional[TemporaryExtraction] = None, ): """ Class to aggregate phase results for all subdirectories in a given directory. @@ -130,6 +136,11 @@ def __init__( ---------- search_outputs A list of search_outputs + temporary_directory + The temporary extraction zipped outputs were unpacked into, if + ``from_directory`` was called with ``unzip_temporary=True``. Held so + ``close`` can remove it eagerly; the search outputs keep it alive + regardless. """ if len(search_outputs) > 20: print( @@ -139,6 +150,9 @@ def __init__( ) self.search_outputs = search_outputs self.grid_search_outputs = grid_search_outputs + # Set here rather than lazily: ``__getattr__`` returns an + # ``AttributePredicate`` for any name it does not find. + self._temporary_directory = temporary_directory def grid_searches(self): """ @@ -162,6 +176,7 @@ def from_directory( directory: Union[str, os.PathLike], completed_only=False, reference: Optional[dict] = None, + unzip_temporary: bool = False, ) -> "Aggregator": """ Aggregate phase results for all subdirectories in a given directory. @@ -173,6 +188,10 @@ def from_directory( extracted directory already exists is skipped, so repeat calls do not pay the extraction cost again; delete the extracted directory to force re-extraction. + By default the extraction is written next to the zip and left there, which doubles the disk a results + tree occupies. Pass ``unzip_temporary=True`` to extract into a temporary directory instead, which is + removed once the aggregator and its search outputs are released (or immediately, via ``close``). + Parameters ---------- directory @@ -182,27 +201,62 @@ def from_directory( are included in the aggregator. reference A dictionary mapping paths to types to be used when loading models from disk. + unzip_temporary + If `True` zips are extracted into a temporary directory that is cleaned up automatically, + leaving the aggregated directory untouched. A zip that already has an extracted directory + beside it still uses that directory and is not extracted again. """ print("Aggregator loading search_outputs... could take some time.") - def scan(scan_directory): + temporary_directory = None + temporary_roots = [] + + def temporary_path(zip_path: Path, scan_root: Path) -> Path: + """ + Where to extract ``zip_path`` inside the shared temporary directory. + + The scanned layout is mirrored so that two zips of the same name in + different directories cannot collide. + """ + nonlocal temporary_directory + if temporary_directory is None: + temporary_directory = TemporaryExtraction() + relative = zip_path.parent.relative_to(scan_root) + return temporary_directory.path / relative / zip_path.stem + + def scan(scan_directory, extract_temporary=False, owner=None): + """ + Walk ``scan_directory``, extracting zips and collecting search outputs. + + ``extract_temporary`` sends extractions to the shared temporary + directory rather than beside the zip; ``owner`` is the temporary + extraction the outputs found here should keep alive. + """ + scan_directory = Path(scan_directory) search_outputs = [] grid_search_outputs = [] for root, dirs, filenames in os.walk(scan_directory, topdown=True): for filename in filenames: if filename.endswith(".zip"): + zip_path = Path(root) / filename extracted = Path(root) / filename[:-4] if extracted.exists(): continue + if extract_temporary: + extracted = temporary_path(zip_path, scan_directory) try: - with zipfile.ZipFile(Path(root) / filename, "r") as f: + with zipfile.ZipFile(zip_path, "r") as f: f.extractall(extracted) except zipfile.BadZipFile: raise zipfile.BadZipFile( f"File is not a zip file: \n " f"{root} \n" f"{filename}" ) - dirs.append(filename[:-4]) + if extract_temporary: + # Outside the tree being walked, so it is scanned separately. + temporary_roots.append(extracted) + else: + dirs.append(filename[:-4]) def should_add(): return not completed_only or ".completed" in filenames @@ -213,6 +267,7 @@ def should_add(): SearchOutput( Path(root), reference=reference, + temporary_directory=owner, ) ) if ".is_grid_search" in filenames: @@ -220,12 +275,35 @@ def should_add(): grid_search_outputs.append( GridSearchOutput( Path(root), + temporary_directory=owner, ) ) return search_outputs, grid_search_outputs - search_outputs, grid_search_outputs = scan(directory) + def scan_all(scan_directory): + """ + Scan a directory and then every temporary extraction it produced. + + Temporary extractions sit outside the walked tree, so each is scanned in + turn. Any zip nested inside one extracts beside itself, which is still + inside the temporary directory and removed with it. + """ + search_outputs, grid_search_outputs = scan( + scan_directory, + extract_temporary=unzip_temporary, + ) + while temporary_roots: + temporary_root = temporary_roots.pop() + extra_search_outputs, extra_grid_search_outputs = scan( + temporary_root, + owner=temporary_directory, + ) + search_outputs.extend(extra_search_outputs) + grid_search_outputs.extend(extra_grid_search_outputs) + return search_outputs, grid_search_outputs + + search_outputs, grid_search_outputs = scan_all(directory) # Under test mode the searches wrote their results beneath an inserted # ``test_mode`` segment (``output/test_mode/``) rather than the @@ -237,7 +315,7 @@ def should_add(): directory = Path(directory) test_mode_directory = directory.parent / "test_mode" / directory.name if test_mode_directory.exists(): - search_outputs, grid_search_outputs = scan(test_mode_directory) + search_outputs, grid_search_outputs = scan_all(test_mode_directory) if len(search_outputs) == 0: print(f"\nNo search_outputs found in {directory}\n") @@ -246,19 +324,62 @@ def should_add(): f"\n A total of {str(len(search_outputs))} search_outputs and results were found." ) - return cls(search_outputs, grid_search_outputs) + return cls( + search_outputs, + grid_search_outputs, + temporary_directory=temporary_directory, + ) - def add_directory(self, directory: Union[str, Path]): + def add_directory( + self, + directory: Union[str, Path], + unzip_temporary: bool = False, + ): """ Add a directory to the aggregator. + + Parameters + ---------- + directory + A directory searched recursively for search outputs. + unzip_temporary + If `True` zips are extracted into a temporary directory that is cleaned + up automatically, as in ``from_directory``. The added search outputs + keep that directory alive; ``close`` does not remove it. """ - aggregator = Aggregator.from_directory(directory) + aggregator = Aggregator.from_directory( + directory, + unzip_temporary=unzip_temporary, + ) self.search_outputs.extend(aggregator.search_outputs) self.grid_search_outputs.extend(aggregator.grid_search_outputs) + def close(self): + """ + Remove the temporary directory zipped outputs were extracted into, if there + is one, without waiting for garbage collection. + + Search outputs read out of it cannot be loaded afterwards. Only the + aggregator returned by ``from_directory`` holds the directory; one produced + by slicing or querying it does not, so ``close`` there does nothing. + """ + if self._temporary_directory is not None: + self._temporary_directory.cleanup() + self._temporary_directory = None + + def __enter__(self) -> "Aggregator": + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + def remove_unzipped(self): """ Removes the unzipped output directory for each phase. + + Only relevant to the default extraction mode, which unpacks each zip beside + itself and leaves it there. Outputs extracted with ``unzip_temporary=True`` + are cleaned up on their own. """ for phase in self.search_outputs: split_path = Path(phase.directory).parent diff --git a/autofit/aggregator/search_output.py b/autofit/aggregator/search_output.py index 293e66e9d..7f3e99f30 100644 --- a/autofit/aggregator/search_output.py +++ b/autofit/aggregator/search_output.py @@ -2,8 +2,11 @@ import json import logging import pickle +import tempfile +import weakref from abc import ABC from pathlib import Path +from shutil import rmtree from typing import Generator, Tuple, Optional, List, cast, Type import dill @@ -48,10 +51,56 @@ def _create_file_handle(*args, **kwargs): dill._dill._create_filehandle = _create_file_handle +class TemporaryExtraction: + """ + A temporary directory into which the aggregator extracts zipped search outputs. + + Every search output read out of the directory holds a reference to the + ``TemporaryExtraction`` that owns it, so the extracted files live exactly as + long as something still points at them and are removed once the last such + object is garbage collected. ``cleanup`` removes them eagerly. + + A ``weakref.finalize`` is used rather than ``tempfile.TemporaryDirectory`` + because the latter warns (``ResourceWarning``) whenever it is cleaned up + implicitly, and implicit cleanup is the normal path here. + """ + + def __init__(self, prefix: str = "autofit_aggregator_"): + self.path = Path(tempfile.mkdtemp(prefix=prefix)) + # The callback must not close over ``self`` or the object would never + # become unreachable; ``self.path`` is bound as an argument instead. + self._finalizer = weakref.finalize(self, rmtree, self.path, True) + + @property + def is_alive(self) -> bool: + """ + Whether the extracted files are still on disk. + """ + return self._finalizer.alive + + def cleanup(self): + """ + Remove the extracted files now, without waiting for garbage collection. + + Search outputs still pointing into the directory cannot be read afterwards. + """ + self._finalizer() + + class AbstractSearchOutput(ABC): - def __init__(self, directory: Path, reference: Optional[dict] = None): + def __init__( + self, + directory: Path, + reference: Optional[dict] = None, + temporary_directory: Optional[TemporaryExtraction] = None, + ): self.directory = directory self._reference = reference + # Keeps a temporary extraction alive for as long as this output can be + # read from it. ``None`` for outputs read from a real directory. + # Must be set here: ``__getattr__`` would otherwise try to load a + # pickle of this name from disk. + self._temporary_directory = temporary_directory @property def is_complete(self) -> bool: @@ -194,7 +243,12 @@ class SearchOutput(AbstractSearchOutput, fit_interface.Fit): is_grid_search = False - def __init__(self, directory: Path, reference: dict = None): + def __init__( + self, + directory: Path, + reference: dict = None, + temporary_directory: Optional[TemporaryExtraction] = None, + ): """ Represents the output of a single search. Comprises the ``files`` directory written by the search (including ``search.json``) and other dataset files. @@ -203,8 +257,11 @@ def __init__(self, directory: Path, reference: dict = None): ---------- directory The directory of the search + temporary_directory + The temporary extraction this output was read from, if any. Held so the + extracted files outlive the scan that produced them. """ - super().__init__(directory, reference) + super().__init__(directory, reference, temporary_directory) self.__search = None self.__model = None self._samples = None diff --git a/test_autofit/aggregator/test_from_directory.py b/test_autofit/aggregator/test_from_directory.py index 832761c00..33bc780aa 100644 --- a/test_autofit/aggregator/test_from_directory.py +++ b/test_autofit/aggregator/test_from_directory.py @@ -1,4 +1,5 @@ import json +import gc import shutil import zipfile from pathlib import Path @@ -48,6 +49,90 @@ def test_zip_not_re_extracted(zipped_directory): assert not (zipped_directory / "search_output" / ".completed").exists() +def test_zip_temporary_leaves_no_extracted_directory(zipped_directory): + aggregator = Aggregator.from_directory(zipped_directory, unzip_temporary=True) + + assert len(aggregator) == 1 + assert not (zipped_directory / "search_output").exists() + assert [path.name for path in zipped_directory.iterdir()] == ["search_output.zip"] + + +def test_zip_temporary_loads_the_same_outputs(zipped_directory, scan_directory): + temporary = Aggregator.from_directory(zipped_directory, unzip_temporary=True) + alongside = Aggregator.from_directory(scan_directory) + + assert len(temporary) == len(alongside) + assert {output.name for output in temporary[0].jsons} == { + output.name for output in alongside[0].jsons + } + + +def test_zip_temporary_removed_when_released(zipped_directory): + aggregator = Aggregator.from_directory(zipped_directory, unzip_temporary=True) + # Only the path is kept: holding the extraction itself would keep it alive. + path = aggregator[0]._temporary_directory.path + + assert path.exists() + + del aggregator + gc.collect() + + assert not path.exists() + + +def test_zip_temporary_outlives_the_aggregator(zipped_directory): + """ + A search output kept after the aggregator is dropped can still be read. + """ + aggregator = Aggregator.from_directory(zipped_directory, unzip_temporary=True) + search_output = aggregator[0] + + del aggregator + gc.collect() + + assert search_output._temporary_directory.is_alive + assert {output.name for output in search_output.jsons} == { + "directory.example", + "model", + "samples_info", + "search", + } + + +def test_zip_temporary_removed_on_close(zipped_directory): + with Aggregator.from_directory(zipped_directory, unzip_temporary=True) as aggregator: + path = aggregator[0]._temporary_directory.path + assert path.exists() + + assert not path.exists() + + +def test_zip_temporary_uses_an_existing_extracted_directory(zipped_directory): + Aggregator.from_directory(zipped_directory) + + aggregator = Aggregator.from_directory(zipped_directory, unzip_temporary=True) + + assert len(aggregator) == 1 + assert aggregator[0].directory == zipped_directory / "search_output" + assert aggregator[0]._temporary_directory is None + + +def test_zip_temporary_mirrors_the_scanned_layout(tmp_path): + source = Path(__file__).parent / "search_output" + for name in ("one", "two"): + directory = tmp_path / name + directory.mkdir() + with zipfile.ZipFile(directory / "search_output.zip", "w") as f: + for path in source.rglob("*"): + if path.is_file(): + f.write(path, path.relative_to(source)) + + aggregator = Aggregator.from_directory(tmp_path, unzip_temporary=True) + + assert len(aggregator) == 2 + assert len({output.directory for output in aggregator}) == 2 + + def test_outputs_by_suffix(scan_directory): search_output = SearchOutput(scan_directory / "search_output") From 57d838c3862de4483ab9e09c801324ab2aff2487 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 9 Sep 2026 13:20:24 -0400 Subject: [PATCH 2/2] test(aggregator): cover grid searches under temporary extraction (#1584) The grid-search branch of the scan gained the same ownership reference as the search-output branch, and nothing exercised it: the aggregator tests carried no `.is_grid_search` fixture at all. The assertion that matters is `children`. Pairing a grid search with its child searches goes through `is_relative_to` on their directories, which only holds if both were extracted into the same mirrored temporary tree; a flat or per-zip extraction would silently return a grid search with no children. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01EwQS9x9Ls1NBUpbASL7n1s --- .../aggregator/test_from_directory.py | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/test_autofit/aggregator/test_from_directory.py b/test_autofit/aggregator/test_from_directory.py index 33bc780aa..708e21ba1 100644 --- a/test_autofit/aggregator/test_from_directory.py +++ b/test_autofit/aggregator/test_from_directory.py @@ -133,6 +133,43 @@ def test_zip_temporary_mirrors_the_scanned_layout(tmp_path): assert len({output.directory for output in aggregator}) == 2 +@pytest.fixture(name="zipped_grid_search_directory") +def make_zipped_grid_search_directory(tmp_path): + """ + A grid search, with one child search, archived as a single zip. + """ + source = Path(__file__).parent / "search_output" + staging = tmp_path / "staging" + staging.mkdir() + shutil.copytree(source, staging / "child") + (staging / ".is_grid_search").write_text("my_unique_tag") + + with zipfile.ZipFile(tmp_path / "grid.zip", "w") as f: + for path in staging.rglob("*"): + if path.is_file(): + f.write(path, path.relative_to(staging)) + shutil.rmtree(staging) + return tmp_path + + +def test_zip_temporary_grid_search(zipped_grid_search_directory): + aggregator = Aggregator.from_directory( + zipped_grid_search_directory, + unzip_temporary=True, + ) + + assert len(aggregator.grid_search_outputs) == 1 + + grid_search = aggregator.grid_searches()[0] + + assert grid_search.unique_tag == "my_unique_tag" + # The child is paired with its grid search, which only holds if both were + # extracted into the same mirrored temporary tree. + assert len(grid_search.children) == 1 + assert aggregator.grid_search_outputs[0]._temporary_directory is not None + assert [path.name for path in zipped_grid_search_directory.iterdir()] == ["grid.zip"] + + def test_outputs_by_suffix(scan_directory): search_output = SearchOutput(scan_directory / "search_output")