diff --git a/.claude/rules/running.md b/.claude/rules/running.md index 75d23d677..295112ca0 100644 --- a/.claude/rules/running.md +++ b/.claude/rules/running.md @@ -13,7 +13,7 @@ setup. redacted. The standard's agents and upstream scripts get only the relay's word, never a key. - What a recipe needs of each machine is asked before Run and again as it - starts (`nullius/prerequisites.py`). `runs//run.json` lets a + starts (`nullius/prerequisites.py`). `runs//run.json` and `plan.json` let a restarted Nullius pick a run up again. ## Running the app diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 831043d94..fcd9456c0 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -54,7 +54,12 @@ followed and mirrored as a part is; each job's end stays its first part's. An agent's run that fails with more to come pauses the run and the page -asks: continue or stop. Every state change lands in ``runs//run.json``; +asks: continue or stop. Every state change lands in ``runs//run.json``, +small and of one size from the first trial to the last, with what may change +after the start (a job's cap, a part run ``again``): the plan is beside it in +``plan.json``, written once when the run starts, and its scripts in ``run.sh`` +and each part's ``run-.sh``, nowhere else; a run of one part runs +``run.sh`` itself. ``restore`` reads those records when Nullius starts and reattaches to what is still running, waits again where it was paused, and settles what ended while nobody was looking; one process at a time, by the runs root's lock. @@ -147,7 +152,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" -RECORD = "run.json" +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``) LOCK = ".lock" # in the runs root, held by the one process that follows its runs STANDARD = "standard" # the Nullius standard's runner key (standard/pages/recipe.py HARNESS) REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # this repository: app/ is in it @@ -215,12 +222,24 @@ def _base(part: dict) -> str: return f"run-{_ID.sub('_', part['id'])}" -def _script_rx(base: str) -> str: - """An extended regex for a command line that runs ``.sh``: the word - itself, alone or at the end of a path. Its first letter is bracketed so - the shell that asks, whose own command line holds the regex, never - matches it.""" - return "(^|[ /])[" + base[0] + "]" + base[1:].replace(".", r"\.") + r"\.sh( |$)" +def _write_script(folder: str, name: str, text: str) -> None: + ondisk.write_whole(os.path.join(folder, name), text if text.endswith("\n") else text + "\n") + + +def _script(part: dict) -> str: + """The script a part runs: ``.sh``, or the whole run's ``run.sh`` + for a run of one part (``Plan.steps``).""" + return "run.sh" if part.get("whole") else _base(part) + ".sh" + + +def _script_rx(part: dict) -> str: + """An extended regex for a command line that runs the part's script + (``_script``): the word itself, alone or at the end of a path - for a run + of one part ``run-run.sh`` too, which Nullius ran it as before. Each first + letter is bracketed so the shell that asks, whose own command line holds + the regex, never matches it.""" + names = [_script(part)] + ([_base(part) + ".sh"] if part.get("whole") else []) + return "(^|[ /])(" + "|".join("[" + n[0] + "]" + n[1:].replace(".", r"\.") for n in names) + ")( |$)" # Where a target shows its processes. A target without it (no /proc: not @@ -229,16 +248,16 @@ def _script_rx(base: str) -> str: PROC = "/proc" -def _part_pids(base: str, pids=()) -> str: +def _part_pids(part: dict, pids=()) -> str: """Shell, run in the run directory, that prints the part's processes, one pid per line: those whose working directory is the run directory and - whose command line runs ``.sh`` - the detached shell, the script's + whose command line runs its script (``_script_rx``) - the detached shell, the script's own bash, or a launcher on its way to them. Asked of ``pids`` (what the record holds), of the pid the part wrote, and of whatever ``pgrep`` finds by that command line, so a part is found with no pid saved. A pid the part held, since given to another process, is never printed, so nothing that is not the part's is ever signalled when the target supports ``PROC``.""" - rx = _script_rx(base) + base, rx = _base(part), _script_rx(part) return (f"for p in {' '.join(str(int(p)) for p in pids if p)} $(head -c 32 {base}.pid 2>/dev/null | tr -cd 0-9) " f"$(pgrep -f '{rx}' 2>/dev/null); do [ \"$p\" != $$ ] || continue; " f"if [ -d {PROC}/$$ ]; then [ {PROC}/$p/cwd -ef . ] && tr '\\0' ' ' <{PROC}/$p/cmdline 2>/dev/null | grep -Eq '{rx}' && echo $p; " @@ -264,21 +283,28 @@ class Plan: docker: bool = False # a runner that needs docker on its target though it is not Harbor (the standard's container backend) 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 - caps: dict = field(default_factory=dict) # a job's spending cap set on its page, {job: USD}: it holds from the job's next run 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 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}] + return [p for p in self.parts if p.get("script")] or [{"id": "run", "label": "the run", "script": self.script, "whole": True}] def check(self) -> Optional[str]: if not _NAME.fullmatch(self.name): return "the run needs a name: letters, digits, dots, dashes" if not self.script.strip() and not any(p.get("script") for p in self.parts): return "nothing to run" + if self.colliding(): + return self.colliding() if self.tasks and not os.path.isdir(os.path.expanduser(self.tasks)): return f"the task folder {self.tasks} is not a directory here" return None + def colliding(self) -> Optional[str]: + """Why two of its parts would run one script file, or None: the second's would overwrite the first's.""" + files = [_base(p) for p in self.parts if p.get("script")] + same = next((f for f in files if files.count(f) > 1), None) + return f"two parts run the same script, {same}.sh: give each part its own id" if same else None + def to_dict(self) -> dict: d = asdict(self) d["host"] = self.host.entry if self.host else None @@ -436,8 +462,12 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl self.app_on_target = rec.get("app_on_target", "") # the standard's source tree or runner snapshot on the target self.catalogue_on_target = rec.get("catalogue_on_target", "") # writable definitions, separate from the immutable runner self.workspace = rec.get("workspace", "") # the workspace its job was added to, the one a restart adds it back to - # the trials the log has said already, (job, trial), so a restart says each once + # how far into each job's events feed the log has said its trials, in bytes, so a restart reads only what is new + self._feeds: Dict[str, int] = {str(k): int(v) for k, v in (rec.get("feeds") or {}).items()} + # a record from before the feeds' positions: the trials it said, (job, trial), until their feed has a position self._seen_trials: set = {(k[0], k[1]) for k in rec.get("seen_trials") or ()} + self._planned = "version" in rec # the plan is in its own file already + self.caps: dict = dict(rec.get("caps") or {}) # a job's spending cap set on its page, {job: USD}: it holds from the job's next run self._settled: set = set() # the kept tries whose trial's copy was settled (settle_retried) if record: # a run still going reads its log now, to go on from it; one that ended when its page asks @@ -500,21 +530,47 @@ def events(self, value: List[dict]) -> None: def _save(self, strict: bool = False) -> None: - """``run.json``, the run as it is now. A write that fails is let go, the + """``run.json``, the run as it is now, with what may change after the + start (``caps``, the parts run ``again``), after its plan + (``_save_plan``) at the first save. A write that fails is let go, the last record saved standing; ``strict`` (the first, ``start_all``): OSError.""" with self._turn: - data = {"id": self.id, "plan": self.plan.to_dict(), "state": self.state, "step": self.step, "part": self.part, "pid": self.pid, + data = {"version": VERSION, "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, "seen_trials": [list(k) for k in sorted(self._seen_trials, key=str)]} + "launched": self.launched, "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._seen_trials: + data["seen_trials"] = [list(k) for k in sorted(self._seen_trials, key=str)] try: os.makedirs(self.dir, exist_ok=True) + if not self._planned: + self._save_plan() + self._planned = True ondisk.write_whole(os.path.join(self.dir, RECORD), json.dumps(data, indent=1)) except OSError: if strict: raise + def _save_plan(self) -> None: + """``plan.json``, and each script once, in its own file: the whole run's + in ``run.sh``, a part's in ``run-.sh``, where a run on this + machine launches it (``_launch``). The parts run ``again`` are the + record's (``_save``): only their scripts are written here, for a record + from before ``plan.json``.""" + plan = self.plan.to_dict() + scripts = {"run.sh": plan.pop("script")} + for part in plan["parts"]: + if part.get("script"): + scripts[_base(part) + ".sh"] = part.pop("script") + else: + part["script"] = "" # said here: a part without the field has its script in its file + plan["parts"] = [p for p in plan["parts"] if not p.get("again")] + for name, text in scripts.items(): + _write_script(self.dir, name, text) + ondisk.write_whole(os.path.join(self.dir, PLAN), json.dumps(plan, indent=1)) + def log(self, line: str) -> None: if line.startswith("** ") and ("post-quantum" in line or "store now, decrypt later" in line or "openssh.com/pq" in line): @@ -786,7 +842,7 @@ def _kill_part(self) -> Optional[int]: command = ('export PATH="$HOME/.local/bin:$PATH"; ' + f"cd {self._q(self._run_dir())} 2>/dev/null || exit 0; " f"ended() {{ e=$(head -c 32 {base}.exit 2>/dev/null | tr -cd 0-9); [ -z \"$e\" ] || " f"{{ {self._log_since(base)}; printf '\\n__part__ %s' \"$e\"; exit 0; }}; }}; ended; : >{base}.stop; " - f"s=none; [ -e {base}.launch ] || [ -e {base}.pid ] || [ -e {base}.log ] && s=stopped; k=$({_part_pids(base, [self.pid])}); " + f"s=none; [ -e {base}.launch ] || [ -e {base}.pid ] || [ -e {base}.log ] && s=stopped; k=$({_part_pids(part, [self.pid])}); " f"for p in $k; do s=stopped; kill -TERM -- -$p 2>/dev/null; done; for p in $k; do kill -TERM $p 2>/dev/null; done; " f"for i in 1 2 3 4 5 6 7 8 9 10; do a=; for p in $k; do kill -0 $p 2>/dev/null && a=1; done; [ -n \"$a\" ] || break; sleep 0.05; done; " + (f"rm -rf {self._licence_dir()}; " if self._licence_dir() else "") @@ -815,8 +871,6 @@ def _kill_part(self) -> Optional[int]: def _main(self) -> None: try: os.makedirs(self.jobs, exist_ok=True) - with open(os.path.join(self.dir, "run.sh"), "w", encoding="utf-8") as fh: - fh.write(self.plan.script if self.plan.script.endswith("\n") else self.plan.script + "\n") problem = self.plan.check() if problem: return self._fail("plan", problem) @@ -861,6 +915,7 @@ def again(self, part: dict, env=os.environ) -> "Execution": 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") + _write_script(self.dir, _base(part) + ".sh", part["script"]) # first: a record never names a script that is not there self.plan.parts.append(dict(part)) self._credentials(None, None, env) self.part = [p["id"] for p in self.plan.steps()].index(part["id"]) @@ -1032,10 +1087,12 @@ def _wait_decision(self, remaining: List[dict]) -> bool: def _trial_lines(self) -> None: """One line per trial that ended since the last look, read from the - jobs' own feeds, so the log says what finished as it finishes. The - trials said are saved with the record as soon as they are said, so a - restart, which reads the feeds again from their start, says none of - them twice.""" + jobs' own feeds, so the log says what finished as it finishes. Each + feed is read from where the last look left it, and that position is + saved with the record as soon as its trials are said, so a restart + says none of them twice. A record from before the positions holds the + trials it said instead: a feed of its is read once from its start, + those left out.""" try: names = sorted(os.listdir(self.jobs)) except OSError: @@ -1043,10 +1100,19 @@ def _trial_lines(self) -> None: said = False for name in names: feed = os.path.join(self.jobs, name, "events.jsonl") + old = () if name in self._feeds else self._seen_trials ends: Dict[str, int] = {} try: - with open(feed, encoding="utf-8", errors="replace") as fh: - for raw in fh: + with open(feed, "rb") as fh: + at = self._feeds.get(name, 0) + if at > os.fstat(fh.fileno()).st_size: + at = 0 # shorter than what was read: another feed under the name + fh.seek(at) + for line in fh: + if not line.endswith(b"\n"): + break # a line still being written: read whole at the next look + at += len(line) + raw = line.decode("utf-8", "replace") if '"trial.end"' not in raw: continue try: @@ -1055,13 +1121,11 @@ def _trial_lines(self) -> None: continue if ev.get("event") != "trial.end" or ev.get("back"): continue # a try put back after a Stop ended nothing new - # a trial run again ends once more in the same feed: its later ends are said too, each once - k = ends[str(ev.get("trial"))] = ends.get(str(ev.get("trial")), 0) + 1 - key = (name, ev.get("trial") if k == 1 else f"{ev.get('trial')}#{k}") - if key in self._seen_trials: - continue - with self._turn: # _save reads the set from the page's thread too - self._seen_trials.add(key) + if old: + # a trial run again ends once more in the same feed: its later ends were recorded as said too + k = ends[str(ev.get("trial"))] = ends.get(str(ev.get("trial")), 0) + 1 + if (name, ev.get("trial") if k == 1 else f"{ev.get('trial')}#{k}") in old: + continue said = True d = ev.get("durations") or {} secs = sum(v for v in d.values() if isinstance(v, (int, float))) @@ -1073,6 +1137,9 @@ def _trial_lines(self) -> None: + (f" · {int(secs // 60)}:{int(secs % 60):02d}" if secs else "")) except OSError: continue + with self._turn: # _save reads both from the page's thread too + self._feeds[name] = at + self._seen_trials = {k for k in self._seen_trials if k[0] != name} if said: self._save() @@ -1248,7 +1315,8 @@ def _prepare(self, fresh: bool = True, again: bool = False) -> bool: if self.plan.runner == STANDARD and not self._app_on_host(): return False run_dir = self._run_dir() - rc, out = self._sh(f"mkdir -p {_rq(run_dir + '/jobs')} && cat > {_rq(run_dir + '/run.sh')}", 30, stdin=self.plan.script) + rc, out = self._sh(f"mkdir -p {_rq(run_dir + '/jobs')} && cat > {_rq(run_dir + '/run.sh')}", 30, + stdin=self.plan.script if self.plan.script.endswith("\n") else self.plan.script + "\n") if rc != 0: self._fail("run", "the script did not land on the host: " + out.strip()[-400:]) return False @@ -1483,7 +1551,7 @@ def _look(self, names: List[str], part: Optional[dict] = None, pids=()) -> Optio too): ({name: digits}, [pid]). Asked again while the target does not answer, as ``_follow`` does; None for a Stop said meanwhile.""" files = " ".join(shlex.quote(n) for n in names) - procs = f"for p in $({_part_pids(_base(part), pids)}); do echo \"@proc $p\"; done; " if part else "" + procs = f"for p in $({_part_pids(part, pids)}); do echo \"@proc $p\"; done; " if part else "" while True: rc, out = self._sh(f"cd {self._q(self._run_dir())} 2>/dev/null || exit 0; for f in {files}; do " f"[ -f \"$f\" ] && printf '@file %s %s\\n' \"$f\" \"$(head -c 32 \"$f\" | tr -cd 0-9)\"; done; {procs}true", 60) @@ -1611,8 +1679,17 @@ def _launch(self, part: dict) -> Optional[bool]: where = self.plan.host.label if self.on_host else "this machine" self._begin("run", f"running {part['label']} on {where}") run_dir = self._run_dir() - script = _base(part) + ".sh" - rc, out = self._sh(f"cat > {self._q(run_dir + '/' + script)}", 30, stdin=part["script"] if part["script"].endswith("\n") else part["script"] + "\n") + script, base = _script(part), _base(part) + # Here each script is the one the record reads back, written whole once (_save_plan, again): never + # opened again, so a launch cut short cannot leave it empty. On a host, run.sh is there from _prepare. + if not self.on_host: + rc, out = 0, "" + if not os.path.exists(os.path.join(run_dir, script)): + _write_script(run_dir, script, part["script"]) + elif part.get("whole"): + rc, out = 0, "" + else: + rc, out = self._sh(f"cat > {self._q(run_dir + '/' + script)}", 30, stdin=part["script"] if part["script"].endswith("\n") else part["script"] + "\n") if rc != 0: self._fail("run", f"the script did not land on {where}: " + out.strip()[-400:]) return False @@ -1638,7 +1715,6 @@ def _launch(self, part: dict) -> Optional[bool]: + ([("API_MODEL_NAME", self.plan.model)] if self.plan.model else []) # this machine's Hugging Face endpoint: a host's run reads no saved settings (--from-run) + ([("HF_ENDPOINT", settings.hf_endpoint())] if self.on_host and settings.hf_endpoint() else [])) - base = script[:-3] # macOS has no setsid executable. Python can create the same session and # exec in place, keeping $!, the pid file and the process group identical. python = shlex.quote("python3" if self.on_host else sys.executable) @@ -1693,7 +1769,7 @@ def _follow(self, part: dict) -> int: and no exit code is gone, a failure of its own.""" base = _base(part) # Alive while a process runs its script in its run directory (_part_pids). - alive = f"[ -n \"$({_part_pids(base, [self.pid])})\" ] && echo alive || echo gone" + alive = f"[ -n \"$({_part_pids(part, [self.pid])})\" ] && echo alive || echo gone" while True: # Read in the reverse of the order the target writes them (the log, the exit code, the process # ends): an exit code seen means the whole log is there, a process gone means none is coming. @@ -1777,24 +1853,57 @@ def start(plan: Plan, **kw) -> Execution: return start_all([Execution(plan, **kw)])[0] -def start_all(runs: List[Execution]) -> List[Execution]: +class NameTaken(ValueError): + """A run's name another launch took after it was checked (``reserve``).""" + + +def reserve(runs: List[Execution]) -> None: + """Each run's folder made where there is none, so one launch alone holds + each name: NameTaken for a name taken meanwhile, OSError when the runs + root cannot hold it; either way the folders this made are removed.""" + made = [] + try: + for ex in runs: + os.makedirs(ex.root, exist_ok=True) + try: + os.mkdir(ex.dir) + except FileExistsError: + raise NameTaken(name_taken(ex.plan.name)) from None + made.append(ex) + except (OSError, NameTaken): + release(made) + raise + + +def release(runs: List[Execution]) -> None: + """The folders of *runs*, reserved and not started, removed with what was + written there: their names are free again, and a later save writes the + plan anew.""" + for ex in runs: + shutil.rmtree(ex.dir, ignore_errors=True) + ex._planned = False + + +def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]: """Start *runs*, those of one launch, once each has its first record: a run without one could not be picked up after a restart (``restore``). - OSError when one cannot be saved: none is registered or started, and the - records already saved are removed, since a restart would start them.""" - saved = [] + Their folders are reserved first unless ``reserved`` says they are. OSError + when one cannot be saved: none is registered or started, and their + folders are released, since a restart would start them and their names + would stay taken. ValueError, before anything is written, for a plan whose + parts would run one script file (``Plan.colliding``).""" + for ex in runs: + if ex.plan.colliding(): + if reserved: + release(runs) + raise ValueError(ex.plan.colliding()) + if not reserved: + reserve(runs) try: for ex in runs: ex._save(strict=True) - saved.append(ex) except OSError: - for ex in runs: - try: - if ex in saved: - os.remove(os.path.join(ex.dir, RECORD)) - os.rmdir(ex.dir) # only the folder the save made, empty - except OSError: - pass + release(runs) raise for ex in runs: EXECUTIONS[ex.id] = ex @@ -1886,6 +1995,32 @@ def _follow(root: str) -> None: _FOLLOWED[key] = fh +def recorded(path: str, scripts: bool = True) -> tuple: + """The record and the plan of the run folder *path*, each as it was saved + (``Plan.from_dict`` takes the plan): the plan from ``plan.json``, with the + parts run ``again`` and its ``scripts`` read back from their files, or + whole from a record written before it had a file of its own; the caps + the record's (``caps``), wherever they were. OSError or ValueError when + either cannot be read, a record of a later version included.""" + with open(os.path.join(path, RECORD), encoding="utf-8") as fh: + rec = json.load(fh) + if "plan" in rec: + plan = rec["plan"] + rec.setdefault("caps", plan.pop("caps", None) or {}) + return rec, plan + if rec.get("version", 0) > 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) + 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] + for part, name in ((plan, "run.sh"), *((p, _base(p) + ".sh") for p in plan.get("parts") or () if "script" not in p)) if scripts else (): + with open(os.path.join(path, name), encoding="utf-8") as fh: + part["script"] = fh.read() + return rec, plan + + def restore(root: Optional[str] = None, **kw) -> List[Execution]: """At start-up: every recorded run under the root. The ones still alive are reattached (their thread follows the part that was running, or @@ -1900,11 +2035,9 @@ def restore(root: Optional[str] = None, **kw) -> List[Execution]: except OSError: return back for name in names: - path = os.path.join(root, name, RECORD) try: - with open(path, encoding="utf-8") as fh: - rec = json.load(fh) - plan = Plan.from_dict(rec["plan"]) + rec, plan = recorded(os.path.join(root, name)) + plan = Plan.from_dict(plan) except (OSError, ValueError, KeyError, TypeError): continue ex = Execution(plan, root=root, record=rec, **kw) @@ -2011,7 +2144,10 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, ``uids``: its jobs' identities and where each came from (``Job.uid_source``), whose judgements ``delete`` keeps when a copy is found elsewhere.""" path, rec = _deletable(name, root) - plan = rec.get("plan") or {} + try: + plan = recorded(path, scripts=False)[1] or {} + except (OSError, ValueError): # a run whose plan cannot be read goes from this machine alone + plan = {} # a run refused at the name check never made the host folder: one of that name there is not its own host = hosts.parse(plan["host"]) if plan.get("host") and (rec.get("launched") or rec.get("step") not in ("connect", "name")) else None held, olds = [], [] diff --git a/app/nullius/runs/launches.py b/app/nullius/runs/launches.py index 63b840281..a4c00c45b 100644 --- a/app/nullius/runs/launches.py +++ b/app/nullius/runs/launches.py @@ -5,7 +5,7 @@ this order: - **The run record.** A run started from the builder's Run writes - ``runs//run.json``, and its plan names every job it launches + ``runs//run.json``, and its plan beside it names every job it launches (``execution.Plan.jobs``). Those jobs are one launch, including the ones Harbor has not written yet. - **Inferred, for everything else** — an imported tree, a job run by hand: runs on the same dataset whose start is within diff --git a/app/site/diagrams.py b/app/site/diagrams.py index 56ca15aa2..1b4ff293f 100644 --- a/app/site/diagrams.py +++ b/app/site/diagrams.py @@ -357,7 +357,7 @@ def run_leaves() -> Figure: f.path([(120, 296), (520, 296)], 'bus', head=False) for cx in (120, 320, 520): f.path([(cx, 296), (cx, 312)]) - f.node(232, 24, 176, 64, 'runs//', ['run.json: plan and state', 'run-part.sh, log, exit file'], 'store') + f.node(232, 24, 176, 64, 'runs//', ['plan.json, run.json: state', 'run-part.sh, log, exit file'], 'store') f.node(232, 120, 176, 64, 'jobs//', ['config.json, result.json,', 'events.jsonl'], 'store') f.node(232, 216, 176, 64, '/', ['result.json, trial.log,', 'exception.txt'], 'store') f.node(40, 312, 160, 56, 'agent/', ['trajectory.json, logs,', 'traces'], 'focal') diff --git a/app/tests/execution_support.py b/app/tests/execution_support.py index b477a1d8c..717c6d198 100644 --- a/app/tests/execution_support.py +++ b/app/tests/execution_support.py @@ -161,5 +161,5 @@ def ssh_commands(self): def killed(self, pid, part="run"): """A Stop's kill went to the host for ``pid``, by its process group, - once the host has found it still the part's own (``_own_pids``).""" - return any("kill -TERM -- -$p" in c and f"for p in {pid}" in c and execution._script_rx(f"run-{part}") in c for c in self.ssh_commands()) + once the host has found it still the part's own (``_own_pids``). ``run``: a run of one part.""" + return any("kill -TERM -- -$p" in c and f"for p in {pid}" in c and execution._script_rx({"id": part, "whole": part == "run"}) in c for c in self.ssh_commands()) diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index 8498b6f71..541901828 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -5,6 +5,7 @@ import shlex import os import shutil +import tempfile import threading import time import unittest @@ -29,6 +30,18 @@ def test_run_names_must_match_in_full(self): self.assertEqual(execution.Plan(name=name, script="true").check(), "the run needs a name: letters, digits, dots, dashes") + def test_two_parts_that_would_run_one_script_are_refused(self): + for ids in (("same", "same"), ("a b", "a_b")): # the second as a route spells the first + with self.subTest(ids=ids): + parts = [{"id": i, "label": i, "script": f"echo {n}"} for n, i in enumerate(ids)] + self.assertEqual(execution.Plan(name="r", script="", parts=parts).check(), + "two parts run the same script, run-a_b.sh: give each part its own id" if ids[1] == "a_b" + else "two parts run the same script, run-same.sh: give each part its own id") + root = Path(tempfile.mkdtemp(prefix="nullius-collide-")); self.addCleanup(shutil.rmtree, root, True) + with self.assertRaisesRegex(ValueError, "two parts run the same script"): # started directly: no record to restore + execution.start(execution.Plan(name="r", script="", parts=parts), root=str(root)) + self.assertEqual((list(root.iterdir()), [e for e in execution.EXECUTIONS.values() if e.root == str(root)]), ([], [])) + class Here(Base): """Local runs are real: bash, setsid, the exit file, the log.""" @@ -42,10 +55,12 @@ def test_the_script_runs_detached_with_the_local_paths_and_the_key_as_environmen self.assertIn(f"harbor=harbor tasks={self.tmp} jobs={self.tmp / 'runs' / 'tau3-x3' / 'jobs'} model=openai/gpt-5", text) # the harbor on PATH self.assertIn("key=21/21 chars url=https://llm.example/v1", text) # the key reached the run d = self.tmp / "runs" / "tau3-x3" - self.assertEqual((d / "run-run.sh").read_text(), script + "\n"); self.assertEqual((d / "run-run.exit").read_text().strip(), "0") - self.assertNotIn("sk-verysecretkey12345", (d / "run-run.sh").read_text()); self.assertNotIn("sk-verysecretkey12345", (d / "run.json").read_text()) + self.assertEqual((d / "run.sh").read_text(), script + "\n"); self.assertEqual((d / "run-run.exit").read_text().strip(), "0") + self.assertFalse((d / "run-run.sh").exists()) # a run of one part runs run.sh + self.assertNotIn("sk-verysecretkey12345", (d / "run.sh").read_text()); self.assertNotIn("sk-verysecretkey12345", (d / "run.json").read_text()) rec = json.loads((d / "run.json").read_text()) - self.assertEqual((rec["state"], rec["exit_code"], rec["plan"]["name"], rec["plan"]["host"]), ("done", 0, "tau3-x3", None)) + plan = json.loads((d / "plan.json").read_text()) + self.assertEqual((rec["state"], rec["exit_code"], plan["name"], plan["host"]), ("done", 0, "tau3-x3", None)) def test_missing_setsid_uses_python_and_records_the_real_exit_code(self): # Simulate macOS command lookup while retaining the real shell/processes. @@ -179,6 +194,24 @@ def test_a_failing_script_is_a_failed_run(self): self.assertEqual((ex.state, ex.exit_code, ex.error), ("failed", 3, "the run exited 3")) +class FirstSave(Base): + def test_a_launch_whose_record_cannot_be_saved_leaves_no_folder_behind(self): + root = self.tmp / "runs" + plans = [execution.Plan(name="s1", script="true", parts=[{"id": "a", "label": "a", "script": "true"}]), execution.Plan(name="s2", script="true")] + real = execution.ondisk.write_whole + def full(path, data, mode=None): + if path == str(root / "s2" / "run.json"): + raise OSError(28, "No space left on device") + return real(path, data, mode) + runs = [execution.Execution(p, root=str(root)) for p in plans] + with patch.object(execution.ondisk, "write_whole", full), self.assertRaises(OSError): + execution.start_all(runs) + self.assertEqual((list(root.iterdir()), dict(execution.EXECUTIONS)), ([], {})) # names free again, nothing started + for ex in execution.start_all(runs): # tried again: each with its plan, read back + self.wait(ex) + self.assertEqual([execution.recorded(ex.dir)[1]["name"] for ex in runs], ["s1", "s2"]) + + class DockerHere(Base): """A Harbor run here asks docker first, as a run on a host does - and so does the standard on its container backend - and starts nothing when it @@ -232,7 +265,7 @@ def test_the_standard_on_its_docker_backend_asks_too_and_off_it_does_not(self): ex = self.start(execution.Plan(name="std", script="", parts=parts, runner="standard", docker=True, keyless=True)) self.assertEqual((ex.state, ex.step), ("failed", "docker")) self.assertTrue(ex.error.startswith("docker is on this machine but does not answer"), ex.error) - self.assertFalse((self.tmp / "runs" / "std" / "run-run.sh").exists()) + self.assertFalse((self.tmp / "runs" / "std" / "run-run.launch").exists()) (self.tmp / "asked").unlink() ex = self.start(execution.Plan(name="std-local", script="", parts=parts, runner="standard", keyless=True)) # the local backend: no containers self.assertNotEqual(ex.step, "docker", ex.lines) @@ -605,7 +638,7 @@ def run(argv, timeout=600.0, stdin=None, sent=sent): self.assertTrue(ex.error.startswith(f"{var} holds a line break; "), ex.error) self.assertNotIn("cut short", ex.error) d = root / name if target == "here" else self.on_host(name) - self.assertFalse(d.exists() and any(p.name.startswith("run-a.") for p in d.iterdir())) # not claimed, not started + self.assertFalse(d.exists() and any(p.name.startswith("run-a.") and p.name != "run-a.sh" for p in d.iterdir())) # not claimed, not started self.assertFalse(marker.exists()) self.assertNotIn(secret, "\n".join(ex.lines)) for f in root.rglob("*"): @@ -792,16 +825,17 @@ def test_the_part_runs_detached_with_the_host_s_harbor_and_the_job_mirrored_back self.assertRegex(place, r"^tasks/[0-9a-f]{10}/tasks$") self.assertTrue(all(c[-2].startswith("bench:~/.nullius/runs/tau3-x3/jobs/") for c in rsyncs[1:])) # the job came back self.assertGreaterEqual(len(rsyncs), 2) - landed = next(s for c, s in self.calls if c[0] == "ssh" and "cat > " in c[-1] and "run-run.sh" in c[-1]) - self.assertEqual(landed, self.plan.script + "\n") # the part's script, over stdin + landed = [s for c, s in self.calls if c[0] == "ssh" and "cat > " in c[-1] and ".sh" in c[-1]] + self.assertEqual(landed, [self.plan.script + "\n"]) # the run's script, over stdin, once launch = next((c, s) for c, s in self.calls if c[0] == "ssh" and "setsid nohup" in c[-1]) + self.assertIn("bash run.sh <", launch[0][-1]) # as run.sh, the one script of a run of one part self.assertIn("BatchMode=yes", launch[0]); self.assertIn("read -r K", launch[0][-1]) self.assertIn("NULLIUS_HARBOR=harbor ", launch[0][-1]); self.assertIn(f'NULLIUS_TASKS="$HOME/.nullius/{place}"', launch[0][-1]) self.assertIn('export PATH="$HOME/.local/bin:$PATH"', launch[0][-1]) # where a uv-installed harbor lives self.assertIn('NULLIUS_JOBS="$HOME/.nullius/runs/tau3-x3/jobs"', launch[0][-1]); self.assertIn("API_MODEL_NAME=openai/gpt-5", launch[0][-1]) self.assertNotIn("sk-verysecretkey12345", launch[0][-1]); self.assertEqual(launch[1], "sk-verysecretkey12345\n\n@end\n") # stdin: the key, the endpoint, the end line self.assertIn("harbor: starting", ex.lines); self.assertNotIn("sk-verysecretkey12345", "\n".join(ex.lines)) - self.assertEqual(json.loads((self.tmp / "runs" / "tau3-x3" / "run.json").read_text())["plan"]["host"], "bench") + self.assertEqual(json.loads((self.tmp / "runs" / "tau3-x3" / "plan.json").read_text())["host"], "bench") def test_a_host_s_run_is_sent_this_machine_s_hugging_face_endpoint(self): with mock.patch.dict(os.environ, {"HF_ENDPOINT": "https://hf-mirror.com/"}): diff --git a/app/tests/test_execution_again.py b/app/tests/test_execution_again.py index bfc86f85f..1c5aefcd4 100644 --- a/app/tests/test_execution_again.py +++ b/app/tests/test_execution_again.py @@ -35,6 +35,8 @@ def test_a_part_runs_again_in_the_run_s_folder_with_the_key_read_now(self): self.assertEqual(ex.state, "done", ex.lines) first = ex.job_state("j1") self.assertIsNone(ex.holds("j1")) + saved = self.tmp / "runs" / "std-here" / "plan.json" + written = (saved.read_bytes(), saved.stat().st_mtime_ns, saved.stat().st_ino) gate = self.tmp / "go" script = f'until [ -e {shlex.quote(str(gate))} ]; do sleep 0.02; done; echo "again key=${{#API_TOKEN}} jobs=$NULLIUS_JOBS"' with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-second-key-2"}): @@ -57,15 +59,30 @@ def test_a_part_runs_again_in_the_run_s_folder_with_the_key_read_now(self): # the job's end is still its own part's; the run's record holds both parts self.assertEqual(ex.job_state("j1"), first) self.assertIsNone(ex.again_of("j1")) - rec = json.loads((d / "run.json").read_text()) - self.assertEqual([p["id"] for p in rec["plan"]["parts"]], ["fake", "again-1"]) + rec, plan = execution.recorded(str(d)) + self.assertEqual([p["id"] for p in plan["parts"]], ["fake", "again-1"]) + self.assertEqual(plan["parts"][1]["script"], script + "\n") + # the part run again is the record's, its script its own file: the plan is as the run's start wrote it + self.assertEqual((saved.read_bytes(), saved.stat().st_mtime_ns, saved.stat().st_ino), written) + self.assertEqual([p["id"] for p in json.loads(written[0])["parts"]], ["fake"]) + self.assertEqual(json.loads((d / "run.json").read_text())["again"], [{k: v for k, v in part(script).items() if k != "script"}]) self.assertEqual(sorted(rec["ends"]), ["again-1", "fake"]) self.assertEqual(ex.part_for("j1"), "fake") # a restart reads it as it was execution.EXECUTIONS.clear() - back = execution.Execution(execution.Plan.from_dict(rec["plan"]), root=str(self.tmp / "runs"), record=rec) + back = execution.Execution(execution.Plan.from_dict(plan), root=str(self.tmp / "runs"), record=rec) self.assertEqual((back.state, back.job_state("j1")), ("done", first)) + def test_a_part_whose_script_cannot_be_written_is_not_recorded(self): + ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start()) + with mock.patch.object(execution, "_write_script", side_effect=OSError(28, "No space left on device")), self.assertRaises(OSError): + ex.again(part("true"), env={"OPENAI_API_KEY": "sk-first-key-0001"}) + self.assertEqual([p["id"] for p in ex.plan.parts], ["fake"]) + ex._save() # a later save, a cap's + execution.EXECUTIONS.clear() + execution.restore(str(self.tmp / "runs")) + self.assertEqual([e.plan.name for e in execution.EXECUTIONS.values()], ["std-here"]) # still read back + def test_a_part_run_again_that_fails_fails_the_run_and_not_the_job(self): ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start()) first = ex.job_state("j1") diff --git a/app/tests/test_execution_recovery.py b/app/tests/test_execution_recovery.py index e9a0f7d22..11f9cc899 100644 --- a/app/tests/test_execution_recovery.py +++ b/app/tests/test_execution_recovery.py @@ -101,11 +101,87 @@ def test_a_trial_line_is_said_once_across_a_restart(self): self.assertEqual([l for l in again.lines if "task-" in l], said) self.assertEqual([l for l in (d / "nullius.log").read_text().splitlines() if "task-" in l], said) # a record from before the trials were kept loads, with none said yet - old = json.loads((d / "run.json").read_text()); old.pop("seen_trials", None) + old = json.loads((d / "run.json").read_text()); old.pop("feeds") before = execution.Execution(execution.Plan(name="r", script="", parts=parts), root=str(self.tmp), record=old) before._trial_lines() self.assertEqual(len([l for l in before.lines if "task-" in l]), 6) + END = '{"event":"trial.end","trial":"t%d","task":"task-%d","outcome":"resolved","reward":1.0}\n' + + def said(self, d): + return [l.split(" · ")[1] for l in (d / "nullius.log").read_text().splitlines() if "task-" in l] + + def test_a_restart_in_the_middle_of_a_feed_says_each_trial_once(self): + """The record holds how far each feed was read, not the trials: it is as + large after 300 trial ends as after one, and a restart reads on from there.""" + d = self.tmp / "r"; feed = d / "jobs" / "r-a" / "events.jsonl"; feed.parent.mkdir(parents=True) + ex = execution.Execution(execution.Plan(name="r", script="true"), root=str(self.tmp)) + sizes = [] + for n in range(1, 301): + with open(feed, "a") as fh: + fh.write('{"event":"trial.phase","trial":"t%d"}\n' % n + self.END % (n, n)) + ex._trial_lines(); sizes.append((d / "run.json").stat().st_size) + rec = json.loads((d / "run.json").read_text()) + self.assertEqual((rec["version"], rec["feeds"], "seen_trials" in rec), (execution.VERSION, {"r-a": feed.stat().st_size}, False)) + self.assertLessEqual(sizes[-1] - sizes[0], len(str(feed.stat().st_size))) # the position's own digits, nothing per trial + half = self.END % (301, 301) + with open(feed, "a") as fh: + fh.write(half[:40]) # a line the feed's writer is in the middle of + ex._trial_lines(); execution.EXECUTIONS.clear() + back = execution.Execution(execution.Plan.from_dict(execution.recorded(str(d))[1]), root=str(self.tmp), record=execution.recorded(str(d))[0]) + with open(feed, "a") as fh: + fh.write(half[40:] + self.END % (302, 302)) + back._trial_lines(); back._trial_lines() + self.assertEqual(self.said(d), [f"task-{n}" for n in range(1, 303)]) + + def test_the_plan_and_each_script_are_written_once(self): + """``plan.json`` holds the plan and the recipe, the scripts are their own + files, and a trial end rewrites none of them.""" + d = self.tmp / "r" + parts = [{"id": "a", "label": "a", "script": f"mkdir -p $NULLIUS_JOBS/r-a; printf '%s' '{self.END % (1, 1)}' >> $NULLIUS_JOBS/r-a/events.jsonl"}, + {"id": "b", "label": "b", "script": "echo b\n"}] + plan = execution.Plan(name="r", script="echo whole", parts=parts + [{"id": "none", "label": "none"}], recipe={"benchmark": "demo"}) + ex = execution.Execution(plan, root=str(self.tmp)); ex._save() + first = {n: ((d / n).stat().st_ino, (d / n).stat().st_mtime_ns) for n in ("plan.json", "run.sh", "run-a.sh", "run-b.sh")} + time.sleep(0.01) + self.wait(ex.start()) + self.assertEqual((ex.state, self.said(d)), ("done", ["task-1"]), ex.lines) + # a launch here never opens a script again: one cut short would leave it empty for the record to read back + self.assertEqual({n: ((d / n).stat().st_ino, (d / n).stat().st_mtime_ns) for n in first}, first) + saved = json.loads((d / "plan.json").read_text()) + self.assertEqual((saved["recipe"], "script" in saved, saved["parts"]), ({"benchmark": "demo"}, False, [{"id": "a", "label": "a"}, {"id": "b", "label": "b"}, {"id": "none", "label": "none", "script": ""}])) + self.assertNotIn("plan", json.loads((d / "run.json").read_text())) + self.assertEqual([(d / n).read_text() for n in ("run.sh", "run-a.sh", "run-b.sh")], ["echo whole\n", parts[0]["script"] + "\n", "echo b\n"]) + execution.EXECUTIONS.clear(); execution.restore(str(self.tmp)) + back = execution.EXECUTIONS[ex.id].plan + self.assertEqual((back.recipe, back.script, back.steps()), ({"benchmark": "demo"}, "echo whole\n", [dict(parts[0], script=parts[0]["script"] + "\n"), parts[1]])) + self.assertFalse((d / "run-none.sh").exists()) + + def test_a_record_from_before_the_plan_file_restores_and_resumes(self): + """A run folder written before ``version``: its plan and scripts in + ``run.json`` with the trials it said. It waits again at its pause, runs + on, says only the trial that ended since, and is recorded as runs are now.""" + d = self.tmp / "r"; feed = d / "jobs" / "r-a" / "events.jsonl"; feed.parent.mkdir(parents=True) + feed.write_text("".join(self.END % (n, n) for n in (1, 2, 3))) + parts = [{"id": "a", "label": "a", "script": "exit 2"}, + {"id": "b", "label": "b", "script": f"mkdir -p $NULLIUS_JOBS/r-b; printf '%s' '{self.END % (4, 4)}' >> $NULLIUS_JOBS/r-b/events.jsonl"}] + plan = execution.Plan(name="r", script="exit 2", parts=parts, recipe={"benchmark": "demo"}).to_dict() + (d / "run.json").write_text(json.dumps({ + "id": "r-1", "plan": plan, "state": "paused", "step": "run", "part": 1, "pid": None, "log_offset": 0, "exit_code": None, "error": None, + "question": "a exited 2. Continue with b, or stop?", "ends": {"a": {"rc": 2, "at": 1.0, "label": "a"}}, "started": 1.0, "finished": None, + "harbor": "harbor", "tasks_on_target": "", "app_on_target": "", "catalogue_on_target": "", "workspace": "", "launched": "a", + "seen_trials": [["r-a", "t1"], ["r-a", "t2"]]}, indent=1)) + again = execution.restore(str(self.tmp))[0] + self.assertEqual((again.id, again.plan.recipe, again.plan.steps()), ("r-1", {"benchmark": "demo"}, parts)) + self.until(again, "paused"); again.continue_(); self.wait(again) + self.assertEqual((again.state, self.said(d)), ("done", ["task-3", "task-4"]), again.lines) + rec, saved = execution.recorded(str(d)) + self.assertEqual((rec["version"], "plan" in rec, "seen_trials" in rec, sorted(rec["feeds"])), (execution.VERSION, False, False, ["r-a", "r-b"])) + self.assertEqual(execution.Plan.from_dict(saved).steps(), [dict(p, script=p["script"] + "\n") for p in parts]) + execution.EXECUTIONS.clear(); execution.restore(str(self.tmp)) + execution.EXECUTIONS["r-1"]._trial_lines() + self.assertEqual(self.said(d), ["task-3", "task-4"]) + def test_a_pause_waits_again_after_a_restart(self): parts = [{"id": "a", "label": "a", "script": "exit 2"}, {"id": "b", "label": "b", "script": "echo b"}] ex = execution.Execution(execution.Plan(name="r", script="", parts=parts), root=str(self.tmp)).start() @@ -501,11 +577,16 @@ class RestartOnHost(HostBase): """A restart asks the host what a part left in its run directory before it trusts the record.""" - def recorded(self, plan, **fields): + def recorded(self, plan, before=False, **fields): + """``before``: as a Nullius before ``plan.json`` recorded it.""" ex = execution.Execution(plan, root=str(self.tmp / "runs"), run=self.answer, key="k" * 20) ex._save() path = self.tmp / "runs" / plan.name / "run.json" - rec = json.loads(path.read_text()); rec.update(fields); path.write_text(json.dumps(rec)) + rec = json.loads(path.read_text()); rec.update(fields) + if before: + rec = {k: v for k, v in rec.items() if k not in ("version", "feeds", "caps", "again")} + rec.update(plan=plan.to_dict(), seen_trials=[]); (path.parent / "plan.json").unlink() + path.write_text(json.dumps(rec)) execution.EXECUTIONS.clear(); self.calls.clear() def holding(self, files): @@ -519,12 +600,21 @@ def answer(argv, timeout=0, stdin=None): def test_a_part_started_before_its_pid_was_saved_is_followed_by_the_pid_it_wrote(self): self.recorded(self.plan, state="running", step="run", part=0, pid=None, harbor="harbor") + self.followed_by_the_pid_it_wrote() + + def test_a_run_of_one_part_recorded_before_the_plan_file_is_followed_as_it_ran(self): + """Launched as ``run-run.sh`` by a Nullius before: found by it still.""" + self.recorded(self.plan, before=True, state="running", step="run", part=0, pid=None, harbor="harbor") + self.followed_by_the_pid_it_wrote() + self.assertTrue((self.tmp / "runs" / self.plan.name / "plan.json").exists()) # recorded as runs are now + + def followed_by_the_pid_it_wrote(self): back = execution.restore(str(self.tmp / "runs"), run=self.holding({"run-run.pid": "4242", "run-run.log": ""}), key="k" * 20) self.assertEqual(len(back), 1); self.wait(back[0]) self.assertEqual((back[0].state, back[0].exit_code), ("done", 0), back[0].lines) self.assertFalse(any("setsid nohup" in c[-1] for c, _ in self.calls)) # not started a second time follows = [c[-1] for c, _ in self.calls if "__nullius__" in c[-1]] - self.assertTrue(follows and all("for p in 4242 " in c and execution._script_rx("run-run") in c for c in follows)) # 4242, while it runs the part + self.assertTrue(follows and all("for p in 4242 " in c and execution._script_rx(self.plan.steps()[0]) in c for c in follows)) # 4242, while it runs the part self.assertIn("harbor: starting", back[0].lines) # its log, from its start def test_a_stop_cut_short_before_the_pid_was_saved_kills_the_part_it_finds(self): @@ -570,8 +660,8 @@ def end_part(self): pass self.part.wait() - def ask(self, pids=()): - out = subprocess.run(["bash", "-c", execution._part_pids("run-a", pids)], cwd=self.dir, capture_output=True, text=True, timeout=10) + def ask(self, pids=(), part=None): + out = subprocess.run(["bash", "-c", execution._part_pids(part or {"id": "a"}, pids)], cwd=self.dir, capture_output=True, text=True, timeout=10) return [int(l) for l in out.stdout.split()] def test_a_running_part_is_found_with_proc_and_without(self): @@ -579,6 +669,18 @@ def test_a_running_part_is_found_with_proc_and_without(self): with patch.object(execution, "PROC", os.path.join(self.dir, "no-proc")): self.assertIn(self.part.pid, self.ask()) + def test_a_run_of_one_part_is_found_by_run_sh_and_by_the_run_run_sh_it_ran_before(self): + whole = execution.Plan(name="r", script="sleep 30").steps()[0] + self.assertEqual(self.ask(part=whole), []) # run-a.sh is another part's + for name in ("run.sh", "run-run.sh"): + with self.subTest(name=name): + Path(self.dir, name).write_text("sleep 30\n") + p = subprocess.Popen(["bash", name], cwd=self.dir, start_new_session=True) + try: + self.assertEqual(self.ask(part=whole), [p.pid]) + finally: + os.killpg(p.pid, 9); p.wait() + def test_without_proc_a_dead_pid_is_not_taken_for_the_part(self): dead = subprocess.Popen(["true"]); dead.wait() with patch.object(execution, "PROC", os.path.join(self.dir, "no-proc")): diff --git a/app/ui_tests/test_rerun_page.py b/app/ui_tests/test_rerun_page.py index 88e8d0056..fe7ba4e44 100644 --- a/app/ui_tests/test_rerun_page.py +++ b/app/ui_tests/test_rerun_page.py @@ -366,8 +366,10 @@ def test_the_page_shows_the_job_s_one_cap_and_a_change_holds_from_the_next_run(s "Spending cap for the whole run $0.31 spent so far. The new cap applies from the job's next run. Cap, USD Cancel Save") r = self.cap("r1", {"max_usd": "6"}) self.assertEqual((r.status_code, r.json["left_usd"]), (200, 5.69), r.get_data(as_text=True)) - record = json.loads((self.tmp / "runs" / "r1" / "run.json").read_text()) - self.assertEqual(record["plan"]["caps"], {"r1": 6.0}) # kept with the run, for the job's next run + self.assertEqual(execution.recorded(str(self.tmp / "runs" / "r1"))[0]["caps"], {"r1": 6.0}) # kept with the run, for the job's next run + plan = self.tmp / "runs" / "r1" / "plan.json" + written = (plan.read_bytes(), plan.stat().st_mtime_ns, plan.stat().st_ino) + self.assertNotIn("caps", json.loads(written[0])) html = self.page("/job/r1?view=results") self.assertEqual(text(html, r'
'), "Spending cap $6.00") self.assertEqual(text(html, r'

