Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions app/nullius/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand All @@ -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"]:
Expand Down
5 changes: 3 additions & 2 deletions app/nullius/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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)),
Expand Down
12 changes: 7 additions & 5 deletions app/nullius/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 5 additions & 2 deletions app/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions app/tests/test_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 3 additions & 3 deletions app/ui_tests/test_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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'<script id="nb-schema" type="application/json">(.*?)</script>', r.get_data(as_text=True), re.S).group(1))
Expand Down Expand Up @@ -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):
Expand Down
73 changes: 71 additions & 2 deletions app/ui_tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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"]})
Expand Down Expand Up @@ -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"))
Expand All @@ -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()
2 changes: 1 addition & 1 deletion app/ui_tests/test_harbor_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion app/ui_tests/test_prerequisites_route.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading