Skip to content

Commit 8efe038

Browse files
committed
Merge main into feat/agent-computer
2 parents c8f42af + f6ef315 commit 8efe038

25 files changed

Lines changed: 484 additions & 108 deletions

‎app/nullius/execution.py‎

Lines changed: 62 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1674,25 +1674,45 @@ def active() -> List[Execution]:
16741674
return [e for e in EXECUTIONS.values() if e.state in ALIVE]
16751675

16761676

1677-
def for_job(job_id: str) -> Optional[Execution]:
1677+
def owners() -> Dict[str, Execution]:
1678+
"""Each job a plan names -> the newest execution whose script writes it; of
1679+
several started at once, the first listed."""
1680+
out: Dict[str, Execution] = {}
1681+
for e in EXECUTIONS.values():
1682+
for j in e.plan.jobs:
1683+
name = str(j.get("name"))
1684+
if name not in out or e.started > out[name].started:
1685+
out[name] = e
1686+
return out
1687+
1688+
1689+
def run_ends(owner: Optional[Dict[str, Execution]] = None) -> Dict[str, Optional[tuple]]:
1690+
"""Each job a run writes -> its ``job_state`` once the whole run has ended,
1691+
None while the run is alive: the ``runs`` of ``workspace.load_jobs``. A
1692+
part's end is written down before the run's last copy from its host.
1693+
``owner``: ``owners()``, when the caller holds it."""
1694+
return {name: None if e.state in ALIVE else e.job_state(name)
1695+
for name, e in (owners() if owner is None else owner).items()}
1696+
1697+
1698+
def for_job(job_id: str, owner: Optional[Dict[str, Execution]] = None) -> Optional[Execution]:
16781699
"""The newest execution whose script writes this job, if any - the one
16791700
the job page shows beside the job, or instead of it while Harbor has
1680-
not written it yet."""
1681-
found = [e for e in EXECUTIONS.values() if any(str(j.get("name")) == job_id for j in e.plan.jobs)]
1682-
return max(found, key=lambda e: e.started) if found else None
1701+
not written it yet. ``owner``: ``owners()``, when the caller holds it."""
1702+
return (owners() if owner is None else owner).get(job_id)
16831703

16841704

16851705
ENDED = ("stopped", "failed", "done")
16861706

16871707

1688-
def ended_for(job_id: str) -> Optional[tuple]:
1708+
def ended_for(job_id: str, owner: Optional[Dict[str, Execution]] = None) -> Optional[tuple]:
16891709
"""``(state, finished_at)`` when the run that writes this job has ended
16901710
- stopped, failed or done - by the runner's own record; None while it
16911711
is alive or when no run of this application wrote the job. A Harbor
16921712
killed by a Stop leaves its feed without ``job.end`` and its result
16931713
record with trials "running", so a page reading either alone would say
1694-
the job goes on; this is the fact that says otherwise."""
1695-
ex = for_job(job_id)
1714+
the job goes on; this is the fact that says otherwise. ``owner``: as ``for_job``'s."""
1715+
ex = for_job(job_id, owner)
16961716
return ex.job_state(job_id) if ex is not None else None
16971717

16981718

@@ -1762,6 +1782,37 @@ def size_of(path: str) -> int:
17621782
return total
17631783

17641784

1785+
# Sizes of ended runs' folders, by folder: (what they were read at, bytes).
1786+
_SIZES: Dict[str, tuple] = {}
1787+
_SIZES_LOCK = threading.Lock()
1788+
1789+
1790+
def run_size(ex: "Execution") -> int:
1791+
"""``size_of`` the run's folder, as the Launches page lists it: walked at
1792+
each ask while the run is alive; once it has ended, again only when its
1793+
state, its record, its folder or its jobs folder moved. What Delete asks
1794+
(``deletion``) walks the folder afresh.
1795+
shortcut: a file changed deep in an ended run alone (a trace view saved on
1796+
its trial page) is counted from the next move of those; walk the job folders too if that matters."""
1797+
if ex.state in ALIVE:
1798+
return size_of(ex.dir)
1799+
1800+
def mtime(path):
1801+
try:
1802+
return os.stat(path).st_mtime_ns
1803+
except OSError:
1804+
return None
1805+
seen = (ex.state, ex.finished, *map(mtime, (ex.dir, os.path.join(ex.dir, RECORD), ex.jobs)))
1806+
with _SIZES_LOCK:
1807+
known = _SIZES.get(ex.dir)
1808+
if known is not None and known[0] == seen:
1809+
return known[1]
1810+
size = size_of(ex.dir)
1811+
with _SIZES_LOCK:
1812+
_SIZES[ex.dir] = (seen, size)
1813+
return size
1814+
1815+
17651816
def _deletable(name: str, root: Optional[str]) -> tuple:
17661817
"""A run's folder and record, when it is a run that has ended; ValueError
17671818
(alive, or not a run) or OSError (its record unreadable) otherwise."""
@@ -1781,15 +1832,15 @@ def deletable(names: List[str], root: Optional[str] = None) -> None:
17811832
_deletable(n, root)
17821833