.*?

'), "Budget for the whole run: $6.00, $5.69 left.") @@ -378,7 +380,8 @@ def test_the_page_shows_the_job_s_one_cap_and_a_change_holds_from_the_next_run(s "changes": [{"at": "2026-11-20T20:00:00+00:00", "max_usd": 6.0, "was": 4.0}]}) self.assertEqual(self.post("r1", {"trials": [trial_name(1)]}).status_code, 200) self.assertIn(f"--unit {trial_name(1)} --from-run", self.asked[-1][1]["script"]) - self.assertEqual(json.loads((self.tmp / "runs" / "r1" / "run.json").read_text())["plan"]["caps"], {}) + self.assertEqual(execution.recorded(str(self.tmp / "runs" / "r1"))[0]["caps"], {}) + self.assertEqual((plan.read_bytes(), plan.stat().st_mtime_ns, plan.stat().st_ino), written) # a cap is the record's, never the plan's self.assertEqual(text(self.page("/job/r1?view=results"), r'
.*?
'), "$0.40 spent · Change") def test_a_change_is_refused_at_or_under_what_was_spent_and_while_a_later_run_goes_on(self): @@ -398,7 +401,7 @@ def test_a_change_is_refused_at_or_under_what_was_spent_and_while_a_later_run_go self.assertEqual((r.status_code, r.json["error"]), (409, "Still running: more tasks can be started once it has ended.")) self.assertEqual(text(self.page("/job/r1?view=results"), r'
.*?
'), "$0.31 spent · change it when this run ends") - self.assertEqual(ex.plan.caps, {}) + self.assertEqual(ex.caps, {}) def test_a_job_whose_cap_is_spent_is_refused_and_the_question_says_so(self): d = self.run_of() diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 717806636..3cb6e02aa 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -174,6 +174,25 @@ def test_a_name_still_running_or_used_before_is_refused_and_nothing_starts(self) self.assertEqual((dict(execution.EXECUTIONS), self.adopted), ({}, [])) # nothing started, the free name included self.assertFalse((self.tmp / "runs" / "fresh").exists()) + def test_a_name_another_launch_takes_after_the_check_is_refused_and_its_folder_left_alone(self): + late = self.tmp / "runs" / "late" + real = execution.reserve + def another(runs): # the other launch lands between the check and the start + late.mkdir(parents=True); (late / "plan.json").write_text("theirs") + return real(runs) + plans = [execution.Plan(name="fresh", script="true"), execution.Plan(name="late", script="true")] + with patch.object(execution, "reserve", another): + self.assertEqual(web.execute.begin(plans), ([], execution.name_taken("late"), 409)) + self.assertEqual((dict(execution.EXECUTIONS), self.adopted), ({}, [])) # no workspace was given the other launch's jobs + self.assertEqual(sorted(p.name for p in late.iterdir()), ["plan.json"]); self.assertEqual((late / "plan.json").read_text(), "theirs") + self.assertFalse((self.tmp / "runs" / "fresh").exists()) # this launch's own folder, plan and script included, gone + + def test_a_runs_folder_that_cannot_hold_runs_is_a_storage_error_not_a_name(self): + (self.tmp / "runs").write_text("") + runs, problem, status = web.execute.begin([execution.Plan(name="free", script="true")]) + self.assertEqual((runs, status), ([], 503)) + self.assertIn("could not be saved", problem) + def test_a_launch_refuses_a_linked_workspace_before_starting(self): home = self.tmp / "workspaces" home.mkdir() @@ -768,8 +787,8 @@ def test_a_restart_reopens_the_open_workspace_and_puts_the_run_back_into_its_own self.assertEqual(json.loads(self.record.read_text())["workspace"], self.ws.name) def test_a_rename_refiles_the_run_and_a_restart_puts_it_back_in_the_renamed_workspace(self): - rec = json.loads(self.record.read_text()) - ex = execution.Execution(execution.Plan.from_dict(rec["plan"]), root=str(self.tmp / "runs"), record=rec) + rec, plan = execution.recorded(str(self.record.parent)) + ex = execution.Execution(execution.Plan.from_dict(plan), root=str(self.tmp / "runs"), record=rec) execution.EXECUTIONS[ex.id] = ex # the run as the page holds it r = self.client.post("/workspaces/rename", data={"name": self.ws.name, "label": "sharp lemur", "csrf": self.csrf}, headers={"Origin": "http://localhost"}); self.addCleanup(r.close) diff --git a/app/web/execute.py b/app/web/execute.py index 2a8bf083b..1699a37c7 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -249,19 +249,28 @@ def begin(plans: list, into: str = "") -> tuple: if os.path.exists(os.path.join(execution.runs_root(), plan.name)): return [], execution.name_taken(plan.name), 409 prepared = [execution.Execution(plan) for plan in plans] + saving = (lambda error: (f"The run's record could not be saved ({error.strerror or error}). " + f"Check the permissions and free space of {execution.runs_root()}, then retry.")) + # Each name held by this launch alone before anything is written under it + try: + execution.reserve(prepared) + except execution.NameTaken as error: + return [], str(error), 409 + except OSError as error: + return [], saving(error), 503 # Save the destination before any worker can run. Its name goes into # the first run record, rather than a second write after launch. try: shared.adopt_runs(prepared, into, persist=False) - except ValueError as error: - return [], str(error), 400 - except OSError: + except (ValueError, OSError) as error: + execution.release(prepared) + if isinstance(error, ValueError): + return [], str(error), 400 return [], "The launch workspace could not be saved. Check its permissions and free space, then retry.", 503 try: - execution.start_all(prepared) + execution.start_all(prepared, reserved=True) except OSError as error: - return [], (f"The run's record could not be saved ({error.strerror or error}). " - f"Check the permissions and free space of {execution.runs_root()}, then retry."), 503 + return [], saving(error), 503 return prepared, "", 200 @@ -346,25 +355,25 @@ def job_rerun(job_id): def job_cap(job, ex, settle: bool = False) -> dict | None: """The job's one spending cap as its page shows it and its next run has it (``rerun.budget``): the cap - set on the page (``Plan.caps``) where it differs from the job's own, else the job's. ``settle``: a cap set on the + set on the page (``Execution.caps``) where it differs from the job's own, else the job's. ``settle``: a cap set on the page that the job's record now holds is dropped from the run's record. None for a job with no cap.""" if not job.standard: return None - set_here = (ex.plan.caps or {}).get(job.job_id) if ex is not None else None + set_here = (ex.caps or {}).get(job.job_id) if ex is not None else None try: got = rerun.budget(job.dir, cap=set_here) except (OSError, ValueError, TypeError, KeyError): return None if settle and set_here is not None and got is not None and not got["changed"]: with ex._turn: - ex.plan.caps = {k: v for k, v in ex.plan.caps.items() if k != job.job_id} + ex.caps = {k: v for k, v in ex.caps.items() if k != job.job_id} ex._save() return got @app.route("/job//cap", methods=["POST"]) def job_cap_change(job_id): - """A new spending cap for the whole job, from its next run on: kept in its run's record (``Plan.caps``) and + """A new spending cap for the whole job, from its next run on: kept in its run's record (``Execution.caps``) and handed to that run as ``rerun --max-usd``. Refused where the page offers no next run (``again_offer``: a run of the job under way), and for a cap at or under what the job has spent, when that is known.""" shared._require_csrf() @@ -389,8 +398,8 @@ def job_cap_change(job_id): if not now.get("unknown") and (now["left_usd"] <= 0 or ledger.usd(cap) == ledger.usd(now["spent_usd"])): return jsonify(ok=False, error=f"The cap must be above what this run has spent, {ledger.usd(now['spent_usd'])} USD."), 400 with ex._turn: - caps = {k: v for k, v in (ex.plan.caps or {}).items() if k != job_id} - ex.plan.caps = caps if not now["changed"] else dict(caps, **{job_id: cap}) + caps = {k: v for k, v in (ex.caps or {}).items() if k != job_id} + ex.caps = caps if not now["changed"] else dict(caps, **{job_id: cap}) ex._save() return jsonify(ok=True, max_usd=cap, left_usd=None if now.get("unknown") else now["left_usd"]) diff --git a/docs/builder.md b/docs/builder.md index b66cb5615..5228bd82d 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -83,7 +83,7 @@ a declared model list keeps those published choices. | --- | --- | --- | | Draft | The browser, one per browser | Saved on every change; *Start over* forgets it | | Saved recipes | `recipes/.json` under the user data directory, one file each | Any browser lists and loads them. Save and Delete work only from a browser on the application host. An existing name updates its recipe. Saving a loaded recipe under a new name renames it. Import and export as JSON. | -| A run's recipe | `runs//run.json` | Job page, *New run like this*: the same recipe, at Review. | +| A run's recipe | `runs//plan.json` | Job page, *New run like this*: the same recipe, at Review. | | A job's record | Its `config.json` and `lock.json` | *New run like this* without a kept recipe: rebuilt, what it cannot carry named | *Import* adds a recipe file, or a list, and refuses the whole file when one @@ -107,7 +107,7 @@ and Delete work only from a browser on the application host. | Restart of Nullius | Reattaches; the job goes back into the workspace it started in, under the name a rename gave it, while that workspace exists, without opening it. The workspace open before the restart opens again. One process follows a runs folder: a second `nullius serve` on it stops with a message | | Cannot run from the page | Generated tasks and custom agents are not supported by Run | | Refused | Reads *refused* on the runs page, with why; the job was never written | -| Files | `//`: script, log, `run.json`, `jobs/`; default `runs/` under the user data directory (`nullius paths`) | +| Files | `//`: scripts, log, `plan.json`, `run.json`, `jobs/`; default `runs/` under the user data directory (`nullius paths`) | ## Harbor diff --git a/docs/diagrams/run-leaves.svg b/docs/diagrams/run-leaves.svg index b48173bd5..8c7d4a464 100644 --- a/docs/diagrams/run-leaves.svg +++ b/docs/diagrams/run-leaves.svg @@ -45,7 +45,7 @@ runs/<name>/ -run.json: plan and state +plan.json, run.json: state run-part.sh, log, exit file