From 6cc5a7ac739888c04753b297e193feaab6614908 Mon Sep 17 00:00:00 2001 From: Markus Fritzsche Date: Sat, 31 Oct 2026 12:19:15 -0400 Subject: [PATCH] Add experiments stored in a single tar file Experiment(archive=True) keeps the experiment directory in .tar from the build step on. Runs extract their files into a temporary directory and append the files they create or change; a later member overrides an earlier one. Writers hold an exclusive flock and readers a shared one, and the archive always ends with two zero blocks, so appending never scans it. Parse and fetch read the archive directly. Fast Downward runs call the driver relative to the run directory, since the experiment directory does not exist for archived experiments. --- docs/news.rst | 5 + downward/experiment.py | 11 +- lab/archive.py | 241 ++++++++++++++++++ lab/data/slurm-archived-run-job-body.template | 16 ++ lab/environments.py | 29 ++- lab/experiment.py | 172 +++++++++---- lab/fetcher.py | 153 ++++++++--- tests/test_archive.py | 88 +++++++ 8 files changed, 619 insertions(+), 96 deletions(-) create mode 100644 lab/archive.py create mode 100644 lab/data/slurm-archived-run-job-body.template create mode 100644 tests/test_archive.py diff --git a/docs/news.rst b/docs/news.rst index a7d02468f..e0fa6bf17 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -8,6 +8,11 @@ Lab ^^^ * Use ``ArrheniusEnvironment`` in example experiments and recommend Arrhenius's ``fat`` partition (Jendrik Seipp). +* Add ``Experiment(archive=True)``, which stores the experiment directory in + the single tar file ``.tar`` from the build step on to save inodes on + cluster file systems. Runs execute in temporary directories and append their + files to the archive; the parse and fetch steps read the archive directly + (Markus Fritzsche). v8.10 (2026-06-26) diff --git a/downward/experiment.py b/downward/experiment.py index 986c18c0c..f2b4ad15a 100644 --- a/downward/experiment.py +++ b/downward/experiment.py @@ -77,8 +77,11 @@ def __init__(self, exp: Experiment, algo: FastDownwardAlgorithm, task: suites.Ta ) input_files = ["{domain}", "{problem}"] + # Runs execute in their run directory, two levels below the + # experiment directory. driver = os.path.join( - exp.path, + "..", + "..", algo.cached_revision.get_relative_exp_path("fast-downward.py"), ) self.add_command( @@ -149,10 +152,10 @@ class FastDownwardExperiment(Experiment): #: "planner_wall_clock_time", "score_planner_memory", "score_planner_time". PLANNER_PARSER = PlannerParser() - def __init__(self, path=None, environment=None, revision_cache=None): + def __init__(self, path=None, environment=None, revision_cache=None, archive=False): """ See :class:`lab.experiment.Experiment` for an explanation of - the *path* and *environment* parameters. + the *path*, *environment* and *archive* parameters. *revision_cache* is the directory for caching Fast Downward revisions. It defaults to ``/data/revision-cache``. @@ -176,7 +179,7 @@ def __init__(self, path=None, environment=None, revision_cache=None): >>> exp.add_parser(exp.PLANNER_PARSER) """ - Experiment.__init__(self, path=path, environment=environment) + Experiment.__init__(self, path=path, environment=environment, archive=archive) self.revision_cache = revision_cache or os.path.join( get_default_data_dir(), "revision-cache" diff --git a/lab/archive.py b/lab/archive.py new file mode 100644 index 000000000..b13fa5b26 --- /dev/null +++ b/lab/archive.py @@ -0,0 +1,241 @@ +"""Store an experiment directory in a single uncompressed tar file. + +An experiment created with ``Experiment(archive=True)`` lives in the file +``.tar`` instead of the directory ````. Each member name is +the path of the file relative to the experiment directory. + +The archive is append-only: runs and parsers append the files they create +or change, and a later member overrides an earlier member with the same +name. Writers hold an exclusive ``flock`` on the archive and readers a +shared one, so runs on different cluster nodes can share the archive. + +The archive always ends with exactly two zero blocks. Appending therefore +starts at a known offset and never scans the archive. +""" + +import collections +import contextlib +import fcntl +import io +import logging +import os +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +from lab import tools + +END_OF_ARCHIVE = tarfile.NUL * (2 * tarfile.BLOCKSIZE) + +# Matches members inside run directories and captures the run directory. +_RUN_MEMBER = re.compile(r"(runs-\d+-\d+/[^/]+)(/|$)") + + +def get_archive_path(exp_path): + return f"{os.fspath(exp_path).rstrip('/')}.tar" + + +def get_run_dir_of_member(name): + """Return the run directory containing member *name*, or None.""" + match = _RUN_MEMBER.match(name) + return match.group(1) if match else None + + +class ExperimentArchive: + def __init__(self, path): + self.path = Path(path) + + def create(self): + """Create an empty archive.""" + self.path.parent.mkdir(parents=True, exist_ok=True) + with open(self.path, "xb") as f: + f.write(END_OF_ARCHIVE) + + @contextlib.contextmanager + def reader(self): + """Yield a TarFile for reading while holding a shared lock.""" + with open(self.path, "rb") as f: + fcntl.flock(f, fcntl.LOCK_SH) + with tarfile.open(fileobj=f, mode="r:") as tar: + yield tar + + @contextlib.contextmanager + def writer(self, dereference=False): + """Yield a TarFile that appends members while holding an exclusive lock. + + If the block raises an exception, the archive is restored to its + previous state. + """ + with open(self.path, "r+b") as f: + fcntl.flock(f, fcntl.LOCK_EX) + start = f.seek(-len(END_OF_ARCHIVE), os.SEEK_END) + tar = tarfile.TarFile(fileobj=f, mode="w", dereference=dereference) + try: + yield tar + except BaseException: + f.seek(start) + f.write(END_OF_ARCHIVE) + f.truncate() + raise + # TarFile.close() would pad the archive to a full record, so we + # write the end-of-archive marker ourselves. + f.seek(tar.offset) + f.write(END_OF_ARCHIVE) + f.truncate() + + def members(self): + """Return a dict from member names to their latest TarInfo.""" + with self.reader() as tar: + return {member.name: member for member in tar} + + @staticmethod + def group_by_run_dir(members): + """Map each run directory to its members. Key None holds the others.""" + groups = collections.defaultdict(list) + for name, member in members.items(): + groups[get_run_dir_of_member(name)].append(member) + return groups + + def extract(self, members, dest): + with self.reader() as tar: + for member in members: + # We trust the archive since lab wrote it. + tar.extract(member, dest, filter="fully_trusted") + + def append(self, root, names): + """Append the files *names* (relative to *root*) to the archive.""" + with self.writer() as tar: + for name in names: + tar.add(Path(root) / name, arcname=name, recursive=False) + + +class ArchiveBuilder: + """Write the files of an experiment into its archive during the build step.""" + + def __init__(self, tar, exp_path): + self.tar = tar + self.exp_path = exp_path + self.dirs = {"."} + + def _name(self, path): + return os.path.relpath(path, self.exp_path) + + def _info(self, path, type, mode): + info = tarfile.TarInfo(self._name(path)) + info.type = type + info.mode = mode + info.mtime = int(time.time()) + return info + + def makedirs(self, path): + if self._name(path) not in self.dirs: + self.dirs.add(self._name(path)) + self.tar.addfile(self._info(path, tarfile.DIRTYPE, 0o755)) + + def write_file(self, path, content, permissions=None): + data = content.encode() + info = self._info(path, tarfile.REGTYPE, permissions or 0o644) + info.size = len(data) + self.tar.addfile(info, io.BytesIO(data)) + + def copy(self, source, path): + self.tar.add(source, arcname=self._name(path)) + + def symlink(self, source, path, start): + # Runs are executed in temporary directories, so relative links to + # files outside of the experiment would break. + info = self._info(path, tarfile.SYMTYPE, 0o777) + info.linkname = os.path.abspath(source) + self.tar.addfile(info) + + +def _changed_files(exp_dir, run_dir, members): + """Return the files in *run_dir* that are new or differ from the archive.""" + changed = [] + for root, _, files in os.walk(exp_dir / run_dir): + for filename in files: + path = Path(root) / filename + name = str(path.relative_to(exp_dir)) + member = members.get(name) + stat = path.lstat() + if ( + member is None + or (member.isfile() and member.size != stat.st_size) + or (member.isfile() and int(member.mtime) != int(stat.st_mtime)) + or (member.issym() and member.linkname != os.readlink(path)) + ): + changed.append(name) + return sorted(changed) + + +def _execute_run(archive, members, run_members, exp_dir, run_dir): + """Execute a run in *exp_dir* and append its new files to the archive. + + Return True iff the run wrote to driver.err. + """ + if f"{run_dir}/driver.log" in members: + logging.info(f"The run in {run_dir} has already been started --> skip it") + return False + + archive.extract(run_members, exp_dir) + path = exp_dir / run_dir + with ( + open(path / "driver.log", "w") as driver_log, + open(path / "driver.err", "w") as driver_err, + ): + retcode = subprocess.call( + [tools.get_python_executable(), "run"], + cwd=path, + stdout=driver_log, + stderr=driver_err, + ) + if retcode != 0: + driver_err.write(f"The run script finished with exit code {retcode}\n") + + # driver.log always has content for a started run, so we never delete it. + driver_err_path = path / "driver.err" + failed = driver_err_path.stat().st_size > 0 + if not failed: + driver_err_path.unlink() + + archive.append(exp_dir, _changed_files(exp_dir, run_dir, members)) + shutil.rmtree(path) + return failed + + +def execute_runs(archive_path, run_dirs): + """Execute the given runs of an archived experiment one after another. + + The experiment files outside of run directories are extracted once + into a temporary directory, each run directory right before its run. + Return True iff at least one run wrote to driver.err. + """ + archive = ExperimentArchive(archive_path) + members = archive.members() + groups = archive.group_by_run_dir(members) + failed = False + with tempfile.TemporaryDirectory(prefix="lab-") as scratch: + exp_dir = Path(scratch) + archive.extract(groups[None], exp_dir) + for run_dir in run_dirs: + logging.info(f"Starting run in {run_dir}") + failed |= _execute_run(archive, members, groups[run_dir], exp_dir, run_dir) + return failed + + +def main(): + """Execute runs of an archived experiment: ARCHIVE RUN_ID [RUN_ID ...]""" + from lab.experiment import get_run_dir + + tools.configure_logging() + archive_path, *run_ids = sys.argv[1:] + execute_runs(archive_path, [get_run_dir(int(run_id)) for run_id in run_ids]) + + +if __name__ == "__main__": + main() diff --git a/lab/data/slurm-archived-run-job-body.template b/lab/data/slurm-archived-run-job-body.template new file mode 100644 index 000000000..41b2eb695 --- /dev/null +++ b/lab/data/slurm-archived-run-job-body.template @@ -0,0 +1,16 @@ +# Shuffle runs to avoid systematic bias. +declare -a SHUFFLED_RUN_IDS=(%(run_order)s) +NUM_RUNS=%(num_runs)d +RUNS_PER_TASK=%(runs_per_task)d + +# Compute which indices belong to the Slurm task. +let "START_INDEX=($SLURM_ARRAY_TASK_ID - 1) * RUNS_PER_TASK" +let "END_INDEX=START_INDEX + RUNS_PER_TASK - 1" + +if [ $END_INDEX -ge $NUM_RUNS ]; then + let "END_INDEX=$NUM_RUNS - 1" +fi + +# Execute runs in a temporary directory and append their files to the archive. +"%(python)s" -m lab.archive "%(archive_path)s" \ + "${SHUFFLED_RUN_IDS[@]:$START_INDEX:$((END_INDEX - START_INDEX + 1))}" diff --git a/lab/environments.py b/lab/environments.py index f462f7e90..02372dc66 100644 --- a/lab/environments.py +++ b/lab/environments.py @@ -9,7 +9,7 @@ import sys from pathlib import Path -from lab import tools +from lab import archive, tools def _get_job_prefix(exp_name): @@ -88,6 +88,9 @@ def __init__(self, processes=None, **kwargs): self.processes = processes def write_main_script(self): + if self.exp.archive: + # start_runs() executes archived runs directly. + return script = tools.fill_template( "local-job.py", task_order=self._get_task_order(len(self.exp.runs)), @@ -97,10 +100,28 @@ def write_main_script(self): self.exp.add_new_file("", self.EXP_RUN_SCRIPT, script, permissions=0o755) def start_runs(self): + if self.exp.archive: + self._start_archived_runs() + return tools.run_command( [tools.get_python_executable(), self.EXP_RUN_SCRIPT], cwd=self.exp.path ) + def _start_archived_runs(self): + from lab.experiment import get_run_dir + + run_dirs = [ + get_run_dir(run_id) for run_id in self._get_task_order(len(self.exp.runs)) + ] + chunks = [run_dirs[i :: self.processes] for i in range(self.processes)] + with multiprocessing.Pool(processes=self.processes) as pool: + failed = pool.starmap( + archive.execute_runs, + [(self.exp.archive_path, chunk) for chunk in chunks if chunk], + ) + if any(failed): + sys.exit("Error: At least one run failed.") + def run_steps(self, steps): for step in steps: step() @@ -249,6 +270,7 @@ class SlurmEnvironment(Environment): NICE_VALUE = 0 JOB_HEADER_TEMPLATE_FILE = "slurm-job-header" RUN_JOB_BODY_TEMPLATE_FILE = "slurm-run-job-body" + ARCHIVED_RUN_JOB_BODY_TEMPLATE_FILE = "slurm-archived-run-job-body" STEP_JOB_BODY_TEMPLATE_FILE = "slurm-step-job-body" def __init__( @@ -325,7 +347,10 @@ def _get_run_job_body(self, run_step): num_tasks = self._get_num_tasks(run_step) logging.info(f"Grouping {num_runs} runs into {num_tasks} Slurm tasks.") return tools.fill_template( - self.RUN_JOB_BODY_TEMPLATE_FILE, + self.ARCHIVED_RUN_JOB_BODY_TEMPLATE_FILE + if self.exp.archive + else self.RUN_JOB_BODY_TEMPLATE_FILE, + archive_path=self.exp.archive_path, exp_path=self.exp.path, num_runs=num_runs, python=tools.get_python_executable(), diff --git a/lab/experiment.py b/lab/experiment.py index af27ec78a..0a8d1a4f5 100644 --- a/lab/experiment.py +++ b/lab/experiment.py @@ -3,11 +3,18 @@ import logging import os import re +import shutil import sys +import tempfile from collections import OrderedDict from pathlib import Path from lab import environments, tools +from lab.archive import ( + ArchiveBuilder, + ExperimentArchive, + get_archive_path, +) from lab.fetcher import Fetcher from lab.parser import Parser from lab.steps import Step, get_step, get_steps_text @@ -84,6 +91,24 @@ def __init__(self, name, source, dest, symlink): self.symlink = symlink +class _DirectoryBuilder: + """Write the files of an experiment into its directory during the build step.""" + + def makedirs(self, path): + tools.makedirs(path) + + def write_file(self, path, content, permissions=None): + tools.write_file(path, content) + if permissions is not None: + os.chmod(path, permissions) + + def copy(self, source, path): + tools.copy(source, path) + + def symlink(self, source, path, start): + os.symlink(os.path.relpath(source, start=start), path) + + class _Buildable: """Abstract base class for Experiment and Run.""" @@ -298,20 +323,19 @@ def _get_abs_path(self, rel_path): def _get_rel_path(self, abs_path): return os.path.relpath(abs_path, start=self.path) - def _build_properties_file(self, properties_filename): - combined_props = tools.Properties(self._get_abs_path(properties_filename)) - combined_props.update(self.properties) - combined_props.write() + def _build_properties_file(self, builder, properties_filename): + builder.write_file( + self._get_abs_path(properties_filename), str(self.properties) + ) - def _build_new_files(self): + def _build_new_files(self, builder): for dest, content, permissions in self.new_files: filename = self._get_abs_path(dest) - tools.makedirs(os.path.dirname(filename)) + builder.makedirs(os.path.dirname(filename)) logging.debug(f'Writing file "{filename}"') - tools.write_file(filename, content) - os.chmod(filename, permissions) + builder.write_file(filename, content, permissions) - def _build_resources(self): + def _build_resources(self, builder): for resource in self.resources: if not os.path.exists(resource.source): logging.critical(f"Resource not found: {resource.source}") @@ -320,18 +344,14 @@ def _build_resources(self): # Only copy resources that reside in the experiment/run dir. continue if resource.symlink: - # Do not create a symlink if the file doesn't exist. - if not os.path.exists(resource.source): - continue - source = self._get_rel_path(resource.source) - os.symlink(source, dest) - logging.debug(f"Linking from {source} to {dest}") + logging.debug(f"Linking from {resource.source} to {dest}") + builder.symlink(resource.source, dest, start=self.path) continue # Even if the directory containing a resource has already been added, # we copy the resource since we might want to overwrite it. logging.debug(f"Copying {resource.source} to {dest}") - tools.copy(resource.source, dest) + builder.copy(resource.source, dest) class Experiment(_Buildable): @@ -342,13 +362,22 @@ class Experiment(_Buildable): """ - def __init__(self, path=None, environment=None): + def __init__(self, path=None, environment=None, archive=False): """ The experiment will be built at *path*. It defaults to ``/data//``. E.g., for the script ``experiments/myexp.py``, the default *path* will be ``experiments/data/myexp/``. + If *archive* is True, the experiment directory is stored in the + single uncompressed tar file ``.tar`` from the build step + on, which saves inodes on cluster file systems. Each run extracts + its files into a temporary directory (respecting ``TMPDIR``) and + appends the files it creates or changes to the archive. The parse + and fetch steps read the archive directly. Custom steps that + expect the directory ```` don't work with archived + experiments. + *environment* must be an :ref:`Environment ` instance. You can use :class:`~lab.environments.LocalEnvironment` to run your @@ -366,6 +395,7 @@ def __init__(self, path=None, environment=None): self.path = os.path.abspath(path) if any(char in self.path for char in (":", ",")): logging.critical(f"Path contains commas or colons: {self.path}") + self.archive = archive self.environment = environment or environments.LocalEnvironment() self.environment.exp = self @@ -380,6 +410,15 @@ def name(self): """Return the directory name of the experiment's ``path``.""" return os.path.basename(self.path) + @property + def archive_path(self): + """Return the path of the archive that stores an archived experiment.""" + return get_archive_path(self.path) + + @property + def _data_path(self): + return self.archive_path if self.archive else self.path + @property def eval_dir(self): """Return the name of the default evaluation directory. @@ -453,6 +492,10 @@ def parse(self): data from the experiment into the evaluation directory. """ + if self.archive: + self._parse_archive() + return + if not os.path.isdir(self.path): logging.critical(f"{self.path} is missing or not a directory") @@ -465,19 +508,43 @@ def parse(self): props_path = run_dir / "properties" if props_path.is_file(): props_path.unlink() + self._parse_run_dir(run_dir, index, num_runs) + + def _parse_run_dir(self, run_dir, index, num_runs): + loglevel = logging.INFO if index % 100 == 0 else logging.DEBUG + logging.log(loglevel, f"Parsing run: {index:6d}/{num_runs:d}") + props = tools.Properties(filename=run_dir / "properties") + for parser in self.parsers: + parser.parse(run_dir, props) + try: + props.write() + except ValueError as err: + logging.critical( + f"Failed to write properties file in {run_dir}: {err}\n" + "Often the solution is to revise a parser." + ) - loglevel = logging.INFO if index % 100 == 0 else logging.DEBUG - logging.log(loglevel, f"Parsing run: {index:6d}/{num_runs:d}") - props = tools.Properties(filename=props_path) - for parser in self.parsers: - parser.parse(run_dir, props) - try: - props.write() - except ValueError as err: - logging.critical( - f"Failed to write properties file in {run_dir}: {err}\n" - "Often the solution is to revise a parser." + def _parse_archive(self): + if not os.path.isfile(self.archive_path): + logging.critical(f"{self.archive_path} is missing or not a file") + + archive = ExperimentArchive(self.archive_path) + groups = archive.group_by_run_dir(archive.members()) + run_dirs = sorted(run_dir for run_dir in groups if run_dir is not None) + num_runs = len(run_dirs) + logging.info( + f"Running {len(self.parsers)} parsers in {num_runs:d} archived run " + f"directories." + ) + with tempfile.TemporaryDirectory(prefix="lab-") as scratch: + for index, run_dir in enumerate(run_dirs, start=1): + props_name = f"{run_dir}/properties" + archive.extract( + [m for m in groups[run_dir] if m.name != props_name], scratch ) + self._parse_run_dir(Path(scratch) / run_dir, index, num_runs) + archive.append(scratch, [props_name]) + shutil.rmtree(Path(scratch) / run_dir) def add_fetcher( self, src=None, dest=None, merge=None, name=None, filter=None, **kwargs @@ -489,8 +556,9 @@ def add_fetcher( You can use this method to combine results from multiple experiments. - *src* can be an experiment or evaluation directory or a properties - file. It defaults to ``exp.path``. + *src* can be an experiment or evaluation directory, an experiment + archive or a properties file. It defaults to ``exp.path`` or, for + archived experiments, ``exp.archive_path``. *dest* must be a new or existing evaluation directory. It defaults to ``exp.eval_dir``. If *dest* already contains @@ -526,7 +594,7 @@ def add_fetcher( >>> exp.add_fetcher(filter_algorithm=["algo_1", "algo_5"]) """ - src = src or self.path + src = src or self._data_path dest = dest or self.eval_dir name = name or f"fetch-{os.path.basename(src.rstrip('/'))}" self.add_step(name, Fetcher(), src, dest, merge=merge, filter=filter, **kwargs) @@ -587,9 +655,9 @@ def run_steps(self): env.run_steps(steps) def _remove_experiment_dir(self): - if os.path.exists(self.path): - tools.confirm_overwrite_or_abort(self.path) - tools.remove_path(self.path) + if os.path.exists(self._data_path): + tools.confirm_overwrite_or_abort(self._data_path) + tools.remove_path(self._data_path) def build(self, write_to_disk=True): """ @@ -605,17 +673,25 @@ def build(self, write_to_disk=True): if not write_to_disk: return - logging.info(f'Experiment path: "{tools.get_relative_path(self.path)}"') + logging.info(f'Experiment path: "{tools.get_relative_path(self._data_path)}"') self._remove_experiment_dir() - tools.makedirs(self.path) + if self.archive: + archive = ExperimentArchive(self.archive_path) + archive.create() + with archive.writer(dereference=True) as tar: + self._build(ArchiveBuilder(tar, self.path)) + else: + self._build(_DirectoryBuilder()) - self._build_resources() - self._build_runs() - self._build_properties_file(STATIC_EXPERIMENT_PROPERTIES_FILENAME) + def _build(self, builder): + builder.makedirs(self.path) + self._build_resources(builder) + self._build_runs(builder) + self._build_properties_file(builder, STATIC_EXPERIMENT_PROPERTIES_FILENAME) # The main script can need other experiment files and it adds new files self.environment.write_main_script() - self._build_new_files() + self._build_new_files(builder) def start_runs(self): """Execute all runs that were added to the experiment. @@ -626,7 +702,7 @@ def start_runs(self): """ self.environment.start_runs() - def _build_runs(self): + def _build_runs(self, builder): """ Uses the relative directory information and writes all runs to disc. """ @@ -640,7 +716,7 @@ def _build_runs(self): logging.info(f"Build run {index:6}/{num_runs}") for name, (command, kwargs) in self.commands.items(): run.add_command(name, command, **kwargs) - run.build(index) + run.build(index, builder) logging.info("Finished building runs") @@ -660,8 +736,8 @@ def __init__(self, experiment): self.experiment = experiment self.path = None - def build(self, run_id): - """Write the run's files to disk. + def build(self, run_id, builder): + """Write the run's files with *builder*. This method is called automatically by the experiment. @@ -669,15 +745,15 @@ def build(self, run_id): rel_run_dir = get_run_dir(run_id) self.set_property("run_dir", rel_run_dir) self.path = os.path.join(self.experiment.path, rel_run_dir) - os.makedirs(self.path) + builder.makedirs(self.path) # We need to build the run script before the resources, because # the run script is added as a resource. self._build_run_script() - self._build_new_files() - self._build_resources() + self._build_new_files(builder) + self._build_resources(builder) self._check_id() - self._build_properties_file(STATIC_RUN_PROPERTIES_FILENAME) + self._build_properties_file(builder, STATIC_RUN_PROPERTIES_FILENAME) def _build_run_script(self): if not self.commands: diff --git a/lab/fetcher.py b/lab/fetcher.py index 9d3dd9798..758de2c04 100644 --- a/lab/fetcher.py +++ b/lab/fetcher.py @@ -1,9 +1,11 @@ +import json import logging import sys from pathlib import Path import lab.experiment from lab import tools +from lab.archive import ExperimentArchive def _check_eval_dir(eval_dir: Path): @@ -46,40 +48,67 @@ class Fetcher: def fetch_dir(self, run_dir): """Combine "static-properties" and "properties" from a run dir and return it.""" run_dir = Path(run_dir) - static_props = tools.Properties( - filename=run_dir / lab.experiment.STATIC_RUN_PROPERTIES_FILENAME - ) dynamic_props_path = run_dir / "properties" - dynamic_props = tools.Properties(filename=dynamic_props_path) - if not dynamic_props_path.exists(): - logging.critical( - f'Properties file "{tools.get_relative_path(dynamic_props_path)}" is' - f' missing. Did you forget to add or run the "parse" step?' - ) - elif not dynamic_props: - logging.critical( - f'Properties file "{tools.get_relative_path(dynamic_props_path)}" is' - f" empty. Have you added at least one parser?" - ) + return _combine_run_properties( + static_props=tools.Properties( + filename=run_dir / lab.experiment.STATIC_RUN_PROPERTIES_FILENAME + ), + dynamic_props=tools.Properties(filename=dynamic_props_path), + dynamic_props_name=tools.get_relative_path(dynamic_props_path), + has_dynamic_props=dynamic_props_path.exists(), + has_driver_log=(run_dir / "driver.log").exists(), + logs={ + name: (run_dir / name).read_text() + for name in ["driver.err", "run.err"] + if (run_dir / name).exists() + }, + ) - props = tools.Properties() - props.update(static_props) - props.update(dynamic_props) + def _fetch_archive(self, archive_path): + """Yield the combined properties of each run in an experiment archive.""" + archive = ExperimentArchive(archive_path) + with archive.reader() as tar: + members = {member.name: member for member in tar} + groups = archive.group_by_run_dir(members) + run_dirs = sorted(run_dir for run_dir in groups if run_dir is not None) + num_runs = len(run_dirs) + logging.info(f"Collecting properties from {num_runs:d} archived runs") + + def read(name): + return tar.extractfile(members[name]).read().decode() + + def read_props(name): + props = tools.Properties() + if name in members: + props.update(json.loads(read(name))) + return props - driver_log = run_dir / "driver.log" - if not driver_log.exists(): - props.add_unexplained_error( - "driver.log is missing. Probably the run was never started." - ) + for index, run_dir in enumerate(run_dirs, start=1): + props_name = f"{run_dir}/properties" + _log_progress(index, num_runs) + yield _combine_run_properties( + static_props=read_props( + f"{run_dir}/{lab.experiment.STATIC_RUN_PROPERTIES_FILENAME}" + ), + dynamic_props=read_props(props_name), + dynamic_props_name=f"{archive_path}:{props_name}", + has_dynamic_props=props_name in members, + has_driver_log=f"{run_dir}/driver.log" in members, + logs={ + name: read(f"{run_dir}/{name}") + for name in ["driver.err", "run.err"] + if f"{run_dir}/{name}" in members + }, + ) - driver_err = run_dir / "driver.err" - run_err = run_dir / "run.err" - for logfile in [driver_err, run_err]: - if logfile.exists(): - content = logfile.read_text() - if content: - props.add_unexplained_error(f"{logfile.name}: {content}") - return props + def _fetch_dirs(self, src_dir): + """Yield the combined properties of each run in an experiment directory.""" + run_dirs = sorted(src_dir.glob("runs-*-*/*")) + num_dirs = len(run_dirs) + logging.info(f"Collecting properties from {num_dirs:d} run directories") + for index, run_dir in enumerate(run_dirs, start=1): + _log_progress(index, num_dirs) + yield self.fetch_dir(run_dir) def __call__(self, src_dir, eval_dir=None, merge=None, filter=None, **kwargs): """ @@ -100,8 +129,12 @@ def __call__(self, src_dir, eval_dir=None, merge=None, filter=None, **kwargs): src_dir = Path(src_dir) if not src_dir.exists(): logging.critical(f"{src_dir} is missing") + is_archive = src_dir.suffix == ".tar" + # For archived experiments, the eval and grid-steps directories are + # named after the experiment directory. + exp_dir = src_dir.with_suffix("") if is_archive else src_dir - eval_dir = eval_dir or str(src_dir).rstrip("/") + "-eval" + eval_dir = eval_dir or str(exp_dir).rstrip("/") + "-eval" eval_dir = Path(eval_dir) logging.info( f"Fetching properties from {tools.get_relative_path(src_dir)} " @@ -122,7 +155,7 @@ def __call__(self, src_dir, eval_dir=None, merge=None, filter=None, **kwargs): if not src_props_file.is_file() and path.is_file(): src_props_file = path break - fetch_from_eval_dir = src_props_file.exists() + fetch_from_eval_dir = not is_archive and src_props_file.exists() combined_props = tools.Properties(eval_dir / "properties") run_filter = tools.RunFilter(filter, **kwargs) if fetch_from_eval_dir: @@ -134,7 +167,7 @@ def __call__(self, src_dir, eval_dir=None, merge=None, filter=None, **kwargs): logging.info(f"Fetched properties of {len(src_props)} runs.") else: try: - slurm_err_content = tools.get_slurm_err_content(src_dir) + slurm_err_content = tools.get_slurm_err_content(exp_dir) except FileNotFoundError: slurm_err_content = "" @@ -142,19 +175,16 @@ def __call__(self, src_dir, eval_dir=None, merge=None, filter=None, **kwargs): logging.warning("There was output to *-grid-steps/slurm.err") new_props = tools.Properties() - run_dirs = sorted(src_dir.glob("runs-*-*/*")) - num_dirs = len(run_dirs) - logging.info(f"Collecting properties from {num_dirs:d} run directories") - for index, run_dir in enumerate(run_dirs, start=1): - props = self.fetch_dir(run_dir) + runs = ( + self._fetch_archive(src_dir) + if is_archive + else self._fetch_dirs(src_dir) + ) + for props in runs: if slurm_err_content: props.add_unexplained_error("output-to-slurm.err") id_string = "-".join(props["id"]) new_props[id_string] = props - loglevel = logging.INFO if index % 100 == 0 else logging.DEBUG - logging.log( - loglevel, f"Collected {index:6d}/{num_dirs} properties files" - ) run_filter.apply(new_props) combined_props.update(new_props) @@ -170,3 +200,42 @@ def __call__(self, src_dir, eval_dir=None, merge=None, filter=None, **kwargs): f"Wrote properties file. It contains {unexplained_errors} " f"runs with unexplained errors." ) + + +def _combine_run_properties( + static_props, + dynamic_props, + dynamic_props_name, + has_dynamic_props, + has_driver_log, + logs, +): + if not has_dynamic_props: + logging.critical( + f'Properties file "{dynamic_props_name}" is' + f' missing. Did you forget to add or run the "parse" step?' + ) + elif not dynamic_props: + logging.critical( + f'Properties file "{dynamic_props_name}" is' + f" empty. Have you added at least one parser?" + ) + + props = tools.Properties() + props.update(static_props) + props.update(dynamic_props) + + if not has_driver_log: + props.add_unexplained_error( + "driver.log is missing. Probably the run was never started." + ) + + for name, content in logs.items(): + if content: + props.add_unexplained_error(f"{name}: {content}") + return props + + +def _log_progress(index, num_runs): + loglevel = logging.INFO if index % 100 == 0 else logging.DEBUG + logging.log(loglevel, f"Collected {index:6d}/{num_runs} properties files") diff --git a/tests/test_archive.py b/tests/test_archive.py new file mode 100644 index 000000000..775703d4a --- /dev/null +++ b/tests/test_archive.py @@ -0,0 +1,88 @@ +"""Test that archived experiments produce the same results as directory ones.""" + +import json +import sys +import tarfile + +import pytest + +from lab.archive import ExperimentArchive +from lab.environments import LocalEnvironment +from lab.experiment import Experiment +from lab.fetcher import Fetcher +from lab.parser import Parser + + +def _run_experiment(path, input_file, archive): + exp = Experiment(path, environment=LocalEnvironment(processes=2), archive=archive) + exp.add_resource("script", input_file.parent / "script.py", "script.py") + parser = Parser() + parser.add_pattern("square", r"square: (\d+)", type=int) + exp.add_parser(parser) + for number in range(1, 6): + run = exp.add_run() + run.add_resource("input", input_file, "input.txt", symlink=True) + run.add_command("square", [sys.executable, "{script}", str(number), "{input}"]) + run.set_property("id", [f"run-{number}"]) + exp.build() + exp.start_runs() + exp.parse() + exp.parse() # Parsing twice must not change the results. + Fetcher()(exp._data_path, merge=False) + with open(exp.eval_dir + "/properties") as f: + return json.load(f) + + +@pytest.fixture +def inputs(tmp_path): + (tmp_path / "script.py").write_text( + "import sys\n" + "number = int(sys.argv[1])\n" + "# Run 3 writes to stderr, which the fetcher reports as an error.\n" + "stream = sys.stderr if number == 3 else sys.stdout\n" + "print(open(sys.argv[2]).read().strip(), file=stream)\n" + "print(f'square: {number * number}')\n" + ) + input_file = tmp_path / "input.txt" + input_file.write_text("input") + return input_file + + +def test_archived_experiment_matches_directory_experiment(tmp_path, inputs): + dir_props = _run_experiment(tmp_path / "dir-exp", inputs, archive=False) + archive_props = _run_experiment(tmp_path / "archive-exp", inputs, archive=True) + + assert not (tmp_path / "archive-exp").exists() + assert (tmp_path / "archive-exp.tar").is_file() + assert (tmp_path / "archive-exp-eval" / "properties").is_file() + assert dir_props == archive_props + assert [archive_props[f"run-{n}"]["square"] for n in range(1, 6)] == [ + 1, + 4, + 9, + 16, + 25, + ] + assert "unexplained_errors" in archive_props["run-3"] + + +def test_archive_ends_with_end_of_archive_marker(tmp_path, inputs): + _run_experiment(tmp_path / "exp", inputs, archive=True) + archive = tmp_path / "exp.tar" + data = archive.read_bytes() + assert data.endswith(tarfile.NUL * 2 * tarfile.BLOCKSIZE) + assert not data[: -2 * tarfile.BLOCKSIZE].endswith(tarfile.NUL * tarfile.BLOCKSIZE) + with tarfile.open(archive) as tar: + assert "runs-00001-00100/00001/driver.log" in tar.getnames() + + +def test_failed_append_leaves_archive_unchanged(tmp_path): + archive = ExperimentArchive(tmp_path / "exp.tar") + archive.create() + (tmp_path / "file").write_text("content") + archive.append(tmp_path, ["file"]) + before = archive.path.read_bytes() + with pytest.raises(FileNotFoundError): + archive.append(tmp_path, ["file", "missing"]) + assert archive.path.read_bytes() == before + assert list(archive.members()) == ["file"]