Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .claude/rules/running.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ setup.
redacted. The standard's agents and upstream scripts get only the relay's
word, never a key.
- What a recipe needs of each machine is asked before Run and again as it
starts (`nullius/prerequisites.py`). `runs/<name>/run.json` lets a
starts (`nullius/prerequisites.py`). `runs/<name>/run.json` and `plan.json` let a
restarted Nullius pick a run up again.

## Running the app
Expand Down
248 changes: 192 additions & 56 deletions app/nullius/execution.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion app/nullius/runs/launches.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
this order:

- **The run record.** A run started from the builder's Run writes
``runs/<name>/run.json``, and its plan names every job it launches
``runs/<name>/run.json``, and its plan beside it names every job it launches
(``execution.Plan.jobs``). Those jobs are one launch, including the ones
Harbor has not written yet.
- **Inferred, for everything else** — an imported tree, a job run by hand: runs on the same dataset whose start is within
Expand Down
2 changes: 1 addition & 1 deletion app/site/diagrams.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def run_leaves() -> Figure:
f.path([(120, 296), (520, 296)], 'bus', head=False)
for cx in (120, 320, 520):
f.path([(cx, 296), (cx, 312)])
f.node(232, 24, 176, 64, 'runs/<name>/', ['run.json: plan and state', 'run-part.sh, log, exit file'], 'store')
f.node(232, 24, 176, 64, 'runs/<name>/', ['plan.json, run.json: state', 'run-part.sh, log, exit file'], 'store')
f.node(232, 120, 176, 64, 'jobs/<job-name>/', ['config.json, result.json,', 'events.jsonl'], 'store')
f.node(232, 216, 176, 64, '<trial>/', ['result.json, trial.log,', 'exception.txt'], 'store')
f.node(40, 312, 160, 56, 'agent/', ['trajectory.json, logs,', 'traces'], 'focal')
Expand Down
4 changes: 2 additions & 2 deletions app/tests/execution_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,5 +161,5 @@ def ssh_commands(self):

def killed(self, pid, part="run"):
"""A Stop's kill went to the host for ``pid``, by its process group,
once the host has found it still the part's own (``_own_pids``)."""
return any("kill -TERM -- -$p" in c and f"for p in {pid}" in c and execution._script_rx(f"run-{part}") in c for c in self.ssh_commands())
once the host has found it still the part's own (``_own_pids``). ``run``: a run of one part."""
return any("kill -TERM -- -$p" in c and f"for p in {pid}" in c and execution._script_rx({"id": part, "whole": part == "run"}) in c for c in self.ssh_commands())
50 changes: 42 additions & 8 deletions app/tests/test_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import shlex
import os
import shutil
import tempfile
import threading
import time
import unittest
Expand All @@ -29,6 +30,18 @@ def test_run_names_must_match_in_full(self):
self.assertEqual(execution.Plan(name=name, script="true").check(),
"the run needs a name: letters, digits, dots, dashes")

def test_two_parts_that_would_run_one_script_are_refused(self):
for ids in (("same", "same"), ("a b", "a_b")): # the second as a route spells the first
with self.subTest(ids=ids):
parts = [{"id": i, "label": i, "script": f"echo {n}"} for n, i in enumerate(ids)]
self.assertEqual(execution.Plan(name="r", script="", parts=parts).check(),
"two parts run the same script, run-a_b.sh: give each part its own id" if ids[1] == "a_b"
else "two parts run the same script, run-same.sh: give each part its own id")
root = Path(tempfile.mkdtemp(prefix="nullius-collide-")); self.addCleanup(shutil.rmtree, root, True)
with self.assertRaisesRegex(ValueError, "two parts run the same script"): # started directly: no record to restore
execution.start(execution.Plan(name="r", script="", parts=parts), root=str(root))
self.assertEqual((list(root.iterdir()), [e for e in execution.EXECUTIONS.values() if e.root == str(root)]), ([], []))


class Here(Base):
"""Local runs are real: bash, setsid, the exit file, the log."""
Expand All @@ -42,10 +55,12 @@ def test_the_script_runs_detached_with_the_local_paths_and_the_key_as_environmen
self.assertIn(f"harbor=harbor tasks={self.tmp} jobs={self.tmp / 'runs' / 'tau3-x3' / 'jobs'} model=openai/gpt-5", text) # the harbor on PATH
self.assertIn("key=21/21 chars url=https://llm.example/v1", text) # the key reached the run
d = self.tmp / "runs" / "tau3-x3"
self.assertEqual((d / "run-run.sh").read_text(), script + "\n"); self.assertEqual((d / "run-run.exit").read_text().strip(), "0")
self.assertNotIn("sk-verysecretkey12345", (d / "run-run.sh").read_text()); self.assertNotIn("sk-verysecretkey12345", (d / "run.json").read_text())
self.assertEqual((d / "run.sh").read_text(), script + "\n"); self.assertEqual((d / "run-run.exit").read_text().strip(), "0")
self.assertFalse((d / "run-run.sh").exists()) # a run of one part runs run.sh
self.assertNotIn("sk-verysecretkey12345", (d / "run.sh").read_text()); self.assertNotIn("sk-verysecretkey12345", (d / "run.json").read_text())
rec = json.loads((d / "run.json").read_text())
self.assertEqual((rec["state"], rec["exit_code"], rec["plan"]["name"], rec["plan"]["host"]), ("done", 0, "tau3-x3", None))
plan = json.loads((d / "plan.json").read_text())
self.assertEqual((rec["state"], rec["exit_code"], plan["name"], plan["host"]), ("done", 0, "tau3-x3", None))

