diff --git a/autofit/campaign/__init__.py b/autofit/campaign/__init__.py index 32d2bbec9..3da298bef 100644 --- a/autofit/campaign/__init__.py +++ b/autofit/campaign/__init__.py @@ -5,10 +5,15 @@ success checks, propose-only retry policy, the autonerves site); - ``scheduler``: the ``Scheduler`` protocol and its Fake, Local and Slurm adapters; - ``lint``: the partition lint (CPU-only work never goes on a GPU partition); -- ``submit``: arrays per stage and chunk, chained per index, with a job ledger. +- ``submit``: arrays per stage and chunk, chained per index, with a job ledger; +- ``collector``: accounting joined with status records → ``digest`` + (``digest.json``, a ≤2 KB ``digest.md``, ``tasks.jsonl``, ``failed_.txt``); +- ``proposals``: resubmit and pending-update proposals (never acted on); +- ``retro``: the digest of a finished campaign from a ``sacct`` dump alone. -Command line: ``python -m autofit.campaign {validate,submit}``; in Python, -``autofit.campaign.submit.submit(campaign, scheduler)``. +Command line: ``python -m autofit.campaign {validate,submit,status,resubmit,retro}``; +in Python, ``autofit.campaign.submit.submit(campaign, scheduler)`` and +``autofit.campaign.retro.retro(dump, ...)``. Run states and failure classes come from ``autofit.non_linear.status.states``. """ @@ -20,3 +25,6 @@ ) from autofit.campaign.spec import Campaign, CampaignException, Resources, Stage from autofit.campaign.submit import read_ledger +from autofit.campaign.collector import collect +from autofit.campaign.digest import TaskOutcome, build_digest, digest_markdown +from autofit.campaign.proposals import propose_resubmit diff --git a/autofit/campaign/__main__.py b/autofit/campaign/__main__.py index a2efe46e5..1c4c4da2e 100644 --- a/autofit/campaign/__main__.py +++ b/autofit/campaign/__main__.py @@ -5,11 +5,21 @@ -------- validate Check the campaign file against its site; print every problem. -submit [--stage S ...] [--indices SPEC] [--dry-run] +submit [--stage S ...] [--indices SPEC] [--proposal FILE] [--dry-run] Submit the stages (default: all) over the manifest (or ``--indices``, a Slurm array spec of campaign indices), chunk by chunk. Every array is linted against - the GPU-partition rule first. ``--dry-run`` prints the batch scripts and submits - nothing. + the GPU-partition rule first. ``--proposal`` submits an approved resubmit proposal + (its stage, indices and resources). ``--dry-run`` prints the batch scripts and + submits nothing. +status + Collect the campaign (one accounting query, one capacity snapshot, the status + records), write the digest files and print ``digest.md``. +resubmit --stage S --class C + Write ``resubmit__.json``, a proposal sized from the failed tasks' own + measurements (from the last ``status``), and print it. Nothing is submitted. +retro --sacct DUMP [--workdir-prefix DIR ...] [--name-regex RE] [--stage-regex RE] + [--other-stage NAME] [--status-root DIR] [--site NAME] [--name NAME] [--output DIR] + The digest of a finished campaign from a ``sacct --parsable2`` dump alone. """ import argparse import json @@ -44,12 +54,17 @@ def _submit(arguments) -> int: try: campaign = Campaign.load(arguments.campaign) indices = parse_array_spec(arguments.indices)[0] if arguments.indices else None + stages = arguments.stage + resources = None + if arguments.proposal: + stages, indices, resources = _proposal(campaign, arguments.proposal) scheduler = None if arguments.dry_run else scheduler_for(campaign) entries = submit( campaign, scheduler, - stages=arguments.stage, + stages=stages, indices=indices, + resources=resources, dry_run=arguments.dry_run, ) except (CampaignException, PartitionLintError) as exception: @@ -65,6 +80,90 @@ def _submit(arguments) -> int: return 0 +def _proposal(campaign, path): + from autofit.campaign.spec import Resources + + proposal = json.loads(open(path).read()) + if not proposal.get("indices") or not proposal.get("resources"): + raise CampaignException(f"Proposal {path} has nothing to submit: {proposal.get('reason')}") + raw = dict(proposal["resources"]) + resources = Resources(**raw) + return [proposal["stage"]], parse_array_spec(proposal["indices"])[0], {proposal["stage"]: resources} + + +def _status(arguments) -> int: + from autofit.campaign.collector import collect + from autofit.campaign.digest import digest_markdown + from autofit.campaign.scheduler import scheduler_for + + try: + campaign = Campaign.load(arguments.campaign) + except CampaignException as exception: + print(exception, file=sys.stderr) + return 1 + digest = collect(campaign, scheduler_for(campaign)) + print(digest_markdown(digest), end="") + return 0 + + +def _resubmit(arguments) -> int: + from autofit.campaign.digest import read_outcomes + from autofit.campaign.proposals import propose_resubmit + + try: + campaign = Campaign.load(arguments.campaign) + except CampaignException as exception: + print(exception, file=sys.stderr) + return 1 + if arguments.stage not in campaign.stages: + print(f"Unknown stage {arguments.stage!r}.", file=sys.stderr) + return 1 + tasks = campaign.directory / "tasks.jsonl" + if not tasks.exists(): + print(f"No {tasks}: run `status` first.", file=sys.stderr) + return 1 + proposal = propose_resubmit( + campaign.stages[arguments.stage], + getattr(arguments, "class"), + read_outcomes(tasks), + site=campaign.site if campaign.site_name else None, + ) + path = campaign.directory / f"resubmit_{arguments.stage}_{getattr(arguments, 'class')}.json" + path.write_text(json.dumps(proposal, indent=1, default=str)) + print(json.dumps(proposal, indent=1, default=str)) + if proposal["indices"]: + print( + f"\nProposal only. To act on it once approved:\n" + f" python -m autofit.campaign submit {arguments.campaign} --proposal {path}" + ) + return 0 + + +def _retro(arguments) -> int: + from autofit.campaign.digest import digest_markdown, write_digest + from autofit.campaign.retro import retro + + site = None + if arguments.site: + from autonerves.site_config import load_site, site_path + + site = load_site(site_path(arguments.site)) + digest, outcomes = retro( + arguments.sacct, + workdir_prefixes=arguments.workdir_prefix or (), + name_regex=arguments.name_regex, + stage_regex=arguments.stage_regex, + status_root=arguments.status_root, + site=site, + name=arguments.name, + other_stage=arguments.other_stage, + ) + if arguments.output: + write_digest(arguments.output, digest, outcomes) + print(digest_markdown(digest), end="") + return 0 + + def main(argv=None) -> int: parser = argparse.ArgumentParser(prog="python -m autofit.campaign") commands = parser.add_subparsers(dest="command", required=True) @@ -77,9 +176,32 @@ def main(argv=None) -> int: submit.add_argument("campaign") submit.add_argument("--stage", action="append", help="Stage to submit (repeatable).") submit.add_argument("--indices", help="Campaign indices, as a Slurm array spec.") + submit.add_argument("--proposal", help="Submit an approved resubmit proposal.") submit.add_argument("--dry-run", action="store_true", help="Print, do not submit.") submit.set_defaults(handler=_submit) + status = commands.add_parser("status", help="Collect the campaign into its digest.") + status.add_argument("campaign") + status.set_defaults(handler=_status) + + resubmit = commands.add_parser("resubmit", help="Propose a resubmit (never submits).") + resubmit.add_argument("campaign") + resubmit.add_argument("--stage", required=True) + resubmit.add_argument("--class", required=True, help="timeout, oom, node_fail, ...") + resubmit.set_defaults(handler=_resubmit) + + retro = commands.add_parser("retro", help="Digest a finished campaign from sacct.") + retro.add_argument("--sacct", required=True, help="A sacct --parsable2 dump.") + retro.add_argument("--workdir-prefix", action="append", help="Keep jobs under this WorkDir.") + retro.add_argument("--name-regex", help="Keep jobs whose name matches.") + retro.add_argument("--stage-regex", help="Stage from job name (group 'stage').") + retro.add_argument("--other-stage", help="Stage of jobs the stage regex misses.") + retro.add_argument("--status-root", help="Join status records under this directory.") + retro.add_argument("--site", help="Site layer (GPU-only partitions).") + retro.add_argument("--name", default="retro", help="Campaign name in the digest.") + retro.add_argument("--output", help="Write the digest files here.") + retro.set_defaults(handler=_retro) + arguments = parser.parse_args(argv) return arguments.handler(arguments) diff --git a/autofit/campaign/collector.py b/autofit/campaign/collector.py new file mode 100644 index 000000000..72c36aaa0 --- /dev/null +++ b/autofit/campaign/collector.py @@ -0,0 +1,252 @@ +""" +The live collector: one pass over a campaign's scheduler accounting and status records, +reduced to the digest. + +- **Jobs** come from the campaign's job ledger (``submit``), queried in one call. +- **Status records** (``.status.json``, hpc-campaign phase 1) under the + campaign's ``status_root`` are joined to tasks by the scheduler job and task ids the + fit recorded for itself. +- **State**: the scheduler decides what a fit cannot say for itself (``timeout``, + ``oom``, ``node_fail``, ``cancelled``); otherwise the status record's state and + failure class win over a bare exit code, and a task with neither is classified + from accounting alone. +- **Success**: a completed task of a stage with a ``success`` check counts as done only + if its zip exists with ``.completed`` and every listed member inside. +- **Unsubmitted** manifest objects of a submitted stage are reported as ``unsubmitted``. + +``collect`` writes the digest files into ``/campaign//`` and returns +the digest; it never submits, updates or cancels anything. +""" +import json +import logging +import os +import zipfile +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Tuple + +from autofit.campaign.digest import TaskOutcome, build_digest, write_digest +from autofit.campaign.proposals import propose_updates +from autofit.campaign.scheduler.base import TaskRecord +from autofit.campaign.scheduler.sacct import latest_per_task +from autofit.campaign.submit import ledger_indices, read_ledger +from autofit.non_linear.status.states import Product, RunState + +logger = logging.getLogger(__name__) + +SCHEDULER_DECIDES = {str(RunState.TIMEOUT), str(RunState.OOM), str(RunState.NODE_FAIL), "cancelled", "preempted"} + +StatusIndex = Dict[Tuple[str, Optional[int]], Dict] + + +def scan_status(root) -> StatusIndex: + """ + Every status record under ``root``, keyed by the ``(job_id, task_id)`` the fit + recorded; the newest record wins when a task wrote more than one. + """ + index: StatusIndex = {} + root = Path(root) + if not root.exists(): + return index + suffix = str(Product.STATUS) + for directory, _, files in os.walk(root): + for name in files: + if not name.endswith(suffix): + continue + path = Path(directory) / name + try: + document = json.loads(path.read_text()) + except (OSError, ValueError): + logger.warning(f"Unreadable status record {path}.") + continue + job = document.get("job") or {} + job_id = job.get("job_id") + if job_id is None: + continue + task_id = job.get("task_id") + key = (str(job_id), None if task_id is None else int(task_id)) + current = index.get(key) + if current is None or (document.get("updated") or "") >= (current.get("updated") or ""): + document["_path"] = str(path) + index[key] = document + return index + + +def merge_state(record: TaskRecord, status: Optional[Dict]) -> Tuple[str, Optional[str]]: + """ + ``(state, failure_class)`` of a task from its accounting record and status record. + """ + scheduler_state = str(record.state) + if scheduler_state in SCHEDULER_DECIDES: + return scheduler_state, None + if status is not None and status.get("state"): + state = status["state"] + if state == str(RunState.SKIPPED): + return str(RunState.COMPLETED), None + if state == str(RunState.TIMEOUT_PENDING) and scheduler_state in ("completed", "failed"): + # Signalled before the limit and then ended by it, or stopped. + return str(RunState.TIMEOUT), None + if state in (str(RunState.RUNNING), str(RunState.PENDING)) and scheduler_state in ("completed", "failed"): + # The process ended without a final status write (killed hard). + return scheduler_state, None if scheduler_state == "completed" else "unrecorded" + if state == str(RunState.TIMEOUT_PENDING): + return str(RunState.RUNNING), None + return state, status.get("failure_class") + if scheduler_state == str(RunState.FAILED): + return scheduler_state, "unrecorded" + return scheduler_state, None + + +def check_success(campaign, stage, index: int) -> Optional[bool]: + """ + Whether task ``index`` of ``stage`` passes the stage's ``success`` check (``None`` + when the stage declares none). + """ + success = stage.success + if not success.zip_complete: + return None + try: + path = campaign.path(success.zip_complete.format(**campaign.fields(index))) + except (KeyError, IndexError): + return False + zip_path = path if path.suffix == ".zip" else Path(f"{path}{Product.ZIP}") + try: + with zipfile.ZipFile(zip_path) as f: + names = set(f.namelist()) + except (OSError, zipfile.BadZipFile): + return False + if str(Product.COMPLETED) not in names: + return False + return all(member in names for member in success.members) + + +def outcome_of( + stage: str, + record: TaskRecord, + status: Optional[Dict], + index: Optional[int], + cpu_s_all_attempts: float, +) -> TaskOutcome: + state, failure_class = merge_state(record, status) + progress = (status or {}).get("progress") or {} + outputs = (status or {}).get("outputs") or {} + resources = (status or {}).get("resources") or {} + max_rss = record.max_rss_mb or resources.get("peak_rss_mb") + return TaskOutcome( + stage=stage, + key=record.key, + state=state, + index=index, + job_id=record.job_id, + failure_class=failure_class, + scheduler_state=record.scheduler_state, + elapsed_s=record.elapsed_s, + time_limit_s=record.time_limit_s, + cpus=record.cpus, + req_mem_mb=record.req_mem_mb, + max_rss_mb=max_rss, + total_cpu_s=record.total_cpu_s, + partition=record.partition, + gres=record.gres, + node=record.node, + attempts=max(record.attempts, (status or {}).get("attempt") or 1), + cpu_s_all_attempts=cpu_s_all_attempts, + bytes=outputs.get("bytes"), + fraction=progress.get("fraction"), + start=record.start.isoformat() if record.start else None, + end=record.end.isoformat() if record.end else None, + ) + + +def cpu_seconds_by_task(records: Iterable[TaskRecord]) -> Dict[str, float]: + """ + Allocated CPU-seconds (elapsed × CPUs) of every attempt, summed per task. + """ + totals: Dict[str, float] = {} + for record in records: + if record.elapsed_s and record.cpus: + totals[record.key] = totals.get(record.key, 0.0) + record.elapsed_s * record.cpus + return totals + + +def outcomes_for(campaign, scheduler, status: Optional[StatusIndex] = None) -> List[TaskOutcome]: + """ + The outcome of every task in the campaign's ledger, one per campaign index and stage + (the newest array covering it wins), plus ``unsubmitted`` rows. + """ + ledger = read_ledger(campaign) + if status is None: + status = scan_status(campaign.path(campaign.status_root)) + entries = {str(entry["job_id"]): entry for entry in ledger} + records = scheduler.query(list(entries)) + cpu_s = cpu_seconds_by_task(records) + + outcomes: Dict[Tuple[str, int], TaskOutcome] = {} + order: Dict[Tuple[str, int], int] = {} + position = {job_id: i for i, job_id in enumerate(entries)} + for record in latest_per_task(records): + entry = entries.get(str(record.job_id)) + if entry is None or record.task_id is None: + continue + index = entry["offset"] + record.task_id + stage_name = entry["stage"] + key = (stage_name, index) + rank = position[str(record.job_id)] + if key in order and order[key] > rank: + # An older array of a task already seen from its resubmit. + outcomes[key].attempts += record.attempts + outcomes[key].cpu_s_all_attempts += cpu_s.get(record.key, 0.0) + continue + outcome = outcome_of( + stage_name, + record, + status.get((str(record.job_id), record.task_id)), + index, + cpu_s.get(record.key, 0.0), + ) + previous = outcomes.get(key) + if previous is not None: + # A resubmit: the earlier array's attempts and CPU time count too. + outcome.attempts += previous.attempts + outcome.cpu_s_all_attempts += previous.cpu_s_all_attempts + if outcome.state == str(RunState.COMPLETED) and stage_name in campaign.stages: + outcome.success = check_success(campaign, campaign.stages[stage_name], index) + outcomes[key] = outcome + order[key] = rank + + submitted: Dict[str, set] = {} + for entry in ledger: + submitted.setdefault(entry["stage"], set()).update(ledger_indices(entry)) + manifest = set(campaign.indices()) + for stage_name in submitted: + for index in sorted(manifest - submitted[stage_name]): + outcomes[(stage_name, index)] = TaskOutcome( + stage=stage_name, key=f"-_{index}", state="unsubmitted", index=index + ) + return [outcomes[key] for key in sorted(outcomes)] + + +def collect(campaign, scheduler, write: bool = True) -> Dict: + """ + Collect the campaign's state into its digest (and write the digest files). + """ + outcomes = outcomes_for(campaign, scheduler) + site = campaign.site if campaign.site_name else None + partitions = sorted( + {name for stage in campaign.stages.values() for name in (stage.resources.partition or "").split(",") if name} + ) + try: + capacity = scheduler.capacity(partitions or None) + except Exception as exception: + logger.warning(f"Capacity snapshot failed: {exception}") + capacity = None + digest = build_digest(str(campaign.name), outcomes, site=site, capacity=capacity) + for name, stage_digest in digest["stages"].items(): + if name in campaign.stages: + updates = propose_updates( + [o for o in outcomes if o.stage == name], stage_digest, campaign.stages[name], site=site + ) + if updates: + stage_digest["update_pending"] = updates + if write: + write_digest(campaign.directory, digest, outcomes) + return digest diff --git a/autofit/campaign/digest.py b/autofit/campaign/digest.py new file mode 100644 index 000000000..d804a959e --- /dev/null +++ b/autofit/campaign/digest.py @@ -0,0 +1,422 @@ +""" +The campaign digest: what a campaign's tasks did, per stage, in one small document. + +Both the live collector (``autofit.campaign.collector``) and the retrospective mode +(``autofit.campaign.retro``) reduce their inputs to ``TaskOutcome``s and call +``build_digest``. ``write_digest`` writes: + +- ``digest.json``: the per-stage summary (counts by state and failure class, p50 / p95 / + max wall time and peak memory against the request, CPU efficiency, CPU-hours split + into successful and failed or repeated work, disk, ETA, drift flags and proposals); +- ``digest.md``: the same, as at most ``MAX_MD_BYTES`` of markdown, which is what an + agent reads; +- ``tasks.jsonl``: one row per task, for tools (``resubmit`` reads it); +- ``failed_.txt``: one task per line for every failure class present. + +Every proposal is a proposal: nothing here submits, updates or cancels a job. +""" +import json +import math +from collections import Counter, defaultdict +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Dict, Iterable, List, Optional + +from autofit.campaign.lint import gpu_partitions_of, split_partitions +from autofit.campaign.units import format_time, requests_gpu +from autofit.non_linear.status.states import RunState +from autofit.tools.util import open_atomic + +SCHEMA = 1 +MAX_MD_BYTES = 2048 + +FINISHED_BAD = ("timeout", "oom", "node_fail", "failed", "cancelled", "preempted") + +# Drift thresholds. +TIMEOUT_RATE = 0.05 +MEMORY_HIGH = 0.9 +MEMORY_LOW = 0.4 +CPU_EFFICIENCY_LOW = 0.5 +MIN_SAMPLE = 20 + + +@dataclass +class TaskOutcome: + """ + One task's outcome, from scheduler accounting joined with its status record. + Memory is in MB, times in seconds; ``cpu_s_all_attempts`` is the allocated + CPU time of every attempt (what the cluster spent). + """ + + stage: str + key: str + state: str + index: Optional[int] = None + job_id: Optional[str] = None + failure_class: Optional[str] = None + scheduler_state: Optional[str] = None + elapsed_s: Optional[float] = None + time_limit_s: Optional[float] = None + cpus: Optional[int] = None + req_mem_mb: Optional[float] = None + max_rss_mb: Optional[float] = None + total_cpu_s: Optional[float] = None + partition: Optional[str] = None + gres: Optional[str] = None + node: Optional[str] = None + attempts: int = 1 + cpu_s_all_attempts: float = 0.0 + bytes: Optional[int] = None + success: Optional[bool] = None + fraction: Optional[float] = None + start: Optional[str] = None + end: Optional[str] = None + + @property + def cpu_efficiency(self) -> Optional[float]: + if not self.elapsed_s or not self.cpus or self.total_cpu_s is None: + return None + return self.total_cpu_s / (self.elapsed_s * self.cpus) + + @property + def failure_list(self) -> Optional[str]: + """ + The ``failed_`` list this task belongs on, if any. + """ + if self.state == str(RunState.FAILED): + return self.failure_class or "unrecorded" + if self.state in FINISHED_BAD: + return self.state + if self.state == str(RunState.COMPLETED) and self.success is False: + return "success_check" + return None + + +def percentile(values: List[float], q: float) -> Optional[float]: + """ + The ``q``-th percentile (0-100) of ``values`` by linear interpolation. + """ + values = sorted(v for v in values if v is not None) + if not values: + return None + position = (len(values) - 1) * q / 100.0 + lower = math.floor(position) + upper = math.ceil(position) + if lower == upper: + return float(values[lower]) + return values[lower] + (values[upper] - values[lower]) * (position - lower) + + +def _median(values) -> Optional[float]: + return percentile(list(values), 50) + + +def _round(value, digits=0): + if value is None: + return None + return round(value, digits) if digits else int(round(value)) + + +def _summary(values: List[float]) -> Dict: + return { + "p50": _round(percentile(values, 50)), + "p95": _round(percentile(values, 95)), + "max": _round(max(values)) if values else None, + "n": len(values), + } + + +def _gpu_misuse(outcome: TaskOutcome, site) -> bool: + names = split_partitions(outcome.partition) + return bool(gpu_partitions_of(names, site=site)) and not requests_gpu(outcome.gres) + + +def stage_digest(outcomes: List[TaskOutcome], site=None) -> Dict: + """ + The digest of one stage's outcomes (see the module docstring). + """ + states = Counter(outcome.state for outcome in outcomes) + failure_classes = Counter( + outcome.failure_class or "unrecorded" + for outcome in outcomes + if outcome.state == str(RunState.FAILED) + ) + completed = [o for o in outcomes if o.state == str(RunState.COMPLETED)] + finished = [o for o in outcomes if o.state not in ("pending", "running")] + remaining = [o for o in outcomes if o.state in ("pending", "running")] + + walls = [o.elapsed_s for o in completed if o.elapsed_s is not None] + rss = [o.max_rss_mb for o in completed if o.max_rss_mb] + efficiency = [o.cpu_efficiency for o in completed if o.cpu_efficiency is not None] + time_request = _median(o.time_limit_s for o in outcomes if o.time_limit_s) + mem_request = _median(o.req_mem_mb for o in outcomes if o.req_mem_mb) + cpus = _median(o.cpus for o in outcomes if o.cpus) + + cpu_h_success = sum(o.elapsed_s * o.cpus for o in completed if o.elapsed_s and o.cpus) / 3600 + cpu_h_all = sum(o.cpu_s_all_attempts for o in outcomes) / 3600 + + digest = { + "tasks": len(outcomes), + "states": dict(sorted(states.items())), + "failure_classes": dict(sorted(failure_classes.items())), + "success_check_failed": sum(1 for o in completed if o.success is False), + "attempts": sum(o.attempts for o in outcomes), + "request": { + "cpus": _round(cpus), + "mem_mb": _round(mem_request), + "time_s": _round(time_request), + "partitions": sorted({o.partition for o in outcomes if o.partition}), + }, + "wall_s": _summary(walls), + "rss_mb": _summary(rss), + "cpu_efficiency_p50": _round(_median(efficiency), 3), + "cpu_h": { + "successful": _round(cpu_h_success, 1), + "all_attempts": _round(cpu_h_all, 1), + "failed_or_repeated": _round(max(cpu_h_all - cpu_h_success, 0.0), 1), + }, + } + + misuse = [o for o in outcomes if _gpu_misuse(o, site)] + if misuse: + digest["gpu_partition_cpu_tasks"] = { + "tasks": len(misuse), + "cpu_h": _round(sum(o.cpu_s_all_attempts for o in misuse) / 3600, 1), + } + + sizes = [o.bytes for o in completed if o.bytes] + if sizes: + mean = sum(sizes) / len(sizes) + digest["disk"] = { + "bytes_used": int(sum(o.bytes or 0 for o in outcomes)), + "bytes_per_completed": int(mean), + "bytes_forecast_remaining": int(mean * len(remaining)), + } + + running_cpus = sum(o.cpus or 0 for o in outcomes if o.state == "running") + p50 = digest["wall_s"]["p50"] + if remaining and running_cpus and p50 and cpus: + remaining_cpu_s = 0.0 + for o in remaining: + done = (o.fraction or 0.0) if o.state == "running" else 0.0 + remaining_cpu_s += p50 * (1 - min(done, 1.0)) * (o.cpus or cpus) + digest["eta_s"] = _round(remaining_cpu_s / running_cpus) + + digest["flags"] = _flags(digest, outcomes, completed, finished, remaining) + return digest + + +def _flags(digest, outcomes, completed, finished, remaining) -> List[Dict]: + flags = [] + request = digest["request"] + timeouts = sum(1 for o in finished if o.state == str(RunState.TIMEOUT)) + if finished and timeouts / len(finished) >= TIMEOUT_RATE: + flags.append( + { + "flag": "timeouts", + "detail": f"{timeouts}/{len(finished)} finished tasks hit the time limit", + "propose": "raise the time limit of pending tasks (p95 + 25 %) or resubmit timeouts", + } + ) + rss_p95 = digest["rss_mb"]["p95"] + if rss_p95 and request["mem_mb"] and len(completed) >= MIN_SAMPLE: + ratio = rss_p95 / request["mem_mb"] + if ratio >= MEMORY_HIGH: + flags.append( + { + "flag": "memory_tight", + "detail": f"p95 peak memory is {ratio:.0%} of the request", + "propose": f"mem {_round(rss_p95 * 1.5)} MB per task", + } + ) + elif ratio <= MEMORY_LOW: + flags.append( + { + "flag": "memory_slack", + "detail": f"p95 peak memory is {ratio:.0%} of the request (strands cores)", + "propose": f"mem {_round(rss_p95 * 1.5)} MB per task", + } + ) + efficiency = digest["cpu_efficiency_p50"] + if efficiency is not None and efficiency < CPU_EFFICIENCY_LOW and len(completed) >= MIN_SAMPLE: + flags.append( + { + "flag": "cpu_efficiency", + "detail": f"median CPU efficiency {efficiency:.0%}", + "propose": "fewer CPUs per task", + } + ) + if digest.get("gpu_partition_cpu_tasks"): + flags.append( + { + "flag": "cpu_on_gpu_partition", + "detail": f"{digest['gpu_partition_cpu_tasks']['tasks']} CPU-only tasks ran on a GPU partition", + "propose": "never again: the partition lint refuses this at submit", + } + ) + if digest["success_check_failed"]: + flags.append( + { + "flag": "success_check", + "detail": f"{digest['success_check_failed']} completed tasks fail the stage's success check", + "propose": "inspect failed_success_check.txt", + } + ) + return flags + + +def build_digest( + name: str, + outcomes: Iterable[TaskOutcome], + site=None, + capacity: Optional[Dict] = None, + extra: Optional[Dict] = None, + now: Optional[datetime] = None, +) -> Dict: + """ + The digest of a campaign's outcomes, stage by stage, plus totals and a capacity + snapshot. + """ + outcomes = list(outcomes) + by_stage: Dict[str, List[TaskOutcome]] = defaultdict(list) + for outcome in outcomes: + by_stage[outcome.stage].append(outcome) + stages = {stage: stage_digest(items, site=site) for stage, items in by_stage.items()} + + totals_states = Counter(o.state for o in outcomes) + digest = { + "schema": SCHEMA, + "campaign": name, + "updated": (now or datetime.now(timezone.utc)).strftime("%Y-%m-%dT%H:%M:%SZ"), + "totals": { + "tasks": len(outcomes), + "states": dict(sorted(totals_states.items())), + "cpu_h_all_attempts": _round(sum(o.cpu_s_all_attempts for o in outcomes) / 3600, 1), + "cpu_h_successful": _round( + sum(s["cpu_h"]["successful"] or 0 for s in stages.values()), 1 + ), + }, + "stages": stages, + } + if capacity: + digest["capacity"] = { + name: { + "cpus_idle": c.cpus_idle, + "cpus_total": c.cpus_total, + "pending_gpu_jobs": c.pending_gpu_jobs, + } + for name, c in capacity.items() + } + if extra: + digest.update(extra) + return digest + + +def _hours(seconds) -> str: + return "-" if seconds is None else format_time(seconds) + + +def digest_markdown(digest: Dict, max_bytes: int = MAX_MD_BYTES) -> str: + """ + ``digest`` as markdown of at most ``max_bytes`` bytes: a header, one table row per + stage, then flags; flags are dropped from the end, then stages, until it fits. + """ + totals = digest["totals"] + header = [ + f"# {digest['campaign']} — {digest['updated']}", + "", + f"{totals['tasks']} tasks: " + + ", ".join(f"{k} {v}" for k, v in totals["states"].items()) + + f". CPU-h {totals['cpu_h_all_attempts']} (successful {totals['cpu_h_successful']}).", + ] + if digest.get("period"): + header.append(f"Period {digest['period']['first_submit']} → {digest['period']['last_end']}.") + rows = [ + "", + "| stage | done/all | fail | wall p50/p95 | req time | RSS p95/req MB | eff | CPU-h ok/all |", + "|---|---|---|---|---|---|---|---|", + ] + flags = [] + for name, stage in digest["stages"].items(): + states = stage["states"] + bad = sum(states.get(k, 0) for k in FINISHED_BAD) + rows.append( + f"| {name} | {states.get('completed', 0)}/{stage['tasks']} | {bad} | " + f"{_hours(stage['wall_s']['p50'])}/{_hours(stage['wall_s']['p95'])} | " + f"{_hours(stage['request']['time_s'])} | " + f"{stage['rss_mb']['p95'] or '-'}/{stage['request']['mem_mb'] or '-'} | " + f"{stage['cpu_efficiency_p50'] if stage['cpu_efficiency_p50'] is not None else '-'} | " + f"{stage['cpu_h']['successful']}/{stage['cpu_h']['all_attempts']} |" + ) + for flag in stage["flags"]: + flags.append(f"- {name}: {flag['flag']} — {flag['detail']}; propose {flag['propose']}") + if digest.get("capacity"): + rows.append("") + rows.append( + "Idle CPUs: " + + ", ".join(f"{k} {v['cpus_idle']}/{v['cpus_total']}" for k, v in digest["capacity"].items()) + ) + flag_block = ["", "Flags:"] + flags if flags else [] + + def render(rows_, flags_): + return "\n".join(header + rows_ + flags_) + "\n" + + text = render(rows, flag_block) + while len(text.encode()) > max_bytes and len(flag_block) > 2: + flag_block = flag_block[:-1] + text = render(rows, flag_block + ["- (more flags in digest.json)"]) + if len(text.encode()) > max_bytes: + flag_block = [] + while len(text.encode()) > max_bytes and len(rows) > 4: + rows = rows[:-1] + text = render(rows + ["| … | more stages in digest.json |"], flag_block) + text = text if len(text.encode()) <= max_bytes else text.encode()[: max_bytes - 4].decode(errors="ignore") + "\n…\n" + return text + + +def outcome_row(outcome: TaskOutcome) -> Dict: + return {key: value for key, value in asdict(outcome).items() if value is not None} + + +def read_outcomes(path) -> List[TaskOutcome]: + """ + The ``TaskOutcome``s of a ``tasks.jsonl``. + """ + outcomes = [] + for line in Path(path).read_text().splitlines(): + if line.strip(): + outcomes.append(TaskOutcome(**json.loads(line))) + return outcomes + + +def write_digest(directory, digest: Dict, outcomes: Iterable[TaskOutcome]) -> Path: + """ + Write ``digest.json``, ``digest.md``, ``tasks.jsonl`` and the ``failed_.txt`` + lists into ``directory`` (atomically, each), removing lists no longer current. + """ + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + outcomes = list(outcomes) + + with open_atomic(directory / "digest.json", "w") as f: + json.dump(digest, f, indent=1, default=str) + with open_atomic(directory / "digest.md", "w") as f: + f.write(digest_markdown(digest)) + with open_atomic(directory / "tasks.jsonl", "w") as f: + for outcome in outcomes: + f.write(json.dumps(outcome_row(outcome), default=str) + "\n") + + lists: Dict[str, List[str]] = defaultdict(list) + for outcome in outcomes: + name = outcome.failure_list + if name: + index = "-" if outcome.index is None else outcome.index + lists[name].append(f"{outcome.stage}\t{index}\t{outcome.key}") + for stale in directory.glob("failed_*.txt"): + if stale.stem[len("failed_"):] not in lists: + stale.unlink() + for name, lines in lists.items(): + with open_atomic(directory / f"failed_{name}.txt", "w") as f: + f.write("\n".join(sorted(lines)) + "\n") + return directory diff --git a/autofit/campaign/proposals.py b/autofit/campaign/proposals.py new file mode 100644 index 000000000..bebe138c7 --- /dev/null +++ b/autofit/campaign/proposals.py @@ -0,0 +1,201 @@ +""" +Resubmit and pending-update proposals, sized from the tasks' own measurements. + +A proposal is only ever written down: ``python -m autofit.campaign resubmit`` writes a +``resubmit__.json`` and prints the command that would act on it +(``submit --proposal ``), which a human runs once they approve it (ruling F5). + +Sizing, per the stage's ``retry`` policy (defaults in brackets): + +- ``timeout`` [``time: p95+25%``]: the larger of the completed tasks' p95 wall time and + the longest timed-out run, plus 25 %, capped at the partition's ``max_time``; +- ``oom`` [``mem: peak*1.5``]: the larger of the OOM tasks' peak memory and their + request, times 1.5, as ``--mem-per-cpu``, capped at the partition's memory per node; +- ``node_fail`` / ``preempted``: the same request again; +- a Python failure (``exception``, ``bad_input``) is not resubmitted: its cause needs + fixing first; ``missing_seed`` / ``upstream_incomplete`` follow the upstream stage. + +A task already tried ``max`` more times than its first attempt is left out, with the +reason. +""" +import copy +import re +from typing import Dict, List + +from autofit.campaign.digest import TaskOutcome, percentile +from autofit.campaign.lint import split_partitions +from autofit.campaign.units import array_spec, format_time, parse_time + +RESUBMITTABLE = {"timeout", "oom", "node_fail", "preempted"} +NOT_RESUBMITTED = { + "exception": "a Python exception: fix the cause, then resubmit", + "bad_input": "invalid inputs: fix the data or settings first", + "missing_seed": "the upstream result is missing: resubmit the upstream stage", + "upstream_incomplete": "the upstream result is incomplete: resubmit the upstream stage", + "unrecorded": "failed without a status record: read the job log first", + "cancelled": "cancelled (by a user or an unmet dependency): resubmit the upstream stage", +} + +_TIME_RULE = re.compile(r"^\s*p(\d+)\s*\+\s*(\d+)\s*%\s*$") +_MEM_RULE = re.compile(r"^\s*peak\s*\*\s*([0-9.]+)\s*$") + + +def _site_limits(resources, site): + max_time = None + mem_node = None + if site is None: + return max_time, mem_node + for name in split_partitions(resources.partition): + partition = site.partitions.get(name) + if partition is None: + continue + if partition.max_time: + limit = parse_time(partition.max_time) + max_time = limit if max_time is None else min(max_time, limit) + if partition.mem_per_node_mb: + mem_node = partition.mem_per_node_mb if mem_node is None else min(mem_node, partition.mem_per_node_mb) + return max_time, mem_node + + +def propose_resubmit( + stage, + failure: str, + outcomes: List[TaskOutcome], + site=None, +) -> Dict: + """ + The resubmit proposal for ``stage``'s tasks of failure class ``failure``. + + Parameters + ---------- + stage + The campaign ``Stage`` (its resources and ``retry`` policy). + failure + ``timeout``, ``oom``, ``node_fail``, ``preempted`` (or a class that is never + resubmitted, for which the proposal says why). + outcomes + The stage's outcomes (all of them: completed tasks size a timeout). + """ + tasks = [o for o in outcomes if o.stage == stage.name and o.failure_list == failure] + proposal = { + "stage": stage.name, + "class": failure, + "tasks": len(tasks), + "indices": None, + "resources": None, + "changes": {}, + "excluded": [], + "reason": None, + } + if not tasks: + proposal["reason"] = "no tasks of this class" + return proposal + if failure not in RESUBMITTABLE: + proposal["reason"] = NOT_RESUBMITTED.get(failure, "not resubmitted automatically") + return proposal + + policy = stage.retry.get(failure) + if policy in ("none", None) and failure in stage.retry: + proposal["reason"] = f"the stage's retry policy for {failure} is none" + return proposal + policy = policy or {} + maximum = policy.get("max") + + eligible = [] + for task in tasks: + if maximum is not None and task.attempts > int(maximum): + proposal["excluded"].append( + {"key": task.key, "reason": f"{task.attempts} attempts, retry max {maximum}"} + ) + elif task.index is None: + proposal["excluded"].append({"key": task.key, "reason": "no campaign index"}) + else: + eligible.append(task) + + resources = copy.deepcopy(stage.resources) + max_time, mem_node = _site_limits(resources, site) + + if failure == "timeout": + rule = _TIME_RULE.match(str(policy.get("time", "p95+25%"))) + if rule is None: + raise ValueError(f"Unknown timeout rule {policy.get('time')!r}; use pNN+MM%.") + q, extra = int(rule.group(1)), int(rule.group(2)) + completed = [o.elapsed_s for o in outcomes if o.stage == stage.name and o.state == "completed" and o.elapsed_s] + base = max( + [percentile(completed, q) or 0.0] + [t.elapsed_s or 0.0 for t in tasks] + ) + new_time = base * (1 + extra / 100.0) + if max_time is not None and new_time > max_time: + new_time = max_time + proposal["changes"]["note"] = f"capped at the partition max_time {format_time(max_time)}" + old = resources.time_s + if old is not None and new_time <= old: + proposal["changes"]["note"] = ( + "cannot raise the time limit further; the tasks need to resume from " + "their checkpoints, so resubmitting continues them" + ) + new_time = old + resources.time_s = int(new_time) + proposal["changes"]["time"] = [format_time(old), format_time(resources.time_s)] + + elif failure == "oom": + rule = _MEM_RULE.match(str(policy.get("mem", "peak*1.5"))) + if rule is None: + raise ValueError(f"Unknown OOM rule {policy.get('mem')!r}; use peak*X.") + factor = float(rule.group(1)) + peak = max(max(t.max_rss_mb or 0.0, t.req_mem_mb or 0.0) for t in tasks) + new_mem = peak * factor + if mem_node is not None and new_mem > mem_node: + new_mem = mem_node + proposal["changes"]["note"] = f"capped at the partition's {mem_node} MB per node" + old = resources.mem_mb + resources.mem_per_cpu_mb = int(-(-new_mem // resources.cpus)) + proposal["changes"]["mem_mb"] = [old, resources.mem_mb] + + if not eligible: + proposal["reason"] = "every task has exhausted its retries" + return proposal + + proposal["indices"] = array_spec([t.index for t in eligible]) + proposal["tasks"] = len(eligible) + proposal["resources"] = { + key: value for key, value in vars(resources).items() if value is not None + } + return proposal + + +def propose_updates(outcomes: List[TaskOutcome], digest_stage: Dict, stage, site=None) -> List[Dict]: + """ + ``scontrol update`` proposals for a stage's arrays that still have pending tasks, + from its drift flags: a raised time limit after timeouts, a corrected memory + request after tight or slack memory. + """ + pending_jobs = sorted({o.job_id for o in outcomes if o.state == "pending" and o.job_id}) + if not pending_jobs: + return [] + flags = {flag["flag"] for flag in digest_stage.get("flags", [])} + fields: Dict = {} + max_time, mem_node = _site_limits(stage.resources, site) + if "timeouts" in flags and digest_stage["wall_s"]["p95"]: + base = max(digest_stage["wall_s"]["p95"], max((o.elapsed_s or 0) for o in outcomes if o.state == "timeout")) + new_time = int(base * 1.25) + if max_time is not None: + new_time = min(new_time, max_time) + fields["time"] = format_time(new_time) + if flags & {"memory_tight", "memory_slack"} and digest_stage["rss_mb"]["p95"]: + new_mem = digest_stage["rss_mb"]["p95"] * 1.5 + if mem_node is not None: + new_mem = min(new_mem, mem_node) + fields["mem_per_cpu_mb"] = int(-(-new_mem // (stage.resources.cpus or 1))) + if not fields: + return [] + mapping = {"time": "TimeLimit", "mem_per_cpu_mb": "MinMemoryCPU"} + return [ + { + "job_id": job_id, + "fields": fields, + "command": f"scontrol update JobId={job_id} " + + " ".join(f"{mapping[k]}={v}" for k, v in fields.items()), + } + for job_id in pending_jobs + ] diff --git a/autofit/campaign/retro.py b/autofit/campaign/retro.py new file mode 100644 index 000000000..351aaccd8 --- /dev/null +++ b/autofit/campaign/retro.py @@ -0,0 +1,175 @@ +""" +Retrospective mode: the digest of a finished campaign from a ``sacct`` dump alone. + +A campaign that ran before ``campaign.yaml`` existed (the Euclid DR1 campaign) has no +job ledger and few status records, but the scheduler kept accounting for every attempt. +``retro`` reads one ``sacct --parsable2 --units=M --duplicates`` dump, selects the +campaign's jobs by working directory and / or job name, names each job's stage from its +job name, optionally joins status records, and builds the same digest as the live +collector, plus the campaign's period and peak concurrency. + +What it can and cannot say: each row is a *scheduler task*, not an object. A task that +timed out in one array and was resubmitted in another is two tasks here, because +nothing in accounting links them; the digest therefore reports task outcomes and +CPU-hours, never "objects done". Pending-array placeholder lines are counted as +``pending`` once per line. +""" +import re +from collections import Counter +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, Tuple + +from autofit.campaign.collector import cpu_seconds_by_task, outcome_of, scan_status +from autofit.campaign.digest import TaskOutcome, build_digest +from autofit.campaign.scheduler import sacct +from autofit.campaign.scheduler.base import TaskRecord + + +def under(path: Optional[str], prefixes: Sequence[str]) -> bool: + """ + Whether ``path`` is one of ``prefixes`` or inside one (a path boundary, so + ``/a/euclid_dr1`` does not match ``/a/euclid_dr1_old``). + """ + if not prefixes: + return True + if not path: + return False + path = path.rstrip("/") + for prefix in prefixes: + prefix = prefix.rstrip("/") + if path == prefix or path.startswith(prefix + "/"): + return True + return False + + +def stage_of(name: Optional[str], stage_regex: Optional[str], other: Optional[str] = None) -> str: + """ + The stage named by a job name: the regex's ``stage`` group (or first group) when + it matches, else ``other`` when given, else the job name itself. + """ + if not name: + return other or "unnamed" + if stage_regex: + match = re.search(stage_regex, name) + if match: + groups = match.groupdict() + if groups.get("stage"): + return groups["stage"] + if match.groups(): + return match.group(1) + if other: + return other + return name + + +def select( + records: Iterable[TaskRecord], + workdir_prefixes: Sequence[str] = (), + name_regex: Optional[str] = None, +) -> List[TaskRecord]: + pattern = re.compile(name_regex) if name_regex else None + return [ + record + for record in records + if under(record.workdir, workdir_prefixes) + and (pattern is None or pattern.search(record.name or "")) + ] + + +def peak_concurrency(records: Iterable[TaskRecord]) -> Tuple[int, Optional[str]]: + """ + The most CPUs the campaign held at once, and when (from start / end times). + """ + events = [] + for record in records: + if record.start and record.end and record.cpus and record.end > record.start: + events.append((record.start, record.cpus)) + events.append((record.end, -record.cpus)) + events.sort(key=lambda event: (event[0], event[1])) + current = peak = 0 + when = None + for stamp, delta in events: + current += delta + if current > peak: + peak, when = current, stamp + return peak, when.isoformat() if when else None + + +def retro_outcomes( + records: List[TaskRecord], + stage_regex: Optional[str] = None, + status_root: Optional[str] = None, + other_stage: Optional[str] = None, +) -> List[TaskOutcome]: + status = scan_status(status_root) if status_root else {} + cpu_s = cpu_seconds_by_task(records) + outcomes = [] + for record in sacct.latest_per_task(records): + outcomes.append( + outcome_of( + stage_of(record.name, stage_regex, other_stage), + record, + status.get((str(record.job_id), record.task_id)), + None, + cpu_s.get(record.key, 0.0), + ) + ) + return outcomes + + +def retro( + sacct_path, + workdir_prefixes: Sequence[str] = (), + name_regex: Optional[str] = None, + stage_regex: Optional[str] = None, + status_root: Optional[str] = None, + site=None, + name: str = "retro", + other_stage: Optional[str] = None, +) -> Tuple[Dict, List[TaskOutcome]]: + """ + The digest and outcomes of the campaign selected from the ``sacct`` dump at + ``sacct_path`` (read only). + + Parameters + ---------- + workdir_prefixes + Keep jobs whose ``WorkDir`` is one of these directories or inside one. + name_regex + Keep jobs whose name matches. + stage_regex + Name each job's stage from its job name (``stage`` group or first group). + other_stage + The stage of every job ``stage_regex`` does not match (default: its own name). + status_root + Join status records found under this directory. + site + The ``autonerves.site_config.Site`` (to recognise GPU-only partitions). + """ + records = sacct.parse(Path(sacct_path).read_text()) + selected = select(records, workdir_prefixes, name_regex) + outcomes = retro_outcomes(selected, stage_regex, status_root, other_stage) + + submits = [r.submit for r in selected if r.submit] + ends = [r.end for r in selected if r.end] + peak, peak_at = peak_concurrency(selected) + extra = { + "mode": "retro", + "source": { + "sacct": Path(sacct_path).name, + "rows": len(records), + "allocations_selected": len(selected), + "workdir_prefixes": list(workdir_prefixes), + "name_regex": name_regex, + "stage_regex": stage_regex, + "other_stage": other_stage, + "jobs": len({r.job_id for r in selected}), + }, + "period": { + "first_submit": min(submits).isoformat() if submits else None, + "last_end": max(ends).isoformat() if ends else None, + }, + "peak_cpus": {"cpus": peak, "at": peak_at}, + "partitions": dict(Counter(r.partition for r in selected if r.partition)), + } + return build_digest(name, outcomes, site=site, extra=extra), outcomes diff --git a/test_autofit/campaign/test_collector.py b/test_autofit/campaign/test_collector.py new file mode 100644 index 000000000..b9a1451f9 --- /dev/null +++ b/test_autofit/campaign/test_collector.py @@ -0,0 +1,168 @@ +""" +The collector end to end on the FakeScheduler: injected timeout, OOM, exception and +missing-seed tasks come out in the right classes, lists and proposals. +""" +import json +import zipfile + +import pytest + +from autofit.campaign import Campaign, collect, propose_resubmit +from autofit.campaign.__main__ import main +from autofit.campaign.digest import MAX_MD_BYTES, read_outcomes +from autofit.campaign.scheduler import FakeScheduler, PartitionCapacity +from autofit.campaign.submit import submit + +LIMIT = 4 * 3600 + + +def _outcomes(stage, index, attempt): + if stage != "vis_lp": + return None + if index == 1: + return {"scheduler_state": "TIMEOUT", "elapsed_s": LIMIT, "max_rss_mb": 5000} + if index == 2: + return {"scheduler_state": "OUT_OF_MEMORY", "elapsed_s": 600, "max_rss_mb": 12288} + if index in (3, 5): + return {"scheduler_state": "FAILED", "elapsed_s": 60} + return {"elapsed_s": 3000 + 100 * index, "max_rss_mb": 6000 + 10 * index} + + +def _status(root, job_id, task_id, state, failure_class=None): + path = root / "output" / f"{job_id}_{task_id}.status.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps( + { + "schema": 1, + "state": state, + "failure_class": failure_class, + "attempt": 1, + "job": {"job_id": job_id, "task_id": task_id}, + "outputs": {"bytes": 1000}, + "updated": "2026-10-30T00:00:00Z", + } + ) + ) + + +def _zip(root, tile, members=("files/samples_summary.json", ".completed")): + path = root / "output" / "dr1" / tile / "vis_lp.zip" + path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(path, "w") as f: + for member in members: + f.writestr(member, "{}") + + +@pytest.fixture(name="collected") +def make_collected(campaign_file, ral): + root = campaign_file.parent + campaign = Campaign.load(campaign_file) + capacity = {"ral": PartitionCapacity("ral", cpus_idle=52, cpus_total=252, pending_gpu_jobs=0)} + scheduler = FakeScheduler(outcomes=_outcomes, capacity=capacity, site=ral) + entries = submit(campaign, scheduler, stages=["vis_lp"]) + scheduler.run() + jobs = {entry["offset"]: entry["job_id"] for entry in entries} + _status(root, jobs[0], 3, "failed", "exception") + _status(root, jobs[4], 1, "failed", "missing_seed") + for index in (0, 4, 6, 7, 8, 9): + _zip(root, f"Tile{index:03d}") + # Index 0 lacks a required member: completed by the scheduler, not by the check. + _zip(root, "Tile000", members=(".completed",)) + # vis_pix waits on vis_lp and is not run yet: pending tasks for update proposals. + submit(campaign, scheduler, stages=["vis_pix"]) + return campaign, scheduler, collect(campaign, scheduler) + + +def test_states_and_classes(collected): + campaign, _, digest = collected + vis_lp = digest["stages"]["vis_lp"] + assert vis_lp["states"] == {"completed": 6, "failed": 2, "oom": 1, "timeout": 1} + assert vis_lp["failure_classes"] == {"exception": 1, "missing_seed": 1} + assert vis_lp["success_check_failed"] == 1 + assert digest["stages"]["vis_pix"]["states"] == {"pending": 10} + assert digest["capacity"]["ral"]["cpus_idle"] == 52 + assert vis_lp["wall_s"]["max"] == 3900 and vis_lp["wall_s"]["n"] == 6 + assert vis_lp["cpu_h"]["all_attempts"] > vis_lp["cpu_h"]["successful"] + + +def test_files(collected): + campaign, _, digest = collected + directory = campaign.directory + lists = {p.name: p.read_text().split("\n")[0] for p in directory.glob("failed_*.txt")} + assert set(lists) == { + "failed_timeout.txt", + "failed_oom.txt", + "failed_exception.txt", + "failed_missing_seed.txt", + "failed_success_check.txt", + } + assert lists["failed_timeout.txt"].startswith("vis_lp\t1\t") + assert lists["failed_missing_seed.txt"].startswith("vis_lp\t5\t") + md = (directory / "digest.md").read_text() + assert len(md.encode()) <= MAX_MD_BYTES + assert "| vis_lp | 6/10 | 4 |" in md + assert json.loads((directory / "digest.json").read_text())["campaign"] == "demo" + assert len(read_outcomes(directory / "tasks.jsonl")) == 20 + + +def test_proposals(collected, ral): + campaign, _, _ = collected + outcomes = read_outcomes(campaign.directory / "tasks.jsonl") + stage = campaign.stages["vis_lp"] + + timeout = propose_resubmit(stage, "timeout", outcomes, site=ral) + assert timeout["indices"] == "1" + assert timeout["changes"]["time"] == ["04:00:00", "05:00:00"] + + oom = propose_resubmit(stage, "oom", outcomes, site=ral) + assert oom["indices"] == "2" + assert oom["changes"]["mem_mb"] == [12288, 18432] + assert oom["resources"]["mem_per_cpu_mb"] == 4608 + + exception = propose_resubmit(stage, "exception", outcomes) + assert exception["indices"] is None and "fix the cause" in exception["reason"] + seed = propose_resubmit(stage, "missing_seed", outcomes) + assert seed["indices"] is None and "upstream" in seed["reason"] + + +def test_retry_max_excludes(collected): + campaign, _, _ = collected + outcomes = read_outcomes(campaign.directory / "tasks.jsonl") + for outcome in outcomes: + if outcome.state == "timeout": + outcome.attempts = 2 + proposal = propose_resubmit(campaign.stages["vis_lp"], "timeout", outcomes) + assert proposal["indices"] is None and proposal["excluded"][0]["reason"] == "2 attempts, retry max 1" + + +def test_resubmit_round_trip(collected, monkeypatch, capsys, ral): + campaign, scheduler, _ = collected + import autofit.campaign.scheduler as schedulers + + monkeypatch.setattr(schedulers, "scheduler_for", lambda campaign, runner=None: scheduler) + path = str(campaign.source) + assert main(["resubmit", path, "--stage", "vis_lp", "--class", "timeout"]) == 0 + out = capsys.readouterr().out + assert "Proposal only" in out + # Nothing was submitted by the proposal. + jobs_before = len(scheduler.requests) + assert main(["submit", path, "--proposal", str(campaign.directory / "resubmit_vis_lp_timeout.json")]) == 0 + assert len(scheduler.requests) == jobs_before + 1 + request = list(scheduler.requests.values())[-1] + assert request.indices == [1] and request.resources.time_s == 5 * 3600 + + scheduler.run() + assert main(["status", path]) == 0 + digest = json.loads((campaign.directory / "digest.json").read_text()) + vis_lp = digest["stages"]["vis_lp"] + # The resubmitted task 1 timed out again: one task, two attempts. + assert vis_lp["tasks"] == 10 and vis_lp["attempts"] == 11 + assert not (campaign.directory / "failed_none.txt").exists() + + +def test_update_pending_proposals(collected): + campaign, _, digest = collected + assert "update_pending" not in digest["stages"]["vis_pix"] + vis_lp = digest["stages"]["vis_lp"] + assert {flag["flag"] for flag in vis_lp["flags"]} >= {"timeouts", "success_check"} diff --git a/test_autofit/campaign/test_digest.py b/test_autofit/campaign/test_digest.py new file mode 100644 index 000000000..d78f7984e --- /dev/null +++ b/test_autofit/campaign/test_digest.py @@ -0,0 +1,63 @@ +from autofit.campaign.digest import ( + MAX_MD_BYTES, + TaskOutcome, + build_digest, + digest_markdown, + percentile, + write_digest, +) +from autofit.campaign.proposals import propose_updates +from autofit.campaign.spec import Stage, Resources + + +def test_percentile(): + assert percentile([1, 2, 3, 4], 50) == 2.5 + assert percentile([10], 95) == 10 + assert percentile([], 50) is None + assert percentile(list(range(101)), 95) == 95 + + +def _outcome(i, stage="fit", state="completed", **kwargs): + defaults = dict(job_id="1", elapsed_s=1000 + i, cpus=4, total_cpu_s=(1000 + i) * 4 * 0.8, req_mem_mb=16000, + max_rss_mb=4000, time_limit_s=7200, partition="ral", cpu_s_all_attempts=(1000 + i) * 4) + defaults.update(kwargs) + return TaskOutcome(stage=stage, key=f"1_{i}", state=state, index=i, **defaults) + + +def test_stage_statistics_and_slack_flag(): + outcomes = [_outcome(i) for i in range(30)] + [_outcome(99, state="pending", job_id="2")] + digest = build_digest("c", outcomes) + stage = digest["stages"]["fit"] + assert stage["wall_s"] == {"p50": 1014, "p95": 1028, "max": 1029, "n": 30} + assert stage["cpu_efficiency_p50"] == 0.8 + assert [f["flag"] for f in stage["flags"]] == ["memory_slack"] + updates = propose_updates(outcomes, stage, Stage("fit", "x", Resources(cpus=4))) + assert updates == [{"job_id": "2", "fields": {"mem_per_cpu_mb": 1500}, + "command": "scontrol update JobId=2 MinMemoryCPU=1500"}] + + +def test_gpu_partition_misuse(ral): + outcomes = [_outcome(i, partition="gpu") for i in range(3)] + [ + _outcome(5, partition="gpu", gres="gres/gpu=1") + ] + stage = build_digest("c", outcomes, site=ral)["stages"]["fit"] + assert stage["gpu_partition_cpu_tasks"]["tasks"] == 3 + assert "cpu_on_gpu_partition" in [f["flag"] for f in stage["flags"]] + + +def test_markdown_capped(): + outcomes = [] + for s in range(40): + outcomes += [_outcome(i, stage=f"a_very_long_stage_name_number_{s}", state="timeout") for i in range(3)] + text = digest_markdown(build_digest("c" * 50, outcomes)) + assert len(text.encode()) <= MAX_MD_BYTES + assert "more stages in digest.json" in text + + +def test_write_digest_replaces_stale_lists(tmp_path): + outcomes = [_outcome(0, state="timeout")] + write_digest(tmp_path, build_digest("c", outcomes), outcomes) + assert (tmp_path / "failed_timeout.txt").exists() + outcomes = [_outcome(0)] + write_digest(tmp_path, build_digest("c", outcomes), outcomes) + assert not (tmp_path / "failed_timeout.txt").exists() diff --git a/test_autofit/campaign/test_local.py b/test_autofit/campaign/test_local.py index 7fa5ce43c..58fe98558 100644 --- a/test_autofit/campaign/test_local.py +++ b/test_autofit/campaign/test_local.py @@ -1,4 +1,3 @@ -import sys import textwrap from autofit.campaign import Campaign diff --git a/test_autofit/campaign/test_retro.py b/test_autofit/campaign/test_retro.py new file mode 100644 index 000000000..2e7070938 --- /dev/null +++ b/test_autofit/campaign/test_retro.py @@ -0,0 +1,66 @@ +from autofit.campaign.__main__ import main +from autofit.campaign.retro import peak_concurrency, retro, stage_of, under +from autofit.campaign.scheduler.sacct import parse +from test_autofit.campaign.test_sacct import HEADER + +ROWS = [ + "1_0|1|euclid_dr1_vis_lp_n5k_p01|ral|COMPLETED|0:0|2026-09-01T00:00:00|2026-09-01T00:00:00|2026-09-01T02:00:00|02:00:00|04:00:00|4|12288M|||07:00:00|08:00:00|1|n1|cpu=4|cpu=4|/m/euclid_dr1/hpc/batch_cpu", + "1_0.batch|1.batch|batch||COMPLETED|0:0|2026-09-01T00:00:00|2026-09-01T00:00:00|2026-09-01T02:00:00|02:00:00||4||6000M|6000M|07:00:00|08:00:00|1|n1||cpu=4|", + "1_1|2|euclid_dr1_vis_lp_n5k_p01|ral|TIMEOUT|0:0|2026-09-01T00:00:00|2026-09-01T01:00:00|2026-09-01T05:00:00|04:00:00|04:00:00|4|12288M|||15:00:00|16:00:00|1|n1|cpu=4|cpu=4|/m/euclid_dr1/hpc/batch_cpu", + "1_1.batch|2.batch|batch||CANCELLED|0:15|2026-09-01T00:00:00|2026-09-01T01:00:00|2026-09-01T05:00:00|04:00:00||4||9000M|9000M|15:00:00|16:00:00|1|n1||cpu=4|", + "3_0|3|euclid_dr1_sed_v2g|gpu|COMPLETED|0:0|2026-09-30T00:00:00|2026-09-30T00:00:00|2026-09-30T01:00:00|01:00:00|08:00:00|8|8192M|||06:00:00|08:00:00|1|g1|cpu=8|cpu=8|/m/active/euclid_dr1/hpc/batch_cpu", + "4_0|4|other|ral|COMPLETED|0:0|2026-09-01T00:00:00|2026-09-01T00:00:00|2026-09-01T01:00:00|01:00:00|08:00:00|8|8192M|||06:00:00|08:00:00|1|n2|cpu=8|cpu=8|/m/euclid_dr1_old/hpc", +] +STAGES = r"euclid_dr1_(?Pvis_lp|vis_pix|sed)" + + +def _dump(tmp_path): + path = tmp_path / "dump.psv" + path.write_text("\n".join([HEADER] + ROWS) + "\n") + return path + + +def test_under_is_a_path_boundary(): + assert under("/m/euclid_dr1/hpc", ["/m/euclid_dr1"]) + assert under("/m/euclid_dr1", ["/m/euclid_dr1/"]) + assert not under("/m/euclid_dr1_old/hpc", ["/m/euclid_dr1"]) + assert under("/anything", []) + + +def test_stage_of(): + assert stage_of("euclid_dr1_vis_pix_v2g_p05", STAGES) == "vis_pix" + assert stage_of("subval_source_pix", STAGES) == "subval_source_pix" + assert stage_of("euclid_dr1_release_package", STAGES, other="tooling") == "tooling" + + +def test_peak_concurrency(tmp_path): + peak, at = peak_concurrency(parse(_dump(tmp_path).read_text())) + # 1_0 and 4_0 start together; 4_0 ends as 1_1 starts (end before start). + assert peak == 12 and at == "2026-09-01T00:00:00" + + +def test_retro(tmp_path, ral): + digest, outcomes = retro( + _dump(tmp_path), + workdir_prefixes=["/m/euclid_dr1", "/m/active/euclid_dr1"], + stage_regex=STAGES, + site=ral, + name="dr1", + ) + assert digest["source"]["allocations_selected"] == 3 + assert set(digest["stages"]) == {"vis_lp", "sed"} + vis_lp = digest["stages"]["vis_lp"] + assert vis_lp["states"] == {"completed": 1, "timeout": 1} + assert vis_lp["rss_mb"]["max"] == 6000 + assert vis_lp["cpu_h"] == {"successful": 8.0, "all_attempts": 24.0, "failed_or_repeated": 16.0} + assert digest["stages"]["sed"]["gpu_partition_cpu_tasks"] == {"tasks": 1, "cpu_h": 8.0} + assert digest["period"] == {"first_submit": "2026-09-01T00:00:00", "last_end": "2026-09-30T01:00:00"} + + +def test_retro_cli(tmp_path, capsys): + output = tmp_path / "out" + assert main(["retro", "--sacct", str(_dump(tmp_path)), "--workdir-prefix", "/m/euclid_dr1", + "--stage-regex", STAGES, "--site", "ral", "--name", "dr1", "--output", str(output)]) == 0 + assert "# dr1" in capsys.readouterr().out + assert (output / "failed_timeout.txt").read_text().startswith("vis_lp\t-\t1_1") + assert sorted(p.name for p in output.iterdir()) == ["digest.json", "digest.md", "failed_timeout.txt", "tasks.jsonl"]