17831834

1784-
def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable) -> dict:
1835+
def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, ends: dict) -> dict:
17851836
path, rec = _deletable(name, root)
17861837
plan = rec.get("plan") or {}
17871838
# a run refused at the name check never made the host folder: one of that name there is not its own
17881839
host = hosts.parse(plan["host"]) if plan.get("host") and (rec.get("launched") or rec.get("step") not in ("connect", "name")) else None
17891840
held = []
17901841
for ws, roots in holding(path):
17911842
dirs = parse.find_job_dirs(roots)
1792-
ids = [j.job_id for j in workspace.load_jobs(ws, roots)]
1843+
ids = [j.job_id for j in workspace.load_jobs(ws, roots, ends)]
17931844
# a job of the same id from another root shares these judgements: they stay
17941845
others = {e.get("job_id") for d, e in workspace.job_index(ws).items() if d not in dirs}
17951846
judged = judgements.job_dirs(ws.dir, [i for i in ids if i.split("~")[0] not in others])
@@ -1807,7 +1858,8 @@ def deletion(names: List[str], home: str, root: Optional[str] = None, holding: O
18071858
a run: nothing goes then. ``holding``: a run folder's ``workspace.holding``,
18081859
when the caller has it already."""
18091860
holding = holding or (lambda path: workspace.holding(home, path))
1810-
runs = [_run_deletion(n, home, root, holding) for n in dict.fromkeys(names)]
1861+
ends = run_ends()
1862+
runs = [_run_deletion(n, home, root, holding, ends) for n in dict.fromkeys(names)]
18111863
copies: Dict[str, int] = {}
18121864
for r in runs:
18131865
if r["host"]:

‎app/nullius/workspace.py‎

Lines changed: 88 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,16 @@
1919
still going changes its files, the signature moves, the job is parsed again.
2020
A cached job that was parsed by an older version of ``parse`` is refreshed
2121
too — the signature carries ``parse.SCHEMA`` so a change there invalidates.
22+
23+
A job that has ended (``_ended``: its result records a finish and nothing
24+
running or pending) is checked by its *head* alone: its own result.json and
25+
config.json, and its folder, whose mtime moves when a trial folder comes or
26+
goes. A Harbor resume rewrites result.json, so it is caught; a file changed
27+
inside a trial of an ended job and nothing else is not. The workspace's
28+
Refresh (``clear_cache``) reads every job again. A job a run of this
29+
application writes is checked trial by trial while that run goes on (a host
30+
run's copy can bring a trial's files after the job's own), and its head
31+
carries the run's end, so the last copy is checked trial by trial once more.
2232
"""
2333
from __future__ import annotations
2434

@@ -311,6 +321,25 @@ def stat(path):
311321
return hashlib.sha256("\n".join(parts).encode()).hexdigest(), trials
312322

313323

324+
def _head(job_dir: str) -> str:
325+
"""What an ended job's parse can change by without a trial changing in place:
326+
its own records, and its folder's mtime (a trial folder added or removed)."""
327+
parts = [f"schema={SCHEMA}/{parse.SCHEMA}"]
328+
for path in (job_dir, os.path.join(job_dir, "result.json"), os.path.join(job_dir, "config.json")):
329+
try:
330+
st = os.stat(path)
331+
except OSError:
332+
parts.append("-")
333+
continue
334+
parts.append(f"{st.st_size}:{st.st_mtime_ns}")
335+
return "\n".join(parts)
336+
337+
338+
def _ended(job: parse.Job) -> bool:
339+
"""Its result records a finish and nothing running or pending: its trials are final."""
340+
return job.finished_at is not None and job.state == "finished"
341+
342+
314343
def _encode(obj):
315344
if isinstance(obj, datetime):
316345
return {"$dt": obj.isoformat()}
@@ -381,37 +410,70 @@ def _write_index(ws: Workspace, index: dict) -> None:
381410
_write_atomically(_index_path(ws), lambda fh: json.dump(index, fh, ensure_ascii=False, indent=1))
382411

383412

384-
# Jobs already decoded in this process, by cache file: (signature, Job). A page
385-
# that loads the workspace then skips the JSON decode and the rebuild of every
386-
# unchanged job. A Job is never changed once loaded (parse.split_agents and the
387-
# compare page make new ones with dataclasses.replace).
413+
# Jobs already decoded in this process, by cache file: (signature, Job, trial
414+
# signatures, head). A page that loads the workspace then skips the JSON decode
415+
# and the rebuild of every unchanged job. A Job is never changed once loaded
416+
# (parse.split_agents and the compare page make new ones with dataclasses.replace).
388417
_DECODED: dict = {}
389418
_DECODED_LOCK = threading.Lock()
390419

391420

392-
def load_job(ws: Workspace, job_dir: str, index: dict | None = None) -> tuple:
393-
"""(Job, from_cache). Parses only when the signature changed. ``index``:
394-
the rail's index as load_jobs holds it, noted in place."""
395-
sig, trial_sigs = _signatures(job_dir)
421+
def _read_cache(path: str, job_dir: str) -> tuple | None:
422+
"""(signature, head, Job) of the cache file *path* when it is *job_dir*'s, else None."""
423+
try:
424+
with open(path, encoding="utf-8") as fh:
425+
cached = json.load(fh, object_hook=_decode)
426+
# "agents": a cache from before split_agents knows nothing of a job's several agents
427+
if cached.get("dir") == job_dir and "agents" in cached.get("job", {}):
428+
return cached.get("signature"), cached.get("head"), job_from_dict(cached["job"])
429+
except (OSError, json.JSONDecodeError, TypeError, KeyError, ValueError, AttributeError):
430+
pass
431+
return None
432+
433+
434+
def _write_cache(ws: Workspace, path: str, sig: str, head: str, job: parse.Job) -> None:
435+
os.makedirs(ws.jobs_dir, exist_ok=True)
436+
_write_atomically(path, lambda fh: json.dump({"signature": sig, "head": head, "dir": job.dir, "cached": _now(),
437+
"job": job_to_dict(job)}, fh, default=_encode, ensure_ascii=False))
438+
439+
440+
def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict | None = None) -> tuple:
441+
"""(Job, from_cache). Parses only when the signature changed; an ended job
442+
whose head is unchanged is not stated trial by trial. ``index``: the
443+
rail's index as load_jobs holds it, noted in place. ``runs``: job folder
444+
name -> the end of the run of this application that writes it, None while
445+
that run goes on; a job no run writes has no entry."""
446+
run = (runs or {}).get(os.path.basename(job_dir), "")
447+
short = run is not None # the head alone may answer
448+
head = _head(job_dir) + (f"\nrun={run}" if run else "") # before anything is read: a change after it is caught next time
396449
path = _cache_file(ws, job_dir)
397450
with _DECODED_LOCK:
398451
known = _DECODED.get(path)
452+
if short and known is not None and known[1].dir == job_dir and known[3] == head and _ended(known[1]):
453+
_note_in_index(ws, job_dir, known[1], index)
454+
return known[1], True
455+
cached = _read_cache(path, job_dir) if known is None else None
456+
if short and cached is not None and cached[1] == head and _ended(cached[2]):
457+
with _DECODED_LOCK:
458+
_DECODED[path] = (cached[0], cached[2], {}, head)
459+
_note_in_index(ws, job_dir, cached[2], index)
460+
return cached[2], True
461+
sig, trial_sigs = _signatures(job_dir)
399462
if sig:
400463
if known is not None and known[0] == sig and known[1].dir == job_dir:
464+
with _DECODED_LOCK:
465+
_DECODED[path] = (sig, known[1], known[2], head)
401466
_note_in_index(ws, job_dir, known[1], index)
402467
return known[1], True
403-
try:
404-
with open(path, encoding="utf-8") as fh:
405-
cached = json.load(fh, object_hook=_decode)
406-
# "agents": a cache from before split_agents knows nothing of a job's several agents
407-
if cached.get("signature") == sig and cached.get("dir") == job_dir and "agents" in cached.get("job", {}):
408-
job = job_from_dict(cached["job"])
409-
with _DECODED_LOCK:
410-
_DECODED[path] = (sig, job, trial_sigs)
411-
_note_in_index(ws, job_dir, job, index)
412-
return job, True
413-
except (OSError, json.JSONDecodeError, TypeError, KeyError, ValueError):
414-
pass
468+
if known is not None:
469+
cached = _read_cache(path, job_dir)
470+
if cached is not None and cached[0] == sig:
471+
if cached[1] != head and _ended(cached[2]):
472+
_write_cache(ws, path, sig, head, cached[2]) # read by its head from the next process on
473+
with _DECODED_LOCK:
474+
_DECODED[path] = (sig, cached[2], trial_sigs, head)
475+
_note_in_index(ws, job_dir, cached[2], index)
476+
return cached[2], True
415477
reuse = None
416478
if known is not None and known[1].dir == job_dir:
417479
before = {t.dir: t for t in known[1].trials}
@@ -420,23 +482,22 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None) -> tuple:
420482
reuse = lambda sub: before.get(sub) if old_sigs.get(sub) and old_sigs.get(sub) == trial_sigs.get(sub) else None
421483
job = parse.parse_job(job_dir, reuse=reuse)
422484
if sig:
423-
os.makedirs(ws.jobs_dir, exist_ok=True)
424-
_write_atomically(path, lambda fh: json.dump({"signature": sig, "dir": job_dir, "cached": _now(),
425-
"job": job_to_dict(job)}, fh, default=_encode, ensure_ascii=False))
485+
_write_cache(ws, path, sig, head, job)
426486
with _DECODED_LOCK:
427-
_DECODED[path] = (sig, job, trial_sigs)
487+
_DECODED[path] = (sig, job, trial_sigs, head)
428488
_note_in_index(ws, job_dir, job, index)
429489
return job, False
430490

