Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 69 additions & 7 deletions autofit/aggregator/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
./aggregator.py ../output pipeline=data_mass_x1_source_x1_positions
"""

import logging
import os
import zipfile
from collections import defaultdict
Expand All @@ -29,6 +30,8 @@
TemporaryExtraction,
)

logger = logging.getLogger(__name__)


class AggregatorGroup:
def __init__(self, groups: ["AggregatorGroup"]):
Expand Down Expand Up @@ -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:
"""
Expand All @@ -236,26 +247,51 @@ 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
# ``<search>/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:
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}"
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():
Expand All @@ -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(
Expand All @@ -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,
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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,
Expand Down
75 changes: 66 additions & 9 deletions autofit/non_linear/paths/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
"""
Expand Down
84 changes: 82 additions & 2 deletions test_autofit/aggregator/test_from_directory.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import gc
import os
import shutil
import zipfile
from pathlib import Path
Expand Down Expand Up @@ -33,20 +34,71 @@ 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
assert (zipped_directory / "search_output" / "files" / "search.json").exists()


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 ``<search>/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):
Expand Down Expand Up @@ -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)

Expand All @@ -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"):
Expand Down
Loading
Loading