def test_missing_setsid_uses_python_and_records_the_real_exit_code(self):
# Simulate macOS command lookup while retaining the real shell/processes.
Expand Down Expand Up @@ -179,6 +194,24 @@ def test_a_failing_script_is_a_failed_run(self):
self.assertEqual((ex.state, ex.exit_code, ex.error), ("failed", 3, "the run exited 3"))


class FirstSave(Base):
def test_a_launch_whose_record_cannot_be_saved_leaves_no_folder_behind(self):
root = self.tmp / "runs"
plans = [execution.Plan(name="s1", script="true", parts=[{"id": "a", "label": "a", "script": "true"}]), execution.Plan(name="s2", script="true")]
real = execution.ondisk.write_whole
def full(path, data, mode=None):
if path == str(root / "s2" / "run.json"):
raise OSError(28, "No space left on device")
return real(path, data, mode)
runs = [execution.Execution(p, root=str(root)) for p in plans]
with patch.object(execution.ondisk, "write_whole", full), self.assertRaises(OSError):
execution.start_all(runs)
self.assertEqual((list(root.iterdir()), dict(execution.EXECUTIONS)), ([], {})) # names free again, nothing started
for ex in execution.start_all(runs): # tried again: each with its plan, read back
self.wait(ex)
self.assertEqual([execution.recorded(ex.dir)[1]["name"] for ex in runs], ["s1", "s2"])


