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/execution.py b/app/nullius/execution.py
index c4d912673..8c972b314 100644
--- a/app/nullius/execution.py
+++ b/app/nullius/execution.py
@@ -650,10 +650,11 @@ def start(self) -> "Execution":
self.thread.start()
return self
- def file_under(self, workspace: str) -> None:
- """Record the workspace the run's job went into."""
+ def file_under(self, workspace: str, *, persist: bool = True) -> None:
+ """Record the workspace; before launch, defer persistence to start()."""
self.workspace = workspace
- self._save()
+ if persist:
+ self._save()
def resume(self) -> "Execution":
"""Pick a recorded run up where it was: the part that was running is
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..c6e2c1f5b 100644
--- a/app/nullius/workspace.py
+++ b/app/nullius/workspace.py
@@ -125,19 +125,40 @@ def save(ws: Workspace) -> None:
ondisk.write_whole(os.path.join(ws.dir, "workspace.json"), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1))
-def load(home_dir: str, name: str) -> Workspace | None:
+def load(home_dir: str, name: str, *, strict: bool = False) -> Workspace | None:
+ """Read a workspace. Strict launch reads refuse a damaged existing destination."""
if not name or not _NAME.fullmatch(name):
return None
try:
with open(_path(home_dir, name), encoding="utf-8") as fh:
data = json.load(fh)
- except (OSError, json.JSONDecodeError):
+ except FileNotFoundError:
+ if strict and os.path.lexists(os.path.join(home_dir, name)):
+ raise ValueError("The launch workspace has no manifest. Repair it or choose another workspace.")
return None
- if not isinstance(data, dict) or not data.get("name"):
+ except (OSError, ValueError) as error:
+ if strict:
+ raise ValueError("The launch workspace cannot be read. Repair it or choose another workspace.") from error
return None
known = {f.name for f in fields(Workspace)} - {"dir"}
- return Workspace(dir=os.path.join(home_dir, name),
- **{k: v for k, v in data.items() if k in known})
+ try:
+ if not isinstance(data, dict) or not data.get("name"):
+ raise ValueError("missing workspace name")
+ ws = Workspace(dir=os.path.join(home_dir, name),
+ **{k: v for k, v in data.items() if k in known})
+ if strict and (ws.name != name
+ or any(not isinstance(getattr(ws, k), str) for k in ("name", "label", "created", "opened"))
+ or not isinstance(ws.closed, bool)
+ or any(not isinstance(roots, list) or any(not isinstance(r, str) for r in roots)
+ for roots in (ws.roots, ws.job_roots))):
+ raise ValueError("invalid workspace fields")
+ return ws
+ except (TypeError, ValueError) as error:
+ if strict:
+ raise ValueError("The launch workspace has an invalid manifest. Repair it or choose another workspace.") from error
+ if not isinstance(data, dict) or not data.get("name"):
+ return None
+ raise
def list_all(home_dir: str) -> list:
@@ -177,13 +198,15 @@ 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:
- 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, 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..41787860a 100644
--- a/app/ui_tests/test_agents.py
+++ b/app/ui_tests/test_agents.py
@@ -43,12 +43,14 @@ def setUp(self):
"OPENROUTER_API_KEY": "", "MODEL_API_URL": ""}))
self.stack.enter_context(patch.object(definitions, "load", fixture_load))
self.stack.enter_context(patch.object(definitions, "get", fixture_get))
+ self.stack.enter_context(patch.dict(execution.EXECUTIONS, clear=True))
self.started = []
- 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))
+ def start(ex):
+ self.started.append(ex.plan)
+ ex.state = "done"
+ return ex
+ self.stack.enter_context(patch.object(execution.Execution, "start", start))
+ self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="", **kw: None))
self.client = web.app.test_client()
def test_capability_source_retains_pin_and_install_details(self):
@@ -374,12 +376,14 @@ def setUp(self):
"OPENROUTER_API_KEY": "", "MODEL_API_URL": ""}))
self.stack.enter_context(patch.object(definitions, "load", fixture_load))
self.stack.enter_context(patch.object(web.execute, "docker_problem", lambda: None)) # this machine's docker, said usable
+ self.stack.enter_context(patch.dict(execution.EXECUTIONS, clear=True))
self.started = []
- 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))
+ def start(ex):
+ self.started.append(ex.plan)
+ ex.state = "done"
+ return ex
+ self.stack.enter_context(patch.object(execution.Execution, "start", start))
+ self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="", **kw: 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))
@@ -464,12 +468,14 @@ def setUp(self):
self.stack.enter_context(patch.dict(os.environ, {"HOSTS": "me@bench", "RUNS_DIR": str(self.tmp / "runs"), "OPENAI_API_KEY": "sk-test-0123456789",
"OPENROUTER_API_KEY": "", "MODEL_API_URL": ""}))
self.stack.enter_context(patch.object(web.execute, "docker_problem", lambda: None))
+ self.stack.enter_context(patch.dict(execution.EXECUTIONS, clear=True))
self.started = []
- 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))
+ def start(ex):
+ self.started.append(ex.plan)
+ ex.state = "done"
+ return ex
+ self.stack.enter_context(patch.object(execution.Execution, "start", start))
+ self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="", **kw: 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..4b457cb2d 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="", **kw: 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."""
@@ -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"]})
@@ -728,7 +740,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="", **kw: 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 +763,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..3a99f6f7a 100644
--- a/app/ui_tests/test_harbor_routes.py
+++ b/app/ui_tests/test_harbor_routes.py
@@ -12,7 +12,6 @@
import unittest
from contextlib import ExitStack
from pathlib import Path
-from types import SimpleNamespace
from unittest.mock import patch
from urllib import error
@@ -36,11 +35,12 @@ def setUp(self):
self.stack.enter_context(patch.dict(builder_web._HARBOR_RELEASES, clear=True))
self.stack.enter_context(patch.dict(builder_web._HARBOR_REFS, clear=True))
self.started = []
- 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))
+ def start(ex):
+ self.started.append(ex.plan)
+ ex.state = "done"
+ return ex
+ self.stack.enter_context(patch.object(execution.Execution, "start", start))
+ self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="", **kw: 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..716a9e0d1 100644
--- a/app/ui_tests/test_prerequisites_route.py
+++ b/app/ui_tests/test_prerequisites_route.py
@@ -27,9 +27,12 @@ def setUp(self):
self.stack.enter_context(patch.dict(web.app.config, TESTING=True))
self.stack.enter_context(patch.dict(execution.EXECUTIONS, clear=True))
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))
+ def start(ex):
+ self.started.append(ex.plan)
+ ex.state = "done"
+ return ex
+ self.stack.enter_context(patch.object(execution.Execution, "start", start))
+ self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="", **kw: 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..658f9e6e5 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
@@ -79,7 +80,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="", **kw: 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 +174,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 +427,218 @@ 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_workspace_failure_starts_no_worker_and_writes_no_run_record(self):
+ for failing in ("lock", "save"):
+ with self.subTest(failing=failing), patch.dict(execution.EXECUTIONS, clear=True), \
+ patch.object(execution.Plan, "check", return_value=""), \
+ patch.object(execution.Execution, "start") as start:
+ target = web.shared.ondisk if failing == "lock" else workspace
+ method = "locked" if failing == "lock" else "save"
+ with patch.object(target, method, side_effect=OSError("disk failure")):
+ runs, problem, status = web.execute.begin([
+ execution.Plan(name="first", script="true"), execution.Plan(name="second", script="true")], "trials")
+ self.assertEqual((runs, status), ([], 503), problem)
+ start.assert_not_called()
+ self.assertEqual(execution.EXECUTIONS, {})
+ self.assertEqual(list((self.tmp / "runs").glob("*/run.json")), [])
+
+ 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)
+ before = (Path(ws.dir) / "workspace.json").read_bytes()
+ with patch.dict(execution.EXECUTIONS, clear=True), \
+ patch.object(execution.Plan, "check", return_value=""), \
+ patch.object(execution.Execution, "start") as start, \
+ patch.object(workspace, "save", side_effect=OSError("disk failure")):
+ runs, problem, status = web.execute.begin([execution.Plan(name="launch", script="true")], "trials")
+ self.assertEqual((runs, status), ([], 503), problem)
+ start.assert_not_called()
+ self.assertEqual(ws.roots, [str(self.root)])
+ self.assertEqual((Path(ws.dir) / "workspace.json").read_bytes(), before)
+
+ def test_a_damaged_destination_is_preserved_and_starts_nothing(self):
+ dest = Path(self.home) / "trials"
+ dest.mkdir(parents=True)
+ manifest = dest / "workspace.json"
+ valid = dict(name="trials", label="Trials", roots=["/kept"], created="", opened="")
+ for contents in (None, "{broken", "[]", '{"name":"trials"}',
+ json.dumps(dict(valid, name="other")), json.dumps(dict(valid, roots="/kept")),
+ json.dumps(dict(valid, closed="false")), json.dumps(dict(valid, job_roots=[3]))):
+ with self.subTest(contents=contents), patch.dict(execution.EXECUTIONS, clear=True), \
+ patch.object(execution.Plan, "check", return_value=""), \
+ patch.object(execution.Execution, "start") as start:
+ if contents is not None:
+ manifest.write_text(contents)
+ runs, problem, status = web.execute.begin([execution.Plan(name="launch", script="true")], "trials")
+ self.assertEqual((runs, status), ([], 400), problem)
+ start.assert_not_called()
+ self.assertEqual(execution.EXECUTIONS, {})
+ self.assertEqual(list((self.tmp / "runs").glob("*/run.json")), [])
+ if contents is None:
+ self.assertFalse(manifest.exists())
+ else:
+ self.assertEqual(manifest.read_text(), contents)
+
+ def test_workspace_is_saved_and_recorded_before_worker_starts(self):
+ seen = []
+
+ def worker(ex):
+ record = json.loads((Path(ex.dir) / "run.json").read_text())
+ ws = workspace.load(self.home, "trials")
+ seen.append((record["workspace"], ex.jobs in ws.roots))
+
+ with patch.dict(execution.EXECUTIONS, clear=True), \
+ patch.object(execution.Plan, "check", return_value=""), \
+ patch.object(execution.Execution, "_main", worker):
+ runs, problem, status = web.execute.begin([execution.Plan(name="launch", script="true")], "trials")
+ for ex in runs:
+ ex.thread.join(5)
+ self.assertEqual(status, 200, problem)
+ self.assertEqual(seen, [("trials", True)])
+
+ 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)
+ 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)
+ 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_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_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)
+ (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):
+ 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())
+ self.assertFalse((self.tmp / "outside-lock").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), \
+ 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/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..a74d583e2 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,12 @@ 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")
+ 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)
+ return _start_standard(recipe, into)
where = str(body.get("where") or "local")
host = None
if where != "local":
@@ -69,7 +75,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 +131,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 +149,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 +201,20 @@ 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)
+ 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))
+ 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()
if problem:
@@ -206,15 +223,23 @@ def begin(plans: list) -> tuple:
return [], f"{plan.name} is running already", 409
if os.path.exists(os.path.join(execution.runs_root(), plan.name)):
return [], execution.name_taken(plan.name), 409
- 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)
- return started, "", 200
-
-
-def _start(plan: execution.Plan):
- started, problem, status = begin([plan])
+ prepared = [execution.Execution(plan) for plan in plans]
+ # Save the destination before any worker can run. Its name goes into
+ # the first run record, rather than a second write after launch.
+ try:
+ shared.adopt_runs(prepared, into, persist=False)
+ except ValueError as error:
+ return [], str(error), 400
+ except OSError:
+ return [], "The launch workspace could not be saved. Check its permissions and free space, then retry.", 503
+ for ex in prepared:
+ execution.EXECUTIONS[ex.id] = ex
+ ex.start()
+ return prepared, "", 200
+
+
+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..e4eac2ef8 100644
--- a/app/web/shared.py
+++ b/app/web/shared.py
@@ -4,6 +4,7 @@
import glob
import hashlib
import ipaddress
+from dataclasses import replace
from itertools import islice
import secrets
import os
@@ -16,7 +17,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
@@ -331,8 +332,9 @@ def adopt_roots(roots, label="", new=False, into=""):
if into and not (ws and ws.name == into):
ws = workspace.load(WS_HOME, into)
if ws and not new:
- ws.roots = list(ws.roots) + [r for r in roots if r not in ws.roots]
- workspace.save(ws)
+ added = list(ws.roots) + [r for r in roots if r not in ws.roots]
+ workspace.save(replace(ws, roots=added))
+ ws.roots = added
if STATE["workspace"] is ws:
open_workspace(ws)
return ws
@@ -343,12 +345,25 @@ def adopt_roots(roots, label="", new=False, into=""):
return ws
-def adopt_runs(runs):
+def adopt_runs(runs, into="", *, persist=True):
"""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. With ``persist=False``, the runs have not started: their
+ first record will name the workspace, without writing a resumable run yet."""
+ 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)
+ else:
+ ws = adopt_roots(roots)
for ex in runs:
- ex.file_under(ws.name)
+ if persist:
+ ex.file_under(ws.name)
+ else:
+ ex.file_under(ws.name, persist=False)
def _load_jobs():
diff --git a/docs/api.md b/docs/api.md
index dcb936304..5e332edac 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` names the jobs' workspace, created if missing. The open workspace stays open.
- Standard recipes only. A Harbor recipe starts from the builder.
## Asking a judge
@@ -128,7 +129,7 @@ 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
```