diff --git a/autofit/aggregator/aggregator.py b/autofit/aggregator/aggregator.py index 1451a1587..77144dc9d 100755 --- a/autofit/aggregator/aggregator.py +++ b/autofit/aggregator/aggregator.py @@ -12,6 +12,7 @@ ./aggregator.py ../output pipeline=data_mass_x1_source_x1_positions """ +import logging import os import zipfile from collections import defaultdict @@ -29,6 +30,8 @@ TemporaryExtraction, ) +logger = logging.getLogger(__name__) + class AggregatorGroup: def __init__(self, groups: ["AggregatorGroup"]): @@ -203,13 +206,21 @@ def from_directory( 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. + leaving the aggregated directory untouched. A zip whose extracted directory already sits + beside it and carries a ``.completed`` file still uses that directory and is not extracted + again; one whose sibling directory has no ``.completed`` file is extracted, because such a + directory is written after the search was archived and does not stand for the search. + + Returns + ------- + An aggregator whose search outputs are ordered by path, so that the same results tree gives + the same order on every machine regardless of the filesystem's directory-entry order. """ print("Aggregator loading search_outputs... could take some time.") temporary_directory = None temporary_roots = [] + incomplete_count = 0 def temporary_path(zip_path: Path, scan_root: Path) -> Path: """ @@ -236,13 +247,31 @@ def scan(scan_directory, extract_temporary=False, owner=None): search_outputs = [] grid_search_outputs = [] + nonlocal incomplete_count + 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 + sibling = Path(root) / filename[:-4] + extracted = sibling + if sibling.exists(): + if (sibling / ".completed").exists(): + continue + # A directory beside the zip that carries no + # ``.completed`` is not the extraction of a finished + # search: post-completion writers (cache artifacts + # derived from a finished result) recreate + # ``/files/`` after the real directory was + # zipped and removed. Preferring it over the zip + # silently loses the search under ``completed_only``, + # so the zip wins and its contents are authoritative. + logger.warning( + f"Aggregator: {sibling} has no .completed file but " + f"{zip_path.name} does; the zip was used. The " + f"directory holds files written after the search " + f"was archived." + ) if extract_temporary: extracted = temporary_path(zip_path, scan_directory) try: @@ -250,12 +279,19 @@ def scan(scan_directory, extract_temporary=False, owner=None): f.extractall(extracted) except zipfile.BadZipFile: raise zipfile.BadZipFile( - f"File is not a zip file: \n " f"{root} \n" f"{filename}" + f"File is not a zip file: \n " + f"{root} \n" + f"{filename}" ) if extract_temporary: # Outside the tree being walked, so it is scanned separately. temporary_roots.append(extracted) - else: + if filename[:-4] in dirs: + # The incomplete sibling is superseded by the + # temporary extraction; walking it too would + # yield the same search a second time. + dirs.remove(filename[:-4]) + elif filename[:-4] not in dirs: dirs.append(filename[:-4]) def should_add(): @@ -270,6 +306,8 @@ def should_add(): temporary_directory=owner, ) ) + else: + incomplete_count += 1 if ".is_grid_search" in filenames: if should_add(): grid_search_outputs.append( @@ -288,6 +326,16 @@ def scan_all(scan_directory): 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. + + The collected outputs are sorted by path before they are returned. + ``os.walk`` yields directory entries in whatever order the filesystem + reports — hash order on ext4, insertion order on tmpfs — so without + this an aggregator's outputs come back in a machine-dependent order, + and anything that pairs a row to an output by index (the summary CSV + writers, ``add_label_column``) pairs them differently on different + machines. The sort is applied to the collected lists rather than to + ``dirs`` inside the walk because the temporary extractions are + scanned separately and so never pass through that walk. """ search_outputs, grid_search_outputs = scan( scan_directory, @@ -301,6 +349,10 @@ def scan_all(scan_directory): ) search_outputs.extend(extra_search_outputs) grid_search_outputs.extend(extra_grid_search_outputs) + + search_outputs.sort(key=lambda output: str(output.directory)) + grid_search_outputs.sort(key=lambda output: str(output.directory)) + return search_outputs, grid_search_outputs search_outputs, grid_search_outputs = scan_all(directory) @@ -315,6 +367,7 @@ def scan_all(scan_directory): directory = Path(directory) test_mode_directory = directory.parent / "test_mode" / directory.name if test_mode_directory.exists(): + incomplete_count = 0 search_outputs, grid_search_outputs = scan_all(test_mode_directory) if len(search_outputs) == 0: @@ -324,6 +377,15 @@ def scan_all(scan_directory): f"\n A total of {str(len(search_outputs))} search_outputs and results were found." ) + # A search dropped for having no ``.completed`` file is invisible in the + # count above, so a run that aggregates a fraction of its searches looks + # like a complete one. Say how many were left out. + if completed_only and incomplete_count > 0: + print( + f" {incomplete_count} further search_outputs were excluded because " + f"they have no .completed file." + ) + return cls( search_outputs, grid_search_outputs, diff --git a/autofit/non_linear/paths/abstract.py b/autofit/non_linear/paths/abstract.py index 7764724c9..958842d82 100644 --- a/autofit/non_linear/paths/abstract.py +++ b/autofit/non_linear/paths/abstract.py @@ -397,6 +397,17 @@ def preserve_in_zip(self, file_path): that was invalidated and recomputed — it is replaced, otherwise the stale copy would come back at the next ``restore()``. + Under ``remove_files`` the zip is the **only** store for a search: + the output directory is deleted once the search is archived, so a + loose copy left beside the zip is not a second home for the file but + a directory that should not exist. It shadows the zip for + ``Aggregator.from_directory``, which then sees a search output with + no ``.completed`` file. The loose copy is therefore deleted once the + member is in the archive, along with any parent directory that + emptied as a result, and the cache it holds is recomputed the next + time it is asked for. With ``remove_files`` unset the output + directory is the primary store and the loose copy stays. + Parameters ---------- file_path @@ -406,23 +417,69 @@ def preserve_in_zip(self, file_path): if not Path(self._zip_path).exists(): return - arcname = str(Path(file_path).relative_to(self.output_path)) + file_path = Path(file_path) + arcname = str(file_path.relative_to(self.output_path)) + + replace = False with zipfile.ZipFile(self._zip_path, "a") as f: try: info = f.getinfo(arcname) except KeyError: f.write(file_path, arcname) - return + info = None - if _matches_archived(info, file_path): - return + if info is not None and not _matches_archived(info, file_path): + replace = True - _replace_zip_member( - zip_path=self._zip_path, - arcname=arcname, - file_path=file_path, - ) + if replace: + _replace_zip_member( + zip_path=self._zip_path, + arcname=arcname, + file_path=file_path, + ) + + if self.remove_files: + self._remove_preserved_copy(file_path) + + def _remove_preserved_copy(self, file_path: Path): + """ + Delete a file that has just been written into the search's zip, and any + directory between it and ``output_path`` that the deletion emptied. + + Called only under ``remove_files``, where the zip is the search's only + store; see ``preserve_in_zip``. + + Parameters + ---------- + file_path + Absolute path of the loose file, which lives under ``output_path``. + """ + output_path = Path(self.output_path) + + try: + file_path.unlink() + except FileNotFoundError: + return + except OSError as e: + logger.debug(f"Could not remove the preserved copy at {file_path}: {e}") + return + + directory = file_path.parent + while True: + try: + directory.relative_to(output_path) + except ValueError: + # Walked above the search's own output directory. + return + try: + directory.rmdir() + except OSError: + # Not empty, or gone already — nothing further to prune. + return + if directory == output_path: + return + directory = directory.parent def restore(self): """ diff --git a/test_autofit/aggregator/test_from_directory.py b/test_autofit/aggregator/test_from_directory.py index 708e21ba1..5e87b9d2f 100644 --- a/test_autofit/aggregator/test_from_directory.py +++ b/test_autofit/aggregator/test_from_directory.py @@ -1,5 +1,6 @@ import json import gc +import os import shutil import zipfile from pathlib import Path @@ -33,6 +34,33 @@ def test_from_directory(scan_directory): assert len(aggregator) == 1 +def test_search_outputs_are_sorted_by_path(tmp_path, monkeypatch): + """ + ``os.walk`` yields directory entries in whatever order the filesystem + reports — hash order on ext4, insertion order on tmpfs — so the aggregated + outputs must be sorted before they are returned. Without the sort the order + is machine-dependent, and everything that pairs a row to an output by index + (the summary CSV writers, ``add_label_column``) pairs them differently on + different machines. + """ + source = Path(__file__).parent / "search_output" + for name in ("a", "b"): + shutil.copytree(source, tmp_path / name) + + real_walk = os.walk + + def reversed_walk(top, **kwargs): + for root, dirs, filenames in real_walk(top, **kwargs): + dirs.reverse() + yield root, dirs, filenames + + monkeypatch.setattr(os, "walk", reversed_walk) + + aggregator = Aggregator.from_directory(tmp_path) + + assert [output.directory.name for output in aggregator] == ["a", "b"] + + def test_zip_extracted_and_loaded(zipped_directory): aggregator = Aggregator.from_directory(zipped_directory) assert len(aggregator) == 1 @@ -40,13 +68,37 @@ def test_zip_extracted_and_loaded(zipped_directory): def test_zip_not_re_extracted(zipped_directory): + """ + An extracted directory that carries ``.completed`` is the search, so the zip + beside it is left alone and the directory on disk is not overwritten. + """ Aggregator.from_directory(zipped_directory) - (zipped_directory / "search_output" / ".completed").unlink() + completed = zipped_directory / "search_output" / ".completed" + completed.write_text("not the archived content") + aggregator = Aggregator.from_directory(zipped_directory) assert len(aggregator) == 1 - assert not (zipped_directory / "search_output" / ".completed").exists() + assert completed.read_text() == "not the archived content" + + +def test_incomplete_sibling_directory_loses_to_the_zip(zipped_directory): + """ + A directory beside the zip with no ``.completed`` file is not the extraction + of a finished search — post-completion writers recreate ``/files/`` + after the real directory was zipped and removed. The zip wins, so the search + is still aggregated under ``completed_only``. + """ + extracted = zipped_directory / "search_output" + (extracted / "files").mkdir(parents=True) + (extracted / "files" / "search.json").write_text("{}") + (extracted / "files" / "cache_artifact.json").write_text("{}") + + aggregator = Aggregator.from_directory(zipped_directory, completed_only=True) + + assert len(aggregator) == 1 + assert (extracted / ".completed").exists() def test_zip_temporary_leaves_no_extracted_directory(zipped_directory): @@ -108,7 +160,12 @@ def test_zip_temporary_removed_on_close(zipped_directory): def test_zip_temporary_uses_an_existing_extracted_directory(zipped_directory): + """ + The completed extraction beside the zip is used as-is; nothing is extracted + into the temporary directory. + """ Aggregator.from_directory(zipped_directory) + assert (zipped_directory / "search_output" / ".completed").exists() aggregator = Aggregator.from_directory(zipped_directory, unzip_temporary=True) @@ -117,6 +174,29 @@ def test_zip_temporary_uses_an_existing_extracted_directory(zipped_directory): assert aggregator[0]._temporary_directory is None +def test_zip_temporary_incomplete_sibling_directory_loses_to_the_zip(zipped_directory): + """ + The temporary-extraction path has the same precedence: a sibling directory + without ``.completed`` does not stand for the search, so the zip is extracted + into the temporary directory and the sibling is left untouched on disk. + """ + extracted = zipped_directory / "search_output" + (extracted / "files").mkdir(parents=True) + (extracted / "files" / "search.json").write_text("{}") + + aggregator = Aggregator.from_directory( + zipped_directory, + completed_only=True, + unzip_temporary=True, + ) + + assert len(aggregator) == 1 + assert aggregator[0]._temporary_directory is not None + assert aggregator[0].directory != extracted + assert not (extracted / ".completed").exists() + assert (extracted / "files" / "search.json").read_text() == "{}" + + def test_zip_temporary_mirrors_the_scanned_layout(tmp_path): source = Path(__file__).parent / "search_output" for name in ("one", "two"): diff --git a/test_autofit/non_linear/paths/test_paths.py b/test_autofit/non_linear/paths/test_paths.py index a7777da8c..e67459fda 100644 --- a/test_autofit/non_linear/paths/test_paths.py +++ b/test_autofit/non_linear/paths/test_paths.py @@ -121,6 +121,10 @@ def test__preserve_in_zip__file_survives_restore(tmp_path): import zipfile paths = af.DirectoryPaths(name="preserve_test", path_prefix=str(tmp_path)) + # The output directory is the primary store, so the loose copy stays put; + # ``test__preserve_in_zip__removes_the_loose_copy_under_remove_files`` covers + # the other setting. + paths.remove_files = False files_path = Path(paths._files_path) files_path.mkdir(parents=True, exist_ok=True) @@ -149,6 +153,69 @@ def test__preserve_in_zip__file_survives_restore(tmp_path): assert cache_file.exists() +def test__preserve_in_zip__removes_the_loose_copy_under_remove_files(tmp_path): + """ + Under ``remove_files`` the zip is the search's only store, so once the file + is a member the loose copy — and every directory it emptied, up to and + including ``output_path`` — is removed. Left behind, that directory shadows + the zip for ``Aggregator.from_directory`` and, carrying no ``.completed`` + file, silently drops the search under ``completed_only``. + """ + import zipfile + + paths = af.DirectoryPaths(name="preserve_remove_test", path_prefix=str(tmp_path)) + paths.remove_files = True + + files_path = Path(paths._files_path) + files_path.mkdir(parents=True, exist_ok=True) + (files_path / "samples_summary.json").write_text("{}") + + paths.zip_remove() + assert Path(paths._zip_path).exists() + assert not Path(paths.output_path).exists() + + # A post-completion cache write recreates ``/files/``. + cache_file = Path(paths._files_path) / "cache_artifact.json" + cache_file.write_text('{"cached": true}') + + paths.preserve_in_zip(cache_file) + + with zipfile.ZipFile(paths._zip_path) as f: + assert f.read("files/cache_artifact.json") == b'{"cached": true}' + + assert not cache_file.exists() + assert not files_path.exists() + assert not Path(paths.output_path).exists() + + # The restore cycle still brings it back from the zip. + paths.restore() + assert cache_file.exists() + + +def test__preserve_in_zip__keeps_the_loose_copy_without_remove_files(tmp_path): + """ + With ``remove_files`` unset the output directory is the primary store, so + the loose copy is left where the writer put it. + """ + paths = af.DirectoryPaths(name="preserve_keep_test", path_prefix=str(tmp_path)) + paths.remove_files = False + + files_path = Path(paths._files_path) + files_path.mkdir(parents=True, exist_ok=True) + (files_path / "samples_summary.json").write_text("{}") + + paths.zip_remove() + assert Path(paths._zip_path).exists() + + cache_file = Path(paths._files_path) / "cache_artifact.json" + cache_file.write_text('{"cached": true}') + + paths.preserve_in_zip(cache_file) + + assert cache_file.exists() + assert cache_file.read_text() == '{"cached": true}' + + def test__preserve_in_zip__replaces_stale_member(tmp_path): import zipfile