Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 136 additions & 28 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand All @@ -533,18 +539,21 @@ 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,
"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, "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:
Expand All @@ -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
Expand All @@ -576,27 +587,47 @@ 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
clean = clean.replace(key, "[REDACTED]")
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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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); "
Expand All @@ -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):
Expand Down
Loading
Loading