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
51 changes: 48 additions & 3 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +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.deleted = False # its folder went with Delete launch: it never runs again (``again``)
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] = []
Expand Down Expand Up @@ -946,10 +947,12 @@ def again(self, part: dict, env=os.environ) -> "Execution":
mirrored back as it goes. The part's files are its own
(``run-<part>``): nothing of a part before is read as its. Its end is
the run's; each job's own end stays its first part's (``job_state``).
ValueError while the run lives."""
ValueError while the run lives or is being deleted."""
with self._turn:
if self.state in ALIVE:
raise ValueError(f"{self.plan.name} is {self.state}: a run takes one more part once it has ended")
if self._deleting():
raise ValueError(f"{self.plan.name} is being deleted: nothing was started")
_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)
Expand All @@ -963,6 +966,18 @@ def again(self, part: dict, env=os.environ) -> "Execution":
self.thread.start()
return self

def _deleting(self) -> bool:
"""Its folder went with Delete launch, or a delete holds it: nothing of it is written again."""
return self.deleted or os.path.realpath(self.dir) in _DELETING

def drop_cap(self, job_id: str) -> None:
"""The cap set on the page for ``job_id`` (``caps``) is dropped from the record, once the job's own
holds it; nothing is written for a run being deleted."""
with self._turn:
if job_id in self.caps and not self._deleting():
self.caps = {k: v for k, v in self.caps.items() if k != job_id}
self._save()

def _main_again(self) -> None:
try:
missing = self._missing()
Expand Down Expand Up @@ -2455,14 +2470,42 @@ def _remove_run(path: str) -> None:
os.rmdir(path)


# The run folders a delete holds, each by one delete (``_CLAIMS``): none of their runs takes one more part
# (``Execution.again``) until it is done.
_DELETING: set = set()
_CLAIMS = threading.Lock()


