From 333db242774e0b9f8bb0539b9ba72edde9bd37e4 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 10:23:54 +0100 Subject: [PATCH 1/9] feat(web): let a run started over the API name the workspace its jobs go into A program that starts a run over the API cannot say where its jobs go: they land in the workspace open on the server, or in a new one with a random name when none is open. A person reading the pages then finds runs they did not start in the workspace they are looking at. A start now takes a workspace: the `workspace` field of `POST /api/v1/runs`, `Client.start(workspace=...)`, `nullius remote run --workspace NAME` and the `workspace` input of MCP's `start_run`. The workspace is made, closed, when there is none, and the run's record names it for a restart. The open workspace stays open with its own jobs, and a restart reopens it, not the one the run went into. A name that is not lowercase letters, digits and dashes is refused with 400, as is a workspace that is a symbolic link or leads outside the workspaces folder. Without the field nothing changes. The builder's Run offers no workspace: its runs go into the open one, as before. --- app/nullius/client.py | 11 +++-- app/nullius/mcp_server.py | 5 +- app/nullius/workspace.py | 4 +- app/tests/test_client.py | 7 ++- app/tests/test_workspace.py | 17 +++++++ app/ui_tests/test_agents.py | 6 +-- app/ui_tests/test_api.py | 61 +++++++++++++++++++++++- app/ui_tests/test_harbor_routes.py | 2 +- app/ui_tests/test_prerequisites_route.py | 2 +- app/ui_tests/test_run_routes.py | 44 ++++++++++++++++- app/web/api.py | 7 ++- app/web/execute.py | 37 +++++++++----- app/web/shared.py | 9 ++-- docs/api.md | 7 +-- 14 files changed, 180 insertions(+), 39 deletions(-) diff --git a/app/nullius/client.py b/app/nullius/client.py index 17c4e795c..d9597e01f 100644 --- a/app/nullius/client.py +++ b/app/nullius/client.py @@ -181,9 +181,11 @@ def check(self, recipe: Union[dict, str], where=None) -> dict: """What Review shows for a recipe (a dict, or a saved one's id or name): ``ready``, ``errors``, ``confirm``, ``machines``.""" return self.request("POST", "/runs/check", self._run_body(recipe, where)) - def start(self, recipe: Union[dict, str], where=None, name: Optional[str] = None, confirm: bool = False) -> dict: - """Start a recipe; ``runs`` holds one run per machine. ``confirm``: the yes to the question ``check`` returns.""" - return self.request("POST", "/runs", self._run_body(recipe, where, name=name, confirm=confirm)) + def start(self, recipe: Union[dict, str], where=None, name: Optional[str] = None, confirm: bool = False, + workspace: Optional[str] = None) -> dict: + """Start a recipe; ``runs`` holds one run per machine. ``confirm``: the yes to the question ``check`` returns. + ``workspace``: the one its jobs go into, made when there is none; the open one stays open.""" + return self.request("POST", "/runs", self._run_body(recipe, where, name=name, confirm=confirm, workspace=workspace)) def runs(self) -> list: return self.request("GET", "/runs") @@ -285,6 +287,7 @@ def main(argv=None) -> int: p.add_argument("recipe", metavar="RECIPE") p.add_argument("--where") p.add_argument("--name", help="the run's name (default: the recipe's name and the second)") + p.add_argument("--workspace", help="the workspace its jobs go into, made when there is none (default: the open one)") p.add_argument("--yes", action="store_true", help="answer yes to the question the check returns") p.add_argument("--follow", action="store_true", help="print the log until the run ends; exit 4 unless it ends done") sub.add_parser("runs", help="the runs the server follows") @@ -302,7 +305,7 @@ def main(argv=None) -> int: return EXIT_USAGE try: if a.cmd == "run": - out = nx.start(_recipe_arg(a.recipe), where=a.where, name=a.name, confirm=a.yes) + out = nx.start(_recipe_arg(a.recipe), where=a.where, name=a.name, confirm=a.yes, workspace=a.workspace) if a.follow: ok = True for r in out["runs"]: diff --git a/app/nullius/mcp_server.py b/app/nullius/mcp_server.py index 9f1a36740..e5fa484ae 100644 --- a/app/nullius/mcp_server.py +++ b/app/nullius/mcp_server.py @@ -23,6 +23,7 @@ _TRIAL = {**_JOB, "trial": dict(_S, description="a trial name of that job, as get_job returns it")} _RECIPE = {"recipe": {"description": "a saved recipe's id or name (list_recipes), or a whole recipe object"}} _RUN = {"run_id": dict(_S, description="a run id, as start_run or list_runs returns it")} +_WORKSPACE = {"workspace": dict(_S, description="the workspace its jobs go into, made when there is none; else the open one")} # name: (description, properties, required, the call) TOOLS = { @@ -56,8 +57,8 @@ "and the question to confirm.", {**_RECIPE, "where": _S}, ["recipe"], lambda nx, a: nx.check(a["recipe"], a.get("where"))), "start_run": ("Start a recipe. It spends model tokens and machine time: call check_run first, and set confirm only " - "when the person has agreed to the question it returned.", {**_RECIPE, "where": _S, "confirm": _B}, ["recipe"], - lambda nx, a: nx.start(a["recipe"], a.get("where"), confirm=a.get("confirm") is True)), + "when the person has agreed to the question it returned.", {**_RECIPE, "where": _S, "confirm": _B, **_WORKSPACE}, ["recipe"], + lambda nx, a: nx.start(a["recipe"], a.get("where"), confirm=a.get("confirm") is True, workspace=a.get("workspace"))), "list_runs": ("The runs the server follows: state, stages, job ids.", {}, [], lambda nx, a: nx.runs()), "get_run": ("One run: state, stages, and its log lines from `since` on.", {**_RUN, "since": _I}, ["run_id"], lambda nx, a: nx.run(a["run_id"], a.get("since") or 0)), diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index aec94bf54..09f589b44 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -177,13 +177,13 @@ def _free(name: str, taken) -> str: return next(c for c in (f"{name[:NAME_MAX - len(str(i)) - 1].rstrip('-')}-{i}" for i in range(2, 1000)) if c not in taken) -def create(home_dir: str, roots, label: str = "") -> Workspace: +def create(home_dir: str, roots, label: str = "", *, opened: bool = True) -> Workspace: taken = {ws.name for ws in list_all(home_dir)} name = slug(label) name = _free(name, taken) if name else random_name(taken) now = _now() ws = Workspace(name=name, label=label.strip() or name, roots=list(roots), - created=now, opened=now, dir=os.path.join(home_dir, name)) + created=now, opened=now if opened else "", closed=not opened, dir=os.path.join(home_dir, name)) save(ws) return ws diff --git a/app/tests/test_client.py b/app/tests/test_client.py index c3a1e5aa7..232a59875 100644 --- a/app/tests/test_client.py +++ b/app/tests/test_client.py @@ -107,6 +107,7 @@ def test_every_call_carries_the_token_and_asks_its_route(self): (lambda: self.nx.start("nightly"), "POST", "/runs", "", {"recipe": "nightly"}), # no yes unless asked for (lambda: self.nx.start("nightly", where=["local", "bench"], name="n-1", confirm=True), "POST", "/runs", "", {"recipe": "nightly", "where": ["local", "bench"], "name": "n-1", "confirm": True}), + (lambda: self.nx.start("nightly", workspace="trials"), "POST", "/runs", "", {"recipe": "nightly", "workspace": "trials"}), (lambda: self.nx.runs(), "GET", "/runs", "", None), (lambda: self.nx.run("r1"), "GET", "/runs/r1", "", None), (lambda: self.nx.run("r1", since=40), "GET", "/runs/r1", "since=40", None), @@ -289,8 +290,8 @@ def test_run_sends_a_recipe_file_or_a_saved_name_and_the_yes_only_when_given(sel path = os.path.join(tmp, "r.json") with open(path, "w") as fh: json.dump(doc, fh) - self.remote("run", path, "--where", "bench", "--name", "g-1", "--yes") - self.assertEqual(self.last()["body"], {"recipe": recipe, "where": "bench", "name": "g-1", "confirm": True}) + self.remote("run", path, "--where", "bench", "--name", "g-1", "--workspace", "trials", "--yes") + self.assertEqual(self.last()["body"], {"recipe": recipe, "where": "bench", "name": "g-1", "workspace": "trials", "confirm": True}) with open(path, "w") as fh: fh.write("{not json") self.assertEqual(self.remote("run", path)[0], 2) @@ -368,6 +369,8 @@ def test_start_run_says_yes_only_when_told(self): self.assertEqual(self.last()["body"], {"recipe": "nightly"}) self.call("start_run", {"recipe": "nightly", "confirm": True}) self.assertEqual(self.last()["body"], {"recipe": "nightly", "confirm": True}) + self.call("start_run", {"recipe": "nightly", "workspace": "trials"}) + self.assertEqual(self.last()["body"], {"recipe": "nightly", "workspace": "trials"}) asked = len(self.server.asked) for yes in ("false", "true", 1, [0]): # only true is a yes self.assertEqual(self.call("start_run", {"recipe": "nightly", "confirm": yes})["error"]["code"], -32602, yes) diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index ad8533950..a7ca94220 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -183,6 +183,23 @@ def test_last_open_is_the_latest_unless_the_user_closed_it(self): workspace.touch(b) self.assertEqual(workspace.last_open(self.home).name, "b") + def test_an_unopened_workspace_is_remembered_only_after_it_is_opened(self): + a = workspace.create(self.home, [], "destination", opened=False) + self.assertEqual((a.opened, a.closed), ("", True)) + self.assertIsNone(workspace.last_open(self.home)) + with patch.object(workspace, "_now", return_value="2000-01-01T00:00:00+00:00"): + b = workspace.create(self.home, [], "existing") + c = workspace.create(self.home, [], "another", opened=False) + self.assertEqual((workspace.load(self.home, c.name).opened, c.closed), ("", True)) + self.assertEqual(workspace.last_open(self.home).name, b.name) + b.closed = True + workspace.save(b) + self.assertIsNone(workspace.last_open(self.home)) + workspace.touch(a) + self.assertTrue(a.opened) + self.assertFalse(a.closed) + self.assertEqual(workspace.last_open(self.home).name, a.name) + class Holding(unittest.TestCase): def test_each_folder_lists_the_workspaces_with_a_root_in_it(self): diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index 08b4aff64..2958b1c2f 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -48,7 +48,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() def test_capability_source_retains_pin_and_install_details(self): @@ -379,7 +379,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {"id": plan.name + "-1"}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) self.schema = json.loads(re.search(r'', r.get_data(as_text=True), re.S).group(1)) @@ -469,7 +469,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {"id": plan.name}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() def get(self, url): diff --git a/app/ui_tests/test_api.py b/app/ui_tests/test_api.py index a32fa4d82..01805bbe9 100644 --- a/app/ui_tests/test_api.py +++ b/app/ui_tests/test_api.py @@ -533,7 +533,7 @@ def run(argv, timeout=600, stdin=None, stop=None): self.stack.enter_context(patch.object(execution, "subprocess_run", run)) self.stack.enter_context(patch.object(execution, "docker_here", lambda sh, needs="", program="docker": None)) self.adopted = [] - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: self.adopted.extend(ex.plan.name for ex in runs))) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": self.adopted.extend(ex.plan.name for ex in runs))) def scripted(self, script="echo started; echo \"key=${#OPENAI_API_KEY}\""): """A recipe of the first two problems, whose run is this test's script in place of the standard's command.""" @@ -728,7 +728,7 @@ def test_a_recipe_is_checked_started_followed_and_read_back(self): runs = Runs("test_a_run_is_followed_listed_and_stopped_by_its_id") runs.stack, runs.adopted = self.stack, [] recipe = Runs.scripted(runs, "echo one; echo two") - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda started: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda started, into="": None)) self.stack.enter_context(patch.object(execution, "docker_here", lambda sh, needs="", program="docker": None)) nx = client.Client(self.url, self.runner) nx.save_recipe(dict(recipe, title="Nightly")) @@ -751,6 +751,63 @@ def test_the_command_and_the_mcp_tools_ask_the_same_server(self): refused = call("start_run", {"recipe": gsm8k(), "confirm": True}) # a read token starts nothing, by any door self.assertEqual((refused["isError"], json.loads(refused["content"][0]["text"])["error"]), (True, "This token's scope is read: this needs run.")) + def test_a_start_puts_its_jobs_in_the_workspace_it_names_by_every_door(self): + """By the route, the client, the command and the MCP tool: the jobs go into the workspace named, made when there + is none, and the open one stays open with its jobs as they were; named none, they go into the open one. A name + the pages would not make, or a read token, starts nothing and makes no workspace, refused as that door refuses.""" + self.stack.enter_context(patch.object(execution, "docker_here", lambda sh, needs="", program="docker": None)) + self.stack.enter_context(patch.object(execution.Execution, "_main", lambda ex: None)) # where the jobs go is what is read here + home, numbers = web.shared.WS_HOME, iter(range(100)) + recipe = lambda: gsm8k(name=f"g{next(numbers)}") # a run's name each: two starts in one second + token = lambda who: self.reader if who == "reader" else self.runner + + def route(who, **into): + r = self.post("/runs", {"recipe": recipe(), "confirm": True, **into}, token=who) + return r.status_code, r.json + + def python(who, **into): + try: + return 200, client.Client(self.url, token(who)).start(recipe(), confirm=True, **into) + except client.ApiError as e: + return e.status, {"error": str(e)} + + def command(who, **into): + path, out, err = self.tmp / "recipe.json", io.StringIO(), io.StringIO() + path.write_text(json.dumps(recipe())) + with patch.dict(os.environ, {"NULLIUS_SERVER": self.url, "NULLIUS_TOKEN": token(who)}), \ + contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = cli.main(["remote", "run", str(path), "--yes", *(["--workspace", into["workspace"]] if into else [])]) + return code, json.loads(out.getvalue()) if code == 0 else {"error": err.getvalue().strip()} + + def tool(who, **into): + got = mcp_server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { + "name": "start_run", "arguments": {"recipe": recipe(), "confirm": True, **into}}}, client.Client(self.url, token(who)))["result"] + return got["isError"], json.loads(got["content"][0]["text"]) + + opened = web.shared.STATE["workspace"] + held = list(opened.roots) + for n, (start, started, refused) in enumerate(((route, 200, (400, 403)), (python, 200, (400, 403)), (command, 0, (4, 4)), (tool, False, (True, True)))): + with self.subTest(start.__name__): + into = f"trials-{n}" + self.assertIsNone(workspace.load(home, into)) + status, got = start("runner", workspace=into) + self.assertEqual(status, started, got) + run = got["runs"][0] + made = workspace.load(home, into) + self.assertEqual((made.roots, made.closed, execution.EXECUTIONS[run["id"]].workspace), ([run["jobs"]], True, into)) + self.assertIs(web.shared.STATE["workspace"], opened) + self.assertEqual(workspace.load(home, opened.name).roots, held) # the open one, as it was + again = start("runner", workspace=into)[1]["runs"][0] # there now: added to + self.assertEqual(workspace.load(home, into).roots, [run["jobs"], again["jobs"]]) + plain = start("runner")[1]["runs"][0] # none named: the open one + held.append(plain["jobs"]) + self.assertEqual((workspace.load(home, opened.name).roots, execution.EXECUTIONS[plain["id"]].workspace), (held, opened.name)) + before = (len(execution.EXECUTIONS), sorted(w.name for w in workspace.list_all(home))) + self.assertEqual(start("runner", workspace="Not a name"), + (refused[0], {"error": "A workspace's name is lowercase letters, digits and dashes."})) + self.assertEqual(start("reader", workspace="elsewhere"), (refused[1], {"error": "This token's scope is read: this needs run."})) + self.assertEqual((len(execution.EXECUTIONS), sorted(w.name for w in workspace.list_all(home))), before) + if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_harbor_routes.py b/app/ui_tests/test_harbor_routes.py index f8fb04d69..5cd11c6cd 100644 --- a/app/ui_tests/test_harbor_routes.py +++ b/app/ui_tests/test_harbor_routes.py @@ -40,7 +40,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {"id": plan.name + "-1", "state": "preparing"}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) with self.client.session_transaction() as s: diff --git a/app/ui_tests/test_prerequisites_route.py b/app/ui_tests/test_prerequisites_route.py index 22f724a03..1a64b8cb0 100644 --- a/app/ui_tests/test_prerequisites_route.py +++ b/app/ui_tests/test_prerequisites_route.py @@ -29,7 +29,7 @@ def setUp(self): self.started = [] self.stack.enter_context(patch.object(execution, "start", lambda plan: self.started.append(plan) or SimpleNamespace( jobs=str(self.tmp), summary=lambda: {"id": "x", "state": "preparing"}))) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) with self.client.session_transaction() as s: diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index a456c9b4e..38a120fdf 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -79,7 +79,7 @@ def run(argv, timeout=600, stdin=None, stop=None): return 0, "" self.stack.enter_context(patch.object(execution, "subprocess_run", run)) self.stack.enter_context(patch.object(execution, "docker_here", lambda sh, needs="": None)) # docker answers here, as the probe says it does there - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: self.adopted.extend(ex.jobs for ex in runs))) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": self.adopted.extend(ex.jobs for ex in runs))) self.adopted = [] self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) @@ -173,6 +173,32 @@ def test_a_name_still_running_or_used_before_is_refused_and_nothing_starts(self) self.assertEqual((dict(execution.EXECUTIONS), self.adopted), ({}, [])) # nothing started, the free name included self.assertFalse((self.tmp / "runs" / "fresh").exists()) + def test_a_launch_refuses_a_linked_workspace_before_starting(self): + home = self.tmp / "workspaces" + home.mkdir() + outside = self.tmp / "outside" + outside.mkdir() + inside = home / "inside" + inside.mkdir() + linked = home / "trials" + run = SimpleNamespace(jobs=str(self.tmp / "runs" / "launch" / "jobs"), summary=lambda: {"id": "launch"}) + with patch.object(web.shared, "WS_HOME", str(home)), patch.object(execution, "start", return_value=run) as start: + for target in (outside, inside, self.tmp / "absent"): + with self.subTest(target=target): + linked.symlink_to(target, target_is_directory=True) + try: + r = self.post({"name": "launch", "script": "true", "workspace": "trials"}) + self.assertEqual(r.status_code, 400) + self.assertIn("symbolic link", r.json["error"]) + start.assert_not_called() + self.assertFalse((target / "workspace.json").exists()) + finally: + linked.unlink() + runs, problem, status = web.execute.begin([], "../outside") + self.assertEqual((runs, status), ([], 400)) + self.assertIn("inside the workspaces folder", problem) + start.assert_not_called() + def test_a_single_run_opens_its_job_page_before_harbor_writes_the_job(self): r = self.post({"name": "tau3-x3", "script": "true", "where": "local", "jobs": [{"name": "tau3-x3", "agent": "oracle", "dataset": "tau3-x3"}]}) self.assertEqual(r.status_code, 200, r.get_data(as_text=True)); self.assertEqual(r.json["open"], "/job/tau3-x3") @@ -400,6 +426,22 @@ def test_the_workspace_left_open_opens_again(self): self.root.rmdir() # roots gone: it opens as the open action does self.assertEqual(self.restart().roots, [str(self.root)]) + def test_a_launch_destination_does_not_replace_the_workspace_reopened(self): + with patch.object(workspace, "_now", return_value="2000-01-01T00:00:00+00:00"): + ws = workspace.create(self.home, [str(self.root)], label="existing") + web.shared.open_workspace(ws) + filed = [] + run = SimpleNamespace(jobs=str(self.tmp / "runs" / "launch" / "jobs"), file_under=filed.append) + web.shared.adopt_runs([run], "destination") + destination = workspace.load(self.home, "destination") + self.assertEqual((destination.opened, destination.closed), ("", True)) + self.assertEqual((destination.roots, filed), ([run.jobs], ["destination"])) + self.assertIs(web.shared.STATE["workspace"], ws) + self.assertEqual(self.restart().name, ws.name) + web.shared.open_workspace(destination) + self.assertTrue(workspace.load(self.home, destination.name).opened) + self.assertEqual(self.restart().name, destination.name) + def test_a_second_server_on_the_runs_folder_stops_with_one_line(self): refused = execution.Followed("another Nullius follows the runs in /r: stop it before starting this one") with patch.object(execution, "restore", side_effect=refused), self.assertRaises(SystemExit) as end: diff --git a/app/web/api.py b/app/web/api.py index c03f027a7..88451bf81 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -474,9 +474,10 @@ def api_run_check(): @app.route(PREFIX + "/runs", methods=["POST"]) @api("run") def api_run_start(): - """Start a recipe: ``{"recipe": {...} | "", "where"?, "name"?, "confirm"?}``. A new run each + """Start a recipe: ``{"recipe": {...} | "", "where"?, "name"?, "confirm"?, "workspace"?}``. A new run each time, named by the recipe's name and the second unless ``name`` says; refused with what Review would show - when the recipe does not compile, a machine lacks a prerequisite, or its question is not answered.""" + when the recipe does not compile, a machine lacks a prerequisite, or its question is not answered. + ``workspace``: the one its jobs go into, made when there is none, in place of the open one.""" body = _body() post, doc = _checked(_recipe_of(body)) if doc["errors"]: @@ -485,6 +486,8 @@ def api_run_start(): return _error(409, "A machine lacks what this recipe needs: see machines.", **doc) if doc["confirm"] and body.get("confirm") is not True: return _error(409, doc["confirm"] + " Send \"confirm\": true to start it.", **doc) + if "workspace" in body: + post["workspace"] = body["workspace"] started = execute.start(post) out = started[0].get_json() if isinstance(started, tuple) else started.get_json() status = started[1] if isinstance(started, tuple) else 200 diff --git a/app/web/execute.py b/app/web/execute.py index 0ac77cb01..39e0e94bc 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -6,7 +6,7 @@ import re import time from flask import abort, jsonify, request, url_for -from nullius import execution, hosts, prerequisites, prices, providers, settings +from nullius import execution, hosts, prerequisites, prices, providers, settings, workspace from nullius.harbor import source as harbor_source from nullius.standard.backends import boat from nullius.standard.pages import recipe as standard_recipe @@ -18,7 +18,9 @@ @app.route("/run", methods=["POST"]) def run_start(): """Start a plan. The builder posts the recipe; - the target is this machine or one of the Settings' hosts. Same guards + the target is this machine or one of the Settings' hosts. ``workspace``: + the workspace its jobs go into, made under that name when there is none, + in place of the open one (the API sends it; the builder does not). Same guards as every mutation: form token, same origin, and a loopback client - running is writing to a machine.""" shared._require_csrf() @@ -31,8 +33,11 @@ def start(body: dict): """``run_start`` past its guards: what the page posts, and what the API posts once its token is checked (``web/api.py``).""" recipe = body.get("recipe") if isinstance(body.get("recipe"), dict) else {} + into = body.get("workspace") or "" + if into and (not isinstance(into, str) or workspace.slug(into) != into): + return jsonify(ok=False, error="A workspace's name is lowercase letters, digits and dashes."), 400 if recipe.get("harness") == standard_recipe.HARNESS: - return _start_standard(recipe) + return _start_standard(recipe, into) where = str(body.get("where") or "local") host = None if where != "local": @@ -69,7 +74,7 @@ def start(body: dict): parts=[{"id": re.sub(r"[^A-Za-z0-9_.-]", "_", str(p.get("id") or "")), "label": str(p.get("label") or ""), "script": str(p.get("script") or "")} for p in (body.get("parts") or []) if isinstance(p, dict)], recipe=recipe) - return _start(plan) + return _start(plan, into) def credentials_for(provider, endpoint=None) -> dict: @@ -125,10 +130,10 @@ def standard_plans(recipe: dict, out: dict, known) -> tuple: return plans, "" -def _start_standard(recipe: dict): +def _start_standard(recipe: dict, into: str = ""): """The standard: compiled here from its definitions; on this machine, a host, or split over several - one run per machine, every - one checked before any starts.""" + one checked before any starts. ``into``: the workspace its jobs go into (``begin``).""" if len(json.dumps(recipe)) > 200_000: return jsonify(ok=False, error="the recipe is too large to keep with the run"), 400 out = standard_recipe.compile(recipe, docker_unusable=docker_problem, boat_unusable=boat.unusable, @@ -143,8 +148,8 @@ def _start_standard(recipe: dict): if problem: return jsonify(ok=False, error=problem), 400 if len(plans) == 1: - return _start(plans[0]) - started, problem, status = begin(plans) + return _start(plans[0], into) + started, problem, status = begin(plans, into) if problem: return jsonify(ok=False, error=problem), status return jsonify(ok=True, open=url_for("index", view="launch"), runs=[ex.summary() for ex in started], @@ -195,9 +200,15 @@ def docker_problem(): return prerequisites.docker_here() -def begin(plans: list) -> tuple: +def begin(plans: list, into: str = "") -> tuple: """Start ``plans``, each checked before any starts: (the runs, "", 200), or - ([], why not, its status) and nothing started.""" + ([], why not, its status) and nothing started. ``into``: the workspace + their jobs go into, the open one when empty (``shared.adopt_runs``).""" + if into: + dest = os.path.join(shared.WS_HOME, into) + home = os.path.realpath(shared.WS_HOME) + if os.path.islink(dest) or os.path.commonpath([home, os.path.realpath(dest)]) != home: + return [], "A launch workspace must be inside the workspaces folder and cannot be a symbolic link.", 400 for plan in plans: problem = plan.check() if problem: @@ -209,12 +220,12 @@ def begin(plans: list) -> tuple: started = [execution.start(plan) for plan in plans] # The job lands (or is mirrored) under runs//jobs: the workspace # reads it from now on. - shared.adopt_runs(started) + shared.adopt_runs(started, into) return started, "", 200 -def _start(plan: execution.Plan): - started, problem, status = begin([plan]) +def _start(plan: execution.Plan, into: str = ""): + started, problem, status = begin([plan], into) if problem: return jsonify(ok=False, error=problem), status summary, jobs = started[0].summary(), plan.jobs diff --git a/app/web/shared.py b/app/web/shared.py index b2c5359c5..f9c02f4ea 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -343,10 +343,13 @@ def adopt_roots(roots, label="", new=False, into=""): return ws -def adopt_runs(runs): +def adopt_runs(runs, into=""): """Runs just started: their jobs into a workspace as ``adopt_roots`` puts - them, each record naming it for a restart to put them back.""" - ws = adopt_roots([ex.jobs for ex in runs]) + them - ``into``, made under that name when there is none, the open one + left as it is - each record naming it for a restart to put them back.""" + if into and workspace.load(WS_HOME, into) is None: + workspace.create(WS_HOME, [], into, opened=False) + ws = adopt_roots([ex.jobs for ex in runs], into=into) for ex in runs: ex.file_under(ws.name) diff --git a/docs/api.md b/docs/api.md index dcb936304..d305601fe 100644 --- a/docs/api.md +++ b/docs/api.md @@ -79,7 +79,7 @@ job["adjusted_solve_rate"], job["counts"] | `judge(job, trial)`, `judge_job(job, confirm=False)` | Ask a judge: [below](#asking-a-judge) | | `recipes()`, `recipe(id_or_name)`, `save_recipe(recipe)` | The builder's saved recipes | | `check(recipe, where=None)` | What Review shows: `ready`, `errors`, `confirm`, `machines` | -| `start(recipe, where=None, name=None, confirm=False)` | `runs`: one per machine | +| `start(recipe, where=None, name=None, confirm=False, workspace=None)` | `runs`: one per machine | | `runs()`, `run(id, since=0)`, `follow(id)`, `wait(id)` | State, stages, log | | `stop(id)`, `continue_(id)` | Stop; answer a paused run | @@ -102,6 +102,7 @@ A recipe's `task_sets` runs a task set in place of a dataset's tasks: `{"test": - Build a recipe in the [run builder](builder.md), save it, start it by name. - Each start is a new run: the recipe's name and the second, or `name`. - `where` replaces the recipe's machines: `local`, or a host of Settings. +- `workspace` (lowercase letters, digits and dashes) puts its jobs in that workspace, made when there is none; the open one stays open. The builder's Run has none. - Standard recipes only. A Harbor recipe starts from the builder. ## Asking a judge @@ -128,12 +129,12 @@ nullius remote leaderboard nullius remote judgements JOB [--lane llm] nullius remote judge JOB [TRIAL] [--lane llm] [--yes] nullius remote check RECIPE -nullius remote run RECIPE [--where W] [--name N] [--yes] [--follow] +nullius remote run RECIPE [--where W] [--name N] [--workspace NAME] [--yes] [--follow] nullius remote status RUN nullius remote stop RUN ``` -`RECIPE`: a recipe file, or a saved recipe's name or id. `--workspace NAME` on `jobs`, `job`, `compare`, `leaderboard`, `judgements` and `judge` names another workspace. One JSON document on stdout. Exit 3 not found, 4 refused or unreachable; `run --follow` exits 4 unless the run ends `done`. +`RECIPE`: a recipe file, or a saved recipe's name or id. `--workspace NAME` on `jobs`, `job`, `compare`, `leaderboard`, `judgements` and `judge` names another workspace; on `run`, the one its jobs go into. One JSON document on stdout. Exit 3 not found, 4 refused or unreachable; `run --follow` exits 4 unless the run ends `done`. ## Assistants From 5bebd6358fcf856356065f85567ae6594e141429 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 11:23:18 +0100 Subject: [PATCH 2/9] fix(execution): serialize named workspace adoption --- app/nullius/workspace.py | 10 +++--- app/ui_tests/test_run_routes.py | 54 +++++++++++++++++++++++++++++++++ app/web/shared.py | 16 +++++++--- docs/api.md | 1 + 4 files changed, 73 insertions(+), 8 deletions(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 09f589b44..51dc52cee 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -177,10 +177,12 @@ def _free(name: str, taken) -> str: return next(c for c in (f"{name[:NAME_MAX - len(str(i)) - 1].rstrip('-')}-{i}" for i in range(2, 1000)) if c not in taken) -def create(home_dir: str, roots, label: str = "", *, opened: bool = True) -> Workspace: - taken = {ws.name for ws in list_all(home_dir)} - name = slug(label) - name = _free(name, taken) if name else random_name(taken) +def create(home_dir: str, roots, label: str = "", *, opened: bool = True, exact: bool = False) -> Workspace: + name = label + if not exact: + taken = {ws.name for ws in list_all(home_dir)} + name = slug(label) + name = _free(name, taken) if name else random_name(taken) now = _now() ws = Workspace(name=name, label=label.strip() or name, roots=list(roots), created=now, opened=now if opened else "", closed=not opened, dir=os.path.join(home_dir, name)) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 38a120fdf..29fe80e3e 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -11,6 +11,7 @@ import shutil import subprocess import tempfile +import threading import time import unittest from contextlib import ExitStack @@ -442,6 +443,59 @@ def test_a_launch_destination_does_not_replace_the_workspace_reopened(self): self.assertTrue(workspace.load(self.home, destination.name).opened) self.assertEqual(self.restart().name, destination.name) + def test_concurrent_starts_keep_both_jobs_without_using_a_suffixed_link(self): + for delayed in ("save", "create"): + with self.subTest(delayed=delayed): + home = self.tmp / delayed + home.mkdir() + outside = self.tmp / (delayed + "-outside") + outside.mkdir() + (home / "trials-2").symlink_to(outside, target_is_directory=True) + waiting, second_done = threading.Event(), threading.Event() + outcomes, errors = [], [] + real = getattr(workspace, delayed) + + def delay(*args, **kwargs): + if threading.current_thread().name == "first" and not waiting.is_set(): + waiting.set() + second_done.wait(1) + return real(*args, **kwargs) + + def start(name): + try: + outcomes.append(web.execute.begin([execution.Plan(name=name, script="true")], "trials")) + except BaseException as error: + errors.append(error) + finally: + if name == "second": + second_done.set() + + with patch.object(web.shared, "WS_HOME", str(home)), patch.dict(execution.EXECUTIONS, clear=True), \ + patch.dict(os.environ, {"RUNS_DIR": str(self.tmp / (delayed + "-runs"))}), \ + patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None), patch.object(workspace, delayed, delay): + first = threading.Thread(target=start, args=("first",), name="first") + second = threading.Thread(target=start, args=("second",), name="second") + first.start() + try: + self.assertTrue(waiting.wait(5)) + second.start() + finally: + first.join(5) + if second.ident is not None: + second.join(5) + for ex in list(execution.EXECUTIONS.values()): + ex.thread.join(5) + self.assertFalse(first.is_alive() or second.is_alive()) + self.assertEqual(errors, []) + self.assertEqual([outcome[2] for outcome in outcomes], [200, 200]) + self.assertFalse((outside / "workspace.json").exists()) + runs = list(execution.EXECUTIONS.values()) + self.assertEqual(len(runs), 2) + self.assertEqual({ex.workspace for ex in runs}, {"trials"}) + self.assertEqual(set(workspace.load(str(home), "trials").roots), {ex.jobs for ex in runs}) + self.assertIsNone(web.shared.STATE["workspace"]) + def test_a_second_server_on_the_runs_folder_stops_with_one_line(self): refused = execution.Followed("another Nullius follows the runs in /r: stop it before starting this one") with patch.object(execution, "restore", side_effect=refused), self.assertRaises(SystemExit) as end: diff --git a/app/web/shared.py b/app/web/shared.py index f9c02f4ea..84ad3d5ae 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -16,7 +16,7 @@ from nullius import execution from nullius.catalogue import catalog from nullius import workspace -from nullius import settings, paths +from nullius import settings, paths, ondisk from nullius.redact import redact from .core import app @@ -347,9 +347,17 @@ def adopt_runs(runs, into=""): """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 - each record naming it for a restart to put them back.""" - if into and workspace.load(WS_HOME, into) is None: - workspace.create(WS_HOME, [], into, opened=False) - ws = adopt_roots([ex.jobs for ex in runs], into=into) + 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")): + ws = workspace.load(WS_HOME, into) or workspace.create(WS_HOME, [], into, opened=False, exact=True) + ws.roots = list(ws.roots) + [r for r in roots if r not in ws.roots] + workspace.save(ws) + if STATE["workspace"] and STATE["workspace"].name == into: + open_workspace(ws) + else: + ws = adopt_roots(roots) for ex in runs: ex.file_under(ws.name) diff --git a/docs/api.md b/docs/api.md index d305601fe..3bd8da6e7 100644 --- a/docs/api.md +++ b/docs/api.md @@ -103,6 +103,7 @@ A recipe's `task_sets` runs a task set in place of a dataset's tasks: `{"test": - Each start is a new run: the recipe's name and the second, or `name`. - `where` replaces the recipe's machines: `local`, or a host of Settings. - `workspace` (lowercase letters, digits and dashes) puts its jobs in that workspace, made when there is none; the open one stays open. The builder's Run has none. +- A named workspace uses the exact name; concurrent starts keep every job. - Standard recipes only. A Harbor recipe starts from the builder. ## Asking a judge From 906b15cf49a71e72dd84ab8df6d8c203ba681337 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 11:23:26 +0100 Subject: [PATCH 3/9] fix(execution): keep the open workspace's own object when a start names it A start that named the open workspace read a second copy of it from disk, added its jobs to that copy and made the copy the open one. A start that names no workspace adds to the first copy, and two such starts at once could each drop the other's job from the open workspace's roots. Under the lock, a named start now makes the workspace when it is missing and adds its jobs through adopt_roots, which uses the open workspace's own object, as before the lock. --- app/ui_tests/test_run_routes.py | 4 ++++ app/web/shared.py | 8 +++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 29fe80e3e..c22761d96 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -438,6 +438,10 @@ def test_a_launch_destination_does_not_replace_the_workspace_reopened(self): self.assertEqual((destination.opened, destination.closed), ("", True)) self.assertEqual((destination.roots, filed), ([run.jobs], ["destination"])) self.assertIs(web.shared.STATE["workspace"], ws) + mine = SimpleNamespace(jobs=str(self.tmp / "runs" / "mine" / "jobs"), file_under=filed.append) + web.shared.adopt_runs([mine], ws.name) # the open one named: the object every start adds to + self.assertIs(web.shared.STATE["workspace"], ws) + self.assertEqual((ws.roots, filed[-1]), ([str(self.root), mine.jobs], ws.name)) self.assertEqual(self.restart().name, ws.name) web.shared.open_workspace(destination) self.assertTrue(workspace.load(self.home, destination.name).opened) diff --git a/app/web/shared.py b/app/web/shared.py index 84ad3d5ae..02f955b14 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -351,11 +351,9 @@ def adopt_runs(runs, into=""): if into: os.makedirs(WS_HOME, exist_ok=True) with ondisk.locked(os.path.join(WS_HOME, f".{into}.lock")): - ws = workspace.load(WS_HOME, into) or workspace.create(WS_HOME, [], into, opened=False, exact=True) - ws.roots = list(ws.roots) + [r for r in roots if r not in ws.roots] - workspace.save(ws) - if STATE["workspace"] and STATE["workspace"].name == into: - open_workspace(ws) + if workspace.load(WS_HOME, into) is None: + workspace.create(WS_HOME, [], into, opened=False, exact=True) + ws = adopt_roots(roots, into=into) else: ws = adopt_roots(roots) for ex in runs: From 1202d6a7ccbd846e24e1255a29ea822b28ada706 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 11:23:29 +0100 Subject: [PATCH 4/9] fix(execution): refuse linked workspace manifests --- app/ui_tests/test_run_routes.py | 22 ++++++++++++++++++++++ app/web/execute.py | 3 ++- docs/api.md | 1 + 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index c22761d96..0ded3643b 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -500,6 +500,28 @@ def start(name): self.assertEqual(set(workspace.load(str(home), "trials").roots), {ex.jobs for ex in runs}) self.assertIsNone(web.shared.STATE["workspace"]) + def test_a_linked_workspace_manifest_is_refused_before_it_is_read(self): + outside = workspace.create(str(self.tmp / "outside"), ["/r/kept"], "kept") + inside = workspace.create(self.home, [str(self.root)], "inside") + destination = Path(self.home) / "trials" + destination.mkdir() + manifest = destination / "workspace.json" + plan = SimpleNamespace(name="launch", check=lambda: "") + run = SimpleNamespace(jobs=str(self.tmp / "runs" / "launch" / "jobs"), file_under=lambda name: None) + for target in (Path(outside.dir) / "workspace.json", Path(inside.dir) / "workspace.json", self.tmp / "absent.json"): + with self.subTest(target=target.relative_to(self.tmp)): + manifest.symlink_to(target) + try: + with patch("builtins.open", wraps=open) as read, patch.dict(execution.EXECUTIONS, clear=True), \ + patch.object(execution, "start", return_value=run) as start: + runs, problem, status = web.execute.begin([plan], "trials") + self.assertEqual((status, read.call_count, start.call_count), (400, 0, 0)) + self.assertEqual(runs, []) + self.assertEqual(problem, "A launch workspace must be inside the workspaces folder and cannot be a symbolic link.") + self.assertTrue(manifest.is_symlink()) + finally: + manifest.unlink() + def test_a_second_server_on_the_runs_folder_stops_with_one_line(self): refused = execution.Followed("another Nullius follows the runs in /r: stop it before starting this one") with patch.object(execution, "restore", side_effect=refused), self.assertRaises(SystemExit) as end: diff --git a/app/web/execute.py b/app/web/execute.py index 39e0e94bc..a587b8e0f 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -206,8 +206,9 @@ def begin(plans: list, into: str = "") -> tuple: their jobs go into, the open one when empty (``shared.adopt_runs``).""" if into: dest = os.path.join(shared.WS_HOME, into) + manifest = os.path.join(dest, "workspace.json") home = os.path.realpath(shared.WS_HOME) - if os.path.islink(dest) or os.path.commonpath([home, os.path.realpath(dest)]) != home: + if any(os.path.islink(path) or os.path.commonpath([home, os.path.realpath(path)]) != home for path in (dest, manifest)): return [], "A launch workspace must be inside the workspaces folder and cannot be a symbolic link.", 400 for plan in plans: problem = plan.check() diff --git a/docs/api.md b/docs/api.md index 3bd8da6e7..cc71c7a04 100644 --- a/docs/api.md +++ b/docs/api.md @@ -96,6 +96,7 @@ A run starts as Review starts it. | The recipe has errors (400) | Fixed: `errors` names them | | A machine lacks a prerequisite (409) | Met: `machines` lists each | | The recipe asks a question (409), such as the whole dataset | `confirm=True` | +| The workspace folder or `workspace.json` is linked or outside the workspaces folder (400) | Use an unlinked workspace inside that folder | A recipe's `task_sets` runs a task set in place of a dataset's tasks: `{"test": "first-two"}`, a name the catalogue lists. It asks no question. From 5f16c395895f71c6b5b3f70d29b45e5c0003805f Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 11:23:29 +0100 Subject: [PATCH 5/9] fix(execution): reject workspace path conflicts before starting --- app/ui_tests/test_run_routes.py | 20 ++++++++++++++++++++ app/web/execute.py | 2 ++ docs/api.md | 1 + 3 files changed, 23 insertions(+) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 0ded3643b..5db1bdf45 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -522,6 +522,26 @@ def test_a_linked_workspace_manifest_is_refused_before_it_is_read(self): finally: manifest.unlink() + def test_workspace_path_conflicts_leave_no_execution_or_run_record(self): + home = Path(self.home) + home.mkdir() + (home / "occupied-file").write_text("keep") + (home / "occupied-manifest" / "workspace.json").mkdir(parents=True) + for name in ("occupied-file", "occupied-manifest"): + with self.subTest(name=name), patch.dict(execution.EXECUTIONS, clear=True), \ + patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None): + try: + runs, problem, status = web.execute.begin([execution.Plan(name=name, script="true")], name) + finally: + for ex in list(execution.EXECUTIONS.values()): + ex.thread.join(5) + self.assertEqual((runs, status), ([], 400), problem) + self.assertEqual(execution.EXECUTIONS, {}) + self.assertEqual(list((self.tmp / "runs").glob("*/run.json")), []) + self.assertEqual((home / "occupied-file").read_text(), "keep") + self.assertTrue((home / "occupied-manifest" / "workspace.json").is_dir()) + def test_a_second_server_on_the_runs_folder_stops_with_one_line(self): refused = execution.Followed("another Nullius follows the runs in /r: stop it before starting this one") with patch.object(execution, "restore", side_effect=refused), self.assertRaises(SystemExit) as end: diff --git a/app/web/execute.py b/app/web/execute.py index a587b8e0f..64f1bf9c9 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -210,6 +210,8 @@ def begin(plans: list, into: str = "") -> tuple: home = os.path.realpath(shared.WS_HOME) if any(os.path.islink(path) or os.path.commonpath([home, os.path.realpath(path)]) != home for path in (dest, manifest)): return [], "A launch workspace must be inside the workspaces folder and cannot be a symbolic link.", 400 + if (os.path.exists(dest) and not os.path.isdir(dest)) or (os.path.exists(manifest) and not os.path.isfile(manifest)): + return [], "The launch workspace conflicts with an existing file or folder.", 400 for plan in plans: problem = plan.check() if problem: diff --git a/docs/api.md b/docs/api.md index cc71c7a04..8f48857f4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -97,6 +97,7 @@ A run starts as Review starts it. | A machine lacks a prerequisite (409) | Met: `machines` lists each | | The recipe asks a question (409), such as the whole dataset | `confirm=True` | | The workspace folder or `workspace.json` is linked or outside the workspaces folder (400) | Use an unlinked workspace inside that folder | +| The workspace path is a file, or its `workspace.json` is a folder (400) | Remove the conflicting entry or choose another workspace | A recipe's `task_sets` runs a task set in place of a dataset's tasks: `{"test": "first-two"}`, a name the catalogue lists. It asks no question. From 7187a5da047fe8ba13eb2ceb43e9bd6afb3d2444 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 11:23:30 +0100 Subject: [PATCH 6/9] fix(execution): validate supplied workspace values before defaulting --- app/ui_tests/test_api.py | 12 ++++++++++++ app/ui_tests/test_run_routes.py | 25 +++++++++++++++++++++++++ app/web/execute.py | 5 +++-- docs/api.md | 1 + 4 files changed, 41 insertions(+), 2 deletions(-) diff --git a/app/ui_tests/test_api.py b/app/ui_tests/test_api.py index 01805bbe9..4cc91c33d 100644 --- a/app/ui_tests/test_api.py +++ b/app/ui_tests/test_api.py @@ -615,6 +615,18 @@ def test_a_standard_recipe_starts_as_the_page_starts_it(self): again = self.post("/runs", {"recipe": gsm8k(), "confirm": True, "name": "mine"}) # a name is a run, once self.assertEqual(again.status_code, 409, again.json) + def test_a_supplied_workspace_must_be_a_valid_name_of_any_json_type(self): + recipe = self.scripted("true") + self.stack.enter_context(patch.object(execution.Execution, "_main", lambda ex: None)) + self.addCleanup(self.wait) + for i, value in enumerate((False, 0, 0.0, [], {}, "", True, 1, ["trials"], {"name": "trials"}, "Bad", "a/b", "a" * 49)): + with self.subTest(value=value): + r = self.post("/runs", {"recipe": recipe, "name": f"invalid-{i}", "workspace": value}) + self.assertEqual((r.status_code, r.json.get("error")), + (400, "A workspace's name is lowercase letters, digits and dashes.")) + self.assertEqual((execution.EXECUTIONS, self.adopted), ({}, [])) + self.assertFalse((self.tmp / "runs").exists()) + def test_a_recipe_runs_a_task_set_kept_on_the_server(self): entry = task_sets.create(definitions.get("benchmark", "gsm8k"), "First two", dataset="test", units=["0001", "0002"]) recipe = gsm8k(task_sets={"test": entry["name"]}) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 5db1bdf45..968ee1495 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -542,6 +542,31 @@ def test_workspace_path_conflicts_leave_no_execution_or_run_record(self): self.assertEqual((home / "occupied-file").read_text(), "keep") self.assertTrue((home / "occupied-manifest" / "workspace.json").is_dir()) + def test_an_absent_or_null_workspace_keeps_the_default_destination(self): + for opened in (False, True): + with self.subTest(opened=opened), patch.dict(execution.EXECUTIONS, clear=True), \ + patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None): + web.shared.close_workspace() + ws = workspace.create(self.home, [str(self.root)], "existing") if opened else None + if ws: + web.shared.open_workspace(ws) + for i, extra in enumerate(({}, {"workspace": None})): + body = {"name": f"default-{opened}-{i}", "script": "true", **extra} + with web.app.test_request_context(): + response = web.execute.start(body) + try: + self.assertEqual(response.status_code, 200) + ws = ws or web.shared.STATE["workspace"] + self.assertIs(web.shared.STATE["workspace"], ws) + run = execution.EXECUTIONS[response.json["id"]] + self.assertEqual(run.workspace, ws.name) + self.assertIn(run.jobs, workspace.load(self.home, ws.name).roots) + finally: + response.close() + for ex in list(execution.EXECUTIONS.values()): + ex.thread.join(5) + def test_a_second_server_on_the_runs_folder_stops_with_one_line(self): refused = execution.Followed("another Nullius follows the runs in /r: stop it before starting this one") with patch.object(execution, "restore", side_effect=refused), self.assertRaises(SystemExit) as end: diff --git a/app/web/execute.py b/app/web/execute.py index 64f1bf9c9..5ae09fcf2 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -33,9 +33,10 @@ def start(body: dict): """``run_start`` past its guards: what the page posts, and what the API posts once its token is checked (``web/api.py``).""" recipe = body.get("recipe") if isinstance(body.get("recipe"), dict) else {} - into = body.get("workspace") or "" - if into and (not isinstance(into, str) or workspace.slug(into) != into): + into = body.get("workspace") + if into is not None and (not isinstance(into, str) or not into or workspace.slug(into) != into): return jsonify(ok=False, error="A workspace's name is lowercase letters, digits and dashes."), 400 + into = into or "" if recipe.get("harness") == standard_recipe.HARNESS: return _start_standard(recipe, into) where = str(body.get("where") or "local") diff --git a/docs/api.md b/docs/api.md index 8f48857f4..ed6c646d6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -106,6 +106,7 @@ A recipe's `task_sets` runs a task set in place of a dataset's tasks: `{"test": - `where` replaces the recipe's machines: `local`, or a host of Settings. - `workspace` (lowercase letters, digits and dashes) puts its jobs in that workspace, made when there is none; the open one stays open. The builder's Run has none. - A named workspace uses the exact name; concurrent starts keep every job. +- Omit `workspace` or send null to keep the usual destination; an empty name or another JSON type is refused (400). - Standard recipes only. A Harbor recipe starts from the builder. ## Asking a judge From 3d915bfbcb65d4bd09143cd438a3ccc40b4ce5ae Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 11:23:42 +0100 Subject: [PATCH 7/9] docs(docs): keep the API page's workspace field to its one line The line on `workspace` already gives the names a start takes. The four lines added with the fixes covered a link or a file in the workspace's place, null, and starts at the same moment: the server's answer names each refusal, and no reader acts on them before a start. --- docs/api.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/api.md b/docs/api.md index ed6c646d6..d305601fe 100644 --- a/docs/api.md +++ b/docs/api.md @@ -96,8 +96,6 @@ A run starts as Review starts it. | The recipe has errors (400) | Fixed: `errors` names them | | A machine lacks a prerequisite (409) | Met: `machines` lists each | | The recipe asks a question (409), such as the whole dataset | `confirm=True` | -| The workspace folder or `workspace.json` is linked or outside the workspaces folder (400) | Use an unlinked workspace inside that folder | -| The workspace path is a file, or its `workspace.json` is a folder (400) | Remove the conflicting entry or choose another workspace | A recipe's `task_sets` runs a task set in place of a dataset's tasks: `{"test": "first-two"}`, a name the catalogue lists. It asks no question. @@ -105,8 +103,6 @@ A recipe's `task_sets` runs a task set in place of a dataset's tasks: `{"test": - Each start is a new run: the recipe's name and the second, or `name`. - `where` replaces the recipe's machines: `local`, or a host of Settings. - `workspace` (lowercase letters, digits and dashes) puts its jobs in that workspace, made when there is none; the open one stays open. The builder's Run has none. -- A named workspace uses the exact name; concurrent starts keep every job. -- Omit `workspace` or send null to keep the usual destination; an empty name or another JSON type is refused (400). - Standard recipes only. A Harbor recipe starts from the builder. ## Asking a judge From df7b905926ade6051485445acaee36ff68bb00fe Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 12:08:18 +0100 Subject: [PATCH 8/9] fix(execution): refuse conflicting workspace lock paths --- app/ui_tests/test_run_routes.py | 48 +++++++++++++++++++++++++++++++++ app/web/execute.py | 4 ++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 968ee1495..18ed4a691 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -542,6 +542,54 @@ def test_workspace_path_conflicts_leave_no_execution_or_run_record(self): self.assertEqual((home / "occupied-file").read_text(), "keep") self.assertTrue((home / "occupied-manifest" / "workspace.json").is_dir()) + def test_workspace_lock_conflicts_leave_no_execution_or_run_record(self): + home = Path(self.home) + home.mkdir() + lock = home / ".trials.lock" + outside = self.tmp / "outside-lock" + for kind in ("missing-target", "held-lock", "directory"): + with self.subTest(kind=kind), patch.dict(execution.EXECUTIONS, clear=True), \ + patch.object(execution.Plan, "check", return_value=""), \ + patch.object(execution.Execution, "_main", lambda ex: None): + held = None + if kind == "directory": + lock.mkdir() + elif kind == "held-lock": + root = str(self.tmp / "runs") + execution._follow(root) + held = execution._FOLLOWED[os.path.realpath(root)] + lock.symlink_to(Path(root) / execution.LOCK) + else: + lock.symlink_to(outside) + outcomes, errors = [], [] + + def start(): + try: + outcomes.append(web.execute.begin([execution.Plan(name=kind, script="true")], "trials")) + except BaseException as error: + errors.append(error) + + thread = threading.Thread(target=start) + thread.start() + try: + thread.join(2) + blocked = thread.is_alive() + finally: + if held is not None: + execution._FOLLOWED.pop(os.path.realpath(root)).close() + thread.join(5) + for ex in list(execution.EXECUTIONS.values()): + ex.thread.join(5) + lock.rmdir() if kind == "directory" else lock.unlink() + self.assertFalse(thread.is_alive()) + self.assertFalse(blocked, "The start waited for the server's own lock.") + self.assertEqual(errors, []) + self.assertEqual(outcomes, [([], "The launch workspace conflicts with an existing file or folder.", 400)]) + self.assertEqual(execution.EXECUTIONS, {}) + self.assertEqual(list((self.tmp / "runs").glob("*/run.json")), []) + self.assertFalse((home / "trials").exists()) + self.assertFalse(outside.exists()) + def test_an_absent_or_null_workspace_keeps_the_default_destination(self): for opened in (False, True): with self.subTest(opened=opened), patch.dict(execution.EXECUTIONS, clear=True), \ diff --git a/app/web/execute.py b/app/web/execute.py index 5ae09fcf2..c57cc4fc1 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -208,10 +208,12 @@ def begin(plans: list, into: str = "") -> tuple: if into: dest = os.path.join(shared.WS_HOME, into) manifest = os.path.join(dest, "workspace.json") + lock = os.path.join(shared.WS_HOME, f".{into}.lock") home = os.path.realpath(shared.WS_HOME) if any(os.path.islink(path) or os.path.commonpath([home, os.path.realpath(path)]) != home for path in (dest, manifest)): return [], "A launch workspace must be inside the workspaces folder and cannot be a symbolic link.", 400 - if (os.path.exists(dest) and not os.path.isdir(dest)) or (os.path.exists(manifest) and not os.path.isfile(manifest)): + if ((os.path.exists(dest) and not os.path.isdir(dest)) or (os.path.exists(manifest) and not os.path.isfile(manifest)) + or os.path.islink(lock) or (os.path.exists(lock) and not os.path.isfile(lock))): return [], "The launch workspace conflicts with an existing file or folder.", 400 for plan in plans: problem = plan.check() From a9a55d58fd1d72d0e173a9e411077e44d638c99a Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 30 Nov 2026 12:08:51 +0100 Subject: [PATCH 9/9] test(execution): check the lock path refusals in the nearby conflict case The repository's test rules ask to extend a nearby case first. The path conflict test already asserts the refusal, no execution and no run record: a folder and a link in the lock's place are two more names in it, and the link's target outside the workspaces folder must not be created. A link to a lock the server holds is refused by the same link check. --- app/ui_tests/test_run_routes.py | 53 +++------------------------------ 1 file changed, 4 insertions(+), 49 deletions(-) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 18ed4a691..4906d0712 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -527,7 +527,9 @@ def test_workspace_path_conflicts_leave_no_execution_or_run_record(self): home.mkdir() (home / "occupied-file").write_text("keep") (home / "occupied-manifest" / "workspace.json").mkdir(parents=True) - for name in ("occupied-file", "occupied-manifest"): + (home / ".lock-folder.lock").mkdir() + (home / ".lock-link.lock").symlink_to(self.tmp / "outside-lock") + for name in ("occupied-file", "occupied-manifest", "lock-folder", "lock-link"): with self.subTest(name=name), patch.dict(execution.EXECUTIONS, clear=True), \ patch.object(execution.Plan, "check", return_value=""), \ patch.object(execution.Execution, "_main", lambda ex: None): @@ -541,54 +543,7 @@ def test_workspace_path_conflicts_leave_no_execution_or_run_record(self): self.assertEqual(list((self.tmp / "runs").glob("*/run.json")), []) self.assertEqual((home / "occupied-file").read_text(), "keep") self.assertTrue((home / "occupied-manifest" / "workspace.json").is_dir()) - - def test_workspace_lock_conflicts_leave_no_execution_or_run_record(self): - home = Path(self.home) - home.mkdir() - lock = home / ".trials.lock" - outside = self.tmp / "outside-lock" - for kind in ("missing-target", "held-lock", "directory"): - with self.subTest(kind=kind), patch.dict(execution.EXECUTIONS, clear=True), \ - patch.object(execution.Plan, "check", return_value=""), \ - patch.object(execution.Execution, "_main", lambda ex: None): - held = None - if kind == "directory": - lock.mkdir() - elif kind == "held-lock": - root = str(self.tmp / "runs") - execution._follow(root) - held = execution._FOLLOWED[os.path.realpath(root)] - lock.symlink_to(Path(root) / execution.LOCK) - else: - lock.symlink_to(outside) - outcomes, errors = [], [] - - def start(): - try: - outcomes.append(web.execute.begin([execution.Plan(name=kind, script="true")], "trials")) - except BaseException as error: - errors.append(error) - - thread = threading.Thread(target=start) - thread.start() - try: - thread.join(2) - blocked = thread.is_alive() - finally: - if held is not None: - execution._FOLLOWED.pop(os.path.realpath(root)).close() - thread.join(5) - for ex in list(execution.EXECUTIONS.values()): - ex.thread.join(5) - lock.rmdir() if kind == "directory" else lock.unlink() - self.assertFalse(thread.is_alive()) - self.assertFalse(blocked, "The start waited for the server's own lock.") - self.assertEqual(errors, []) - self.assertEqual(outcomes, [([], "The launch workspace conflicts with an existing file or folder.", 400)]) - self.assertEqual(execution.EXECUTIONS, {}) - self.assertEqual(list((self.tmp / "runs").glob("*/run.json")), []) - self.assertFalse((home / "trials").exists()) - self.assertFalse(outside.exists()) + self.assertFalse((self.tmp / "outside-lock").exists()) def test_an_absent_or_null_workspace_keeps_the_default_destination(self): for opened in (False, True):