diff --git a/app/nullius/execution.py b/app/nullius/execution.py index ead98279e..100b9c749 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -430,7 +430,7 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl # A Stop (the page's thread) and the run's own thread pausing or ending, each with the record # it saves, one at a time: a Stop is never written over, a record never half of each. self._turn = threading.RLock() - self._lock = threading.Lock() + self._lock = threading.RLock() # the log's lines: a look's trial lines hold it from their record to the last self.thread: Optional[threading.Thread] = None self._lines: List[str] = [] #: what a part is downloading, while it does: {label, done, total} in bytes, from its `@progress` lines @@ -469,10 +469,16 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl 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 ()} + # the trial lines a look is writing, saved before the first of them (_trial_lines): a restart finds which got there + self._pending: Optional[dict] = None + self._waiting: List[str] = [] # lines logged while those could not be settled: written once they are self._planned = "version" in rec # the plan is in its own file already self._held: Optional[int] = None # the folder's lock while it has no record yet (``reserve``) 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 rec.get("pending"): + self._pending = rec["pending"] + self._settle_said() if record: # a run still going reads its log now, to go on from it; one that ended when its page asks self._unread = True @@ -506,8 +512,8 @@ def _credentials(self, key: Optional[str], url: Optional[str], env, agent_keys: def _read_log(self) -> None: self._unread = False try: - with open(self.log_path, encoding="utf-8") as fh: - self._lines = fh.read().splitlines() + with open(self.log_path, encoding="utf-8", errors="replace") as fh: + self._lines = fh.read().splitlines() + self._waiting except OSError: pass self._events = [e for e in map(progress.parse, self._lines) if e] @@ -533,11 +539,12 @@ def events(self, value: List[dict]) -> None: self._unread, self._events = False, value - def _save(self, strict: bool = False) -> None: + def _save(self, strict: bool = False) -> bool: """``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.""" + (``_save_plan``) at the first save; True once written. A write that + fails is let go, the last record saved standing; ``strict`` (the + first, ``start_all``): OSError.""" with self._turn: 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, @@ -545,6 +552,8 @@ def _save(self, strict: bool = False) -> None: "catalogue_on_target": self.catalogue_on_target, "workspace": self.workspace, "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._pending: + data["pending"] = self._pending if self._seen_trials: data["seen_trials"] = [list(k) for k in sorted(self._seen_trials, key=str)] try: @@ -556,6 +565,8 @@ def _save(self, strict: bool = False) -> None: except OSError: if strict: raise + return False + return True def _save_plan(self) -> None: """``plan.json``, and each script once, in its own file: the whole run's @@ -576,9 +587,14 @@ def _save_plan(self) -> None: 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): - return # ssh's own warning about the host's key exchange, not the run's + def _log_size(self) -> int: + try: + return os.path.getsize(self.log_path) + except OSError: + return 0 + + def _clean(self, line: str) -> str: + """A line as the log writes it: redacted.""" clean = redact.redact(line.rstrip("\n")) for key in (self._key, *(v for n, v in self._roles.items() if n.endswith("_KEY"))): if key and key != settings.MODEL_KEY_PLACEHOLDER: # the placeholder is no secret, and a common word @@ -586,17 +602,32 @@ def log(self, line: str) -> None: for value in list(self._agent_keys.values()) + self._redact: if len(value) >= 8: clean = clean.replace(value, "[REDACTED]") + return clean + + 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): + return # ssh's own warning about the host's key exchange, not the run's + clean = self._clean(line) ev = progress.parse(clean) + settled = self._settle_said() # never a line after trial lines a look left unsettled with self._lock: self.lines.append(clean) if ev is not None: self.events.append(ev) - try: - os.makedirs(self.dir, exist_ok=True) - with open(self.log_path, "a", encoding="utf-8") as fh: - fh.write(clean + "\n") - except OSError: - pass + if settled and self._pending is None: + self._write(clean) + else: + self._waiting.append(clean) + + def _write(self, clean: str) -> bool: + """One line appended to the log; False when it was refused.""" + try: + os.makedirs(self.dir, exist_ok=True) + with open(self.log_path, "a", encoding="utf-8") as fh: + fh.write(clean + "\n") + except OSError: + return False + return True def _log_since(self, base: str) -> str: """Shell that prints a part's log from ``log_offset`` to its size @@ -1089,23 +1120,83 @@ def _wait_decision(self, remaining: List[dict]) -> bool: self._save() return True + def _settle_said(self, at: Optional[int] = None) -> bool: + """The pending trial lines (``_trial_lines``) checked against the log's + bytes from where they began, in this process or after a restart: those + there whole, in order, move their job's feed past their trial ends (to + ``at`` when all are); the start of the next one, cut short and nothing + after it, is taken out; the record is saved without them, and the rest + are said at the next look. True once saved, or with nothing pending; + until then the record keeps them and every look stops here.""" + if self._pending is None: + return True + with self._turn, self._lock: + pending = self._pending + if pending is None: + return True + job, start = str(pending.get("job")), int(pending.get("from", 0)) + try: + with open(self.log_path, "rb") as fh: + fh.seek(start) + there = fh.read() + except FileNotFoundError: + there = b"" # no log yet: none of them got there + except OSError: + return False + n, end = 0, 0 + said = pending.get("said") or [] + for line, _ in said: + b = (line + "\n").encode("utf-8") + if there[end:end + len(b)] != b: + break + n, end = n + 1, end + len(b) + rest = there[end:] + if rest and n < len(said) and (said[n][0] + "\n").encode("utf-8").startswith(rest): + try: + os.truncate(self.log_path, start + end) + except OSError as e: + said_so = f" the log's last line, cut short, could not be taken out: {e}" + if said_so not in self.lines: # said on the page once, not at every look that tries again + self.lines.append(said_so) + return False + self._unread = True # the page reads the log as it is now + feeds, seen = dict(self._feeds), self._seen_trials + if n: + self._feeds[job] = at if at is not None and n == len(said) else int(said[n - 1][1]) + self._seen_trials = {k for k in self._seen_trials if k[0] != job} + self._pending = None + if not self._save(): + self._pending, self._feeds, self._seen_trials = pending, feeds, seen + return False + for line in self._waiting: + self._write(line) + self._waiting = [] + return True + 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. 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 + says none of them twice. Before a job's lines, the record holds them, + where in the log they begin, and the feed position each says up to; no + other line is logged until the last, and the log's bytes then tell + which got there (``_settle_said``). No line is written without that + record, none after one refused, and no look reads on until it is settled. + 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.""" + if not self._settle_said(): + return try: names = sorted(os.listdir(self.jobs)) except OSError: return - 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] = {} + lines: List[tuple] = [] # (line, the feed's position after its trial end) try: with open(feed, "rb") as fh: at = self._feeds.get(name, 0) @@ -1130,22 +1221,34 @@ def _trial_lines(self) -> None: 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))) reward, score = ev.get("reward"), ev.get("score") # a trial its benchmark scored without a pass or fail is neither mark: its score is said mark = "✓" if ev.get("outcome") == "resolved" else "·" if ev.get("outcome") == "scored" else "✕" - self.log(f" {mark} {name} · {ev.get('task') or ev.get('trial')} · {ev.get('outcome')}" - + (f" · reward {reward}" if reward is not None else f" · score {score:.3g}" if isinstance(score, (int, float)) else "") - + (f" · {int(secs // 60)}:{int(secs % 60):02d}" if secs else "")) + lines.append((f" {mark} {name} · {ev.get('task') or ev.get('trial')} · {ev.get('outcome')}" + + (f" · reward {reward}" if reward is not None else f" · score {score:.3g}" if isinstance(score, (int, float)) else "") + + (f" · {int(secs // 60)}:{int(secs % 60):02d}" if secs else ""), at)) 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() + # the lines and the position together, so a record saved meanwhile (_save) has neither or both + with self._turn, self._lock: + if not lines: + self._feeds[name] = at + self._seen_trials = {k for k in self._seen_trials if k[0] != name} + continue + clean = [self._clean(line) for line, _ in lines] + self._pending = {"job": name, "from": self._log_size(), "said": [[c, pos] for c, (_, pos) in zip(clean, lines)]} + if not self._save(): + self._pending = None + return + kept = self.lines # read before the lines are written: a restored run reads its log first + for c in clean: + if not self._write(c): + break + kept.append(c) + if not self._settle_said(at): + return @property @@ -1775,6 +1878,10 @@ def _follow(self, part: dict) -> int: # Alive while a process runs its script in its run directory (_part_pids). alive = f"[ -n \"$({_part_pids(part, [self.pid])})\" ] && echo alive || echo gone" while True: + if not self._settle_said(): # trial lines a look left unsettled: nothing read on, no end taken, until they are + if self._stop.wait(SYNC_EVERY): + return 130 + continue # 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. rc, out = self._sh(f"cd {self._q(self._run_dir())} 2>/dev/null; s=$({alive}); [ -f {base}.exit ] && s=$(cat {base}.exit); " @@ -1792,9 +1899,10 @@ def _follow(self, part: dict) -> int: self._mirror() else: self._trial_lines() - if status.isdigit(): + settled = self._pending is None # else the part ends at a look that settles its trials' lines + if settled and status.isdigit(): return int(status) - if status == "gone": + if settled and status == "gone": self.log(f" {part['label']} is gone without an exit code") return 1 if self._stop.wait(SYNC_EVERY): diff --git a/app/tests/test_execution_recovery.py b/app/tests/test_execution_recovery.py index 11f9cc899..79381ee58 100644 --- a/app/tests/test_execution_recovery.py +++ b/app/tests/test_execution_recovery.py @@ -134,6 +134,245 @@ def test_a_restart_in_the_middle_of_a_feed_says_each_trial_once(self): back._trial_lines(); back._trial_lines() self.assertEqual(self.said(d), [f"task-{n}" for n in range(1, 303)]) + class Gone(BaseException): + """Nullius killed.""" + + def gone_after(self, ex, n, during=None): + """``ex._trial_lines()`` with Nullius killed as it opens the log for its + trial line ``n + 1``; ``during(path)`` first at each feed it opens.""" + real, log, opened = open, ex.log_path, [0] + + def opener(path, mode="r", *a, **k): + if str(path) == log and "a" in mode: + opened[0] += 1 + if opened[0] > n: + raise self.Gone() + elif during and str(path).endswith("events.jsonl"): + during(path) + return real(path, mode, *a, **k) + with patch.object(execution, "open", opener, create=True): + try: + ex._trial_lines() + except self.Gone: + pass + execution.EXECUTIONS.clear() + + def restarted(self, d, redact=()): + rec, plan = execution.recorded(str(d)) + ex = execution.Execution(execution.Plan.from_dict(plan), root=str(self.tmp), record=rec) + ex._redact = list(redact) + return ex + + def two_jobs(self, d, a="r-a", b="r-b", redact=()): + """A run that said task-1, with three more ends in job ``a`` and one in ``b``.""" + (d / "jobs" / a).mkdir(parents=True); (d / "jobs" / b).mkdir() + ex = execution.Execution(execution.Plan(name=d.name, script="true"), root=str(self.tmp)); ex._redact = list(redact) + (d / "jobs" / a / "events.jsonl").write_text(self.END % (1, 1)); ex._trial_lines() + with open(d / "jobs" / a / "events.jsonl", "a") as fh: + fh.write("".join(self.END % (n, n) for n in (2, 3, 4))) + (d / "jobs" / b / "events.jsonl").write_text(self.END % (9, 9)) + return ex + + def test_nullius_gone_at_any_line_of_a_batch_says_each_trial_once(self): + """Killed before, between or after a batch's lines, a line half written + too, then a record saved before the restart's first look: each once.""" + for n in range(5): + with self.subTest(n): + d = self.tmp / f"r{n}"; ex = self.two_jobs(d) + self.gone_after(ex, n) + if n < 4: + with open(d / "nullius.log", "a") as fh: + fh.write(" ✓ r-") # the next line, cut short + self.restarted(d)._save(); execution.EXECUTIONS.clear() + back = self.restarted(d); back._trial_lines(); back._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + + def test_two_jobs_said_alike_each_keep_their_line(self): + secrets = ("SECRETVALUE1", "SECRETVALUE2") + d = self.tmp / "r" + ex = execution.Execution(execution.Plan(name="r", script="true"), root=str(self.tmp)); ex._redact = list(secrets); ex._save() + for s in secrets: + (d / "jobs" / f"r-{s}").mkdir(parents=True); (d / "jobs" / f"r-{s}" / "events.jsonl").write_text(self.END % (1, 1)) + self.gone_after(ex, 1) + back = self.restarted(d, secrets); back._trial_lines() + self.assertEqual((d / "nullius.log").read_text().splitlines(), [" ✓ r-[REDACTED] · task-1 · resolved · reward 1.0"] * 2) + + def test_a_part_line_like_a_trial_line_is_not_taken_for_it(self): + d = self.tmp / "r"; ex = self.two_jobs(d) + ex.log(" ✓ r-a · task-2 · resolved · reward 1.0") # a part printed it + self.gone_after(ex, 0) + back = self.restarted(d); back._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-2", "task-3", "task-4", "task-9"]) + + def test_a_record_saved_during_the_first_look_after_a_restart_keeps_what_was_said(self): + d = self.tmp / "r"; ex = self.two_jobs(d) + self.gone_after(ex, 1) + back = self.restarted(d) + + def stop(path): # a Stop from the page as the look reads a feed + t = threading.Thread(target=back.stop); t.start(); t.join(5) + raise self.Gone() + self.gone_after(back, 99, during=stop) + again = self.restarted(d); again._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + + def test_a_feed_away_at_the_first_look_is_said_once_when_back(self): + d = self.tmp / "r"; ex = self.two_jobs(d) + self.gone_after(ex, 1) + feed = d / "jobs" / "r-a" / "events.jsonl"; feed.rename(d / "away") + back = self.restarted(d); back._trial_lines() + (d / "away").rename(feed); execution.EXECUTIONS.clear() + again = self.restarted(d); again._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-9", "task-3", "task-4"]) + + def failing(self, saves, appends): + """The record's writes and the log's appends, numbered from 1: ``"no"`` + refuses one, ``"gone"`` kills Nullius there.""" + real_write, real_open, n = execution.ondisk.write_whole, open, {"save": 0, "append": 0} + + def refuse(kind, which): + n[kind] += 1 + if which.get(n[kind]) == "gone": + raise self.Gone() + if which.get(n[kind]) == "no": + raise PermissionError(13, "read-only") + + def write(path, *a, **k): + if str(path).endswith("run.json"): + refuse("save", saves) + return real_write(path, *a, **k) + + def opener(path, mode="r", *a, **k): + if str(path).endswith("nullius.log") and "a" in mode: + refuse("append", appends) + return real_open(path, mode, *a, **k) + return write, opener + + def test_a_refused_trial_line_is_never_taken_for_the_next(self): + """Of two lines of one length, the first refused, the second not: Nullius + gone before its record says neither as said in place of the other.""" + d = self.tmp / "r"; (d / "jobs" / "r-a").mkdir(parents=True) + ex = execution.Execution(execution.Plan(name="r", script="true"), root=str(self.tmp)); ex._save() + (d / "jobs" / "r-a" / "events.jsonl").write_text(self.END % (1, 1) + self.END % (2, 2)) + write, opener = self.failing(saves={2: "gone"}, appends={1: "no"}) + with patch.object(execution.ondisk, "write_whole", write), patch.object(execution, "open", opener, create=True): + try: + ex._trial_lines() + except self.Gone: + pass + execution.EXECUTIONS.clear() + back = self.restarted(d); back._trial_lines() + self.assertEqual(sorted(self.said(d)), ["task-1", "task-2"]) + + def test_no_trial_line_is_written_or_repaired_without_its_record(self): + """A run folder that takes no record: no trial line is written, before a + batch or after a restart, and a line logged meanwhile is never cut as one.""" + d = self.tmp / "r"; ex = self.two_jobs(d) + with patch.object(execution.ondisk, "write_whole", side_effect=PermissionError(13, "read-only")): + ex._trial_lines() + self.assertEqual(self.said(d), ["task-1"]) + self.gone_after(ex, 0) # gone with its record kept, before its first line + with patch.object(execution.ondisk, "write_whole", side_effect=PermissionError(13, "read-only")): + back = self.restarted(d) + back.log(" a part's line, longer than the trial lines it follows, and whole") + execution.EXECUTIONS.clear() + again = self.restarted(d); again._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + + def test_a_cut_the_log_cannot_repair_now_is_repaired_at_the_next_restart(self): + d = self.tmp / "r"; ex = self.two_jobs(d) + self.gone_after(ex, 0) + with open(d / "nullius.log", "ab") as fh: + fh.write(" ✓".encode()[:3]) # inside the mark's bytes + with patch.object(execution.os, "truncate", side_effect=PermissionError(13, "read-only")): + back = self.restarted(d) + self.assertIn("pending", json.loads((d / "run.json").read_text())) + execution.EXECUTIONS.clear() + again = self.restarted(d); again._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + + def test_a_look_after_storage_returns_says_each_trial_once(self): + """Restored where the lines a dead Nullius left could not be settled - the + record refused, or a cut line it could not take out - the same process + says each trial once when storage takes them again, and shows no cut line.""" + for refused in ("record", "cut"): + with self.subTest(refused): + d = self.tmp / refused; ex = self.two_jobs(d) + self.gone_after(ex, 1) + if refused == "cut": + with open(d / "nullius.log", "ab") as fh: + fh.write(" ✓".encode()[:3]) + with patch.object(execution.ondisk, "write_whole", side_effect=PermissionError(13, "read-only")) if refused == "record" else \ + patch.object(execution.os, "truncate", side_effect=PermissionError(13, "read-only")): + back = self.restarted(d); back._trial_lines() + back._trial_lines(); back._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + self.assertNotIn("\ufffd", "\n".join(back.lines)) + + def test_a_part_line_read_while_trial_lines_are_unsettled_is_in_the_log(self): + """A part's line read after the record refused to settle a dead Nullius's + lines, and its offset saved: it is in the log, whatever comes next.""" + d = self.tmp / "r"; ex = self.two_jobs(d) + self.gone_after(ex, 1) + with patch.object(execution.ondisk, "write_whole", side_effect=PermissionError(13, "read-only")): + back = self.restarted(d) + back._read("a part's own line"); back.log_offset = 18; back._save() + execution.EXECUTIONS.clear() + again = self.restarted(d); again._trial_lines() + self.assertIn("a part's own line", (d / "nullius.log").read_text().splitlines()) + self.assertEqual(sorted(self.said(d)), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + + def test_a_part_ends_only_once_its_last_output_and_trials_are_said(self): + """A part that has ended, followed while a dead Nullius's trial lines + cannot be settled: its end waits until they are, and its last line is said.""" + d = self.tmp / "r"; ex = self.two_jobs(d) + self.gone_after(ex, 1) + (d / "run-a.log").write_text("the part's last line\n"); (d / "run-a.exit").write_text("0") + real, refused = execution.ondisk.write_whole, [0] + + def write(path, *a, **k): # the record refused at the first three tries + if str(path).endswith("run.json") and refused[0] < 3: + refused[0] += 1 + raise PermissionError(13, "read-only") + return real(path, *a, **k) + with patch.object(execution.ondisk, "write_whole", write): + back = self.restarted(d) + rc = back._follow({"id": "a", "label": "a", "script": "true"}) + self.assertEqual(rc, 0) + self.assertIn("the part's last line", (d / "nullius.log").read_text().splitlines()) + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + + def test_a_log_that_cannot_be_read_keeps_its_trial_lines_pending(self): + d = self.tmp / "r"; ex = self.two_jobs(d) + self.gone_after(ex, 1) + real = open + + def opener(path, mode="r", *a, **k): + if str(path).endswith("nullius.log") and "b" in mode: + raise PermissionError(13, "write-only") + return real(path, mode, *a, **k) + with patch.object(execution, "open", opener, create=True): + back = self.restarted(d); back._trial_lines() + self.assertIn("pending", json.loads((d / "run.json").read_text())) + back._trial_lines(); back._trial_lines() + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + + def test_a_stop_is_never_written_onto_a_cut_line(self): + """A Stop while a cut trial line could not be taken out: the Stop is + recorded at once, its line written whole once the cut one is out.""" + d = self.tmp / "r"; ex = self.two_jobs(d) + self.gone_after(ex, 1) + with open(d / "nullius.log", "ab") as fh: + fh.write(" ✓".encode()[:3]) + with patch.object(execution.os, "truncate", side_effect=PermissionError(13, "read-only")): + back = self.restarted(d) + back.stop() + self.assertEqual(json.loads((d / "run.json").read_text())["state"], "stopping") + back._trial_lines() + log = (d / "nullius.log").read_bytes().decode("utf-8").splitlines() + self.assertIn("— stop requested", log) + self.assertEqual(self.said(d), ["task-1", "task-2", "task-3", "task-4", "task-9"]) + 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."""