def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), run: Optional[Callable] = None) -> dict:
"""Delete the runs *names* of one launch (``deletion`` says what goes):
per run its folder, its entry here, its roots, parsed jobs and judgements
in every workspace, and its copy on its host when that host's label is in
*copies*. Returns ``deletion``'s answer, with ``stays``: the runs whose
folder could not go (they keep everything else), and ``kept``: one line
per thing that stays. The judgements of the user's store go last, once
every folder went or stayed: those of a job no folder of which is left."""
every folder went or stayed: those of a job no folder of which is left.
Each run is held by this delete alone, then found ended under its own
lock, so a Rerun meanwhile is refused; ValueError for one alive or held
by another delete."""
held = []
try:
for n in dict.fromkeys(names):
path = run_folder(n, root)
with _CLAIMS:
if path in _DELETING:
raise ValueError(f"{n} is being deleted")
_DELETING.add(path); held.append(path)
for ex in [e for e in list(EXECUTIONS.values()) if os.path.realpath(e.dir) == path]:
with ex._turn:
if ex.state in ALIVE:
raise ValueError(f"{n} is {ex.state}: stop it before you delete it")
return _delete(names, home, root, copies, run)
finally:
with _CLAIMS:
_DELETING.difference_update(held)


def _delete(names: List[str], home: str, root: Optional[str], copies, run: Optional[Callable]) -> dict:
gone = deletion(names, home, root, final=True)
gone["stays"], gone["kept"] = [], []
went = []
Expand All @@ -2475,7 +2518,9 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r
continue
went.append(r)
for key in [k for k, e in EXECUTIONS.items() if os.path.realpath(e.dir) == r["dir"]]:
del EXECUTIONS[key]
ex = EXECUTIONS.pop(key)
with ex._turn:
ex.deleted = True # before its claim goes: a Rerun that found it is refused
for w in r["workspaces"]:
judgements.forget(w["ws"].dir, w["judged"])
# read again: another run of the launch may have left this workspace already
Expand Down
90 changes: 90 additions & 0 deletions app/tests/test_execution_again.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import os
import shlex
import shutil
import threading
from pathlib import Path
from unittest import mock

Expand Down Expand Up @@ -93,6 +94,95 @@ def test_a_part_run_again_that_fails_fails_the_run_and_not_the_job(self):
self.assertIsNone(ex.refused("j1"))
self.assertFalse(ex.never_ran("j1"))

def test_a_run_being_deleted_runs_nothing_again(self):
ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start())
execution.EXECUTIONS[ex.id] = ex
gate, real, said = self.tmp / "go", execution._run_deletion, []
self.addCleanup(gate.write_text, "")
def rerun_meanwhile(*a, **kw):
found = real(*a, **kw) # Rerun pressed once the delete found the run ended
try:
ex.again(part(f"until [ -e {shlex.quote(str(gate))} ]; do sleep 0.02; done"), env={"OPENAI_API_KEY": "sk-first-key-0001"})
except ValueError as e:
said.append(str(e))
return found
with mock.patch.object(execution, "_run_deletion", rerun_meanwhile):
execution.delete(["std-here"], str(self.tmp / "ws"), str(self.tmp / "runs"))
self.assertEqual((said, ex.state), (["std-here is being deleted: nothing was started"], "done"))
self.assertFalse(os.path.exists(ex.dir))

def test_a_delete_over_a_run_another_delete_holds_lets_no_rerun_in(self):
ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start())
execution.EXECUTIONS[ex.id] = ex
gate = self.tmp / "go"
self.addCleanup(gate.write_text, "")
slow = execution.Plan(name="std-two", script="", runner="standard", model="m-1", key_var="OPENAI_API_KEY", url_var="",
parts=[{"id": "slow", "label": "Slow", "script": f"until [ -e {shlex.quote(str(gate))} ]; do sleep 0.02; done"}])
two = self.until(execution.Execution(slow, root=str(self.tmp / "runs"), key="sk-first-key-0001").start(), "running")
execution.EXECUTIONS[two.id] = two
reached, go, real = threading.Event(), threading.Event(), execution._remove_run
def paused(path):
reached.set(); go.wait(10)
return real(path)
args = (str(self.tmp / "ws"), str(self.tmp / "runs"))
with mock.patch.object(execution, "_remove_run", paused):
first = threading.Thread(target=execution.delete, args=(["std-here"], *args))
first.start(); self.addCleanup(go.set)
self.assertTrue(reached.wait(10)) # Delete A, about to remove std-here
with self.assertRaises(ValueError):
execution.delete(["std-here", "std-two"], *args) # Delete B, over a launch with a running shard
with self.assertRaisesRegex(ValueError, "std-here is being deleted"):
ex.again(part("true"), env={"OPENAI_API_KEY": "sk-first-key-0001"})
go.set(); first.join(10)
self.assertEqual((ex.state, os.path.exists(ex.dir), two.state), ("done", False, "running"))

def test_a_rerun_that_found_its_run_before_the_delete_never_reaches_a_new_run_of_its_name(self):
ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start())
execution.EXECUTIONS[ex.id] = ex
execution.delete(["std-here"], str(self.tmp / "ws"), str(self.tmp / "runs"))
new = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start())
execution.EXECUTIONS[new.id] = new
with self.assertRaisesRegex(ValueError, "std-here is being deleted: nothing was started"):
ex.again(part("true"), env={"OPENAI_API_KEY": "sk-first-key-0001"}) # the page's POST, held since it found ex
self.assertFalse((Path(new.dir) / "run-again-1.sh").exists())
self.assertEqual(execution.recorded(new.dir)[0]["id"], new.id)

def test_a_delete_waiting_on_a_rerun_s_lock_finds_it_running(self):
ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start())
execution.EXECUTIONS[ex.id] = ex
gate = self.tmp / "go"
self.addCleanup(gate.write_text, "")

class Seen:
"""The run's lock, saying when the delete's thread asks for it."""
def __init__(self, lock):
self.lock, self.asked = lock, threading.Event()
def __enter__(self):
if threading.current_thread().name == "deleter":
self.asked.set()
return self.lock.__enter__()
def __exit__(self, *a):
return self.lock.__exit__(*a)
ex._turn = seen = Seen(ex._turn)
said = []
def deleting():
try:
execution.delete(["std-here"], str(self.tmp / "ws"), str(self.tmp / "runs"))
except ValueError as e:
said.append(str(e))
deleter = threading.Thread(target=deleting, name="deleter")
with seen: # Rerun, holding the run's lock
ex.again(part(f"until [ -e {shlex.quote(str(gate))} ]; do sleep 0.02; done"), env={"OPENAI_API_KEY": "sk-first-key-0001"})
deleter.start()
self.assertTrue(seen.asked.wait(10), "the delete never asked for the run's lock")
deleter.join(10)
self.assertEqual(len(said), 1, said)
self.assertRegex(said[0], r"^std-here is (preparing|running): stop it before you delete it$")
self.assertTrue(os.path.isdir(ex.dir))
self.assertIn(ex.id, execution.EXECUTIONS)
gate.write_text("")
self.assertEqual(self.wait(ex).state, "done", ex.lines)

def test_the_cli_s_rerun_is_the_command_and_its_words_reach_it(self):
"""The generated command runs precisely the named tasks of a finished job."""
dest = self.tmp / "catalogue/benchmarks/fakebench"
Expand Down
26 changes: 26 additions & 0 deletions app/ui_tests/test_rerun_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from web import execute

UNITS = ["t-0", "t-1", "t-2"]
AGAIN = execution.Execution.again


def trial_name(k):
Expand Down Expand Up @@ -384,6 +385,31 @@ def test_the_page_shows_the_job_s_one_cap_and_a_change_holds_from_the_next_run(s
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'<div class="sp cap-spent small muted" id="cap-spent">.*?</div>'), "$0.40 spent · Change")

def test_a_rerun_that_found_its_run_before_the_delete_writes_nothing_where_it_was(self):
"""The POST reads the job's cap, Delete launch goes meanwhile: the cap the job now holds is not settled
into the deleted run's folder, nor into a new run of its name."""
made = {name: self.run_of(name) for name in ("r1", "r2")}
for d in made.values():
self.capped(d, {"max_usd": 4.0, "spent_usd": 0.31, "stopped": False, "cut_off": [], "not_run": []})
self.open(*[d.parent for d in made.values()])
self.stack.enter_context(patch.object(execution.Execution, "again", AGAIN))
real, replaced = execute.rerun.budget, {}
for name in made:
execution.EXECUTIONS[f"{name}-1"].caps = {name: 4.0} # the page's cap, now the job's own

def deleted_meanwhile(*a, name=name, **kw):
got = real(*a, **kw)
execution.delete([name], str(self.tmp / "ws"))
if name == "r2": # a new launch takes its name
self.run_of(name)
replaced[name] = (self.tmp / "runs" / name / "run.json").read_bytes()
return got
with patch.object(execute.rerun, "budget", deleted_meanwhile):
r = self.post(name, {"trials": [trial_name(0)]})
self.assertEqual(r.status_code, 409, r.get_data(as_text=True))
self.assertFalse((self.tmp / "runs" / "r1").exists())
self.assertEqual((self.tmp / "runs" / "r2" / "run.json").read_bytes(), replaced["r2"])

def test_a_change_is_refused_at_or_under_what_was_spent_and_while_a_later_run_goes_on(self):
d = self.run_of()
self.capped(d, {"max_usd": 4.0, "spent_usd": 0.31, "stopped": False, "cut_off": [], "not_run": []})
Expand Down
4 changes: 1 addition & 3 deletions app/web/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,7 @@ def job_cap(job, ex, settle: bool = False) -> dict | None:
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.caps = {k: v for k, v in ex.caps.items() if k != job.job_id}
ex._save()
ex.drop_cap(job.job_id)
return got


Expand Down
Loading