diff --git a/app/nullius/execution.py b/app/nullius/execution.py index aa4d58d3..88335fe8 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -116,7 +116,7 @@ import time from dataclasses import asdict, dataclass, field from datetime import datetime, timezone -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, List, Optional, Tuple from nullius import hosts, ondisk, paths, prices as price_list, progress, providers, redact, secrets, settings, workspace from nullius.judge import store as judgements @@ -360,6 +360,19 @@ def _clean_env() -> Dict[str, str]: return {k: v for k, v in os.environ.items() if k not in gone} +def provider_record(plan: Plan, env=os.environ) -> Tuple[str, str]: + """(setting, value): the record of a standard run's preset provider (``OPENROUTER``) as this machine + holds it, which the launcher exports so the run - reading no saved settings, ``--from-run`` - serves + the protocols it names. A record holds a name, a base and endpoints, never a key + (``providers.record_problem``); one that does not validate, or none, gives ("", "").""" + provider = (plan.recipe or {}).get("provider") + if plan.runner != STANDARD or plan.keyless or provider not in providers.PRESETS: + return "", "" + name = providers.setting_of(provider) + value = env.get(name, "") if name else "" + return (name, json.dumps(json.loads(value))) if value and not providers.record_problem(name, value) else ("", "") + + class Execution: """One run of one plan, in its own thread. ``state`` is one of preparing, running, paused, stopping, done, failed, stopped; ``log`` is what @@ -386,6 +399,7 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl 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 = "", "" + self._record = provider_record(plan, env) # 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": @@ -1497,6 +1511,8 @@ def _launch(self, part: dict) -> Optional[bool]: + ([("NULLIUS_PYTHON", sys.executable)] if self.plan.runner == STANDARD and not self.on_host else []) + ([("NULLIUS_LICENCE_DIR", self._licence_dir())] if self._licence_dir() else []) + ([("API_MODEL_NAME", self.plan.model)] if self.plan.model else []) + # the provider's record, as the builder read it here: the run reads no saved settings (--from-run) + + ([self._record] if self._record[0] else []) # this machine's Hugging Face endpoint: a host's run reads no saved settings (--from-run) + ([("HF_ENDPOINT", settings.hf_endpoint())] if self.on_host and settings.hf_endpoint() else [])) base = script[:-3] @@ -1507,13 +1523,15 @@ def _launch(self, part: dict) -> Optional[bool]: detach = (f"if ! command -v setsid >/dev/null 2>&1; then " f"command -v {python} >/dev/null 2>&1 || {{ echo 'detached runs need setsid or Python 3'; exit 1; }}; " f"setsid() {{ exec {python} -c {session} \"$@\"; }}; fi; ") + clear_records = ("unset " + " ".join(providers.setting_of(p) for p in providers.PRESETS) + "; " + if self.plan.runner == STANDARD else "") # stdin: the key, the endpoint, then one NAME=value line per agent key, then the end line - which alone says it all arrived launcher = ('IFS= read -r K && IFS= read -r U || { echo @cut; exit 1; }; E=; ' 'while IFS= read -r L; do [ "$L" = ' + STDIN_END + ' ] && { E=1; break; }; ' 'case "$L" in [A-Z_]*=*) export "$L";; *) echo @cut; exit 1;; esac; done; [ -n "$E" ] || { echo @cut; exit 1; }; unset E L; ' '[ -n "$K" ] && export ' + " ".join(f'{n}="$K"' for n in KEY_NAMES) + '; ' '[ -n "$U" ] && export ' + " ".join(f'{n}="$U"' for n in URL_NAMES) + '; unset K U; ' - f'export {exports}; cd {self._q(run_dir)} || exit 1; ' + f'{clear_records}export {exports}; cd {self._q(run_dir)} || exit 1; ' + detach + # An exclusive claim (noclobber: O_EXCL) prevents concurrent launchers starting the same part. From the claim on, this launcher runs # in the run directory until the part has started, which is how a restart tells it is on its way. diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 5c5bf226..4dc465e3 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -55,8 +55,9 @@ Keys come from the process environment, then the saved user settings. Nothing is printed of them. With ``--from-run`` (a run the builder or a page started, ``standard/pages/recipe.py``) saved settings are not -read: the key is the one the run was handed, ``OPENAI_API_KEY``, and the -endpoint ``OPENAI_BASE_URL`` when it names one (``run_env``). The licences a +read: the key is the one the run was handed, ``OPENAI_API_KEY``, the +endpoint ``OPENAI_BASE_URL`` when it names one, and the provider's record +when the launcher exported one (``run_env``). The licences a benchmark's environments declare are never in either: the run reads them from the benchmark's store (``nullius.secrets``) on this machine, or, on a host, from the one line its launcher handed it (``licences``). A data provider's token the @@ -110,12 +111,16 @@ def run_env(provider: str, env=os.environ) -> dict: and its endpoint as ``OPENAI_BASE_URL`` (empty for OpenAI's own), so they are named here as the provider's own settings and nothing else is - but the Boat key, handed the same way to a run on Boat: on a host, the only - way it has one.""" + way it has one; and the preset provider's record (``OPENROUTER``), which + the launcher exports as the builder read it: the protocols it serves.""" out = {k: v for k, v in env.items() if k in run.KEEP or k == boat.NAME} if env.get("OPENAI_API_KEY"): out[providers.key_setting(provider)] = env["OPENAI_API_KEY"] if provider == "custom" and env.get("OPENAI_BASE_URL"): out["MODEL_API_URL"] = env["OPENAI_BASE_URL"] + record = providers.setting_of(provider) if provider in providers.PRESETS else "" + if record and env.get(record): + out[record] = env[record] return out diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index c2c324a5..b3de2f6a 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -5,6 +5,7 @@ import shlex import os import shutil +import subprocess import threading import time import unittest @@ -845,6 +846,57 @@ def test_the_price_list_goes_with_the_run_even_empty_so_the_host_s_own_is_never_ launch = next(c for c, _ in self.calls if c[0] == "ssh" and "setsid nohup" in c[-1]) self.assertIn('NULLIUS_PRICES="$HOME/.nullius/runs/std-priced/prices.json"', launch[-1]) + def launched_environment(self, ambient=None): + argv, stdin = next((c, s) for c, s in self.calls if c[0] == "ssh" and "setsid nohup" in c[-1]) + prefix, marker, _ = argv[-1].partition("if ! command -v setsid") + self.assertTrue(marker) + home = self.tmp / "remote" + (home / ".nullius" / "runs" / self.plan.name).mkdir(parents=True, exist_ok=True) + # Run the launcher's exports without starting a detached process. + command = prefix + shlex.join([execution.sys.executable, "-c", + "import json, os; print(json.dumps(dict(os.environ)))"]) + done = subprocess.run(["bash", "-c", command], input=stdin, capture_output=True, text=True, timeout=10, + env={"PATH": os.defpath, "HOME": str(home), **(ambient or {})}) + self.assertEqual(done.returncode, 0, done.stderr) + return json.loads(done.stdout) + + def test_the_run_exports_its_own_providers_record_as_validated_and_no_other(self): + record = '{"endpoints": {"messages": "/messages"}}' + for label, provider, value, exported in ( + ("own", "openrouter", record, record), + ("duplicate-endpoint", "openrouter", + '{"endpoints":{"messages":"/messages?token=discarded-token","messages":"/messages"}}', record), + ("duplicate-record", "openrouter", + '{"endpoints":{"messages":"/messages?token=discarded-token"},"endpoints":{"messages":"/messages"}}', record), + ("other", "openai", record, None), + ("bad", "openrouter", '{"key": "sk-not-a-setting"}', None), + ): + with self.subTest(label=label): + self.calls.clear(); self.polls = 0 + self.plan.name, self.plan.recipe = f"std-record-{label}", {"provider": provider} + with patch.dict(os.environ, {"OPENROUTER": value}): + ex = self.run_it() + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + self.assertEqual(self.launched_environment().get("OPENROUTER"), exported) + self.assertNotIn("discarded-token", str(self.calls)) + self.assertNotIn("sk-not-a-setting", str(self.calls)) + + def test_preset_records_are_cleared_before_the_selected_record_is_exported(self): + from nullius.standard import cli + record = '{"endpoints": {"messages": "/messages"}}' + ambient = {providers.setting_of(p): "{}" for p in providers.PRESETS} + ambient["OPENROUTER"] = '{"endpoints": {"messages": "/host-messages"}}' + for label, value in (("absent", ""), ("selected", record)): + with self.subTest(label=label): + self.calls.clear(); self.polls = 0 + self.plan.name, self.plan.recipe = f"std-inherited-{label}", {"provider": "openrouter"} + with patch.dict(os.environ, {"OPENROUTER": value}): + ex = self.run_it() + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + env = self.launched_environment(ambient) + self.assertEqual({k: env[k] for k in ambient if k in env}, {"OPENROUTER": record} if value else {}) + self.assertEqual("openrouter" in providers.offered(["messages"], cli.run_env("openrouter", env)), bool(value)) + def test_what_it_does_is_said_in_stages_its_own_and_the_cli_s(self): """Getting the host ready is said stage by stage in the run's log, and the cli's own stages come through the part's log: the page folds them.""" diff --git a/app/tests/test_standard_recipe.py b/app/tests/test_standard_recipe.py index 3f4fbd3f..cbccc9c4 100644 --- a/app/tests/test_standard_recipe.py +++ b/app/tests/test_standard_recipe.py @@ -15,6 +15,7 @@ import unittest from unittest.mock import patch +from nullius import providers from nullius.standard import cli from nullius.standard.contract import definitions from nullius.standard.pages import recipe @@ -457,6 +458,12 @@ def test_the_handed_key_is_named_as_the_providers_own_and_nothing_else_is_kept(s self.assertEqual(cli.run_env("openrouter", env), {"OPENROUTER_API_KEY": "sk-handed", "PATH": "/bin"}) self.assertEqual(cli.run_env("custom", env), {"MODEL_API_KEY": "sk-handed", "MODEL_API_URL": "http://127.0.0.1:9/v1", "PATH": "/bin"}) self.assertEqual(cli.run_env("openai", env), {"OPENAI_API_KEY": "sk-handed", "PATH": "/bin"}) + record = '{"endpoints": {"messages": "/messages"}}' + env = {"OPENAI_API_KEY": "sk-handed", "PATH": "/bin", "OPENROUTER": record, "OPENAI": '{"endpoints": {}}'} + self.assertEqual(cli.run_env("openrouter", env), {"OPENROUTER_API_KEY": "sk-handed", "PATH": "/bin", "OPENROUTER": record}) + self.assertEqual(cli.run_env("anthropic", env), {"ANTHROPIC_API_KEY": "sk-handed", "PATH": "/bin"}) + self.assertIn("openrouter", providers.offered(["messages"], cli.run_env("openrouter", env))) + self.assertNotIn("openrouter", providers.offered(["messages"], cli.run_env("openrouter", dict(env, OPENROUTER="")))) def test_the_boat_key_handed_to_a_run_on_boat_is_kept(self): # on a host, the key handed over stdin is the run's only one: no store there holds it diff --git a/docs/cli/run.md b/docs/cli/run.md index ca998236..eba9d7f2 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -45,7 +45,7 @@ nullius standard run locomo model --model gpt-4o-mini | `--simulator-model` | Instead of the official simulated user | | `--name` | The job's name | | `--jobs` | Where jobs are written (default `jobs_standard/` relative to the current directory) | -| `--from-run` | Started by Nullius: `OPENAI_API_KEY` and `OPENAI_BASE_URL` only, saved settings unread | +| `--from-run` | Started by Nullius: `OPENAI_API_KEY`, `OPENAI_BASE_URL` and the provider's record only, saved settings unread | | `--shard I/N`, `--launch` | One shard of a launch: [Shard and merge](shard-and-merge.md) | | Rule | Detail |