From 373ea29ccf94202ca46ec9003d4718f4fdbcc018 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 3 Dec 2026 21:50:17 +0100 Subject: [PATCH] fix(runs): remove the workspace roots a refused launch added --- app/nullius/execution.py | 56 ++++- app/nullius/workspace.py | 56 ++++- app/ui_tests/test_run_routes.py | 353 +++++++++++++++++++++++++++++++- app/web/execute.py | 64 +++++- app/web/shared.py | 22 +- 5 files changed, 521 insertions(+), 30 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 2e8018f8e..5e41b4f64 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -2040,6 +2040,11 @@ class NameTaken(ValueError): """A run's name another launch took after it was checked (``reserve``).""" +class Undecided(OSError): + """A launch whose decision could not be read back after it was written + (``start_all``): a restart starts it or not, as the file says then.""" + + RESERVED = ".launching" # in a run's folder from its reservation until it starts; names its launch's decision (``start_all``) LEGACY = ".reserved" # an older Nullius's mark, until its first record; one left beside a record is ignored, as it did # What a launch writes in its folder before its first record (``_save``): the @@ -2191,13 +2196,13 @@ def reserve(runs: List[Execution]) -> None: raise -def release(runs: List[Execution]) -> bool: +def release(runs: List[Execution], kept: Optional[list] = None) -> bool: """The folders of *runs*, reserved and not started, removed with what was written there: their names are free again, and a later save writes the plan anew. Each record goes first, then its folder is moved aside whole, so no instant leaves a record without its mark; a record that cannot go keeps its folder as it is (``_orphan`` takes it over). True when every - folder went.""" + folder went; *kept* given the folders that stay.""" every = True for ex in runs: try: @@ -2210,12 +2215,27 @@ def release(runs: List[Execution]) -> bool: pass except OSError: every = False + if kept is not None: + kept.append(ex.dir) _unhold(ex) ex._planned = False return every -def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]: +def _refuse(runs: List[Execution], decision: str, undo: Optional[Callable], kept: Optional[list]) -> None: + """A launch refused before its decision: ``undo``, then its folders + released and its decision removed once no mark is left to name it.""" + try: + if undo is not None: + undo() + finally: + if release(runs, kept) and decision: # else kept: a mark left may name it + with contextlib.suppress(OSError): + os.unlink(decision) + + +def start_all(runs: List[Execution], reserved: bool = False, then: Optional[Callable] = None, + undo: Optional[Callable] = None, kept: Optional[list] = None) -> List[Execution]: """Start *runs*, those of one launch, once each has its first record: a run without one could not be picked up after a restart (``restore``). Their folders are reserved first unless ``reserved`` says they are. OSError @@ -2224,6 +2244,14 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]: would stay taken. ValueError, before anything is written, for a plan whose parts would run one script file (``Plan.colliding``). + ``then``: called once every record is saved, the records saved again + after it; ``undo``: called on a refusal before the folders go, while the + names and the decision are held, to take back what ``then`` did; *kept*: + as ``release``'s. What ``then`` raises refuses the launch as a failed + save does. A failed decision write is read back: written, the launch + starts (an interrupt leaves it to the restart); still ``preparing``, it + is refused; unknown, everything stays and ``Undecided`` says so. + The launch starts by one decision: a file of this call's own token in the first run's root, ``preparing`` before any mark names it, ``committed`` once every record is saved. A restart starts every run or none @@ -2247,12 +2275,24 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]: ondisk.write_whole(os.path.join(ex.dir, RESERVED), json.dumps({"decision": decision, "token": token})) for ex in runs: ex._save(strict=True) - ondisk.write_whole(decision, json.dumps({"token": token, "state": "committed"})) - except OSError: - if release(runs) and decision: # else kept: a mark left may name it - with contextlib.suppress(OSError): - os.unlink(decision) + if then is not None: + then() + for ex in runs: + ex._save(strict=True) + except BaseException: + _refuse(runs, decision, undo, kept) raise + try: + ondisk.write_whole(decision, json.dumps({"token": token, "state": "committed"})) + except BaseException as error: + said = _decided(runs[0].dir) # read back while the names are held + if said is False: + _refuse(runs, decision, undo, kept) + raise + if said is None and isinstance(error, Exception): + raise Undecided(f"the launch's decision, {decision}, could not be read back") from error + if said is None or not isinstance(error, Exception): + raise # left as it is: a restart reads the decision unmarked = 0 for ex in runs: try: diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 440d7c880..2d43a7244 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -227,11 +227,61 @@ def _set_state(ws: Workspace, **state) -> None: ws.opened, ws.closed = now.opened, now.closed -def add_roots(ws: Workspace, roots) -> None: - """*ws* with *roots* it does not hold yet.""" +def add_roots(ws: Workspace, roots) -> list: + """*ws* with *roots* it does not hold yet: those it took, as its record was saved.""" + added = [] + def add(now): - now.roots = list(now.roots) + [r for r in roots if r not in now.roots] + added[:] = [r for r in dict.fromkeys(roots) if r not in now.roots] + now.roots = list(now.roots) + added _change(ws, add) + return added + + +def take_back(home_dir: str, ws: Workspace, roots) -> tuple: + """*ws* without *roots* in its record, the rest of it - parsed jobs, index, state - as it + is: (the workspace as found, "taken"), (it, "kept") when its record could not be saved + and it still lists some, or (*ws*, "unknown") when it cannot be found or read, so what + it lists is not known. + Found by its uid, or for one saved without, by its folder and created time; looked up + again when it moves meanwhile.""" + for _ in range(3): + where = _found(home_dir, ws) + if where is None: + break + taken = [] + + def drop(now): + now.roots = [r for r in now.roots if r not in roots] + taken.append(now) + try: + _change(where, drop) + except OSError: + again = _found(home_dir, ws) # where it is now: moved meanwhile, looked up again + if again is not None and again.dir == where.dir: + return again, "kept" if any(r in again.roots for r in roots) else "taken" + continue + except (TypeError, ValueError): + break + if taken: + return where, "taken" + return ws, "unknown" + + +def _found(home_dir: str, ws: Workspace) -> Workspace | None: + """*ws* where it is now (``_still``): under its name, else under any other.""" + try: + names = sorted(os.listdir(home_dir)) if ws.uid or ws.folder else [] + except OSError: + names = [] + for name in dict.fromkeys([ws.name] + names): + try: + there = _still(ws, load(home_dir, name)) + except (TypeError, ValueError): + continue + if there is not None: + return there + return None def _state(ws_dir: str) -> dict | None: diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 617e141d7..4fffd8837 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -18,7 +18,7 @@ from contextlib import ExitStack from pathlib import Path from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import Mock, patch from nullius import execution, hosts, workspace from nullius.runs import parse @@ -618,6 +618,357 @@ def fail_second(path, data, mode=None): # the first run's record save self.assertEqual((started, execution.EXECUTIONS), ([], {})) self.assertEqual(list((self.tmp / "runs").glob("*/run.json")), []) + def test_a_refused_launch_leaves_no_root_it_added(self): + write, touch, release, retried = execution.ondisk.write_whole, workspace.touch, execution.release, [] + + def full(path, data, mode=None): # every first record refused + if Path(path).name == "run.json": + raise OSError(28, "No space left on device") + return write(path, data, mode) + + def refused(ws): + raise OSError("disk failure") + + def retry_once_released(runs, *kept): # the same name launched again as soon as it is free + release(runs, *kept) + if not retried: + with patch.object(workspace, "touch", touch): + retried.append(web.execute.begin([execution.Plan(name=runs[0].plan.name, script="true")], "trials")) + + kept = str(self.tmp / "runs" / "kept" / "jobs") + ws = workspace.create(self.home, [str(self.root), kept], "trials") + web.shared.open_workspace(ws) + cases = {"record": [(execution.ondisk, "write_whole", full)], "state": [(workspace, "touch", refused)], + "retry": [(workspace, "touch", refused), (execution, "release", retry_once_released)]} + for case, patches in cases.items(): + for name in ("launch", "kept"): # a root it added; one held before + with self.subTest(case=case, name=name), patch.dict(execution.EXECUTIONS, clear=True), \ + patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None), ExitStack() as stack: + for target, method, effect in patches: + stack.enter_context(patch.object(target, method, effect)) + runs, problem, status = web.execute.begin([execution.Plan(name=name, script="true")], "trials") + self.assertEqual((runs, status), ([], 503), problem) + self.assertNotIn("could not be removed", problem) # a retry's folder is its own + roots = [str(self.root), kept] + [ex.jobs for r in retried for ex in r[0]] + self.assertEqual(workspace.load(self.home, "trials").roots, roots) + self.assertEqual((ws.roots, web.shared.STATE["roots"]), (roots, roots)) + self.assertEqual([status for _, _, status in retried], [200]) + + def test_a_refused_launch_takes_back_only_what_it_added_and_frees_its_name(self): + write = execution.ondisk.write_whole + jobs = str(self.tmp / "runs" / "launch" / "jobs") + trials = workspace.create(self.home, [str(self.root)], "trials") + workspace.create(self.home, [jobs], "other", opened=False) + web.shared.open_workspace(trials) + + def launch(*patches): + with patch.dict(execution.EXECUTIONS, clear=True), patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None), ExitStack() as stack: + for target, method, effect in patches: + stack.enter_context(patch.object(target, method, effect)) + return web.execute.begin([execution.Plan(name="launch", script="true")], "trials") + + def full(path, data, mode=None): # no write goes through + raise OSError(28, "No space left on device") + + def refused(ws): + raise OSError("disk failure") + + def renamed_then_refused(ws): # another workspace with the same root renamed meanwhile + if workspace.load(self.home, "other"): + workspace.rename(self.home, workspace.load(self.home, "other"), "renamed") + refused(ws) + + with self.subTest("a disk that stays full"): + runs, problem, status = launch((execution.ondisk, "write_whole", full)) + self.assertEqual((runs, status), ([], 503), problem) + self.assertEqual(workspace.load(self.home, "trials").roots, [str(self.root)]) + with self.subTest("another workspace holding the root, renamed"): + runs, problem, status = launch((workspace, "touch", renamed_then_refused)) + self.assertEqual((runs, status), ([], 503), problem) + self.assertEqual(workspace.load(self.home, "renamed").roots, [jobs]) + self.assertEqual(workspace.load(self.home, "trials").roots, [str(self.root)]) + with self.subTest("a take-back the disk refuses is said"): + def touch_then_full(ws): + execution.ondisk.write_whole = full + refused(ws) + try: + runs, problem, status = launch((workspace, "touch", touch_then_full)) + finally: + execution.ondisk.write_whole = write + self.assertEqual((runs, status), ([], 503), problem) + self.assertIn(f"Workspace {trials.label} could not drop {jobs}", problem) + workspace.forget(trials, [jobs], []) + with self.subTest("another workspace damaged"): + (Path(self.home) / "damaged").mkdir() + (Path(self.home) / "damaged" / "workspace.json").write_text(json.dumps( + dict(name="damaged", label="Damaged", roots=None, created="", opened=""))) + runs, problem, status = launch((workspace, "touch", refused)) + self.assertEqual((runs, status), ([], 503), problem) + runs, problem, status = launch() # the name is free again + self.assertEqual(status, 200, problem) + + def test_a_refused_launch_never_starts_files_where_it_ran_and_says_what_stays(self): + write, touch = execution.ondisk.write_whole, workspace.touch + jobs = str(self.tmp / "runs" / "launch" / "jobs") + + def launch(into, *patches): + with patch.dict(execution.EXECUTIONS, clear=True), patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None), ExitStack() as stack: + for target, method, effect in patches: + stack.enter_context(patch.object(target, method, effect)) + return web.execute.begin([execution.Plan(name="launch", script="true")], into) + + def full(path, data, mode=None): + raise OSError(28, "No space left on device") + + def refused(ws): + raise OSError("disk failure") + + def fresh(name="trials", open_=True): # no run folder, one workspace + shutil.rmtree(self.tmp / "runs" / "launch", ignore_errors=True) + for decision in (self.tmp / "runs").glob(".launch-*"): + decision.unlink() + shutil.rmtree(self.home, ignore_errors=True) + ws = workspace.create(self.home, [str(self.root)], name) + web.shared.close_workspace(save=False) + if open_: + web.shared.open_workspace(ws) + return ws + + with self.subTest("a failure once it is decided leaves it to the restart"): + fresh() + held = [] + + def unhold_once(ex): + if not held: + held.append(ex) + raise OSError("busy") + unhold(ex) + unhold = execution._unhold + self.addCleanup(lambda: [unhold(ex) for ex in held]) + with self.assertRaises(OSError): + launch("trials", (execution, "_unhold", unhold_once)) + self.assertTrue((self.tmp / "runs" / "launch" / "run.json").exists()) + self.assertIn(jobs, workspace.load(self.home, "trials").roots) + with self.subTest("nothing open: a record that cannot name its workspace refuses the launch"): + fresh(open_=False) + saves = [] + + def first_record_only(path, data, mode=None): + if Path(path).name == "run.json": + saves.append(path) + if len(saves) > 1: + raise OSError(28, "No space left on device") + return write(path, data, mode) + runs, problem, status = launch("", (execution.ondisk, "write_whole", first_record_only)) + self.assertEqual((runs, status), ([], 503), problem) + self.assertEqual([ws.roots for ws in workspace.list_all(self.home) if jobs in ws.roots], []) + with self.subTest("its workspace moved, another made under its name"): + ws = fresh() + + def moved_then_refused(handle): + if workspace.load(self.home, "trials").uid == ws.uid: + workspace.rename(self.home, workspace.load(self.home, "trials"), "moved") + workspace.create(self.home, [jobs], "trials", opened=False) + raise OSError("disk failure") + runs, problem, status = launch("trials", (workspace, "touch", moved_then_refused)) + self.assertEqual(status, 503, problem) + self.assertNotIn("Workspace", problem) + self.assertEqual((workspace.load(self.home, "moved").roots, workspace.load(self.home, "trials").roots), + ([str(self.root)], [jobs])) + with self.subTest("its workspace opened again meanwhile"): + fresh() + + def reopened_then_refused(handle): + web.shared.STATE["workspace"] = workspace.load(self.home, "trials") + raise OSError("disk failure") + runs, problem, status = launch("trials", (workspace, "touch", reopened_then_refused)) + self.assertEqual(status, 503, problem) + self.assertEqual((web.shared.STATE["workspace"].roots, web.shared.STATE["roots"]), ([str(self.root)], [str(self.root)])) + self.assertEqual(list((self.tmp / "runs").glob(".launch-*")), []) # every folder went: its decision too + with self.subTest("its workspace, saved without a uid, moved"): + ws = fresh() + record = Path(ws.dir) / "workspace.json" + record.write_text(json.dumps({k: v for k, v in json.loads(record.read_text()).items() if k != "uid"})) + web.shared.open_workspace(workspace.load(self.home, "trials")) + + def moved_then_refused(handle): + if workspace.load(self.home, "trials"): + workspace.rename(self.home, workspace.load(self.home, "trials"), "moved") + raise OSError("disk failure") + runs, problem, status = launch("trials", (workspace, "touch", moved_then_refused)) + self.assertEqual(status, 503, problem) + self.assertNotIn("list", problem) + self.assertEqual(workspace.load(self.home, "moved").roots, [str(self.root)]) + with self.subTest("its workspace moved as it is changed"): + fresh() + change, moved = workspace._change, [] + + def moved_first(ws, how): + if not moved and ws.name == "trials" and getattr(how, "__name__", "") == "drop": + moved.append(workspace.rename(self.home, workspace.load(self.home, "trials"), "moved")) + return change(ws, how) + runs, problem, status = launch("trials", (workspace, "touch", refused), (workspace, "_change", moved_first)) + self.assertEqual(status, 503, problem) + self.assertNotIn("list", problem) + self.assertEqual(workspace.load(self.home, "moved").roots, [str(self.root)]) + with self.subTest("its workspace unreadable: said, with the reason of the refusal"): + fresh() + + def unreadable_then_refused(handle): + (Path(self.home) / "trials" / "workspace.json").write_text("{broken") + raise OSError("disk failure") + runs, problem, status = launch("trials", (workspace, "touch", unreadable_then_refused)) + self.assertEqual(status, 503, problem) + self.assertIn("disk failure", problem) + self.assertIn(f"Workspace trials may still list {jobs}.", problem) + with self.subTest("its workspace moved, then the disk full: the one that lists it is named"): + fresh() + + def moved_then_full(handle): + if not workspace.load(self.home, "moved"): + workspace.rename(self.home, workspace.load(self.home, "trials"), "moved") + workspace.create(self.home, [jobs], "trials", opened=False) + execution.ondisk.write_whole = full + refused(handle) + try: + runs, problem, status = launch("trials", (workspace, "touch", moved_then_full)) + finally: + execution.ondisk.write_whole = write + self.assertEqual(status, 503, problem) + self.assertIn(f"Workspace moved could not drop {jobs}", problem) + self.assertNotIn("Workspace trials", problem) + with self.subTest("an error once its decision is written: it starts"): + fresh() + close, replace, published = execution.ondisk.os.close, execution.ondisk.os.replace, [] + + def replaced(src, dst): + replace(src, dst) + published.append(os.path.basename(dst).startswith(".launch-") and "committed" in Path(dst).read_text()) + + def closed(fd): + close(fd) + if published and published[-1]: + published.append(False) + raise OSError(errno.EIO, "Input/output error") + runs, problem, status = launch("trials", (execution.ondisk.os, "replace", replaced), (execution.ondisk.os, "close", closed)) + self.assertEqual(status, 200, problem) + self.assertTrue((self.tmp / "runs" / "launch" / "run.json").exists()) + self.assertIn(jobs, workspace.load(self.home, "trials").roots) + with self.subTest("its workspace moved as its lock is taken, another made under its name"): + fresh() + locked, armed = workspace._locked, [] + + def armed_then_refused(handle): + armed.append(True) + refused(handle) + + def moved_at_lock(ws): + if armed and ws.name == "trials": + armed.clear() + workspace.rename(self.home, workspace.load(self.home, "trials"), "moved") + workspace.create(self.home, [jobs], "trials", opened=False) + raise FileNotFoundError(errno.ENOENT, "No such file or directory") + return locked(ws) + runs, problem, status = launch("trials", (workspace, "touch", armed_then_refused), (workspace, "_locked", moved_at_lock)) + self.assertEqual(status, 503, problem) + self.assertNotIn("Workspace", problem) + self.assertEqual((workspace.load(self.home, "moved").roots, workspace.load(self.home, "trials").roots), + ([str(self.root)], [jobs])) + with self.subTest("a folder busy once: no advice to remove what a retry now holds"): + fresh() + rename = execution.os.rename + + def busy_once(src, dst): + if ".released-" in os.fspath(dst) and not busy: + busy.append(True) + raise OSError(errno.EBUSY, "Device or resource busy") + return rename(src, dst) + busy = [] + runs, problem, status = launch("trials", (workspace, "touch", refused), (execution.os, "rename", busy_once)) + self.assertEqual(status, 503, problem) + self.assertIn("could not be removed: retry the launch.", problem) + self.assertNotIn("remove it", problem) + runs, problem, status = launch("trials") + self.assertEqual(status, 200, problem) + with self.subTest("a root it did not add: nothing said of it"): + ws = fresh() + workspace.add_roots(ws, [jobs]) + + def full_then_refused(handle): + execution.ondisk.write_whole = full + refused(handle) + try: + runs, problem, status = launch("trials", (workspace, "touch", full_then_refused)) + finally: + execution.ondisk.write_whole = write + self.assertEqual(status, 503, problem) + self.assertNotIn("Workspace", problem) + with self.subTest("a refusal keeps its reason and says what it could not undo"): + ws = fresh() + + def refused_and_full(handle): + execution.ondisk.write_whole = full + raise ValueError("Refused.") + try: + with patch.object(execution.os, "rename", side_effect=OSError("busy")): + runs, problem, status = launch("trials", (workspace, "touch", refused_and_full)) + finally: + execution.ondisk.write_whole = write + self.assertEqual(status, 400, problem) + for said in ("Refused.", f"Workspace {ws.label} could not drop {jobs}", f"{self.tmp / 'runs' / 'launch'} could not be removed"): + self.assertIn(said, problem) + self.assertEqual(len(list((self.tmp / "runs").glob(".launch-*"))), 1) # its mark still names it + + def test_a_launch_killed_while_taking_back_its_workspace_never_starts_and_frees_its_name(self): + runs = self.tmp / "runs" + workspace.create(self.home, [str(self.root)], "trials") + killed = ("import os, signal, sys; sys.path.insert(0, sys.argv[1])\n" + "from unittest.mock import patch\nimport web, web.execute\nfrom nullius import execution, ondisk\n" + "web.shared.WS_HOME = sys.argv[2]; write = ondisk.write_whole\n" + "def undecided(path, data, mode=None):\n" + " if os.path.basename(path).startswith('.launch-') and 'committed' in str(data):\n" + " raise OSError(28, 'No space left on device')\n" + " return write(path, data, mode)\n" + "with patch.object(execution.Plan, 'check', return_value=''), patch.object(ondisk, 'write_whole', undecided), \\\n" + " patch.object(web.execute, '_unadopt', lambda added: os.kill(os.getpid(), signal.SIGKILL)):\n" + " web.execute.begin([execution.Plan(name='launch', script='true')], 'trials')\n") + env = dict(os.environ, RUNS_DIR=str(runs), JOB_ROOTS="") + self.assertEqual(subprocess.run([shutil.which("python3"), "-c", killed, str(APP), self.home], env=env).returncode, -9) + resumed = [] + with patch.dict(execution.EXECUTIONS, clear=True), patch.object(execution, "_follow", lambda root: None), \ + patch.object(execution.Execution, "resume", lambda ex: resumed.append(ex) or ex): + execution.restore(str(runs)) + self.assertEqual(resumed, []) + with patch.dict(execution.EXECUTIONS, clear=True), patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None): + started, problem, status = web.execute.begin([execution.Plan(name="launch", script="true")], "trials") + self.assertEqual(status, 200, problem) + + def test_a_launch_interrupted_once_decided_is_left_to_the_restart(self): + runs = self.tmp / "runs" + workspace.create(self.home, [str(self.root)], "trials") + interrupted = ("import os, signal, sys; sys.path.insert(0, sys.argv[1])\n" + "from unittest.mock import patch\nimport web, web.execute\nfrom nullius import execution, ondisk\n" + "web.shared.WS_HOME = sys.argv[2]; replace = os.replace\n" + "def then_interrupted(src, dst):\n" + " replace(src, dst)\n" + " if os.path.basename(dst).startswith('.launch-') and 'committed' in open(dst).read():\n" + " os.kill(os.getpid(), signal.SIGINT)\n" + "with patch.object(execution.Plan, 'check', return_value=''), patch.object(ondisk.os, 'replace', then_interrupted):\n" + " web.execute.begin([execution.Plan(name='launch', script='true')], 'trials')\n") + env = dict(os.environ, RUNS_DIR=str(runs), JOB_ROOTS="") + self.assertNotEqual(subprocess.run([shutil.which("python3"), "-c", interrupted, str(APP), self.home], env=env, + capture_output=True).returncode, 0) + self.assertIn(str(runs / "launch" / "jobs"), workspace.load(self.home, "trials").roots) + resumed = [] + with patch.dict(execution.EXECUTIONS, clear=True), patch.object(execution, "_follow", lambda root: None), \ + patch.object(execution.Execution, "resume", lambda ex: resumed.append(ex) or ex): + execution.restore(str(runs)) + self.assertEqual([ex.plan.name for ex in resumed], ["launch"]) + def test_a_failed_workspace_save_does_not_add_roots_in_memory(self): ws = workspace.create(self.home, [str(self.root)], "trials") web.shared.open_workspace(ws) diff --git a/app/web/execute.py b/app/web/execute.py index e9cc79b09..3cce0e6b3 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -256,22 +256,64 @@ def begin(plans: list, into: str = "") -> tuple: return [], str(error), 409 except OSError as error: return [], saving(error), 503 - # Save the destination before any worker can run. Its name goes into - # the first run record, rather than a second write after launch. + # Records, then the workspace, then the decision (``start_all``): a + # refused record leaves the workspace untouched, and no run starts, now or + # after a restart, before its root is saved and its record names where. + # Until the decision a refusal takes back the roots it added while it + # still holds the names, so a retry's are its own. + added, unfinished, kept, step = [], [], [], "record" + + def adopt(): + nonlocal step + step = "workspace" + shared.adopt_runs(prepared, into, persist=False, added=added) + step = "record" + + def undo(): + nonlocal step + step = "refused" if step == "record" else "refused-workspace" + unfinished.extend(_unadopt(added)) + try: - shared.adopt_runs(prepared, into, persist=False) - except (ValueError, OSError) as error: - execution.release(prepared) + execution.start_all(prepared, reserved=True, then=adopt, undo=undo, kept=kept) + except execution.Undecided as error: + return [], f"The launch could not be confirmed ({error.__cause__ or error}). A restart starts it if it was saved.", 503 + except BaseException as error: + if not step.startswith("refused"): + raise # decided: it runs, whatever failed after + unfinished += [f"{d} could not be removed: retry the launch." for d in kept] if isinstance(error, ValueError): - return [], str(error), 400 - return [], "The launch workspace could not be saved. Check its permissions and free space, then retry.", 503 - try: - execution.start_all(prepared, reserved=True) - except OSError as error: - return [], saving(error), 503 + return [], " ".join([str(error)] + unfinished), 400 + if not isinstance(error, OSError): + raise + why = saving(error) if step == "refused" else (f"The launch workspace could not be saved ({error.strerror or error}). " + "Check its permissions and free space, then retry.") + return [], " ".join([why] + unfinished), 503 return prepared, "", 200 +def _unadopt(added) -> list: + """The roots a refused launch added (``shared.adopt_roots``), out of each + workspace again (``workspace.take_back``); the one open shows it without + being opened again. One line per workspace that still lists some, or may.""" + left = [] + for ws, roots in added: + try: + where, done = workspace.take_back(shared.WS_HOME, ws, roots) + except Exception: + where, done = ws, "unknown" + if done == "kept": + left.append(f"Workspace {where.label} could not drop {', '.join(roots)}: retry the launch.") + elif done == "unknown": + left.append(f"Workspace {ws.label} may still list {', '.join(roots)}.") + shown = shared.STATE["workspace"] + if done == "taken" and shown is not None and (shown is ws or (shown.uid, shown.folder) == (where.uid, where.folder)): + shown.roots = where.roots + shared.set_source(shown.roots, shown.label) + shared.STATE["job_roots"] = workspace.walked(shown) + return left + + def _start(plan: execution.Plan, into: str = ""): started, problem, status = begin([plan], into) if problem: diff --git a/app/web/shared.py b/app/web/shared.py index fa4fc1e35..a9472db69 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -181,43 +181,51 @@ def close_workspace(save=True): STATE.update({"workspace": None, "roots": [], "label": "", "job_roots": []}) -def adopt_roots(roots, label="", new=False, into=""): +def adopt_roots(roots, label="", new=False, into="", added=None): """Roots the user just pointed at: into the open workspace, or a new one. Without a label, roots that already have a workspace reopen it — so a restart with the same argv lands in the same place, cache and all. ``into``: the workspace to add them to while it exists, left closed unless it is open already; once it is gone, never the open one. + ``added``: a list given (workspace, the roots it took) as its record is + saved, before it is opened. """ ws = STATE["workspace"] if into and not (ws and ws.name == into): ws = workspace.load(WS_HOME, into) if ws and not new: - workspace.add_roots(ws, roots) + took = workspace.add_roots(ws, roots) + if added is not None and took: + added.append((ws, took)) if STATE["workspace"] is ws: open_workspace(ws) return ws ws = None if label else workspace.find_by_roots(WS_HOME, roots, besides=execution.runs_root()) - ws = ws or workspace.create(WS_HOME, roots, label) + if ws is None: + ws = workspace.create(WS_HOME, roots, label) + if added is not None: + added.append((ws, list(roots))) if new or not into or STATE["workspace"] is None: # a gone ``into`` leaves the open workspace open open_workspace(ws) return ws -def adopt_runs(runs, into="", *, persist=True): +def adopt_runs(runs, into="", *, persist=True, added=None): """Runs just started: their jobs into a workspace as ``adopt_roots`` puts them - ``into``, made under that name when there is none, the open one left as it is. With ``persist=False``, the runs have not started: their - first record will name the workspace, without writing a resumable run yet.""" + records, which name the workspace, are left to the launch to save. + ``added``: as ``adopt_roots``.""" roots = [ex.jobs for ex in runs] if into: os.makedirs(WS_HOME, exist_ok=True) with ondisk.locked(os.path.join(WS_HOME, f".{into}.lock")): if workspace.load(WS_HOME, into, strict=True) is None: workspace.create(WS_HOME, [], into, opened=False, exact=True) - ws = adopt_roots(roots, into=into) + ws = adopt_roots(roots, into=into, added=added) else: - ws = adopt_roots(roots) + ws = adopt_roots(roots, added=added) for ex in runs: if persist: ex.file_under(ws.name)