class DockerHere(Base):
"""A Harbor run here asks docker first, as a run on a host does - and
so does the standard on its container backend - and starts nothing when it
Expand Down Expand Up @@ -232,7 +265,7 @@ def test_the_standard_on_its_docker_backend_asks_too_and_off_it_does_not(self):
ex = self.start(execution.Plan(name="std", script="", parts=parts, runner="standard", docker=True, keyless=True))
self.assertEqual((ex.state, ex.step), ("failed", "docker"))
self.assertTrue(ex.error.startswith("docker is on this machine but does not answer"), ex.error)
self.assertFalse((self.tmp / "runs" / "std" / "run-run.sh").exists())
self.assertFalse((self.tmp / "runs" / "std" / "run-run.launch").exists())
(self.tmp / "asked").unlink()
ex = self.start(execution.Plan(name="std-local", script="", parts=parts, runner="standard", keyless=True)) # the local backend: no containers
self.assertNotEqual(ex.step, "docker", ex.lines)
Expand Down Expand Up @@ -605,7 +638,7 @@ def run(argv, timeout=600.0, stdin=None, sent=sent):
self.assertTrue(ex.error.startswith(f"{var} holds a line break; "), ex.error)
self.assertNotIn("cut short", ex.error)
d = root / name if target == "here" else self.on_host(name)
self.assertFalse(d.exists() and any(p.name.startswith("run-a.") for p in d.iterdir())) # not claimed, not started
self.assertFalse(d.exists() and any(p.name.startswith("run-a.") and p.name != "run-a.sh" for p in d.iterdir())) # not claimed, not started
self.assertFalse(marker.exists())
self.assertNotIn(secret, "\n".join(ex.lines))
for f in root.rglob("*"):
Expand Down Expand Up @@ -792,16 +825,17 @@ def test_the_part_runs_detached_with_the_host_s_harbor_and_the_job_mirrored_back
self.assertRegex(place, r"^tasks/[0-9a-f]{10}/tasks$")
self.assertTrue(all(c[-2].startswith("bench:~/.nullius/runs/tau3-x3/jobs/") for c in rsyncs[1:])) # the job came back
self.assertGreaterEqual(len(rsyncs), 2)
landed = next(s for c, s in self.calls if c[0] == "ssh" and "cat > " in c[-1] and "run-run.sh" in c[-1])
self.assertEqual(landed, self.plan.script + "\n") # the part's script, over stdin
landed = [s for c, s in self.calls if c[0] == "ssh" and "cat > " in c[-1] and ".sh" in c[-1]]
self.assertEqual(landed, [self.plan.script + "\n"]) # the run's script, over stdin, once
launch = next((c, s) for c, s in self.calls if c[0] == "ssh" and "setsid nohup" in c[-1])
self.assertIn("bash run.sh <", launch[0][-1]) # as run.sh, the one script of a run of one part
self.assertIn("BatchMode=yes", launch[0]); self.assertIn("read -r K", launch[0][-1])
self.assertIn("NULLIUS_HARBOR=harbor ", launch[0][-1]); self.assertIn(f'NULLIUS_TASKS="$HOME/.nullius/{place}"', launch[0][-1])
self.assertIn('export PATH="$HOME/.local/bin:$PATH"', launch[0][-1]) # where a uv-installed harbor lives
self.assertIn('NULLIUS_JOBS="$HOME/.nullius/runs/tau3-x3/jobs"', launch[0][-1]); self.assertIn("API_MODEL_NAME=openai/gpt-5", launch[0][-1])
self.assertNotIn("sk-verysecretkey12345", launch[0][-1]); self.assertEqual(launch[1], "sk-verysecretkey12345\n\n@end\n") # stdin: the key, the endpoint, the end line
self.assertIn("harbor: starting", ex.lines); self.assertNotIn("sk-verysecretkey12345", "\n".join(ex.lines))
self.assertEqual(json.loads((self.tmp / "runs" / "tau3-x3" / "run.json").read_text())["plan"]["host"], "bench")
self.assertEqual(json.loads((self.tmp / "runs" / "tau3-x3" / "plan.json").read_text())["host"], "bench")

def test_a_host_s_run_is_sent_this_machine_s_hugging_face_endpoint(self):
with mock.patch.dict(os.environ, {"HF_ENDPOINT": "https://hf-mirror.com/"}):
Expand Down
23 changes: 20 additions & 3 deletions app/tests/test_execution_again.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ def test_a_part_runs_again_in_the_run_s_folder_with_the_key_read_now(self):
self.assertEqual(ex.state, "done", ex.lines)
first = ex.job_state("j1")
self.assertIsNone(ex.holds("j1"))
saved = self.tmp / "runs" / "std-here" / "plan.json"
written = (saved.read_bytes(), saved.stat().st_mtime_ns, saved.stat().st_ino)
gate = self.tmp / "go"
script = f'until [ -e {shlex.quote(str(gate))} ]; do sleep 0.02; done; echo "again key=${{#API_TOKEN}} jobs=$NULLIUS_JOBS"'
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-second-key-2"}):
Expand All @@ -57,15 +59,30 @@ def test_a_part_runs_again_in_the_run_s_folder_with_the_key_read_now(self):
# the job's end is still its own part's; the run's record holds both parts
self.assertEqual(ex.job_state("j1"), first)
self.assertIsNone(ex.again_of("j1"))
rec = json.loads((d / "run.json").read_text())
self.assertEqual([p["id"] for p in rec["plan"]["parts"]], ["fake", "again-1"])
rec, plan = execution.recorded(str(d))
self.assertEqual([p["id"] for p in plan["parts"]], ["fake", "again-1"])
self.assertEqual(plan["parts"][1]["script"], script + "\n")
# the part run again is the record's, its script its own file: the plan is as the run's start wrote it
self.assertEqual((saved.read_bytes(), saved.stat().st_mtime_ns, saved.stat().st_ino), written)
self.assertEqual([p["id"] for p in json.loads(written[0])["parts"]], ["fake"])
self.assertEqual(json.loads((d / "run.json").read_text())["again"], [{k: v for k, v in part(script).items() if k != "script"}])
self.assertEqual(sorted(rec["ends"]), ["again-1", "fake"])
self.assertEqual(ex.part_for("j1"), "fake")
# a restart reads it as it was
execution.EXECUTIONS.clear()
back = execution.Execution(execution.Plan.from_dict(rec["plan"]), root=str(self.tmp / "runs"), record=rec)
back = execution.Execution(execution.Plan.from_dict(plan), root=str(self.tmp / "runs"), record=rec)
self.assertEqual((back.state, back.job_state("j1")), ("done", first))

def test_a_part_whose_script_cannot_be_written_is_not_recorded(self):
ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start())
with mock.patch.object(execution, "_write_script", side_effect=OSError(28, "No space left on device")), self.assertRaises(OSError):
ex.again(part("true"), env={"OPENAI_API_KEY": "sk-first-key-0001"})
self.assertEqual([p["id"] for p in ex.plan.parts], ["fake"])
ex._save() # a later save, a cap's
execution.EXECUTIONS.clear()
execution.restore(str(self.tmp / "runs"))
self.assertEqual([e.plan.name for e in execution.EXECUTIONS.values()], ["std-here"]) # still read back

def test_a_part_run_again_that_fails_fails_the_run_and_not_the_job(self):
ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start())
first = ex.job_state("j1")
Expand Down
Loading
Loading