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
36 changes: 24 additions & 12 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.deleted = False # its folder went with Delete launch: it never runs again (``again``)
self.deleted = False # its folder went with Delete launch: it never runs again (``again``) nor saves (``_save``)
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 @@ -545,8 +545,10 @@ def _save(self, strict: bool = False) -> bool:
start (``caps``, the parts run ``again``), after its plan
(``_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."""
first, ``start_all``): OSError. Nothing once ``deleted``: False."""
with self._turn:
if self.deleted:
return False
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,
Expand Down Expand Up @@ -948,6 +950,8 @@ def again(self, part: dict, env=os.environ) -> "Execution":
(``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 or is being deleted."""
if self._deleting(): # at once: a delete under way may hold the run's lock until it is done
raise ValueError(f"{self.plan.name} is being deleted: nothing was started")
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")
Expand Down Expand Up @@ -1019,10 +1023,11 @@ def _main_resumed(self) -> None:
def _fail(self, step: str, why: str) -> None:
if self._stop.is_set(): # a step cut short by a Stop is the stop, not a failure
return self._done(130)
self._stage_end("failed", detail=why[:300])
self.step, self.state, self.error, self.finished = step, "failed", why, time.time()
self.log(f"✕ {step}: {why}")
self._save()
with self._turn: # its end and its record together, as ``_done``'s: a Delete finds both or neither
self._stage_end("failed", detail=why[:300])
self.step, self.state, self.error, self.finished = step, "failed", why, time.time()
self.log(f"✕ {step}: {why}")
self._save()

def _done(self, rc: int) -> None:
"""The run's end, recorded once: ``done`` or ``failed`` by ``rc``,
Expand Down Expand Up @@ -2128,7 +2133,8 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]:
with contextlib.suppress(OSError):
os.unlink(os.path.join(ex.dir, RESERVED)) # its record is there: nothing to take over
_unhold(ex)
EXECUTIONS[ex.id] = ex
with _CLAIMS: # never between a delete's look at an id and its removal
EXECUTIONS[ex.id] = ex
ex.start()
return runs

Expand Down Expand Up @@ -2510,17 +2516,23 @@ def _delete(names: List[str], home: str, root: Optional[str], copies, run: Optio
gone["stays"], gone["kept"] = [], []
went = []
for r in gone["runs"]:
held = [e for e in list(EXECUTIONS.values()) if os.path.realpath(e.dir) == r["dir"]]
try:
_remove_run(r["dir"])
with contextlib.ExitStack() as turns:
for ex in held:
turns.enter_context(ex._turn) # a save waits for the removal: then made, or refused once it went
_remove_run(r["dir"])
for ex in held:
ex.deleted = True # before its claim goes: a Rerun that found it is refused
except OSError as e:
gone["stays"].append(r["name"])
gone["kept"].append(f"{r['name']} stays in {r['dir']}: {e.strerror or e}")
continue
went.append(r)
for key in [k for k, e in EXECUTIONS.items() if os.path.realpath(e.dir) == r["dir"]]:
ex = EXECUTIONS.pop(key)
with ex._turn:
ex.deleted = True # before its claim goes: a Rerun that found it is refused
with _CLAIMS:
for ex in held: # these alone: a launch of the name since is its own
if EXECUTIONS.get(ex.id) is ex:
del EXECUTIONS[ex.id]
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
31 changes: 31 additions & 0 deletions app/tests/test_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,37 @@ def test_a_failing_script_is_a_failed_run(self):
ex = self.wait(execution.Execution(execution.Plan(name="r", script="exit 3"), root=str(self.tmp)).start())
self.assertEqual((ex.state, ex.exit_code, ex.error), ("failed", 3, "the run exited 3"))

def test_a_run_that_ends_while_it_is_deleted_leaves_no_folder(self):
root = self.tmp / "runs"
ex = execution.Execution(execution.Plan(name="r", script="true"), root=str(root))
reached, go, real = threading.Event(), threading.Event(), ex._save
def save(*a, **kw):
if ex.state == "done" and threading.current_thread() is ex.thread:
reached.set(); go.wait(10) # ended, its last record not yet written
return real(*a, **kw)
ex._save = save
ex.start(); execution.EXECUTIONS[ex.id] = ex
self.assertTrue(reached.wait(10), ex.lines)
deleter = threading.Thread(target=execution.delete, args=(["r"], str(self.tmp / "ws"), str(root)))
deleter.start(); deleter.join(0.5) # Delete launch, meanwhile
go.set(); self.wait(ex); deleter.join(10)
ex._save() # a later save, a cap's
self.assertEqual((ex.state, os.path.exists(ex.dir)), ("done", False))

def test_a_launch_of_the_name_while_delete_ends_keeps_its_run_and_record(self):
root = self.tmp / "runs"
old = self.wait(execution.start_all([execution.Execution(execution.Plan(name="r", script="true"), root=str(root))])[0])
real, new = execution._remove_run, []
def then_launched(path):
real(path) # the old folder went; its entry not yet
new.append(self.wait(execution.start_all([execution.Execution(execution.Plan(name="r", script="true"), root=str(root))])[0]))
with mock.patch.object(execution, "_remove_run", then_launched):
execution.delete(["r"], str(self.tmp / "ws"), str(root))
self.assertEqual((old.deleted, new[0].deleted, execution.EXECUTIONS.get(new[0].id)), (True, False, new[0]))
self.assertEqual(execution.recorded(new[0].dir)[0]["state"], "done")
new[0]._save()
self.assertTrue(os.path.isfile(os.path.join(new[0].dir, "run.json")))


class FirstSave(Base):
def test_a_launch_whose_record_cannot_be_saved_leaves_no_folder_behind(self):
Expand Down
7 changes: 4 additions & 3 deletions app/tests/test_execution_again.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ def test_a_delete_over_a_run_another_delete_holds_lets_no_rerun_in(self):
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
reached, go, real, released = threading.Event(), threading.Event(), execution._remove_run, []
def paused(path):
reached.set(); go.wait(10)
reached.set(); released.append(go.wait(10))
return real(path)
args = (str(self.tmp / "ws"), str(self.tmp / "runs"))
with mock.patch.object(execution, "_remove_run", paused):
Expand All @@ -133,8 +133,9 @@ def paused(path):
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"})
self.assertTrue(first.is_alive()) # refused while Delete A still holds it
go.set(); first.join(10)
self.assertEqual((ex.state, os.path.exists(ex.dir), two.state), ("done", False, "running"))
self.assertEqual((released, ex.state, os.path.exists(ex.dir), two.state), ([True], "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())
Expand Down
49 changes: 49 additions & 0 deletions app/ui_tests/test_rerun_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import shutil
import subprocess
import tempfile
import threading
import unittest
from contextlib import ExitStack
from html import unescape
Expand Down Expand Up @@ -410,6 +411,54 @@ def deleted_meanwhile(*a, name=name, **kw):
self.assertFalse((self.tmp / "runs" / "r1").exists())
self.assertEqual((self.tmp / "runs" / "r2" / "run.json").read_bytes(), replaced["r2"])

@unittest.skipIf(os.geteuid() == 0, "root removes a folder whatever its mode")
def test_a_rerun_asked_while_a_delete_that_is_refused_holds_the_run_is_refused_at_once(self):
d = self.run_of()
self.open(d.parent)
self.stack.enter_context(patch.object(execution.Execution, "again", AGAIN))
runs, real, reached, go, got = self.tmp / "runs", execution._remove_run, threading.Event(), threading.Event(), {}
def paused(path):
reached.set(); go.wait(10)
return real(path)
runs.chmod(0o555); self.addCleanup(runs.chmod, 0o755)
with patch.object(execution, "_remove_run", paused):
deleter = threading.Thread(target=lambda: got.update(execution.delete(["r1"], str(self.tmp / "ws"))))
deleter.start(); self.addCleanup(go.set); self.assertTrue(reached.wait(10))
poster = threading.Thread(target=lambda: got.update(posted=self.post("r1", {"trials": [trial_name(0)]})))
poster.start(); poster.join(5)
self.assertFalse(poster.is_alive(), "the rerun waited for the delete")
self.assertEqual((got["posted"].status_code, got["posted"].json["error"]), (409, "r1 is being deleted: nothing was started"))
go.set(); deleter.join(10)
self.assertEqual(got["stays"], ["r1"])
self.assertFalse((runs / "r1" / "run-again-1.sh").exists())
self.assertEqual(execution.recorded(str(runs / "r1"))[0]["state"], "done")

@unittest.skipIf(os.geteuid() == 0, "root removes a folder whatever its mode")
def test_a_cap_changed_while_delete_removes_the_run_is_kept_when_the_folder_stays_and_refused_when_it_went(self):
d = self.run_of()
self.capped(d, {"max_usd": 4.0, "spent_usd": 0.31, "stopped": False, "cut_off": [], "not_run": []})
self.open(d.parent)
runs, real = self.tmp / "runs", execution._remove_run
for mode, cap in ((0o555, "6"), (0o755, "7")): # the runs root refuses the removal, then lets it go
reached, go, got = threading.Event(), threading.Event(), {}
def paused(path):
reached.set(); go.wait(10)
return real(path)
runs.chmod(mode); self.addCleanup(runs.chmod, 0o755)
with patch.object(execution, "_remove_run", paused):
deleter = threading.Thread(target=lambda: got.update(execution.delete(["r1"], str(self.tmp / "ws"))))
deleter.start(); self.assertTrue(reached.wait(10))
poster = threading.Thread(target=lambda: got.update(posted=self.cap("r1", {"max_usd": cap})))
poster.start(); poster.join(0.5) # the change, while Delete holds the run
go.set(); deleter.join(10); poster.join(10)
if mode == 0o555:
self.assertEqual((got["stays"], got["posted"].status_code), (["r1"], 200), got["posted"].get_data(as_text=True))
execution.EXECUTIONS.clear(); execution.restore()
self.assertEqual(execution.EXECUTIONS["r1-1"].caps, {"r1": 6.0}) # read back after a restart
self.assertEqual((got["stays"], got["posted"].status_code, got["posted"].json["error"]),
([], 409, "r1 was deleted: the cap was not changed."))
self.assertFalse((runs / "r1").exists())

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
2 changes: 2 additions & 0 deletions app/web/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,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:
if ex.deleted:
return jsonify(ok=False, error=f"{ex.plan.name} was deleted: the cap was not changed."), 409
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()
Expand Down
Loading