431491

432-
def load_jobs(ws: Workspace, roots) -> list:
492+
def load_jobs(ws: Workspace, roots, runs: dict | None = None) -> list:
433493
"""Every job under *roots*, each from the cache when its files are
434-
unchanged. Same order and de-duplication as ``parse.load_all``."""
494+
unchanged. Same order and de-duplication as ``parse.load_all``.
495+
``runs``: as ``load_job``'s."""
435496
# the rail's index read once and written once, not once per job: re-reading it for
436497
# each made a workspace of n jobs cost n parses of an index of n entries
437498
index = job_index(ws)
438499
before = dict(index)
439-
jobs = [load_job(ws, d, index)[0] for d in parse.find_job_dirs(roots)]
500+
jobs = [load_job(ws, d, index, runs)[0] for d in parse.find_job_dirs(roots)]
440501
if index != before:
441502
_write_index(ws, index)
442503
return parse.split_agents(jobs)

‎app/templates/compare/compare.html‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,10 +146,10 @@
146146
{% endif %}
147147
<tr>
148148
<th{{ classes(METRIC, true, 'rowhead') }}>Outcome mix</th>
149-
{% call(i) each() %}{% set j = jobs[i] %}
149+
{% call(i) each() %}{% set j = jobs[i] %}{% set oc = j.counts %}
150150
<td><span class="minibar">
151-
{%- for k in ORDER %}{% if j.counts[k] %}<span class="seg oc-{{ k }}" style="flex:{{ j.counts[k] }}"
152-
title="{{ LABELS[k] }}: {{ j.counts[k] }}"></span>{% endif %}{% endfor -%}
151+
{%- for k in ORDER %}{% if oc[k] %}<span class="seg oc-{{ k }}" style="flex:{{ oc[k] }}"
152+
title="{{ LABELS[k] }}: {{ oc[k] }}"></span>{% endif %}{% endfor -%}
153153
</span></td>
154154
{% endcall %}
155155
</tr>

‎app/templates/runs/feasibility.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474

7575
<div class="legend feas-summary" role="group" aria-label="Feasibility classes">
7676
<span class="feas-headline" id="feasibility-count"><strong>{{ report.n_feasible }}</strong><span class="faint">/{{ report.rows|length }}</span> feasible</span>
77-
{% for k in F_ORDER %}{% if report.counts[k] %}<span class="chip fv-{{ k }}">{{ F_LABELS[k] }} <b>{{ report.counts[k] }}</b></span>{% endif %}{% endfor %}
77+
{% set oc = report.counts %}{% for k in F_ORDER %}{% if oc[k] %}<span class="chip fv-{{ k }}">{{ F_LABELS[k] }} <b>{{ oc[k] }}</b></span>{% endif %}{% endfor %}
7878
</div>
7979

8080
{% if report.rows %}

0 commit comments

Comments
 (0)