diff --git a/app/nullius/client.py b/app/nullius/client.py
index 17c4e795..d9597e01 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 9f1a3674..e5fa484a 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 aec94bf5..51dc52ce 100644
--- a/app/nullius/workspace.py
+++ b/app/nullius/workspace.py
@@ -177,13 +177,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 c3a1e5aa..232a5987 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 ad853395..a7ca9422 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 08b4aff6..2958b1c2 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 a32fa4d8..4cc91c33 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."""
@@ -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="": 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 f8fb04d6..5cd11c6c 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 22f724a0..1a64b8cb 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 a456c9b4..4906d071 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="": 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,149 @@ 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)
+ 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 c03f027a..88451bf8 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 0ac77cb0..c57cc4fc 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:
@@ -209,12 +226,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 b2c5359c..02f955b1 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
@@ -343,10 +343,19 @@ 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."""
+ 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) 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)
diff --git a/docs/api.md b/docs/api.md
index dcb93630..d305601f 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