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 @@ -9,7 +9,7 @@ setup.
- **Harbor** runs through `uvx` with a pinned PyPI release or locally built repository commit. A Harbor run needs `docker ps` to answer.
- **The standard** runs from the current checkout or installed package; a host gets the running backend and effective catalogue, source edits and user entries included, never configuration or credentials. Several
machines run one shard each.
- **Keys**: a run gets only its provider's key and endpoint; logs are
- **Keys**: a run gets only its providers' keys and endpoints (the agent's, a judge's or simulator's own); logs are
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
Expand Down
35 changes: 29 additions & 6 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@
optional: without it the run is sent
``settings.MODEL_KEY_PLACEHOLDER``, for a server that checks no key - and a
run without that endpoint fails before it starts.
A standard recipe whose judge or user simulator has a provider of its own
(``Plan.roles``) is handed that provider's key and endpoint too, as
``providers.role_vars`` names them, and those of no other provider.
They are read on this machine and handed to the run as environment
(API_TOKEN, OPENAI_API_KEY, LLM_API_KEY; API_URL, OPENAI_BASE_URL,
LLM_BASE_URL) - over stdin to the launcher, never in argv (the key to a
Expand Down Expand Up @@ -134,6 +137,7 @@
# The names the launcher gives a run's key and its endpoint (_launch), read
# from stdin: the only credentials a run's commands get.
KEY_NAMES = ("API_TOKEN", "OPENAI_API_KEY", "LLM_API_KEY")
ROLES = ("judge", "simulator") # the standard's roles a provider of their own may serve (``Plan.roles``)
URL_NAMES = ("API_URL", "OPENAI_BASE_URL", "LLM_BASE_URL")
# The line the launcher's stdin ends with, after the key and the endpoint:
# either may be empty, so only this line says the two arrived whole.
Expand Down Expand Up @@ -261,6 +265,7 @@ class Plan:
keyless: bool = False # nothing in it calls a model (the standard's controls): handed no key and no endpoint at all
licences: dict = field(default_factory=dict) # the standard's on a host: {"benchmark", "names", "providers"} - what it is sent of that benchmark's licences
caps: dict = field(default_factory=dict) # a job's spending cap set on its page, {job: USD}: it holds from the job's next run
roles: dict = field(default_factory=dict) # by role, its own provider's {key_var, url_var, base_url}: the standard's judge or user simulator

def steps(self) -> List[dict]:
return [p for p in self.parts if p.get("script")] or [{"id": "run", "label": "the run", "script": self.script}]
Expand Down Expand Up @@ -340,7 +345,8 @@ def withheld() -> List[str]:
run gets its own endpoint's key alone. A data provider's token name is not one."""
secret = {v.name for v in settings.VARIABLES if v.secret or v.kind in ("endpoint", "provider")} | set(settings.endpoint_names())
return sorted(secret | {old for old, new in settings.INSTEAD.items() if new in secret}
| set(KEY_NAMES + URL_NAMES) | {"GITHUB_TOKEN", "GH_TOKEN", "BOAT_API_KEY"} | set(settings.agent_key_names())
| set(KEY_NAMES + URL_NAMES) | {n for r in ROLES for n in providers.role_vars(r)}
| {"GITHUB_TOKEN", "GH_TOKEN", "BOAT_API_KEY"} | set(settings.agent_key_names())
| set(_licence_names()))


Expand Down Expand Up @@ -448,6 +454,14 @@ def _credentials(self, key: Optional[str], url: Optional[str], env, agent_keys:
self._url = url if url is not None else (providers.base_of(plan.url_var, env) if plan.url_var else plan.base_url)
if plan.keyless: # a run that calls no model is given nothing it could leak
self._key, self._url = "", ""
# each role's own provider, as the launcher hands it: {name: value}, names from providers.role_vars
self._roles: Dict[str, str] = {}
for role, c in sorted((plan.roles or {}).items()):
if role not in ROLES or plan.keyless:
continue
k, u = providers.role_vars(role)
self._roles[k] = env.get(c.get("key_var", ""), "") or (settings.MODEL_KEY_PLACEHOLDER if c.get("url_var") else "")
self._roles[u] = providers.base_of(c["url_var"], env) if c.get("url_var") else c.get("base_url", "")
# the agent keys Settings holds (CURSOR_API_KEY, ...): a Harbor run's agent may need its own vendor's; the standard's never gets one
self._agent_keys = dict(agent_keys) if agent_keys is not None else (settings.agent_key_values(env) if plan.runner == "harbor" else {})
if plan.runner == "standard" and (plan.recipe or {}).get("backend") == "boat":
Expand Down Expand Up @@ -506,8 +520,9 @@ def log(self, line: str) -> None:
if line.startswith("** ") and ("post-quantum" in line or "store now, decrypt later" in line or "openssh.com/pq" in line):
return # ssh's own warning about the host's key exchange, not the run's
clean = redact.redact(line.rstrip("\n"))
if self._key and self._key != settings.MODEL_KEY_PLACEHOLDER: # the placeholder is no secret, and a common word
clean = clean.replace(self._key, "[REDACTED]")
for key in (self._key, *(v for n, v in self._roles.items() if n.endswith("_KEY"))):
if key and key != settings.MODEL_KEY_PLACEHOLDER: # the placeholder is no secret, and a common word
clean = clean.replace(key, "[REDACTED]")
for value in list(self._agent_keys.values()) + self._redact:
if len(value) >= 8:
clean = clean.replace(value, "[REDACTED]")
Expand Down Expand Up @@ -804,6 +819,12 @@ def _missing(self) -> Optional[str]:
return f"{self.plan.key_var} is not set in Settings; the producers and the judge would have no model key"
if not self._url and self.plan.url_var and not self.plan.keyless and (harbor_model or self.plan.runner != "harbor"):
return f"{self.plan.url_var} is not set in Settings; an OpenAI-compatible endpoint has no default, so the run would have nowhere to send its calls"
for role, c in sorted((self.plan.roles or {}).items()):
k, u = providers.role_vars(role)
if k in self._roles and not self._roles[k]:
return f"{c.get('key_var')} is not set in Settings; the {role} would have no model key"
if k in self._roles and not self._roles[u] and c.get("url_var"):
return f"{c['url_var']} is not set in Settings; the {role}'s endpoint has no default"
return self._line_break()

def again(self, part: dict, env=os.environ) -> "Execution":
Expand Down Expand Up @@ -1471,11 +1492,12 @@ def _await_start(self, names: List[str], part: dict) -> Optional[tuple]:
return look

def _stdin(self) -> str:
"""What the launcher reads: the key, the endpoint, the agent keys as
NAME=value, the benchmark's licences as one more (a standard run on a
"""What the launcher reads: the key, the endpoint, the agent keys and
each role's own provider as NAME=value, the benchmark's licences as one more (a standard run on a
host), the end line."""
lic = self._licence_line()
return "".join(f"{line}\n" for line in [self._key, self._url, *(f"{n}={v}" for n, v in self._agent_keys.items()),
*(f"{n}={v}" for n, v in self._roles.items() if v),
*([f"{secrets.HANDED}={lic}"] if lic else []), STDIN_END])

def _licence_dir(self) -> str:
Expand Down Expand Up @@ -1524,7 +1546,8 @@ def _line_break(self) -> Optional[str]:
(``_launch``), would take in pieces. Settings refuses one, so only
the environment Nullius was started in can hold it. The variable is
named, never its value."""
for value, var in ((self._key, self.plan.key_var), (self._url, self.plan.url_var or "the endpoint"), *((v, n) for n, v in self._agent_keys.items())):
for value, var in ((self._key, self.plan.key_var), (self._url, self.plan.url_var or "the endpoint"),
*((v, n) for n, v in self._agent_keys.items()), *((v, n) for n, v in self._roles.items())):
if "\n" in value or "\r" in value:
return (f"{var} holds a line break; a key or an endpoint is one line, and the run's launcher would take this one "
f"in pieces. Set it again on one line in the environment Nullius was started in (Settings refuses a line break)")
Expand Down
4 changes: 3 additions & 1 deletion app/nullius/leaderboard/board.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ def row_identity(job):
return {"agent": agent, "version": version or identity.get("agent_version", job.agent_version),
"model": identity.get("model", job.model_name), "effort": job.reasoning_effort,
"provider": identity.get("provider"), "options": identity.get("agent_options"),
"backend": identity.get("backend") or job.launch.get("environment"), "limits": limits}
"backend": identity.get("backend") or job.launch.get("environment"), "limits": limits,
# a judge or user simulator on a provider of its own is another row; a run without one keeps its key
**({"role_providers": identity["role_providers"]} if identity.get("role_providers") else {})}


def key_for(identity):
Expand Down
6 changes: 6 additions & 0 deletions app/nullius/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,12 @@ def endpoint_vars(endpoint: str = "") -> tuple:
return ("MODEL_API_URL", "MODEL_API_KEY") if not endpoint else (f"MODEL_{endpoint}_API_URL", f"MODEL_{endpoint}_API_KEY")


def role_vars(role: str) -> tuple:
"""(key name, endpoint name) a run started by Nullius is handed a role's own provider under
(``execution``'s launcher, ``standard.cli.run_env``): the judge's, the user simulator's."""
return f"NULLIUS_{role.upper()}_API_KEY", f"NULLIUS_{role.upper()}_BASE_URL"


def base_of(url_var: str, env=None) -> str:
"""The base a run's ``url_var`` names (``execution.Plan``): a custom provider's, from its record when it
has one (MODEL_<ID>_API_URL is its old setting), else the variable's own value."""
Expand Down
5 changes: 3 additions & 2 deletions app/nullius/runs/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
# The shape this module produces. A workspace caches parsed Jobs keyed on it,
# so bump it when a Trial or Job field is added, renamed or means something
# new — otherwise a cache written by the old parse is read back as current.
SCHEMA = "30"
SCHEMA = "31"

# What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK
# retries a 429 below the harness, so a limit the run survived leaves nothing in result.json —
Expand Down Expand Up @@ -1253,7 +1253,7 @@ def identity_of(cfg: dict, res: dict, agent_version: str = "") -> dict:
(``cfg``) and its ``result.json`` (``res``): the benchmark, its version and
options; the agent as the run named it, the version its trials report
(``agent_version``) and its options, defaults included; the backend its units ran on; the model; the
provider; the serving providers pinned by model (``served_by``) and who
provider, and a judge's or user simulator's own (``role_providers``); the serving providers pinned by model (``served_by``) and who
served (``served``); and the limits in force: time limits by phase, turns,
model calls, attempts of each unit, retries, units at a time, and the
spending caps and resource constraints. A fact the job does not record is not a key, never an
Expand All @@ -1273,6 +1273,7 @@ def identity_of(cfg: dict, res: dict, agent_version: str = "") -> dict:
# a control asks no model unless it has a judge or a simulated user; the provider it records is then a default
asks = out["model"] or std.get("judge") or std.get("simulator") or std.get("kind") != "control"
out["provider"] = word(std.get("provider")) if asks else ""
out["role_providers"] = {r: word(std[r + "_provider"]) for r in ("judge", "simulator") if isinstance(std.get(r + "_provider"), str)}
pins = std.get("served_by") if isinstance(std.get("served_by"), dict) else {}
out["served_by"] = {redact(str(m)): [word(s) for s in slugs if isinstance(s, str)]
for m, slugs in pins.items() if isinstance(slugs, list) and slugs}
Expand Down
36 changes: 24 additions & 12 deletions app/nullius/standard/backends/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,8 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi
key_header: str = "authorization", hosts: Optional[Dict[str, str]] = None,
ledger: Optional[str] = None, serving: Optional[Dict[str, List[str]]] = None,
timeout: Optional[int] = None, max_calls: Optional[int] = None, exchanges: str = "off",
exchanges_max_mb: int = exchange_store.MAX_MB, reasoning: Optional[Dict[str, str]] = None) -> List[str]:
exchanges_max_mb: int = exchange_store.MAX_MB, reasoning: Optional[Dict[str, str]] = None,
upstreams: Optional[Dict[str, Tuple[str, str]]] = None) -> List[str]:
"""``docker run`` for a unit's relay: on the default bridge (its way to the
provider), its port published on 127.0.0.1 only. The key is never given:
``key_file``, its file, is mounted read-only at ``RELAY_KEY_IN`` with
Expand All @@ -744,13 +745,17 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi
unit's own relay is given them (``relay.Relay``); ``reasoning`` the same,
by model, the level its requests are sent with. ``exchanges`` and
``exchanges_max_mb``: whether its calls are kept whole in its record
folder, and the bound, always said."""
folder, and the bound, always said. ``upstreams``: by role, ``(base, key
file)`` of the provider that role's routes call (``relay.Relay``), each
key file mounted as ``key_file`` is."""
a = [DOCKER, "run", "-d", "--name", name, "--label", f"{LABEL}={job}", *way_out(), *_userns(), "--user", _user(),
"--cap-drop", "ALL", *_security_opt(), "--init", *capped(),
*[w for n, ip in sorted((hosts or {}).items()) for w in ("--add-host", f"{n}:{ip}")],
"-p", f"127.0.0.1::{RELAY_PORT}", "-v", f"{app}:{app}:ro", "-v", f"{record}:{record}:rw",
*(["-v", f"{os.path.dirname(ledger)}:{os.path.dirname(ledger)}:rw"] if ledger else []),
"--mount", f"type=bind,source={key_file},target={RELAY_KEY_IN},readonly", "-w", app,
"--mount", f"type=bind,source={key_file},target={RELAY_KEY_IN},readonly",
*[w for role, (_, f) in sorted((upstreams or {}).items())
for w in ("--mount", f"type=bind,source={f},target={RELAY_KEY_IN}-{role},readonly")], "-w", app,
"-e", "PYTHONPATH=" + app, "-e", "PYTHONDONTWRITEBYTECODE=1",
image, "python3", "-m", "nullius.standard.calls.relay", "serve", "--listen", f"0.0.0.0:{RELAY_PORT}",
"--base", base, "--record", record, "--key-file", RELAY_KEY_IN, "--public", f"http://{RELAY_ALIAS}:{RELAY_PORT}"]
Expand Down Expand Up @@ -779,6 +784,8 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi
a += ["--key-header", key_header]
if timeout:
a += ["--timeout", str(timeout)]
for role, (b, _) in sorted((upstreams or {}).items()):
a += ["--upstream", f"{role}={b}", "--upstream-key-file", f"{role}={RELAY_KEY_IN}-{role}"]
return a


Expand Down Expand Up @@ -887,12 +894,15 @@ class Loopback:
joins it, so a :class:`SocketDoor` (``door``) passes each connection
instead, and one door container for the run reaches it, on the engine's
default network as the relays are. The relays call it
``host.docker.internal`` there too, at the door's address, on port 8000."""
``host.docker.internal`` there too, at the door's address, on port 8000.
``role``: a door of a role's own provider (``relay.ROLES``), which the
relays call ``<role>.host.docker.internal``, beside the agent's."""

