diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 6de8c856..ad2facd4 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -108,6 +108,25 @@ store itself, and nothing is sent. Log lines pass through ``redact`` before they are kept. +Runs of one queue (``Plan.queue``, the id of one submission of a suite, in +every run's plan and record) are started by one launch and +run one after the other: each names the run before it (``Plan.after``) in the +plan saved before the launch's decision. A run waits, ``preparing``, until the +record of that run on disk says it ended, whatever its outcome; a record +missing or unreadable holds the queue. Its turn is saved (``promoted``) before +anything of it starts, so a restart waits again or goes on, never both. One +Stop is the queue's (``stop``): saved as a flag in its first run's folder +(``QUEUE_STOP``, naming the queue) before any run is told, it ends the run +under way and every run still waiting. While a run of the queue has not ended +none of them runs a part again nor is deleted (``queue_open``); once all have, +a run that runs tasks again is no longer the queue's: its Stop is its own and +the queue's flag does not reach it. A queue's records are of ``QUEUE_VERSION``, +so a Nullius from before queues leaves them alone. What a queue's run is to +its queue is in its record too (``member``): a run whose plan cannot be read +back at ``restore`` is held as that (``Execution.lost``), on the pages and +under the queue's Stop, and holds the runs after it until no process of it is +left on this machine; then it ends ``failed`` and the queue goes on. + What the run is doing is said in stages (``nullius/progress.py``): the steps here that get a host ready - connect, uv, the tasks, app/, a pinned Harbor - each a ``[nullius] stage=...`` line in the run's log, and the run's own (the @@ -127,6 +146,7 @@ import re import shlex import shutil +import signal import stat import subprocess import sys @@ -157,6 +177,9 @@ STOP_WAIT = 20.0 # seconds a Stop's own commands on the target take at most: the kill and the last copy back, together LAUNCH_GRACE = 5.0 # seconds a restart waits for a part a launcher claimed to start (_settle) UV_INSTALL = "curl -LsSf https://astral.sh/uv/install.sh | sh" +QUEUE_STOP = "queue.stop" # in a queue's first run's folder: its Stop, saved before any of its runs is told (``stop``) +QUEUE_VERSION = 2 # of a queue's run's record: a Nullius that knows no queue reads it as a later one's and leaves it +QUEUE_POLL = 1.0 # seconds between a waiting run's looks at the record of the run before it RECORD = "run.json" # the run as it is now (``Execution._save``) PLAN = "plan.json" # its plan, recipe included, without the scripts: they are run.sh and each part's file VERSION = 1 # of the record; one without it holds its plan and every trial it said (``recorded``) @@ -289,6 +312,10 @@ class Plan: keyless: bool = False # nothing in it calls a model (the standard's controls): handed no key and no endpoint at all licences: dict = field(default_factory=dict) # the standard's on a host: {"benchmark", "names", "providers"} - what it is sent of that benchmark's licences roles: dict = field(default_factory=dict) # by role, its own provider's {key_var, url_var, base_url}: the standard's judge or user simulator + queue: str = "" # the queue it is a run of, the id of one submission: a suite's runs, one after the other (``Execution._turn_comes``) + queue_runs: list = field(default_factory=list) # every run of that queue, by name, in order: the first holds its Stop (``QUEUE_STOP``) + queue_recipe: dict = field(default_factory=dict) # the suite's own recipe the queue was compiled from: what "Run the rest" compiles again + after: str = "" # the run of its queue it waits for: it starts once that run's saved record says it ended def steps(self) -> List[dict]: return [p for p in self.parts if p.get("script")] or [{"id": "run", "label": "the run", "script": self.script, "whole": True}] @@ -425,6 +452,7 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl self._run_plain = run or subprocess_run self._run = run or (lambda argv, timeout=600.0, stdin=None: subprocess_run(argv, timeout, stdin, stop=self._stop)) self._credentials(key, url, env, agent_keys) + self._given = (key, url, env, agent_keys) # read again when its turn in a queue comes (``_turn_comes``) # the benchmark's licences a standard run on a host is sent: read from its store at each launch, unless given self._licences_given = licences self._redact: List[str] = [] # the licences' values sent, as text: never in a log line @@ -455,6 +483,10 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl self.launched: str = rec.get("launched") or "" # the fresh checks passed, the run's name on a host its own (``_checked``): None for a record from before the field self.checked: Optional[bool] = rec.get("checked") if record else False + # its turn in its queue came, saved before anything of it starts (``_turn_comes``); a run of no queue has no turn to wait for + self.promoted: bool = bool(rec.get("promoted")) or not plan.after + # why its plan could not be read back (``_lost``): held as its record says it, nothing of it run from here + self.lost: str = "" if self.state == "stopping": # a Stop that a restart interrupted: finish it, do not run on self._stop.set() self.log_offset = int(rec.get("log_offset", 0)) @@ -558,14 +590,18 @@ def _save(self, strict: bool = False, inline: bool = False) -> bool: ``plan.json`` saved as one, its plan in it, no other file written. Nothing once ``deleted``: False.""" with self._turn: - if self.deleted: + if self.deleted or self.lost: # a run held without its plan is saved by ``_keep_lost`` alone return False - data = {"version": VERSION, "id": self.id, "state": self.state, "step": self.step, "part": self.part, "pid": self.pid, + data = {"version": QUEUE_VERSION if self.plan.queue else VERSION, **({"queue": self.plan.queue} if self.plan.queue else {}), "id": self.id, "state": self.state, "step": self.step, "part": self.part, "pid": self.pid, "log_offset": self.log_offset, "exit_code": self.exit_code, "error": self.error, "question": self.question, "ends": self.ends, "started": self.started, "finished": self.finished, "harbor": self.harbor, "tasks_on_target": self.tasks_on_target, "app_on_target": self.app_on_target, "catalogue_on_target": self.catalogue_on_target, "workspace": self.workspace, - "launched": self.launched, "checked": self.checked, "feeds": self._feeds, "caps": self.caps, + "launched": self.launched, "checked": self.checked, **({"promoted": self.promoted} if self.plan.after else {}), "feeds": self._feeds, "caps": self.caps, "again": [{k: v for k, v in p.items() if k != "script"} for p in self.plan.parts if p.get("again")]} + if self.plan.queue: # what it is to its queue, should its plan not be read back (``_lost``) + data["member"] = {"runs": self.plan.queue_runs, "jobs": self.plan.jobs, "runner": self.plan.runner, "remote": bool(self.plan.host), + "recipe": {k: v for k, v in (self.plan.recipe or {}).items() if k in ("suite", "max_usd")}, + "rest_of": (self.plan.queue_recipe or {}).get("rest_of")} if self._pending: data["pending"] = self._pending if self._seen_trials: @@ -758,12 +794,15 @@ def refused(self, job_id: str) -> Optional[str]: def live_state(self, job_id: str) -> Optional[str]: """What one job of this run is doing while the run lives: the run's state for the part running now, ``queued`` for a part still to come - (the parts run one after another), and the run's own while it + (the parts run one after another) and for a run waiting for its turn + in its queue, and the run's own while it prepares or stops, which is every part's. ``not run`` for one held back by a pause: nothing starts it unless the page says continue. None once the run ended.""" if self.state not in ALIVE: return None + if self.state == "preparing" and not self.promoted: # a run waiting for its turn in its queue + return "queued" part = self.part_for(job_id) if self.state in ("preparing", "stopping") or part is None or part == self.launched or self.again_of(job_id) is not None: return self.state @@ -828,10 +867,65 @@ def file_under(self, workspace: str, *, persist: bool = True) -> None: def resume(self) -> "Execution": """Pick a recorded run up where it was: the part that was running is followed again, a pause waits again, the rest runs on.""" + if self.plan.queue and not self.rerunning() and _queue_stopped(self.root, self.plan): + self.state = "stopping" # its queue's Stop was saved, and Nullius went before this run was told + self._stop.set() self.thread = threading.Thread(target=self._main_resumed, name=f"run-{self.plan.name}", daemon=True) self.thread.start() return self + def _keep_lost(self, rec: dict, remote: bool, kw: dict) -> None: + """A run whose plan could not be read back (``_lost``), looked at until it ends or can be picked up: its + record stays as it was, so the runs after it wait. Each look reads the plan again: readable, the run is + picked up as any other. Else, once no process of it is left on this machine (``_in_folder``) and its + turn has come - the run before it ended - it is recorded ``failed`` with the reason, and the queue goes + on. Under the queue's Stop its processes are ended, by their groups, and it is recorded ``stopped``. + One on a host, or where processes cannot be listed, is never known to be gone: it is held until a + Stop, which records it ``stopped`` and says its processes were not reached.""" + runs = self.plan.queue_runs + before = runs[runs.index(self.plan.name) - 1] if self.plan.name in runs[1:] else "" + while True: + try: + again, plan = recorded(self.dir) + new = Execution(Plan.from_dict(plan), root=self.root, record=again, **kw) + except (OSError, ValueError, KeyError, TypeError): + pass + else: + with _QUEUES: + EXECUTIONS[self.id] = new + if new.state in ALIVE: + new.resume() + return + stopping = self._stop.is_set() or (not self.rerunning() and _queue_stopped(self.root, self.plan)) + left = None if remote else _in_folder(self.dir) + for pid in (left or ()) if stopping else (): + try: + group = os.getpgid(pid) + os.killpg(group, signal.SIGTERM) if group != os.getpgid(0) else os.kill(pid, signal.SIGTERM) + except OSError: + pass + turn = self.promoted or not before + if not turn: + try: + with open(os.path.join(self.root, before, RECORD), encoding="utf-8") as fh: + turn = json.load(fh).get("state") in ENDED + except (OSError, ValueError, AttributeError): + pass + if (stopping and not left) or (left == [] and turn): + state = "stopped" if stopping else "failed" + said = self.lost + ("; its processes could not be reached" if stopping and left is None else "") + try: + with _QUEUES: # as a turn is saved: a Stop of the queue is before or after, never during + ondisk.write_whole(os.path.join(self.dir, RECORD), json.dumps(dict(rec, state=state, error=said, finished=time.time()), indent=1)) + except OSError: + pass # held, and written at the next look + else: + self.log(f"✕ {said}" + ("" if stopping else "; the runs after it go on")) + with self._turn: + self.state, self.error, self.finished = state, said, time.time() + return + time.sleep(QUEUE_POLL) + def continue_(self) -> None: """Answer a pause: go on with the next agent.""" self.question = None @@ -920,8 +1014,78 @@ def _kill_part(self) -> Optional[int]: self.pid, self._live = None, None return int(code) + def rerunning(self) -> bool: + """Whether the run is running tasks again (``again``, a part only a run of a closed queue is given): it is + then no longer its queue's, from that part's start until the run's end is recorded.""" + return self.state in ALIVE and any(p.get("again") for p in self.plan.parts) + + def _turn_comes(self) -> bool: + """Wait, ``preparing``, for this run's turn in its queue: until the + record on disk of the run before it (``Plan.after``) says that run + ended, whatever its outcome. True once the turn is saved + (``promoted``, a strict save: nothing of the run starts before); + False when the run ended here instead - the queue's Stop, saved + (``QUEUE_STOP``) or said to this run, or the run before it recorded + ``stopped``. A record missing, unreadable, of another queue, of another run + (its id), of another version or of a later attempt, or not yet ended holds the + queue, and a turn that cannot be saved is tried again: the log says + why once. A run before it that ended in this process but whose record + does not say so is asked to save it again.""" + said = None + while not self.promoted: + why = None + with _QUEUES: # a Stop of the queue is saved before or after this turn, never during + state = None + try: + with open(os.path.join(self.root, self.plan.after, RECORD), encoding="utf-8") as fh: + before = json.load(fh) + state = before.get("state") + if before.get("queue") != self.plan.queue: # a folder of that name another launch made: never this run's turn + state, why = None, f"the record of {self.plan.after} is not this launch's" + elif (not re.fullmatch(re.escape(self.plan.after) + r"-\d+", str(before.get("id"))) or before.get("version") != QUEUE_VERSION + or before.get("again")): # another run's record, or one of a later attempt: not the end waited for + state, why = None, f"the record of {self.plan.after} is not that run's first attempt" + except (OSError, ValueError, AttributeError): + why = f"the record of {self.plan.after} cannot be read" + if self._stop.is_set() or state == "stopped" or _queue_stopped(self.root, self.plan): + self._stop.set() + elif state in ENDED: + self.promoted, was = True, self.started + self.started = time.time() + try: + self._credentials(*self._given) # the keys as Settings holds them now, not as the launch read them + + if not self._save(strict=True): + return False # deleted + except OSError as e: + self.promoted, self.started = False, was + why = str(e) if isinstance(e, Unreadable) else f"its turn could not be saved ({e.strerror or e})" + else: + self.log(f"— {self.plan.after} ended ({state}): starting") + return True + elif why is None: + before = next((e for e in list(EXECUTIONS.values()) if e.plan.name == self.plan.after and e.root == self.root), None) + if before is not None and before.state in ENDED: + before._save() # its end was not saved: tried again, read at the next look + why = f"the end of {self.plan.after} is not saved yet" + if self._stop.is_set(): + self._done(130) + return False + now = why or f"waiting for {self.plan.after} to end" + if now != said: + said = now + self.log(f"— {now}" + ("; the queue is held until it can" if why else "")) + with self._turn: + if self.state == "preparing": + self.step = "queued" + self._save() + self._stop.wait(QUEUE_POLL) + return True + def _main(self) -> None: try: + if not self._turn_comes(): + return os.makedirs(self.jobs, exist_ok=True) problem = self.plan.check() if problem: @@ -1022,6 +1186,8 @@ def again(self, part: dict, env=os.environ, settle: Optional[tuple] = None) -> " with self._turn: if self.state in ALIVE: raise ValueError(f"{self.plan.name} is {self.state}: a run takes one more part once it has ended") + if queue_open(self): + raise ValueError(f"{self.plan.name} is one of a suite's runs, and some have not ended: nothing was started") if self._deleting(): raise ValueError(f"{self.plan.name} is being deleted: nothing was started") name = _base(part) + ".sh" @@ -1111,6 +1277,8 @@ def holds(self, job_id: str) -> Optional[str]: def _main_resumed(self) -> None: try: self.log(f"— Nullius is back; picking the run up at {self.plan.steps()[min(self.part, len(self.plan.steps()) - 1)]['label']}") + if not self._turn_comes(): + return unbegun = self._unbegun() if unbegun is None: return @@ -2104,6 +2272,99 @@ def start(plan: Plan, **kw) -> Execution: return start_all([Execution(plan, **kw)])[0] +_QUEUES = threading.Lock() # a queue's Stop and each of its runs' turn, one at a time (``stop``, ``Execution._turn_comes``) + + +def _queue_stop(root: str, plan: Plan) -> str: + return os.path.join(root, (plan.queue_runs or [plan.name])[0], QUEUE_STOP) + + +def _queue_stopped(root: str, plan: Plan) -> bool: + """Whether the Stop of *plan*'s queue is saved: its flag, naming that queue. One that cannot be read counts, + one another launch left in a folder of that name does not.""" + try: + with open(_queue_stop(root, plan), encoding="utf-8") as fh: + return json.load(fh).get("queue") == plan.queue + except FileNotFoundError: + return False + except (OSError, ValueError, AttributeError): + return True + + +def queue_of(ex: Execution) -> List[Execution]: + """The runs of *ex*'s queue this process holds, *ex* alone when it is of none.""" + if not ex.plan.queue: + return [ex] + return [e for e in list(EXECUTIONS.values()) if e.plan.queue == ex.plan.queue and e.root == ex.root] or [ex] + + +def _unended(ex: Execution) -> List[str]: + """The runs of *ex*'s queue whose saved record does not say they ended: one waiting or under way, one whose + end was not saved, one whose record cannot be read, one this process does not hold included. Its members are + the plan's (``Plan.queue_runs``), not what this process holds; one whose folder is gone, or holds the readable + record of another queue's run, is left out.""" + out = [] + for name in ex.plan.queue_runs or [e.plan.name for e in queue_of(ex)]: + if not os.path.isdir(os.path.join(ex.root, name)): + continue # deleted, once the queue had closed + try: + with open(os.path.join(ex.root, name, RECORD), encoding="utf-8") as fh: + rec = json.load(fh) + if rec.get("queue") != ex.plan.queue or rec.get("state") in ENDED: + continue # ended, or another launch's run in a folder of that name: its own was deleted + except (OSError, ValueError, AttributeError): + pass + out.append(name) + return out + + +def queue_open(ex: Execution) -> bool: + """Whether a run of *ex*'s queue has not ended: one running, one still waiting for its turn, or one whose + saved record does not say it ended (``_unended``), held by this process or not. A run that runs tasks again + once all had ended does not open it again.""" + if not ex.plan.queue: + return False + held = {e.plan.name: e for e in queue_of(ex)} + return (any(e.state in ALIVE and not e.rerunning() for e in held.values()) + or any(not (name in held and held[name].rerunning()) for name in _unended(ex))) + + +def _first_is_ours(ex: Execution) -> bool: + """Whether the folder that holds the queue's Stop is known to be its first run's: its record there names + the queue, or, that not readable, its plan does, or this process holds that run. False otherwise - the first + run was deleted once the queue had closed and its name taken by another launch, which may have no record + yet (``reserve``): nothing of this queue is written into a folder that is not shown to be its own.""" + folder = os.path.dirname(_queue_stop(ex.root, ex.plan)) + for name in (RECORD, PLAN): + try: + with open(os.path.join(folder, name), encoding="utf-8") as fh: + return json.load(fh).get("queue") == ex.plan.queue + except (OSError, ValueError, AttributeError): + pass + return any(e.dir == folder and not e.deleted for e in queue_of(ex)) + + +def stop(ex: Execution) -> bool: + """Stop *ex*; of an open queue, the queue: its Stop saved first (``QUEUE_STOP``), then the run under way and + every run waiting told, each ending ``stopped`` by itself. Saved too while a record of the queue does not say + its run ended, though every run this process holds has: a Stop asked again after one that could not be saved. + False when the Stop could not be saved: no run is told, since one ending without the flag would let the run + after it start. A run running tasks again is stopped alone.""" + if not ex.plan.queue or ex.rerunning(): + ex.stop() + return True + with _QUEUES: + runs = [e for e in queue_of(ex) if not e.rerunning()] + if (any(e.state in ALIVE for e in runs) or _unended(ex)) and _first_is_ours(ex): + try: + ondisk.write_whole(_queue_stop(ex.root, ex.plan), json.dumps({"queue": ex.plan.queue, "at": time.time()})) + except OSError: + return False + for e in runs: + e.stop() + return True + + class Unreadable(OSError): """A key Settings holds for a run, or a file in its folder, could not be read: its message names it.""" @@ -2480,10 +2741,12 @@ def recorded(path: str, scripts: bool = True) -> tuple: plan = rec["plan"] rec.setdefault("caps", plan.pop("caps", None) or {}) return rec, plan - if rec.get("version", 0) > VERSION: + if rec.get("version", 0) > QUEUE_VERSION: raise ValueError(f"{path} was recorded by a later Nullius") with open(os.path.join(path, PLAN), encoding="utf-8") as fh: plan = json.load(fh) + if plan.get("go_on"): + raise ValueError(f"{path} is a suite's joined plan, of a design that was dropped: it is not picked up; run the suite again") rec.setdefault("caps", plan.pop("caps", None) or {}) ids = {p.get("id") for p in plan.get("parts") or ()} plan["parts"] = (plan.get("parts") or []) + [dict(p) for p in rec.get("again") or () if p.get("id") not in ids] @@ -2513,7 +2776,8 @@ def restore(root: Optional[str] = None, **kw) -> List[Execution]: try: rec, plan = recorded(os.path.join(root, name)) plan = Plan.from_dict(plan) - except (OSError, ValueError, KeyError, TypeError): + except (OSError, ValueError, KeyError, TypeError) as e: + _lost(root, name, e, kw) continue ex = Execution(plan, root=root, record=rec, **kw) EXECUTIONS[ex.id] = ex @@ -2522,6 +2786,52 @@ def restore(root: Optional[str] = None, **kw) -> List[Execution]: return back +def _lost(root: str, name: str, why: Exception, kw: dict) -> Optional[Execution]: + """A run of a queue whose plan ``restore`` cannot read back, held as its record says it (``member``): on the + pages, in its queue (``queue_of``) and under its Stop, with a plan of what the record kept and nothing to + run. While the record says it is alive it is looked at again (``Execution._keep_lost``). None, and nothing held, + for a run of no queue, and for a record that cannot be read or is a later Nullius's: the queue is held by + that record.""" + try: + with open(os.path.join(root, name, RECORD), encoding="utf-8") as fh: + rec = json.load(fh) + if not rec.get("queue") or rec.get("version", 0) > QUEUE_VERSION: + return None + member = rec.get("member") if isinstance(rec.get("member"), dict) else {} + # the parts it ran again stay its plan's: a run running tasks again is not its queue's, held or not (``rerunning``) + plan = Plan(name=name, script="", queue=str(rec["queue"]), queue_runs=[str(n) for n in member.get("runs") or [name]], + parts=[dict(p) for p in rec.get("again") or () if isinstance(p, dict)], + jobs=[dict(j) for j in member.get("jobs") or ()], runner=str(member.get("runner") or "harbor"), + recipe=dict(member.get("recipe") or {}), queue_recipe={"rest_of": member["rest_of"]} if member.get("rest_of") else {}) + ex = Execution(plan, root=root, record=rec, **kw) + except (OSError, ValueError, AttributeError, TypeError, KeyError): + return None + ex.lost = f"could not be picked up again: {getattr(why, 'strerror', None) or why}" + ex.promoted = bool(rec.get("promoted", True)) + EXECUTIONS[ex.id] = ex + if ex.state in ALIVE: + ex.thread = threading.Thread(target=ex._keep_lost, args=(rec, bool(member.get("remote")), kw), name=f"run-{name}", daemon=True) + ex.thread.start() + return ex + + +def _in_folder(path: str) -> Optional[List[int]]: + """The processes of this machine whose working directory is the run folder *path* or under it: a part's + detached shell stays there until its script ends. None where that cannot be told (no ``PROC``).""" + if not os.path.isdir(PROC): + return None + real, out = os.path.realpath(path), [] + for p in os.listdir(PROC): + if p.isdigit() and int(p) != os.getpid(): + try: + cwd = os.readlink(os.path.join(PROC, p, "cwd")) + except OSError: + continue + if cwd == real or cwd.startswith(real + os.sep): + out.append(int(p)) + return out + + # --- deleting a launch --------------------------------------------------------- def run_folder(name: str, root: Optional[str] = None) -> str: @@ -2602,6 +2912,8 @@ def _deletable(name: str, root: Optional[str]) -> tuple: state = ex.state if ex is not None else rec.get("state") if state in ALIVE: raise ValueError(f"{name} is {state}: stop it before you delete it") + if ex is not None and queue_open(ex): + raise ValueError(f"{name} is one of a suite's runs, and some have not ended: stop the suite before you delete it") return path, rec @@ -2767,6 +3079,8 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r with ex._turn: if ex.state in ALIVE: raise ValueError(f"{n} is {ex.state}: stop it before you delete it") + if queue_open(ex): + raise ValueError(f"{n} is one of a suite's runs, and some have not ended: stop the suite before you delete it") return _delete(names, home, root, copies, run) finally: with _CLAIMS: diff --git a/app/tests/test_execution_queue.py b/app/tests/test_execution_queue.py new file mode 100644 index 00000000..e082f1f4 --- /dev/null +++ b/app/tests/test_execution_queue.py @@ -0,0 +1,366 @@ +"""A queue: runs of one launch, one after the other, across a Stop, a Delete and a restart at each of its boundaries.""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import time +from pathlib import Path +from unittest.mock import patch + +from nullius import execution + +from tests.execution_support import Base + + +class Queue(Base): + def setUp(self): + super().setUp() + self.addCleanup(setattr, execution, "QUEUE_POLL", execution.QUEUE_POLL); execution.QUEUE_POLL = 0.02 + self.root, self.order = self.tmp / "runs", self.tmp / "order" + + def plans(self, scripts): + """A plan per script, named q1, q2...: each says its name in ``order`` first, and waits for the run before it.""" + names = [f"q{i}" for i in range(1, len(scripts) + 1)] + return [execution.Plan(name=n, script=f"echo {n} >> {self.order}; {s}", queue="one-launch", queue_runs=names, after=names[i - 1] if i else "") + for i, (n, s) in enumerate(zip(names, scripts))] + + def launch(self, *scripts): + return execution.start_all([execution.Execution(p, root=str(self.root)) for p in self.plans(scripts)]) + + def ran(self): + return self.order.read_text().split() if self.order.exists() else [] + + def test_each_run_starts_once_the_one_before_it_ended_and_a_failed_one_does_not_stop_the_next(self): + gate = self.tmp / "gate" + q1, q2, q3 = self.launch(f"while [ ! -e {gate} ]; do sleep 0.02; done", "exit 3", "true") + self.until_recorded(q1, "running") + time.sleep(0.3) + self.assertEqual((self.ran(), q2.state, q2.step, q3.state), (["q1"], "preparing", "queued", "preparing")) + self.assertIn("— waiting for q1 to end", q2.lines) + self.assertEqual((q1.live_state("q1"), q2.live_state("q2")), ("running", "queued")) # as the Runs page says it + gate.write_text("") + for ex in (q1, q2, q3): + self.wait(ex) + self.assertEqual((self.ran(), [e.state for e in (q1, q2, q3)]), (["q1", "q2", "q3"], ["done", "failed", "done"])) + self.assertGreaterEqual(q3.started, q2.finished) # its start is its turn, not the launch + self.assertEqual(execution.recorded(q3.dir)[1]["after"], "q2") # the link is in the plan the launch saved + + def test_a_record_that_cannot_be_read_holds_the_queue_until_it_can(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + q3 = execution.Execution(execution.Plan(name="q3", script="true", queue="one-launch", queue_runs=["q1", "q2", "q3"], after="gone"), root=str(self.root)).start() + time.sleep(0.3) + self.assertEqual(q3.state, "preparing") + self.assertIn("— the record of gone cannot be read; the queue is held until it can", q3.lines) + (self.root / "gone").mkdir(); (self.root / "gone" / "run.json").write_text('{"state": "running", "queue": "one-launch"}') + time.sleep(0.2) + self.assertEqual(q3.state, "preparing") # a run not ended, as far as its record says + (self.root / "gone" / "run.json").write_text('{"state": "failed", "queue": "another-launch"}') + time.sleep(0.2) + self.assertEqual(q3.state, "preparing") # a run of that name another launch made + self.assertIn("— the record of gone is not this launch's; the queue is held until it can", q3.lines) + mine = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "gone" / "run.json").write_text(json.dumps(mine)) # a sibling's record copied over it: ended, of this queue + time.sleep(0.2) + self.assertEqual(q3.state, "preparing") + self.assertIn("— the record of gone is not that run's first attempt; the queue is held until it can", q3.lines) + for other in ({"version": execution.VERSION}, {"again": [{"id": "again-1"}]}): + (self.root / "gone" / "run.json").write_text(json.dumps({**mine, "id": "gone-1", **other})) + time.sleep(0.2) + self.assertEqual(q3.state, "preparing", other) + (self.root / "gone" / "run.json").write_text(json.dumps(dict(mine, id="gone-1", state="failed"))) + self.assertEqual(self.wait(q3).state, "done") + + def test_an_end_that_was_not_saved_holds_the_next_run_until_it_is(self): + real, refuse = execution.Execution._save, [True] + def save(ex, *a, **kw): + if ex.plan.name == "q1" and ex.state == "done" and refuse[0]: + return False # the disk was full as it ended + return real(ex, *a, **kw) + with patch.object(execution.Execution, "_save", save): + q1, q2 = self.launch("true", "true") + self.wait(q1); time.sleep(0.3) + self.assertEqual((q2.state, self.ran()), ("preparing", ["q1"])) + self.assertIn("— the end of q1 is not saved yet; the queue is held until it can", q2.lines) + refuse[0] = False + self.assertEqual(self.wait(q2).state, "done") + + def test_stop_ends_the_run_under_way_and_every_run_waiting_and_none_starts_after_a_restart(self): + q1, q2, q3 = runs = self.launch("sleep 30", "true", "true") + self.until_recorded(q1, "running") + self.assertTrue(execution.stop(q3)) # any of its runs: the Stop is the queue's + for ex in runs: + self.wait(ex) + self.assertEqual(([e.state for e in runs], self.ran()), (["stopped"] * 3, ["q1"])) + self.assertTrue((self.root / "q1" / execution.QUEUE_STOP).exists()) + self.assertIn("✕ stopped before the run: exit 130", q2.lines) + execution.EXECUTIONS.clear() + self.assertEqual(execution.restore(str(self.root)), []) + + def test_no_run_of_an_open_queue_is_deleted_or_run_again(self): + gate = self.tmp / "gate" + q1, q2, q3 = self.launch("true", f"while [ ! -e {gate} ]; do sleep 0.02; done", "true") + self.wait(q1); self.until_recorded(q2, "running") + for names in (["q1"], ["q1", "q2", "q3"]): + with self.assertRaisesRegex(ValueError, "stop"): + execution.delete(names, str(self.tmp / "ws"), str(self.root)) + self.assertRaisesRegex(ValueError, "q1 is one of a suite's runs", execution.deletable, ["q1"], str(self.root)) + with self.assertRaisesRegex(ValueError, "one of a suite's runs, and some have not ended"): + q1.again({"id": "again-1", "label": "again", "script": "true", "again": "job"}) + gate.write_text("") + self.wait(q2); self.wait(q3) + gone = execution.delete(["q1", "q2", "q3"], str(self.tmp / "ws"), str(self.root)) + self.assertEqual((gone["stays"], sorted(os.listdir(self.root))), ([], [".lock"] if (self.root / ".lock").exists() else [])) + + KILLED = ("import json, os, re, signal, sys\n" + "sys.path.insert(0, sys.argv[1]); from nullius import execution\n" + "root, plans, end, mark, stop = json.loads(sys.argv[2])\n" + "execution.QUEUE_POLL = execution.SYNC_EVERY = 0.02\n" + "real = execution.ondisk.write_whole\n" + "def call(path, data, *a, **k):\n" + " out = real(path, data, *a, **k)\n" + " if end in str(path) and (re.search(mark[3:], data) if mark.startswith('re:') else mark in data): os.kill(os.getpid(), signal.SIGKILL)\n" + " return out\n" + "execution.ondisk.write_whole = call\n" + "execution.docker_here = lambda *a, **k: None\n" + "exs = execution.start_all([execution.Execution(execution.Plan(**p), root=root) for p in plans])\n" + "if stop:\n" + " while not os.path.exists(stop): pass\n" + " execution.stop(exs[-1])\n" + "for ex in exs: ex.thread.join(60)\n") + + def killed(self, scripts, end, mark, stop=False): + """The queue of *scripts* launched in a process of its own, killed just after it wrote *mark* to a file whose path holds *end*; *stop*: it stops the queue once q1 runs.""" + app = str(Path(execution.__file__).resolve().parents[1]) + plans = [{"name": p.name, "script": p.script, "queue": p.queue, "queue_runs": p.queue_runs, "after": p.after} for p in self.plans(scripts)] + return subprocess.run([sys.executable, "-c", self.KILLED, app, json.dumps([str(self.root), plans, end, mark, str(self.order) if stop else ""])], timeout=60).returncode + + def test_a_queue_killed_at_any_of_its_boundaries_runs_each_of_its_runs_once_in_order_after_a_restart(self): + for case, end, mark in (("the launch decided, none started", ".launch-", '"committed"'), + ("q1 ended, q2 not yet promoted", "q1/run.json", '"state": "done"'), + ("q2 promoted, nothing of it started", "q2/run.json", '"promoted": true'), + ("q2 ended failed, q3 not yet promoted", "q2/run.json", '"state": "failed"'), + ("q3 promoted", "q3/run.json", '"promoted": true'), + ("q1 under way", "q1/run.json", '"state": "running"'), # between two boundaries + ("q2 under way", "q2/run.json", '"state": "running"')): + with self.subTest(case=case): + slug = case.replace(" ", "-").replace(",", "") + self.root, self.order = self.tmp / slug, self.tmp / (slug + ".order") + self.assertEqual(self.killed(["true", "exit 3", "true"], end, mark), -9) + back = execution.restore(str(self.root)) + for ex in back: + self.wait(ex, 20) + states = {e.plan.name: e.state for e in execution.EXECUTIONS.values()} + self.assertEqual((self.ran(), states), (["q1", "q2", "q3"], {"q1": "done", "q2": "failed", "q3": "done"}), case) + execution.EXECUTIONS.clear() + + def test_a_queue_killed_as_its_stop_was_saved_starts_nothing_more_after_a_restart(self): + self.assertEqual(self.killed(["sleep 30", "true", "true"], execution.QUEUE_STOP, '"at"', stop=True), -9) + for ex in execution.restore(str(self.root)): + self.wait(ex, 30) + self.assertEqual(({e.plan.name: e.state for e in execution.EXECUTIONS.values()}, self.ran()), + ({"q1": "stopped", "q2": "stopped", "q3": "stopped"}, ["q1"])) + + AGAIN = {"id": "again-1", "label": "again", "script": "sleep 30", "again": "job"} + + def test_a_run_again_after_a_stop_is_its_own_and_one_does_not_hold_the_others(self): + q1, q2 = runs = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + execution.stop(q1) + for ex in runs: + self.wait(ex) + q1.again(dict(self.AGAIN)) # the queue closed: its Stop is past + self.until_recorded(q1, "running") + self.assertFalse(execution.queue_open(q2)) # one run again does not hold the launch + execution.deletable(["q2"], str(self.root)) + execution.EXECUTIONS.clear() # Nullius restarted: the old flag is not this attempt's + back, = execution.restore(str(self.root)) + time.sleep(0.3) + self.assertEqual((back.plan.name, back.state), ("q1", "running")) + flag = self.root / "q1" / execution.QUEUE_STOP + flag.unlink() + self.assertTrue(execution.stop(back)) # its own Stop, not the queue's + self.assertEqual((self.wait(back).state, flag.exists()), ("stopped", False)) + + def test_a_flag_another_launch_left_stops_nothing(self): + gate = self.tmp / "gate" + q1, q2 = self.launch(f"while [ ! -e {gate} ]; do sleep 0.02; done", "true") + self.until_recorded(q1, "running") + (self.tmp / "flag").write_text('{"queue": "another-launch"}') # put there whole: one half written cannot be read, and stops + os.replace(self.tmp / "flag", self.root / "q1" / execution.QUEUE_STOP) + gate.write_text("") + self.assertEqual([self.wait(e).state for e in (q1, q2)], ["done", "done"]) + + def test_a_stop_asked_again_is_saved_while_a_record_does_not_say_its_run_ended(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="preparing", promoted=False))) # its end never reached the disk + self.assertTrue(execution.stop(q1)) + self.assertEqual(json.loads((self.root / "q1" / execution.QUEUE_STOP).read_text())["queue"], "one-launch") + execution.EXECUTIONS.clear() + for ex in execution.restore(str(self.root)): + self.wait(ex) + self.assertEqual(self.ran(), ["q1", "q2"]) # q2 is not started a second time + + def test_a_queue_s_records_are_of_a_version_an_older_nullius_leaves_alone(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + self.assertEqual((rec["version"], rec["queue"]), (execution.QUEUE_VERSION, "one-launch")) + self.assertGreater(rec["version"], execution.VERSION) + with patch.object(execution, "QUEUE_VERSION", execution.VERSION): # as a Nullius from before queues reads it + self.assertRaisesRegex(ValueError, "a later Nullius", execution.recorded, str(self.root / "q2")) + plan = json.loads((self.root / "q1" / "plan.json").read_text()) + (self.root / "q1" / "plan.json").write_text(json.dumps(dict(plan, go_on=True))) + self.assertRaisesRegex(ValueError, "a suite's joined plan, of a design that was dropped", execution.recorded, str(self.root / "q1")) + + def lost(self, script="sleep 3", then=("true",)): + """q1 under way, its process alive, Nullius killed, and its plan not to be read back at the restart.""" + self.assertEqual(self.killed([script, *then], "q1/run.json", r're:"pid": \d'), -9) + self.plan = (self.root / "q1" / "plan.json").read_text() + (self.root / "q1" / "plan.json").write_text("{") + execution.restore(str(self.root)) + return [next(e for e in execution.EXECUTIONS.values() if e.plan.name == n) for n in ("q1", "q2")] + + def test_a_run_whose_plan_cannot_be_read_back_holds_the_next_one_until_its_process_is_gone(self): + q1, q2 = self.lost() + time.sleep(1) + self.assertEqual((self.ran(), q1.state, q2.state), (["q1"], "running", "preparing")) # q1's part runs on: q2 does not start + self.assertTrue(q1.lost and execution.queue_open(q2)) + self.assertEqual([e.plan.name for e in execution.queue_of(q2)], ["q1", "q2"]) # on the launch, under its Stop + self.assertRaisesRegex(ValueError, "stop", execution.delete, ["q1", "q2"], str(self.tmp / "ws"), str(self.root)) + self.wait(q1, 20) + self.assertEqual(self.wait(q2, 20).state, "done") + rec = json.loads((self.root / "q1" / "run.json").read_text()) + self.assertEqual((rec["state"], q1.state, self.ran()), ("failed", "failed", ["q1", "q2"])) + self.assertGreaterEqual(json.loads((self.root / "q2" / "run.json").read_text())["started"], rec["finished"]) + self.assertIn("could not be picked up again", rec["error"]) + self.assertIn("the runs after it go on", (self.root / "q1" / "nullius.log").read_text()) + execution.EXECUTIONS.clear() # the restart after: still one of its launch + self.assertEqual(execution.restore(str(self.root)), []) + self.assertEqual({e.plan.name: (e.state, bool(e.lost)) for e in execution.EXECUTIONS.values()}, {"q1": ("failed", True), "q2": ("done", False)}) + self.assertEqual(execution.delete(["q1", "q2"], str(self.tmp / "ws"), str(self.root))["stays"], []) + + def test_a_plan_that_can_be_read_again_is_picked_up_not_failed(self): + q1, q2 = self.lost() + time.sleep(0.3) + (self.root / "q1" / "plan.json").write_text(self.plan) # unreadable once + for _ in range(100): + q1 = next(e for e in execution.EXECUTIONS.values() if e.plan.name == "q1") + if not q1.lost: + break + time.sleep(0.05) + self.assertEqual((self.wait(q1, 20).state, self.wait(q2, 20).state, self.ran()), ("done", "done", ["q1", "q2"])) + + def test_the_stop_of_a_queue_ends_a_run_held_without_its_plan(self): + q1, q2 = self.lost("sleep 30") + self.assertTrue(execution.stop(q2)) + self.wait(q1, 20); self.wait(q2, 20) + self.assertEqual((json.loads((self.root / "q1" / "run.json").read_text())["state"], q2.state, self.ran()), ("stopped", "stopped", ["q1"])) + self.assertEqual(execution._in_folder(q1.dir), []) + self.assertFalse(execution.queue_open(q2)) + + def test_a_stop_that_cannot_be_saved_tells_no_run(self): + q1, q2 = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + real = execution.ondisk.write_whole + def full(path, *a, **kw): + if str(path).endswith(execution.QUEUE_STOP): + raise OSError(28, "No space left on device") + return real(path, *a, **kw) + with patch.object(execution.ondisk, "write_whole", full): + self.assertFalse(execution.stop(q1)) + time.sleep(0.2) + self.assertEqual((q1.state, q2.state), ("running", "preparing")) # none was told: none ends without the flag + self.assertTrue(execution.stop(q1)) + self.assertEqual([self.wait(e).state for e in (q1, q2)], ["stopped", "stopped"]) + + def test_a_run_again_that_finished_is_not_stopped_by_the_old_flag_at_a_restart(self): + q1, q2 = runs = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + execution.stop(q1) + for ex in runs: + self.wait(ex) + q1.again(dict(self.AGAIN, script="true")) + self.assertEqual(self.wait(q1).state, "done") + rec = json.loads((self.root / "q1" / "run.json").read_text()) + (self.root / "q1" / "run.json").write_text(json.dumps(dict(rec, state="running", finished=None))) # killed between its part's end and its own + self.assertTrue((self.root / "q1" / execution.QUEUE_STOP).exists()) + execution.EXECUTIONS.clear() + back, = execution.restore(str(self.root)) + self.assertEqual((back.plan.name, self.wait(back).state), ("q1", "done")) + + def test_a_name_another_launch_took_neither_holds_the_queue_nor_gets_its_stop(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + execution.delete(["q1"], str(self.tmp / "ws"), str(self.root)) # the queue closed: each run is its own + other = execution.Execution(execution.Plan(name="q1", script="true", queue="another-launch", queue_runs=["q1"]), root=str(self.root)) + self.wait(execution.start_all([other])[0]) + self.assertFalse(execution.queue_open(q2)) + execution.deletable(["q2"], str(self.root)) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="running"))) # its end unsaved: a Stop would be saved + self.assertTrue(execution.stop(q2)) + self.assertFalse((self.root / "q1" / execution.QUEUE_STOP).exists()) # not in the other launch's folder + + def test_a_name_reserved_by_another_launch_with_no_record_yet_does_not_get_the_stop(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + execution.delete(["q1"], str(self.tmp / "ws"), str(self.root)) + other = [execution.Execution(execution.Plan(name="q1", script="true", queue="another-launch", queue_runs=["q1"]), root=str(self.root))] + execution.reserve(other) # its folder is there, its first record is not + self.assertFalse((self.root / "q1" / "run.json").exists()) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="running"))) # a Stop would be saved + self.assertTrue(execution.stop(q2)) + self.assertFalse((self.root / "q1" / execution.QUEUE_STOP).exists()) + self.assertEqual(self.wait(execution.start_all(other, reserved=True)[0]).state, "done") # and it starts as reserved + + def test_a_run_again_held_without_its_plan_does_not_take_the_old_stop(self): + q1, q2 = runs = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + execution.stop(q1) + for ex in runs: + self.wait(ex) + q1.again(dict(self.AGAIN)) + self.until_recorded(q1, "running") + for _ in range(200): + if execution._in_folder(q1.dir): break + time.sleep(0.02) + (self.root / "q1" / "plan.json").write_text("{") + execution.EXECUTIONS.clear() # Nullius restarted: the flag of the Stop before is still there + execution.restore(str(self.root)) + held = next(e for e in execution.EXECUTIONS.values() if e.plan.name == "q1") + time.sleep(0.5) + self.assertEqual((bool(held.lost), held.rerunning(), held.state, json.loads((self.root / "q1" / "run.json").read_text())["state"]), + (True, True, "running", "running")) + self.assertTrue(execution.stop(held)) # its own Stop ends it + self.wait(held, 20); q1.stop(); self.wait(q1, 20) + self.assertEqual(held.state, "stopped") + + def test_a_queue_is_open_by_its_records_not_by_what_this_process_holds(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="running"))) + execution.EXECUTIONS.pop(q2.id) # not held here + self.assertTrue(execution.queue_open(q1)) + self.assertRaisesRegex(ValueError, "stop", execution.deletable, ["q1"], str(self.root)) + (self.root / "q2" / "run.json").write_text(json.dumps(rec)) + self.assertFalse(execution.queue_open(q1)) + + def test_a_waiting_run_reads_its_key_as_its_turn_comes(self): + gate, env = self.tmp / "gate", dict(os.environ, MY_KEY="at-launch") + plans = self.plans([f"while [ ! -e {gate} ]; do sleep 0.02; done", "true"]) + for p in plans: + p.key_var = "MY_KEY" + q1, q2 = execution.start_all([execution.Execution(p, root=str(self.root), env=env) for p in plans]) + self.until_recorded(q1, "running") + env["MY_KEY"] = "set-since" # changed in Settings while q2 waited + gate.write_text("") + self.wait(q2) + self.assertEqual((q1._key, q2._key), ("at-launch", "set-since")) diff --git a/app/ui_tests/test_api.py b/app/ui_tests/test_api.py index 9b9f83e8..6231ea68 100644 --- a/app/ui_tests/test_api.py +++ b/app/ui_tests/test_api.py @@ -683,6 +683,9 @@ def test_a_running_run_is_stopped_from_another_machine(self): for _ in range(400): if "started" in "\n".join(self.get(f"/runs/{run_id}").json["log"]): break time.sleep(0.02) + with patch.object(execution, "stop", lambda ex: False): # a queue's Stop that could not be saved + s = self.post(f"/runs/{run_id}/stop", environ_base={"REMOTE_ADDR": "10.0.0.7"}) + self.assertEqual((s.status_code, "no run was told" in s.json["error"]), (503, True)) s = self.post(f"/runs/{run_id}/stop", environ_base={"REMOTE_ADDR": "10.0.0.7"}) self.assertEqual((s.status_code, s.json["id"]), (200, run_id)) self.assertIn(s.json["state"], ("stopping", "stopped")) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 4fffd883..83d95622 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -549,6 +549,10 @@ def test_the_page_carries_the_token_the_stop_button_sends(self): for _ in range(200): if ex.pid: break time.sleep(0.02) + with patch.object(execution, "stop", lambda ex: False): # a queue's Stop that could not be saved: said, none told + s = self.client.post(f"/run/{r.json['id']}/stop", headers={"Origin": "http://localhost", "X-CSRF-Token": self.csrf}); self.addCleanup(s.close) + self.assertEqual((s.status_code, s.json["ok"], ex.state), (503, False, "running")) + self.assertIn("no run was told", s.json["error"]) s = self.client.post(f"/run/{r.json['id']}/stop", headers={"Origin": "http://localhost", "X-CSRF-Token": self.csrf}); self.addCleanup(s.close) self.assertEqual(s.status_code, 200); self.assertEqual(s.json["state"], "stopping") # said at once ex.thread.join(10); self.assertEqual((ex.state, ex.exit_code), ("stopped", 130)) diff --git a/app/web/api.py b/app/web/api.py index 34bd93f9..0cbd7fc2 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -532,7 +532,8 @@ def api_run(run_id): @api("run") def api_run_stop(run_id): ex = _run(run_id) - ex.stop() + if not execution.stop(ex): # a suite's Stop is its whole queue's, saved before its runs are told + raise _Refused(503, "the Stop could not be saved, so no run was told: stop it again") return _json(ex.summary()) diff --git a/app/web/execute.py b/app/web/execute.py index 3cce0e6b..95f7841a 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -484,7 +484,8 @@ def run_stop(run_id): ex = execution.EXECUTIONS.get(run_id) if ex is None: abort(404) - ex.stop() + if not execution.stop(ex): # a suite's Stop is its whole queue's, saved before its runs are told + return jsonify({**ex.summary(), "ok": False, "error": "The Stop could not be saved, so no run was told: stop it again."}), 503 return jsonify(ok=True, **ex.summary())