NAME = "host.docker.internal"
DOOR_PORT = 8000 # not the endpoint's: below 1024 needs a capability on podman

def __init__(self, base: str, *, image: str = "", job: str = ""):
def __init__(self, base: str, *, image: str = "", job: str = "", role: str = ""):
self.name, self.role = (f"{role}.{self.NAME}" if role else self.NAME), role
self.target = urllib.parse.urlsplit(base)
self.base, self.hosts = base, {}
self.image, self.job = image, job # the door container's (use_socket_doors)
Expand All @@ -902,13 +912,13 @@ def __init__(self, base: str, *, image: str = "", job: str = ""):

def _url(self, port: Optional[int]) -> str:
t = self.target
netloc = (t.netloc.rpartition("@")[0] + "@" if "@" in t.netloc else "") + self.NAME + (f":{port}" if port else "")
netloc = (t.netloc.rpartition("@")[0] + "@" if "@" in t.netloc else "") + self.name + (f":{port}" if port else "")
return urllib.parse.urlunsplit((t.scheme, netloc, t.path, t.query, t.fragment))

def start(self) -> "Loopback":
if use_socket_doors():
self.door = SocketDoor(*self._endpoint())
self.container = f"nullius-{slug(self.job)}-model"
self.container = f"nullius-{slug(self.job)}-model" + (f"-{self.role}" if self.role else "")
try:
make_bridge()
_docker(door_argv(self.image, name=self.container, job=self.job, port=self.DOOR_PORT,
Expand All @@ -922,17 +932,17 @@ def start(self) -> "Loopback":
except Exception:
self.stop()
raise
self.base, self.hosts = self._url(self.DOOR_PORT), {self.NAME: ip[0]}
self.base, self.hosts = self._url(self.DOOR_PORT), {self.name: ip[0]}
return self
gateway = bridge_gateway()
try:
if not gateway:
raise OSError("no bridge gateway")
self._server = socket.create_server((gateway, 0))
except OSError:
self.base, self.hosts = self._url(self.target.port), {self.NAME: "host-gateway"}
self.base, self.hosts = self._url(self.target.port), {self.name: "host-gateway"}
return self
self.base, self.hosts = self._url(self._server.getsockname()[1]), {self.NAME: gateway}
self.base, self.hosts = self._url(self._server.getsockname()[1]), {self.name: gateway}
threading.Thread(target=_pass_each, args=(self._server, self._endpoint()), daemon=True).start()
return self

Expand Down Expand Up @@ -1056,8 +1066,9 @@ def __init__(self, job: str, tag: str, record_dir: str, *, image: str, app: str,
ledger: Optional[str] = None, network_probe: Optional[str] = None, probe_now: bool = True,
serving: Optional[Dict[str, List[str]]] = None, timeout: Optional[int] = None, max_calls: Optional[int] = None,
exchanges: str = "off", exchanges_max_mb: int = exchange_store.MAX_MB,
reasoning: Optional[Dict[str, str]] = None):
reasoning: Optional[Dict[str, str]] = None, upstreams: Optional[Dict[str, Tuple[str, str]]] = None):
self.job, self.tag, self.dir, self.image, self.app = job, tag, record_dir, image, app
self.upstreams = dict(upstreams or {}) # by role, (base, key) of the provider its routes call
self.max_calls = max_calls
self.exchanges, self.exchanges_max_mb = exchanges, exchanges_max_mb
self.ledger = ledger
Expand Down Expand Up @@ -1092,7 +1103,8 @@ def start(self) -> "Unit":
hosts=self.hosts, ledger=self.ledger, serving=self.serving,
timeout=self.timeout, max_calls=self.max_calls,
exchanges=self.exchanges, exchanges_max_mb=self.exchanges_max_mb,
reasoning=self.reasoning)
reasoning=self.reasoning,
upstreams={role: (b, self._key_file("key-" + role, k)) for role, (b, k) in self.upstreams.items()})
self.started.append(self.names["relay"])
_docker(argv[1:])
_docker(["network", "connect", "--alias", RELAY_ALIAS, self.names["network"], self.names["relay"]])
Expand Down
Loading