From 38ae694d51a5d54efc91e4305e06818019eb0f92 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 16 Nov 2026 16:43:05 +0100 Subject: [PATCH 01/14] refactor(standard): sort the package into one folder per purpose app/nullius/standard held 32 modules side by side. They are now eight folders, each one purpose, with cli.py left at the top because `python3 -m nullius.standard.cli` is documented and the host snapshot and the recipe launcher look for that file: contract/ ports, names, definitions, match requirements/ install, hostreq, network_requirements protocols/ acp, jsonl, cancellation calls/ relay, ledger containers/ container, setup_container, forward, egress, mcp_machine, mcp_bridge, web_services runner/ run, job, pace, shard, merge, payload proofs/ conform, fidelity, prove, pins pages/ recipe, howto No module is renamed and none changes what it does. What follows the move: every import, the two module names a container is started by (the relay and the setup driver), the three constants a module derives from its own path (definitions, run, payload), the wheel's package list, the PR judge's path floor for the relay, and the paths named in the docs, the skills and AGENTS.md, whose map now names pace too. A new trace names runner/job.py as its producer. Import paths change without aliases: a driver kept in user storage that imports nullius.standard.jsonl or nullius.standard.container must follow. --- .claude/skills/docs-drift/SKILL.md | 2 +- .claude/skills/import-agent/SKILL.md | 5 ++-- .claude/skills/import-capability/SKILL.md | 7 +++-- .claude/skills/import-standard/SKILL.md | 5 ++-- .github/scripts/judge_pr.py | 2 +- .github/workflows/docker-tests.yml | 2 +- AGENTS.md | 13 +++++++-- .../catalogue/benchmarks/humaneval/driver.py | 2 +- .../catalogue/benchmarks/tau3-bench/driver.py | 2 +- .../benchmarks/tau3-bench/mcp_server.py | 2 +- app/nullius/constraints.py | 2 +- app/nullius/execution.py | 13 +++++---- app/nullius/hosts.py | 2 +- app/nullius/onboarding.py | 2 +- app/nullius/prerequisites.py | 3 +- app/nullius/providers.py | 2 +- app/nullius/recipes/launch.py | 6 ++-- app/nullius/runs/launches.py | 2 +- app/nullius/sandbox.py | 2 +- app/nullius/secrets.py | 2 +- app/nullius/standard/__init__.py | 22 ++++++++++----- app/nullius/standard/calls/__init__.py | 6 ++++ app/nullius/standard/{ => calls}/ledger.py | 0 app/nullius/standard/{ => calls}/relay.py | 8 +++--- app/nullius/standard/cli.py | 18 ++++++------ app/nullius/standard/containers/__init__.py | 14 ++++++++++ .../standard/{ => containers}/container.py | 9 +++--- .../standard/{ => containers}/egress.py | 0 .../standard/{ => containers}/forward.py | 0 .../standard/{ => containers}/mcp_bridge.py | 0 .../standard/{ => containers}/mcp_machine.py | 2 +- .../{ => containers}/setup_container.py | 7 +++-- .../standard/{ => containers}/web_services.py | 0 app/nullius/standard/contract/__init__.py | 7 +++++ .../standard/{ => contract}/definitions.py | 12 ++++---- app/nullius/standard/{ => contract}/match.py | 4 +-- app/nullius/standard/{ => contract}/names.py | 0 app/nullius/standard/{ => contract}/ports.py | 0 .../kits/agent-conversation-v1/driver.py | 2 +- .../standard/kits/agent-search-v1/driver.py | 4 +-- .../standard/kits/agent-task-v1/driver.py | 2 +- .../standard/kits/agent-tools-v1/driver.py | 4 +-- .../kits/agent-workspace-v1/driver.py | 4 +-- .../standard/kits/cap-memory-v1/driver.py | 2 +- app/nullius/standard/pages/__init__.py | 7 +++++ app/nullius/standard/{ => pages}/howto.py | 0 app/nullius/standard/{ => pages}/recipe.py | 7 +++-- app/nullius/standard/proofs/__init__.py | 7 +++++ app/nullius/standard/{ => proofs}/conform.py | 3 +- app/nullius/standard/{ => proofs}/fidelity.py | 6 +++- app/nullius/standard/{ => proofs}/pins.py | 0 app/nullius/standard/{ => proofs}/prove.py | 5 +++- app/nullius/standard/protocols/__init__.py | 7 +++++ app/nullius/standard/{ => protocols}/acp.py | 2 +- .../standard/{ => protocols}/cancellation.py | 0 app/nullius/standard/{ => protocols}/jsonl.py | 2 +- app/nullius/standard/requirements/__init__.py | 8 ++++++ .../standard/{ => requirements}/hostreq.py | 0 .../standard/{ => requirements}/install.py | 2 +- .../network_requirements.py | 0 app/nullius/standard/runner/__init__.py | 8 ++++++ app/nullius/standard/{ => runner}/job.py | 4 +-- app/nullius/standard/{ => runner}/merge.py | 4 +-- app/nullius/standard/{ => runner}/pace.py | 0 app/nullius/standard/{ => runner}/payload.py | 4 +-- app/nullius/standard/{ => runner}/run.py | 15 ++++++---- app/nullius/standard/{ => runner}/shard.py | 0 app/packaging/verify.py | 2 +- app/static/builder/command-builder-core.js | 4 +-- app/static/builder/command-builder.js | 6 ++-- app/templates/catalogue/benchmark.html | 2 +- app/tests/catalogue_docs.py | 2 +- app/tests/docker_tier.py | 2 +- app/tests/test_audit_regressions.py | 7 +++-- app/tests/test_capability_names.py | 4 ++- app/tests/test_catalog.py | 2 +- app/tests/test_catalogue_overlay.py | 3 +- app/tests/test_catalogue_sources.py | 2 +- app/tests/test_classify.py | 8 ++++-- app/tests/test_constraints.py | 8 ++++-- app/tests/test_driver_path.py | 8 +++--- app/tests/test_execution.py | 3 +- app/tests/test_hf_endpoint.py | 3 +- app/tests/test_judge.py | 2 +- app/tests/test_kit_check_isolation.py | 13 +++++---- app/tests/test_locomo_rag.py | 2 +- app/tests/test_locomo_setups.py | 3 +- app/tests/test_longmemeval_setups.py | 3 +- app/tests/test_network_requirements.py | 8 ++++-- app/tests/test_onboarding.py | 2 +- app/tests/test_prerequisites.py | 5 +++- app/tests/test_prices.py | 2 +- app/tests/test_progress.py | 4 ++- app/tests/test_published_setups.py | 4 ++- app/tests/test_sandbox.py | 2 +- app/tests/test_search_kit.py | 5 ++-- app/tests/test_secrets.py | 8 +++--- app/tests/test_settings.py | 4 +-- app/tests/test_setup_container.py | 11 ++++---- app/tests/test_standard_acp.py | 4 +-- app/tests/test_standard_bench_options.py | 7 +++-- app/tests/test_standard_capability_trace.py | 2 +- app/tests/test_standard_check_safety.py | 4 ++- app/tests/test_standard_conform.py | 4 ++- app/tests/test_standard_container.py | 3 +- app/tests/test_standard_controls.py | 16 +++++++---- app/tests/test_standard_definitions.py | 4 ++- app/tests/test_standard_environments.py | 5 +++- app/tests/test_standard_fidelity.py | 3 +- app/tests/test_standard_forward.py | 2 +- app/tests/test_standard_howto.py | 4 ++- app/tests/test_standard_install.py | 2 +- app/tests/test_standard_ledger.py | 4 +-- app/tests/test_standard_mcp_machine.py | 9 ++++-- app/tests/test_standard_options.py | 7 ++++- app/tests/test_standard_own_image.py | 5 +++- app/tests/test_standard_parts.py | 2 +- app/tests/test_standard_payload.py | 11 ++++---- app/tests/test_standard_recipe.py | 5 +++- app/tests/test_standard_relay.py | 12 ++++---- app/tests/test_standard_run.py | 28 +++++++++++-------- app/tests/test_standard_setup_checks.py | 4 ++- app/tests/test_standard_setups.py | 13 +++++---- app/tests/test_standard_shard.py | 2 +- app/tests/test_standard_skills.py | 6 +++- app/tests/test_standard_tau3_bench.py | 4 ++- app/tests/test_standard_tools_kit.py | 8 ++++-- app/tests/test_standard_trace.py | 2 +- app/tests/test_standard_ui.py | 4 ++- app/tests/test_standard_units.py | 6 +++- app/tests/test_standard_upstream_drivers.py | 6 +++- app/tests/test_standard_versions.py | 12 ++++---- app/tests/test_systemd_scope.py | 2 +- app/tests/test_tau3_setups.py | 4 ++- app/tests/test_unified_cli.py | 6 ++-- app/ui_tests/test_add_dialog.py | 2 +- app/ui_tests/test_agents.py | 4 +-- app/ui_tests/test_capped_job.py | 3 +- app/ui_tests/test_every_route.py | 4 +-- app/ui_tests/test_launch_shards.py | 2 +- app/ui_tests/test_licences_page.py | 4 +-- app/ui_tests/test_live_board.py | 2 +- app/ui_tests/test_prerequisites_route.py | 2 +- app/ui_tests/test_settings_page.py | 3 +- app/ui_tests/test_use_bundled.py | 2 +- app/web/agents.py | 7 +++-- app/web/builder.py | 7 +++-- app/web/catalogue.py | 6 ++-- app/web/execute.py | 2 +- app/web/filters.py | 3 +- app/web/runs.py | 2 +- app/web/settings.py | 4 +-- docs/agents/add-manually.md | 2 +- docs/benchmarks/osworld1-machine.md | 6 ++-- docs/cli/shard-and-merge.md | 4 +-- docs/field-guide.md | 2 +- docs/standard.md | 16 +++++------ pyproject.toml | 5 +++- 158 files changed, 487 insertions(+), 269 deletions(-) create mode 100644 app/nullius/standard/calls/__init__.py rename app/nullius/standard/{ => calls}/ledger.py (100%) rename app/nullius/standard/{ => calls}/relay.py (99%) create mode 100644 app/nullius/standard/containers/__init__.py rename app/nullius/standard/{ => containers}/container.py (99%) rename app/nullius/standard/{ => containers}/egress.py (100%) rename app/nullius/standard/{ => containers}/forward.py (100%) rename app/nullius/standard/{ => containers}/mcp_bridge.py (100%) rename app/nullius/standard/{ => containers}/mcp_machine.py (99%) rename app/nullius/standard/{ => containers}/setup_container.py (97%) rename app/nullius/standard/{ => containers}/web_services.py (100%) create mode 100644 app/nullius/standard/contract/__init__.py rename app/nullius/standard/{ => contract}/definitions.py (99%) rename app/nullius/standard/{ => contract}/match.py (96%) rename app/nullius/standard/{ => contract}/names.py (100%) rename app/nullius/standard/{ => contract}/ports.py (100%) create mode 100644 app/nullius/standard/pages/__init__.py rename app/nullius/standard/{ => pages}/howto.py (100%) rename app/nullius/standard/{ => pages}/recipe.py (99%) create mode 100644 app/nullius/standard/proofs/__init__.py rename app/nullius/standard/{ => proofs}/conform.py (98%) rename app/nullius/standard/{ => proofs}/fidelity.py (98%) rename app/nullius/standard/{ => proofs}/pins.py (100%) rename app/nullius/standard/{ => proofs}/prove.py (98%) create mode 100644 app/nullius/standard/protocols/__init__.py rename app/nullius/standard/{ => protocols}/acp.py (99%) rename app/nullius/standard/{ => protocols}/cancellation.py (100%) rename app/nullius/standard/{ => protocols}/jsonl.py (98%) create mode 100644 app/nullius/standard/requirements/__init__.py rename app/nullius/standard/{ => requirements}/hostreq.py (100%) rename app/nullius/standard/{ => requirements}/install.py (99%) rename app/nullius/standard/{ => requirements}/network_requirements.py (100%) create mode 100644 app/nullius/standard/runner/__init__.py rename app/nullius/standard/{ => runner}/job.py (99%) rename app/nullius/standard/{ => runner}/merge.py (99%) rename app/nullius/standard/{ => runner}/pace.py (100%) rename app/nullius/standard/{ => runner}/payload.py (99%) rename app/nullius/standard/{ => runner}/run.py (99%) rename app/nullius/standard/{ => runner}/shard.py (100%) diff --git a/.claude/skills/docs-drift/SKILL.md b/.claude/skills/docs-drift/SKILL.md index 70d982eb..49cdccef 100644 --- a/.claude/skills/docs-drift/SKILL.md +++ b/.claude/skills/docs-drift/SKILL.md @@ -50,7 +50,7 @@ or name the merge commit and diff its first parent. | changed under | read these, asking "does this paragraph still describe the code?" | | --- | --- | | `pyproject.toml`, `app/nullius/cli.py`, `app/nullius/__main__.py`, `app/nullius/paths.py`, `app/nullius/migrate.py` | README Quickstart; `docs/getting-started.md` installation and migration; `docs/cli/README.md`; `docs/settings/README.md` storage and precedence; AGENTS installation and dependency rules; preserve source commands as well as installed commands | - | `app/nullius/catalogue/storage.py`, `app/nullius/standard/definitions.py`, `app/nullius/standard/payload.py` | `docs/standard.md`, `docs/builder.md`, `docs/how-it-works.md`; all import skills and manual-add guides: user overlays versus bundled contributions, whole-folder selection, and runtime snapshots sent to hosts; generated Supported pages use explicit bundled roots | + | `app/nullius/catalogue/storage.py`, `app/nullius/standard/contract/definitions.py`, `app/nullius/standard/runner/payload.py` | `docs/standard.md`, `docs/builder.md`, `docs/how-it-works.md`; all import skills and manual-add guides: user overlays versus bundled contributions, whole-folder selection, and runtime snapshots sent to hosts; generated Supported pages use explicit bundled roots | | `app/nullius/runs/` | README "How to read a result"; `.claude/rules/running.md` "Interpreting results" and its runs-list paragraph (for `launches.py`); `docs/field-guide.md`, what each field it names means (`app/tests/test_field_guide.py` checks only that the names exist, the counts add up and the outcomes are the classifier's); `docs/how-it-works.md` "What you get back, page by page"; `docs/cli/` when a CLI changed | | `app/nullius/traces/` | `.claude/rules/traces.md` — the load-bearing rules and the filter, zoom and save rules are stated there, so a reader that changed shape drifts the rule, not only the README; README "How to read a result" | | `app/nullius/importers/` | README "Supported harnesses" (the table and the notes under it) and "Local by design"; `.claude/rules/running.md`, the import paragraph; `docs/cli/import.md`; the AGENTS map's `importers/` entry — the gate checks the registry's labels, you check the sentences | diff --git a/.claude/skills/import-agent/SKILL.md b/.claude/skills/import-agent/SKILL.md index f56f5d28..63eb33c7 100644 --- a/.claude/skills/import-agent/SKILL.md +++ b/.claude/skills/import-agent/SKILL.md @@ -49,7 +49,8 @@ with `PYTHONPATH="$PWD/app"` from the checkout root: "$NULLIUS_PY" - <<'PY' from nullius import paths, settings settings.load(paths.settings_file()) -from nullius.standard import definitions, howto +from nullius.standard.contract import definitions +from nullius.standard.pages import howto print("schema:", definitions.__file__) print("examples:", howto.__file__) print("catalogue:", paths.catalogue_dir()) @@ -145,7 +146,7 @@ See `docs/standard.md`, "Native capabilities and composition". `cli new agent KEY` (lower case letters, digits, dashes) writes `agents/KEY/agent.json` under the active user catalogue and prints its path. Fill it in, starting from -the shape `app/nullius/standard/howto.py` shows (`AGENT_JSON`, +the shape `app/nullius/standard/pages/howto.py` shows (`AGENT_JSON`, `AGENT_OPTIONS`) and the catalogue's agents (their shape, never their contents): diff --git a/.claude/skills/import-capability/SKILL.md b/.claude/skills/import-capability/SKILL.md index 7e4988c7..41d01071 100644 --- a/.claude/skills/import-capability/SKILL.md +++ b/.claude/skills/import-capability/SKILL.md @@ -50,7 +50,8 @@ command below from the checkout root: "$NULLIUS_PY" - <<'PY' from nullius import paths, settings settings.load(paths.settings_file()) -from nullius.standard import definitions, howto, ports +from nullius.standard.contract import definitions, ports +from nullius.standard.pages import howto for module in (definitions, howto, ports): print(module.__name__, module.__file__) print("catalogue:", paths.catalogue_dir()) @@ -89,7 +90,7 @@ below. CLI mutations protect bundled resources in source checkouts too. tool and write nothing of it before the yes. Without a way to ask (a subagent), report it as an open question and leave it unwritten. - **A kind with no port yet** (only `cap.memory/v1` exists today; see - `app/nullius/standard/ports.py`) is a generic change: a new port with a + `app/nullius/standard/contract/ports.py`) is a generic change: a new port with a kit, worded for every capability of its kind. Ask before adding it; this is a source contribution, not a user catalogue edit to installed core code. @@ -148,7 +149,7 @@ See `docs/standard.md`, "Native capabilities and composition". user catalogue, and a `capability.py` that already speaks `cap.memory/v1`. Use the writable paths the command prints. 2. **Wrap** in `capability.py` (the shape `FEATURE_PY` in - `app/nullius/standard/howto.py` shows): `add` gets a session `{id, date, + `app/nullius/standard/pages/howto.py` shows): `add` gets a session `{id, date, turns, text}` and stores it with the library's own call, replying `{}`; `recall` gets the question and replies `{"memory": }` from the library's own search; an error replies `{"error": ...}`. Send the diff --git a/.claude/skills/import-standard/SKILL.md b/.claude/skills/import-standard/SKILL.md index a09f7857..563d50d5 100644 --- a/.claude/skills/import-standard/SKILL.md +++ b/.claude/skills/import-standard/SKILL.md @@ -60,7 +60,8 @@ Python command below. Read module files, never edit an installed module: "$NULLIUS_PY" - <<'PY' from nullius import paths, settings settings.load(paths.settings_file()) -from nullius.standard import definitions, howto, ports +from nullius.standard.contract import definitions, ports +from nullius.standard.pages import howto from nullius.catalogue import catalog for module in (definitions, howto, ports, catalog): print(module.__name__, module.__file__) @@ -149,7 +150,7 @@ never a second key. Preserve both routes when it already runs through Harbor. Only the final message matters: `agent.task/v1`. A port too many shuts out agents for nothing; a port too few makes runs fail instead of being refused. - **A port that does not exist yet is a generic change, not a special case.** - Propose it as a new port with a kit (`app/nullius/standard/ports.py` and + Propose it as a new port with a kit (`app/nullius/standard/contract/ports.py` and `standard/kits//`), worded for every benchmark of its kind; never shape it after the one at hand. Ask before adding it. This requires a source contribution; a user catalogue cannot extend installed core code. diff --git a/.github/scripts/judge_pr.py b/.github/scripts/judge_pr.py index 83ab2151..feff3fae 100644 --- a/.github/scripts/judge_pr.py +++ b/.github/scripts/judge_pr.py @@ -323,7 +323,7 @@ def criteria_of(body: str) -> tuple: ("low", ()), ] MAJOR_FLOOR = ("app/nullius/standard/", "app/nullius/execution.py", "app/nullius/hosts.py", "app/nullius/secrets.py", - "app/nullius/runs/classify.py", "app/nullius/runs/parse.py", "app/nullius/standard/relay.py") + "app/nullius/runs/classify.py", "app/nullius/runs/parse.py", "app/nullius/standard/calls/relay.py") def split_diff(diff: str) -> list: diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.yml index 8ce8d77d..088efa37 100644 --- a/.github/workflows/docker-tests.yml +++ b/.github/workflows/docker-tests.yml @@ -34,7 +34,7 @@ jobs: - name: base image # The standard's one base image, and the fixture own image's FROM. run: | - PYTHONPATH=app python3 -c "from nullius.standard import container; print(container.base_image())" + PYTHONPATH=app python3 -c "from nullius.standard.containers import container; print(container.base_image())" docker pull --quiet ubuntu:24.04 - name: backend suite with the docker tier run: python3 app/tests/parallel.py --docker diff --git a/AGENTS.md b/AGENTS.md index 8a336c0c..30600e4a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,9 +60,16 @@ and its resources. The source layout stays under `app/`. `harbor/` (`source`: the Harbor a recipe pins - built, kept, scanned for its agents; `feed`: the live feed any Harbor writes, from its own trial hooks), `importers/` (`atif` ATIF, `otel` OpenTelemetry, and the `cli`), `judge/` (`questions`, `state`, `client`, `store`, `batch`, `reconcile`, `lanes`), - `standard/` (the Nullius standard, `docs/standard.md`: `ports`, `names` (capability vocabulary and legacy aliases), `definitions` (with an agent's or capability's versions), `match`, - `jsonl`, `acp`, `cancellation` (interruptible protocol waits), `relay`, `ledger` (a run's spending cap), `pins` (image digests checked against registry tags), `install`, `run`, `container` (the container backend), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `network_requirements` (an environment's declared public web access: the schema and the connectivity check), `hostreq` (what a benchmark's options need of the machine its driver runs on: the check and the install) and `egress` (an own image's check's proxy to public addresses), `job`, `conform`, `fidelity` (ACP against the agent's own CLI), `prove` (a benchmark's controls and proofs), `shard` and `merge` (one run over many machines), `recipe` (the builder's standard recipe), `howto` (the How to add steps) and the `cli`; its - `payload` snapshots the running backend and effective catalogue for a remote host; + `standard/` (the Nullius standard, `docs/standard.md`, one folder per purpose: + `contract/`: `ports`, `names` (capability vocabulary and legacy aliases), `definitions` (with an agent's or capability's versions), `match`; + `requirements/`, what a run needs of the machine: `install`, `hostreq` (what a benchmark's options need of the machine its driver runs on: the check and the install), `network_requirements` (an environment's declared public web access: the schema and the connectivity check); + `protocols/`: `jsonl`, `acp`, `cancellation` (interruptible protocol waits); + `calls/`: `relay`, `ledger` (a run's spending cap); + `containers/`: `container` (the container backend), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `egress` (an own image's check's proxy to public addresses); + `runner/`: `run`, `job`, `pace` (how soon the next unit starts after one ends rate-limited), `shard` and `merge` (one run over many machines), `payload` (a snapshot of the running backend and effective catalogue for a remote host); + `proofs/`: `conform`, `fidelity` (ACP against the agent's own CLI), `prove` (a benchmark's controls and proofs), `pins` (image digests checked against registry tags); + `pages/`: `recipe` (the builder's standard recipe), `howto` (the How to add steps); + and the `cli` at its top; conformance kits under `standard/kits/`, each a benchmark: a `driver` and, for the tools kit, an MCP server `mcp_kit`) - the definitions it reads are in the catalogue: a benchmark's `standard.json` and `driver` in its folder (τ³-bench's also the MCP diff --git a/app/nullius/catalogue/benchmarks/humaneval/driver.py b/app/nullius/catalogue/benchmarks/humaneval/driver.py index 67982b4a..d71ab885 100644 --- a/app/nullius/catalogue/benchmarks/humaneval/driver.py +++ b/app/nullius/catalogue/benchmarks/humaneval/driver.py @@ -57,7 +57,7 @@ sys.path.insert(0, os.environ["NULLIUS_UPSTREAM"]) from human_eval.data import read_problems # noqa: E402 as published from human_eval.execution import check_correctness # noqa: E402 -from nullius.standard.container import CHECK_IMAGE, check_argv # noqa: E402 +from nullius.standard.containers.container import CHECK_IMAGE, check_argv # noqa: E402 PROBLEMS = {} diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/driver.py b/app/nullius/catalogue/benchmarks/tau3-bench/driver.py index a0a2606c..08b2e8f3 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/driver.py +++ b/app/nullius/catalogue/benchmarks/tau3-bench/driver.py @@ -119,7 +119,7 @@ from tau2.runner.progress import run_with_retry from tau2.utils import load_file -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve from search_relay import route_qwen route_qwen(os.environ.get("NULLIUS_OPTION_RETRIEVAL")) diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py b/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py index d44211b6..aeaa1e0e 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py +++ b/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py @@ -21,7 +21,7 @@ ``TAU_DOMAIN`` names the domain (``airline``, ``retail``, ...), ``TAU_RETRIEVAL`` a knowledge domain's retrieval config. It runs on the machine in the driver's environment, never in the agent's container -(``mcp_servers`` in ``standard.json``; ``nullius.standard.mcp_machine``). +(``mcp_servers`` in ``standard.json``; ``nullius.standard.containers.mcp_machine``). """ import contextlib import copy diff --git a/app/nullius/constraints.py b/app/nullius/constraints.py index eab317a9..4b8ec516 100644 --- a/app/nullius/constraints.py +++ b/app/nullius/constraints.py @@ -49,7 +49,7 @@ container in the host's cgroup namespace reads. ``read`` turns what it printed into ``{capacity, enforced, refused, applied, systemd}``; ``save`` keeps that per machine, and ``warnings`` is what Settings says of a value against it. A run checks again on its own -engine and its own systemd before its first unit (``standard/run.py``). +engine and its own systemd before its first unit (``standard/runner/run.py``). """ from __future__ import annotations diff --git a/app/nullius/execution.py b/app/nullius/execution.py index c38811fa..99c50e26 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -31,7 +31,7 @@ it does not. A plan for the Nullius standard (``runner`` ``standard``, -``standard/recipe.py``) runs this repository's own ``cli`` from +``standard/pages/recipe.py``) runs this repository's own ``cli`` from ``$NULLIUS_STANDARD``: this repository here; from an installed wheel or on a host, a content-addressed copy of the backend and effective catalogue. Only code, definitions and their declared resources travel, never user @@ -41,7 +41,7 @@ (an agent's pip install builds with it), and docker when the plan says so (``docker``: a recipe on the container backend) - checked, like a Harbor run's, before anything is sent. A run split over several machines is one plan per -machine, each one shard (``standard/shard.py``). +machine, each one shard (``standard/runner/shard.py``). The target reads an explicit catalogue: the user's catalogue for a local run; on a host, a writable copy of the snapshot in the run's ``catalogue/``. @@ -124,7 +124,8 @@ from nullius import hosts, paths, prices as price_list, progress, redact, secrets, settings from nullius.harbor import source as harbor_source -from nullius.standard import container, payload as standard_payload +from nullius.standard.containers import container +from nullius.standard.runner import payload as standard_payload REMOTE_HOME = "~/.nullius" # on a host: tasks/, runs/, app/, harbor/ (a pinned Harbor's wheels) # The names the launcher gives a run's key and its endpoint (_launch), read @@ -140,7 +141,7 @@ LAUNCH_GRACE = 5.0 # seconds a restart waits for a part a launcher claimed to start (_settle) UV_INSTALL = "curl -LsSf https://astral.sh/uv/install.sh | sh" RECORD = "run.json" -STANDARD = "standard" # the Nullius standard's runner key (standard/recipe.py HARNESS) +STANDARD = "standard" # the Nullius standard's runner key (standard/pages/recipe.py HARNESS) REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # this repository: app/ is in it _NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$") _ID = re.compile(r"[^A-Za-z0-9_.-]") @@ -253,7 +254,7 @@ class Plan: jobs: List[dict] = field(default_factory=list) # the job directories the script writes: [{"name", "agent", "dataset"}] parts: List[dict] = field(default_factory=list) # the run, one agent at a time: [{"id", "label", "script"}]; empty: the whole script at once recipe: dict = field(default_factory=dict) # the builder's recipe the script was compiled from, so the run can be opened again as one; {} for a plan from before - runner: str = "harbor" # or "standard" (standard/recipe.py): the Nullius standard's own cli + runner: str = "harbor" # or "standard" (standard/pages/recipe.py): the Nullius standard's own cli harbor_pin: dict = field(default_factory=dict) # the Harbor the recipe pins (harbor/source.py pin_of); {} for a plan from before: the harbor on PATH docker: bool = False # a runner that needs docker on its target though it is not Harbor (the standard's container backend) keyless: bool = False # nothing in it calls a model (the standard's controls): handed no key and no endpoint at all @@ -350,7 +351,7 @@ def _licence_names() -> List[str]: own; a data provider's token (``provider``) is none, so a shell's reaches a Harbor run. A standard driver or agent never inherits it (``run.KEEP``).""" try: - from nullius.standard import definitions + from nullius.standard.contract import definitions return sorted({s["name"] for b in definitions.load("benchmark", every=True)[0] for s in definitions.secrets_of(b) if not s.get("provider")}) except Exception: diff --git a/app/nullius/hosts.py b/app/nullius/hosts.py index 3a4ebdea..a428eea0 100644 --- a/app/nullius/hosts.py +++ b/app/nullius/hosts.py @@ -247,7 +247,7 @@ def measure(host: Optional[Host], run: Optional[Callable] = None, timeout: float program = engine or "docker" options = ["--security-opt", "no-new-privileges", *(["--security-opt", "label=disable"] if program == "podman" else [])] else: - from nullius.standard import container + from nullius.standard.containers import container program, options = container.DOCKER, [*container._userns(), "--user", container._user(), *container._security_opt()] # with the engine program's environment, as a run's check and its units: what one sees, the others do run = run or (lambda argv, t: subprocess_run(argv, t, env=container.client_env())) diff --git a/app/nullius/onboarding.py b/app/nullius/onboarding.py index 5af93cfd..feebad3f 100644 --- a/app/nullius/onboarding.py +++ b/app/nullius/onboarding.py @@ -19,7 +19,7 @@ from typing import Callable, Iterable, Optional from nullius import providers -from nullius.standard import container +from nullius.standard.containers import container CONTROLS = ("nop", "oracle") PROVIDER_KEYS = ("OPENROUTER_API_KEY", "OPENAI_API_KEY", "MODEL_API_URL") diff --git a/app/nullius/prerequisites.py b/app/nullius/prerequisites.py index daaf3598..4af357a9 100644 --- a/app/nullius/prerequisites.py +++ b/app/nullius/prerequisites.py @@ -35,7 +35,8 @@ from typing import Callable, Dict, List, Optional from nullius import constraints, hosts -from nullius.standard import container, hostreq +from nullius.standard.containers import container +from nullius.standard.requirements import hostreq LABEL = {"engine": "Docker or Podman", "docker": "Docker", "uv": "uv", "harbor": "Harbor on PATH", "python3": "python3", "git": "git"} diff --git a/app/nullius/providers.py b/app/nullius/providers.py index 22c65bf3..3c431e98 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -238,7 +238,7 @@ def test(choice: str, env=None, *, opener=None, clock=time.monotonic) -> dict: if provider not in TESTED: raise ValueError("This provider has no test.") if provider == "anthropic": - from nullius.standard.relay import ANTHROPIC_VERSION + from nullius.standard.calls.relay import ANTHROPIC_VERSION base, key = ANTHROPIC[0], env.get(ANTHROPIC[1], "") auth, models = {"x-api-key": key, "anthropic-version": ANTHROPIC_VERSION}, base + "/models?limit=1000" else: diff --git a/app/nullius/recipes/launch.py b/app/nullius/recipes/launch.py index 3bf99551..aa371672 100644 --- a/app/nullius/recipes/launch.py +++ b/app/nullius/recipes/launch.py @@ -57,17 +57,17 @@ def parameter(key, label, group, kind, default=None, *, help="", **extra): def payload(cat, jobs, workspace_name=""): from nullius import providers - from nullius.standard import recipe as standard + from nullius.standard.pages import recipe as standard models = sorted({j.model_name for j in jobs if j.model_name}) dated = [j for j in jobs if j.model_name and j.started_at] latest = max(dated, key=lambda j: j.started_at.timestamp()).model_name if dated else "" return { "version": 1, "workspace": workspace_name or "unassigned", "agents": AGENTS, - # Harbor and the Nullius standard: the page offers choices, the core and standard/recipe.py compile them. + # Harbor and the Nullius standard: the page offers choices, the core and standard/pages/recipe.py compile them. "runners": [standard.RUNNER, providers.HARBOR], # why a saved recipe of a runner no longer offered does not open (a benchmark's own scripts: its Original setup) "runnerGone": providers.GONE, - # the standard's benchmarks, agents and capabilities, and why a pair does not fit (standard/recipe.py, choices) + # the standard's benchmarks, agents and capabilities, and why a pair does not fit (standard/pages/recipe.py, choices) "standard": standard.choices(), "parameters": PARAMETERS, "benchmarks": [asdict(b) | {"label": b.label} for b in cat.benchmarks], "datasets": [asdict(d) | LAUNCH.get(d.key, {}) for d in cat.datasets], diff --git a/app/nullius/runs/launches.py b/app/nullius/runs/launches.py index 1295ea02..0a978077 100644 --- a/app/nullius/runs/launches.py +++ b/app/nullius/runs/launches.py @@ -33,7 +33,7 @@ from datetime import datetime, timezone from nullius.runs.parse import _budget, _iso -from nullius.standard import merge +from nullius.standard.runner import merge WINDOW_SEC = 30 * 60 diff --git a/app/nullius/sandbox.py b/app/nullius/sandbox.py index a491268f..540217d6 100644 --- a/app/nullius/sandbox.py +++ b/app/nullius/sandbox.py @@ -22,7 +22,7 @@ import subprocess from typing import List, Optional -from nullius.standard import container +from nullius.standard.containers import container REGISTRY = "https://index.docker.io/v1/" # Docker Hub, as docker names it in its config HUB = "docker.io" # as podman names it: without it, podman logs in to its first search registry diff --git a/app/nullius/secrets.py b/app/nullius/secrets.py index 5ca41be0..1c6ecb3f 100644 --- a/app/nullius/secrets.py +++ b/app/nullius/secrets.py @@ -15,7 +15,7 @@ ``index.json`` beside them says, per name, when it was set, when it expires (when said), its kind and the file it came from - never the value. A page reads :func:`status` or :func:`state`; only a run reads :func:`value` or -:func:`path`, when a unit starts (``standard/run.py``), or to send it to a +:func:`path`, when a unit starts (``standard/runner/run.py``), or to send it to a host over stdin (``execution``). Standard library only. """ from __future__ import annotations diff --git a/app/nullius/standard/__init__.py b/app/nullius/standard/__init__.py index a0b0f822..8cd7cef7 100644 --- a/app/nullius/standard/__init__.py +++ b/app/nullius/standard/__init__.py @@ -1,15 +1,23 @@ """The Nullius standard: benchmarks, agents and capabilities, matched by ports. A benchmark *needs* ports, an agent or a capability *offers* them, and a pair fits -when every port the benchmark needs is offered and proven (``match``). A port -is a versioned contract (``ports``) with a conformance kit, a tiny benchmark +when every port the benchmark needs is offered and proven (``contract.match``). A port +is a versioned contract (``contract.ports``) with a conformance kit, a tiny benchmark run against the agent or capability before its claim is written down -(``conform``). The definitions are files in the catalogue (``definitions``). +(``proofs.conform``). The definitions are files in the catalogue (``contract.definitions``). -A run (``run``) sets each unit up with the benchmark's driver (``jsonl``), -drives the agent over ACP (``acp``) with the benchmark's environment as MCP +A run (``runner.run``) sets each unit up with the benchmark's driver (``protocols.jsonl``), +drives the agent over ACP (``protocols.acp``) with the benchmark's environment as MCP servers, sends every model call through a relay that holds the key and records -the call (``relay``), scores the unit with the driver, and writes a job in -Harbor's shape (``job``) that the rest of the application reads unchanged. +the call (``calls.relay``), scores the unit with the driver, and writes a job in +Harbor's shape (``runner.job``) that the rest of the application reads unchanged. ``docs/standard.md`` is the design. + +One folder per purpose: ``contract`` (what a definition may say, which pairs fit), +``requirements`` (what a run needs of the machine), ``protocols`` (ACP and JSON +lines), ``calls`` (the relay and the spending cap), ``containers`` (the container +backend and its doors), ``runner`` (a run, on one machine or several), ``proofs`` +(kits, fidelity, a benchmark's controls) and ``pages`` (the builder's recipe, the How +to add steps). ``cli`` is the shell command over all of them; ``kits/`` holds the +conformance kits, each a benchmark. """ diff --git a/app/nullius/standard/calls/__init__.py b/app/nullius/standard/calls/__init__.py new file mode 100644 index 00000000..5bd24ead --- /dev/null +++ b/app/nullius/standard/calls/__init__.py @@ -0,0 +1,6 @@ +"""A run's model calls: relayed, recorded, capped. + +``relay`` is the model endpoint every agent, driver and capability of a run is +given: it holds the key and records each call. ``ledger`` is the run's spending +cap, the one file every relay of a job books its calls in. +""" diff --git a/app/nullius/standard/ledger.py b/app/nullius/standard/calls/ledger.py similarity index 100% rename from app/nullius/standard/ledger.py rename to app/nullius/standard/calls/ledger.py diff --git a/app/nullius/standard/relay.py b/app/nullius/standard/calls/relay.py similarity index 99% rename from app/nullius/standard/relay.py rename to app/nullius/standard/calls/relay.py index a8c59455..ecd54dd1 100644 --- a/app/nullius/standard/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -45,7 +45,7 @@ from typing import Dict, List, Optional from nullius.redact import redact -from nullius.standard import ledger as ledgers +from nullius.standard.calls import ledger as ledgers PLACEHOLDER_KEY = "nullius-relay" _TAG = re.compile(r"^[A-Za-z0-9_-]{1,64}$") @@ -723,7 +723,7 @@ def failure(calls: List[dict]) -> Optional[tuple]: # -- the relay as a process of its own: a container backend's sidecar ---------- def serve(argv=None) -> int: - """``python3 -m nullius.standard.relay serve --listen HOST:PORT --base URL + """``python3 -m nullius.standard.calls.relay serve --listen HOST:PORT --base URL --record DIR --key-file PATH [--model M] [--route TAG=MODEL ...] [--side-model M ...] [--key-header NAME] [--public URL] [--prices JSON] [--ledger FILE]``. @@ -735,7 +735,7 @@ def serve(argv=None) -> int: is ready; SIGTERM (or SIGINT) stops it.""" import argparse import signal - ap = argparse.ArgumentParser(prog="nullius.standard.relay serve") + ap = argparse.ArgumentParser(prog="nullius.standard.calls.relay serve") ap.add_argument("--listen", default="127.0.0.1:0", help="HOST:PORT") ap.add_argument("--base", required=True, help="the provider's endpoint") ap.add_argument("--record", required=True, help="the folder each route's calls are recorded in") @@ -781,5 +781,5 @@ def serve(argv=None) -> int: if __name__ == "__main__": import sys if sys.argv[1:2] != ["serve"]: - sys.exit("python3 -m nullius.standard.relay serve --listen HOST:PORT --base URL --record DIR --key-file PATH [--model M]") + sys.exit("python3 -m nullius.standard.calls.relay serve --listen HOST:PORT --base URL --record DIR --key-file PATH [--model M]") sys.exit(serve(sys.argv[2:])) diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 56be6ddb..14a34a44 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -18,11 +18,11 @@ an agent's run or conformance check there is refused without ``--unsandboxed``. ``--backend container`` (``docker``, its earlier name) runs each unit's agent or capability in a container whose only way out is the unit's relay, or a public web proxy when its environment -declares ``network`` (``standard/container.py``), and needs no such yes. +declares ``network`` (``standard/containers/container.py``), and needs no such yes. A benchmark's control (``nop``, ``oracle``: its ``controls``) runs no agent and calls no model - only a judged benchmark's judge - so it asks for neither. ``prove`` runs a benchmark's controls and checks its units and that nothing -leaks, and writes what passed into its ``proven`` (``standard/prove.py``). +leaks, and writes what passed into its ``proven`` (``standard/proofs/prove.py``). A benchmark, an agent or a capability is named by its key (its default version) or ``key@version``. ``list`` shows every definition - each version - and which @@ -35,12 +35,12 @@ each check K times, held by a majority); ``run`` runs a benchmark into a job under ``--jobs`` (``jobs_standard/``), which the application opens like any other; ``fidelity`` drives an agent over ACP and through its own command, compares the requests its model was sent, and -writes the verdict into the definition (``standard/fidelity.py``). ``--shard I/N`` runs one -shard of the dataset's units (``standard/shard.py``: by the unit id's hash, then +writes the verdict into the definition (``standard/proofs/fidelity.py``). ``--shard I/N`` runs one +shard of the dataset's units (``standard/runner/shard.py``: by the unit id's hash, then ``--limit``), the job recording its shard and its launch (``--launch``); ``--units FILE`` runs only the units a file lists (``run.units_file``: one id a line), read on the machine the command runs on, ``--from-run`` or not; ``merge`` -puts a launch's shard jobs together into one job (``standard/merge.py``). ``--option`` +puts a launch's shard jobs together into one job (``standard/runner/merge.py``). ``--option`` sets one of the agent's or capability's options (``options`` in its definition); the rest keep the vendor's defaults, and the job's config records them all. A run says each stage before its first unit, and each unit's end, as one @@ -49,7 +49,7 @@ Keys come from the process environment, then the saved user settings - the file the Settings page edits. Nothing is printed of them. With ``--from-run`` (a run -the builder or a page started, ``standard/recipe.py``) saved settings are not +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 benchmark's environments declare are never in either: the run reads them from @@ -72,7 +72,9 @@ if __name__ == "__main__" and "--from-run" not in sys.argv[1:]: settings.load(paths.settings_file()) -from nullius.standard import conform, definitions, fidelity, job, match, merge, pins, ports, prove, run, shard +from nullius.standard.contract import definitions, match, ports +from nullius.standard.proofs import conform, fidelity, pins, prove +from nullius.standard.runner import job, merge, run, shard ENV_FILE = paths.settings_file() @@ -132,7 +134,7 @@ def older(d: dict, ports_=None) -> list: def skills(d: dict, ports_=None) -> list: """``agent.tools/v1 skills: decoys ✗ · chain ✓ · retry ✗``, for each port ``d`` offers (of ``ports_``, when given) whose kit has skills.""" - from nullius.standard.recipe import skills_of + from nullius.standard.pages.recipe import skills_of proven, out = d.get("proven") or {}, [] for p in d.get("offers") or []: got = skills_of(p, proven.get(p)) if ports_ is None or p in ports_ else [] diff --git a/app/nullius/standard/containers/__init__.py b/app/nullius/standard/containers/__init__.py new file mode 100644 index 00000000..45f7126a --- /dev/null +++ b/app/nullius/standard/containers/__init__.py @@ -0,0 +1,14 @@ +"""The container backend, and the doors through it. + +``container`` runs each unit's agent or capability in a container of its own, +its relay beside it; ``setup_container`` runs an Original setup's driver in +one. The rest is what crosses the boundary, one address at a time: ``forward`` +(a licence server, or a server on the machine), ``egress`` (an own image's +check, to public addresses only), ``mcp_machine`` and ``mcp_bridge`` (a +benchmark's MCP server run on the machine, and the agent's bridge to it) and +``web_services`` (the HTTP fixtures a driver's setup declares). + +``forward.py``, ``egress.py`` and ``mcp_bridge.py`` are each mounted alone into +a container and run there: they import nothing of this application, and +``container`` and ``mcp_machine`` find them beside themselves. +""" diff --git a/app/nullius/standard/container.py b/app/nullius/standard/containers/container.py similarity index 99% rename from app/nullius/standard/container.py rename to app/nullius/standard/containers/container.py index bafb447c..57a3e3ad 100644 --- a/app/nullius/standard/container.py +++ b/app/nullius/standard/containers/container.py @@ -38,7 +38,7 @@ **The relay is a sidecar, and the agent's only way out** but for the public web proxy of an environment that declares ``network``. Per unit, an internal network (``docker network create --internal``: no route off it); a -relay container (``python3 -m nullius.standard.relay serve``) on the default +relay container (``python3 -m nullius.standard.calls.relay serve``) on the default bridge *and* on that network as ``relay``; the agent's container on the internal network alone. Its model endpoint is ``http://relay:8080//v1`` and nothing else answers it. The real key reaches the relay's container @@ -127,7 +127,8 @@ from typing import Dict, Iterable, List, Optional, Tuple from nullius import constraints, paths -from nullius.standard import definitions, install +from nullius.standard.contract import definitions +from nullius.standard.requirements import install def _runs_podman(path: str) -> bool: """Whether the program at ``path`` is podman under another name: a link to @@ -740,7 +741,7 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi *(["-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, "-e", "PYTHONPATH=" + app, "-e", "PYTHONDONTWRITEBYTECODE=1", - image, "python3", "-m", "nullius.standard.relay", "serve", "--listen", f"0.0.0.0:{RELAY_PORT}", + 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}"] if model: a += ["--model", model] @@ -1144,7 +1145,7 @@ def _door(self, name: str, alias: str, port: int, sock: str, what: str) -> None: if platform.system() == "Darwin": # Docker Desktop cannot connect to host Unix sockets through a # file mount. Expose only this socket via a loopback TCP bridge. - from nullius.standard import forward + from nullius.standard.containers import forward nonce = token_hex(32) class Handler(socketserver.BaseRequestHandler): def handle(self): diff --git a/app/nullius/standard/egress.py b/app/nullius/standard/containers/egress.py similarity index 100% rename from app/nullius/standard/egress.py rename to app/nullius/standard/containers/egress.py diff --git a/app/nullius/standard/forward.py b/app/nullius/standard/containers/forward.py similarity index 100% rename from app/nullius/standard/forward.py rename to app/nullius/standard/containers/forward.py diff --git a/app/nullius/standard/mcp_bridge.py b/app/nullius/standard/containers/mcp_bridge.py similarity index 100% rename from app/nullius/standard/mcp_bridge.py rename to app/nullius/standard/containers/mcp_bridge.py diff --git a/app/nullius/standard/mcp_machine.py b/app/nullius/standard/containers/mcp_machine.py similarity index 99% rename from app/nullius/standard/mcp_machine.py rename to app/nullius/standard/containers/mcp_machine.py index 09d59755..985c352f 100644 --- a/app/nullius/standard/mcp_machine.py +++ b/app/nullius/standard/containers/mcp_machine.py @@ -42,7 +42,7 @@ import threading from typing import List, Optional, Tuple -from nullius.standard import install +from nullius.standard.requirements import install BRIDGE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mcp_bridge.py") DOOR_PORT = 9000 # where a door listens, on the unit's network diff --git a/app/nullius/standard/setup_container.py b/app/nullius/standard/containers/setup_container.py similarity index 97% rename from app/nullius/standard/setup_container.py rename to app/nullius/standard/containers/setup_container.py index 89409291..e1136c57 100644 --- a/app/nullius/standard/setup_container.py +++ b/app/nullius/standard/containers/setup_container.py @@ -20,7 +20,10 @@ import uuid from urllib.parse import urlsplit -from nullius.standard import container, definitions, hostreq, install, jsonl +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import hostreq, install UV_VERSION = "0.13.4" CREDENTIALS_IN = "/opt/nullius/credentials" # the driver's credentials' one file, in its container @@ -79,7 +82,7 @@ def command(self, env, cwd, *, prepare=False, files=(), credentials=None): UV_CACHE_DIR=os.path.join(self.cache, "uv-cache"), UV_PYTHON_INSTALL_DIR=os.path.join(self.cache, "python")) name = "nullius-setup-" + uuid.uuid4().hex[:20] - cmd = ["python3", "-m", "nullius.standard.setup_container", self.config, self.cache, + cmd = ["python3", "-m", "nullius.standard.containers.setup_container", self.config, self.cache, "prepare" if prepare else "run"] + ([CREDENTIALS_IN] if credentials else []) argv = container.run_argv(self.image, cmd, name=name, network=container.BRIDGE if container.podman() else "bridge", job=self.job, workdir=cwd, mounted=mounts, env=values, path=container.IMAGE_PATH) diff --git a/app/nullius/standard/web_services.py b/app/nullius/standard/containers/web_services.py similarity index 100% rename from app/nullius/standard/web_services.py rename to app/nullius/standard/containers/web_services.py diff --git a/app/nullius/standard/contract/__init__.py b/app/nullius/standard/contract/__init__.py new file mode 100644 index 00000000..e9b008c3 --- /dev/null +++ b/app/nullius/standard/contract/__init__.py @@ -0,0 +1,7 @@ +"""The contract: what a definition may say, and which pairs fit. + +``ports`` names each port of version 1 and the kit that proves it, ``names`` the +canonical vocabulary and the earlier names still read, ``definitions`` the three +definition files - a benchmark's, an agent's, a capability's - with what each +may say, and ``match`` which pairs fit and why the others do not. +""" diff --git a/app/nullius/standard/definitions.py b/app/nullius/standard/contract/definitions.py similarity index 99% rename from app/nullius/standard/definitions.py rename to app/nullius/standard/contract/definitions.py index 125c2b2f..5152ec2b 100644 --- a/app/nullius/standard/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -29,7 +29,7 @@ capability and no model of its own; ``nop`` and ``oracle`` are the words Harbor calls its controls by, so the runs pages read the jobs as controls. A benchmark's ``proven`` is what ``cli prove`` found, per dataset -(``standard/prove.py``). +(``standard/proofs/prove.py``). A benchmark's **setups** are driver methods behind one Original procedure. ``original`` uses the upstream's model selection; ``model`` substitutes the @@ -81,14 +81,14 @@ import re from typing import Callable, Dict, List, Optional, Tuple -from nullius.standard import ports +from nullius.standard.contract import ports from nullius import paths from nullius.catalogue import storage from . import names -HERE = os.path.dirname(os.path.abspath(__file__)) -CATALOGUE = os.path.join(os.path.dirname(HERE), "catalogue") -KITS = os.path.join(HERE, "kits") +STANDARD = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # the standard's folder, which holds this one +CATALOGUE = os.path.join(os.path.dirname(STANDARD), "catalogue") +KITS = os.path.join(STANDARD, "kits") KINDS = { "benchmark": {"schema": "nullius.benchmark/v1", "dir": "benchmarks", "file": "standard.json"}, @@ -885,7 +885,7 @@ def _environments(envs, here: Optional[str]) -> List[str]: if "local_ok" in e and not isinstance(e["local_ok"], bool): bad.append(f"{w}.local_ok: true or false") if "network" in e: - from . import network_requirements + from ..requirements import network_requirements bad += [f"{w}.{message}" for message in network_requirements.problems(e["network"])] bad += _secrets(w, e.get("needs_secrets"), bool(e.get("local_ok")), settings) kinds: Dict[str, set] = {} diff --git a/app/nullius/standard/match.py b/app/nullius/standard/contract/match.py similarity index 96% rename from app/nullius/standard/match.py rename to app/nullius/standard/contract/match.py index a1c875b1..1a6a181d 100644 --- a/app/nullius/standard/match.py +++ b/app/nullius/standard/contract/match.py @@ -12,8 +12,8 @@ from typing import Dict, List -from nullius.standard import ports -from nullius.standard.definitions import CONTROLS, port_skills, ref_of, skills_shown +from nullius.standard.contract import ports +from nullius.standard.contract.definitions import CONTROLS, port_skills, ref_of, skills_shown def fit(bench: dict, other: dict) -> List[str]: diff --git a/app/nullius/standard/names.py b/app/nullius/standard/contract/names.py similarity index 100% rename from app/nullius/standard/names.py rename to app/nullius/standard/contract/names.py diff --git a/app/nullius/standard/ports.py b/app/nullius/standard/contract/ports.py similarity index 100% rename from app/nullius/standard/ports.py rename to app/nullius/standard/contract/ports.py diff --git a/app/nullius/standard/kits/agent-conversation-v1/driver.py b/app/nullius/standard/kits/agent-conversation-v1/driver.py index f61cba17..ed65fa13 100644 --- a/app/nullius/standard/kits/agent-conversation-v1/driver.py +++ b/app/nullius/standard/kits/agent-conversation-v1/driver.py @@ -1,5 +1,5 @@ """Kit for agent.conversation/v1: the second turn needs the first.""" -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve CODES = {"c1": "heron-42", "c2": "maple-17"} diff --git a/app/nullius/standard/kits/agent-search-v1/driver.py b/app/nullius/standard/kits/agent-search-v1/driver.py index f8c29750..36efb317 100644 --- a/app/nullius/standard/kits/agent-search-v1/driver.py +++ b/app/nullius/standard/kits/agent-search-v1/driver.py @@ -18,8 +18,8 @@ from urllib.parse import parse_qs, urlsplit, quote from urllib.request import urlopen -from nullius.standard.container import CHECK_IMAGE -from nullius.standard.jsonl import serve +from nullius.standard.containers.container import CHECK_IMAGE +from nullius.standard.protocols.jsonl import serve UNITS = ('find-source', 'disambiguate', 'follow-reference') FIXTURES = {} diff --git a/app/nullius/standard/kits/agent-task-v1/driver.py b/app/nullius/standard/kits/agent-task-v1/driver.py index c36b3a59..d9f33b4c 100644 --- a/app/nullius/standard/kits/agent-task-v1/driver.py +++ b/app/nullius/standard/kits/agent-task-v1/driver.py @@ -1,5 +1,5 @@ """Kit for agent.task/v1: the answer is the agent's final message.""" -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve WORDS = {"t1": "lantern", "t2": "quartz", "t3": "meadow"} diff --git a/app/nullius/standard/kits/agent-tools-v1/driver.py b/app/nullius/standard/kits/agent-tools-v1/driver.py index c7c444a7..0b034c54 100644 --- a/app/nullius/standard/kits/agent-tools-v1/driver.py +++ b/app/nullius/standard/kits/agent-tools-v1/driver.py @@ -22,8 +22,8 @@ import secrets import sys -from nullius.standard.container import CHECK_IMAGE -from nullius.standard.jsonl import serve +from nullius.standard.containers.container import CHECK_IMAGE +from nullius.standard.protocols.jsonl import serve HERE = os.path.dirname(os.path.abspath(__file__)) _spec = importlib.util.spec_from_file_location("nullius_kit_mcp", os.path.join(HERE, "mcp_kit.py")) diff --git a/app/nullius/standard/kits/agent-workspace-v1/driver.py b/app/nullius/standard/kits/agent-workspace-v1/driver.py index 21d72fa2..10f04561 100644 --- a/app/nullius/standard/kits/agent-workspace-v1/driver.py +++ b/app/nullius/standard/kits/agent-workspace-v1/driver.py @@ -4,8 +4,8 @@ import subprocess import sys -from nullius.standard.container import check_argv -from nullius.standard.jsonl import serve +from nullius.standard.containers.container import check_argv +from nullius.standard.protocols.jsonl import serve CALC = "def add(a, b):\n return a - b\n" TEST = "from calc import add\nassert add(2, 3) == 5, add(2, 3)\nprint('OK')\n" diff --git a/app/nullius/standard/kits/cap-memory-v1/driver.py b/app/nullius/standard/kits/cap-memory-v1/driver.py index f78f05ce..299debc9 100644 --- a/app/nullius/standard/kits/cap-memory-v1/driver.py +++ b/app/nullius/standard/kits/cap-memory-v1/driver.py @@ -1,5 +1,5 @@ """Kit for cap.memory/v1: add sessions, recall for a question, the fact must come back.""" -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve FILLER = ["We discussed the train timetable for the weekend.", "The weather was cold and grey all morning.", "I watched a documentary about volcanoes.", "Dinner plans changed to a quiet night in.", diff --git a/app/nullius/standard/pages/__init__.py b/app/nullius/standard/pages/__init__.py new file mode 100644 index 00000000..ed85f282 --- /dev/null +++ b/app/nullius/standard/pages/__init__.py @@ -0,0 +1,7 @@ +"""The standard as the application's pages show it. + +``recipe`` gives the run builder its choices and compiles a recipe into the +command a run starts with, and the check or proof an Agents, Capabilities or +Benchmarks page starts. ``howto`` is the How to add steps of the Agents and +Capabilities tabs. +""" diff --git a/app/nullius/standard/howto.py b/app/nullius/standard/pages/howto.py similarity index 100% rename from app/nullius/standard/howto.py rename to app/nullius/standard/pages/howto.py diff --git a/app/nullius/standard/recipe.py b/app/nullius/standard/pages/recipe.py similarity index 99% rename from app/nullius/standard/recipe.py rename to app/nullius/standard/pages/recipe.py index 9e397d1c..a78b893f 100644 --- a/app/nullius/standard/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -40,7 +40,10 @@ from nullius import constraints as limits, hosts, providers from nullius.providers import PROVIDERS, STEP -from nullius.standard import hostreq, definitions, ledger, match, ports, prove +from nullius.standard.calls import ledger +from nullius.standard.contract import definitions, match, ports +from nullius.standard.proofs import prove +from nullius.standard.requirements import hostreq HARNESS = "standard" # The builder's runner card (command-builder-core.js, runners()): not a definition file, so builtin like Harbor's. @@ -675,7 +678,7 @@ def conformance(kind: str, key: str, *, model: str, provider: str, unsandboxed: """The check an Agents or Capabilities page starts: every kit the agent or capability can take, as one command (``cli conform``), the jobs it will write named ahead (``conform.job_name``). {errors, script, jobs, label}.""" - from nullius.standard import conform + from nullius.standard.proofs import conform o = definitions.get(kind, key) if kind in ("agent", "capability") else None errors = [] if o is None: diff --git a/app/nullius/standard/proofs/__init__.py b/app/nullius/standard/proofs/__init__.py new file mode 100644 index 00000000..bf51bb9e --- /dev/null +++ b/app/nullius/standard/proofs/__init__.py @@ -0,0 +1,7 @@ +"""What is proven before it is offered. + +``conform`` runs a port's kit against an agent or a capability. ``fidelity`` +compares an agent driven over ACP with its own CLI. ``prove`` runs a +benchmark's controls and checks. ``pins`` compares a benchmark's image pins +with their registry tags. The kits themselves are in ``standard/kits/``. +""" diff --git a/app/nullius/standard/conform.py b/app/nullius/standard/proofs/conform.py similarity index 98% rename from app/nullius/standard/conform.py rename to app/nullius/standard/proofs/conform.py index ea378a28..0d515179 100644 --- a/app/nullius/standard/conform.py +++ b/app/nullius/standard/proofs/conform.py @@ -28,7 +28,8 @@ from typing import Callable, Dict, List, Optional from nullius.runs import parse -from nullius.standard import definitions, ports, run +from nullius.standard.contract import definitions, ports +from nullius.standard.runner import run STAMP = "%Y-%m-%d__%H-%M-%S" diff --git a/app/nullius/standard/fidelity.py b/app/nullius/standard/proofs/fidelity.py similarity index 98% rename from app/nullius/standard/fidelity.py rename to app/nullius/standard/proofs/fidelity.py index bc60de26..d0268e08 100644 --- a/app/nullius/standard/fidelity.py +++ b/app/nullius/standard/proofs/fidelity.py @@ -30,7 +30,11 @@ from typing import Callable, Dict, List, Optional from nullius import prices as price_list -from nullius.standard import definitions, install, jsonl, relay, run +from nullius.standard.calls import relay +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install +from nullius.standard.runner import run SIDES = ("acp", "cli") # Fields that label a request for the vendor - ids, cache keys, analytics - diff --git a/app/nullius/standard/pins.py b/app/nullius/standard/proofs/pins.py similarity index 100% rename from app/nullius/standard/pins.py rename to app/nullius/standard/proofs/pins.py diff --git a/app/nullius/standard/prove.py b/app/nullius/standard/proofs/prove.py similarity index 98% rename from app/nullius/standard/prove.py rename to app/nullius/standard/proofs/prove.py index 59ad318e..cb29722b 100644 --- a/app/nullius/standard/prove.py +++ b/app/nullius/standard/proofs/prove.py @@ -49,7 +49,10 @@ from typing import Callable, Dict, List, Optional from nullius.runs import parse -from nullius.standard import definitions, install, jsonl, run, shard as shards +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install +from nullius.standard.runner import run, shard as shards STAMP = "%Y-%m-%d__%H-%M-%S" SHORT = 12 # characters: a reference shorter than this is not looked for diff --git a/app/nullius/standard/protocols/__init__.py b/app/nullius/standard/protocols/__init__.py new file mode 100644 index 00000000..a0a32128 --- /dev/null +++ b/app/nullius/standard/protocols/__init__.py @@ -0,0 +1,7 @@ +"""How Nullius speaks to the programs it starts. + +``acp`` is the ACP client that drives an agent. ``jsonl`` is the JSON lines a +benchmark's driver and a capability are spoken to in, and ``serve``, the other +side, for one written in Python. ``cancellation`` is the wait both give up when +their run stops. +""" diff --git a/app/nullius/standard/acp.py b/app/nullius/standard/protocols/acp.py similarity index 99% rename from app/nullius/standard/acp.py rename to app/nullius/standard/protocols/acp.py index 464d7c00..8d4ba933 100644 --- a/app/nullius/standard/acp.py +++ b/app/nullius/standard/protocols/acp.py @@ -34,7 +34,7 @@ import os import queue from concurrent.futures import CancelledError -from nullius.standard.cancellation import reply +from nullius.standard.protocols.cancellation import reply import signal import subprocess import threading diff --git a/app/nullius/standard/cancellation.py b/app/nullius/standard/protocols/cancellation.py similarity index 100% rename from app/nullius/standard/cancellation.py rename to app/nullius/standard/protocols/cancellation.py diff --git a/app/nullius/standard/jsonl.py b/app/nullius/standard/protocols/jsonl.py similarity index 98% rename from app/nullius/standard/jsonl.py rename to app/nullius/standard/protocols/jsonl.py index 98bf61fd..69d63c57 100644 --- a/app/nullius/standard/jsonl.py +++ b/app/nullius/standard/protocols/jsonl.py @@ -13,7 +13,7 @@ import os import queue from concurrent.futures import CancelledError -from nullius.standard.cancellation import reply as wait_reply +from nullius.standard.protocols.cancellation import reply as wait_reply import signal import subprocess import threading diff --git a/app/nullius/standard/requirements/__init__.py b/app/nullius/standard/requirements/__init__.py new file mode 100644 index 00000000..2571a8a5 --- /dev/null +++ b/app/nullius/standard/requirements/__init__.py @@ -0,0 +1,8 @@ +"""What a run needs of the machine before its first unit. + +``install`` puts what a definition names - an agent's or a capability's +packages, a driver's environment, an upstream, a dataset - under +``STANDARD_DIR``, once. ``hostreq`` checks the programs and the GPU memory a +benchmark's ``host`` asks for, and says the commands that install them. +``network_requirements`` checks the public web access an environment declares. +""" diff --git a/app/nullius/standard/hostreq.py b/app/nullius/standard/requirements/hostreq.py similarity index 100% rename from app/nullius/standard/hostreq.py rename to app/nullius/standard/requirements/hostreq.py diff --git a/app/nullius/standard/install.py b/app/nullius/standard/requirements/install.py similarity index 99% rename from app/nullius/standard/install.py rename to app/nullius/standard/requirements/install.py index c4108856..06fd46a9 100644 --- a/app/nullius/standard/install.py +++ b/app/nullius/standard/requirements/install.py @@ -42,7 +42,7 @@ import subprocess from typing import Callable, Dict, List, Optional -from nullius.standard import definitions +from nullius.standard.contract import definitions from nullius import paths diff --git a/app/nullius/standard/network_requirements.py b/app/nullius/standard/requirements/network_requirements.py similarity index 100% rename from app/nullius/standard/network_requirements.py rename to app/nullius/standard/requirements/network_requirements.py diff --git a/app/nullius/standard/runner/__init__.py b/app/nullius/standard/runner/__init__.py new file mode 100644 index 00000000..5885999e --- /dev/null +++ b/app/nullius/standard/runner/__init__.py @@ -0,0 +1,8 @@ +"""A run, from its units to its job, on one machine or several. + +``run`` sets each unit up, produces and scores it. ``job`` writes the result as +a job in Harbor's shape. ``pace`` slows the start of units when the provider +says the run goes too fast. ``shard`` and ``merge`` split one launch over +several machines and put its jobs back together; ``payload`` is the snapshot of +this runner a host is sent. +""" diff --git a/app/nullius/standard/job.py b/app/nullius/standard/runner/job.py similarity index 99% rename from app/nullius/standard/job.py rename to app/nullius/standard/runner/job.py index 683d4e14..60784df7 100644 --- a/app/nullius/standard/job.py +++ b/app/nullius/standard/runner/job.py @@ -29,7 +29,7 @@ from datetime import datetime, timezone from typing import Dict, List, Optional -from nullius.standard import ledger +from nullius.standard.calls import ledger from nullius.traces import otel, trace @@ -337,7 +337,7 @@ def trace_from_run(trajectory: dict, calls: List[dict], other: dict, produce: tu end = max(ends(turn["children"])) turn.update(end_ns=end, duration_ns=end - turn["start_ns"]) session["children"] = sorted(session["children"] + turns, key=lambda s: s["start_ns"]) - return {"schema_version": otel.SCHEMA, "producer": "app/nullius/standard/job.py", "trial_name": trajectory.get("session_id") or "", + return {"schema_version": otel.SCHEMA, "producer": "app/nullius/standard/runner/job.py", "trial_name": trajectory.get("session_id") or "", "session_id": trajectory.get("session_id") or "", "agent": trajectory.get("agent") or {}, "clock": {"source": "this machine's clock, as the relay and the ACP client saw each call", "note": "wall_ns is the agent's window; a tool call's time is what the agent reported"}, diff --git a/app/nullius/standard/merge.py b/app/nullius/standard/runner/merge.py similarity index 99% rename from app/nullius/standard/merge.py rename to app/nullius/standard/runner/merge.py index 97cb517f..938f1e20 100644 --- a/app/nullius/standard/merge.py +++ b/app/nullius/standard/runner/merge.py @@ -32,8 +32,8 @@ import shutil from typing import Dict, List, Optional -from nullius.standard import job -from nullius.standard.names import backend as backend_name +from nullius.standard.runner import job +from nullius.standard.contract.names import backend as backend_name # What every shard of one launch shares, as (what a refusal calls it, where it is in config.json). diff --git a/app/nullius/standard/pace.py b/app/nullius/standard/runner/pace.py similarity index 100% rename from app/nullius/standard/pace.py rename to app/nullius/standard/runner/pace.py diff --git a/app/nullius/standard/payload.py b/app/nullius/standard/runner/payload.py similarity index 99% rename from app/nullius/standard/payload.py rename to app/nullius/standard/runner/payload.py index 3bbe4f02..5e08f58f 100644 --- a/app/nullius/standard/payload.py +++ b/app/nullius/standard/runner/payload.py @@ -19,9 +19,9 @@ from pathlib import Path from nullius import paths -from nullius.standard import definitions +from nullius.standard.contract import definitions -PACKAGE = Path(__file__).resolve().parents[1] +PACKAGE = Path(__file__).resolve().parents[2] FORMAT = 1 _KINDS = {"benchmarks": ("benchmark.json", "standard.json"), "agents": ("agent.json",), "capabilities": ("capability.json",)} diff --git a/app/nullius/standard/run.py b/app/nullius/standard/runner/run.py similarity index 99% rename from app/nullius/standard/run.py rename to app/nullius/standard/runner/run.py index 200ddac0..436e59aa 100644 --- a/app/nullius/standard/run.py +++ b/app/nullius/standard/runner/run.py @@ -71,7 +71,12 @@ from nullius import constraints as limits, paths, prices as price_list, progress, providers from nullius.redact import redact from nullius.harbor import feed as live_feed -from nullius.standard import acp, container, definitions, hostreq, install, job, jsonl, ledger as ledgers, match, mcp_machine, pace as pacing, relay, shard as shards +from nullius.standard.calls import ledger as ledgers, relay +from nullius.standard.containers import container, mcp_machine +from nullius.standard.contract import definitions, match +from nullius.standard.protocols import acp, jsonl +from nullius.standard.requirements import hostreq, install +from nullius.standard.runner import job, pace as pacing, shard as shards # the totals a unit's end carries onto the live board, from its trial's agent_result FEED_TOTALS = ("n_input_tokens", "n_cache_tokens", "n_output_tokens", "cost_usd") @@ -79,7 +84,7 @@ # The variables of this machine's environment a run's processes keep: where # programs are, the locale, the temporary folder. Not a key among them. KEEP = ("PATH", "LANG", "LC_ALL", "TMPDIR", "TERM", "NVM_DIR", "NODE_PATH", "SSL_CERT_FILE", "SSL_CERT_DIR") -APP = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # the folder holding the nullius package +APP = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) # the folder holding the nullius package def driver_path() -> str: @@ -849,7 +854,7 @@ def ready(self) -> None: upstream, its dataset when it is downloaded, its driver's environment when it declares one (``driver.install``), the agent's or capability's packages. Refused when one cannot be had.""" - from . import network_requirements + from ..requirements import network_requirements why = network_requirements.check(self.bench, self.other) if why: raise Refused("; ".join(why)) @@ -899,7 +904,7 @@ def ready(self) -> None: f["url"], f["sha256"], progress=None if there else p.download("file")) drv = install.driver_dir(self.bench) if self.backend == "container" and self.upstream: - from nullius.standard import setup_container + from nullius.standard.containers import setup_container with p.stage("driver", start=f"preparing {self.bench['key']}'s container driver"): needs = definitions.option_needs(self.bench, self.bench_options)["host"] image = setup_container.image(self.image, self.bench, needs, os.path.join(self.job_dir, ".work", "image.log")) @@ -1331,7 +1336,7 @@ def unit_relay(self, tag: str, trial: str, setup: dict, env_def: Optional[dict] self.machine_env(trial), work, work) except mcp_machine.Unknown as e: raise _Ended("EnvironmentSetupError", f"the unit's setup: {e}") - from . import web_services + from ..containers import web_services try: doors.extend(web_services.doors(setup)) except (ValueError, OSError) as e: diff --git a/app/nullius/standard/shard.py b/app/nullius/standard/runner/shard.py similarity index 100% rename from app/nullius/standard/shard.py rename to app/nullius/standard/runner/shard.py diff --git a/app/packaging/verify.py b/app/packaging/verify.py index ae740b3b..f6b85a2b 100644 --- a/app/packaging/verify.py +++ b/app/packaging/verify.py @@ -25,7 +25,7 @@ import importlib.metadata, importlib.util, json, pathlib, sys import nullius from nullius.catalogue import catalog -from nullius.standard import definitions +from nullius.standard.contract import definitions assert importlib.util.find_spec('flask') is None assert importlib.util.find_spec('harbor') is None assert importlib.util.find_spec('app') is None diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index d20fd5b5..50b48e85 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -1,6 +1,6 @@ /* Pure recipe compiler for Harbor recipes. It prints shell; it has no DOM, storage, or execution API. This file also creates, loads and saves Nullius standard recipes; the server compiles those - (POST /new-run/runner, standard/recipe.py). Other harnesses are rejected. */ + (POST /new-run/runner, standard/pages/recipe.py). Other harnesses are rejected. */ (function (root, factory) { if (typeof module === 'object' && module.exports) module.exports = factory; else root.NulliusRecipe = factory; @@ -25,7 +25,7 @@ const runners = () => schema.runners || [{key: 'harbor', label: 'Harbor', builtin: true}]; // Unsupported runners use the server's rejection message. const RUNNER_GONE = schema.runnerGone || 'Only Harbor and Nullius recipes are supported.'; - // The Nullius standard (nullius/standard/recipe.py): a benchmark, an agent or a capability that proved the ports it + // The Nullius standard (nullius/standard/pages/recipe.py): a benchmark, an agent or a capability that proved the ports it // needs, a model. Its choices and why a pair does not fit come with the schema; the server compiles the recipe. const isStandard = r => !!(r && r.harness === 'standard'); const standard = () => schema.standard || {benchmarks: [], agents: [], capabilities: [], fits: {}, ports: {}}; diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index f4eb338f..8a1b6bfc 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -334,7 +334,7 @@ }; // The Nullius standard (C.isStandard): a benchmark, then an agent or a capability among every one there is - the // ones that have not proved the ports it needs shown greyed, with the reasons - a model and a scope. The server - // compiles the choices (POST /new-run/runner, nullius/standard/recipe.py). + // compiles the choices (POST /new-run/runner, nullius/standard/pages/recipe.py). // what a unit is: the benchmark's, or a setup's own when only setups run (a conversation, where the paper batches its questions) const unitsOf = rec => { const b = C.standardBench(rec) || {}, own = (b.setups || []).filter(x => C.chosenOf(rec).includes(x.key)); return own.length && own.length === C.chosenOf(rec).length ? own[0].units : b.units || {noun: 'unit', nouns: 'units'}; }; @@ -348,7 +348,7 @@ // an option's key read as words: reasoning_effort -> Reasoning effort const words = k => { const t = String(k).replace(/[_-]+/g, ' ').trim(); return t.charAt(0).toUpperCase() + t.slice(1); }; // A control's proof on a dataset: ✓ with what passed (when, in its title), ✕ with the value the last try - // reached against its bound, or not run. Its source (nullius/standard/definitions.py, SOURCES) is in its title. + // reached against its bound, or not run. Its source (nullius/standard/contract/definitions.py, SOURCES) is in its title. const SOURCE_SAYS = {official: 'from the authors', adapter: 'from Harbor\'s adapter', nullius: 'made by Nullius'}; const bound = e => { const [k, v] = Object.entries(e || {})[0] || ['at_least', 1]; return [k === 'at_most' ? '>' : '<', v]; }; function proofOf(proven, failed, expect) { @@ -371,7 +371,7 @@ const backend = rec.backend || 'local'; const selected = C.standardOthers(rec).filter(o => C.chosenOf(rec).includes(o.key)); const dockerWhy = list.includes('local') && here.docker ? 'Not on this machine: ' + here.docker : ''; - // Review's rule (nullius/standard/recipe.py): a setup's image installs what has an install; nothing else reaches its container + // Review's rule (nullius/standard/pages/recipe.py): a setup's image installs what has an install; nothing else reaches its container const cannot = selected.some(o => o.setup) ? optionNeeds(rec).host.filter(n => (b.host || {})[n] && !b.host[n].install.length) : []; const containerWhy = dockerWhy || (cannot.length ? cannot.join(', ') + ' cannot be provided in a container: choose local processes.' : ''); const agentRun = b && b.family === 'agent' && selected.some(o => !o.control && !o.setup); diff --git a/app/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index ec8adfb8..35ac1135 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -36,7 +36,7 @@

✓ {{ rec.passed }}{% if rec.limit %} · first {{ rec.limit }}{% endif %} diff --git a/app/tests/catalogue_docs.py b/app/tests/catalogue_docs.py index 0a55fc44..4067752c 100644 --- a/app/tests/catalogue_docs.py +++ b/app/tests/catalogue_docs.py @@ -30,7 +30,7 @@ from nullius.catalogue import catalog, citation, sources # noqa: E402 from nullius.recipes import launch # noqa: E402 -from nullius.standard import definitions, match, ports # noqa: E402 +from nullius.standard.contract import definitions, match, ports # noqa: E402 REPO = os.path.abspath(os.path.join(APP, "..")) START = "" diff --git a/app/tests/docker_tier.py b/app/tests/docker_tier.py index 61019b03..ea20c39c 100644 --- a/app/tests/docker_tier.py +++ b/app/tests/docker_tier.py @@ -7,7 +7,7 @@ import os import subprocess -from nullius.standard import container +from nullius.standard.containers import container VAR = "NULLIUS_TEST_DOCKER" diff --git a/app/tests/test_audit_regressions.py b/app/tests/test_audit_regressions.py index e75e3b19..d2aca04c 100644 --- a/app/tests/test_audit_regressions.py +++ b/app/tests/test_audit_regressions.py @@ -10,7 +10,8 @@ import unittest from types import SimpleNamespace -from nullius.standard import job, run, definitions +from nullius.standard.contract import definitions +from nullius.standard.runner import job, run from nullius.traces import charts, trajectory from nullius.judge import state from nullius.runs import parse @@ -86,7 +87,9 @@ def _stop_a_memory_run(self, to_a_thread): root = Path(tmp) (root / 'memory.py').write_text("import os,sys,time\nopen('pid','w').write(str(os.getpid()))\nfor line in sys.stdin: time.sleep(60)\n") script = f""" -from nullius.standard import definitions,run,cli +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.runner import run cli._exit_on_term() b=definitions.get('benchmark','fakememo',{ROOT!r}) o=definitions.get('capability','fakemem',{ROOT!r}) diff --git a/app/tests/test_capability_names.py b/app/tests/test_capability_names.py index ac007cf5..face5d63 100644 --- a/app/tests/test_capability_names.py +++ b/app/tests/test_capability_names.py @@ -9,7 +9,9 @@ from contextlib import redirect_stderr, redirect_stdout from unittest.mock import patch -from nullius.standard import cli, definitions, match, names, payload, ports +from nullius.standard import cli +from nullius.standard.contract import definitions, match, names, ports +from nullius.standard.runner import payload from .test_standard_definitions import BENCH, CAPABILITY diff --git a/app/tests/test_catalog.py b/app/tests/test_catalog.py index 24345d39..145e99a9 100644 --- a/app/tests/test_catalog.py +++ b/app/tests/test_catalog.py @@ -13,7 +13,7 @@ import unittest from nullius.catalogue import catalog -from nullius.standard import definitions as standard_definitions +from nullius.standard.contract import definitions as standard_definitions REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) UUID = re.compile(rb"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.I) diff --git a/app/tests/test_catalogue_overlay.py b/app/tests/test_catalogue_overlay.py index e64d9c29..a55f6e44 100644 --- a/app/tests/test_catalogue_overlay.py +++ b/app/tests/test_catalogue_overlay.py @@ -11,7 +11,8 @@ from nullius import paths from nullius.catalogue import catalog, harbor_entry, storage -from nullius.standard import definitions, install +from nullius.standard.contract import definitions +from nullius.standard.requirements import install from .test_harbor_entry import form from .test_standard_definitions import AGENT, BENCH, CAPABILITY from .test_standard_versions import VERSIONED diff --git a/app/tests/test_catalogue_sources.py b/app/tests/test_catalogue_sources.py index 224e7fab..47596970 100644 --- a/app/tests/test_catalogue_sources.py +++ b/app/tests/test_catalogue_sources.py @@ -8,7 +8,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from nullius.catalogue import catalog, sources # noqa: E402 -from nullius.standard import definitions # noqa: E402 +from nullius.standard.contract import definitions # noqa: E402 COMMIT = "0123456789abcdef0123456789abcdef01234567" diff --git a/app/tests/test_classify.py b/app/tests/test_classify.py index 6d65a0b9..960f2a2b 100644 --- a/app/tests/test_classify.py +++ b/app/tests/test_classify.py @@ -79,7 +79,7 @@ class LiveBoardAgrees(unittest.TestCase): def test_both_boards_charge_the_infrastructure_as_the_classifier_does(self): from types import SimpleNamespace from nullius.harbor import feed - from nullius.standard import job + from nullius.standard.runner import job harbor = lambda kind: feed.outcome_of(SimpleNamespace(verifier_result=None, exception_info=SimpleNamespace(exception_type=kind)))[0] standard = lambda kind: job.feed_outcome("pass", None, (kind, kind))["outcome"] for name in HARBOR_INFRA + HARBOR_RATE_LIMIT + HARBOR_SETUP: @@ -94,7 +94,8 @@ def test_both_boards_charge_the_infrastructure_as_the_classifier_does(self): def test_a_unit_the_runs_spending_cap_cut_off_has_its_own_outcome_outside_the_rate_on_both(self): """The standard's own: its relay refused the call (``standard.ledger``), so the unit had no attempt. Not an API error: nothing failed. The live feed's word for it is ``budget``.""" - from nullius.standard import job, ledger + from nullius.standard.calls import ledger + from nullius.standard.runner import job self.assertEqual(C.from_verdict(ledger.ERROR, None), C.SPENDING_CAP) self.assertIn(C.SPENDING_CAP, C.INFRA_OUTCOMES) self.assertEqual(C.ORDER.index(C.SPENDING_CAP), C.ORDER.index(C.UNKNOWN) - 1) @@ -103,7 +104,8 @@ def test_a_unit_the_runs_spending_cap_cut_off_has_its_own_outcome_outside_the_ra def test_a_unit_that_reached_its_own_spending_cap_counts_against_the_agent_on_both(self): """It had its attempt and spent its allowance, as one that spends its time does: a result, in the rate.""" - from nullius.standard import job, ledger + from nullius.standard.calls import ledger + from nullius.standard.runner import job self.assertEqual(C.from_verdict(ledger.UNIT_ERROR, None), C.AGENT_ERROR) self.assertEqual(job.feed_outcome("pass", None, (ledger.UNIT_ERROR, "its own cap"))["outcome"], "agent_error") diff --git a/app/tests/test_constraints.py b/app/tests/test_constraints.py index b5dd39d4..1a2e414e 100644 --- a/app/tests/test_constraints.py +++ b/app/tests/test_constraints.py @@ -18,7 +18,11 @@ from unittest import mock from nullius import constraints, prerequisites, settings -from nullius.standard import container, definitions, install, recipe, run +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.requirements import install +from nullius.standard.runner import run ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") ALL = {"cpus": 2, "memory_mb": 512, "processes": 100, "concurrency": 3, "cpu_set": "0-1", "gpu_ids": [0]} @@ -316,7 +320,7 @@ def setUp(self): self.addCleanup(container.cap, {}) def test_every_container_a_run_starts_takes_the_machine_s_caps(self): - from nullius.standard import setup_container + from nullius.standard.containers import setup_container container.cap({"cpus": 1.5, "memory_mb": 512, "concurrency": 2, "gpu_ids": [0]}) flags = ["--cpus", "1.5", "--memory", "512m", "--memory-swap", "512m"] tmp = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, tmp, True) diff --git a/app/tests/test_driver_path.py b/app/tests/test_driver_path.py index fea82263..b40242bc 100644 --- a/app/tests/test_driver_path.py +++ b/app/tests/test_driver_path.py @@ -10,7 +10,7 @@ import unittest from unittest import mock -from nullius.standard import run +from nullius.standard.runner import run def imports(path: str, *names: str) -> dict: @@ -28,7 +28,7 @@ def test_from_a_checkout_the_driver_sees_nullius_and_not_the_rest_of_app(self): path = run.driver_path() self.assertEqual(os.listdir(path), ["nullius"]) self.assertEqual(os.path.realpath(os.path.join(path, "nullius")), os.path.realpath(os.path.join(run.APP, "nullius"))) - self.assertEqual(imports(path, "nullius.standard.jsonl", "web"), {"nullius.standard.jsonl": True, "web": False}) + self.assertEqual(imports(path, "nullius.standard.protocols.jsonl", "web"), {"nullius.standard.protocols.jsonl": True, "web": False}) def test_from_a_wheel_the_driver_does_not_see_the_tools_site_packages(self): with tempfile.TemporaryDirectory() as site: @@ -42,8 +42,8 @@ def test_from_a_wheel_the_driver_does_not_see_the_tools_site_packages(self): run.APP = app self.assertNotEqual(path, site) self.assertEqual(os.listdir(path), ["nullius"]) - self.assertEqual(imports(path, "nullius.standard.jsonl", "nullius_tool_only_dep"), - {"nullius.standard.jsonl": True, "nullius_tool_only_dep": False}) + self.assertEqual(imports(path, "nullius.standard.protocols.jsonl", "nullius_tool_only_dep"), + {"nullius.standard.protocols.jsonl": True, "nullius_tool_only_dep": False}) def test_it_is_made_once_and_kept(self): self.assertEqual(run.driver_path(), run.driver_path()) diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index 9aaa6709..f70d140a 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -783,7 +783,8 @@ def test_gaias_hugging_face_token_is_handed_from_data_providers_alone(self): # over the launcher's stdin as a licence is, read from Settings → Data providers; a value GAIA's own folder # holds under that name is never sent from nullius import secrets - from nullius.standard import definitions, recipe + from nullius.standard.contract import definitions + from nullius.standard.pages import recipe gaia = definitions.get("benchmark", "gaia") out = recipe.compile({"version": 1, "harness": "standard", "name": "gaia-nop", "title": "t", "benchmark": "gaia", "dataset": "gaia-validation", "other": "nop", "provider": "openai", "model": "", "limit": 1, diff --git a/app/tests/test_hf_endpoint.py b/app/tests/test_hf_endpoint.py index 352204d0..9d7c76a4 100644 --- a/app/tests/test_hf_endpoint.py +++ b/app/tests/test_hf_endpoint.py @@ -11,7 +11,8 @@ from unittest import mock from nullius import settings -from nullius.standard import install, run +from nullius.standard.requirements import install +from nullius.standard.runner import run class Endpoint(unittest.TestCase): diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index 0b78317b..ed360028 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -614,7 +614,7 @@ def test_priority_is_the_deepest_path_and_a_test_alone_is_low(self): self.assertEqual(J.priority_of(["app/web/runs.py", "docs/a.md"])[0], "medium") self.assertEqual(J.priority_of(["app/nullius/catalogue/benchmarks/x/benchmark.json"])[0], "medium") self.assertEqual(J.priority_of(["app/nullius/runs/parse.py"])[0], "high") - self.assertEqual(J.priority_of(["app/nullius/standard/relay.py", "docs/a.md"]), ("extreme", "app/nullius/standard/relay.py")) + self.assertEqual(J.priority_of(["app/nullius/standard/calls/relay.py", "docs/a.md"]), ("extreme", "app/nullius/standard/calls/relay.py")) self.assertEqual(J.priority_of([".github/workflows/x.yml"])[0], "extreme") self.assertEqual(J.priority_of([".github/ISSUE_TEMPLATE/bug.yml", ".github/pull_request_template.md"])[0], "low") diff --git a/app/tests/test_kit_check_isolation.py b/app/tests/test_kit_check_isolation.py index 5de23955..238081f6 100644 --- a/app/tests/test_kit_check_isolation.py +++ b/app/tests/test_kit_check_isolation.py @@ -17,7 +17,9 @@ import unittest from pathlib import Path -from nullius.standard import container, definitions, jsonl +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl from tests import APP from tests.execution_support import gone @@ -98,7 +100,8 @@ class AcpFiles(unittest.TestCase): def client_fs(self, backend): from unittest import mock - from nullius.standard import acp, run + from nullius.standard.protocols import acp + from nullius.standard.runner import run seen = {} class Stop(Exception): pass @@ -140,7 +143,7 @@ def test_only_regular_files_and_folders_stay(self): self.assertEqual(sorted(p.name for p in v.rglob("*")), ["kept.txt", "sub"]) def test_a_trial_is_never_written_through_a_link(self): - from nullius.standard import job + from nullius.standard.runner import job trial = self.tmp / "unit__1"; (trial / "verifier").mkdir(parents=True); (trial / "agent").mkdir() (trial / "verifier" / "score.json").symlink_to(self.victim) (trial / "verifier" / "reward.txt").symlink_to(self.victim) @@ -163,14 +166,14 @@ def background(self, then: str) -> str: return pidfile, ["sh", "-c", f"sleep 60 & echo $! > {pidfile}; {then}"] def test_a_normal_end_ends_what_it_left_running(self): - from nullius.standard import run + from nullius.standard.runner import run pidfile, cmd = self.background("echo done") r = run.run_group(cmd, 10, stdout=subprocess.PIPE, text=True) self.assertEqual((r.returncode, r.stdout.strip()), (0, "done")) self.assertTrue(gone(int(Path(pidfile).read_text()))) def test_a_timeout_ends_the_whole_group(self): - from nullius.standard import run + from nullius.standard.runner import run pidfile, cmd = self.background("sleep 30") with self.assertRaises(subprocess.TimeoutExpired): run.run_group(cmd, 2, stdout=subprocess.PIPE, text=True) # time for sh to write the pid first diff --git a/app/tests/test_locomo_rag.py b/app/tests/test_locomo_rag.py index 429be706..1afeb373 100644 --- a/app/tests/test_locomo_rag.py +++ b/app/tests/test_locomo_rag.py @@ -16,7 +16,7 @@ import textwrap import unittest -from nullius.standard import definitions +from nullius.standard.contract import definitions BENCH = definitions.get("benchmark", "locomo") DRIVER = os.path.join(BENCH["_here"], "driver.py") diff --git a/app/tests/test_locomo_setups.py b/app/tests/test_locomo_setups.py index e5872dd9..96e6138c 100644 --- a/app/tests/test_locomo_setups.py +++ b/app/tests/test_locomo_setups.py @@ -11,7 +11,8 @@ import re import unittest -from nullius.standard import definitions, install +from nullius.standard.contract import definitions +from nullius.standard.requirements import install BENCH = definitions.get("benchmark", "locomo") diff --git a/app/tests/test_longmemeval_setups.py b/app/tests/test_longmemeval_setups.py index 89646a2f..aa783797 100644 --- a/app/tests/test_longmemeval_setups.py +++ b/app/tests/test_longmemeval_setups.py @@ -17,7 +17,8 @@ import textwrap import unittest -from nullius.standard import definitions, install +from nullius.standard.contract import definitions +from nullius.standard.requirements import install BENCH = definitions.get("benchmark", "longmemeval") DRIVER = os.path.join(BENCH["_here"], "driver.py") diff --git a/app/tests/test_network_requirements.py b/app/tests/test_network_requirements.py index 34d93a63..4bc348e8 100644 --- a/app/tests/test_network_requirements.py +++ b/app/tests/test_network_requirements.py @@ -4,8 +4,10 @@ from types import SimpleNamespace from unittest.mock import Mock, patch import tempfile -from nullius.standard import container -from nullius.standard import network_requirements as net, recipe, definitions +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.requirements import network_requirements as net from tests.test_standard_recipe import defs, a_recipe @@ -85,7 +87,7 @@ def test_only_the_runs_first_unit_probes_the_proxy_route(self): unit._online() self.assertEqual(unit.network_env['HTTPS_PROXY'], 'http://egress:3128') # its proxy, still self.assertNotIn(unit.names['agent'] + '-network-check', str(docker.call_args_list)) - from nullius.standard import run + from nullius.standard.runner import run r = run.Run.__new__(run.Run) self.assertEqual([r.first_probe() for _ in range(3)], [True, False, False]) diff --git a/app/tests/test_onboarding.py b/app/tests/test_onboarding.py index 93d0ebe7..6addb244 100644 --- a/app/tests/test_onboarding.py +++ b/app/tests/test_onboarding.py @@ -10,7 +10,7 @@ from unittest import mock from nullius import onboarding -from nullius.standard import container +from nullius.standard.containers import container NO_DOCKER = lambda: False diff --git a/app/tests/test_prerequisites.py b/app/tests/test_prerequisites.py index e1c60b0c..6e5f562b 100644 --- a/app/tests/test_prerequisites.py +++ b/app/tests/test_prerequisites.py @@ -7,7 +7,10 @@ from unittest import mock from nullius import hosts, prerequisites -from nullius.standard import container, definitions, recipe, run +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.runner import run SETUP = {"sandbox": {"summary": "a sandbox", "check": ["srt", "bwrap"], "install": ["sudo apt-get install -y bubblewrap"]}} diff --git a/app/tests/test_prices.py b/app/tests/test_prices.py index b5695e8f..24a89721 100644 --- a/app/tests/test_prices.py +++ b/app/tests/test_prices.py @@ -12,7 +12,7 @@ from unittest import mock from nullius import prices -from nullius.standard import run +from nullius.standard.runner import run # LiteLLM's shape: costs per token, a sample entry and an image model without an input price. LISTING = { diff --git a/app/tests/test_progress.py b/app/tests/test_progress.py index dde576bb..a428f0d4 100644 --- a/app/tests/test_progress.py +++ b/app/tests/test_progress.py @@ -13,7 +13,9 @@ from unittest.mock import patch from nullius import progress -from nullius.standard import definitions, install, run +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import run class Line(unittest.TestCase): diff --git a/app/tests/test_published_setups.py b/app/tests/test_published_setups.py index e8abf447..c69dedd3 100644 --- a/app/tests/test_published_setups.py +++ b/app/tests/test_published_setups.py @@ -18,7 +18,9 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from nullius.catalogue import catalog -from nullius.standard import definitions, install, jsonl +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install APP = os.path.dirname(os.path.dirname(os.path.abspath(definitions.CATALOGUE))) diff --git a/app/tests/test_sandbox.py b/app/tests/test_sandbox.py index 1baa8207..ed4507b5 100644 --- a/app/tests/test_sandbox.py +++ b/app/tests/test_sandbox.py @@ -12,7 +12,7 @@ from unittest import mock from nullius import sandbox -from nullius.standard import container +from nullius.standard.containers import container def done(code=0, out="", err=""): diff --git a/app/tests/test_search_kit.py b/app/tests/test_search_kit.py index 7f8d0644..18885906 100644 --- a/app/tests/test_search_kit.py +++ b/app/tests/test_search_kit.py @@ -6,7 +6,8 @@ import tempfile import unittest from urllib.request import urlopen -from nullius.standard import definitions, match, web_services +from nullius.standard.containers import web_services +from nullius.standard.contract import definitions, match spec = importlib.util.spec_from_file_location('search_kit', Path(definitions.KITS) / 'agent-search-v1' / 'driver.py') kit = importlib.util.module_from_spec(spec) @@ -108,7 +109,7 @@ def test_gaia_requires_search_and_unproven_agents_do_not_fit(self): from tests import docker_tier -from nullius.standard import container +from nullius.standard.containers import container import subprocess import socket from unittest import mock diff --git a/app/tests/test_secrets.py b/app/tests/test_secrets.py index aba3e76e..68a7abcf 100644 --- a/app/tests/test_secrets.py +++ b/app/tests/test_secrets.py @@ -45,7 +45,7 @@ def test_a_data_providers_token_is_read_from_its_provider_alone(self): secrets.store_of("bench-a", "HF_TOKEN", "elsewhere") def test_a_run_reads_a_data_providers_token_from_its_provider_alone(self): - from nullius.standard import run + from nullius.standard.runner import run bench = {"key": "bench-a", "environments": {"e": {"needs_secrets": [ {"name": "HF_TOKEN", "to": "driver", "provider": "huggingface"}, {"name": "LICENSE_KEY", "to": "driver"}]}}} secrets.set("bench-a", "HF_TOKEN", "stale-synthetic") @@ -161,7 +161,7 @@ def bench(self): "path": "/opt/x/lic"}]}}} def test_written_0600_in_a_0700_folder(self): - from nullius.standard import run + from nullius.standard.runner import run with tempfile.TemporaryDirectory() as d: spill = os.path.join(d, "spill") got = run.Licences.handed(self.bench(), {"LIC": b"secret"}, spill) @@ -170,7 +170,7 @@ def test_written_0600_in_a_0700_folder(self): self.assertEqual(oct(os.stat(p).st_mode & 0o777), "0o600") def test_a_folder_open_to_others_or_a_link_is_refused(self): - from nullius.standard import run + from nullius.standard.runner import run with tempfile.TemporaryDirectory() as d: wide = os.path.join(d, "wide") os.mkdir(wide, 0o777) @@ -186,7 +186,7 @@ def test_a_folder_open_to_others_or_a_link_is_refused(self): self.assertEqual(os.listdir(target), []) def test_a_link_planted_as_the_file_is_not_followed(self): - from nullius.standard import run + from nullius.standard.runner import run with tempfile.TemporaryDirectory() as d: spill = os.path.join(d, "spill") os.mkdir(spill, 0o700) diff --git a/app/tests/test_settings.py b/app/tests/test_settings.py index 0279ac0a..7dad9650 100644 --- a/app/tests/test_settings.py +++ b/app/tests/test_settings.py @@ -30,8 +30,8 @@ def test_every_variable_the_application_reads_is_in_the_table(self): read -= {"LOCALAPPDATA"} # Windows's user directory, not a Nullius setting read -= {"OPENAI_BASE_URL"} # what a run's launcher hands it (execution.URL_NAMES), read by the run: standard cli --from-run read -= {"NULLIUS_LICENCE_DIR"} # the same: where a host's run writes a licence file (execution, standard cli) - read -= {"NULLIUS_FORWARD_TO"} # a licence server's forwarder's, in its own container (standard/forward.py) - read -= {"NULLIUS_MCP_AT"} # the MCP bridge's, in the agent's container (standard/mcp_bridge.py) + read -= {"NULLIUS_FORWARD_TO"} # a licence server's forwarder's, in its own container (standard/containers/forward.py) + read -= {"NULLIUS_MCP_AT"} # the MCP bridge's, in the agent's container (standard/containers/mcp_bridge.py) read -= {"DOCKER_CONFIG"} # docker's own: where it keeps a login (sandbox.py reads the username) read -= {"DOCKER_HOST", "DOCKER_CONTEXT"} # docker's own: when set, container.py leaves the current context to them read -= {"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"} # the user's session: where systemd-run finds its manager (constraints.session) diff --git a/app/tests/test_setup_container.py b/app/tests/test_setup_container.py index 60c73c83..43428ef0 100644 --- a/app/tests/test_setup_container.py +++ b/app/tests/test_setup_container.py @@ -9,7 +9,8 @@ import unittest from unittest.mock import patch -from nullius.standard import container, setup_container, jsonl +from nullius.standard.containers import container, setup_container +from nullius.standard.protocols import jsonl from tests import docker_tier APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -147,14 +148,14 @@ def test_the_launcher_puts_the_credentials_in_the_drivers_environment(self): env = {'PATH': os.environ.get('PATH', ''), 'PYTHONPATH': APP, 'NULLIUS_HOME': root + '/profile'} def launch(*credentials): - return subprocess.run([sys.executable, '-m', 'nullius.standard.setup_container', root + '/setup.json', + return subprocess.run([sys.executable, '-m', 'nullius.standard.containers.setup_container', root + '/setup.json', root + '/cache', 'run', *credentials], env=env, capture_output=True, text=True, timeout=60).stdout self.assertEqual(launch(root + '/credentials'), 'fixture-only') self.assertEqual(launch(), 'unset') def test_the_container_starts_the_driver_with_the_command_a_host_run_starts(self): - from nullius.standard import install + from nullius.standard.requirements import install with tempfile.TemporaryDirectory() as root: bench = {'key': 'fixture', '_here': root, 'driver': {'command': [sys.executable, '{here}/show.py']}} with open(root + '/show.py', 'w') as f: @@ -162,7 +163,7 @@ def test_the_container_starts_the_driver_with_the_command_a_host_run_starts(self with open(root + '/setup.json', 'w') as f: json.dump({'bench': bench, 'upstream': None, 'needs': []}, f) env = {'PATH': os.environ.get('PATH', ''), 'PYTHONPATH': APP, 'NULLIUS_HOME': root + '/profile'} - said = subprocess.run([sys.executable, '-m', 'nullius.standard.setup_container', root + '/setup.json', + said = subprocess.run([sys.executable, '-m', 'nullius.standard.containers.setup_container', root + '/setup.json', root + '/cache', 'run'], env=env, capture_output=True, text=True, timeout=60).stdout command, extra = install.driver_argv(bench, root + '/cache') self.assertEqual((said, extra), (' '.join(command[1:]), {})) @@ -206,7 +207,7 @@ class SetupDriverFiles(unittest.TestCase): """A benchmark's downloaded files reach its Docker setup driver as they reach a local one.""" def test_the_files_are_in_the_drivers_environment_and_mounted(self): - from nullius.standard import run + from nullius.standard.runner import run tmp = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, tmp, True) got = {} diff --git a/app/tests/test_standard_acp.py b/app/tests/test_standard_acp.py index 08363e4e..639de9ce 100644 --- a/app/tests/test_standard_acp.py +++ b/app/tests/test_standard_acp.py @@ -7,7 +7,7 @@ import tempfile import unittest -from nullius.standard import acp +from nullius.standard.protocols import acp FAKE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "fake_acp_agent.py") @@ -102,7 +102,7 @@ def test_permission_is_granted(self): def test_an_adapters_warning_comes_as_a_notice_not_in_the_answer(self): # the client takes notices, so an adapter's warning is never text in front of the answer - from nullius.standard import job + from nullius.standard.runner import job sid = self.c.new_session(self.ws) t = self.c.prompt(sid, "warn", timeout=20) self.assertEqual(t.text, "ok") diff --git a/app/tests/test_standard_bench_options.py b/app/tests/test_standard_bench_options.py index ab016691..11bee911 100644 --- a/app/tests/test_standard_bench_options.py +++ b/app/tests/test_standard_bench_options.py @@ -12,7 +12,10 @@ from unittest.mock import patch from nullius import hosts, prerequisites -from nullius.standard import definitions, hostreq, recipe, run +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.requirements import hostreq +from nullius.standard.runner import run TAU = definitions.get("benchmark", "tau3-bench") @@ -144,7 +147,7 @@ def fake(argv, timeout): class Relay(unittest.TestCase): def test_an_embeddings_reply_is_recorded_by_its_usage_never_its_vectors(self): import json - from nullius.standard import relay + from nullius.standard.calls import relay body = json.dumps({"object": "list", "data": [{"embedding": [0.1, 0.2]}] * 3, "usage": {"prompt_tokens": 1000, "total_tokens": 1000}}).encode() got = relay.read_reply("/embeddings", body, False) self.assertEqual((got["embeddings"], got["usage"]["input"]), (3, 1000)) diff --git a/app/tests/test_standard_capability_trace.py b/app/tests/test_standard_capability_trace.py index 30db504e..3477c467 100644 --- a/app/tests/test_standard_capability_trace.py +++ b/app/tests/test_standard_capability_trace.py @@ -9,7 +9,7 @@ import json import unittest -from nullius.standard import job +from nullius.standard.runner import job class CapabilityTrace(unittest.TestCase): diff --git a/app/tests/test_standard_check_safety.py b/app/tests/test_standard_check_safety.py index 8b2d2e3b..629f7759 100644 --- a/app/tests/test_standard_check_safety.py +++ b/app/tests/test_standard_check_safety.py @@ -28,7 +28,9 @@ import urllib.request from unittest import mock -from nullius.standard import container, definitions, egress, run +from nullius.standard.containers import container, egress +from nullius.standard.contract import definitions +from nullius.standard.runner import run from tests import docker_tier TB = os.path.join(definitions.CATALOGUE, "benchmarks", "terminal-bench") diff --git a/app/tests/test_standard_conform.py b/app/tests/test_standard_conform.py index cb61ee16..85d82642 100644 --- a/app/tests/test_standard_conform.py +++ b/app/tests/test_standard_conform.py @@ -7,7 +7,9 @@ import tempfile import unittest -from nullius.standard import conform, definitions, install, match +from nullius.standard.contract import definitions, match +from nullius.standard.proofs import conform +from nullius.standard.requirements import install FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard") diff --git a/app/tests/test_standard_container.py b/app/tests/test_standard_container.py index c4c2f4a5..55d020d2 100644 --- a/app/tests/test_standard_container.py +++ b/app/tests/test_standard_container.py @@ -19,7 +19,8 @@ import urllib.request from unittest import mock -from nullius.standard import container, install +from nullius.standard.containers import container +from nullius.standard.requirements import install from tests import docker_tier diff --git a/app/tests/test_standard_controls.py b/app/tests/test_standard_controls.py index e1c6b84e..3aeeeed2 100644 --- a/app/tests/test_standard_controls.py +++ b/app/tests/test_standard_controls.py @@ -12,7 +12,11 @@ from unittest.mock import patch from nullius.runs import classify, feasibility, parse -from nullius.standard import definitions, install, match, prove, recipe, run +from nullius.standard.contract import definitions, match +from nullius.standard.pages import recipe +from nullius.standard.proofs import prove +from nullius.standard.requirements import install +from nullius.standard.runner import run FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") CONTROLS = {"nop": {"source": "nullius", "from": "Nothing runs; the answer is empty."}, @@ -115,7 +119,7 @@ def test_two_shards_run_every_unit_once_tagged_by_its_place_and_merge_into_one_j """The shard before the limit, each unit's tag its place in the whole dataset, the config saying which shard of which launch; merged, the two read as the one run they are.""" - from nullius.standard import merge, shard + from nullius.standard.runner import merge, shard b = kit("agent-workspace-v1", os.path.join(self.tmp, "kits")) go = lambda which, **kw: run.run(b, definitions.control(b, which), model="", provider="openai", jobs_root=os.path.join(self.tmp, "jobs"), env={}, say=lambda s: None, **kw) @@ -199,7 +203,7 @@ def test_the_result_has_every_check_and_proven_is_written_with_the_jobs(self): self.assertEqual(definitions.problems(written, "benchmark"), []) def test_a_shard_s_proof_runs_its_controls_on_its_units_and_says_which(self): - from nullius.standard import shard + from nullius.standard.runner import shard b = kit("agent-workspace-v1", os.path.join(self.tmp, "kits")) got = self.prove(b, shard=(2, 2), launch="P", write=False)["kit"] self.assertEqual(got["oracle"]["shard"], "2/2"); self.assertNotIn("shard", got["units"]) @@ -281,7 +285,7 @@ def test_units_that_may_not_be_redistributed_are_counted_never_named(self): self.assertIn("held-unit-2", b["proven"]["leaky"]["failed"]["leak"]["problems"][0]) -LEAKY = '''from nullius.standard.jsonl import serve +LEAKY = '''from nullius.standard.protocols.jsonl import serve import os ANSWER = "the reference answer is forty-two" def units(dataset): @@ -302,7 +306,7 @@ def score(unit, dir, transcript, answer): serve({"units": units, "setup": setup, "oracle": oracle, "score": score}) ''' -HELD = '''from nullius.standard.jsonl import serve +HELD = '''from nullius.standard.protocols.jsonl import serve import os ANSWER = "the reference answer is forty-two" UNITS = {"choice": ["held-unit-1"], "leaky": ["held-unit-2"]} @@ -397,7 +401,7 @@ def test_units_receive_saved_or_handed_driver_credentials_only(self): here = Path(tmp) / "benchmark" here.mkdir() (here / "driver.py").write_text('''import os -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def units(dataset): assert os.environ.get("HF_TOKEN") == "synthetic-proof-token" assert "AGENT_ONLY" not in os.environ diff --git a/app/tests/test_standard_definitions.py b/app/tests/test_standard_definitions.py index ea0c6cb6..5970c721 100644 --- a/app/tests/test_standard_definitions.py +++ b/app/tests/test_standard_definitions.py @@ -13,7 +13,9 @@ import unittest from unittest import mock -from nullius.standard import cli, definitions, jsonl, match, ports +from nullius.standard import cli +from nullius.standard.contract import definitions, match, ports +from nullius.standard.protocols import jsonl from tests import APP BENCH = { diff --git a/app/tests/test_standard_environments.py b/app/tests/test_standard_environments.py index fcf2e526..1c221d92 100644 --- a/app/tests/test_standard_environments.py +++ b/app/tests/test_standard_environments.py @@ -22,7 +22,10 @@ from nullius import secrets, settings from nullius.runs import classify, parse -from nullius.standard import container, definitions, install, run +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import run from tests import docker_tier HERE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "envbench") diff --git a/app/tests/test_standard_fidelity.py b/app/tests/test_standard_fidelity.py index c29733be..f9a3772d 100644 --- a/app/tests/test_standard_fidelity.py +++ b/app/tests/test_standard_fidelity.py @@ -4,7 +4,8 @@ import unittest -from nullius.standard import fidelity, relay +from nullius.standard.calls import relay +from nullius.standard.proofs import fidelity CONTEXT = [{"type": "message", "role": "developer", "content": [{"type": "input_text", "text": "permissions"}]}, {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "write result.txt"}]}] diff --git a/app/tests/test_standard_forward.py b/app/tests/test_standard_forward.py index 0f560d02..6dbd2563 100644 --- a/app/tests/test_standard_forward.py +++ b/app/tests/test_standard_forward.py @@ -14,7 +14,7 @@ import unittest from unittest import mock -from nullius.standard import forward +from nullius.standard.containers import forward def _greeter(greeting: bytes, host: str = "127.0.0.1") -> int: diff --git a/app/tests/test_standard_howto.py b/app/tests/test_standard_howto.py index fa7f5ec3..065f8ca9 100644 --- a/app/tests/test_standard_howto.py +++ b/app/tests/test_standard_howto.py @@ -13,7 +13,9 @@ import unittest from unittest.mock import patch -from nullius.standard import cli, definitions, howto +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import howto class Steps(unittest.TestCase): diff --git a/app/tests/test_standard_install.py b/app/tests/test_standard_install.py index e13c82c0..a770a124 100644 --- a/app/tests/test_standard_install.py +++ b/app/tests/test_standard_install.py @@ -10,7 +10,7 @@ import unittest from unittest import mock -from nullius.standard import install +from nullius.standard.requirements import install class UpstreamTest(unittest.TestCase): diff --git a/app/tests/test_standard_ledger.py b/app/tests/test_standard_ledger.py index 9cdbfd75..aef4d231 100644 --- a/app/tests/test_standard_ledger.py +++ b/app/tests/test_standard_ledger.py @@ -11,7 +11,7 @@ import threading import unittest -from nullius.standard import ledger +from nullius.standard.calls import ledger ROW = {"input": 1.0, "output": 10.0} @@ -230,7 +230,7 @@ def test_relays_in_other_processes_book_in_the_same_ledger(self): books and settles; none of it is lost between them.""" led = ledger.Ledger.create(self.path, 100.0) app = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - code = ("import sys\nfrom nullius.standard import ledger\nled = ledger.Ledger(sys.argv[1])\n" + code = ("import sys\nfrom nullius.standard.calls import ledger\nled = ledger.Ledger(sys.argv[1])\n" "for _ in range(40):\n b, _ = led.reserve(0.5)\n led.settle(b, 0.01)\n") procs = [subprocess.Popen([sys.executable, "-c", code, self.path], env={"PATH": os.environ.get("PATH", ""), "PYTHONPATH": app}) for _ in range(4)] diff --git a/app/tests/test_standard_mcp_machine.py b/app/tests/test_standard_mcp_machine.py index b58d0253..0949a889 100644 --- a/app/tests/test_standard_mcp_machine.py +++ b/app/tests/test_standard_mcp_machine.py @@ -1,5 +1,5 @@ """A benchmark's MCP server run on the machine, in the driver's environment -(``mcp_servers``; ``nullius.standard.mcp_machine``): declared and checked; on +(``mcp_servers``; ``nullius.standard.containers.mcp_machine``): declared and checked; on the local backend the agent starts it from that environment; on docker a listener here, one door on the unit's network (``forward.py`` to a Unix socket) and a bridge in the agent's container. And the driver environment @@ -19,7 +19,10 @@ import unittest from unittest import mock -from nullius.standard import container, definitions, install, mcp_machine, run +from nullius.standard.containers import container, mcp_machine +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import run FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard") FORWARD = container.FORWARD @@ -45,7 +48,7 @@ ''' DRIVER = r'''import json, os -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def log(dir): return os.path.join(os.path.dirname(os.path.abspath(dir)), "verifier", "calls.jsonl") def setup(unit, dir): diff --git a/app/tests/test_standard_options.py b/app/tests/test_standard_options.py index c35ed797..c1315660 100644 --- a/app/tests/test_standard_options.py +++ b/app/tests/test_standard_options.py @@ -10,7 +10,12 @@ import tempfile import unittest -from nullius.standard import cli, conform, definitions, install, recipe, run +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.proofs import conform +from nullius.standard.requirements import install +from nullius.standard.runner import run FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard") ROOT = os.path.join(FIX, "catalogue") diff --git a/app/tests/test_standard_own_image.py b/app/tests/test_standard_own_image.py index 4da62bc3..24f66117 100644 --- a/app/tests/test_standard_own_image.py +++ b/app/tests/test_standard_own_image.py @@ -17,7 +17,10 @@ from nullius.runs import classify from tests import docker_tier -from nullius.standard import container, definitions, install, run +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import run HERE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "ownbench") diff --git a/app/tests/test_standard_parts.py b/app/tests/test_standard_parts.py index ea875b87..2f0dff5a 100644 --- a/app/tests/test_standard_parts.py +++ b/app/tests/test_standard_parts.py @@ -14,7 +14,7 @@ import unittest from nullius.runs import parse -from nullius.standard import job +from nullius.standard.runner import job BENCH = {"key": "locomo", "family": "capability", "needs": [], "score": {"kind": "score", "says": "mean token F1"}} diff --git a/app/tests/test_standard_payload.py b/app/tests/test_standard_payload.py index 38e9ada2..58c6517f 100644 --- a/app/tests/test_standard_payload.py +++ b/app/tests/test_standard_payload.py @@ -14,7 +14,8 @@ from unittest.mock import patch from nullius import execution, paths -from nullius.standard import install, payload +from nullius.standard.requirements import install +from nullius.standard.runner import payload class Snapshot(unittest.TestCase): @@ -254,7 +255,7 @@ def test_real_runtime_snapshot_loads_user_definition_from_an_unrelated_directory key, here = payload.build(str(self.cache)) self.assertFalse((Path(here) / "app/.env").exists()) other = self.tmp / "elsewhere"; other.mkdir() - ran = subprocess.run([sys.executable, "-c", "from nullius.standard import definitions; print(definitions.get('agent', 'reference')['label'])"], + ran = subprocess.run([sys.executable, "-c", "from nullius.standard.contract import definitions; print(definitions.get('agent', 'reference')['label'])"], cwd=other, env=dict(os.environ, PYTHONPATH=str(Path(here) / "app"), NULLIUS_CATALOGUE=str(Path(here) / "app/nullius/catalogue")), capture_output=True, text=True) @@ -280,7 +281,7 @@ def test_proof_metadata_saves_to_the_selected_catalogue_without_mutating_the_sna for selected in (self.catalogue, remote): with self.subTest(selected=selected): ran = subprocess.run([sys.executable, "-c", - "from nullius.standard import definitions; " + "from nullius.standard.contract import definitions; " "d = definitions.get('agent', 'reference'); " "assert d['label'] == 'Selected reference'; " "d.setdefault('proven', {})['fixture-proof'] = {'job': 'fixture-evidence'}; " @@ -316,7 +317,7 @@ def test_installed_local_execution_has_one_backend_provider_and_keeps_helpers_an shutil.copytree(installed / "catalogue/agents/reference", self.catalogue / "agents/reference") self.write(installed / "standard/cli.py", '''import json, os, pathlib, sys import nullius -from nullius.standard import definitions +from nullius.standard.contract import definitions providers = sorted({str((pathlib.Path(p or os.getcwd()) / "nullius").resolve()) for p in sys.path if (pathlib.Path(p or os.getcwd()) / "nullius").is_dir()}) definition = definitions.get("agent", "reference") @@ -335,7 +336,7 @@ def test_installed_local_execution_has_one_backend_provider_and_keeps_helpers_an driver = '''import hashlib, json, pathlib, sys import nullius from nullius import execution, paths -from nullius.standard import recipe +from nullius.standard.pages import recipe execution.SYNC_EVERY = 0.02 def make_plan(index): # Repeat without changing any input, then verify proof persistence too. diff --git a/app/tests/test_standard_recipe.py b/app/tests/test_standard_recipe.py index 076791f4..ae91ea52 100644 --- a/app/tests/test_standard_recipe.py +++ b/app/tests/test_standard_recipe.py @@ -15,7 +15,10 @@ import unittest from unittest.mock import patch -from nullius.standard import cli, conform, definitions, recipe +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.proofs import conform ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") diff --git a/app/tests/test_standard_relay.py b/app/tests/test_standard_relay.py index 83197949..2f534ac7 100644 --- a/app/tests/test_standard_relay.py +++ b/app/tests/test_standard_relay.py @@ -20,7 +20,9 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from nullius.runs import classify -from nullius.standard import job, jsonl, ledger, relay +from nullius.standard.calls import ledger, relay +from nullius.standard.protocols import jsonl +from nullius.standard.runner import job CHAT = {"choices": [{"message": {"role": "assistant", "content": "hello"}}], "usage": {"prompt_tokens": 10, "completion_tokens": 2, "prompt_tokens_details": {"cached_tokens": 4}}} @@ -473,7 +475,7 @@ def serve(self, key, *extra): with open(os.path.join(d, "key"), "w") as f: f.write(key + "\n") env = {"PATH": os.environ.get("PATH", ""), "PYTHONPATH": self.app} - return subprocess.Popen([sys.executable, "-m", "nullius.standard.relay", "serve", "--listen", "127.0.0.1:0", + return subprocess.Popen([sys.executable, "-m", "nullius.standard.calls.relay", "serve", "--listen", "127.0.0.1:0", "--base", f"http://127.0.0.1:{self.up.server_address[1]}/v1", "--record", d, "--key-file", os.path.join(d, "key"), "--model", "the-recipes", *extra], env=env, stdout=subprocess.PIPE, text=True) @@ -516,7 +518,7 @@ def test_serve_books_its_calls_in_the_runs_ledger(self): def test_serve_without_its_key_file_refuses(self): import subprocess - p = subprocess.Popen([sys.executable, "-m", "nullius.standard.relay", "serve", "--base", "http://127.0.0.1:9/v1", + p = subprocess.Popen([sys.executable, "-m", "nullius.standard.calls.relay", "serve", "--base", "http://127.0.0.1:9/v1", "--record", tempfile.mkdtemp(), "--key-file", "/nonexistent/key"], env={"PATH": os.environ.get("PATH", ""), "PYTHONPATH": self.app}, stdout=subprocess.PIPE, text=True) self.assertIn("cannot read --key-file", p.stdout.readline()) @@ -817,7 +819,7 @@ def test_a_key_the_header_refuses_never_reaches_the_reply_or_the_record(self): self.assertNotIn("SECRETSECRET", f.read()) def test_a_run_refuses_such_a_key_before_it_starts(self): - from nullius.standard import run + from nullius.standard.runner import run for key in ("sk-abc\r", " sk-abc", "\ufeffsk-abc", "sk-ab\u200bc"): with self.assertRaises(run.Refused): run.provider_endpoint("openai", {"OPENAI_API_KEY": key}) @@ -827,7 +829,7 @@ def test_a_run_refuses_such_a_key_before_it_starts(self): ECHO = r""" import sys sys.path.insert(0, sys.argv[1]) -from nullius.standard import jsonl +from nullius.standard.protocols import jsonl jsonl.serve({"echo": lambda **kw: {"got": kw}, "boom": lambda **kw: 1 / 0}) """ diff --git a/app/tests/test_standard_run.py b/app/tests/test_standard_run.py index 2a7ec268..855ce38e 100644 --- a/app/tests/test_standard_run.py +++ b/app/tests/test_standard_run.py @@ -14,12 +14,17 @@ from unittest import mock from nullius.runs import classify, live, parse -from nullius.standard import acp, container, definitions, install, ledger, pace as pacing, relay, run +from nullius.standard.calls import ledger, relay +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.protocols import acp +from nullius.standard.requirements import install +from nullius.standard.runner import pace as pacing, run ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") # A conversation whose user a model plays: it opens, speaks once more, then is done. CHAT_DRIVER = '''import json, sys, urllib.request -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve ROUTES = [] def ask(sim, text): ROUTES.append(sim["model"]) @@ -38,7 +43,7 @@ def turn(unit, dir, transcript, simulator=None): ''' JUDGED_DRIVER = '''import json, urllib.request -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def score(unit, dir, transcript, answer, judge=None): req = urllib.request.Request(judge["base_url"] + "/chat/completions", headers={"Content-Type": "application/json"}, data=json.dumps({"model": judge["model"], "messages": [{"role": "user", "content": answer or "x"}]}).encode()) @@ -48,7 +53,7 @@ def score(unit, dir, transcript, answer, judge=None): ''' CWD_DRIVER = '''import os -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def setup(unit, dir): os.makedirs("data", exist_ok=True) open(os.path.join("data", ".cache"), "w").write("x") @@ -57,7 +62,7 @@ def setup(unit, dir): "score": lambda unit, dir, transcript, answer: {"reward": 1.0, "passed": True, "detail": {}}}) ''' -CALLING_DRIVER = '''from nullius.standard.jsonl import serve +CALLING_DRIVER = '''from nullius.standard.protocols.jsonl import serve serve({"units": lambda dataset: {"units": [f"m{i}" for i in range(8)]}, "setup": lambda unit, dir: {"prompt": "model hi"}, "score": lambda unit, dir, transcript, answer: {"reward": 1.0, "passed": True, "detail": {}}}) ''' @@ -67,11 +72,11 @@ def setup(unit, dir): UNEVEN_DRIVER = CALLING_DRIVER.replace('{"prompt": "model hi"}', '{"prompt": "model " + ("x" * 3000 if unit == "m5" else "hi")}') # the same, m5's agent taking its refused call in its stride and ending its turn; each score leaves a mark in the workspace SWALLOWING_DRIVER = (UNEVEN_DRIVER.replace('"model " + ("x" * 3000', '("swallow " if unit == "m5" else "model ") + ("x" * 3000') - .replace("from nullius.standard.jsonl import serve", "import os\nfrom nullius.standard.jsonl import serve") + .replace("from nullius.standard.protocols.jsonl import serve", "import os\nfrom nullius.standard.protocols.jsonl import serve") .replace('"score": lambda unit, dir, transcript, answer: {', '"score": lambda unit, dir, transcript, answer: open(os.path.join(dir, "scored"), "w").close() or {')) # one unit whose agent takes a refused call in its stride and ends its turn, and whose answer fails -GAVE_UP_DRIVER = '''from nullius.standard.jsonl import serve +GAVE_UP_DRIVER = '''from nullius.standard.protocols.jsonl import serve serve({"units": lambda dataset: {"units": ["s"]}, "setup": lambda unit, dir: {"prompt": "swallow hi"}, "score": lambda unit, dir, transcript, answer: {"reward": 0.0, "passed": False, "detail": {}}}) ''' @@ -650,7 +655,7 @@ def test_an_agent_run_needs_an_explicit_yes_to_running_unsandboxed(self): def test_selected_auxiliary_files_are_downloaded_and_given_only_to_the_driver(self): import hashlib from unittest import mock - from nullius.standard import install + from nullius.standard.requirements import install b = definitions.get("benchmark", "fakebench", ROOT) b["files"] = {"keys": {"url": "https://example.org/keys.json", "sha256": hashlib.sha256(b"{}").hexdigest()}} b["options"] = { @@ -818,7 +823,7 @@ def test_a_simulator_is_only_for_a_conversation(self): def test_the_container_backend_needs_no_yes_but_a_usable_engine(self): from unittest import mock - from nullius.standard import container + from nullius.standard.containers import container b = definitions.get("benchmark", "fakebench", ROOT) a = definitions.get("agent", "fake", ROOT) env = {"MODEL_API_URL": "http://127.0.0.1:9/v1"} @@ -886,7 +891,8 @@ def start(self, env, cwd, log, **kw): def test_on_the_docker_backend_the_agent_is_installed_in_the_base_image_whatever_this_machine(self): from unittest import mock - from nullius.standard import container, install + from nullius.standard.containers import container + from nullius.standard.requirements import install b = definitions.get("benchmark", "fakebench", ROOT) a = definitions.get("agent", "fake", ROOT) env = {"MODEL_API_URL": "http://127.0.0.1:9/v1"} @@ -907,7 +913,7 @@ def test_on_the_docker_backend_the_agent_is_installed_in_the_base_image_whatever def test_a_model_door_that_fails_to_open_still_writes_the_jobs_result(self): from unittest import mock - from nullius.standard import container + from nullius.standard.containers import container b = definitions.get("benchmark", "fakebench", ROOT) a = definitions.get("agent", "fake", ROOT) env = {"MODEL_API_URL": "http://127.0.0.1:9/v1"} diff --git a/app/tests/test_standard_setup_checks.py b/app/tests/test_standard_setup_checks.py index d4d106d6..c5b6b9b6 100644 --- a/app/tests/test_standard_setup_checks.py +++ b/app/tests/test_standard_setup_checks.py @@ -3,7 +3,9 @@ import unittest from unittest import mock -from nullius.standard import container, definitions, run +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.runner import run from tests.test_standard_setups import bench diff --git a/app/tests/test_standard_setups.py b/app/tests/test_standard_setups.py index e4b451ba..6bb88deb 100644 --- a/app/tests/test_standard_setups.py +++ b/app/tests/test_standard_setups.py @@ -13,12 +13,15 @@ from unittest.mock import patch from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from nullius.standard import definitions, hostreq, install, match, recipe, run +from nullius.standard.contract import definitions, match +from nullius.standard.pages import recipe +from nullius.standard.requirements import hostreq, install +from nullius.standard.runner import run # A paper's benchmark in miniature: two conversations, each answered by the upstream's own code (``answer``) in one # call to the model it is asked as, and scored by whether the reply came back. DRIVER = '''import json, os, sys, urllib.request -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def units(dataset, setup=None): return {"units": ["c1", "c2"] if setup else ["c1:0", "c1:1", "c2:0"]} def answer(unit, dir, setup, model, base_url, key): @@ -227,13 +230,13 @@ def test_a_reply_with_no_text_is_said_as_the_models(self): def test_a_docker_setup_still_requires_a_working_daemon(self): o, _ = definitions.setup(self.b, "original") - with patch("nullius.standard.container.unusable", return_value="daemon unavailable"): + with patch("nullius.standard.containers.container.unusable", return_value="daemon unavailable"): with self.assertRaisesRegex(run.Refused, "daemon unavailable"): run.Run(self.b, o, model="paper-1", provider="custom", jobs_root=self.tmp, env=self.env, backend="container") def test_docker_setup_runs_driver_and_linux_dependencies_with_scoped_credentials(self): from tests import docker_tier - from nullius.standard import container + from nullius.standard.containers import container why = docker_tier.why_not() if why: self.skipTest(why) @@ -412,7 +415,7 @@ def trial(self, unit, reward=None, error=False): return r def test_pass_hat_k_as_tau_bench_counts_it(self): - from nullius.standard import job + from nullius.standard.runner import job rs = [self.trial("a", 1.0), self.trial("a", 1.0), self.trial("b", 1.0), self.trial("b", 0.0)] self.assertEqual(job.pass_hat(rs), {"units": 2, "attempts": 2, "1": 0.75, "2": 0.5, "at": {"1": 0.75, "2": 1.0}}) self.assertIsNone(job.pass_hat(rs[:1] + rs[2:3])) # one attempt each: no pass^k diff --git a/app/tests/test_standard_shard.py b/app/tests/test_standard_shard.py index 5eba633e..8835af32 100644 --- a/app/tests/test_standard_shard.py +++ b/app/tests/test_standard_shard.py @@ -17,7 +17,7 @@ from nullius import workspace from nullius.runs import launches, parse -from nullius.standard import job, merge, shard +from nullius.standard.runner import job, merge, shard BENCH = {"key": "fakebench", "_ref": "fakebench", "family": "agent", "needs": ["agent.workspace/v1"], "units": {"noun": "task", "nouns": "tasks"}, "score": {"kind": "pass", "says": "the tests pass"}} diff --git a/app/tests/test_standard_skills.py b/app/tests/test_standard_skills.py index 6a072720..87d1cee4 100644 --- a/app/tests/test_standard_skills.py +++ b/app/tests/test_standard_skills.py @@ -11,7 +11,11 @@ import tempfile import unittest -from nullius.standard import cli, conform, definitions, install, match, recipe +from nullius.standard import cli +from nullius.standard.contract import definitions, match +from nullius.standard.pages import recipe +from nullius.standard.proofs import conform +from nullius.standard.requirements import install FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard") TOOLS = "agent.tools/v1" diff --git a/app/tests/test_standard_tau3_bench.py b/app/tests/test_standard_tau3_bench.py index 694afc7b..0a6ce51e 100644 --- a/app/tests/test_standard_tau3_bench.py +++ b/app/tests/test_standard_tau3_bench.py @@ -23,7 +23,9 @@ import unittest from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from nullius.standard import definitions, install, jsonl +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install APP = os.path.dirname(os.path.dirname(os.path.abspath(definitions.CATALOGUE))) # what a driver imports BENCH = definitions.get("benchmark", "tau3-bench") diff --git a/app/tests/test_standard_tools_kit.py b/app/tests/test_standard_tools_kit.py index 3cecc9cd..94d2e359 100644 --- a/app/tests/test_standard_tools_kit.py +++ b/app/tests/test_standard_tools_kit.py @@ -13,7 +13,8 @@ import tempfile import unittest -from nullius.standard import definitions, jsonl +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl KIT = os.path.join(definitions.KITS, "agent-tools-v1") APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -240,7 +241,7 @@ def test_on_docker_the_server_is_started_by_the_images_python(self): """The agent starts it in its container: this machine's interpreter, mounted over the image's, would not run.""" tmp = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp, True) - from nullius.standard import container + from nullius.standard.containers import container env = {"PATH": os.environ.get("PATH", ""), "PYTHONPATH": APP, "PYTHONDONTWRITEBYTECODE": "1", container.CHECK_IMAGE: "nullius/base:test"} d = jsonl.Proc([sys.executable, os.path.join(KIT, "driver.py")], KIT, env, os.path.join(tmp, "driver.log")).start() @@ -281,7 +282,8 @@ def test_a_proof_on_an_older_kit_is_still_a_proof_and_says_so(self): self.assertIsNone(definitions.older_kit("agent.tools/v1", None)) def test_cli_names_an_older_proof_and_still_counts_it(self): - from nullius.standard import cli, match + from nullius.standard import cli + from nullius.standard.contract import match d = {"_kind": "agent", "label": "Bot", "key": "bot", "offers": ["agent.task/v1", "agent.tools/v1"], "proven": {"agent.task/v1": {"passed": "3/3"}, "agent.tools/v1": {"passed": "2/2"}}} self.assertEqual(cli.older(d), ["agent.tools/v1 proven on kit v1; kit v2 is current"]) diff --git a/app/tests/test_standard_trace.py b/app/tests/test_standard_trace.py index f4ea267d..4776475b 100644 --- a/app/tests/test_standard_trace.py +++ b/app/tests/test_standard_trace.py @@ -7,7 +7,7 @@ import tempfile import unittest -from nullius.standard import job +from nullius.standard.runner import job from nullius.traces import trace T = 1_800_000_000.0 diff --git a/app/tests/test_standard_ui.py b/app/tests/test_standard_ui.py index 4750b174..5caa9312 100644 --- a/app/tests/test_standard_ui.py +++ b/app/tests/test_standard_ui.py @@ -11,7 +11,9 @@ from unittest.mock import patch from nullius import execution -from nullius.standard import definitions, ports, prove, recipe +from nullius.standard.contract import definitions, ports +from nullius.standard.pages import recipe +from nullius.standard.proofs import prove FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") CONTROLS = {"nop": {"source": "nullius", "from": "Nothing runs; the answer is empty."}, diff --git a/app/tests/test_standard_units.py b/app/tests/test_standard_units.py index d7c93daa..faf6e9ca 100644 --- a/app/tests/test_standard_units.py +++ b/app/tests/test_standard_units.py @@ -22,7 +22,11 @@ from nullius import progress from nullius.harbor import feed -from nullius.standard import cli, container, definitions, install, merge, pace as pacing, run, shard +from nullius.standard import cli +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import merge, pace as pacing, run, shard from tests.test_standard_run import Echo ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") diff --git a/app/tests/test_standard_upstream_drivers.py b/app/tests/test_standard_upstream_drivers.py index 79eabc1b..4f3915ad 100644 --- a/app/tests/test_standard_upstream_drivers.py +++ b/app/tests/test_standard_upstream_drivers.py @@ -26,7 +26,11 @@ from unittest import mock from pathlib import Path -from nullius.standard import container, definitions, install, jsonl, run +from nullius.standard.containers import container +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install +from nullius.standard.runner import run from tests import docker_tier BENCH = { diff --git a/app/tests/test_standard_versions.py b/app/tests/test_standard_versions.py index 898a0dc4..7497a366 100644 --- a/app/tests/test_standard_versions.py +++ b/app/tests/test_standard_versions.py @@ -13,7 +13,9 @@ import unittest from unittest.mock import patch -from nullius.standard import cli, conform, definitions, match +from nullius.standard import cli +from nullius.standard.contract import definitions, match +from nullius.standard.proofs import conform BENCH = { "schema": "nullius.benchmark/v1", "key": "toy", "label": "Toy", "summary": "A toy.", @@ -269,7 +271,7 @@ def test_problems_of_a_version_name_it(self): self.assertIn("versions.2: datasets: at least one", bad) def test_match_and_the_recipe_name_a_version(self): - from nullius.standard import recipe + from nullius.standard.pages import recipe defs = {"benchmark": definitions.load("benchmark", self.root, every=True)[0], "agent": definitions.load("agent", self.root, every=True)[0], "capability": []} self.assertEqual(set(match.table(defs["benchmark"], defs["agent"], [])), {"toy", "toy@2"}) @@ -285,7 +287,7 @@ def test_match_and_the_recipe_name_a_version(self): self.assertEqual([(v["ref"], v["default"]) for v in page[0]["versions"]], [("toy@2", False), ("toy", True)]) def test_a_run_and_its_proof_carry_the_version(self): - from nullius.standard import prove + from nullius.standard.proofs import prove b = definitions.get("benchmark", "toy@2", self.root) got = prove.prove(b, dataset="hard", jobs_root=os.path.join(self.root, "jobs"), stamp="2026-10-12__00-00-00", say=lambda s: None) self.assertTrue(got["hard"]["nop"]["ok"], got) @@ -362,7 +364,7 @@ def test_a_fork_is_a_version_with_its_own_repository_and_commit_and_no_borrowed_ self.assertEqual(tagged["upstream"]["tag"], "fix-1") def test_each_version_is_cloned_at_its_own_commit_and_its_data_checked_by_its_own_digest(self): - from nullius.standard import install + from nullius.standard.requirements import install d = self.bench({"repository": self.upstream, "tag": "v1.0.0", "tested": self.published}, {"repository": self.fork, "tested": self.fixed}) one, fork = definitions.resolve(dict(d, _here=self.tmp), "1"), definitions.resolve(dict(d, _here=self.tmp), "fork") @@ -378,7 +380,7 @@ def test_each_version_is_cloned_at_its_own_commit_and_its_data_checked_by_its_ow self.assertNotEqual(install.driver_dir(dict(one, driver=drv), self.home), install.driver_dir(dict(fork, driver=drv), self.home)) def test_a_fetch_never_waits_on_a_password(self): - from nullius.standard import install + from nullius.standard.requirements import install self.assertEqual(install.git_env()["GIT_TERMINAL_PROMPT"], "0") def test_the_tag_is_a_plain_name_of_the_repository(self): diff --git a/app/tests/test_systemd_scope.py b/app/tests/test_systemd_scope.py index e10f1077..7d0bf0ce 100644 --- a/app/tests/test_systemd_scope.py +++ b/app/tests/test_systemd_scope.py @@ -27,7 +27,7 @@ AS_USER = """ import json, os, subprocess, time from nullius import constraints -from nullius.standard import run +from nullius.standard.runner import run asked = json.loads(os.environ["ASKED"]) out = {"check": constraints.scope_check(asked), "given": [os.environ.get(k) for k in ("XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS")]} plain = {"PATH": os.environ["PATH"]} diff --git a/app/tests/test_tau3_setups.py b/app/tests/test_tau3_setups.py index 5a940a14..8e5fc3e6 100644 --- a/app/tests/test_tau3_setups.py +++ b/app/tests/test_tau3_setups.py @@ -21,7 +21,9 @@ import unittest from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from nullius.standard import definitions, install, jsonl +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install APP = os.path.dirname(os.path.dirname(os.path.abspath(definitions.CATALOGUE))) BENCH = definitions.get("benchmark", "tau3-bench") diff --git a/app/tests/test_unified_cli.py b/app/tests/test_unified_cli.py index 06243c82..c82840e2 100644 --- a/app/tests/test_unified_cli.py +++ b/app/tests/test_unified_cli.py @@ -14,7 +14,9 @@ from unittest.mock import patch from nullius import cli -from nullius.standard import cli as standard_cli, definitions, pins +from nullius.standard import cli as standard_cli +from nullius.standard.contract import definitions +from nullius.standard.proofs import pins APP = Path(__file__).resolve().parents[1] @@ -107,7 +109,7 @@ def test_settings_are_loaded_before_command_module_initialization(self): exec(INVOCATION) except SystemExit as exc: assert exc.code == 0 -from nullius.standard import install +from nullius.standard.requirements import install import os assert install.HOME == os.environ['STANDARD_DIR'], install.HOME """.replace("INVOCATION", repr(invocation)) diff --git a/app/ui_tests/test_add_dialog.py b/app/ui_tests/test_add_dialog.py index 6499002b..f6c62fc9 100644 --- a/app/ui_tests/test_add_dialog.py +++ b/app/ui_tests/test_add_dialog.py @@ -5,7 +5,7 @@ import subprocess import unittest -from nullius.standard import howto +from nullius.standard.pages import howto SCRIPT = Path(__file__).resolve().parents[1] / "static" / "catalogue" / "add.js" diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index ae4d363e..10d35464 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -16,7 +16,7 @@ from unittest.mock import patch from nullius import execution -from nullius.standard import definitions +from nullius.standard.contract import definitions from .test_routes import web ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tests", "fixtures", "standard", "catalogue") @@ -118,7 +118,7 @@ def test_active_catalogue_tree_is_open_before_javascript(self): self.assertTrue(block[1].startswith('>')) def test_kits_catalogue_and_proof_links(self): - from nullius.standard import ports + from nullius.standard.contract import ports from html import unescape page = self.get("/kits").get_data(as_text=True) for port, info in ports.PORTS.items(): diff --git a/app/ui_tests/test_capped_job.py b/app/ui_tests/test_capped_job.py index 3f3ff983..40e40183 100644 --- a/app/ui_tests/test_capped_job.py +++ b/app/ui_tests/test_capped_job.py @@ -13,7 +13,8 @@ from nullius import workspace from nullius.runs import classify -from nullius.standard import job, ledger +from nullius.standard.calls import ledger +from nullius.standard.runner import job from ui_tests.builder_support import AGENT as CUSTOM_AGENT, APP, PIN, CompilerCase from .test_routes import web diff --git a/app/ui_tests/test_every_route.py b/app/ui_tests/test_every_route.py index 4bf32406..f2b3441c 100644 --- a/app/ui_tests/test_every_route.py +++ b/app/ui_tests/test_every_route.py @@ -150,10 +150,10 @@ def test_every_get_rule_answers(self): local["key"] = catalog.load().listed_benchmarks[0].key # an agent's or a capability's page is the standard's definition of that key if raw in ("/agents/", "/capabilities/", "/features/"): - from nullius.standard import definitions + from nullius.standard.contract import definitions local["key"] = definitions.load("agent" if raw.startswith("/agents") else "capability")[0][0]["key"] if raw == "/kits/": - from nullius.standard import definitions + from nullius.standard.contract import definitions local["key"] = definitions.kits()[0]["key"] # its edit form is for a Harbor entry on the hub or in the registry if raw == "/benchmarks//edit": diff --git a/app/ui_tests/test_launch_shards.py b/app/ui_tests/test_launch_shards.py index 1738feca..4733abe7 100644 --- a/app/ui_tests/test_launch_shards.py +++ b/app/ui_tests/test_launch_shards.py @@ -19,7 +19,7 @@ from nullius import execution, hosts, workspace from nullius.runs import parse -from nullius.standard import merge +from nullius.standard.runner import merge from tests.test_standard_shard import write_shard from .test_controls_apart import text_of from .test_routes import web diff --git a/app/ui_tests/test_licences_page.py b/app/ui_tests/test_licences_page.py index f2adaad4..d3898b4f 100644 --- a/app/ui_tests/test_licences_page.py +++ b/app/ui_tests/test_licences_page.py @@ -19,8 +19,8 @@ from unittest.mock import patch from nullius import secrets -from nullius.standard import definitions -from nullius.standard import recipe as standard_recipe +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe as standard_recipe from .test_agents import fixture_load from .test_routes import web diff --git a/app/ui_tests/test_live_board.py b/app/ui_tests/test_live_board.py index 01dc5738..9125b7d3 100644 --- a/app/ui_tests/test_live_board.py +++ b/app/ui_tests/test_live_board.py @@ -25,7 +25,7 @@ from pathlib import Path from unittest.mock import patch from nullius.runs import live, parse -from nullius.standard import ledger +from nullius.standard.calls import ledger from nullius import workspace APP_DIR = Path(__file__).resolve().parents[1] diff --git a/app/ui_tests/test_prerequisites_route.py b/app/ui_tests/test_prerequisites_route.py index 717f9361..20d2e467 100644 --- a/app/ui_tests/test_prerequisites_route.py +++ b/app/ui_tests/test_prerequisites_route.py @@ -13,7 +13,7 @@ from unittest.mock import patch from nullius import execution, prerequisites, providers -from nullius.standard import hostreq +from nullius.standard.requirements import hostreq from .test_routes import web STOPPED = "docker is installed but not usable by this user: Cannot connect to the Docker daemon" diff --git a/app/ui_tests/test_settings_page.py b/app/ui_tests/test_settings_page.py index b8dacaf4..57261a80 100644 --- a/app/ui_tests/test_settings_page.py +++ b/app/ui_tests/test_settings_page.py @@ -995,7 +995,8 @@ def test_the_sandbox_is_asked_when_shown_and_a_login_goes_to_docker_only(self): def test_data_provider_save_is_local_guarded_and_never_echoes_token(self): from nullius import secrets - from nullius.standard import definitions, run + from nullius.standard.contract import definitions + from nullius.standard.runner import run gaia = run.Licences(definitions.get("benchmark", "gaia")) # GAIA's HF_TOKEN: this provider's alone with tempfile.TemporaryDirectory() as folder, patch.dict(os.environ, {"SECRETS_DIR": folder}): headers = {"Origin": "http://localhost", "X-CSRF-Token": self.token()} diff --git a/app/ui_tests/test_use_bundled.py b/app/ui_tests/test_use_bundled.py index 3b5c2254..efc592d7 100644 --- a/app/ui_tests/test_use_bundled.py +++ b/app/ui_tests/test_use_bundled.py @@ -7,7 +7,7 @@ from unittest.mock import patch from nullius.catalogue import catalog, storage -from nullius.standard import definitions +from nullius.standard.contract import definitions from .test_routes import web diff --git a/app/web/agents.py b/app/web/agents.py index b791d254..1d130acf 100644 --- a/app/web/agents.py +++ b/app/web/agents.py @@ -9,7 +9,7 @@ when the open workspace holds that job - and every benchmark of its family, the ones it fits linked to a builder recipe for the pair and the others with the reasons. *Prove its ports* runs its conformance -kits as a run of this machine (``standard/recipe.py``, ``conformance``), the +kits as a run of this machine (``standard/pages/recipe.py``, ``conformance``), the record rewritten by what passes. An agent or a capability with several versions is one card, its default @@ -28,8 +28,9 @@ from flask import abort, flash, redirect, render_template, request, url_for from nullius import execution, paths, providers from nullius.catalogue import storage -from nullius.standard import conform, definitions, howto, match, ports -from nullius.standard import recipe as standard_recipe +from nullius.standard.contract import definitions, match, ports +from nullius.standard.pages import howto, recipe as standard_recipe +from nullius.standard.proofs import conform from .core import app from . import shared diff --git a/app/web/builder.py b/app/web/builder.py index cacd9a6d..00d9e19a 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -13,8 +13,9 @@ from nullius.harbor import source as harbor_source from nullius.catalogue import catalog from nullius.recipes import launch as command_builder -from nullius.standard import definitions, hostreq -from nullius.standard import recipe as standard_recipe +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe as standard_recipe +from nullius.standard.requirements import hostreq from .core import app @@ -219,7 +220,7 @@ def _licence_states() -> dict: benchmark whose environments need licences: what is held of each name they declare, a data provider's token in that provider's store.""" from nullius import secrets - from nullius.standard import definitions + from nullius.standard.contract import definitions out: dict = {} for b in definitions.load("benchmark", every=True)[0]: for s in definitions.secrets_of(b): diff --git a/app/web/catalogue.py b/app/web/catalogue.py index 4c0fbde6..57911313 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -12,9 +12,9 @@ from flask import abort, flash, jsonify, redirect, render_template, request, url_for from nullius import execution, paths, providers, secrets, settings from nullius.catalogue import catalog, citation, harbor_entry, sources, storage -from nullius.standard import definitions as standard_definitions -from nullius.standard import howto, prove -from nullius.standard import recipe as standard_recipe +from nullius.standard.contract import definitions as standard_definitions +from nullius.standard.pages import howto, recipe as standard_recipe +from nullius.standard.proofs import prove from .core import app from . import execute diff --git a/app/web/execute.py b/app/web/execute.py index 6c61f26f..5dfda462 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -8,7 +8,7 @@ from flask import abort, jsonify, request, url_for from nullius import execution, hosts, prerequisites, prices, providers, settings from nullius.harbor import source as harbor_source -from nullius.standard import recipe as standard_recipe +from nullius.standard.pages import recipe as standard_recipe from .core import app from . import shared diff --git a/app/web/filters.py b/app/web/filters.py index 71304b90..640b9bd0 100644 --- a/app/web/filters.py +++ b/app/web/filters.py @@ -8,7 +8,8 @@ from nullius import importers as harnesses from nullius.runs import classify from nullius import workspace -from nullius.standard import ledger, ports, definitions +from nullius.standard.calls import ledger +from nullius.standard.contract import ports, definitions from .core import app from . import shared diff --git a/app/web/runs.py b/app/web/runs.py index 9ae2e702..88d4c115 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -177,7 +177,7 @@ def _cut_short(r) -> str: return "" -# A shard's job as a recipe names it (standard/recipe.py): ``-shard-of``. +# A shard's job as a recipe names it (standard/pages/recipe.py): ``-shard-of``. _SHARD = re.compile(r"-shard-(\d+)of\d+$") # A participant's state is its shards' most telling: one still working, else the one that ended worst. _TELLING = ("running", "preparing", "stopping", "paused", "queued", "failed", "refused", "stopped", execution.NOT_RUN, diff --git a/app/web/settings.py b/app/web/settings.py index 19164b1b..e3dcb76c 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -6,8 +6,8 @@ import socket from flask import abort, flash, jsonify, redirect, render_template, request, url_for from nullius import constraints, execution, hosts, paths, prerequisites, prices, providers, sandbox, secrets, settings -from nullius.standard import container -from nullius.standard import recipe as standard_recipe +from nullius.standard.containers import container +from nullius.standard.pages import recipe as standard_recipe from nullius.judge import client from .core import app diff --git a/docs/agents/add-manually.md b/docs/agents/add-manually.md index 67d3a126..893cef8c 100644 --- a/docs/agents/add-manually.md +++ b/docs/agents/add-manually.md @@ -18,7 +18,7 @@ import json import shutil from pathlib import Path from nullius import paths, settings -from nullius.standard import definitions +from nullius.standard.contract import definitions settings.load(paths.settings_file()) source = Path(definitions.entry_dir("agent", "goose")) diff --git a/docs/benchmarks/osworld1-machine.md b/docs/benchmarks/osworld1-machine.md index 534b2972..aff3a55d 100644 --- a/docs/benchmarks/osworld1-machine.md +++ b/docs/benchmarks/osworld1-machine.md @@ -33,7 +33,8 @@ By default the command line runs 4 tasks at once: four VMs, 16 cores and 16 GB o ```bash eval "$(PYTHONPATH=app python3 -c ' import shlex - from nullius.standard import definitions, install + from nullius.standard.contract import definitions + from nullius.standard.requirements import install b = definitions.get("benchmark", "osworld1") print("ENV=" + shlex.quote(install.driver_dir(b))) print("UP=" + shlex.quote(install.upstream_dir(b))) @@ -45,7 +46,8 @@ By default the command line runs 4 tasks at once: four VMs, 16 cores and 16 GB o ```bash PYTHONPATH=app python3 -c ' - from nullius.standard import definitions, install + from nullius.standard.contract import definitions + from nullius.standard.requirements import install b = definitions.get("benchmark", "osworld1") print(install.driver_packages(b)) ' diff --git a/docs/cli/shard-and-merge.md b/docs/cli/shard-and-merge.md index e9e9fc9e..eef3b1e6 100644 --- a/docs/cli/shard-and-merge.md +++ b/docs/cli/shard-and-merge.md @@ -11,10 +11,10 @@ nullius standard merge jobs_standard/*__shard-* -o jobs_standard/humaneval-oracl | Rule | Detail | | --- | --- | | No central relay | Each unit's relay runs on its machine with its own key; a provider's limit is per key | -| Shards by the unit's id | `sha256(unit id) mod N` (`app/nullius/standard/shard.py`): every unit in exactly one shard, new units leave the rest in place; changing N moves most. Order: `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6`: the first six of shard 1) | +| Shards by the unit's id | `sha256(unit id) mod N` (`app/nullius/standard/runner/shard.py`): every unit in exactly one shard, new units leave the rest in place; changing N moves most. Order: `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6`: the first six of shard 1) | | A unit keeps its place | `u0042` is the 43rd unit of the dataset in every shard; shard jobs never share a trial name | | One launch | Each shard's `config.json` records `standard.shard` (`index`, `of`, `units_total`, `partition`, `planned`, `limit`) and `standard.launch`: `--launch`, or the day (UTC), benchmark, agent or capability and model. The runs page groups them until merged, each agent's or control's shards as one row with the numbers `merge` would give and the units not run beside the count; the row unfolds into one row per shard. Once merged, it shows and counts the merged job in place of the source jobs named by its `merged_from` record. Unmerged jobs still count; source job files are kept | -| `merge JOB_DIR... -o OUT` | One job (`app/nullius/standard/merge.py`): trials hard-linked, each `result.json` naming the merged job and shard; the job's `result.json` recomputed; `config.json` with `merged_from` for `shard`. Different launches, versions, datasets, agents, models, backends or N refused unless `--force`; lists of different units and two trials of one unit always. Units no shard ran are named | +| `merge JOB_DIR... -o OUT` | One job (`app/nullius/standard/runner/merge.py`): trials hard-linked, each `result.json` naming the merged job and shard; the job's `result.json` recomputed; `config.json` with `merged_from` for `shard`. Different launches, versions, datasets, agents, models, backends or N refused unless `--force`; lists of different units and two trials of one unit always. Units no shard ran are named | | A list of units | `--units FILE` on every machine: each shard runs the listed units of its own; its `units_total` counts the listed units ([Run a benchmark](run.md#a-list-of-units)). `merge` compares the units each list holds, in any order. A list's file name, comments and sha256 may differ from shard to shard; the merged job records the first shard's list | | A spending cap | Each shard's own; the builder shares a recipe's cap over its shards. `merge` adds them into one `budget` when every shard had one | | `prove --shard I/N` | Controls and leak on that shard, units on all; recorded as `shard` | diff --git a/docs/field-guide.md b/docs/field-guide.md index 8fbffd36..4a87d85a 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -81,7 +81,7 @@ Any Harbor run reads as is; a run from another harness once an importer has conv `nullius/importers/` -A run Harbor never wrote (ATIF trajectories, an OpenTelemetry export), converted into a job directory first. On such rows the importer decides what a number is. A standard run is written in Harbor's shape by Nullius itself (nullius/standard/job.py). +A run Harbor never wrote (ATIF trajectories, an OpenTelemetry export), converted into a job directory first. On such rows the importer decides what a number is. A standard run is written in Harbor's shape by Nullius itself (nullius/standard/runner/job.py). *Layer 1 · run* diff --git a/docs/standard.md b/docs/standard.md index f6f0068b..d1c024d6 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -142,13 +142,13 @@ record); verifier/reward.txt and score.json | --- | --- | | Units | Run `-j` at a time, each with its own workspace (a git repository of its own), home and relay | | A relay per unit | Its record is the trial's `.work/relay`; the judge and simulated user are routes on it (`-judge`, `-simulator`). An option whose driver embeds gets a relay of the run's own before any unit, recorded in `.work/relay-benchmark` as the benchmark's cost | -| Backends (`--backend`) | `local`: processes on this machine. `container`: each unit's agent or capability in a container, its relay beside it (`standard/container.py`), on Docker, or on Podman 4.7 or later where `docker` is missing or is podman under that name. Podman needs no Docker API socket and no `containers.conf` change. Where a `docker` program is on the PATH, Nullius runs it even when it does not answer. The reason it gives then says that podman is on the machine. `docker`, the old name of `container`, is still accepted. For agent and capability runs the driver stays on the machine; Original setups instead containerize the driver and its answerer (`standard/setup_container.py`); in a container a check that runs what the agent left (the workspace kit's test) runs it in a throwaway, network-less container of the unit's image (`container.check_argv`), and no check reads through a link the agent planted; `config.json` records the backend and the image | +| Backends (`--backend`) | `local`: processes on this machine. `container`: each unit's agent or capability in a container, its relay beside it (`standard/containers/container.py`), on Docker, or on Podman 4.7 or later where `docker` is missing or is podman under that name. Podman needs no Docker API socket and no `containers.conf` change. Where a `docker` program is on the PATH, Nullius runs it even when it does not answer. The reason it gives then says that podman is on the machine. `docker`, the old name of `container`, is still accepted. For agent and capability runs the driver stays on the machine; Original setups instead containerize the driver and its answerer (`standard/containers/setup_container.py`); in a container a check that runs what the agent left (the workspace kit's test) runs it in a throwaway, network-less container of the unit's image (`container.check_argv`), and no check reads through a link the agent planted; `config.json` records the backend and the image | | Progress | One line per stage on stderr and in `progress.jsonl`: `[nullius] stage=install agent=codex@2.2.2 state=done seconds=41 at=...` (`start`, `done`, `cached`, `failed`; a download's bytes every 5 s) for the base image, an environment, the upstream, a dataset, `driver.install` and the agent; then `stage=units n=10`, `stage=unit i=3 of=10 unit=... outcome=passed`, `stage=done`; `stage=refused` alone for a run refused first. From `stage=units` the job also writes `events.jsonl`, Harbor's live feed | | Outcomes | A last model call that got a 429 is `rate_limited`, a refused key an API error, both outside the agent's rate, unless the unit passed; a turn past its limit is the agent's timeout. `"kind": "score"` leaves a score and no pass | | Rate limits | After a unit ends `rate_limited`, no unit starts for 5 s, doubling while units keep ending so (up to 300 s) and reset by any other end; `stage=units state=progress` says the pause and how many run. Each `rate_limited` unit is run once more after the others, one at a time: its first attempt moves whole to `retried//`, the second is the trial and counts. Not after a Stop, a refused key or the spending cap, which counts both attempts | | The relay | Headers pass through except the credentials, replaced by the relay's key; `agent/calls.jsonl` names them, never their values. A 429 reaches the agent as it came, never retried. Every call goes as the run's model, the one asked recorded as `model_asked`, except `model.side_models`, sent as asked and recorded `side`. Provider `anthropic` speaks Anthropic's Messages (`ANTHROPIC_API_KEY` as `x-api-key`) | | Constraints (`--constraint KEY=VALUE`) | What the machine allows Nullius, from Settings ([constraints](settings/run-hosts.md#constraints)): flags on every container the run starts on the machine, on either backend; a systemd scope for each process the run starts there (its drivers, and its agents and capabilities on the local backend); the most units at a time; the CPU affinity; the driver's `CUDA_VISIBLE_DEVICES`. Before the first unit, the run checks the container caps on the engine and the scope caps on systemd: the local backend refuses a cap that no scope holds, and the container backend runs its drivers without a scope. `config.json` records the values under `standard.constraints` | -| A spending cap (`--max-usd`, `--max-usd-per-unit`) | Each relay books a call in the job's ledger (`.work/ledger`, `standard/ledger.py`) before sending it, and refuses the one that does not fit the run's cap or its unit's ([Run a benchmark](cli/run.md#a-spending-cap)) | +| A spending cap (`--max-usd`, `--max-usd-per-unit`) | Each relay books a call in the job's ledger (`.work/ledger`, `standard/calls/ledger.py`) before sending it, and refuses the one that does not fit the run's cap or its unit's ([Run a benchmark](cli/run.md#a-spending-cap)) | ## Safety @@ -190,7 +190,7 @@ A benchmark whose tools are its upstream's own code declares `mcp_servers`, run "mcp": [{"name": "airline", "server": "domain", "env": {"TAU_DOMAIN": "airline", "TAU_AT": ""}}] ``` -The agent's session still gets a stdio server (`standard/mcp_machine.py`): +The agent's session still gets a stdio server (`standard/containers/mcp_machine.py`): | Backend | How the agent reaches it | | --- | --- | @@ -257,7 +257,7 @@ An entry with `"provider": "huggingface"` is a `value` to the `driver`, read fro | --- | --- | --- | | `value` (default) | A key or access token, the variable `name` of its process | By name, never on an argument list | | `file` | A licence file; `env` names a variable holding its path, required on local processes | Mounted read-only at `path` (absolute, not under `/proc`, `/sys` or `/dev`) | -| `server` | A licence server, `host:port`, as the variable `name` | A forwarder beside the relay (`standard/forward.py`) under the server's own name, the one address the agent may reach; an IPv4 address as `licence-server-`, `host.docker.internal` the machine the run is on. On a rootless engine or Podman on Linux, `host.docker.internal` is reached as `licence-server-` through a Unix socket | +| `server` | A licence server, `host:port`, as the variable `name` | A forwarder beside the relay (`standard/containers/forward.py`) under the server's own name, the one address the agent may reach; an IPv4 address as `licence-server-`, `host.docker.internal` the machine the run is on. On a rootless engine or Podman on Linux, `host.docker.internal` is reached as `licence-server-` through a Unix socket | | Rule | Detail | | --- | --- | @@ -314,7 +314,7 @@ A benchmark whose tasks are containers (their own Dockerfile and `FROM`) says so | Task internet ends before the check | When `internet: true`, `HTTP_PROXY`/`HTTPS_PROXY` name the proxy; internal relay and benchmark server aliases remain direct through `NO_PROXY`. `agent/egress.log` records allowed and refused traffic. The proxy is removed before verification, also after failed or cancelled work; failure to remove it prevents verification. Tasks without the flag retain their existing isolation | | The check runs where the work is | `score` is sent `verified: {exit, timed_out, output, dir, collected}`; the driver never runs docker. What changed in the container is `agent/container-changes.txt` | | Nothing of the agent runs during the check | Every process but init and the keep-alive is stopped, then killed; `verifier/stopped.txt` names each, one that cannot be stopped is a `VerifierError`. `keep_processes: true` lets them run on, free to alter the tests | -| The check's way out is a proxy | `network: true` adds a proxy container (`standard/egress.py`) as `egress`, told to the check's command alone (`HTTP_PROXY`, `HTTPS_PROXY`); it connects only to global addresses, never `169.254.0.0/16`, `100.64.0.0/10`, private ranges, loopback or the docker bridge. `verifier/egress.log` keeps what it let through and refused. A download has to honour the proxy variables | +| The check's way out is a proxy | `network: true` adds a proxy container (`standard/containers/egress.py`) as `egress`, told to the check's command alone (`HTTP_PROXY`, `HTTPS_PROXY`); it connects only to global addresses, never `169.254.0.0/16`, `100.64.0.0/10`, private ranges, loopback or the docker bridge. `verifier/egress.log` keeps what it let through and refused. A download has to honour the proxy variables | | Controls | `nop` leaves the image as it is; `oracle` replies `{"answer": "", "solve": {copy, write, run, seconds}}`, run in the container. Neither needs the container backend, both need Docker or Podman | | Where it cannot run | An agent's unit needs the container backend (never `local_ok`); a capability benchmark has no own image | @@ -338,10 +338,10 @@ N machines are N runs of the same command, each with `--shard I/N`, and one merg | Rule | Detail | | --- | --- | | No central relay | Each unit's relay runs on its own machine with the key it was handed; split a launch over keys of their own if one cannot carry it. A spending cap is each shard's own | -| Shards by the unit's id | `sha256(unit id) mod N` (`standard/shard.py`); changing N moves most units. Order: the driver's `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6` is the first six units of shard 1) | +| Shards by the unit's id | `sha256(unit id) mod N` (`standard/runner/shard.py`); changing N moves most units. Order: the driver's `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6` is the first six units of shard 1) | | A unit keeps its place | `u0042` is the 43rd unit of the whole dataset in every shard | | One launch | Each shard's `config.json` records `standard.shard` (`index`, `of`, `units_total`, `partition`, `planned`, `limit`) and `standard.launch` (`--launch`, else the UTC day, benchmark, agent or capability and model). With `--units`, `units_total` counts the listed units. The shards' lists hold the same units; a list's file name, comments and sha256 may differ from shard to shard | -| `cli merge JOB_DIR... -o OUT` | One job (`standard/merge.py`): trials hard-linked, `result.json` recomputed, `config.json` with `merged_from`. Shards that differ in launch, version, dataset, agent, model, backend or N are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. `merge` compares the units each list holds, in any order; the sha256 is kept in the record only | +| `cli merge JOB_DIR... -o OUT` | One job (`standard/runner/merge.py`): trials hard-linked, `result.json` recomputed, `config.json` with `merged_from`. Shards that differ in launch, version, dataset, agent, model, backend or N are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. `merge` compares the units each list holds, in any order; the sha256 is kept in the record only | | `cli prove --shard I/N` | The controls and the leak check on that shard's units; each record says `shard` | ```bash title="Two machines, one merge" @@ -462,7 +462,7 @@ The upstream's dependencies go in `driver.install` (a capability's `install` is - **`embeddings`**: the value gets the run's own relay as the driver's `OPENAI_BASE_URL` (and its MCP servers'), the model pinned on its route. Bare OpenAI model names work on OpenAI or OpenRouter; qualified names such as `qwen/qwen3-embedding-8b` require OpenRouter. On OpenRouter, bare names acquire their maker's prefix in both the price inventory and the sent request. A judge route handed to litellm goes in its `api_base`. - **`reranker`**: the chat model used by the upstream search. The driver receives one `OPENAI_BASE_URL`: embeddings requests use the embedding pin when present, while chat and Responses requests use the reranker pin. A BM25 reranker needs no embedding model. Both models count toward the run's price requirements and spending cap. - **`files`**: a benchmark declares `{name: {url: "https://…", sha256: "…"}}`; an option value names them with `needs.files: [name]`. A needs block may add `when: {other_option: [values]}` to require its resources only under those selections. Only active options and needs fetch files, once per digest under `STANDARD_DATA_DIR` (the dataset cache by default), refusing a mismatched download. The driver receives each path as `NULLIUS_FILE_` (upper case). Names use lower case letters and underscores. -- **`host`**: `{summary, check: [programs on PATH], install: {apt, npm}}` (`standard/hostreq.py`), whatever the backend; hardware (a CUDA GPU, by `nvidia-smi`) has no `install`. Optional `gpu_memory_mb` is a positive whole number of MiB required on the largest GPU, read with `nvidia-smi` (total memory, not free memory or the sum across cards). The local builder and run startup refuse insufficient memory with the required and available amounts; an unavailable query names `nvidia-smi` instead. Remote GPU memory is checked when the run starts on the host. A run refuses missing programs and says the install commands when supplied. +- **`host`**: `{summary, check: [programs on PATH], install: {apt, npm}}` (`standard/requirements/hostreq.py`), whatever the backend; hardware (a CUDA GPU, by `nvidia-smi`) has no `install`. Optional `gpu_memory_mb` is a positive whole number of MiB required on the largest GPU, read with `nvidia-smi` (total memory, not free memory or the sum across cards). The local builder and run startup refuse insufficient memory with the required and available amounts; an unavailable query names `nvidia-smi` instead. Remote GPU memory is checked when the run starts on the host. A run refuses missing programs and says the install commands when supplied. - **One integration per benchmark.** Add supported behavior as options on that entry, not numbered integration revisions. Record the selected options with each run and revalidate affected proofs. ### An agent diff --git a/pyproject.toml b/pyproject.toml index 1b2a9d66..66f21a56 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,7 +39,10 @@ include-package-data = false packages = [ "nullius", "nullius.catalogue", "nullius.compare", "nullius.harbor", "nullius.importers", "nullius.judge", "nullius.recipes", "nullius.runs", - "nullius.standard", "nullius.traces", "_nullius_app", "_nullius_app.web", + "nullius.standard", "nullius.standard.calls", "nullius.standard.containers", + "nullius.standard.contract", "nullius.standard.pages", "nullius.standard.proofs", + "nullius.standard.protocols", "nullius.standard.requirements", "nullius.standard.runner", + "nullius.traces", "_nullius_app", "_nullius_app.web", ] [tool.setuptools.package-dir] From e030e9de4064e5138c13656dba276ce003ae5d2e Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 16 Nov 2026 17:01:50 +0100 Subject: [PATCH 02/14] refactor: write a file whole, lock it and digest it in one place Thirteen modules each wrote a file under a temporary name and renamed it into place, in three ways: some with a name of their own and a clean-up, some with a name of their own and none, and four (the judge's store, a run's record, a definition, a Harbor pin's record) with one fixed name, which is what workspace.py documented as the cause of a 500 when two writers met. Three modules each held an flock the same way, and two read a file's sha256 with the same loop. nullius/ondisk.py does each once: write_whole, locked, sha256_of. Every site calls it and keeps what it wrote before. The same bytes and the same permissions were checked site by site against the previous code: 0600 for settings, licences, the constraints store and a Harbor entry, the mode given for a migrated file, the process default elsewhere. What changes: every temporary file is now `...part` beside its target, its own for each write, and removed when the write fails. Two tests that looked for a left-over `.tmp` look for `.part`. The module is not named `files`: 174 local variables are, and one of them hid it in the container backend. --- AGENTS.md | 2 +- app/nullius/catalogue/harbor_entry.py | 15 +-- app/nullius/constraints.py | 14 +-- app/nullius/execution.py | 8 +- app/nullius/harbor/source.py | 8 +- app/nullius/importers/atif.py | 12 +- app/nullius/judge/store.py | 8 +- app/nullius/migrate.py | 13 +-- app/nullius/ondisk.py | 63 +++++++++++ app/nullius/prices.py | 11 +- app/nullius/providers.py | 9 +- app/nullius/secrets.py | 16 +-- app/nullius/settings.py | 31 ++---- app/nullius/standard/calls/ledger.py | 16 +-- app/nullius/standard/containers/container.py | 6 +- app/nullius/standard/contract/definitions.py | 16 +-- app/nullius/standard/requirements/install.py | 23 +--- app/nullius/workspace.py | 33 +----- app/tests/test_ondisk.py | 109 +++++++++++++++++++ app/tests/test_secrets.py | 2 +- app/tests/test_standard_install.py | 3 +- app/tests/test_standard_setups.py | 3 +- app/tests/test_standard_versions.py | 5 +- app/tests/test_workspace.py | 4 +- 24 files changed, 237 insertions(+), 193 deletions(-) create mode 100644 app/nullius/ondisk.py create mode 100644 app/tests/test_ondisk.py diff --git a/AGENTS.md b/AGENTS.md index 30600e4a..4624e742 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,7 @@ and its resources. The source layout stays under `app/`. (the reference `agent`; JiuwenSwarm's `agent` and mini-swe-agent's `run`, the wrappers that start them) and `catalogue/capabilities//` (the keyword-memory `capability`); `workspace` (and `workspace_cli`, its shell command), `cli` and `__main__` (the unified `nullius` and `python -m nullius` commands), - `paths` (user config, data and cache locations), `prices` (the user's model price list: fetched on request, never by a run; what a cost is estimated from), `migrate` (explicit copying of legacy checkout storage), `settings`, `hosts`, `constraints` (what Nullius may use on each machine: one table, the container and systemd scope probes, the warnings), `execution`, `progress` (what a run is doing, one line per stage), `prerequisites` (what a recipe needs of each machine it runs on, asked before Run and again as it starts), `onboarding` (the Getting started checklist: what this machine + `paths` (user config, data and cache locations), `ondisk` (a file written whole then renamed into place, a lock, a digest), `prices` (the user's model price list: fetched on request, never by a run; what a cost is estimated from), `migrate` (explicit copying of legacy checkout storage), `settings`, `hosts`, `constraints` (what Nullius may use on each machine: one table, the container and systemd scope probes, the warnings), `execution`, `progress` (what a run is doing, one line per stage), `prerequisites` (what a recipe needs of each machine it runs on, asked before Run and again as it starts), `onboarding` (the Getting started checklist: what this machine says is done, and where each step is done), `gitrefs` (a repository's branches and tags, by `git ls-remote`), `secrets` (a benchmark's licences, kept per benchmark outside the repository, and the Hugging Face token of Data providers), `sandbox` (Docker's state, and the Docker Hub login Data providers uses) and `redact` at the top. - `app/templates/`, `app/static/` — the interface, grouped by the same capability diff --git a/app/nullius/catalogue/harbor_entry.py b/app/nullius/catalogue/harbor_entry.py index 9de03c2b..8484e6c1 100644 --- a/app/nullius/catalogue/harbor_entry.py +++ b/app/nullius/catalogue/harbor_entry.py @@ -25,11 +25,12 @@ import json import os import re -import tempfile import tomllib from dataclasses import replace from urllib import error, parse, request +from nullius import ondisk + from . import catalog, storage HUB = "https://hub.harborframework.com" @@ -211,17 +212,7 @@ def problems(entry: dict, root: str | None = None, replacing: str = "", dataset: def _write(path: str, entry: dict) -> None: - temporary = None - try: - with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=os.path.dirname(path), - prefix=".entry-", delete=False) as fh: - temporary = fh.name - json.dump(entry, fh, indent=2, ensure_ascii=False) - fh.write("\n") - os.replace(temporary, path) - finally: - if temporary is not None and os.path.exists(temporary): - os.unlink(temporary) + ondisk.write_whole(path, json.dumps(entry, indent=2, ensure_ascii=False) + "\n", mode=0o600) def save(entry: dict, root: str | None = None) -> str: diff --git a/app/nullius/constraints.py b/app/nullius/constraints.py index 4b8ec516..d8699484 100644 --- a/app/nullius/constraints.py +++ b/app/nullius/constraints.py @@ -61,14 +61,13 @@ import shlex import stat import subprocess -import tempfile import textwrap import threading import time from dataclasses import dataclass, field from typing import Callable, Dict, List, Optional, Sequence, Tuple -from nullius import paths +from nullius import ondisk, paths SETTING = "HOST_CONSTRAINTS" LOCAL = "local" # this machine, as a recipe's Where names it @@ -628,16 +627,7 @@ def rekey(text: str, old: str, new: Optional[str]) -> Optional[str]: def _write(doc: dict, env=None) -> None: """The store, written whole to a file of its own, then renamed.""" - out = store_path(env) - os.makedirs(os.path.dirname(out), exist_ok=True) - fd, part = tempfile.mkstemp(dir=os.path.dirname(out), prefix="capacity.json.", suffix=".part") - try: - with os.fdopen(fd, "w", encoding="utf-8") as f: - json.dump(doc, f, indent=1, sort_keys=True) - os.replace(part, out) - except BaseException: - os.unlink(part) - raise + ondisk.write_whole(store_path(env), json.dumps(doc, indent=1, sort_keys=True), mode=0o600) def engine_less(found: Optional[dict]) -> bool: diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 99c50e26..22452354 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -122,7 +122,7 @@ from datetime import datetime, timezone from typing import Callable, Dict, List, Optional -from nullius import hosts, paths, prices as price_list, progress, redact, secrets, settings +from nullius import hosts, ondisk, paths, prices as price_list, progress, redact, secrets, settings from nullius.harbor import source as harbor_source from nullius.standard.containers import container from nullius.standard.runner import payload as standard_payload @@ -485,11 +485,7 @@ def _save(self) -> None: "catalogue_on_target": self.catalogue_on_target, "workspace": self.workspace, "launched": self.launched, "seen_trials": [list(k) for k in sorted(self._seen_trials, key=str)]} try: - os.makedirs(self.dir, exist_ok=True) - tmp = os.path.join(self.dir, RECORD + ".tmp") - with open(tmp, "w", encoding="utf-8") as fh: - json.dump(data, fh, indent=1) - os.replace(tmp, os.path.join(self.dir, RECORD)) + ondisk.write_whole(os.path.join(self.dir, RECORD), json.dumps(data, indent=1)) except OSError: pass diff --git a/app/nullius/harbor/source.py b/app/nullius/harbor/source.py index a6126fb4..326d0b7d 100644 --- a/app/nullius/harbor/source.py +++ b/app/nullius/harbor/source.py @@ -57,7 +57,7 @@ from typing import Callable, Dict, List, Optional from urllib import error, request -from nullius import gitrefs +from nullius import gitrefs, ondisk PACKAGE = "harbor" PYPI = "https://pypi.org/pypi" @@ -444,11 +444,7 @@ def ensure(pin: dict, pins: str, run: Optional[Callable] = None, fetch: Optional def _write(directory: str, name: str, data: dict) -> None: - os.makedirs(directory, exist_ok=True) - tmp = os.path.join(directory, name + ".tmp") - with open(tmp, "w", encoding="utf-8") as fh: - json.dump(data, fh, indent=1) - os.replace(tmp, os.path.join(directory, name)) + ondisk.write_whole(os.path.join(directory, name), json.dumps(data, indent=1)) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 56b2ac7f..38d33eef 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -62,7 +62,6 @@ """ from __future__ import annotations -import hashlib import json import os import re @@ -70,6 +69,7 @@ import shutil from datetime import timezone +from nullius import ondisk from nullius.redact import redact from nullius.traces.trajectory import parse_ts @@ -273,14 +273,6 @@ def number(key): } -def _sha256(path: str) -> str: - digest = hashlib.sha256() - with open(path, "rb") as fh: - for chunk in iter(lambda: fh.read(1 << 16), b""): - digest.update(chunk) - return digest.hexdigest() - - # ── one document = one trial ──────────────────────────────────────────────── def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict: @@ -311,7 +303,7 @@ def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict: "agent_result": _usage(doc), "source_document": { "path": os.path.abspath(path), - "sha256": _sha256(path), + "sha256": ondisk.sha256_of(path), "schema_version": doc["schema_version"], "session_id": doc.get("session_id"), }, diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index b24b873d..068e208d 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -16,6 +16,8 @@ import re from typing import Optional +from nullius import ondisk + from . import client, questions as Q _SAFE = re.compile(r"[^A-Za-z0-9._@+-]") @@ -64,7 +66,6 @@ def save(ws_dir: str, job_id: str, trial_name: str, record: dict, lane: str = "s record's answers merge over the version's earlier answers, so judging one question later does not drop the others.""" path = _path(ws_dir, job_id, trial_name, lane) - os.makedirs(os.path.dirname(path), exist_ok=True) try: with open(path, encoding="utf-8") as fh: data = json.load(fh) or {} @@ -75,10 +76,7 @@ def save(ws_dir: str, job_id: str, trial_name: str, record: dict, lane: str = "s merged = dict(record) merged["answers"] = {**(earlier.get("answers") or {}), **(record.get("answers") or {})} data[version] = merged - tmp = path + ".tmp" - with open(tmp, "w", encoding="utf-8") as fh: - json.dump(data, fh, indent=1) - os.replace(tmp, path) + ondisk.write_whole(path, json.dumps(data, indent=1)) def for_job(ws_dir: str, job_id: str, version: Optional[str] = None, lane: str = "system-one") -> dict: diff --git a/app/nullius/migrate.py b/app/nullius/migrate.py index 7ccf3ded..cac83486 100644 --- a/app/nullius/migrate.py +++ b/app/nullius/migrate.py @@ -14,7 +14,7 @@ import stat import sys -from nullius import paths, settings +from nullius import ondisk, paths, settings SKIP = {".git", "__pycache__", ".pytest_cache", ".venv"} PATH_SETTINGS = {"RUNS_DIR", "WORKSPACES_DIR", "HARBOR_PINS", "STANDARD_DIR", "STANDARD_DATA_DIR", @@ -206,7 +206,6 @@ def add(dest, data, mode=0o600): def apply(pending): """Write the prepared copy using private files. Original data is untouched.""" - import tempfile for dest, inventory in pending.catalogue_entries.items(): if _inventory(dest) != inventory: raise ValueError(f"Destination changed since preview: {dest}") @@ -227,15 +226,7 @@ def mkdir(parent): mkdir(directory) for dest, data, mode, _ in pending.files: mkdir(dest.parent) - fd, temporary = tempfile.mkstemp(prefix=".migrate-", dir=dest.parent) - try: - os.fchmod(fd, mode) - with os.fdopen(fd, "wb") as stream: - stream.write(data) - os.replace(temporary, dest) - finally: - if os.path.exists(temporary): - os.unlink(temporary) + ondisk.write_whole(dest, data, mode=mode) def main(argv=None) -> int: diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py new file mode 100644 index 00000000..c87d38ca --- /dev/null +++ b/app/nullius/ondisk.py @@ -0,0 +1,63 @@ +"""A file written whole, a file held by one process at a time, a file's digest. + +Three things many modules need, each done here once. Standard library only. +""" +from __future__ import annotations + +import contextlib +import hashlib +import os +import uuid + + +def write_whole(path, data, mode=None) -> None: + """``data``, text or bytes, as the whole of ``path`` - or ``path`` left as it was. + + It is written under a name of its own beside ``path``, then renamed over it: + a reader never finds half a file. The name is this write's alone, because two + writers of one file at once are ordinary here (a job's page and its live poll + both re-parse a job whose files keep changing): with one shared temporary + name the first rename took the file away and the second raised + FileNotFoundError, a 500 on the page. Whichever rename lands last wins, and + both wrote a complete file. A write that fails leaves nothing behind. + + ``mode``: the file's permissions, from its first byte (0o600 for what only + its owner reads); this process's default when not given. The folder is made + when it is missing.""" + path = os.fspath(path) + folder = os.path.dirname(os.path.abspath(path)) + os.makedirs(folder, exist_ok=True) + part = os.path.join(folder, f".{os.path.basename(path)}.{uuid.uuid4().hex}.part") + fd = os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode) + try: + if mode is not None: + os.fchmod(fd, mode) # the mode asked for, whatever the umask + with (os.fdopen(fd, "w", encoding="utf-8") if isinstance(data, str) else os.fdopen(fd, "wb")) as f: + f.write(data) + os.replace(part, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(part) + raise + + +@contextlib.contextmanager +def locked(path): + """One holder of ``path`` at a time, across processes: taken on the way in, + given back on the way out. The file is the lock alone and holds nothing.""" + import fcntl # POSIX; the pages import this module and take no lock + with open(path, "a") as f: + fcntl.flock(f, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(f, fcntl.LOCK_UN) + + +def sha256_of(path) -> str: + """The sha256 of a file's bytes, read a piece at a time.""" + digest = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() diff --git a/app/nullius/prices.py b/app/nullius/prices.py index e5653a7e..cb72df74 100644 --- a/app/nullius/prices.py +++ b/app/nullius/prices.py @@ -29,12 +29,11 @@ import argparse import json -import os import time import urllib.request from typing import Callable, Dict, Iterable, Optional, Tuple -from nullius import paths +from nullius import ondisk, paths SOURCE = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json" RATES = ("input", "output", "cached", "cache_write", "cache_write_1h") # USD per million tokens @@ -77,13 +76,7 @@ def _number(v) -> bool: def save(doc: dict, env=None) -> None: """Written whole beside the file, then renamed: a reader never finds half a list.""" - out = path(env) - os.makedirs(os.path.dirname(out) or ".", exist_ok=True) - part = f"{out}.{os.getpid()}.part" - with open(part, "w", encoding="utf-8") as f: - json.dump(doc, f, indent=1, sort_keys=True) - f.write("\n") - os.replace(part, out) + ondisk.write_whole(path(env), json.dumps(doc, indent=1, sort_keys=True) + "\n") def table(env=None) -> Dict[str, dict]: diff --git a/app/nullius/providers.py b/app/nullius/providers.py index 3c431e98..3183758d 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -26,7 +26,7 @@ import urllib.request from typing import List -from nullius import paths, settings +from nullius import ondisk, paths, settings # The builder's steps (command-builder-core.js, STEP): an error names the step that edits it. STEP = {"benchmark": 0, "runner": 1, "dataset": 2, "setup": 3, "agent": 4, "model": 5, "limits": 6, "where": 7, "review": 8} @@ -305,12 +305,7 @@ def remember(results: dict, env=None) -> None: """Set (a result) or forget (None) the last test of each choice, the file written whole and renamed.""" with _TESTS_LOCK: kept = {k: v for k, v in {**tests(env), **results}.items() if v is not None} - out = _tests_file(env) - os.makedirs(os.path.dirname(out), exist_ok=True) - part = f"{out}.{os.getpid()}.part" - with open(part, "w", encoding="utf-8") as f: - json.dump(kept, f, indent=1, sort_keys=True) - os.replace(part, out) + ondisk.write_whole(_tests_file(env), json.dumps(kept, indent=1, sort_keys=True)) def mark(result: dict) -> str: diff --git a/app/nullius/secrets.py b/app/nullius/secrets.py index 1c6ecb3f..c6881f61 100644 --- a/app/nullius/secrets.py +++ b/app/nullius/secrets.py @@ -24,10 +24,9 @@ import json import os import re -import tempfile import time from typing import Dict, Optional, Tuple, Union -from nullius import paths +from nullius import ondisk, paths KINDS = ("value", "file", "server") INDEX = "index.json" @@ -69,18 +68,7 @@ def _name(name: str) -> str: def _write(path: str, data: bytes) -> None: """Written whole under a temporary name beside it, 0600 from its first byte, then renamed over the old one.""" - fd, tmp = tempfile.mkstemp(prefix=".tmp-", dir=os.path.dirname(path)) - try: - os.fchmod(fd, 0o600) - with os.fdopen(fd, "wb") as f: - f.write(data) - os.replace(tmp, path) - except BaseException: - try: - os.unlink(tmp) - except OSError: - pass - raise + ondisk.write_whole(path, data, mode=0o600) def _index(bench: str) -> Dict[str, dict]: diff --git a/app/nullius/settings.py b/app/nullius/settings.py index d351ad60..7dd44ed1 100644 --- a/app/nullius/settings.py +++ b/app/nullius/settings.py @@ -22,11 +22,12 @@ import os import json import re -import tempfile import urllib.parse from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Tuple +from nullius import ondisk + _PATH_OK = re.compile(r"^[^\x00-\x1f]{1,400}$") _URL_OK = re.compile(r"^https?://[^\s/?#]+(?:[/?#]\S*)?$") _REPO_OK = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") @@ -398,26 +399,14 @@ def agent_variable(name: str) -> Variable: def _write_lines(path: str, lines: List[str]) -> None: """Atomically replace one owner-only settings file; never print values.""" - directory = os.path.dirname(os.path.abspath(path)) - os.makedirs(directory, mode=0o700, exist_ok=True) - fd, tmp = tempfile.mkstemp(prefix=".settings-", dir=directory) - try: - os.fchmod(fd, 0o600) - with os.fdopen(fd, "w", encoding="utf-8") as fh: - if str(path).endswith(".json"): - values = {line.partition("=")[0]: line.partition("=")[2] - for line in lines if "=" in line and not line.lstrip().startswith("#")} - json.dump(values, fh, indent=2, ensure_ascii=False) - fh.write("\n") - else: - fh.write("\n".join(lines) + ("\n" if lines else "")) - os.replace(tmp, path) - except BaseException: - try: - os.unlink(tmp) - except OSError: - pass - raise + os.makedirs(os.path.dirname(os.path.abspath(path)), mode=0o700, exist_ok=True) + if str(path).endswith(".json"): + values = {line.partition("=")[0]: line.partition("=")[2] + for line in lines if "=" in line and not line.lstrip().startswith("#")} + text = json.dumps(values, indent=2, ensure_ascii=False) + "\n" + else: + text = "\n".join(lines) + ("\n" if lines else "") + ondisk.write_whole(path, text, mode=0o600) def take(path: str, name: str) -> Optional[str]: diff --git a/app/nullius/standard/calls/ledger.py b/app/nullius/standard/calls/ledger.py index d6134017..54b4813d 100644 --- a/app/nullius/standard/calls/ledger.py +++ b/app/nullius/standard/calls/ledger.py @@ -52,13 +52,14 @@ from __future__ import annotations import contextlib -import fcntl import json import math import os import uuid from typing import Optional, Tuple +from nullius import ondisk + OUTPUT = 4096 # output tokens booked for a call before the run has had a reply from its model ERROR = "SpendingCapError" # what a unit the cap ended carries: its own outcome outside the rate, never a miss (runs.classify) # what a unit that reached its own cap carries: it had its attempt and spent its allowance, as one that spends its @@ -137,12 +138,8 @@ def create(cls, path: str, max_usd: Optional[float] = None, unit_max_usd: Option @contextlib.contextmanager def _locked(self): try: - with open(self.path + ".lock", "a") as f: - fcntl.flock(f, fcntl.LOCK_EX) - try: - yield self._read() - finally: - fcntl.flock(f, fcntl.LOCK_UN) + with ondisk.locked(self.path + ".lock"): + yield self._read() except (OSError, ValueError, KeyError, TypeError) as e: raise Unavailable(f"the spending cap's ledger could not be used: {type(e).__name__}: {e}") @@ -155,10 +152,7 @@ def _read(self) -> dict: def _write(self, doc: dict) -> None: """Written whole beside the file, then renamed: a reader that takes no lock never finds half of it.""" - part = f"{self.path}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part" - with open(part, "w", encoding="utf-8") as f: - json.dump(doc, f) - os.replace(part, self.path) + ondisk.write_whole(self.path, json.dumps(doc)) def reserve(self, amount, unit: Optional[str] = None, model: Optional[str] = None, wait: bool = False, least: Optional[float] = None) -> Tuple[Optional[str], dict]: diff --git a/app/nullius/standard/containers/container.py b/app/nullius/standard/containers/container.py index 57a3e3ad..679e9647 100644 --- a/app/nullius/standard/containers/container.py +++ b/app/nullius/standard/containers/container.py @@ -126,7 +126,7 @@ from secrets import compare_digest, token_hex from typing import Dict, Iterable, List, Optional, Tuple -from nullius import constraints, paths +from nullius import constraints, ondisk, paths from nullius.standard.contract import definitions from nullius.standard.requirements import install @@ -1410,7 +1410,7 @@ def own_context(path: str) -> Dict[str, str]: dirs.sort() for f in sorted(files): p = os.path.join(d, f) - out[os.path.relpath(p, path)] = "link:" + os.readlink(p) if os.path.islink(p) else install.sha256_of(p) + out[os.path.relpath(p, path)] = "link:" + os.readlink(p) if os.path.islink(p) else ondisk.sha256_of(p) return out @@ -1508,7 +1508,7 @@ def node_runtime(machine: Optional[str] = None) -> str: with urllib.request.urlopen(f"https://nodejs.org/dist/v{NODE_VERSION}/{name}.tar.xz", timeout=60) as r, \ open(tarball, "wb") as f: shutil.copyfileobj(r, f) - if install.sha256_of(tarball) != NODE_SHA256[arch]: + if ondisk.sha256_of(tarball) != NODE_SHA256[arch]: raise Unavailable(f"{name}.tar.xz is not the one pinned (sha256)") with tarfile.open(tarball, "r:xz") as t: t.extractall(tmp, filter="data") diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 5152ec2b..21655fa9 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -82,7 +82,7 @@ from typing import Callable, Dict, List, Optional, Tuple from nullius.standard.contract import ports -from nullius import paths +from nullius import ondisk, paths from nullius.catalogue import storage from . import names @@ -1591,15 +1591,10 @@ def path_of(d: dict) -> str: def _locked(path: str): """One writer of a definition file at a time, across processes (two proofs, a conformance check and the user's own edit through the app).""" - import fcntl where = os.path.join(paths.cache_dir(), "locks") os.makedirs(where, exist_ok=True) - with open(os.path.join(where, hashlib.sha256(os.path.realpath(path).encode()).hexdigest()[:24]), "w") as f: - fcntl.flock(f, fcntl.LOCK_EX) - try: - yield - finally: - fcntl.flock(f, fcntl.LOCK_UN) + with ondisk.locked(os.path.join(where, hashlib.sha256(os.path.realpath(path).encode()).hexdigest()[:24])): + yield def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None: @@ -1645,7 +1640,4 @@ def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None: d[k] = clean[k] else: clean = {k: v for k, v in d.items() if not k.startswith("_")} - with open(path + ".part", "w") as f: - json.dump(clean, f, indent=2) - f.write("\n") - os.replace(path + ".part", path) + ondisk.write_whole(path, json.dumps(clean, indent=2) + "\n") diff --git a/app/nullius/standard/requirements/install.py b/app/nullius/standard/requirements/install.py index 06fd46a9..aa16215f 100644 --- a/app/nullius/standard/requirements/install.py +++ b/app/nullius/standard/requirements/install.py @@ -33,7 +33,6 @@ from __future__ import annotations import contextlib -import fcntl import hashlib import json import os @@ -44,7 +43,7 @@ from nullius.standard.contract import definitions -from nullius import paths +from nullius import ondisk, paths HOME = os.environ.get("STANDARD_DIR") or os.path.join(paths.data_dir(), "standard") MARK = ".installed" @@ -102,12 +101,8 @@ def _run(cmd: List[str], cwd: str, log: str, env: Optional[dict] = None, shown: @contextlib.contextmanager def _locked(where: str): os.makedirs(os.path.dirname(where), exist_ok=True) - with open(where + ".lock", "w") as f: - fcntl.flock(f, fcntl.LOCK_EX) - try: - yield - finally: - fcntl.flock(f, fcntl.LOCK_UN) + with ondisk.locked(where + ".lock"): + yield def _digest(obj) -> str: @@ -379,14 +374,6 @@ def _upstream(u: dict, where: str) -> str: return where -def sha256_of(path: str) -> str: - h = hashlib.sha256() - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(1 << 20), b""): - h.update(chunk) - return h.hexdigest() - - def dataset(bench: dict, ds: dict, up: Optional[str], progress: Optional[Callable] = None) -> Optional[str]: """The dataset's file, checked by its sha256: in the upstream when there is one, else beside the definition. None for a dataset with no file (its @@ -399,7 +386,7 @@ def dataset(bench: dict, ds: dict, up: Optional[str], progress: Optional[Callabl path = os.path.join(up or bench["_here"], ds["path"]) if not os.path.isfile(path): raise InstallFailed(f"dataset {ds['id']}: {ds['path']} is not in {'the upstream' if up else 'the definition folder'}") - got = sha256_of(path) + got = ondisk.sha256_of(path) if got != ds["sha256"]: raise InstallFailed(f"dataset {ds['id']}: sha256 {got[:12]}..., the definition says {ds['sha256'][:12]}...") return path @@ -451,7 +438,7 @@ def _fetch(url: str, sha256: str, where: str, what: str, progress: Optional[Call progress(done, total, final=True) except OSError as e: raise InstallFailed(f"{what} {url}: {e}") - got = sha256_of(part) + got = ondisk.sha256_of(part) if got != sha256: os.remove(part) raise InstallFailed(f"{what} {url}: sha256 {got[:12]}..., the definition says {sha256[:12]}...") diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index f28ea682..0d510aed 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -33,7 +33,7 @@ from datetime import datetime, timezone from nullius.runs import parse -from nullius import paths +from nullius import ondisk, paths ADJECTIVES = """brisk quiet tidy sturdy curious gentle nimble patient plucky sunny wry keen mellow bold calm clever crisp eager fuzzy glossy humble jolly lucky merry neat proud quirky @@ -105,30 +105,9 @@ def _path(home_dir: str, name: str) -> str: return os.path.join(home_dir, name, "workspace.json") -def _write_atomically(path: str, dump) -> None: - """Write *path* whole or not at all: *dump* fills a temp file beside it, - which is then renamed over the target. - - The temp name is this writer's own - process and thread - because two - requests writing the same file at once are ordinary here: the job page and - its /live poll both re-parse a job whose files keep changing. With one - shared `.tmp`, the first rename took the file away and the second - raised FileNotFoundError, a 500 on the page. Whichever rename lands - last wins, and both wrote a complete file.""" - tmp = f"{path}.{os.getpid()}.{threading.get_ident()}.tmp" - try: - with open(tmp, "w", encoding="utf-8") as fh: - dump(fh) - os.replace(tmp, path) - finally: - if os.path.exists(tmp): - os.unlink(tmp) - - def save(ws: Workspace) -> None: - os.makedirs(ws.dir, exist_ok=True) data = {k: v for k, v in asdict(ws).items() if k != "dir"} - _write_atomically(os.path.join(ws.dir, "workspace.json"), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1)) + ondisk.write_whole(os.path.join(ws.dir, "workspace.json"), json.dumps(data, ensure_ascii=False, indent=1)) def load(home_dir: str, name: str) -> Workspace | None: @@ -334,8 +313,7 @@ def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | No def _write_index(ws: Workspace, index: dict) -> None: - os.makedirs(ws.jobs_dir, exist_ok=True) - _write_atomically(_index_path(ws), lambda fh: json.dump(index, fh, ensure_ascii=False, indent=1)) + ondisk.write_whole(_index_path(ws), json.dumps(index, ensure_ascii=False, indent=1)) # Jobs already decoded in this process, by cache file: (signature, Job). A page @@ -377,9 +355,8 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None) -> tuple: reuse = lambda sub: before.get(sub) if old_sigs.get(sub) and old_sigs.get(sub) == trial_sigs.get(sub) else None job = parse.parse_job(job_dir, reuse=reuse) if sig: - os.makedirs(ws.jobs_dir, exist_ok=True) - _write_atomically(path, lambda fh: json.dump({"signature": sig, "dir": job_dir, "cached": _now(), - "job": job_to_dict(job)}, fh, default=_encode, ensure_ascii=False)) + ondisk.write_whole(path, json.dumps({"signature": sig, "dir": job_dir, "cached": _now(), "job": job_to_dict(job)}, + default=_encode, ensure_ascii=False)) with _DECODED_LOCK: _DECODED[path] = (sig, job, trial_sigs) _note_in_index(ws, job_dir, job, index) diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py new file mode 100644 index 00000000..26d8b283 --- /dev/null +++ b/app/tests/test_ondisk.py @@ -0,0 +1,109 @@ +"""A file written whole, a lock, a digest (``nullius.ondisk``): what every +module that keeps a file relies on.""" +import hashlib +import os +import shutil +import stat +import tempfile +import threading +import unittest +from unittest import mock + +from nullius import ondisk + + +class Whole(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.path = os.path.join(self.tmp, "deep", "file.json") + + def mode(self, path=None): + return stat.S_IMODE(os.stat(path or self.path).st_mode) + + def left(self): + return sorted(os.listdir(os.path.dirname(self.path))) + + def test_text_and_bytes_land_whole_in_a_folder_made_for_them(self): + ondisk.write_whole(self.path, "é\nsecond line\n") + with open(self.path, "rb") as f: + self.assertEqual(f.read(), "é\nsecond line\n".encode()) + ondisk.write_whole(self.path, b"\x00\xff") + with open(self.path, "rb") as f: + self.assertEqual(f.read(), b"\x00\xff") + self.assertEqual(self.left(), ["file.json"]) + + def test_the_mode_is_the_process_default_unless_one_is_asked(self): + old = os.umask(0o027) + self.addCleanup(os.umask, old) + ondisk.write_whole(self.path, "x") + self.assertEqual(self.mode(), 0o640) # 0666 less the umask, as open() gives + ondisk.write_whole(self.path, "x", mode=0o600) + self.assertEqual(self.mode(), 0o600) + ondisk.write_whole(self.path, "x", mode=0o644) + self.assertEqual(self.mode(), 0o644) # the mode asked for, whatever the umask + + def test_a_write_that_fails_leaves_the_file_as_it_was_and_nothing_beside_it(self): + ondisk.write_whole(self.path, "kept") + with mock.patch.object(os, "replace", side_effect=OSError("no rename")): + with self.assertRaises(OSError): + ondisk.write_whole(self.path, "lost") + with self.assertRaises(TypeError): + ondisk.write_whole(self.path, 42) # neither text nor bytes + with open(self.path) as f: + self.assertEqual(f.read(), "kept") + self.assertEqual(self.left(), ["file.json"]) + + def test_writers_of_one_file_at_once_each_finish_and_one_of_them_wins(self): + texts = [str(i) * 4096 for i in range(16)] + failed = [] + def write(text): + try: + ondisk.write_whole(self.path, text) + except Exception as e: # noqa: BLE001 - the failure under test + failed.append(e) + threads = [threading.Thread(target=write, args=(t,)) for t in texts] + for t in threads: t.start() + for t in threads: t.join(10) + self.assertEqual(failed, []) + with open(self.path) as f: + self.assertIn(f.read(), texts) + self.assertEqual(self.left(), ["file.json"]) + + +class Lock(unittest.TestCase): + def test_one_holder_at_a_time(self): + tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, tmp, True) + path = os.path.join(tmp, "thing.lock") + inside, order = threading.Event(), [] + def second(): + inside.wait(5) + with ondisk.locked(path): + order.append("second") + t = threading.Thread(target=second) + t.start() + with ondisk.locked(path): + inside.set() + t.join(0.3) # it waits while the lock is held + self.assertTrue(t.is_alive()) + order.append("first") + t.join(5) + self.assertEqual(order, ["first", "second"]) + with self.assertRaises(ValueError): # given back when the holder fails too + with ondisk.locked(path): + raise ValueError("inside") + with ondisk.locked(path): + pass + + +class Digest(unittest.TestCase): + def test_it_is_the_sha256_of_the_bytes(self): + with tempfile.NamedTemporaryFile(delete=False) as f: + f.write(b"a" * (3 << 20) + b"tail") + self.addCleanup(os.unlink, f.name) + self.assertEqual(ondisk.sha256_of(f.name), hashlib.sha256(b"a" * (3 << 20) + b"tail").hexdigest()) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_secrets.py b/app/tests/test_secrets.py index 68a7abcf..42ae29e1 100644 --- a/app/tests/test_secrets.py +++ b/app/tests/test_secrets.py @@ -120,7 +120,7 @@ def test_replaced_whole_and_removed(self): self.assertTrue(secrets.delete("b", "A")) self.assertFalse(secrets.delete("b", "A")) self.assertEqual(secrets.status("b"), {}) - self.assertEqual([n for n in os.listdir(os.path.join(self.tmp, "secrets", "b")) if n.startswith(".tmp")], []) + self.assertEqual([n for n in os.listdir(os.path.join(self.tmp, "secrets", "b")) if n.endswith(".part")], []) def test_unpack_decodes_a_host_payload_and_preserves_binary_bytes(self): payload = {"A": base64.b64encode(KEY.encode()).decode(), "F": base64.b64encode(FILE).decode()} diff --git a/app/tests/test_standard_install.py b/app/tests/test_standard_install.py index a770a124..417c7459 100644 --- a/app/tests/test_standard_install.py +++ b/app/tests/test_standard_install.py @@ -10,6 +10,7 @@ import unittest from unittest import mock +from nullius import ondisk from nullius.standard.requirements import install @@ -49,7 +50,7 @@ def go(): def test_a_dataset_is_checked_by_its_digest(self): up = install.upstream(self.bench, os.path.join(self.tmp, "home")) - right = install.sha256_of(os.path.join(up, "data", "items.json")) + right = ondisk.sha256_of(os.path.join(up, "data", "items.json")) self.assertTrue(install.dataset(self.bench, {"id": "d", "path": "data/items.json", "sha256": right}, up)) with self.assertRaisesRegex(install.InstallFailed, "sha256"): install.dataset(self.bench, {"id": "d", "path": "data/items.json", "sha256": "0" * 64}, up) diff --git a/app/tests/test_standard_setups.py b/app/tests/test_standard_setups.py index 6bb88deb..7eb13827 100644 --- a/app/tests/test_standard_setups.py +++ b/app/tests/test_standard_setups.py @@ -13,6 +13,7 @@ from unittest.mock import patch from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from nullius import ondisk from nullius.standard.contract import definitions, match from nullius.standard.pages import recipe from nullius.standard.requirements import hostreq, install @@ -253,7 +254,7 @@ def test_docker_setup_runs_driver_and_linux_dependencies_with_scoped_credentials data = os.path.join(here, "data.txt") with open(data, "w") as f: f.write("fixture data") - self.b["datasets"][0].update(path="data.txt", sha256=install.sha256_of(data), environment="data") + self.b["datasets"][0].update(path="data.txt", sha256=ondisk.sha256_of(data), environment="data") credential = os.path.join(self.tmp, "tool.lic") with open(credential, "w") as f: f.write("fixture licence") diff --git a/app/tests/test_standard_versions.py b/app/tests/test_standard_versions.py index 7497a366..8a057a95 100644 --- a/app/tests/test_standard_versions.py +++ b/app/tests/test_standard_versions.py @@ -13,6 +13,7 @@ import unittest from unittest.mock import patch +from nullius import ondisk from nullius.standard import cli from nullius.standard.contract import definitions, match from nullius.standard.proofs import conform @@ -372,10 +373,10 @@ def test_each_version_is_cloned_at_its_own_commit_and_its_data_checked_by_its_ow self.assertNotEqual(a, b) with open(os.path.join(a, "data", "tasks.json")) as f1, open(os.path.join(b, "data", "tasks.json")) as f2: self.assertEqual((f1.read(), f2.read()), ("[1, 2]\n", "[1, 2, 3]\n")) - right = install.sha256_of(os.path.join(b, "data", "tasks.json")) + right = ondisk.sha256_of(os.path.join(b, "data", "tasks.json")) self.assertTrue(install.dataset(fork, dict(fork["datasets"][0], sha256=right), b)) with self.assertRaises(install.InstallFailed): # the published digest does not hold for the fork - install.dataset(fork, dict(fork["datasets"][0], sha256=install.sha256_of(os.path.join(a, "data", "tasks.json"))), b) + install.dataset(fork, dict(fork["datasets"][0], sha256=ondisk.sha256_of(os.path.join(a, "data", "tasks.json"))), b) drv = {"command": ["{install}/.venv/bin/python", "{here}/driver.py"], "install": {"python": "3.12", "project": "."}} self.assertNotEqual(install.driver_dir(dict(one, driver=drv), self.home), install.driver_dir(dict(fork, driver=drv), self.home)) diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index eedbb3f3..913452c4 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -221,7 +221,7 @@ def test_two_requests_writing_the_same_cache_at_once_both_return(self): gate = threading.Barrier(2, timeout=5) stamp = workspace._now def held_now(): - gate.wait() # both are inside the write, temp file open, nothing renamed yet + gate.wait() # both are about to write: neither has renamed yet return stamp() results, errors = [], [] def load(): @@ -237,7 +237,7 @@ def load(): self.assertEqual([from_cache for _, from_cache in results], [False, False]) job, from_cache = workspace.load_job(self.ws, self.job_dir) self.assertTrue(from_cache); self.assertEqual(job, results[0][0]) - self.assertEqual([n for n in os.listdir(self.ws.jobs_dir) if n.endswith(".tmp")], []) + self.assertEqual([n for n in os.listdir(self.ws.jobs_dir) if n.endswith(".part")], []) def test_load_jobs_matches_load_all(self): _job_dir(self.root, "job-b", n=1) From 177b0692fa53f6df286e2f84fc8bc96b802199bb Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 16 Nov 2026 17:18:11 +0100 Subject: [PATCH 03/14] refactor(traces): split the trace reader into five modules traces/trace.py was 1,477 lines doing five jobs. The code is moved whole, statement by statement with the comments above it, and not edited: spans.py the span model, the two walks, labels, namespace groups fold.py LLM request spans folded under the call they belong to breakdown.py time accounting: Totals, Breakdown, partition, breakdown waterfall.py the axis, the rows, the ticks trace.py Trace, Filter, parse, load, the saved view spans.py imports none of the others, the next three import only it, and trace.py imports all four. Callers take a name from the module that defines it: the two trace producers (standard/runner/job.py, traces/otel.py) now import the accounting alone instead of the whole reader. The field contract pins a class under the module that defines it, so Span, Totals, Breakdown, Extent, Row and Tick move to three new keys. Every pinned field is the same as before. Parsing the two fixture traces whole and filtered, their charts and their saved views gives the same output as the previous reader, byte for byte. --- .claude/rules/traces.md | 5 +- AGENTS.md | 3 +- app/nullius/importers/otel.py | 4 +- app/nullius/standard/runner/job.py | 5 +- app/nullius/traces/breakdown.py | 293 ++++++++ app/nullius/traces/charts.py | 10 +- app/nullius/traces/fold.py | 214 ++++++ app/nullius/traces/otel.py | 13 +- app/nullius/traces/spans.py | 418 +++++++++++ app/nullius/traces/trace.py | 1051 +--------------------------- app/nullius/traces/waterfall.py | 167 +++++ app/static/style.css | 2 +- app/tests/field_contract.json | 116 +-- app/tests/field_contract.py | 3 +- app/tests/test_charts.py | 7 +- app/tests/test_conversation.py | 6 +- app/tests/test_otel.py | 7 +- app/tests/test_standard_trace.py | 3 +- app/tests/test_trace.py | 28 +- app/tests/test_trace_filter.py | 27 +- app/tests/test_trace_fold.py | 30 +- app/ui_tests/test_every_route.py | 3 +- 22 files changed, 1256 insertions(+), 1159 deletions(-) create mode 100644 app/nullius/traces/breakdown.py create mode 100644 app/nullius/traces/fold.py create mode 100644 app/nullius/traces/spans.py create mode 100644 app/nullius/traces/waterfall.py diff --git a/.claude/rules/traces.md b/.claude/rules/traces.md index e7d1316e..c3a185f4 100644 --- a/.claude/rules/traces.md +++ b/.claude/rules/traces.md @@ -1,7 +1,8 @@ ## Traces, as this application renders them -The reader itself — folding, grouping, normalisation — is -`app/nullius/traces/trace.py`. What +The reader itself is `app/nullius/traces/trace.py`, with the span tree and its +grouping in `spans.py`, the folding in `fold.py`, the time accounting in +`breakdown.py` and the waterfall's layout in `waterfall.py`. What this rule keeps is what the **pages** do with it, and these are the parts a plausible change breaks silently. diff --git a/AGENTS.md b/AGENTS.md index 4624e742..c8fd7245 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,7 +47,8 @@ and its resources. The source layout stays under `app/`. - `app/nullius/` — its backend, one package per purpose: `runs/` (reading one Harbor job tree: `parse`, `classify`, `live`, `artifacts`, `feasibility`, `launches`, `verifier` - a verifier's report read by its - benchmark's report block - and the `cli`), `traces/` (`trace`, `trajectory`, + benchmark's report block - and the `cli`), `traces/` (`trace`, the reader, with its span tree `spans`, + its `fold`, its time accounting `breakdown` and its layout `waterfall`; `trajectory`, `conversation`, `charts`, `behavior`, `otel`), `compare/` (`comparison` and its `cli`), `catalogue/` (`catalog`, which loads one folder per benchmark under `catalogue/benchmarks/`, named by its key: its `benchmark.json` with its diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index a7cdd02e..7dbd589d 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -56,7 +56,7 @@ from nullius.redact import redact from nullius.traces import otel as reader -from nullius.traces import trace +from nullius.traces.spans import raw_spans_of NAME = "otel" LABEL = "OpenTelemetry" @@ -148,7 +148,7 @@ def _dump(path: str, data) -> None: def _window(document: dict) -> tuple: """(start_ns, end_ns) over every span, end None when no span ended.""" starts, ends = [], [] - for raw in trace.raw_spans_of(document.get("spans") or []): + for raw in raw_spans_of(document.get("spans") or []): starts.append(raw["start_ns"]) if raw.get("end_ns") is not None: ends.append(raw["end_ns"]) diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index 60784df7..a0257e97 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -30,7 +30,8 @@ from typing import Dict, List, Optional from nullius.standard.calls import ledger -from nullius.traces import otel, trace +from nullius.traces import otel +from nullius.traces.breakdown import breakdown def iso(t: Optional[float]) -> Optional[str]: @@ -341,7 +342,7 @@ def trace_from_run(trajectory: dict, calls: List[dict], other: dict, produce: tu "session_id": trajectory.get("session_id") or "", "agent": trajectory.get("agent") or {}, "clock": {"source": "this machine's clock, as the relay and the ACP client saw each call", "note": "wall_ns is the agent's window; a tool call's time is what the agent reported"}, - "spans": [session], "totals": trace.breakdown([session], finish - begin).as_totals()} + "spans": [session], "totals": breakdown([session], finish - begin).as_totals()} def _jsonl(path: str) -> List[dict]: diff --git a/app/nullius/traces/breakdown.py b/app/nullius/traces/breakdown.py new file mode 100644 index 00000000..e5cae447 --- /dev/null +++ b/app/nullius/traces/breakdown.py @@ -0,0 +1,293 @@ +"""Where a trace's time went: the producer's totals, and the same accounting done here. + +``Totals`` is run-level time exactly as the producer reported it: displayed +verbatim, never recomputed from the tree. ``breakdown`` is the one arithmetic of +our own, every instant charged to exactly one category (``partition``). A view +that leaves spans out needs it, because hiding a span has to move its time +somewhere and the producer cannot be asked again; so do the producers that write +a trace's totals in the first place. ``Breakdown`` is its result, labelled as +derived wherever it is shown, and it never overwrites what the file said. +""" + +from __future__ import annotations + +import bisect +from dataclasses import dataclass, field + +from .spans import _int_or_none, merge_intervals, NS_PER_MS, raw_spans_of + +# A residual under this reads as float noise from the producer's own arithmetic, +# not as real unattributed time. Rendering it produces a zero-width segment with +# a legend entry saying "0ms". +UNACCOUNTED_EPSILON_NS = NS_PER_MS + +# Breakdown segments, in a fixed left-to-right order. The order carries no +# meaning — these are categories, not a timeline — but a stable one keeps the +# strip from reshuffling between trials. +_SEGMENTS = ( + ("llm", "LLM", "llm_ns"), + ("tool", "Tool", "tool_ns"), + ("reasoning", "Reasoning", "reasoning_ns"), + ("idle", "Idle", "idle_ns"), +) + +# The residual is a segment like any other once it reaches a strip, and both +# `segments_of` and `Breakdown.compared_to` need to name and order it. +_UNACCOUNTED = ("unaccounted", "Unaccounted") +_SEGMENT_LABELS = {key: label for key, label, _ in _SEGMENTS} | {_UNACCOUNTED[0]: _UNACCOUNTED[1]} +_SEGMENT_ORDER = [key for key, _, _ in _SEGMENTS] + [_UNACCOUNTED[0]] + +# What a span's own time counts toward when a breakdown has to be recomputed for +# a filtered view. The structural kinds are absent on purpose: `session`, +# `subagent` and `group` bracket their children, so charging them would claim the +# children's work as their own, and `output` is text produced inside a call that +# is already counted as `llm`. +_KIND_CATEGORY = {"llm_request": "llm", "reasoning": "reasoning", "tool": "tool"} + +# Priority for `partition`. A tool that only waits for a human beats real work, +# and both beat the LLM call they happened inside of. +_PRIORITY = ("idle", "tool", "reasoning", "llm") + +# A tool whose whole job is to wait for the human. Harbor opens a span with this +# name; another producer may set an attribute instead. Either way the time +# is not the agent working, so it lands in `idle` rather than `tool`. +_BLOCKED_NAME = "claude_code.tool.blocked_on_user" +_BLOCKED_ATTR = "blocked_on_user" + + +def segments_of(source) -> list: + """[{key, label, ns, pct}] for a stacked strip, zero-length categories dropped. + + Shared by :class:`Totals` and :class:`Breakdown` so the reported strip and a + recomputed one are laid out and labelled identically — the only difference + between them should be the numbers, never the presentation. + + Percentages are of the wall clock, so categories that do not close read as + short of 100% instead of being silently rescaled to fill it; ``unaccounted`` + is what closes them. With no wall clock to divide by they fall back to the + segments' own sum, which is the only honest denominator left. + """ + out = [ + {"key": key, "label": label, "ns": int(getattr(source, attr))} + for key, label, attr in _SEGMENTS + if getattr(source, attr) + ] + if source.unaccounted_ns: + out.append({"key": _UNACCOUNTED[0], "label": _UNACCOUNTED[1], "ns": source.unaccounted_ns}) + denominator = source.wall_ns or sum(seg["ns"] for seg in out) + for seg in out: + seg["pct"] = seg["ns"] / denominator * 100 if denominator else 0.0 + return out + + +@dataclass +class Totals: + """Run-level time, exactly as the producer reported it. + + **Never recomputed from the tree.** Summing nested spans double-counts + their shared time. The producer already resolved that (it skips tools nested + inside tools, and subtracts tool time nested inside LLM spans). The only + arithmetic this class does is the residual, which is a display concern. + """ + + wall_ns: int | None = None + llm_ns: int | None = None + tool_ns: int | None = None + reasoning_ns: int | None = None + idle_ns: int | None = None + span_count: int | None = None + measured_span_count: int | None = None + + @property + def unaccounted_ns(self) -> int: + """Wall clock the categories don't account for. + + The categories are not expected to close: the session span brackets more + than its instrumented children, so a stacked bar that just leaves a gap + reads as a rendering bug. Name the gap instead. Clamped at both ends — + under an epsilon it is noise, and a negative would corrupt the geometry + silently (the same reasoning as `Trial.dur_other`). + """ + if not self.wall_ns: + return 0 + rest = sum(v or 0 for v in (self.llm_ns, self.tool_ns, self.reasoning_ns, self.idle_ns)) + residual = self.wall_ns - rest + return int(residual) if residual >= UNACCOUNTED_EPSILON_NS else 0 + + @property + def segments(self) -> list: + """[{key, label, ns, pct}] for the breakdown strip.""" + return segments_of(self) + + +@dataclass +class Breakdown: + """Category time recomputed from a set of spans — for a filtered view only. + + The producer's ``totals`` stays authoritative and is never replaced by this + (see :class:`Totals`). It exists because hiding spans has to take their time + out of the picture, and the producer cannot be asked a second time. + + It is deliberately *not* the same arithmetic, and it does not reproduce the + same numbers. Harbor's ``llm_ns`` is the plain sum of its LLM spans, while + this partitions the timeline so an instant covered by both a tool call and + the LLM call that asked for it is charged once, to the tool. The two are + shown as separate strips because they measure different things. + + ``wall_ns`` is carried over from the source unchanged: hiding a span does not + make the run shorter, it makes more of the run unattributed. That is what + ``unaccounted_ns`` then absorbs, and it is the honest place for it to land. + """ + + wall_ns: int = 0 + llm_ns: int = 0 + tool_ns: int = 0 + reasoning_ns: int = 0 + idle_ns: int = 0 + span_count: int = 0 + measured_span_count: int = 0 + tokens: dict = field(default_factory=dict) + + @property + def attributed_ns(self) -> int: + """Wall clock the categories account for. Disjoint, so a plain sum.""" + return self.llm_ns + self.tool_ns + self.reasoning_ns + self.idle_ns + + @property + def unaccounted_ns(self) -> int: + residual = (self.wall_ns or 0) - self.attributed_ns + return int(residual) if residual >= UNACCOUNTED_EPSILON_NS else 0 + + @property + def segments(self) -> list: + return segments_of(self) + + def compared_to(self, other: "Breakdown") -> list: + """`segments`, each carrying `delta_ns` against *other*. + + The comparison a filtered view actually needs. Both sides come from this + same partition, so every delta is the filter's doing and nothing else — + whereas the difference against the producer's reported strip mixes the + filter up with two different ways of accounting for the same run, and on + a log-derived trace those disagree by minutes, not milliseconds. + + A category the filter emptied keeps its entry at 0ns: dropping it would + hide the largest thing the filter did. + """ + was = {seg["key"]: seg["ns"] for seg in other.segments} + out = self.segments + here = {seg["key"] for seg in out} + out.extend( + {"key": key, "label": _SEGMENT_LABELS[key], "ns": 0, "pct": 0.0} + for key in was + if key not in here + ) + out.sort(key=lambda seg: _SEGMENT_ORDER.index(seg["key"])) + for seg in out: + seg["delta_ns"] = seg["ns"] - was.get(seg["key"], 0) + return out + + def as_totals(self) -> dict: + """The ``totals`` block to write into a saved filtered trace.""" + return { + "wall_ns": self.wall_ns, + "llm_ns": self.llm_ns, + "tool_ns": self.tool_ns, + "reasoning_ns": self.reasoning_ns, + "idle_ns": self.idle_ns, + "span_count": self.span_count, + "measured_span_count": self.measured_span_count, + "tokens": dict(self.tokens), + } + + +def category_of(raw: dict) -> str | None: + """Which breakdown category a span's own time belongs to, or None. + + None means the span contributes no time of its own — see `_KIND_CATEGORY`. + """ + kind = str(raw.get("kind") or "") + if kind == "tool" and ( + str(raw.get("name") or "") == _BLOCKED_NAME + or (raw.get("attributes") or {}).get(_BLOCKED_ATTR) + ): + return "idle" + return _KIND_CATEGORY.get(kind) + + +def partition(by_category: dict, priority: tuple = _PRIORITY) -> dict: + """Split the timeline so every instant is charged to exactly one category. + + Summing durations exceeds the wall clock as soon as spans nest or overlap, + and both happen here: a tool call sits inside the LLM call that asked for it, + and background subagents run alongside the main thread. Each elementary + segment goes to the highest-priority category covering it, which keeps the + categories disjoint by construction and the stacked strip honest. + """ + merged = {cat: merge_intervals(by_category.get(cat) or []) for cat in priority} + starts = {cat: [start for start, _ in ivs] for cat, ivs in merged.items()} + edges = sorted({point for ivs in merged.values() for iv in ivs for point in iv}) + totals = {cat: 0 for cat in priority} + + def covers(cat: str, low: int) -> bool: + ivs = merged[cat] + i = bisect.bisect_right(starts[cat], low) - 1 + return i >= 0 and ivs[i][1] > low + + for low, high in zip(edges, edges[1:]): + for cat in priority: + if covers(cat, low): + totals[cat] += high - low + break + return totals + + +def breakdown(spans: list, wall_ns: int = 0) -> Breakdown: + """Recompute category time, span counts and tokens over *spans*. + + See :class:`Breakdown` for why this is not the producer's arithmetic and must + not be presented as it. Spans with no usable end contribute no time — an + unknown clock is not a zero one — but they are still counted and their tokens + still add up. + """ + by_category: dict = {} + tokens: dict = {} + count = 0 + measured = 0 + for raw in raw_spans_of(spans): + count += 1 + if str(raw.get("timing_quality") or "") == "measured": + measured += 1 + for key, value in (raw.get("tokens") or {}).items(): + if _int_or_none(value) is not None: + tokens[key] = tokens.get(key, 0) + value + category = category_of(raw) + start = _int_or_none(raw.get("start_ns")) + end = _int_or_none(raw.get("end_ns")) + if category and start is not None and end is not None and end > start: + by_category.setdefault(category, []).append((start, end)) + split = partition(by_category) + return Breakdown( + wall_ns=int(wall_ns or 0), + llm_ns=split.get("llm", 0), + tool_ns=split.get("tool", 0), + reasoning_ns=split.get("reasoning", 0), + idle_ns=split.get("idle", 0), + span_count=count, + measured_span_count=measured, + tokens=tokens, + ) + + +def _totals(raw: dict) -> Totals: + if not raw: + return Totals() + return Totals( + wall_ns=_int_or_none(raw.get("wall_ns")), + llm_ns=_int_or_none(raw.get("llm_ns")), + tool_ns=_int_or_none(raw.get("tool_ns")), + reasoning_ns=_int_or_none(raw.get("reasoning_ns")), + idle_ns=_int_or_none(raw.get("idle_ns")), + span_count=_int_or_none(raw.get("span_count")), + measured_span_count=_int_or_none(raw.get("measured_span_count")), + ) diff --git a/app/nullius/traces/charts.py b/app/nullius/traces/charts.py index 1a3dd976..e1d87db8 100644 --- a/app/nullius/traces/charts.py +++ b/app/nullius/traces/charts.py @@ -11,7 +11,7 @@ and background subagents run alongside the main thread — so adding durations up overshoots the run, sometimes by a lot. That is exactly why the strips next to these charts never sum spans: ``Totals`` is the producer's, displayed verbatim, -and ``Breakdown`` *partitions* the timeline instead (see :func:`trace.partition`). +and ``Breakdown`` *partitions* the timeline instead (see :func:`breakdown.partition`). So the weighted axis here is a share of *summed span time*, never a share of the run, :class:`Charts` carries no ``wall_ns``, and no percentage is ever taken against one. A chart that looked like the breakdown strip and disagreed with it @@ -38,7 +38,7 @@ every headline. Geometry is computed here, in SVG user units against :data:`BOX`, for the same -reason :func:`trace.place` computes the waterfall's: the arithmetic runs on +reason :func:`waterfall.place` computes the waterfall's: the arithmetic runs on nanosecond magnitudes that overflow a JS double, and staying in Python int/float keeps it exact. Values that need formatting leave as integer nanoseconds and get ``|nsdur`` in the template — this module emits numbers, not presentation. The @@ -78,7 +78,7 @@ from nullius.traces.trace import clean as _clean from nullius.traces.trace import toggled as _toggled -from nullius.traces.trace import KIND_ORDER, all_spans, is_instant +from nullius.traces.spans import KIND_ORDER, all_spans, is_instant # The SVG coordinate system every chart is drawn in. One viewBox for all four so # they line up visually across the grid, with room on the left for value labels @@ -418,7 +418,7 @@ def log_edges(lo_ns: int, hi_ns: int, target: int = _TARGET_BINS) -> tuple: every sample rather than clipping the extremes. Never degenerate. A trace whose spans all took the same time still gets a - decade of width — the same stance :func:`trace.extent_of` takes when every + decade of width — the same stance :func:`waterfall.extent_of` takes when every span is an instant, and for the same reason: a zero-width range makes every position NaN. """ @@ -811,7 +811,7 @@ def charts_of(samples: tuple, total: int, excluded: int, """The same four charts over an already-extracted population. Split out from :func:`charts_for` so that several traces could be pooled - without merging their span *trees*. :func:`trace.all_spans` deduplicates by + without merging their span *trees*. :func:`spans.all_spans` deduplicates by span id to guard against a parent cycle — right within one document, and quietly wrong across several, where two traces reusing an id would lose the duplicates without saying so. Extract each trace's samples on its own, then diff --git a/app/nullius/traces/fold.py b/app/nullius/traces/fold.py new file mode 100644 index 00000000..558717db --- /dev/null +++ b/app/nullius/traces/fold.py @@ -0,0 +1,214 @@ +"""A measured LLM call given the log spans for the reply it produced. + +The producer writes one call twice when it has no request id to join on: once as +the exporter measured it, once from the agent's own log. ``fold_llm_requests`` +moves the log's request spans under the call they belong to. It moves rows and no +numbers. + +It runs before namespace grouping (``spans.mark_groups``), and the order is +load-bearing: ``trace`` says why. +""" + +from __future__ import annotations + +from .spans import _BLOCK_KINDS, _int_or_none, _LOG_LLM_NAME, MAX_DEPTH, _MERGED_FROM, _OTEL_LLM_NAME + +def _window(raw: dict) -> tuple: + """(start, end) in ns, an unknown end read as the start — same as `_span`.""" + start = _int_or_none(raw.get("start_ns")) or 0 + end = _int_or_none(raw.get("end_ns")) + return start, start if end is None else end + + +def _tokens_key(raw: dict) -> tuple: + """A call's usage, as something comparable. Empty when none was reported.""" + return tuple( + sorted( + (str(k), v) + for k, v in (raw.get("tokens") or {}).items() + if _int_or_none(v) is not None + ) + ) + + +def _request_groups(wrappers: list) -> list: + """Log request spans grouped by the reply they came from. + + One API call arrives as several records — a thinking block, each tool_use, + the final text — and the producer opens a span per record. They carry one + `message.id` between them, which is exactly the grouping wanted; a producer + that omits it leaves every record its own group, which folds them one by one + and is no worse than not folding at all. + """ + groups: dict = {} + order: list = [] + for raw in wrappers: + key = (raw.get("attributes") or {}).get("message.id") + key = str(key) if key else "ungrouped:" + str(raw.get("span_id") or id(raw)) + if key not in groups: + groups[key] = [] + order.append(key) + groups[key].append(raw) + return [groups[key] for key in order] + + +def _match_requests(containers: list, groups: list) -> dict: + """container span_id → the log request spans belonging to it. + + Harbor joins these on the request id the exporter reported. This runs where + the provider returned none, so the join is on what is left: identical usage, + and overlapping windows. Usage is a hard constraint when both sides report + it and the overlap only ranks the candidates, which is what keeps two calls + that happen to overlap from swapping their blocks. + + A wrong match moves a row under the wrong call; it cannot change a number, + because folding re-parents spans and never touches a clock. + """ + taken: set = set() + out: dict = {} + for container in sorted(containers, key=lambda raw: _window(raw)[0]): + c_start, c_end = _window(container) + c_tokens = _tokens_key(container) + best = None + for index, group in enumerate(groups): + if index in taken: + continue + g_start = min(_window(raw)[0] for raw in group) + g_end = max(_window(raw)[1] for raw in group) + if g_start >= c_end or c_start >= g_end: + continue + g_tokens = next((t for t in map(_tokens_key, group) if t), ()) + if c_tokens and g_tokens and c_tokens != g_tokens: + continue + distance = abs(g_start - c_start) + if best is None or distance < best[0]: + best = (distance, index, group) + if best is not None: + taken.add(best[1]) + out[str(container.get("span_id") or "")] = best[2] + return out + + +def _collect_requests( + spans: list, parent: str, containers: list, wrappers: list, depth: int = 0 +) -> None: + """The calls to fold into, and the log request spans still to fold. + + A request already sitting under a call has been folded — by this function on + an earlier read, or by Harbor itself — and must not be folded again: a saved + view can be filtered again, which re-reads a document this has already seen, + and a second pass would rewrite the provenance of the first. + """ + for raw in spans: + if not isinstance(raw, dict): + continue + name = str(raw.get("name") or "") + if name == _OTEL_LLM_NAME: + containers.append(raw) + elif ( + name == _LOG_LLM_NAME + and str(raw.get("source") or "") == "log" + and parent != _OTEL_LLM_NAME + ): + wrappers.append(raw) + if depth < MAX_DEPTH: + _collect_requests(raw.get("children") or [], name, containers, wrappers, depth + 1) + + +def _folded_child(raw: dict, parent: dict) -> dict: + """One log request span, rewritten to sit under the call it belongs to. + + A record that produced a single typed block *is* that block — the two share + a window exactly — so the two spans collapse into one rather than drawing the + same instants twice more. The block keeps its identity and content; the + request hands over its attributes and its tokens. + + Handing the tokens over matters more than it looks. The producer's own + `totals.tokens` is the sum over every span it wrote, duplicated usage + included: dropping a record's copy here would leave the recomputed breakdown + disagreeing with the reported totals by a factor of three, and this reader + would appear to have invented the defect. + """ + children = [c for c in raw.get("children") or [] if isinstance(c, dict)] + typed = [c for c in children if str(c.get("kind") or "") in _BLOCK_KINDS] + out = dict(raw) + if len(children) == 1 and len(typed) == 1 and _window(typed[0]) == _window(raw): + block = typed[0] + attributes = {**(raw.get("attributes") or {}), **(block.get("attributes") or {})} + attributes[_MERGED_FROM] = str(raw.get("span_id") or "") + out = dict(block, attributes=attributes) + if raw.get("tokens") and not block.get("tokens"): + out["tokens"] = raw["tokens"] + out["parent_span_id"] = str(parent.get("span_id") or "") + return out + + +def fold_llm_requests(spans: list) -> list: + """Each measured LLM call given the log spans for the reply it produced. + + Without this the same call is drawn twice — as `claude_code.llm_request` + under the interaction, and again as `llm_request` under the log's own + `session` subtree — with the second copy carrying the reasoning and output + text and the first carrying the only measured clock. Folding puts the blocks + under the call, which is the shape Harbor itself writes when the exporter + gives it a request id to join on. + + Nothing is invented and nothing is dropped. Every span survives with its own + start, end and tokens; a request span that collapsed into its one block is + that block, carrying what the request knew. The rows move, the clocks do not, + and the producer's `totals` is untouched, as ever. + + Copy-on-write, like `prune`: a document with nothing to fold is returned by + reference. + """ + containers, wrappers = [], [] + _collect_requests(spans, "", containers, wrappers) + if not containers or not wrappers: + return spans + + folded = _match_requests(containers, _request_groups(wrappers)) + if not folded: + return spans + by_id = {str(c.get("span_id") or ""): c for c in containers} + by_container = { + parent_id: [_folded_child(raw, by_id[parent_id]) for raw in group] + for parent_id, group in folded.items() + } + moved = {id(raw) for group in folded.values() for raw in group} + return _fold_tree(spans, by_container, moved)[0] + + +def _fold_tree(spans: list, by_container: dict, moved: set, depth: int = 0) -> tuple: + """(spans, changed) — the tree with the matched request spans relocated. + + Identity, not span id, is what marks a span as moved: ids are opaque strings + from two producers here, and a collision would otherwise delete a span rather + than move it. + """ + out: list = [] + changed = False + for raw in spans: + if not isinstance(raw, dict): + continue + if id(raw) in moved: + changed = True + continue + children = raw.get("children") or [] + if children and depth < MAX_DEPTH: + children, dropped = _fold_tree(children, by_container, moved, depth + 1) + else: + dropped = False + blocks = by_container.get(str(raw.get("span_id") or "")) + if blocks: + children = sorted(children + blocks, key=lambda s: _window(s)[0]) + attributes = dict(raw.get("attributes") or {}) + attributes[_MERGED_FROM] = ", ".join( + str((b.get("attributes") or {}).get(_MERGED_FROM) or b.get("span_id") or "") + for b in blocks + ) + raw = dict(raw, children=children, attributes=attributes) + elif dropped: + raw = dict(raw, children=children) + changed = changed or dropped or bool(blocks) + out.append(raw) + return out, changed diff --git a/app/nullius/traces/otel.py b/app/nullius/traces/otel.py index 73be33e9..e7f7539a 100644 --- a/app/nullius/traces/otel.py +++ b/app/nullius/traces/otel.py @@ -83,7 +83,7 @@ every call twice. A count the span does not carry is absent, never zero. ``totals`` is computed once, here, by the trial page's own partition -(:func:`trace.breakdown`): every instant charged to one category at priority +(:func:`breakdown`): every instant charged to one category at priority idle > tool > reasoning > llm, so nested and concurrent spans never sum past the clock. ``wall_ns`` is the trace's own window — first start to last end — which is what the coverage strip then compares the spans against. Spans are @@ -113,7 +113,8 @@ import re from nullius.redact import redact -from nullius.traces import trace +from nullius.traces.breakdown import breakdown +from nullius.traces.spans import NS_PER_MS, raw_spans_of DEFAULT_MAX_CONTENT = 2000 @@ -427,7 +428,7 @@ def _span_of(rec: dict, is_root: bool, present: set, limit: int) -> dict: start_ns = _int_or_none(wire.get("startTimeUnixNano")) or 0 if events: attributes["otel.events"] = "; ".join( - f"{ev['name']} +{(ev['time_ns'] - start_ns) // trace.NS_PER_MS}ms" + f"{ev['name']} +{(ev['time_ns'] - start_ns) // NS_PER_MS}ms" if ev["time_ns"] is not None else ev["name"] for ev in events) exc = next((ev for ev in events if ev["name"] == "exception"), None) if exc: @@ -530,7 +531,7 @@ def build(trace_id: str, records: list, limit: int = DEFAULT_MAX_CONTENT, span["attributes"]["otel.orphan"] = True notes.append(f"span {sid} sits in a parent cycle; kept as a root") roots.append(span) - reached.update(s["span_id"] for s in trace.raw_spans_of([span])) + reached.update(s["span_id"] for s in raw_spans_of([span])) for span in by_id.values(): span["children"] = _order(span["children"]) roots = _order(roots) @@ -564,7 +565,7 @@ def build(trace_id: str, records: list, limit: int = DEFAULT_MAX_CONTENT, # The trial page's partition, run once here: idle > tool > reasoning > # llm, every instant charged to one category. Tokens are the sum over # LLM spans, the only ones usage was read on. - "totals": trace.breakdown(roots, wall_ns).as_totals(), + "totals": breakdown(roots, wall_ns).as_totals(), "import": { "format": FORMAT, "conventions": CONVENTIONS, @@ -577,7 +578,7 @@ def build(trace_id: str, records: list, limit: int = DEFAULT_MAX_CONTENT, def model_of(document: dict) -> str: """The first LLM span's model name, or "" — what the importer shows.""" - for raw in trace.raw_spans_of(document.get("spans") or []): + for raw in raw_spans_of(document.get("spans") or []): if raw.get("kind") != "llm_request": continue attrs = raw.get("attributes") or {} diff --git a/app/nullius/traces/spans.py b/app/nullius/traces/spans.py new file mode 100644 index 00000000..e365fa9d --- /dev/null +++ b/app/nullius/traces/spans.py @@ -0,0 +1,418 @@ +"""The span tree of an agent trace: the model, the walks over it, what a span is called. + +``Span`` is one event as the pages read it, built from a raw span by ``_span`` and +redacted on the way. There are two walks, ``all_spans`` over parsed spans and +``raw_spans_of`` over the document's own dicts, and each guards against a parent +cycle rather than hanging. + +A span that is a *namespace* for its children rather than an event of its own is +re-kinded ``group`` (``mark_groups``). ``is_group`` says what qualifies and, more +importantly, the near misses that deliberately do not. + +Stdlib only, and no Flask. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field + +from nullius.redact import redact + +NS_PER_MS = 1_000_000 + +# Nesting past this is a malformed producer, not a deep agent. JSON cannot +# express a cycle, so `load` can never hit it — but `parse` takes a dict, and +# either way a runaway tree would exhaust the stack while building the spans, +# long before any of the guards downstream got a look. +MAX_DEPTH = 64 + +# Legend order. Not the enum's order — this groups the model's own production +# (llm/reasoning/output) together, then work, then structure. +KIND_ORDER = ( + "llm_request", "reasoning", "output", "tool", "subagent", + "session", "user_message", "compaction", "group", +) + +# What a namespace span becomes. A kind of its own rather than a flag, because +# every consumer already switches on `kind` — the swatch, the legend, the chart +# split, and `_KIND_CATEGORY` below, which by omitting it charges a group no time. +GROUP_KIND = "group" + +# Said in the label, because the label is the only thing most of the page shows. +# Appended rather than substituted: "Bash [group]" and "Bash" sort together and +# read as the same call seen at two levels, which is what they are. +GROUP_SUFFIX = " [group]" + +# How far a namespace span's children may fall short of covering it and still +# count as accounting for all of it. +# +# They never tile it exactly. Harbor stamps the wrapper to the millisecond and +# its children to the nanosecond, so each of the two boundaries is up to 1ms out, +# and children routinely overrun the parent they sit in — the same clock +# disagreement the global axis exists to show. Allow both boundaries' rounding. +GROUP_SLACK_NS = 2 * NS_PER_MS + +# Kinds that already say they bracket their children. They are exempt from the +# normalisation below, which exists to stop a span *claiming to be work* when it +# is a container — a kind that never made the claim needs no correcting, and +# `_KIND_CATEGORY` already charges these nothing. +_BRACKET_KINDS = ("session", "subagent", GROUP_KIND) + +# The OTel span for one API call, and the log-derived span for one *record* of +# the reply. Harbor merges the two itself when the exporter reports a request id +# (recorded in `harbor.merged_from`); when the provider returns none +# it cannot, and the same call is left drawn twice — once under the interaction, +# once under the parallel `session` subtree. `fold_llm_requests` finishes the job. +_OTEL_LLM_NAME = "claude_code.llm_request" +_LOG_LLM_NAME = "llm_request" + +# What a call can be shown to have produced. A tool_use block is left untyped by +# the producer, and says nothing about what the call was for. +_BLOCK_KINDS = ("reasoning", "output") + +# Provenance for a span this reader assembled, alongside the producer's own +# `harbor.merged_from`. The `app.` prefix is the whole point: it marks what was +# added here from what was measured there. +_MERGED_FROM = "app.merged_from" +_MERGED_KEYS = ("harbor.merged_from", _MERGED_FROM) + +# Content fields, in reading order. `arguments` is a mapping; the rest are text. +_CONTENT_FIELDS = ( + ("input", "Input"), + ("reasoning", "Reasoning"), + ("output", "Output"), + ("arguments", "Arguments"), + ("result", "Result"), +) + + +@dataclass +class Span: + span_id: str = "" + parent_span_id: str = "" # "" on roots — the key is absent, not null + name: str = "" # the instrumentation name + label: str = "" # what to display; often the tool name instead + kind: str = "" + start_ns: int = 0 + end_ns: int | None = None + duration_ns: int | None = None # None means no known end — a marker, not a zero + timing_quality: str = "unknown" + source: str = "" + attributes: list = field(default_factory=list) # [(key, value_str)] + tokens: dict = field(default_factory=dict) + content: list = field(default_factory=list) # [(label, text)] + children: list = field(default_factory=list) + + @property + def merged(self) -> bool: + """Assembled from more than one source (OTLP span + agent log). + + Either the producer said so, or `fold_llm_requests` did it here — the + badge means the same thing to a reader, so both keys light it. + """ + return any(k in _MERGED_KEYS for k, _ in self.attributes) + + +def block_types_of(raw: dict) -> tuple: + """What kinds of block a request can be shown to have produced. + + Two producers say it two ways and both are read: Harbor emits a child span + per block (`reasoning`, `output`), while another may keep the + text on the call itself. Empty when nothing says — a call whose only block + was a `tool_use` is not "an output call", it is just a call. + """ + content = raw.get("content") or {} + seen = {kind for kind in _BLOCK_KINDS if content.get(kind)} + for child in raw.get("children") or []: + if isinstance(child, dict) and str(child.get("kind") or "") in _BLOCK_KINDS: + seen.add(str(child.get("kind"))) + return tuple(kind for kind in _BLOCK_KINDS if kind in seen) + + +def label_of(name: str, attributes: dict, kind: str = "", blocks: tuple = ()) -> str: + """What to show for a span. + + Merged spans overwrite `name` with the log-derived tool name ("Write"); + unmerged ones keep the instrumentation name ("claude_code.tool") and put the + tool name only in an attribute. Prefer the attribute, so both render as the + tool. The raw name stays on the span for the detail pane. + + An LLM call reads the same way. `claude_code.llm_request` is the exporter's + name for the same thing the agent log calls `llm_request`, so it is shown + under the log's name; and when the call produced exactly one *kind* of block + it is shown under that instead — `reasoning`, or `output`. Two kinds is not + one type, so a call that both thought and answered stays `llm_request`. + + Both of those rules make a bracketing span and the call inside it share a + label, which is why `mark_groups` re-kinds the outer one before this ever + sees it: given `group`, the label says so. The suffix is added here rather + than written onto the span so that one function decides what a span is + called, and the raw name and `tool_name` reach the detail pane untouched. + """ + tool = (attributes or {}).get("tool_name") + if isinstance(tool, str) and tool.strip(): + label = tool.strip() + elif name in (_OTEL_LLM_NAME, _LOG_LLM_NAME): + label = blocks[0] if len(blocks) == 1 else _LOG_LLM_NAME + else: + label = name + return label + GROUP_SUFFIX if kind == GROUP_KIND else label + + +def _int_or_none(value) -> int | None: + return value if isinstance(value, int) and not isinstance(value, bool) else None + + +def _content_of(raw: dict) -> list: + out = [] + for key, label in _CONTENT_FIELDS: + value = raw.get(key) + if value is None or value == "" or value == {} or value == []: + continue + if isinstance(value, (dict, list)): + value = json.dumps(value, ensure_ascii=False, indent=2) + out.append((label, redact(str(value)))) + return out + + +def _span(raw: dict, depth: int = 0) -> Span: + # `.get(k) or {}` rather than `.get(k, {})` throughout: the producer writes + # with exclude_none, so optional fields are absent — but a null would slip + # straight past a default argument and reach the template as None. + attributes = raw.get("attributes") or {} + end_ns = _int_or_none(raw.get("end_ns")) + start_ns = _int_or_none(raw.get("start_ns")) or 0 + duration_ns = _int_or_none(raw.get("duration_ns")) + if duration_ns is None and end_ns is not None: + duration_ns = end_ns - start_ns + + name = redact(str(raw.get("name") or "")) + kind = str(raw.get("kind") or "") + return Span( + span_id=str(raw.get("span_id") or ""), + parent_span_id=str(raw.get("parent_span_id") or ""), + name=name, + label=redact( + label_of(str(raw.get("name") or ""), attributes, kind, block_types_of(raw)) + ), + kind=kind, + start_ns=start_ns, + end_ns=end_ns, + duration_ns=duration_ns, + timing_quality=str(raw.get("timing_quality") or "unknown"), + source=str(raw.get("source") or ""), + # Keys are instrumentation enums (gen_ai.request.model), not job text, so + # they are not redacted; every value is. + attributes=sorted((str(k), redact(str(v))) for k, v in attributes.items()), + tokens={k: v for k, v in (raw.get("tokens") or {}).items() if v is not None}, + content=_content_of(raw.get("content") or {}), + children=( + [_span(c, depth + 1) for c in raw.get("children") or []] + if depth < MAX_DEPTH + else [] + ), + ) + + +def all_spans(roots: list): + """Depth-first walk. Guards against a parent cycle rather than hanging.""" + seen = set() + + def walk(span): + if span.span_id and span.span_id in seen: + return + seen.add(span.span_id) + yield span + for child in span.children: + yield from walk(child) + + for root in roots: + yield from walk(root) + + +def find_span(roots: list, span_id: str): + """The span called *span_id* in this tree, or None. Same walk as `all_spans`.""" + if not span_id: + return None + return next((s for s in all_spans(roots) if s.span_id == span_id), None) + + +def raw_spans_of(spans: list, depth: int = 0): + """Depth-first walk of raw span dicts, straight from the document. + + The filter and everything that saves a file work on raw dicts rather than on + parsed :class:`Span`s: a saved trace has to keep every field the producer + wrote — including the content this reader redacts — and a round trip through + the parser would quietly drop whatever it does not render. + """ + for raw in spans: + if not isinstance(raw, dict): + continue + yield raw + if depth < MAX_DEPTH: + yield from raw_spans_of(raw.get("children") or [], depth + 1) + + +def raw_label(raw: dict) -> str: + """The label a raw span will be displayed under. Redacted, like the parsed one. + + Reads `kind` off the span, so it agrees with :func:`_span` only once + :func:`mark_groups` has run. Everything that filters or counts by label goes + through the normalised document for that reason. + """ + return redact(label_of( + str(raw.get("name") or ""), raw.get("attributes") or {}, + str(raw.get("kind") or ""), block_types_of(raw), + )) + + +def _bare_label(raw: dict) -> str: + """A raw span's label as if it were not a group. Its identity, not its role.""" + return label_of( + str(raw.get("name") or ""), raw.get("attributes") or {}, blocks=block_types_of(raw) + ) + + +def _self_ns(raw: dict) -> int | None: + """Time inside *raw* that none of its children covers, or None if unknowable. + + Overlapping children are merged and clipped to the parent first: a tool call + nested in the LLM call that asked for it would otherwise be counted twice and + make a span with real self-time look fully covered. + """ + start = _int_or_none(raw.get("start_ns")) + end = _int_or_none(raw.get("end_ns")) + if start is None or end is None or end <= start: + return None + inside = [] + for child in raw.get("children") or []: + if not isinstance(child, dict): + continue + low = _int_or_none(child.get("start_ns")) + high = _int_or_none(child.get("end_ns")) + if low is None or high is None: + continue + low, high = max(low, start), min(high, end) + if high > low: + inside.append((low, high)) + return (end - start) - sum(high - low for low, high in merge_intervals(inside)) + + +def _same_extent(raw: dict, child: dict) -> bool: + """Do these two spans start and end together, to within `GROUP_SLACK_NS`? + + Both ends, and that is the point. Coverage alone is satisfied by a child that + overruns its parent — a background subagent hung under the launch that + returned in 47ms runs for minutes. Clipped + to the parent it covers all of it, but the launch is a real 47ms event. + """ + for key in ("start_ns", "end_ns"): + mine, theirs = _int_or_none(raw.get(key)), _int_or_none(child.get(key)) + if mine is None or theirs is None or abs(mine - theirs) > GROUP_SLACK_NS: + return False + return True + + +def is_group(raw: dict) -> bool: + """Is this span a namespace for its children rather than an event itself? + + **Its children have to account for all of it**, to within `GROUP_SLACK_NS`. + A span that also spent time of its own is doing something, whatever it is + named. That is necessary but nowhere near sufficient, so one of two further + signals has to say the span adds no distinction to what it contains: + + * **it shares its label with a child** — Harbor's `claude_code.tool` carries + `tool_name: "Bash"` and holds the span that actually ran Bash, so one call + would otherwise be counted twice under one name; or + * **it has a single child of the same extent** — the same bar drawn twice. + An `llm_request` may hold one `reasoning` or `output` block whose start + and end are *byte-identical* to its own, + because the producer splits a response into blocks and a one-block response + is the request again. `fold_llm_requests` runs first and collapses that + pair outright wherever it can match the request to the call it answered, + which is the better answer — one span keeping both clocks and both sets of + text. What reaches here is the remainder it could not match. + + Everything else with children stays what it is, and the near misses are worth + knowing because each one looks like this from a distance. OpenCode's + `ai.streamText` also brackets the stream call it is named for, but can spend + time on its own transport; it is still a call. `claude_code.interaction` + is covered by the calls inside it, and `session`/`subagent` are exempt + outright: a kind that already announces itself as a bracket is not claiming + to be work, and `_KIND_CATEGORY` already charges it nothing. A group is + specifically a span pretending to be the event nested inside it. + + A call `fold_llm_requests` gave children to is exempt for a sharper reason: + it would match, always, and the match would be this reader's own doing. The + fold moves the reply's blocks under the call and then labels the call after + what it produced, so the parent shares a label with a child by construction + and the blocks span the call because they are the reply to it. Nothing was + pretending to be anything — and the call is the one span in that subtree with + a measured clock, so re-kinding it would charge the only real measurement to + nothing and leave the inferred blocks holding the time. + """ + if str(raw.get("kind") or "") in _BRACKET_KINDS: + return False + if _MERGED_FROM in (raw.get("attributes") or {}): + return False + children = [c for c in raw.get("children") or [] if isinstance(c, dict)] + if not children: + return False + self_ns = _self_ns(raw) + if self_ns is None or self_ns > GROUP_SLACK_NS: + return False + if len(children) == 1 and _same_extent(raw, children[0]): + return True + # Compared without the suffix on either side. `mark_groups` works children + # first, so an inner span may already be a group by the time the outer one is + # asked; matching on the displayed label would then miss a doubly-wrapped + # call and leave the outer one claiming to be the tool. + label = _bare_label(raw) + return any(_bare_label(c) == label for c in children) + + +def mark_groups(spans: list, depth: int = 0) -> list: + """*spans* with every namespace span re-kinded `group`, children first. + + Runs once, before anything filters or counts, so that the label a chip + offers, the label in the query string and the label on the row are the same + string — decided per span, never per surviving child. Filtering the `Bash` + inside a group therefore leaves the group a group, still named for what it + used to contain, which is the only answer that keeps a filter from renaming + the rows it was not asked about. + + Copy-on-write like :func:`prune`: a subtree with no groups in it is passed + through by reference, so the caller's document is never mutated. + """ + out: list = [] + changed = False + for raw in spans: + if not isinstance(raw, dict): + changed = True + continue + children = raw.get("children") or [] + if children and depth < MAX_DEPTH: + marked = mark_groups(children, depth + 1) + if marked is not children: + raw, changed = dict(raw, children=marked), True + if is_group(raw): + raw, changed = dict(raw, kind=GROUP_KIND), True + out.append(raw) + return out if changed else spans + + +def merge_intervals(intervals: list) -> list: + """Overlapping [start, end) runs collapsed into disjoint ones.""" + out: list = [] + for start, end in sorted(intervals): + if out and start <= out[-1][1]: + out[-1] = (out[-1][0], max(out[-1][1], end)) + else: + out.append((start, end)) + return out + + +def is_instant(span: Span) -> bool: + """No usable duration: one known instant, or an explicitly unknown clock.""" + return span.timing_quality == "unknown" or not (span.duration_ns and span.duration_ns > 0) diff --git a/app/nullius/traces/trace.py b/app/nullius/traces/trace.py index bb083c71..0db8b2bf 100644 --- a/app/nullius/traces/trace.py +++ b/app/nullius/traces/trace.py @@ -16,32 +16,36 @@ and everything outside it is left out of the waterfall rather than re-scaled. **Totals are the producer's job.** ``totals`` is displayed verbatim and never -recomputed from the tree — see :class:`Totals`. A filtered view is the one case +recomputed from the tree — see :class:`breakdown.Totals`. A filtered view is the one case that needs its own arithmetic, because hiding a span has to move its time somewhere and the producer cannot be asked again; that lives in -:class:`Breakdown`, is labelled as derived wherever it is shown, and never +:class:`breakdown.Breakdown`, is labelled as derived wherever it is shown, and never overwrites what the file said. Two normalisations happen on the way in, in that order, and they are the only two. First, a call the exporter measured is given the log spans for the reply it produced, which the producer writes as a second copy of the same call when it has -no request id to join them on. See :func:`fold_llm_requests`; it moves rows and +no request id to join them on. See :func:`fold.fold_llm_requests`; it moves rows and no numbers. Then a span that is a *namespace* for its children rather than an event of its own is re-kinded ``group`` and reads ``Bash [group]``: Harbor's Claude Code instrumentation opens a ``claude_code.tool`` span carrying ``tool_name: "Bash"`` and puts the permission wait and the actual ``Bash`` execution inside it. Counting the wrapper as work would double-count the call. -See :func:`is_group` for what qualifies and, more importantly, for the near +See :func:`spans.is_group` for what qualifies and, more importantly, for the near misses that deliberately do not. The order is load-bearing. An ``llm_request`` holding a single ``reasoning`` or ``output`` block of byte-identical extent is the same -duplication :func:`fold_llm_requests` resolves, and it resolves it better: the +duplication :func:`fold.fold_llm_requests` resolves, and it resolves it better: the wrapper and its one block collapse into a single span carrying both the request's tokens and the block's text, where re-kinding leaves two rows and charges one of them nothing. Folding first leaves ``is_group`` only the wrappers fold could not match to a call, which is the case it is still needed for. +This module is the reader's front: ``Trace``, ``Filter``, ``parse``, ``load`` and the +saved view. The span tree is ``spans``, the fold ``fold``, the accounting +``breakdown``, the layout ``waterfall``. + Everything is redacted at load, so templates hold display text only. Stdlib only, and no Flask: ``python3 -m unittest discover -s app/tests -t app`` needs no install at all. @@ -49,287 +53,16 @@ from __future__ import annotations -import bisect import json -import math from dataclasses import dataclass, field -from nullius.redact import redact - -NS_PER_MS = 1_000_000 - -# A residual under this reads as float noise from the producer's own arithmetic, -# not as real unattributed time. Rendering it produces a zero-width segment with -# a legend entry saying "0ms". -UNACCOUNTED_EPSILON_NS = NS_PER_MS - -# An exporter can emit thousands of spans for a trivial task. Every row is -# rendered server-side with its own detail pane, so the page has to be bounded. -MAX_ROWS = 2000 - -# Nesting past this is a malformed producer, not a deep agent. JSON cannot -# express a cycle, so `load` can never hit it — but `parse` takes a dict, and -# either way a runaway tree would exhaust the stack while building the spans, -# long before any of the guards downstream got a look. -MAX_DEPTH = 64 - -# Legend order. Not the enum's order — this groups the model's own production -# (llm/reasoning/output) together, then work, then structure. -KIND_ORDER = ( - "llm_request", "reasoning", "output", "tool", "subagent", - "session", "user_message", "compaction", "group", +from .spans import ( + all_spans, find_span, _int_or_none, KIND_ORDER, mark_groups, MAX_DEPTH, raw_label, raw_spans_of, + Span, _span, ) - -# What a namespace span becomes. A kind of its own rather than a flag, because -# every consumer already switches on `kind` — the swatch, the legend, the chart -# split, and `_KIND_CATEGORY` below, which by omitting it charges a group no time. -GROUP_KIND = "group" - -# Said in the label, because the label is the only thing most of the page shows. -# Appended rather than substituted: "Bash [group]" and "Bash" sort together and -# read as the same call seen at two levels, which is what they are. -GROUP_SUFFIX = " [group]" - -# How far a namespace span's children may fall short of covering it and still -# count as accounting for all of it. -# -# They never tile it exactly. Harbor stamps the wrapper to the millisecond and -# its children to the nanosecond, so each of the two boundaries is up to 1ms out, -# and children routinely overrun the parent they sit in — the same clock -# disagreement the global axis exists to show. Allow both boundaries' rounding. -GROUP_SLACK_NS = 2 * NS_PER_MS - -# Kinds that already say they bracket their children. They are exempt from the -# normalisation below, which exists to stop a span *claiming to be work* when it -# is a container — a kind that never made the claim needs no correcting, and -# `_KIND_CATEGORY` already charges these nothing. -_BRACKET_KINDS = ("session", "subagent", GROUP_KIND) - -# Breakdown segments, in a fixed left-to-right order. The order carries no -# meaning — these are categories, not a timeline — but a stable one keeps the -# strip from reshuffling between trials. -_SEGMENTS = ( - ("llm", "LLM", "llm_ns"), - ("tool", "Tool", "tool_ns"), - ("reasoning", "Reasoning", "reasoning_ns"), - ("idle", "Idle", "idle_ns"), -) - -# The residual is a segment like any other once it reaches a strip, and both -# `segments_of` and `Breakdown.compared_to` need to name and order it. -_UNACCOUNTED = ("unaccounted", "Unaccounted") -_SEGMENT_LABELS = {key: label for key, label, _ in _SEGMENTS} | {_UNACCOUNTED[0]: _UNACCOUNTED[1]} -_SEGMENT_ORDER = [key for key, _, _ in _SEGMENTS] + [_UNACCOUNTED[0]] - -# What a span's own time counts toward when a breakdown has to be recomputed for -# a filtered view. The structural kinds are absent on purpose: `session`, -# `subagent` and `group` bracket their children, so charging them would claim the -# children's work as their own, and `output` is text produced inside a call that -# is already counted as `llm`. -_KIND_CATEGORY = {"llm_request": "llm", "reasoning": "reasoning", "tool": "tool"} - -# Priority for `partition`. A tool that only waits for a human beats real work, -# and both beat the LLM call they happened inside of. -_PRIORITY = ("idle", "tool", "reasoning", "llm") - -# A tool whose whole job is to wait for the human. Harbor opens a span with this -# name; another producer may set an attribute instead. Either way the time -# is not the agent working, so it lands in `idle` rather than `tool`. -_BLOCKED_NAME = "claude_code.tool.blocked_on_user" -_BLOCKED_ATTR = "blocked_on_user" - -# The OTel span for one API call, and the log-derived span for one *record* of -# the reply. Harbor merges the two itself when the exporter reports a request id -# (recorded in `harbor.merged_from`); when the provider returns none -# it cannot, and the same call is left drawn twice — once under the interaction, -# once under the parallel `session` subtree. `fold_llm_requests` finishes the job. -_OTEL_LLM_NAME = "claude_code.llm_request" -_LOG_LLM_NAME = "llm_request" - -# What a call can be shown to have produced. A tool_use block is left untyped by -# the producer, and says nothing about what the call was for. -_BLOCK_KINDS = ("reasoning", "output") - -# Provenance for a span this reader assembled, alongside the producer's own -# `harbor.merged_from`. The `app.` prefix is the whole point: it marks what was -# added here from what was measured there. -_MERGED_FROM = "app.merged_from" -_MERGED_KEYS = ("harbor.merged_from", _MERGED_FROM) - -# Content fields, in reading order. `arguments` is a mapping; the rest are text. -_CONTENT_FIELDS = ( - ("input", "Input"), - ("reasoning", "Reasoning"), - ("output", "Output"), - ("arguments", "Arguments"), - ("result", "Result"), -) - - -def segments_of(source) -> list: - """[{key, label, ns, pct}] for a stacked strip, zero-length categories dropped. - - Shared by :class:`Totals` and :class:`Breakdown` so the reported strip and a - recomputed one are laid out and labelled identically — the only difference - between them should be the numbers, never the presentation. - - Percentages are of the wall clock, so categories that do not close read as - short of 100% instead of being silently rescaled to fill it; ``unaccounted`` - is what closes them. With no wall clock to divide by they fall back to the - segments' own sum, which is the only honest denominator left. - """ - out = [ - {"key": key, "label": label, "ns": int(getattr(source, attr))} - for key, label, attr in _SEGMENTS - if getattr(source, attr) - ] - if source.unaccounted_ns: - out.append({"key": _UNACCOUNTED[0], "label": _UNACCOUNTED[1], "ns": source.unaccounted_ns}) - denominator = source.wall_ns or sum(seg["ns"] for seg in out) - for seg in out: - seg["pct"] = seg["ns"] / denominator * 100 if denominator else 0.0 - return out - - -@dataclass(frozen=True) -class Extent: - """The window the axis covers, derived from the spans themselves. - - Never from the host wall clock: spans are stamped inside the container and - ``totals.wall_ns`` on the host, so mixing them puts bars in the wrong place. - """ - - start_ns: int = 0 - end_ns: int = 1 - span_ns: int = 1 # floored at 1 — an all-instant trace would divide by zero - - -@dataclass -class Tick: - pct: float - ns: int # offset from the extent start, not an epoch value - - -@dataclass -class Totals: - """Run-level time, exactly as the producer reported it. - - **Never recomputed from the tree.** Summing nested spans double-counts - their shared time. The producer already resolved that (it skips tools nested - inside tools, and subtracts tool time nested inside LLM spans). The only - arithmetic this class does is the residual, which is a display concern. - """ - - wall_ns: int | None = None - llm_ns: int | None = None - tool_ns: int | None = None - reasoning_ns: int | None = None - idle_ns: int | None = None - span_count: int | None = None - measured_span_count: int | None = None - - @property - def unaccounted_ns(self) -> int: - """Wall clock the categories don't account for. - - The categories are not expected to close: the session span brackets more - than its instrumented children, so a stacked bar that just leaves a gap - reads as a rendering bug. Name the gap instead. Clamped at both ends — - under an epsilon it is noise, and a negative would corrupt the geometry - silently (the same reasoning as `Trial.dur_other`). - """ - if not self.wall_ns: - return 0 - rest = sum(v or 0 for v in (self.llm_ns, self.tool_ns, self.reasoning_ns, self.idle_ns)) - residual = self.wall_ns - rest - return int(residual) if residual >= UNACCOUNTED_EPSILON_NS else 0 - - @property - def segments(self) -> list: - """[{key, label, ns, pct}] for the breakdown strip.""" - return segments_of(self) - - -@dataclass -class Breakdown: - """Category time recomputed from a set of spans — for a filtered view only. - - The producer's ``totals`` stays authoritative and is never replaced by this - (see :class:`Totals`). It exists because hiding spans has to take their time - out of the picture, and the producer cannot be asked a second time. - - It is deliberately *not* the same arithmetic, and it does not reproduce the - same numbers. Harbor's ``llm_ns`` is the plain sum of its LLM spans, while - this partitions the timeline so an instant covered by both a tool call and - the LLM call that asked for it is charged once, to the tool. The two are - shown as separate strips because they measure different things. - - ``wall_ns`` is carried over from the source unchanged: hiding a span does not - make the run shorter, it makes more of the run unattributed. That is what - ``unaccounted_ns`` then absorbs, and it is the honest place for it to land. - """ - - wall_ns: int = 0 - llm_ns: int = 0 - tool_ns: int = 0 - reasoning_ns: int = 0 - idle_ns: int = 0 - span_count: int = 0 - measured_span_count: int = 0 - tokens: dict = field(default_factory=dict) - - @property - def attributed_ns(self) -> int: - """Wall clock the categories account for. Disjoint, so a plain sum.""" - return self.llm_ns + self.tool_ns + self.reasoning_ns + self.idle_ns - - @property - def unaccounted_ns(self) -> int: - residual = (self.wall_ns or 0) - self.attributed_ns - return int(residual) if residual >= UNACCOUNTED_EPSILON_NS else 0 - - @property - def segments(self) -> list: - return segments_of(self) - - def compared_to(self, other: "Breakdown") -> list: - """`segments`, each carrying `delta_ns` against *other*. - - The comparison a filtered view actually needs. Both sides come from this - same partition, so every delta is the filter's doing and nothing else — - whereas the difference against the producer's reported strip mixes the - filter up with two different ways of accounting for the same run, and on - a log-derived trace those disagree by minutes, not milliseconds. - - A category the filter emptied keeps its entry at 0ns: dropping it would - hide the largest thing the filter did. - """ - was = {seg["key"]: seg["ns"] for seg in other.segments} - out = self.segments - here = {seg["key"] for seg in out} - out.extend( - {"key": key, "label": _SEGMENT_LABELS[key], "ns": 0, "pct": 0.0} - for key in was - if key not in here - ) - out.sort(key=lambda seg: _SEGMENT_ORDER.index(seg["key"])) - for seg in out: - seg["delta_ns"] = seg["ns"] - was.get(seg["key"], 0) - return out - - def as_totals(self) -> dict: - """The ``totals`` block to write into a saved filtered trace.""" - return { - "wall_ns": self.wall_ns, - "llm_ns": self.llm_ns, - "tool_ns": self.tool_ns, - "reasoning_ns": self.reasoning_ns, - "idle_ns": self.idle_ns, - "span_count": self.span_count, - "measured_span_count": self.measured_span_count, - "tokens": dict(self.tokens), - } - +from .fold import fold_llm_requests +from .breakdown import Breakdown, breakdown, Totals, _totals +from .waterfall import Extent, extent_of, flatten, raw_extent, ticks_for def clean(values) -> tuple: """Deduplicated, sorted, blank-free — so one view has exactly one URL.""" @@ -421,46 +154,6 @@ class Facet: hidden: bool = False -@dataclass -class Span: - span_id: str = "" - parent_span_id: str = "" # "" on roots — the key is absent, not null - name: str = "" # the instrumentation name - label: str = "" # what to display; often the tool name instead - kind: str = "" - start_ns: int = 0 - end_ns: int | None = None - duration_ns: int | None = None # None means no known end — a marker, not a zero - timing_quality: str = "unknown" - source: str = "" - attributes: list = field(default_factory=list) # [(key, value_str)] - tokens: dict = field(default_factory=dict) - content: list = field(default_factory=list) # [(label, text)] - children: list = field(default_factory=list) - - @property - def merged(self) -> bool: - """Assembled from more than one source (OTLP span + agent log). - - Either the producer said so, or `fold_llm_requests` did it here — the - badge means the same thing to a reader, so both keys light it. - """ - return any(k in _MERGED_KEYS for k, _ in self.attributes) - - -@dataclass -class Row: - """One rendered waterfall row: a span placed on the global axis.""" - - span: Span - depth: int = 0 - has_children: bool = False - offset_ns: int = 0 # exact int; only the percentages become floats - left_pct: float = 0.0 - width_pct: float = 0.0 - is_instant: bool = False - - @dataclass class Trace: run_id: str = "" @@ -545,340 +238,6 @@ def qualities_present(self) -> list: return [q for q in ("measured", "inferred", "unknown") if q in seen] -def block_types_of(raw: dict) -> tuple: - """What kinds of block a request can be shown to have produced. - - Two producers say it two ways and both are read: Harbor emits a child span - per block (`reasoning`, `output`), while another may keep the - text on the call itself. Empty when nothing says — a call whose only block - was a `tool_use` is not "an output call", it is just a call. - """ - content = raw.get("content") or {} - seen = {kind for kind in _BLOCK_KINDS if content.get(kind)} - for child in raw.get("children") or []: - if isinstance(child, dict) and str(child.get("kind") or "") in _BLOCK_KINDS: - seen.add(str(child.get("kind"))) - return tuple(kind for kind in _BLOCK_KINDS if kind in seen) - - -def label_of(name: str, attributes: dict, kind: str = "", blocks: tuple = ()) -> str: - """What to show for a span. - - Merged spans overwrite `name` with the log-derived tool name ("Write"); - unmerged ones keep the instrumentation name ("claude_code.tool") and put the - tool name only in an attribute. Prefer the attribute, so both render as the - tool. The raw name stays on the span for the detail pane. - - An LLM call reads the same way. `claude_code.llm_request` is the exporter's - name for the same thing the agent log calls `llm_request`, so it is shown - under the log's name; and when the call produced exactly one *kind* of block - it is shown under that instead — `reasoning`, or `output`. Two kinds is not - one type, so a call that both thought and answered stays `llm_request`. - - Both of those rules make a bracketing span and the call inside it share a - label, which is why `mark_groups` re-kinds the outer one before this ever - sees it: given `group`, the label says so. The suffix is added here rather - than written onto the span so that one function decides what a span is - called, and the raw name and `tool_name` reach the detail pane untouched. - """ - tool = (attributes or {}).get("tool_name") - if isinstance(tool, str) and tool.strip(): - label = tool.strip() - elif name in (_OTEL_LLM_NAME, _LOG_LLM_NAME): - label = blocks[0] if len(blocks) == 1 else _LOG_LLM_NAME - else: - label = name - return label + GROUP_SUFFIX if kind == GROUP_KIND else label - - -def _int_or_none(value) -> int | None: - return value if isinstance(value, int) and not isinstance(value, bool) else None - - -def _content_of(raw: dict) -> list: - out = [] - for key, label in _CONTENT_FIELDS: - value = raw.get(key) - if value is None or value == "" or value == {} or value == []: - continue - if isinstance(value, (dict, list)): - value = json.dumps(value, ensure_ascii=False, indent=2) - out.append((label, redact(str(value)))) - return out - - -def _span(raw: dict, depth: int = 0) -> Span: - # `.get(k) or {}` rather than `.get(k, {})` throughout: the producer writes - # with exclude_none, so optional fields are absent — but a null would slip - # straight past a default argument and reach the template as None. - attributes = raw.get("attributes") or {} - end_ns = _int_or_none(raw.get("end_ns")) - start_ns = _int_or_none(raw.get("start_ns")) or 0 - duration_ns = _int_or_none(raw.get("duration_ns")) - if duration_ns is None and end_ns is not None: - duration_ns = end_ns - start_ns - - name = redact(str(raw.get("name") or "")) - kind = str(raw.get("kind") or "") - return Span( - span_id=str(raw.get("span_id") or ""), - parent_span_id=str(raw.get("parent_span_id") or ""), - name=name, - label=redact( - label_of(str(raw.get("name") or ""), attributes, kind, block_types_of(raw)) - ), - kind=kind, - start_ns=start_ns, - end_ns=end_ns, - duration_ns=duration_ns, - timing_quality=str(raw.get("timing_quality") or "unknown"), - source=str(raw.get("source") or ""), - # Keys are instrumentation enums (gen_ai.request.model), not job text, so - # they are not redacted; every value is. - attributes=sorted((str(k), redact(str(v))) for k, v in attributes.items()), - tokens={k: v for k, v in (raw.get("tokens") or {}).items() if v is not None}, - content=_content_of(raw.get("content") or {}), - children=( - [_span(c, depth + 1) for c in raw.get("children") or []] - if depth < MAX_DEPTH - else [] - ), - ) - - -def all_spans(roots: list): - """Depth-first walk. Guards against a parent cycle rather than hanging.""" - seen = set() - - def walk(span): - if span.span_id and span.span_id in seen: - return - seen.add(span.span_id) - yield span - for child in span.children: - yield from walk(child) - - for root in roots: - yield from walk(root) - - -def extent_of(roots: list) -> Extent: - spans = list(all_spans(roots)) - if not spans: - return Extent() - start = min(s.start_ns for s in spans) - end = max((s.end_ns if s.end_ns is not None else s.start_ns) for s in spans) - # Floored at 1: a trace whose spans are all instants has end == start, and - # every percentage would come out NaN or Infinity. - return Extent(start_ns=start, end_ns=end, span_ns=max(end - start, 1)) - - -def find_span(roots: list, span_id: str): - """The span called *span_id* in this tree, or None. Same walk as `all_spans`.""" - if not span_id: - return None - return next((s for s in all_spans(roots) if s.span_id == span_id), None) - - -def raw_spans_of(spans: list, depth: int = 0): - """Depth-first walk of raw span dicts, straight from the document. - - The filter and everything that saves a file work on raw dicts rather than on - parsed :class:`Span`s: a saved trace has to keep every field the producer - wrote — including the content this reader redacts — and a round trip through - the parser would quietly drop whatever it does not render. - """ - for raw in spans: - if not isinstance(raw, dict): - continue - yield raw - if depth < MAX_DEPTH: - yield from raw_spans_of(raw.get("children") or [], depth + 1) - - -def raw_label(raw: dict) -> str: - """The label a raw span will be displayed under. Redacted, like the parsed one. - - Reads `kind` off the span, so it agrees with :func:`_span` only once - :func:`mark_groups` has run. Everything that filters or counts by label goes - through the normalised document for that reason. - """ - return redact(label_of( - str(raw.get("name") or ""), raw.get("attributes") or {}, - str(raw.get("kind") or ""), block_types_of(raw), - )) - - -def _bare_label(raw: dict) -> str: - """A raw span's label as if it were not a group. Its identity, not its role.""" - return label_of( - str(raw.get("name") or ""), raw.get("attributes") or {}, blocks=block_types_of(raw) - ) - - -def _self_ns(raw: dict) -> int | None: - """Time inside *raw* that none of its children covers, or None if unknowable. - - Overlapping children are merged and clipped to the parent first: a tool call - nested in the LLM call that asked for it would otherwise be counted twice and - make a span with real self-time look fully covered. - """ - start = _int_or_none(raw.get("start_ns")) - end = _int_or_none(raw.get("end_ns")) - if start is None or end is None or end <= start: - return None - inside = [] - for child in raw.get("children") or []: - if not isinstance(child, dict): - continue - low = _int_or_none(child.get("start_ns")) - high = _int_or_none(child.get("end_ns")) - if low is None or high is None: - continue - low, high = max(low, start), min(high, end) - if high > low: - inside.append((low, high)) - return (end - start) - sum(high - low for low, high in merge_intervals(inside)) - - -def _same_extent(raw: dict, child: dict) -> bool: - """Do these two spans start and end together, to within `GROUP_SLACK_NS`? - - Both ends, and that is the point. Coverage alone is satisfied by a child that - overruns its parent — a background subagent hung under the launch that - returned in 47ms runs for minutes. Clipped - to the parent it covers all of it, but the launch is a real 47ms event. - """ - for key in ("start_ns", "end_ns"): - mine, theirs = _int_or_none(raw.get(key)), _int_or_none(child.get(key)) - if mine is None or theirs is None or abs(mine - theirs) > GROUP_SLACK_NS: - return False - return True - - -def is_group(raw: dict) -> bool: - """Is this span a namespace for its children rather than an event itself? - - **Its children have to account for all of it**, to within `GROUP_SLACK_NS`. - A span that also spent time of its own is doing something, whatever it is - named. That is necessary but nowhere near sufficient, so one of two further - signals has to say the span adds no distinction to what it contains: - - * **it shares its label with a child** — Harbor's `claude_code.tool` carries - `tool_name: "Bash"` and holds the span that actually ran Bash, so one call - would otherwise be counted twice under one name; or - * **it has a single child of the same extent** — the same bar drawn twice. - An `llm_request` may hold one `reasoning` or `output` block whose start - and end are *byte-identical* to its own, - because the producer splits a response into blocks and a one-block response - is the request again. `fold_llm_requests` runs first and collapses that - pair outright wherever it can match the request to the call it answered, - which is the better answer — one span keeping both clocks and both sets of - text. What reaches here is the remainder it could not match. - - Everything else with children stays what it is, and the near misses are worth - knowing because each one looks like this from a distance. OpenCode's - `ai.streamText` also brackets the stream call it is named for, but can spend - time on its own transport; it is still a call. `claude_code.interaction` - is covered by the calls inside it, and `session`/`subagent` are exempt - outright: a kind that already announces itself as a bracket is not claiming - to be work, and `_KIND_CATEGORY` already charges it nothing. A group is - specifically a span pretending to be the event nested inside it. - - A call `fold_llm_requests` gave children to is exempt for a sharper reason: - it would match, always, and the match would be this reader's own doing. The - fold moves the reply's blocks under the call and then labels the call after - what it produced, so the parent shares a label with a child by construction - and the blocks span the call because they are the reply to it. Nothing was - pretending to be anything — and the call is the one span in that subtree with - a measured clock, so re-kinding it would charge the only real measurement to - nothing and leave the inferred blocks holding the time. - """ - if str(raw.get("kind") or "") in _BRACKET_KINDS: - return False - if _MERGED_FROM in (raw.get("attributes") or {}): - return False - children = [c for c in raw.get("children") or [] if isinstance(c, dict)] - if not children: - return False - self_ns = _self_ns(raw) - if self_ns is None or self_ns > GROUP_SLACK_NS: - return False - if len(children) == 1 and _same_extent(raw, children[0]): - return True - # Compared without the suffix on either side. `mark_groups` works children - # first, so an inner span may already be a group by the time the outer one is - # asked; matching on the displayed label would then miss a doubly-wrapped - # call and leave the outer one claiming to be the tool. - label = _bare_label(raw) - return any(_bare_label(c) == label for c in children) - - -def mark_groups(spans: list, depth: int = 0) -> list: - """*spans* with every namespace span re-kinded `group`, children first. - - Runs once, before anything filters or counts, so that the label a chip - offers, the label in the query string and the label on the row are the same - string — decided per span, never per surviving child. Filtering the `Bash` - inside a group therefore leaves the group a group, still named for what it - used to contain, which is the only answer that keeps a filter from renaming - the rows it was not asked about. - - Copy-on-write like :func:`prune`: a subtree with no groups in it is passed - through by reference, so the caller's document is never mutated. - """ - out: list = [] - changed = False - for raw in spans: - if not isinstance(raw, dict): - changed = True - continue - children = raw.get("children") or [] - if children and depth < MAX_DEPTH: - marked = mark_groups(children, depth + 1) - if marked is not children: - raw, changed = dict(raw, children=marked), True - if is_group(raw): - raw, changed = dict(raw, kind=GROUP_KIND), True - out.append(raw) - return out if changed else spans - - -def category_of(raw: dict) -> str | None: - """Which breakdown category a span's own time belongs to, or None. - - None means the span contributes no time of its own — see `_KIND_CATEGORY`. - """ - kind = str(raw.get("kind") or "") - if kind == "tool" and ( - str(raw.get("name") or "") == _BLOCKED_NAME - or (raw.get("attributes") or {}).get(_BLOCKED_ATTR) - ): - return "idle" - return _KIND_CATEGORY.get(kind) - - -def raw_extent(spans: list) -> Extent: - """The axis window, taken from the raw document. - - Called with the *unfiltered* spans on purpose: hiding one must not slide the - remaining bars sideways, or a filter would look like it changed timings it - was only asked to leave out. What it removes shows up as empty axis instead. - Matches `extent_of` span for span, including its treatment of a span with no - usable start (0, like `_span`) or no end (its own start). - """ - starts, ends = [], [] - for raw in raw_spans_of(spans): - start = _int_or_none(raw.get("start_ns")) or 0 - end = _int_or_none(raw.get("end_ns")) - starts.append(start) - ends.append(start if end is None else end) - if not starts: - return Extent() - low, high = min(starts), max(ends) - return Extent(start_ns=low, end_ns=high, span_ns=max(high - low, 1)) - - def inventory(spans: list, filt: "Filter | None" = None) -> list: """Every distinct span label in the document, with how many spans carry it. @@ -923,207 +282,6 @@ def labels_by_id(spans: list) -> dict: } -def _window(raw: dict) -> tuple: - """(start, end) in ns, an unknown end read as the start — same as `_span`.""" - start = _int_or_none(raw.get("start_ns")) or 0 - end = _int_or_none(raw.get("end_ns")) - return start, start if end is None else end - - -def _tokens_key(raw: dict) -> tuple: - """A call's usage, as something comparable. Empty when none was reported.""" - return tuple( - sorted( - (str(k), v) - for k, v in (raw.get("tokens") or {}).items() - if _int_or_none(v) is not None - ) - ) - - -def _request_groups(wrappers: list) -> list: - """Log request spans grouped by the reply they came from. - - One API call arrives as several records — a thinking block, each tool_use, - the final text — and the producer opens a span per record. They carry one - `message.id` between them, which is exactly the grouping wanted; a producer - that omits it leaves every record its own group, which folds them one by one - and is no worse than not folding at all. - """ - groups: dict = {} - order: list = [] - for raw in wrappers: - key = (raw.get("attributes") or {}).get("message.id") - key = str(key) if key else "ungrouped:" + str(raw.get("span_id") or id(raw)) - if key not in groups: - groups[key] = [] - order.append(key) - groups[key].append(raw) - return [groups[key] for key in order] - - -def _match_requests(containers: list, groups: list) -> dict: - """container span_id → the log request spans belonging to it. - - Harbor joins these on the request id the exporter reported. This runs where - the provider returned none, so the join is on what is left: identical usage, - and overlapping windows. Usage is a hard constraint when both sides report - it and the overlap only ranks the candidates, which is what keeps two calls - that happen to overlap from swapping their blocks. - - A wrong match moves a row under the wrong call; it cannot change a number, - because folding re-parents spans and never touches a clock. - """ - taken: set = set() - out: dict = {} - for container in sorted(containers, key=lambda raw: _window(raw)[0]): - c_start, c_end = _window(container) - c_tokens = _tokens_key(container) - best = None - for index, group in enumerate(groups): - if index in taken: - continue - g_start = min(_window(raw)[0] for raw in group) - g_end = max(_window(raw)[1] for raw in group) - if g_start >= c_end or c_start >= g_end: - continue - g_tokens = next((t for t in map(_tokens_key, group) if t), ()) - if c_tokens and g_tokens and c_tokens != g_tokens: - continue - distance = abs(g_start - c_start) - if best is None or distance < best[0]: - best = (distance, index, group) - if best is not None: - taken.add(best[1]) - out[str(container.get("span_id") or "")] = best[2] - return out - - -def _collect_requests( - spans: list, parent: str, containers: list, wrappers: list, depth: int = 0 -) -> None: - """The calls to fold into, and the log request spans still to fold. - - A request already sitting under a call has been folded — by this function on - an earlier read, or by Harbor itself — and must not be folded again: a saved - view can be filtered again, which re-reads a document this has already seen, - and a second pass would rewrite the provenance of the first. - """ - for raw in spans: - if not isinstance(raw, dict): - continue - name = str(raw.get("name") or "") - if name == _OTEL_LLM_NAME: - containers.append(raw) - elif ( - name == _LOG_LLM_NAME - and str(raw.get("source") or "") == "log" - and parent != _OTEL_LLM_NAME - ): - wrappers.append(raw) - if depth < MAX_DEPTH: - _collect_requests(raw.get("children") or [], name, containers, wrappers, depth + 1) - - -def _folded_child(raw: dict, parent: dict) -> dict: - """One log request span, rewritten to sit under the call it belongs to. - - A record that produced a single typed block *is* that block — the two share - a window exactly — so the two spans collapse into one rather than drawing the - same instants twice more. The block keeps its identity and content; the - request hands over its attributes and its tokens. - - Handing the tokens over matters more than it looks. The producer's own - `totals.tokens` is the sum over every span it wrote, duplicated usage - included: dropping a record's copy here would leave the recomputed breakdown - disagreeing with the reported totals by a factor of three, and this reader - would appear to have invented the defect. - """ - children = [c for c in raw.get("children") or [] if isinstance(c, dict)] - typed = [c for c in children if str(c.get("kind") or "") in _BLOCK_KINDS] - out = dict(raw) - if len(children) == 1 and len(typed) == 1 and _window(typed[0]) == _window(raw): - block = typed[0] - attributes = {**(raw.get("attributes") or {}), **(block.get("attributes") or {})} - attributes[_MERGED_FROM] = str(raw.get("span_id") or "") - out = dict(block, attributes=attributes) - if raw.get("tokens") and not block.get("tokens"): - out["tokens"] = raw["tokens"] - out["parent_span_id"] = str(parent.get("span_id") or "") - return out - - -def fold_llm_requests(spans: list) -> list: - """Each measured LLM call given the log spans for the reply it produced. - - Without this the same call is drawn twice — as `claude_code.llm_request` - under the interaction, and again as `llm_request` under the log's own - `session` subtree — with the second copy carrying the reasoning and output - text and the first carrying the only measured clock. Folding puts the blocks - under the call, which is the shape Harbor itself writes when the exporter - gives it a request id to join on. - - Nothing is invented and nothing is dropped. Every span survives with its own - start, end and tokens; a request span that collapsed into its one block is - that block, carrying what the request knew. The rows move, the clocks do not, - and the producer's `totals` is untouched, as ever. - - Copy-on-write, like `prune`: a document with nothing to fold is returned by - reference. - """ - containers, wrappers = [], [] - _collect_requests(spans, "", containers, wrappers) - if not containers or not wrappers: - return spans - - folded = _match_requests(containers, _request_groups(wrappers)) - if not folded: - return spans - by_id = {str(c.get("span_id") or ""): c for c in containers} - by_container = { - parent_id: [_folded_child(raw, by_id[parent_id]) for raw in group] - for parent_id, group in folded.items() - } - moved = {id(raw) for group in folded.values() for raw in group} - return _fold_tree(spans, by_container, moved)[0] - - -def _fold_tree(spans: list, by_container: dict, moved: set, depth: int = 0) -> tuple: - """(spans, changed) — the tree with the matched request spans relocated. - - Identity, not span id, is what marks a span as moved: ids are opaque strings - from two producers here, and a collision would otherwise delete a span rather - than move it. - """ - out: list = [] - changed = False - for raw in spans: - if not isinstance(raw, dict): - continue - if id(raw) in moved: - changed = True - continue - children = raw.get("children") or [] - if children and depth < MAX_DEPTH: - children, dropped = _fold_tree(children, by_container, moved, depth + 1) - else: - dropped = False - blocks = by_container.get(str(raw.get("span_id") or "")) - if blocks: - children = sorted(children + blocks, key=lambda s: _window(s)[0]) - attributes = dict(raw.get("attributes") or {}) - attributes[_MERGED_FROM] = ", ".join( - str((b.get("attributes") or {}).get(_MERGED_FROM) or b.get("span_id") or "") - for b in blocks - ) - raw = dict(raw, children=children, attributes=attributes) - elif dropped: - raw = dict(raw, children=children) - changed = changed or dropped or bool(blocks) - out.append(raw) - return out, changed - - def prune(spans: list, filt: "Filter | None" = None, depth: int = 0) -> tuple: """(kept, removed) — hidden spans dropped, with their subtrees. @@ -1154,81 +312,6 @@ def prune(spans: list, filt: "Filter | None" = None, depth: int = 0) -> tuple: return kept, removed -def merge_intervals(intervals: list) -> list: - """Overlapping [start, end) runs collapsed into disjoint ones.""" - out: list = [] - for start, end in sorted(intervals): - if out and start <= out[-1][1]: - out[-1] = (out[-1][0], max(out[-1][1], end)) - else: - out.append((start, end)) - return out - - -def partition(by_category: dict, priority: tuple = _PRIORITY) -> dict: - """Split the timeline so every instant is charged to exactly one category. - - Summing durations exceeds the wall clock as soon as spans nest or overlap, - and both happen here: a tool call sits inside the LLM call that asked for it, - and background subagents run alongside the main thread. Each elementary - segment goes to the highest-priority category covering it, which keeps the - categories disjoint by construction and the stacked strip honest. - """ - merged = {cat: merge_intervals(by_category.get(cat) or []) for cat in priority} - starts = {cat: [start for start, _ in ivs] for cat, ivs in merged.items()} - edges = sorted({point for ivs in merged.values() for iv in ivs for point in iv}) - totals = {cat: 0 for cat in priority} - - def covers(cat: str, low: int) -> bool: - ivs = merged[cat] - i = bisect.bisect_right(starts[cat], low) - 1 - return i >= 0 and ivs[i][1] > low - - for low, high in zip(edges, edges[1:]): - for cat in priority: - if covers(cat, low): - totals[cat] += high - low - break - return totals - - -def breakdown(spans: list, wall_ns: int = 0) -> Breakdown: - """Recompute category time, span counts and tokens over *spans*. - - See :class:`Breakdown` for why this is not the producer's arithmetic and must - not be presented as it. Spans with no usable end contribute no time — an - unknown clock is not a zero one — but they are still counted and their tokens - still add up. - """ - by_category: dict = {} - tokens: dict = {} - count = 0 - measured = 0 - for raw in raw_spans_of(spans): - count += 1 - if str(raw.get("timing_quality") or "") == "measured": - measured += 1 - for key, value in (raw.get("tokens") or {}).items(): - if _int_or_none(value) is not None: - tokens[key] = tokens.get(key, 0) + value - category = category_of(raw) - start = _int_or_none(raw.get("start_ns")) - end = _int_or_none(raw.get("end_ns")) - if category and start is not None and end is not None and end > start: - by_category.setdefault(category, []).append((start, end)) - split = partition(by_category) - return Breakdown( - wall_ns=int(wall_ns or 0), - llm_ns=split.get("llm", 0), - tool_ns=split.get("tool", 0), - reasoning_ns=split.get("reasoning", 0), - idle_ns=split.get("idle", 0), - span_count=count, - measured_span_count=measured, - tokens=tokens, - ) - - # Stamped into a saved view as both its producer and the hand that filtered it. FILTER_PRODUCER = "app/nullius/trace.py (filtered view)" @@ -1292,110 +375,6 @@ def filtered_document(data: dict, filt: "Filter | None" = None) -> dict: return out -def _clamp(value: float, low: float = 0.0, high: float = 100.0) -> float: - return max(low, min(high, value)) - - -def place(span: Span, extent: Extent) -> tuple: - """(left_pct, width_pct) on the global axis. - - All arithmetic is Python int until this line, so the nanosecond magnitudes - that overflow a JS double are exact here — no BigInt problem to work around. - """ - left = _clamp((span.start_ns - extent.start_ns) / extent.span_ns * 100) - duration = span.duration_ns or 0 - width = _clamp(duration / extent.span_ns * 100, 0.0, 100.0 - left) - return left, width - - -def is_instant(span: Span) -> bool: - """No usable duration: one known instant, or an explicitly unknown clock.""" - return span.timing_quality == "unknown" or not (span.duration_ns and span.duration_ns > 0) - - -def flatten(roots: list, collapsed=frozenset(), extent: Extent | None = None) -> tuple: - """Depth-first rows, skipping the children of collapsed spans. - - Returns (rows, truncated). Collapse is honoured here so it is testable, but - the template renders every row and lets the browser hide descendants — which - is what makes expanding a deep-linked span a no-round-trip operation. - - *extent* is the window the rows are placed on and their offsets counted - from. A zoomed view passes the subtree's own window here (`extent_of` over - the one span), so every offset it shows is from the zoomed span's start — - the same origin its axis ticks use. - """ - if extent is None: - extent = extent_of(roots) - - rows: list = [] - truncated = 0 - seen: set = set() - - def walk(span, depth): - nonlocal truncated - if span.span_id and span.span_id in seen: - return - seen.add(span.span_id) - if len(rows) >= MAX_ROWS: - # Count what is being dropped, so the page can say so rather than - # silently ending mid-tree. - truncated += 1 + sum(1 for _ in all_spans(span.children)) - return - left, width = place(span, extent) - rows.append( - Row( - span=span, - depth=depth, - has_children=bool(span.children), - offset_ns=span.start_ns - extent.start_ns, - left_pct=left, - width_pct=width, - is_instant=is_instant(span), - ) - ) - if span.children and span.span_id not in collapsed: - for child in span.children: - walk(child, depth + 1) - - for root in roots: - walk(root, 0) - return rows, truncated - - -def ticks_for(extent: Extent, n: int = 5) -> list: - """Axis ticks on a 1/2/5×10^k step, labelled as offsets from the start.""" - span = extent.span_ns - if span <= 1: - return [Tick(pct=0.0, ns=0)] - rough = span / max(n, 1) - magnitude = 10 ** int(math.floor(math.log10(rough))) - step = next( - (m * magnitude for m in (1, 2, 5, 10) if m * magnitude >= rough), - 10 * magnitude, - ) - ticks = [] - value = 0 - while value <= span and len(ticks) <= n * 3: - ticks.append(Tick(pct=value / span * 100, ns=int(value))) - value += step - return ticks - - -def _totals(raw: dict) -> Totals: - if not raw: - return Totals() - return Totals( - wall_ns=_int_or_none(raw.get("wall_ns")), - llm_ns=_int_or_none(raw.get("llm_ns")), - tool_ns=_int_or_none(raw.get("tool_ns")), - reasoning_ns=_int_or_none(raw.get("reasoning_ns")), - idle_ns=_int_or_none(raw.get("idle_ns")), - span_count=_int_or_none(raw.get("span_count")), - measured_span_count=_int_or_none(raw.get("measured_span_count")), - ) - - def parse(data: dict, filt: "Filter | None" = None) -> Trace: """Build a Trace from already-decoded JSON. Pure — what the tests drive. diff --git a/app/nullius/traces/waterfall.py b/app/nullius/traces/waterfall.py new file mode 100644 index 00000000..5256ae2e --- /dev/null +++ b/app/nullius/traces/waterfall.py @@ -0,0 +1,167 @@ +"""A trace laid out as a waterfall: one global axis, one row per span. + +``Extent`` is the window the axis covers, derived from the spans themselves. +``place`` puts a bar on it, ``flatten`` gives the rows depth first, ``ticks_for`` +labels the axis. A bar is positioned against the whole trace, never against its +parent: ``trace`` says why. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +from .spans import all_spans, _int_or_none, is_instant, raw_spans_of, Span + +# An exporter can emit thousands of spans for a trivial task. Every row is +# rendered server-side with its own detail pane, so the page has to be bounded. +MAX_ROWS = 2000 + + +@dataclass(frozen=True) +class Extent: + """The window the axis covers, derived from the spans themselves. + + Never from the host wall clock: spans are stamped inside the container and + ``totals.wall_ns`` on the host, so mixing them puts bars in the wrong place. + """ + + start_ns: int = 0 + end_ns: int = 1 + span_ns: int = 1 # floored at 1 — an all-instant trace would divide by zero + + +@dataclass +class Tick: + pct: float + ns: int # offset from the extent start, not an epoch value + + +@dataclass +class Row: + """One rendered waterfall row: a span placed on the global axis.""" + + span: Span + depth: int = 0 + has_children: bool = False + offset_ns: int = 0 # exact int; only the percentages become floats + left_pct: float = 0.0 + width_pct: float = 0.0 + is_instant: bool = False + + +def extent_of(roots: list) -> Extent: + spans = list(all_spans(roots)) + if not spans: + return Extent() + start = min(s.start_ns for s in spans) + end = max((s.end_ns if s.end_ns is not None else s.start_ns) for s in spans) + # Floored at 1: a trace whose spans are all instants has end == start, and + # every percentage would come out NaN or Infinity. + return Extent(start_ns=start, end_ns=end, span_ns=max(end - start, 1)) + + +def raw_extent(spans: list) -> Extent: + """The axis window, taken from the raw document. + + Called with the *unfiltered* spans on purpose: hiding one must not slide the + remaining bars sideways, or a filter would look like it changed timings it + was only asked to leave out. What it removes shows up as empty axis instead. + Matches `extent_of` span for span, including its treatment of a span with no + usable start (0, like `_span`) or no end (its own start). + """ + starts, ends = [], [] + for raw in raw_spans_of(spans): + start = _int_or_none(raw.get("start_ns")) or 0 + end = _int_or_none(raw.get("end_ns")) + starts.append(start) + ends.append(start if end is None else end) + if not starts: + return Extent() + low, high = min(starts), max(ends) + return Extent(start_ns=low, end_ns=high, span_ns=max(high - low, 1)) + + +def _clamp(value: float, low: float = 0.0, high: float = 100.0) -> float: + return max(low, min(high, value)) + + +def place(span: Span, extent: Extent) -> tuple: + """(left_pct, width_pct) on the global axis. + + All arithmetic is Python int until this line, so the nanosecond magnitudes + that overflow a JS double are exact here — no BigInt problem to work around. + """ + left = _clamp((span.start_ns - extent.start_ns) / extent.span_ns * 100) + duration = span.duration_ns or 0 + width = _clamp(duration / extent.span_ns * 100, 0.0, 100.0 - left) + return left, width + + +def flatten(roots: list, collapsed=frozenset(), extent: Extent | None = None) -> tuple: + """Depth-first rows, skipping the children of collapsed spans. + + Returns (rows, truncated). Collapse is honoured here so it is testable, but + the template renders every row and lets the browser hide descendants — which + is what makes expanding a deep-linked span a no-round-trip operation. + + *extent* is the window the rows are placed on and their offsets counted + from. A zoomed view passes the subtree's own window here (`extent_of` over + the one span), so every offset it shows is from the zoomed span's start — + the same origin its axis ticks use. + """ + if extent is None: + extent = extent_of(roots) + + rows: list = [] + truncated = 0 + seen: set = set() + + def walk(span, depth): + nonlocal truncated + if span.span_id and span.span_id in seen: + return + seen.add(span.span_id) + if len(rows) >= MAX_ROWS: + # Count what is being dropped, so the page can say so rather than + # silently ending mid-tree. + truncated += 1 + sum(1 for _ in all_spans(span.children)) + return + left, width = place(span, extent) + rows.append( + Row( + span=span, + depth=depth, + has_children=bool(span.children), + offset_ns=span.start_ns - extent.start_ns, + left_pct=left, + width_pct=width, + is_instant=is_instant(span), + ) + ) + if span.children and span.span_id not in collapsed: + for child in span.children: + walk(child, depth + 1) + + for root in roots: + walk(root, 0) + return rows, truncated + + +def ticks_for(extent: Extent, n: int = 5) -> list: + """Axis ticks on a 1/2/5×10^k step, labelled as offsets from the start.""" + span = extent.span_ns + if span <= 1: + return [Tick(pct=0.0, ns=0)] + rough = span / max(n, 1) + magnitude = 10 ** int(math.floor(math.log10(rough))) + step = next( + (m * magnitude for m in (1, 2, 5, 10) if m * magnitude >= rough), + 10 * magnitude, + ) + ticks = [] + value = 0 + while value <= span and len(ticks) <= n * 3: + ticks.append(Tick(pct=value / span * 100, ns=int(value))) + value += step + return ticks diff --git a/app/static/style.css b/app/static/style.css index 2ac1c745..80dc91ec 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -682,7 +682,7 @@ button.seg:hover { filter: brightness(1.25); } they hang under, because the two came from different clocks; a per-parent layout would have to clamp that away, and the clamp would hide the exact discrepancy the trace format exists to expose. Percentages come from - nullius/traces/trace.py as --left/--width. */ + nullius/traces/waterfall.py as --left/--width. */ /* One grid, shared by the header and every row, so all tracks are identical by construction and a tick at 50% lands over the middle of every bar. */ diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index a1abfd36..adab13a8 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -40,6 +40,32 @@ "held_term" ] }, + "breakdown": { + "Breakdown": [ + "attributed_ns", + "idle_ns", + "llm_ns", + "measured_span_count", + "reasoning_ns", + "segments", + "span_count", + "tokens", + "tool_ns", + "unaccounted_ns", + "wall_ns" + ], + "Totals": [ + "idle_ns", + "llm_ns", + "measured_span_count", + "reasoning_ns", + "segments", + "span_count", + "tool_ns", + "unaccounted_ns", + "wall_ns" + ] + }, "catalog": { "Benchmark": [ "blocker", @@ -368,47 +394,7 @@ "vocab" ] }, - "trace": { - "Breakdown": [ - "attributed_ns", - "idle_ns", - "llm_ns", - "measured_span_count", - "reasoning_ns", - "segments", - "span_count", - "tokens", - "tool_ns", - "unaccounted_ns", - "wall_ns" - ], - "Extent": [ - "end_ns", - "span_ns", - "start_ns" - ], - "Facet": [ - "count", - "hidden", - "kind", - "name" - ], - "Filter": [ - "active", - "names", - "query", - "span_ids", - "zoom" - ], - "Row": [ - "depth", - "has_children", - "is_instant", - "left_pct", - "offset_ns", - "span", - "width_pct" - ], + "spans": { "Span": [ "attributes", "children", @@ -425,21 +411,21 @@ "start_ns", "timing_quality", "tokens" + ] + }, + "trace": { + "Facet": [ + "count", + "hidden", + "kind", + "name" ], - "Tick": [ - "ns", - "pct" - ], - "Totals": [ - "idle_ns", - "llm_ns", - "measured_span_count", - "reasoning_ns", - "segments", - "span_count", - "tool_ns", - "unaccounted_ns", - "wall_ns" + "Filter": [ + "active", + "names", + "query", + "span_ids", + "zoom" ], "Trace": [ "axis", @@ -509,6 +495,26 @@ "total_reasoning_tokens" ] }, + "waterfall": { + "Extent": [ + "end_ns", + "span_ns", + "start_ns" + ], + "Row": [ + "depth", + "has_children", + "is_instant", + "left_pct", + "offset_ns", + "span", + "width_pct" + ], + "Tick": [ + "ns", + "pct" + ] + }, "workspace": { "Workspace": [ "created", diff --git a/app/tests/field_contract.py b/app/tests/field_contract.py index 210dda8d..a2b118de 100644 --- a/app/tests/field_contract.py +++ b/app/tests/field_contract.py @@ -45,7 +45,8 @@ # Moving a module must not reset the field comparison or conceal removals. PACKAGE_OF = { "parse": "nullius.runs", "classify": "nullius.runs", "artifacts": "nullius.runs", - "trace": "nullius.traces", "trajectory": "nullius.traces", "charts": "nullius.traces", + "trace": "nullius.traces", "spans": "nullius.traces", "breakdown": "nullius.traces", "waterfall": "nullius.traces", + "trajectory": "nullius.traces", "charts": "nullius.traces", "conversation": "nullius.traces", "behavior": "nullius.traces", "comparison": "nullius.compare", "catalog": "nullius.catalogue", "benchmarks": "nullius.runs", diff --git a/app/tests/test_charts.py b/app/tests/test_charts.py index d7de6b72..6ae858ce 100644 --- a/app/tests/test_charts.py +++ b/app/tests/test_charts.py @@ -20,6 +20,7 @@ import nullius from nullius.traces import trace +from nullius.traces.waterfall import MAX_ROWS from nullius.traces import charts from .tracedata import DEGRADED, RICH, doc, raw, span @@ -298,11 +299,11 @@ class TheRenderCapDoesNotLeak(unittest.TestCase): def test_the_charts_see_spans_the_waterfall_stops_drawing(self): # `rows` is capped at MAX_ROWS; `roots` is not. A chart built off the # rows would describe a subset while the panel above says otherwise. - many = [span(f"s{i}", 0, (i % 50 + 1) * MS) for i in range(trace.MAX_ROWS + 25)] + many = [span(f"s{i}", 0, (i % 50 + 1) * MS) for i in range(MAX_ROWS + 25)] tr = trace.parse(doc(*many)) cs = charts.charts_for(tr.roots) - self.assertEqual(len(tr.rows), trace.MAX_ROWS) - self.assertEqual(cs.total, trace.MAX_ROWS + 25) + self.assertEqual(len(tr.rows), MAX_ROWS) + self.assertEqual(cs.total, MAX_ROWS + 25) self.assertEqual(sum(b.count for b in chart(cs, "kind-hist").bars), cs.total) diff --git a/app/tests/test_conversation.py b/app/tests/test_conversation.py index 353ccc51..669835a7 100644 --- a/app/tests/test_conversation.py +++ b/app/tests/test_conversation.py @@ -6,6 +6,8 @@ from collections import Counter from nullius.traces import trace, trajectory +from nullius.traces.spans import Span +from nullius.traces.waterfall import Row from nullius.traces import conversation @@ -112,11 +114,11 @@ def test_missing_empty_unreadable_and_invalid_boundaries(self): class SpanWindows(unittest.TestCase): def setUp(self): - self.span = trace.Span(span_id="block:opaque:0", name="Bash", label="Bash", kind="tool", + self.span = Span(span_id="block:opaque:0", name="Bash", label="Bash", kind="tool", timing_quality="inferred", source="log", start_ns=20, duration_ns=30, content=[("Output", "x" * 40000 + " sk-secret123456789")], attributes=[("original", "z" * 30000)], tokens={"input": 50}) - self.trace = trace.Trace(rows=[trace.Row(self.span, offset_ns=-10)]) + self.trace = trace.Trace(rows=[Row(self.span, offset_ns=-10)]) def test_on_demand_selected_content_is_bounded_and_metadata_is_faithful(self): data = conversation.span_detail(self.trace, "block:opaque:0") diff --git a/app/tests/test_otel.py b/app/tests/test_otel.py index 030b1401..8d7141ad 100644 --- a/app/tests/test_otel.py +++ b/app/tests/test_otel.py @@ -13,7 +13,8 @@ import tempfile import unittest -from nullius.traces import otel, trace +from nullius.traces import otel +from nullius.traces.spans import raw_spans_of @@ -36,7 +37,7 @@ def test_langfuse_types_map_like_openinference_kinds(self): self.span("d", "a", "verify", {"langfuse.observation.type": "evaluator"}), self.span("e", "a", "setup", {"langfuse.observation.type": "span"}), ]) - kinds = {raw["name"]: raw["kind"] for raw in trace.raw_spans_of(doc["spans"])} + kinds = {raw["name"]: raw["kind"] for raw in raw_spans_of(doc["spans"])} self.assertEqual(kinds, {"agent": "session", "llm-call-1": "llm_request", "Bash": "tool", "verify": "evaluator", "setup": "span"}) @@ -152,7 +153,7 @@ def test_a_parent_cycle_is_broken_into_an_orphan_root_not_lost(self): "startTimeUnixNano": "1", "endTimeUnixNano": "2", "attributes": []}, "resource": {}, "scope": {"name": "", "version": ""}} doc = otel.build("t", [rec("a", "b", "a"), rec("b", "a", "b"), rec("c", "", "c")]) - names = sorted(r["name"] for r in trace.raw_spans_of(doc["spans"])) + names = sorted(r["name"] for r in raw_spans_of(doc["spans"])) self.assertEqual(names, ["a", "b", "c"]) self.assertEqual(doc["totals"]["span_count"], 3) self.assertTrue(any("parent cycle" in note for note in doc["import"]["notes"])) diff --git a/app/tests/test_standard_trace.py b/app/tests/test_standard_trace.py index 4776475b..dee02982 100644 --- a/app/tests/test_standard_trace.py +++ b/app/tests/test_standard_trace.py @@ -9,6 +9,7 @@ from nullius.standard.runner import job from nullius.traces import trace +from nullius.traces.spans import raw_spans_of T = 1_800_000_000.0 AGENT = {"key": "codex", "_kind": "agent"} @@ -183,7 +184,7 @@ def test_a_trial_that_kept_none_gets_its_model_calls_and_tools_with_no_duration( json.dump(kept, f) self.assertEqual(job.backfill_trace(trial, write=True), "partial") with open(path) as f: - spans = list(trace.raw_spans_of(json.load(f)["spans"])) + spans = list(raw_spans_of(json.load(f)["spans"])) self.assertEqual(next(s for s in spans if s["kind"] == "llm_request")["duration_ns"], 10**9) self.assertTrue(all("duration_ns" not in s for s in spans if s["kind"] == "tool")) diff --git a/app/tests/test_trace.py b/app/tests/test_trace.py index 2de192af..4d20d5ff 100644 --- a/app/tests/test_trace.py +++ b/app/tests/test_trace.py @@ -18,6 +18,8 @@ import unittest from nullius.traces import trace +from nullius.traces.spans import GROUP_KIND, GROUP_SLACK_NS, mark_groups, MAX_DEPTH, NS_PER_MS +from nullius.traces.waterfall import Extent, flatten, MAX_ROWS, Tick, ticks_for from . import FIXTURES @@ -156,7 +158,7 @@ def test_reported_tool_time_is_not_the_sum_of_tool_spans(self): # here sums to 46.1ms against a true 23.3ms, because the `claude_code.tool` # wrapper contains both of the spans it is being added to. tr = trace.load(RICH) - toolish = [r.span for r in tr.rows if r.span.kind in ("tool", trace.GROUP_KIND)] + toolish = [r.span for r in tr.rows if r.span.kind in ("tool", GROUP_KIND)] self.assertEqual(sum(s.duration_ns for s in toolish), 46_146_687) # Re-kinding the wrapper `group` takes the duplicate out of that sum, and # what is left still is not the reported figure — a consumer that adds up @@ -187,7 +189,7 @@ def test_spans_all_at_one_instant_produce_finite_percentages(self): self.assertTrue(0.0 <= row.width_pct <= 100.0) def test_ticks_survive_a_degenerate_extent(self): - self.assertEqual(trace.ticks_for(trace.Extent()), [trace.Tick(pct=0.0, ns=0)]) + self.assertEqual(ticks_for(Extent()), [Tick(pct=0.0, ns=0)]) class Layout(unittest.TestCase): @@ -215,7 +217,7 @@ def test_multiple_roots_are_all_at_depth_zero(self): def test_collapsing_a_span_drops_its_subtree(self): tr = trace.load(RICH) - rows, _ = trace.flatten(tr.roots, collapsed={TOOL_PARENT}) + rows, _ = flatten(tr.roots, collapsed={TOOL_PARENT}) ids = [r.span.span_id for r in rows] self.assertIn(TOOL_PARENT, ids) self.assertNotIn(TOOL_BLOCKED, ids) @@ -235,14 +237,14 @@ def test_a_parent_cycle_terminates(self): a = span("a") a["children"] = [a] rows = trace.parse(doc(a)).rows - self.assertLessEqual(len(rows), trace.MAX_DEPTH + 1) + self.assertLessEqual(len(rows), MAX_DEPTH + 1) def test_pathologically_deep_nesting_bottoms_out(self): node = span("leaf") - for i in range(trace.MAX_DEPTH + 50): + for i in range(MAX_DEPTH + 50): node = span(f"n{i}", children=[node]) tr = trace.parse(doc(node)) - self.assertEqual(max(r.depth for r in tr.rows), trace.MAX_DEPTH) + self.assertEqual(max(r.depth for r in tr.rows), MAX_DEPTH) class SpansWithoutAnEnd(unittest.TestCase): @@ -297,7 +299,7 @@ def test_merged_spans_are_flagged(self): # Milliseconds, because the slack a group is allowed is measured in them. A # hand-built tree in bare integers would be inside it whatever it contained. -MS = trace.NS_PER_MS +MS = NS_PER_MS def wrapper(self_ns=0, label="Bash", inner_kind="tool"): @@ -345,13 +347,13 @@ def test_the_instrumentation_name_survives_for_the_detail_pane(self): def test_a_wrapper_with_time_of_its_own_is_still_a_tool(self): # It is doing something, whatever it is named. - tr = trace.parse(doc(wrapper(self_ns=trace.GROUP_SLACK_NS + 1))) + tr = trace.parse(doc(wrapper(self_ns=GROUP_SLACK_NS + 1))) self.assertEqual(by_id(tr, "outer").span.kind, "tool") def test_the_producers_own_rounding_does_not_decide_it(self): # Harbor stamps the wrapper to the millisecond and its children to the # nanosecond, so a shortfall of a millisecond or so is the clock, not work. - tr = trace.parse(doc(wrapper(self_ns=trace.GROUP_SLACK_NS))) + tr = trace.parse(doc(wrapper(self_ns=GROUP_SLACK_NS))) self.assertEqual(by_id(tr, "outer").span.kind, "group") def test_a_single_child_of_the_same_extent_is_the_same_bar_twice(self): @@ -451,7 +453,7 @@ def test_a_bracket_around_a_bracket_is_a_group_all_the_way_down(self): def test_a_document_with_nothing_to_normalise_is_passed_through(self): spans = [span("a")] - self.assertIs(trace.mark_groups(spans), spans) + self.assertIs(mark_groups(spans), spans) class DegradedTrace(unittest.TestCase): @@ -584,14 +586,14 @@ class LargeTraces(unittest.TestCase): def test_row_count_is_bounded_and_the_remainder_is_counted(self): # An exporter with an unpruned `other` bucket emitted 1037 spans for a # trivial task. Every row carries a detail pane, so the page is capped. - spans = [span(f"s{i}", start=i, end=i + 1) for i in range(trace.MAX_ROWS + 250)] + spans = [span(f"s{i}", start=i, end=i + 1) for i in range(MAX_ROWS + 250)] tr = trace.parse(doc(*spans)) - self.assertEqual(len(tr.rows), trace.MAX_ROWS) + self.assertEqual(len(tr.rows), MAX_ROWS) self.assertEqual(tr.truncated, 250) def test_truncation_counts_unrendered_descendants(self): deep = span("parent", children=[span("kid1"), span("kid2")]) - spans = [span(f"s{i}", start=i, end=i + 1) for i in range(trace.MAX_ROWS)] + [deep] + spans = [span(f"s{i}", start=i, end=i + 1) for i in range(MAX_ROWS)] + [deep] tr = trace.parse(doc(*spans)) self.assertEqual(tr.truncated, 3) diff --git a/app/tests/test_trace_filter.py b/app/tests/test_trace_filter.py index 29798eb7..b7213def 100644 --- a/app/tests/test_trace_filter.py +++ b/app/tests/test_trace_filter.py @@ -24,6 +24,9 @@ import unittest from nullius.traces import trace +from nullius.traces.breakdown import Breakdown, breakdown, Totals +from nullius.traces.spans import find_span, raw_spans_of +from nullius.traces.waterfall import extent_of from .test_trace import RICH, doc, raw, span @@ -50,7 +53,7 @@ def ids(tr): def raw_ids(spans): - return [str(s.get("span_id")) for s in trace.raw_spans_of(spans)] + return [str(s.get("span_id")) for s in raw_spans_of(spans)] class Filters(unittest.TestCase): @@ -211,7 +214,7 @@ def test_a_tool_that_waits_for_a_human_is_idle_not_tool_time(self): def test_the_blocked_marker_is_read_from_an_attribute_too(self): # Harbor names the span; session_to_trace.py sets an attribute instead. spans = [span("t", 0, 100, kind="tool", attributes={"blocked_on_user": True})] - view = trace.breakdown(spans, wall_ns=100) + view = breakdown(spans, wall_ns=100) self.assertEqual((view.idle_ns, view.tool_ns), (100, 0)) def test_it_disagrees_with_the_producer_by_exactly_the_nested_tool_call(self): @@ -226,7 +229,7 @@ def test_structural_spans_contribute_no_time_of_their_own(self): # A session or subagent span brackets its children; charging it would # claim their work twice. for kind in ("session", "subagent", "output", "user_message", "compaction"): - view = trace.breakdown([span("s", 0, 100, kind=kind)], wall_ns=100) + view = breakdown([span("s", 0, 100, kind=kind)], wall_ns=100) self.assertEqual(view.attributed_ns, 0, kind) def test_a_subagent_running_in_parallel_cannot_exceed_the_wall_clock(self): @@ -235,12 +238,12 @@ def test_a_subagent_running_in_parallel_cannot_exceed_the_wall_clock(self): span("b", 0, 100, kind="llm_request"), span("c", 50, 150, kind="tool"), ] - view = trace.breakdown(spans, wall_ns=150) + view = breakdown(spans, wall_ns=150) self.assertEqual(view.attributed_ns, 150) self.assertEqual((view.llm_ns, view.tool_ns), (50, 100)) def test_a_span_with_no_end_contributes_no_time_but_is_still_counted(self): - view = trace.breakdown([span("a", 1000, None, kind="tool")], wall_ns=5000) + view = breakdown([span("a", 1000, None, kind="tool")], wall_ns=5000) self.assertEqual(view.attributed_ns, 0) self.assertEqual(view.span_count, 1) @@ -322,7 +325,7 @@ def test_shares_are_of_the_wall_clock_so_a_gap_reads_as_short(self): # Categories that do not close must not be rescaled to fill the bar. # Real magnitudes: a residual under a millisecond reads as float noise # from the producer's arithmetic and is clamped away instead. - totals = trace.Totals(wall_ns=1_000_000_000, llm_ns=500_000_000) + totals = Totals(wall_ns=1_000_000_000, llm_ns=500_000_000) segments = {s["key"]: s["pct"] for s in totals.segments} self.assertEqual(segments["llm"], 50.0) self.assertEqual(segments["unaccounted"], 50.0) @@ -332,13 +335,13 @@ def test_a_recomputed_strip_is_a_share_of_the_same_wall_clock(self): self.assertAlmostEqual(sum(s["pct"] for s in segments), 100.0, places=6) def test_with_no_wall_clock_the_segments_own_sum_is_the_denominator(self): - totals = trace.Totals(llm_ns=300_000_000, tool_ns=100_000_000) + totals = Totals(llm_ns=300_000_000, tool_ns=100_000_000) segments = {s["key"]: s["pct"] for s in totals.segments} self.assertEqual(segments, {"llm": 75.0, "tool": 25.0}) def test_nothing_measured_divides_by_nothing(self): - self.assertEqual(trace.Totals().segments, []) - self.assertEqual(trace.Breakdown().segments, []) + self.assertEqual(Totals().segments, []) + self.assertEqual(Breakdown().segments, []) class Saving(unittest.TestCase): @@ -394,7 +397,7 @@ def test_the_content_is_written_unredacted(self): # The file on disk is exactly as sensitive as its source; the app redacts # at render, and a saved view must not be a lossy copy. out = trace.filtered_document(raw(), trace.Filter.of(["output"])) - write = next(s for s in trace.raw_spans_of(out["spans"]) if s["span_id"] == TOOL_WRITE) + write = next(s for s in raw_spans_of(out["spans"]) if s["span_id"] == TOOL_WRITE) self.assertEqual(write["content"]["arguments"]["content"], "Hello, world!") def test_filtering_a_saved_view_keeps_the_first_filters_provenance(self): @@ -424,8 +427,8 @@ class Zooming(unittest.TestCase): def test_the_axis_is_the_subtrees_own_extent(self): full = trace.load(RICH) zoomed = trace.load(RICH, trace.Filter.of(zoom=TOOL_PARENT)) - group = trace.find_span(full.roots, TOOL_PARENT) - self.assertEqual(zoomed.axis, trace.extent_of([group])) + group = find_span(full.roots, TOOL_PARENT) + self.assertEqual(zoomed.axis, extent_of([group])) # 850µs wider than the bracket itself: the Write inside it ends after it. self.assertEqual(zoomed.axis.span_ns, 24131419) # The subtree's extent is the same walk the global axis uses, so a child diff --git a/app/tests/test_trace_fold.py b/app/tests/test_trace_fold.py index 901b6255..79810856 100644 --- a/app/tests/test_trace_fold.py +++ b/app/tests/test_trace_fold.py @@ -35,6 +35,10 @@ import unittest from nullius.traces import trace +from nullius.traces.breakdown import breakdown +from nullius.traces.fold import fold_llm_requests +from nullius.traces.spans import raw_spans_of +from nullius.traces.waterfall import raw_extent from .test_trace import doc, span @@ -121,11 +125,11 @@ def reply(think=True, text=False, tool=True, message="msg-1"): def folded(*records, **kwargs): - return trace.fold_llm_requests(capture(*records, **kwargs)["spans"]) + return fold_llm_requests(capture(*records, **kwargs)["spans"]) def find(spans, span_id): - return next(s for s in trace.raw_spans_of(spans) if s.get("span_id") == span_id) + return next(s for s in raw_spans_of(spans) if s.get("span_id") == span_id) def children_of(spans, span_id): @@ -273,20 +277,20 @@ class TheFoldMovesNoNumber(unittest.TestCase): def setUp(self): self.source = capture(*reply(text=True)) self.before = self.source["spans"] - self.after = trace.fold_llm_requests(self.before) + self.after = fold_llm_requests(self.before) def test_the_axis_is_where_it_was(self): - self.assertEqual(trace.raw_extent(self.after), trace.raw_extent(self.before)) + self.assertEqual(raw_extent(self.after), raw_extent(self.before)) def test_the_breakdown_charges_the_same_time(self): - before, after = trace.breakdown(self.before), trace.breakdown(self.after) + before, after = breakdown(self.before), breakdown(self.after) self.assertEqual( (before.llm_ns, before.tool_ns, before.reasoning_ns, before.idle_ns), (after.llm_ns, after.tool_ns, after.reasoning_ns, after.idle_ns), ) def test_the_breakdown_counts_the_same_tokens(self): - self.assertEqual(trace.breakdown(self.after).tokens, trace.breakdown(self.before).tokens) + self.assertEqual(breakdown(self.after).tokens, breakdown(self.before).tokens) def test_the_producers_totals_are_untouched(self): self.assertEqual(trace.parse(self.source).totals.wall_ns, 8_000) @@ -294,20 +298,20 @@ def test_the_producers_totals_are_untouched(self): def test_every_span_survives_but_the_records_that_became_blocks(self): gone = {RECORD_THINK, RECORD_TEXT} self.assertEqual( - {str(s.get("span_id")) for s in trace.raw_spans_of(self.after)}, - {str(s.get("span_id")) for s in trace.raw_spans_of(self.before)} - gone, + {str(s.get("span_id")) for s in raw_spans_of(self.after)}, + {str(s.get("span_id")) for s in raw_spans_of(self.before)} - gone, ) def test_the_source_document_is_not_mutated(self): - trace.fold_llm_requests(self.before) + fold_llm_requests(self.before) self.assertEqual(children_of(self.before, "session:s"), [RECORD_THINK, RECORD_TOOL, RECORD_TEXT]) def test_nothing_to_fold_is_passed_back_by_reference(self): spans = doc(call())["spans"] - self.assertIs(trace.fold_llm_requests(spans), spans) + self.assertIs(fold_llm_requests(spans), spans) def test_folding_twice_changes_nothing(self): - self.assertEqual(trace.fold_llm_requests(self.after), self.after) + self.assertEqual(fold_llm_requests(self.after), self.after) class SavingSeesTheSameTree(unittest.TestCase): @@ -315,7 +319,7 @@ class SavingSeesTheSameTree(unittest.TestCase): def test_hiding_a_call_takes_the_blocks_it_adopted(self): out = trace.filtered_document(capture(*reply()), trace.Filter.of(span_ids=[CALL])) - self.assertEqual([str(s.get("span_id")) for s in trace.raw_spans_of(out["spans"])], + self.assertEqual([str(s.get("span_id")) for s in raw_spans_of(out["spans"])], ["interaction", "session:s"]) self.assertEqual(out["filtered"]["spans_removed"], 3) @@ -324,7 +328,7 @@ def test_what_is_left_matches_what_the_page_shows(self): filt = trace.Filter.of(["reasoning"]) out = trace.filtered_document(source, filt) self.assertEqual( - [str(s.get("span_id")) for s in trace.raw_spans_of(out["spans"])], + [str(s.get("span_id")) for s in raw_spans_of(out["spans"])], [r.span.span_id for r in trace.parse(source, filt).rows], ) diff --git a/app/ui_tests/test_every_route.py b/app/ui_tests/test_every_route.py index f2b3441c..dd33ce39 100644 --- a/app/ui_tests/test_every_route.py +++ b/app/ui_tests/test_every_route.py @@ -32,6 +32,7 @@ from nullius import workspace from nullius.catalogue import catalog, harbor_entry from nullius.traces import trace as trace_mod +from nullius.traces.spans import all_spans try: # a repository's refs listed by `git ls-remote`, where that has landed from nullius import gitrefs @@ -118,7 +119,7 @@ def a_span_id(job) -> str: if not trial.has_trace: continue loaded = trace_mod.load(trial.trace_path) - for span in trace_mod.all_spans(loaded.roots): + for span in all_spans(loaded.roots): if span.span_id: return span.span_id return "" From 92c0d89c813da7f37e4b4c3595f95f456344bd90 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 16 Nov 2026 17:21:30 +0100 Subject: [PATCH 04/14] refactor(web): share the local-client guard and the run start Four small things that were written more than once or sat in the wrong file. The loopback guard lived in the settings page's module and five other route modules reached in for it; the builder kept a wrapper named shared_local_client() to do so. It is shared._local_client() now, beside the form-token guard. Four places checked a plan and started it: the builder's Run, the standard's run over several machines, the Agents page's check and the Benchmarks page's proof. execute.begin() does it once, every plan checked before any starts. The two page routes did not ask whether a run of that name was already going; they do now, as the builder did. test_charts.py held NoFlask, the rule that the backend imports no Flask. It is tests/test_layering.py, and AGENTS.md names it there. test_trace.py carried its own copies of the span and document builders that tests/tracedata.py already provides. --- AGENTS.md | 2 +- app/tests/test_charts.py | 18 ------------- app/tests/test_layering.py | 25 ++++++++++++++++++ app/tests/test_trace.py | 34 +----------------------- app/web/agents.py | 9 +++---- app/web/builder.py | 17 +++++------- app/web/catalogue.py | 16 +++++------- app/web/execute.py | 53 ++++++++++++++++++++------------------ app/web/judge.py | 3 +-- app/web/settings.py | 19 +++++--------- app/web/shared.py | 7 +++++ 11 files changed, 85 insertions(+), 118 deletions(-) create mode 100644 app/tests/test_layering.py diff --git a/AGENTS.md b/AGENTS.md index c8fd7245..66708716 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -143,7 +143,7 @@ and migration, and `docs/settings/README.md` for paths and precedence. Three dependency rules. Each is load-bearing and each has a test. - **`app/nullius/` imports no Flask.** The backend is exercisable from a bare - shell or a notebook. `test_charts.NoFlask` checks every module in the + shell or a notebook. `test_layering.NoFlask` checks every module in the package, not one file. If a test in `app/tests` needs Flask, the layering has broken, not the test. - **One name, one implementation per interpreter.** diff --git a/app/tests/test_charts.py b/app/tests/test_charts.py index 6ae858ce..fa6a31a4 100644 --- a/app/tests/test_charts.py +++ b/app/tests/test_charts.py @@ -16,9 +16,6 @@ import unittest from dataclasses import replace -import pathlib - -import nullius from nullius.traces import trace from nullius.traces.waterfall import MAX_ROWS from nullius.traces import charts @@ -524,21 +521,6 @@ def test_clearing_one_chart_leaves_the_others_switched_off(self): self.assertEqual(cf.cleared().off, ()) -class NoFlask(unittest.TestCase): - def test_no_backend_module_imports_the_web_stack(self): - # Check the entire backend stays Flask-free so it works without the web stack. - backend = pathlib.Path(nullius.__file__).parent - offenders = {} - modules = [m for m in sorted(backend.rglob("*.py")) if "__pycache__" not in m.parts] - self.assertGreater(len(modules), 40) - for module in modules: - bad = [ln for ln in module.read_text(encoding="utf-8").splitlines() - if ln.startswith(("import ", "from ")) and "flask" in ln.lower()] - if bad: - offenders[str(module.relative_to(backend))] = bad - self.assertEqual(offenders, {}) - - class Wrappers(unittest.TestCase): """A span that only brackets others is not a call: left out, and counted.""" diff --git a/app/tests/test_layering.py b/app/tests/test_layering.py new file mode 100644 index 00000000..2463a9ba --- /dev/null +++ b/app/tests/test_layering.py @@ -0,0 +1,25 @@ +"""The backend imports no Flask: it is exercisable from a bare shell or a notebook +(AGENTS.md, Core Architecture).""" +import pathlib +import unittest + +import nullius + + +class NoFlask(unittest.TestCase): + def test_no_backend_module_imports_the_web_stack(self): + # Check the entire backend stays Flask-free so it works without the web stack. + backend = pathlib.Path(nullius.__file__).parent + offenders = {} + modules = [m for m in sorted(backend.rglob("*.py")) if "__pycache__" not in m.parts] + self.assertGreater(len(modules), 40) + for module in modules: + bad = [ln for ln in module.read_text(encoding="utf-8").splitlines() + if ln.startswith(("import ", "from ")) and "flask" in ln.lower()] + if bad: + offenders[str(module.relative_to(backend))] = bad + self.assertEqual(offenders, {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_trace.py b/app/tests/test_trace.py index 4d20d5ff..63dcac88 100644 --- a/app/tests/test_trace.py +++ b/app/tests/test_trace.py @@ -22,9 +22,8 @@ from nullius.traces.waterfall import Extent, flatten, MAX_ROWS, Tick, ticks_for from . import FIXTURES +from .tracedata import DEGRADED, RICH, doc, raw, span -RICH = str(FIXTURES / "trace_rich.json") -DEGRADED = str(FIXTURES / "trace_degraded.json") BAD = str(FIXTURES / "trace_bad.json") # Ids from the real capture. `block:...:0` is a synthetic log-derived id and is @@ -39,37 +38,6 @@ OUTPUT = "block:28bda920-a4fa-4918-9e96-4036d44013fe:0" -def raw(path=RICH): - with open(path, encoding="utf-8") as fh: - return json.load(fh) - - -def span(sid, start=1_000, end=2_000, **fields): - """A minimal span. Only what the format requires, so tests add what they mean.""" - out = { - "span_id": sid, - "trace_id": "t", - "name": sid, - "kind": "tool", - "start_ns": start, - "timing_quality": "measured", - "source": "otel", - "attributes": {}, - "children": [], - } - if end is not None: - out["end_ns"] = end - out["duration_ns"] = end - start - out.update(fields) - return out - - -def doc(*spans, **top): - out = {"schema_version": "harbor-trace-v1", "spans": list(spans)} - out.update(top) - return out - - def by_id(tr, span_id): return next(r for r in tr.rows if r.span.span_id == span_id) diff --git a/app/web/agents.py b/app/web/agents.py index 1d130acf..5d4eaca0 100644 --- a/app/web/agents.py +++ b/app/web/agents.py @@ -35,7 +35,6 @@ from .core import app from . import shared from . import execute -from . import settings as settings_web def _install_words(o: dict) -> list: @@ -106,7 +105,7 @@ def _entry(kind: str, key: str): return render_template("agents/entry.html", kind=kind, e=e, versions=versions if len(mine) > 1 else [], restore_bundle=storage.can_restore(definitions.KINDS[kind]["dir"], key, definitions.CATALOGUE), title=definitions.title(e["d"]), providers=[(p, providers.label(p)) for p in have], - local=settings_web._local_client(), csrf=shared._csrf_token()) + local=shared._local_client(), csrf=shared._csrf_token()) @app.route("/agents") @@ -135,7 +134,7 @@ def _check(kind: str, key: str): """Start the conformance kits of one agent or capability, here, as a run; then its first kit's job page, which follows the run.""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403, description="Checks are started from a browser on the application host only.") version = request.form.get("version", "") back = url_for("agent_page" if kind == "agent" else "feature_page", key=key, **({"v": version} if version else {})) @@ -154,12 +153,10 @@ def _check(kind: str, key: str): plan = execution.Plan(name=f"check-{word}-{time.strftime('%m%d-%H%M%S')}", script=got["script"], runner=standard_recipe.HARNESS, docker=backend == "container", **execute.credentials_for(provider, endpoint), model=request.form.get("model", "").strip(), jobs=got["jobs"], parts=[{"id": word, "label": got["label"] + "'s kits", "script": got["script"]}]) - problem = plan.check() or (execution.name_taken(plan.name) if os.path.exists(os.path.join(execution.runs_root(), plan.name)) else None) + _, problem, _ = execute.begin([plan]) if problem: flash(problem, "error") return redirect(back) - ex = execution.start(plan) - shared.adopt_runs([ex]) n = len(got["jobs"]) flash(f"Checking {got['label']}'s ports: " + (f"{n} kits, one after the other." if n > 1 else "its one kit."), "ok") return redirect(url_for("job", job_id=got["jobs"][0]["name"])) diff --git a/app/web/builder.py b/app/web/builder.py index 00d9e19a..ca59f2ae 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -57,7 +57,7 @@ def new_run(): for b in definitions.load("benchmark", every=True)[0] if b.get("host")} data["standardHere"] = {"docker": execute.docker_problem(), "licences": _licence_states(), "host": host} data["csrf"] = shared._csrf_token() - data["local"] = shared_local_client() + data["local"] = shared._local_client() # ?run=: the recipe a run of this application was started from, # opened as it was. ?like=, the job page's "New run like # this": that recipe when the run kept one, else what the job recorded - @@ -107,7 +107,7 @@ def new_run_prerequisites(): again*, and Run waits for ``ready``; the run asks again as it starts. A host is asked over ssh, so this is never asked on a page load.""" shared._require_csrf() - if not shared_local_client(): + if not shared._local_client(): abort(403, description="Machines are checked from a browser on the application host only.") body = request.get_json(silent=True) or {} recipe = body.get("recipe") if isinstance(body.get("recipe"), dict) else {} @@ -183,7 +183,7 @@ def new_run_harbor_refs(): """A repository's branches and tags, each at its commit, for a Harbor pinned from a repository - a private fork included: git ls-remote with this machine's own credentials, for a browser on this machine only.""" - if not shared_local_client(): + if not shared._local_client(): abort(403, description="Repositories are listed for a browser on the application host only.") url = gitrefs.url_of(request.args.get("repo", "")) if not url: @@ -204,7 +204,7 @@ def new_run_harbor_agents(): repository, installs it in a throwaway environment and asks it, once.""" if request.method == "POST": shared._require_csrf() - if not shared_local_client(): + if not shared._local_client(): abort(403, description="A Harbor is built from a browser on the application host only.") raw = (request.get_json(silent=True) or {}).get("harbor") else: @@ -236,15 +236,10 @@ def _kept_recipe(job_id: str) -> bool: return bool(ex and ex.plan.recipe) -def shared_local_client() -> bool: - from . import settings - return settings._local_client() - - def _host_target(): """The benchmark and its requirements a host check or install is about, and where: 'local' or a host of Settings.""" shared._require_csrf() - if not shared_local_client(): + if not shared._local_client(): abort(403, description="Machines are checked and set up from a browser on the application host only.") b = definitions.get("benchmark", request.form.get("benchmark", "")) if b is None: @@ -401,7 +396,7 @@ def new_run_registry(): def new_run_models(): """Return the selected provider's catalogue, keeping its key on this machine.""" shared._require_csrf() - if not shared_local_client(): + if not shared._local_client(): abort(403) body = request.get_json(silent=True) provider = body.get("provider") if isinstance(body, dict) else None diff --git a/app/web/catalogue.py b/app/web/catalogue.py index 57911313..1f80b5c8 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -49,14 +49,14 @@ def benchmark_page(key): editable=entry is not None and not harbor_entry.not_editable(entry), std=std, std_jobs=jobs, deletable=os.path.isfile(os.path.join(paths.catalogue_dir(), catalog.BENCHMARKS, key, catalog.ENTRY)), restore_bundle=storage.can_restore("benchmarks", key, catalog.ROOT), - local=settings_web._local_client(), + local=shared._local_client(), providers=[(p, providers.label(p)) for p in providers.available(os.environ)]) @app.route("/catalogue///use-bundled", methods=["POST"]) def catalogue_use_bundled(group, key): shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403, description="Catalogue entries are changed from a browser on the application host only.") endpoints = {"benchmarks": "benchmark_page", "agents": "agent_page", "capabilities": "feature_page"} if group not in endpoints: @@ -78,7 +78,7 @@ def benchmark_prove(key): controls call no model, so an unjudged benchmark's run is handed no key at all (``execution.Plan.keyless``).""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403, description="Proofs are started from a browser on the application host only.") back = url_for("benchmark_page", key=key) + "#standard" limit = request.form.get("limit", "").strip() @@ -93,12 +93,10 @@ def benchmark_prove(key): plan = execution.Plan(name=f"prove-{key}-{time.strftime('%m%d-%H%M%S')}", script=got["script"], runner=standard_recipe.HARNESS, **execute.credentials_for(provider, endpoint), keyless=got["keyless"], jobs=got["jobs"], parts=[{"id": key, "label": got["label"] + "'s proofs", "script": got["script"]}]) - problem = plan.check() or (execution.name_taken(plan.name) if os.path.exists(os.path.join(execution.runs_root(), plan.name)) else None) + _, problem, _ = execute.begin([plan]) if problem: flash(problem, "error") return redirect(back) - ex = execution.start(plan) - shared.adopt_runs([ex]) flash(f"Proving {got['label']}: its units and the leak check, then " + (f"{len(got['jobs'])} control runs." if got["jobs"] else "no control: it declares none."), "ok") return redirect(url_for("job", job_id=got["jobs"][0]["name"]) if got["jobs"] else back) @@ -115,7 +113,7 @@ def benchmark_licence(key): store and out of the file - on this click, never by itself. Nothing is ever sent back of a value.""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403, description="Credentials are set from a browser on the application host only.") back = settings_web._settings_return() + "#access-" + key name, action = request.form.get("name", ""), request.form.get("action", "set") @@ -168,7 +166,7 @@ def _guard(): """Every write here: form token, and a browser on this machine - adding a benchmark writes into the user's catalogue.""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403, description="Benchmarks are added from a browser on the application host only.") @@ -233,7 +231,7 @@ def _form(values, errors=(), status=200, editing=None): cat = shared._catalog_cached() return render_template("catalogue/new.html", cat=cat, values=values, errors=list(errors), editing=editing, routable=_routable(), origins=catalog.ORIGINS, catalogue_dir=paths.catalogue_dir(), - writable=settings_web._local_client(), csrf=shared._csrf_token()), status + writable=shared._local_client(), csrf=shared._csrf_token()), status def _back(values, errors, logo, editing=None): diff --git a/app/web/execute.py b/app/web/execute.py index 5dfda462..5a19eb39 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -12,7 +12,6 @@ from .core import app from . import shared -from . import settings as settings_web @app.route("/run", methods=["POST"]) @@ -22,7 +21,7 @@ def run_start(): as every mutation: form token, same origin, and a loopback client - running is writing to a machine.""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403, description="Runs are started from a browser on the application host only.") body = request.get_json(silent=True) or {} recipe = body.get("recipe") if isinstance(body.get("recipe"), dict) else {} @@ -134,16 +133,9 @@ def _start_standard(recipe: dict): return jsonify(ok=False, error=problem), 400 if len(plans) == 1: return _start(plans[0]) - for plan in plans: - problem = plan.check() - if problem: - return jsonify(ok=False, error=problem), 400 - if any(e.plan.name == plan.name for e in execution.active()): - return jsonify(ok=False, error=f"{plan.name} is running already"), 409 - if os.path.exists(os.path.join(execution.runs_root(), plan.name)): - return jsonify(ok=False, error=execution.name_taken(plan.name)), 409 - started = [execution.start(plan) for plan in plans] - shared.adopt_runs(started) + started, problem, status = begin(plans) + 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], **started[0].summary()) @@ -165,20 +157,31 @@ def docker_problem(): return prerequisites.docker_here() -def _start(plan: execution.Plan): - problem = plan.check() - if problem: - return jsonify(ok=False, error=problem), 400 - if any(e.plan.name == plan.name for e in execution.active()): - return jsonify(ok=False, error=f"{plan.name} is running already"), 409 - if os.path.exists(os.path.join(execution.runs_root(), plan.name)): - return jsonify(ok=False, error=execution.name_taken(plan.name)), 409 - ex = execution.start(plan) +def begin(plans: list) -> tuple: + """Start ``plans``, every one checked before any starts: (the runs, "", 200), + or ([], why not, the status a JSON caller answers with) and nothing started. + Every route that starts a run comes through here.""" + for plan in plans: + problem = plan.check() + if problem: + return [], problem, 400 + if any(e.plan.name == plan.name for e in execution.active()): + return [], f"{plan.name} is running already", 409 + if os.path.exists(os.path.join(execution.runs_root(), plan.name)): + return [], execution.name_taken(plan.name), 409 + started = [execution.start(plan) for plan in plans] # The job lands (or is mirrored) under runs//jobs: the workspace # reads it from now on. The Runs page, by launch, shows it from the first # second: its runs queued, preparing, then running, each opening its job. - shared.adopt_runs([ex]) - return jsonify(ok=True, open=url_for("index", view="launch"), **ex.summary()) + shared.adopt_runs(started) + return started, "", 200 + + +def _start(plan: execution.Plan): + started, problem, status = begin([plan]) + if problem: + return jsonify(ok=False, error=problem), status + return jsonify(ok=True, open=url_for("index", view="launch"), **started[0].summary()) @app.route("/run/") @@ -195,7 +198,7 @@ def run_status(run_id): def run_continue(run_id): """The answer to a pause: go on with the next agent.""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403) ex = execution.EXECUTIONS.get(run_id) if ex is None: @@ -207,7 +210,7 @@ def run_continue(run_id): @app.route("/run//stop", methods=["POST"]) def run_stop(run_id): shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403) ex = execution.EXECUTIONS.get(run_id) if ex is None: diff --git a/app/web/judge.py b/app/web/judge.py index b81488ce..ae44b4ca 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -13,7 +13,6 @@ from .core import app from . import shared -from . import settings as settings_web from . import traces def key(lane: str = "system-one") -> client.Judge: @@ -250,7 +249,7 @@ def judge_trial(job, trial, api_key: str, post=None) -> dict: def _guard(): shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403, description="Judging is asked from a browser on the application host only: it is a paid call.") if ws_dir() is None: abort(400, description="No workspace is open; judgements live in the workspace.") diff --git a/app/web/settings.py b/app/web/settings.py index e3dcb76c..a7848917 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -14,13 +14,6 @@ from . import shared -def _local_client() -> bool: - """Only a browser on this machine may write settings: the request comes - from a loopback address and nothing says it was forwarded.""" - forwarded = any(h in request.headers for h in ("X-Forwarded-For", "X-Real-Ip", "Forwarded")) - return request.remote_addr in ("127.0.0.1", "::1") and not forwarded - - @app.route("/settings") def settings_page(): """Every variable the application reads, its state and where it comes @@ -42,7 +35,7 @@ def settings_page(): if needs: access.append({"key": benchmark.key, "title": benchmark.title, "needs": list(needs.values())}) # A written value that goes unseen is said rather than left silent: a key no setting reads. - return render_template("settings/settings.html", embedded=request.args.get("embedded") == "1", groups=groups, benchmark_access=access, csrf=shared._csrf_token(), writable=_local_client(), + return render_template("settings/settings.html", embedded=request.args.get("embedded") == "1", groups=groups, benchmark_access=access, csrf=shared._csrf_token(), writable=shared._local_client(), env_file=shared.ENV_FILE, storage_paths=[("Settings", shared.ENV_FILE), ("User catalogue", paths.catalogue_dir()), ("Workspaces", paths.workspaces_dir()), ("Runs", paths.runs_dir()), @@ -153,7 +146,7 @@ def settings_host_test(): comes back rendered (``info``). Same guards as Save. The entry need not be saved yet; ``local`` is this machine.""" shared._require_csrf() - if not _local_client(): + if not shared._local_client(): abort(403, description="Hosts are tested from a browser on the application host only.") entry = request.form.get("entry", "") if entry == constraints.LOCAL: @@ -199,7 +192,7 @@ def settings_host_key(): 0600 until Save removes its host; the entry that names it comes back. Same guards as Save.""" shared._require_csrf() - if not _local_client(): + if not shared._local_client(): abort(403, description="Hosts are added from a browser on the application host only.") upload = request.files.get("key") try: @@ -220,7 +213,7 @@ def settings_host_enrol(): authorized_keys over ssh, and the entry that comes back names that key. The password is neither stored nor logged. Same guards as Save.""" shared._require_csrf() - if not _local_client(): + if not shared._local_client(): abort(403, description="Hosts are added from a browser on the application host only.") try: user, host, port = _host_form() @@ -293,7 +286,7 @@ def settings_huggingface(): def _sandbox_guard(what): shared._require_csrf() - if not _local_client(): + if not shared._local_client(): abort(403, description=f"{what} from a browser on the application host only.") @@ -411,7 +404,7 @@ def settings_save(): the variable from the file. A variable the process environment also holds is written to the file for the next start, and the message says so.""" shared._require_csrf() - if not _local_client(): + if not shared._local_client(): abort(403, description="Settings are written from a browser on the application host only.") current = {s["name"]: s for s in settings.states(shared.ENV_FILE)} if "host_from" in request.form: diff --git a/app/web/shared.py b/app/web/shared.py index 3d72ffd2..b305f4e7 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -507,6 +507,13 @@ def get_headers(self, environ=None, scope=None): return [*super().get_headers(environ, scope), ("X-Nullius-Reason", "stale-form-token")] +def _local_client() -> bool: + """Only a browser on this machine may write settings or start a run: the request comes + from a loopback address and nothing says it was forwarded.""" + forwarded = any(h in request.headers for h in ("X-Forwarded-For", "X-Real-Ip", "Forwarded")) + return request.remote_addr in ("127.0.0.1", "::1") and not forwarded + + def _require_csrf(): """The one guard every mutation of the environments takes: the session's token, sent back by the form, and a same-origin request.""" From e3309566b3186b11b6414e7c262f26f56fea073e Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 16 Nov 2026 21:51:47 +0100 Subject: [PATCH 05/14] test: hold both writers inside the write again The cache test held its two writers with their temporary file open by a gate in workspace._now, which the write called from inside. Since the cache is written through ondisk.write_whole, the stamp is taken before the write, so the gate held them before either had opened anything. The test still passed, but with one shared temporary name put back it failed 38 or 39 runs in 40 where it had failed all 40. The gate is on the rename now, in this test and in ondisk's own test of several writers. Both fail every run on a shared name. --- app/tests/test_ondisk.py | 12 ++++++++---- app/tests/test_workspace.py | 13 +++++++------ 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index 26d8b283..a18cec68 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -56,15 +56,19 @@ def test_a_write_that_fails_leaves_the_file_as_it_was_and_nothing_beside_it(self def test_writers_of_one_file_at_once_each_finish_and_one_of_them_wins(self): texts = [str(i) * 4096 for i in range(16)] - failed = [] + gate, rename, failed = threading.Barrier(len(texts), timeout=5), os.replace, [] + def held_rename(src, dst): + gate.wait() # every writer has written its own file, none has renamed + return rename(src, dst) def write(text): try: ondisk.write_whole(self.path, text) except Exception as e: # noqa: BLE001 - the failure under test failed.append(e) - threads = [threading.Thread(target=write, args=(t,)) for t in texts] - for t in threads: t.start() - for t in threads: t.join(10) + with mock.patch.object(os, "replace", held_rename): + threads = [threading.Thread(target=write, args=(t,)) for t in texts] + for t in threads: t.start() + for t in threads: t.join(10) self.assertEqual(failed, []) with open(self.path) as f: self.assertIn(f.read(), texts) diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index 913452c4..75770dbc 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -216,20 +216,21 @@ def test_two_requests_writing_the_same_cache_at_once_both_return(self): changing, and both wrote the cache through one shared `.json.tmp`: the first rename took the file away and the second raised FileNotFoundError, a 500 on the page. Both writers are held with - their temp file open until the other has opened its own, then released: + their temp file written until the other has written its own, then released: each must finish, and the cache must be whole.""" gate = threading.Barrier(2, timeout=5) - stamp = workspace._now - def held_now(): - gate.wait() # both are about to write: neither has renamed yet - return stamp() + cache, rename = workspace._cache_file(self.ws, self.job_dir), os.replace + def held_rename(src, dst): + if dst == cache: # the cache alone: the index is written after it, by one or both + gate.wait() # both have written their temp file, neither has renamed yet + return rename(src, dst) results, errors = [], [] def load(): try: results.append(workspace.load_job(self.ws, self.job_dir)) except Exception as e: # noqa: BLE001 - the failure under test errors.append(e) - with patch.object(workspace, "_now", held_now): + with patch.object(os, "replace", held_rename): threads = [threading.Thread(target=load) for _ in range(2)] for t in threads: t.start() for t in threads: t.join(10) From 4cabbae58f9ca358256125cae04744173e97b70c Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 16 Nov 2026 21:51:47 +0100 Subject: [PATCH 06/14] test(web): pin the two refusals of the run start No route test failed when the start stopped looking for a run of the same name still going, or for a run folder of that name: not while each route had its own copy of those checks, and not since they are one function, execute.begin. One test now asks both through /run, and that of several plans none starts unless every one may. --- app/ui_tests/test_run_routes.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index d608816f..e8664fdb 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -15,6 +15,7 @@ import unittest from contextlib import ExitStack from pathlib import Path +from types import SimpleNamespace from unittest.mock import patch from nullius import execution, workspace @@ -157,6 +158,23 @@ def test_what_is_refused(self): self.assertEqual(self.post({"name": "x", "script": "true"}, environ_base={"REMOTE_ADDR": "10.0.0.7"}).status_code, 403) # not loopback self.assertFalse((self.tmp / "runs" / "x").exists()) + def test_a_name_still_running_or_used_before_is_refused_and_nothing_starts(self): + """What every route that starts a run asks first (``execute.begin``): no run of + that name still going, no run folder of that name. Of several plans none + starts unless every one may.""" + body = {"name": "twice", "script": "true", "where": "local"} + going = SimpleNamespace(plan=SimpleNamespace(name="twice"), state="running") + with patch.dict(execution.EXECUTIONS, {"going": going}): + r = self.post(body) + self.assertEqual((r.status_code, r.json["error"]), (409, "twice is running already")) + (self.tmp / "runs" / "twice").mkdir(parents=True) + r = self.post(body) + self.assertEqual((r.status_code, r.json["error"]), (409, execution.name_taken("twice"))) + plans = [execution.Plan(name="fresh", script="true"), execution.Plan(name="twice", script="true")] + self.assertEqual(web.execute.begin(plans), ([], execution.name_taken("twice"), 409)) + self.assertEqual((dict(execution.EXECUTIONS), self.adopted), ({}, [])) # nothing started, the free name included + self.assertFalse((self.tmp / "runs" / "fresh").exists()) + def test_the_run_opens_runs_by_launch_and_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"], "/runs?view=launch") From 0c9a906873837f339768ee746dcfc1e50719129b Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Sat, 21 Nov 2026 15:26:49 +0100 Subject: [PATCH 07/14] refactor(standard): place the five modules main added main added five modules to the top of standard/ after this branch sorted it into folders. Each goes where its code says, and no two folders come to import each other: - boat is a second backend, each unit's agent in a Boat VM, beside the container one. The folder that held the container backend and its doors was named for Docker alone: it is backends/ now. - boat_units sends this runner's snapshot to a Boat VM per unit and merges the shards that come back: with shard, merge and payload in runner/. Beside boat, backends/ and runner/ would import each other. - retries says which failed attempt is tried again: with pace in runner/. - computer_port and computer_pipe are the computer port's MCP server and the session's pipe to it: with acp and jsonl in protocols/. The kit's pipe.py and three tests name the pipe's file by its place, and follow. References follow in 71 files, written as the first move writes them. --- .github/workflows/docker-tests.yml | 2 +- AGENTS.md | 8 ++++---- .../catalogue/benchmarks/humaneval/driver.py | 2 +- .../catalogue/benchmarks/osworld1/driver.py | 2 +- .../catalogue/benchmarks/osworld1/runner.py | 4 ++-- .../catalogue/benchmarks/osworld1/standard.json | 2 +- .../benchmarks/tau3-bench/mcp_server.py | 2 +- app/nullius/execution.py | 4 ++-- app/nullius/hosts.py | 2 +- app/nullius/onboarding.py | 2 +- app/nullius/prerequisites.py | 2 +- app/nullius/sandbox.py | 2 +- app/nullius/standard/__init__.py | 9 +++++---- app/nullius/standard/backends/__init__.py | 16 ++++++++++++++++ app/nullius/standard/{ => backends}/boat.py | 0 .../{containers => backends}/container.py | 2 +- .../standard/{containers => backends}/egress.py | 0 .../standard/{containers => backends}/forward.py | 0 .../{containers => backends}/mcp_bridge.py | 0 .../{containers => backends}/mcp_machine.py | 0 .../{containers => backends}/setup_container.py | 4 ++-- .../{containers => backends}/web_services.py | 0 app/nullius/standard/cli.py | 10 +++++----- app/nullius/standard/containers/__init__.py | 14 -------------- .../standard/kits/agent-computer-v1/desktop.py | 2 +- .../standard/kits/agent-computer-v1/driver.py | 4 ++-- .../standard/kits/agent-computer-v1/pipe.py | 6 +++--- .../standard/kits/agent-search-v1/driver.py | 2 +- .../standard/kits/agent-tools-v1/driver.py | 2 +- .../standard/kits/agent-workspace-v1/driver.py | 2 +- app/nullius/standard/pages/recipe.py | 4 ++-- app/nullius/standard/proofs/conform.py | 3 +-- app/nullius/standard/proofs/prove.py | 3 +-- app/nullius/standard/protocols/__init__.py | 7 +++++-- .../standard/{ => protocols}/computer_pipe.py | 0 .../standard/{ => protocols}/computer_port.py | 0 app/nullius/standard/runner/__init__.py | 7 +++++-- app/nullius/standard/{ => runner}/boat_units.py | 2 +- app/nullius/standard/{ => runner}/retries.py | 0 app/nullius/standard/runner/run.py | 9 ++++----- app/static/builder/command-builder.js | 2 +- app/tests/docker_tier.py | 2 +- .../fixtures/standard/computer_merge_driver.py | 3 +-- app/tests/test_computer_kit.py | 2 +- app/tests/test_computer_kit_driver.py | 6 +++--- app/tests/test_computer_merge.py | 3 ++- app/tests/test_constraints.py | 4 ++-- app/tests/test_kit_check_isolation.py | 2 +- app/tests/test_network_requirements.py | 2 +- app/tests/test_onboarding.py | 2 +- app/tests/test_osworld1_agent_side.py | 2 +- app/tests/test_osworld1_entry_parts.py | 4 ++-- app/tests/test_osworld2_muse.py | 2 +- app/tests/test_prerequisites.py | 2 +- app/tests/test_sandbox.py | 2 +- app/tests/test_search_kit.py | 4 ++-- app/tests/test_settings.py | 4 ++-- app/tests/test_setup_container.py | 6 +++--- app/tests/test_standard_boat.py | 4 ++-- app/tests/test_standard_boat_units.py | 6 +++--- app/tests/test_standard_check_safety.py | 2 +- app/tests/test_standard_computer_pipe.py | 2 +- app/tests/test_standard_computer_port.py | 8 ++++---- app/tests/test_standard_conform.py | 6 +++--- app/tests/test_standard_container.py | 2 +- app/tests/test_standard_context_window.py | 3 +-- app/tests/test_standard_environments.py | 2 +- app/tests/test_standard_forward.py | 2 +- app/tests/test_standard_mcp_machine.py | 4 ++-- app/tests/test_standard_own_image.py | 2 +- app/tests/test_standard_recipe.py | 2 +- app/tests/test_standard_retries.py | 3 +-- app/tests/test_standard_run.py | 8 ++++---- app/tests/test_standard_served_by.py | 2 +- app/tests/test_standard_served_by_constraints.py | 2 +- app/tests/test_standard_setup_checks.py | 2 +- app/tests/test_standard_setups.py | 4 ++-- app/tests/test_standard_tools_kit.py | 2 +- app/tests/test_standard_units.py | 2 +- app/tests/test_standard_upstream_drivers.py | 2 +- app/ui_tests/test_agents.py | 4 ++-- app/ui_tests/test_settings_page.py | 2 +- app/web/builder.py | 2 +- app/web/catalogue.py | 3 ++- app/web/execute.py | 2 +- app/web/settings.py | 3 +-- docs/ports/agent-computer-v1.md | 2 +- docs/settings/sandbox.md | 2 +- docs/standard.md | 8 ++++---- pyproject.toml | 2 +- 90 files changed, 151 insertions(+), 147 deletions(-) create mode 100644 app/nullius/standard/backends/__init__.py rename app/nullius/standard/{ => backends}/boat.py (100%) rename app/nullius/standard/{containers => backends}/container.py (99%) rename app/nullius/standard/{containers => backends}/egress.py (100%) rename app/nullius/standard/{containers => backends}/forward.py (100%) rename app/nullius/standard/{containers => backends}/mcp_bridge.py (100%) rename app/nullius/standard/{containers => backends}/mcp_machine.py (100%) rename app/nullius/standard/{containers => backends}/setup_container.py (98%) rename app/nullius/standard/{containers => backends}/web_services.py (100%) delete mode 100644 app/nullius/standard/containers/__init__.py rename app/nullius/standard/{ => protocols}/computer_pipe.py (100%) rename app/nullius/standard/{ => protocols}/computer_port.py (100%) rename app/nullius/standard/{ => runner}/boat_units.py (99%) rename app/nullius/standard/{ => runner}/retries.py (100%) diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.yml index 088efa37..835d2268 100644 --- a/.github/workflows/docker-tests.yml +++ b/.github/workflows/docker-tests.yml @@ -34,7 +34,7 @@ jobs: - name: base image # The standard's one base image, and the fixture own image's FROM. run: | - PYTHONPATH=app python3 -c "from nullius.standard.containers import container; print(container.base_image())" + PYTHONPATH=app python3 -c "from nullius.standard.backends import container; print(container.base_image())" docker pull --quiet ubuntu:24.04 - name: backend suite with the docker tier run: python3 app/tests/parallel.py --docker diff --git a/AGENTS.md b/AGENTS.md index efd90148..db4fa865 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,13 +65,13 @@ and its resources. The source layout stays under `app/`. `standard/` (the Nullius standard, `docs/standard.md`, one folder per purpose: `contract/`: `ports`, `names` (capability vocabulary and legacy aliases), `definitions` (with an agent's or capability's versions), `match`; `requirements/`, what a run needs of the machine: `install`, `hostreq` (what a benchmark's options need of the machine its driver runs on: the check and the install), `network_requirements` (an environment's declared public web access: the schema and the connectivity check); - `protocols/`: `jsonl`, `acp`, `cancellation` (interruptible protocol waits); + `protocols/`: `jsonl`, `acp`, `cancellation` (interruptible protocol waits), `computer_port` and `computer_pipe` (the computer port's MCP server, served by a desktop benchmark's runner over the benchmark's own loop, and the session's stdio pipe to it); `calls/`: `relay`, `ledger` (a run's spending cap); - `containers/`: `container` (the container backend), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `egress` (an own image's check's proxy to public addresses); - `runner/`: `run`, `job`, `pace` (how soon the next unit starts after a rate limit), `shard` and `merge` (one run over many machines), `payload` (a snapshot of the running backend and effective catalogue for a remote host); + `backends/`: `container` (the container backend), `boat` (the boat backend: each unit's agent in a boat.dev VM), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `egress` (an own image's check's proxy to public addresses); + `runner/`: `run`, `job`, `retries` (what an attempt is tried again after, and how many times), `pace` (how soon the next unit starts after a rate limit), `shard` and `merge` (one run over many machines), `payload` (a snapshot of the running backend and effective catalogue for a remote host), `boat_units` (a benchmark whose units boot a VM of their own, each unit whole in a Boat VM); `proofs/`: `conform`, `fidelity` (ACP against the agent's own CLI), `prove` (a benchmark's controls and proofs), `pins` (image digests checked against registry tags); `pages/`: `recipe` (the builder's standard recipe), `howto` (the How to add steps); - and at its top the `cli`, with what no folder holds yet: `retries` (what an attempt is tried again after, and how many times), `boat` (the boat backend: each unit's agent in a boat.dev VM) and `boat_units` (a benchmark whose units boot a VM of their own, each unit whole in a Boat VM), `computer_port` and `computer_pipe` (the computer port's MCP server, served by a desktop benchmark's runner over the benchmark's own loop, and the session's stdio pipe to it); + and the `cli` at its top; conformance kits under `standard/kits/`, each a benchmark: a `driver` and, for the tools kit, an MCP server `mcp_kit`) - the definitions it reads are in the catalogue: a benchmark's `standard.json` and `driver` in its folder (τ³-bench's also the MCP diff --git a/app/nullius/catalogue/benchmarks/humaneval/driver.py b/app/nullius/catalogue/benchmarks/humaneval/driver.py index d71ab885..8939d4a8 100644 --- a/app/nullius/catalogue/benchmarks/humaneval/driver.py +++ b/app/nullius/catalogue/benchmarks/humaneval/driver.py @@ -57,7 +57,7 @@ sys.path.insert(0, os.environ["NULLIUS_UPSTREAM"]) from human_eval.data import read_problems # noqa: E402 as published from human_eval.execution import check_correctness # noqa: E402 -from nullius.standard.containers.container import CHECK_IMAGE, check_argv # noqa: E402 +from nullius.standard.backends.container import CHECK_IMAGE, check_argv # noqa: E402 PROBLEMS = {} diff --git a/app/nullius/catalogue/benchmarks/osworld1/driver.py b/app/nullius/catalogue/benchmarks/osworld1/driver.py index ea361a01..cba93655 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/driver.py +++ b/app/nullius/catalogue/benchmarks/osworld1/driver.py @@ -409,7 +409,7 @@ def answer(unit, dir, setup, model, base_url, key, **_): def _port(): """The computer port's shared code, from the nullius package on this driver's import path.""" - from nullius.standard import computer_port + from nullius.standard.protocols import computer_port return computer_port diff --git a/app/nullius/catalogue/benchmarks/osworld1/runner.py b/app/nullius/catalogue/benchmarks/osworld1/runner.py index c759e7b8..050385d8 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/runner.py +++ b/app/nullius/catalogue/benchmarks/osworld1/runner.py @@ -1,5 +1,5 @@ """One unit of an agent on OSWorld1: the upstream's DesktopEnv and its own run_single_example, imported and called as -they are, with the computer port's bridge as the loop's agent (nullius.standard.computer_port, agent.computer/v1). +they are, with the computer port's bridge as the loop's agent (nullius.standard.protocols.computer_port, agent.computer/v1). runner.py --example TASK_JSON --result-dir DIR --socket PATH --ready FILE --lifeline FD --steps N --pause SECONDS --vm VM_IMAGE --calls FILE [--held FOLDER] [--prepared FILE] [--given FILE] @@ -138,7 +138,7 @@ def main(argv=None): p.add_argument("--steps", type=int, required=True) p.add_argument("--pause", type=float, required=True) a = p.parse_args(argv) - from nullius.standard import computer_port as port + from nullius.standard.protocols import computer_port as port stop, turn = port.Stop(STOP_SECONDS), Turn() turn.given, turn.said = a.given, port.ready try: # the clean-up holds before the lifeline can stop the runner diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 739a0a01..4e5ab85c 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -35,7 +35,7 @@ "command": [ "{install}/.venv/bin/python" ], - "summary": "The unit's desktop for an agent: the computer port's pipe (the nullius package's standard/computer_pipe.py, whose path setup gives as the first argument) joined to the socket where the unit's runner serves the port's MCP server, its second argument." + "summary": "The unit's desktop for an agent: the computer port's pipe (the nullius package's standard/protocols/computer_pipe.py, whose path setup gives as the first argument) joined to the socket where the unit's runner serves the port's MCP server, its second argument." } }, "limits": { diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py b/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py index aeaa1e0e..48d007fb 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py +++ b/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py @@ -21,7 +21,7 @@ ``TAU_DOMAIN`` names the domain (``airline``, ``retail``, ...), ``TAU_RETRIEVAL`` a knowledge domain's retrieval config. It runs on the machine in the driver's environment, never in the agent's container -(``mcp_servers`` in ``standard.json``; ``nullius.standard.containers.mcp_machine``). +(``mcp_servers`` in ``standard.json``; ``nullius.standard.backends.mcp_machine``). """ import contextlib import copy diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 24c6d56d..5c97e9c2 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -129,7 +129,7 @@ from nullius.judge import store as judgements from nullius.runs import parse from nullius.harbor import source as harbor_source -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.runner import payload as standard_payload REMOTE_HOME = "~/.nullius" # on a host: tasks/, runs/, app/, harbor/ (a pinned Harbor's wheels) @@ -404,7 +404,7 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl # 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": - from nullius.standard import boat # the Boat key, to the standard run that starts VMs with it, and to no other command + from nullius.standard.backends import boat # the Boat key, to the standard run that starts VMs with it, and to no other command if boat.key(env): self._agent_keys[boat.NAME] = boat.key(env) # the benchmark's licences a standard run on a host is sent: read from its store at each launch, unless given diff --git a/app/nullius/hosts.py b/app/nullius/hosts.py index a4481ca4..8f94ca8c 100644 --- a/app/nullius/hosts.py +++ b/app/nullius/hosts.py @@ -248,7 +248,7 @@ def measure(host: Optional[Host], run: Optional[Callable] = None, timeout: float program = engine or "docker" options = ["--security-opt", "no-new-privileges", *(["--security-opt", "label=disable"] if program == "podman" else [])] else: - from nullius.standard.containers import container + from nullius.standard.backends import container program, options = container.DOCKER, [*container._userns(), "--user", container._user(), *container._security_opt()] # with the engine program's environment, as a run's check and its units: what one sees, the others do run = run or (lambda argv, t: subprocess_run(argv, t, env=container.client_env())) diff --git a/app/nullius/onboarding.py b/app/nullius/onboarding.py index ae448c6a..2ff31c19 100644 --- a/app/nullius/onboarding.py +++ b/app/nullius/onboarding.py @@ -19,7 +19,7 @@ from typing import Callable, Iterable, Optional from nullius import providers -from nullius.standard.containers import container +from nullius.standard.backends import container CONTROLS = ("nop", "oracle") diff --git a/app/nullius/prerequisites.py b/app/nullius/prerequisites.py index 98a3ec30..a231f6b3 100644 --- a/app/nullius/prerequisites.py +++ b/app/nullius/prerequisites.py @@ -35,7 +35,7 @@ from typing import Callable, Dict, List, Optional from nullius import constraints, hosts -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.requirements import hostreq LABEL = {"engine": "Docker or Podman", "docker": "Docker", "uv": "uv", "harbor": "Harbor on PATH", "python3": "python3", "git": "git"} diff --git a/app/nullius/sandbox.py b/app/nullius/sandbox.py index 3e38ca2d..4d9c3843 100644 --- a/app/nullius/sandbox.py +++ b/app/nullius/sandbox.py @@ -18,7 +18,7 @@ import subprocess from typing import List, Optional -from nullius.standard.containers import container +from nullius.standard.backends import container REGISTRY = "https://index.docker.io/v1/" # Docker Hub, as docker names it in its config HUB = "docker.io" # as podman names it: without it, podman logs in to its first search registry diff --git a/app/nullius/standard/__init__.py b/app/nullius/standard/__init__.py index 8cd7cef7..102acc84 100644 --- a/app/nullius/standard/__init__.py +++ b/app/nullius/standard/__init__.py @@ -14,10 +14,11 @@ ``docs/standard.md`` is the design. One folder per purpose: ``contract`` (what a definition may say, which pairs fit), -``requirements`` (what a run needs of the machine), ``protocols`` (ACP and JSON -lines), ``calls`` (the relay and the spending cap), ``containers`` (the container -backend and its doors), ``runner`` (a run, on one machine or several), ``proofs`` -(kits, fidelity, a benchmark's controls) and ``pages`` (the builder's recipe, the How +``requirements`` (what a run needs of the machine), ``protocols`` (ACP, JSON +lines, the computer port's server), ``calls`` (the relay and the spending cap), +``backends`` (a container or a Boat VM for each unit, and the doors through a +container), ``runner`` (a run, on one machine or several), ``proofs`` (kits, +fidelity, a benchmark's controls) and ``pages`` (the builder's recipe, the How to add steps). ``cli`` is the shell command over all of them; ``kits/`` holds the conformance kits, each a benchmark. """ diff --git a/app/nullius/standard/backends/__init__.py b/app/nullius/standard/backends/__init__.py new file mode 100644 index 00000000..3696529b --- /dev/null +++ b/app/nullius/standard/backends/__init__.py @@ -0,0 +1,16 @@ +"""Where a unit runs when not among this machine's processes, and the doors through. + +``container`` runs each unit's agent or capability in a container of its own, +its relay beside it; ``setup_container`` runs an Original setup's driver in +one. ``boat`` runs each unit's agent or capability in a boat.dev VM of its +own, its relay still on this machine. The rest is what crosses a container's +boundary, one address at a time: ``forward`` (a licence server, or a server on +the machine), ``egress`` (an own image's check, to public addresses only), +``mcp_machine`` and ``mcp_bridge`` (a benchmark's MCP server run on the +machine, and the agent's bridge to it) and ``web_services`` (the HTTP fixtures +a driver's setup declares). + +``forward.py``, ``egress.py`` and ``mcp_bridge.py`` are each mounted alone into +a container and run there: they import nothing of this application, and +``container`` and ``mcp_machine`` find them beside themselves. +""" diff --git a/app/nullius/standard/boat.py b/app/nullius/standard/backends/boat.py similarity index 100% rename from app/nullius/standard/boat.py rename to app/nullius/standard/backends/boat.py diff --git a/app/nullius/standard/containers/container.py b/app/nullius/standard/backends/container.py similarity index 99% rename from app/nullius/standard/containers/container.py rename to app/nullius/standard/backends/container.py index 1cc2a2d5..f7a382a0 100644 --- a/app/nullius/standard/containers/container.py +++ b/app/nullius/standard/backends/container.py @@ -1176,7 +1176,7 @@ def _door(self, name: str, alias: str, port: int, sock: str, what: str) -> None: if platform.system() == "Darwin": # Docker Desktop cannot connect to host Unix sockets through a # file mount. Expose only this socket via a loopback TCP bridge. - from nullius.standard.containers import forward + from nullius.standard.backends import forward nonce = token_hex(32) class Handler(socketserver.BaseRequestHandler): def handle(self): diff --git a/app/nullius/standard/containers/egress.py b/app/nullius/standard/backends/egress.py similarity index 100% rename from app/nullius/standard/containers/egress.py rename to app/nullius/standard/backends/egress.py diff --git a/app/nullius/standard/containers/forward.py b/app/nullius/standard/backends/forward.py similarity index 100% rename from app/nullius/standard/containers/forward.py rename to app/nullius/standard/backends/forward.py diff --git a/app/nullius/standard/containers/mcp_bridge.py b/app/nullius/standard/backends/mcp_bridge.py similarity index 100% rename from app/nullius/standard/containers/mcp_bridge.py rename to app/nullius/standard/backends/mcp_bridge.py diff --git a/app/nullius/standard/containers/mcp_machine.py b/app/nullius/standard/backends/mcp_machine.py similarity index 100% rename from app/nullius/standard/containers/mcp_machine.py rename to app/nullius/standard/backends/mcp_machine.py diff --git a/app/nullius/standard/containers/setup_container.py b/app/nullius/standard/backends/setup_container.py similarity index 98% rename from app/nullius/standard/containers/setup_container.py rename to app/nullius/standard/backends/setup_container.py index e1136c57..fd392d7e 100644 --- a/app/nullius/standard/containers/setup_container.py +++ b/app/nullius/standard/backends/setup_container.py @@ -20,7 +20,7 @@ import uuid from urllib.parse import urlsplit -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.protocols import jsonl from nullius.standard.requirements import hostreq, install @@ -82,7 +82,7 @@ def command(self, env, cwd, *, prepare=False, files=(), credentials=None): UV_CACHE_DIR=os.path.join(self.cache, "uv-cache"), UV_PYTHON_INSTALL_DIR=os.path.join(self.cache, "python")) name = "nullius-setup-" + uuid.uuid4().hex[:20] - cmd = ["python3", "-m", "nullius.standard.containers.setup_container", self.config, self.cache, + cmd = ["python3", "-m", "nullius.standard.backends.setup_container", self.config, self.cache, "prepare" if prepare else "run"] + ([CREDENTIALS_IN] if credentials else []) argv = container.run_argv(self.image, cmd, name=name, network=container.BRIDGE if container.podman() else "bridge", job=self.job, workdir=cwd, mounted=mounts, env=values, path=container.IMAGE_PATH) diff --git a/app/nullius/standard/containers/web_services.py b/app/nullius/standard/backends/web_services.py similarity index 100% rename from app/nullius/standard/containers/web_services.py rename to app/nullius/standard/backends/web_services.py diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 85991d73..694eefb1 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -18,10 +18,10 @@ an agent's run or conformance check there is refused without ``--unsandboxed``. ``--backend container`` (``docker``, its earlier name) runs each unit's agent or capability in a container whose only way out is the unit's relay, or a public web proxy when its environment -declares ``network`` (``standard/containers/container.py``), and needs no such yes. +declares ``network`` (``standard/backends/container.py``), and needs no such yes. ``--backend boat`` runs each unit's agent or capability in a boat.dev VM of its own, whose only way out is a tunnel to the unit's relay on this machine -(``standard/boat.py``); its API key is Settings → Sandbox's, or ``BOAT_API_KEY``. +(``standard/backends/boat.py``); its API key is Settings → Sandbox's, or ``BOAT_API_KEY``. A benchmark's control (``nop``, ``oracle``: its ``controls``) runs no agent and calls no model - only a judged benchmark's judge - so it asks for neither. ``prove`` runs a benchmark's controls and checks its units and that nothing @@ -75,14 +75,14 @@ import tempfile import time -from nullius.standard.retries import MAX_RETRIES, RETRIES +from nullius.standard.runner.retries import MAX_RETRIES, RETRIES from nullius import constraints as limits, paths, prices as price_list, progress, providers, secrets, settings # The legacy module command needs saved path overrides before install.HOME # and other runtime defaults are computed, just like the unified CLI does. if __name__ == "__main__" and "--from-run" not in sys.argv[1:]: settings.load(paths.settings_file()) -from nullius.standard import boat +from nullius.standard.backends import boat from nullius.standard.contract import definitions, match, ports from nullius.standard.proofs import conform, fidelity, pins, prove from nullius.standard.runner import job, merge, run, shard @@ -616,7 +616,7 @@ def boat_credentials(a, bench, other, vals) -> dict: def _boat_units(a, b, other) -> int: """A benchmark whose units boot VMs of their own, on Boat: each unit whole in a Boat VM (``boat_units``).""" - from nullius.standard import boat_units + from nullius.standard.runner import boat_units if a.units or a.shard: print("refused: whole-task Boat runs do not accept --units or --shard; choose a dataset and --limit") return 2 diff --git a/app/nullius/standard/containers/__init__.py b/app/nullius/standard/containers/__init__.py deleted file mode 100644 index 45f7126a..00000000 --- a/app/nullius/standard/containers/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -"""The container backend, and the doors through it. - -``container`` runs each unit's agent or capability in a container of its own, -its relay beside it; ``setup_container`` runs an Original setup's driver in -one. The rest is what crosses the boundary, one address at a time: ``forward`` -(a licence server, or a server on the machine), ``egress`` (an own image's -check, to public addresses only), ``mcp_machine`` and ``mcp_bridge`` (a -benchmark's MCP server run on the machine, and the agent's bridge to it) and -``web_services`` (the HTTP fixtures a driver's setup declares). - -``forward.py``, ``egress.py`` and ``mcp_bridge.py`` are each mounted alone into -a container and run there: they import nothing of this application, and -``container`` and ``mcp_machine`` find them beside themselves. -""" diff --git a/app/nullius/standard/kits/agent-computer-v1/desktop.py b/app/nullius/standard/kits/agent-computer-v1/desktop.py index ee852569..a5e4b29c 100644 --- a/app/nullius/standard/kits/agent-computer-v1/desktop.py +++ b/app/nullius/standard/kits/agent-computer-v1/desktop.py @@ -42,7 +42,7 @@ import threading from typing import Dict, List, Optional -from nullius.standard.containers import container +from nullius.standard.backends import container HERE = os.path.dirname(os.path.abspath(__file__)) ENVIRONMENT = "desktop" diff --git a/app/nullius/standard/kits/agent-computer-v1/driver.py b/app/nullius/standard/kits/agent-computer-v1/driver.py index 72f7851c..70cb6224 100644 --- a/app/nullius/standard/kits/agent-computer-v1/driver.py +++ b/app/nullius/standard/kits/agent-computer-v1/driver.py @@ -41,8 +41,8 @@ import threading import time -from nullius.standard import computer_port as port -from nullius.standard.containers import container +from nullius.standard.protocols import computer_port as port +from nullius.standard.backends import container from nullius.standard.protocols.jsonl import serve HERE = os.path.dirname(os.path.abspath(__file__)) diff --git a/app/nullius/standard/kits/agent-computer-v1/pipe.py b/app/nullius/standard/kits/agent-computer-v1/pipe.py index eca39daa..385b53e9 100644 --- a/app/nullius/standard/kits/agent-computer-v1/pipe.py +++ b/app/nullius/standard/kits/agent-computer-v1/pipe.py @@ -1,5 +1,5 @@ -"""The session's stdio MCP server ``computer`` for the kit: the computer port's pipe (``computer_pipe.py``, two -folders up), run from the kit's folder, where a benchmark's server command names its files. +"""The session's stdio MCP server ``computer`` for the kit: the computer port's pipe (``protocols/computer_pipe.py``, +two folders up), run from the kit's folder, where a benchmark's server command names its files. pipe.py SOCKET """ @@ -7,7 +7,7 @@ import runpy import sys -PIPE = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "computer_pipe.py") +PIPE = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "protocols", "computer_pipe.py") if __name__ == "__main__": sys.argv[0] = PIPE diff --git a/app/nullius/standard/kits/agent-search-v1/driver.py b/app/nullius/standard/kits/agent-search-v1/driver.py index 36efb317..a455beda 100644 --- a/app/nullius/standard/kits/agent-search-v1/driver.py +++ b/app/nullius/standard/kits/agent-search-v1/driver.py @@ -18,7 +18,7 @@ from urllib.parse import parse_qs, urlsplit, quote from urllib.request import urlopen -from nullius.standard.containers.container import CHECK_IMAGE +from nullius.standard.backends.container import CHECK_IMAGE from nullius.standard.protocols.jsonl import serve UNITS = ('find-source', 'disambiguate', 'follow-reference') diff --git a/app/nullius/standard/kits/agent-tools-v1/driver.py b/app/nullius/standard/kits/agent-tools-v1/driver.py index 0b034c54..f86b97b1 100644 --- a/app/nullius/standard/kits/agent-tools-v1/driver.py +++ b/app/nullius/standard/kits/agent-tools-v1/driver.py @@ -22,7 +22,7 @@ import secrets import sys -from nullius.standard.containers.container import CHECK_IMAGE +from nullius.standard.backends.container import CHECK_IMAGE from nullius.standard.protocols.jsonl import serve HERE = os.path.dirname(os.path.abspath(__file__)) diff --git a/app/nullius/standard/kits/agent-workspace-v1/driver.py b/app/nullius/standard/kits/agent-workspace-v1/driver.py index 10f04561..b247cdcf 100644 --- a/app/nullius/standard/kits/agent-workspace-v1/driver.py +++ b/app/nullius/standard/kits/agent-workspace-v1/driver.py @@ -4,7 +4,7 @@ import subprocess import sys -from nullius.standard.containers.container import check_argv +from nullius.standard.backends.container import check_argv from nullius.standard.protocols.jsonl import serve CALC = "def add(a, b):\n return a - b\n" diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 53ee6e32..085b636c 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -43,13 +43,13 @@ from nullius import constraints as limits, hosts, providers from nullius.providers import PROVIDERS, STEP -from nullius.standard import boat +from nullius.standard.backends import boat from nullius.standard.calls import ledger, relay from nullius.standard.contract import definitions, match, ports from nullius.standard.proofs import prove from nullius.standard.requirements import hostreq from nullius.standard.runner import run -from nullius.standard.retries import MAX_RETRIES +from nullius.standard.runner.retries import MAX_RETRIES CHOOSE_PROVIDER = "Choose a provider: OpenRouter, OpenAI, Anthropic or a custom provider." HARNESS = "standard" diff --git a/app/nullius/standard/proofs/conform.py b/app/nullius/standard/proofs/conform.py index e2259965..edaace82 100644 --- a/app/nullius/standard/proofs/conform.py +++ b/app/nullius/standard/proofs/conform.py @@ -28,9 +28,8 @@ from typing import Callable, Dict, List, Optional from nullius.runs import parse -from nullius.standard import retries from nullius.standard.contract import definitions, ports -from nullius.standard.runner import run +from nullius.standard.runner import retries, run STAMP = "%Y-%m-%d__%H-%M-%S" diff --git a/app/nullius/standard/proofs/prove.py b/app/nullius/standard/proofs/prove.py index 14805876..ec62e024 100644 --- a/app/nullius/standard/proofs/prove.py +++ b/app/nullius/standard/proofs/prove.py @@ -52,11 +52,10 @@ import time from typing import Callable, Dict, List, Optional -from nullius.standard import retries from nullius.standard.contract import definitions from nullius.standard.protocols import jsonl from nullius.standard.requirements import install -from nullius.standard.runner import job, run, shard as shards +from nullius.standard.runner import job, retries, run, shard as shards STAMP = "%Y-%m-%d__%H-%M-%S" SHORT = 12 # characters: a reference shorter than this is not looked for diff --git a/app/nullius/standard/protocols/__init__.py b/app/nullius/standard/protocols/__init__.py index a0a32128..5b03b197 100644 --- a/app/nullius/standard/protocols/__init__.py +++ b/app/nullius/standard/protocols/__init__.py @@ -1,7 +1,10 @@ -"""How Nullius speaks to the programs it starts. +"""How the programs of a run speak to each other. ``acp`` is the ACP client that drives an agent. ``jsonl`` is the JSON lines a benchmark's driver and a capability are spoken to in, and ``serve``, the other side, for one written in Python. ``cancellation`` is the wait both give up when -their run stops. +their run stops. ``computer_port`` is the computer port's MCP server, which a +desktop benchmark's runner serves over its own loop, and ``computer_pipe`` the +stdio server an agent's session starts to reach it, found beside it; neither +imports anything of this application. """ diff --git a/app/nullius/standard/computer_pipe.py b/app/nullius/standard/protocols/computer_pipe.py similarity index 100% rename from app/nullius/standard/computer_pipe.py rename to app/nullius/standard/protocols/computer_pipe.py diff --git a/app/nullius/standard/computer_port.py b/app/nullius/standard/protocols/computer_port.py similarity index 100% rename from app/nullius/standard/computer_port.py rename to app/nullius/standard/protocols/computer_port.py diff --git a/app/nullius/standard/runner/__init__.py b/app/nullius/standard/runner/__init__.py index 5885999e..c3d2b322 100644 --- a/app/nullius/standard/runner/__init__.py +++ b/app/nullius/standard/runner/__init__.py @@ -2,7 +2,10 @@ ``run`` sets each unit up, produces and scores it. ``job`` writes the result as a job in Harbor's shape. ``pace`` slows the start of units when the provider -says the run goes too fast. ``shard`` and ``merge`` split one launch over +says the run goes too fast; ``retries`` says which failed attempt is tried +again, and how many times. ``shard`` and ``merge`` split one launch over several machines and put its jobs back together; ``payload`` is the snapshot of -this runner a host is sent. +this runner a host is sent. ``boat_units`` sends that snapshot to a Boat VM per +unit, for a benchmark whose units boot a VM of their own, and merges what +comes back. """ diff --git a/app/nullius/standard/boat_units.py b/app/nullius/standard/runner/boat_units.py similarity index 99% rename from app/nullius/standard/boat_units.py rename to app/nullius/standard/runner/boat_units.py index e10b7438..6f2213e2 100644 --- a/app/nullius/standard/boat_units.py +++ b/app/nullius/standard/runner/boat_units.py @@ -32,7 +32,7 @@ from typing import Callable, Dict, List, Optional from nullius import paths, secrets -from nullius.standard import boat +from nullius.standard.backends import boat from nullius.standard.contract import definitions from nullius.standard.requirements import hostreq from nullius.standard.runner import merge, payload, shard diff --git a/app/nullius/standard/retries.py b/app/nullius/standard/runner/retries.py similarity index 100% rename from app/nullius/standard/retries.py rename to app/nullius/standard/runner/retries.py diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index bb8cf523..b7d3be7a 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -75,14 +75,13 @@ from nullius import constraints as limits, paths, prices as price_list, progress, providers from nullius.redact import redact from nullius.harbor import feed as live_feed -from nullius.standard import boat +from nullius.standard.backends import boat, container, mcp_machine from nullius.standard.calls import ledger as ledgers, relay -from nullius.standard.containers import container, mcp_machine from nullius.standard.contract import definitions, match from nullius.standard.protocols import acp, jsonl from nullius.standard.requirements import hostreq, install from nullius.standard.runner import job, pace as pacing, shard as shards -from nullius.standard.retries import RETRIES, retryable +from nullius.standard.runner.retries import RETRIES, retryable # the totals a unit's end carries onto the live board, from its trial's agent_result FEED_TOTALS = ("n_input_tokens", "n_cache_tokens", "n_output_tokens", "cost_usd") @@ -1231,7 +1230,7 @@ def ready(self) -> None: f["url"], f["sha256"], progress=None if there else p.download("file")) drv = install.driver_dir(self.bench) if self.backend == "container" and self.upstream: - from nullius.standard.containers import setup_container + from nullius.standard.backends import setup_container with p.stage("driver", start=f"preparing {self.bench['key']}'s container driver"): needs = definitions.option_needs(self.bench, self.bench_options)["host"] image = setup_container.image(self.image, self.bench, needs, os.path.join(self.job_dir, ".work", "image.log")) @@ -1827,7 +1826,7 @@ def unit_relay(self, tag: str, trial: str, setup: dict, env_def: Optional[dict] self.machine_env(trial), work, work) except mcp_machine.Unknown as e: raise _Ended("EnvironmentSetupError", f"the unit's setup: {e}", retryable=False) - from ..containers import web_services + from ..backends import web_services try: doors.extend(web_services.doors(setup)) except (ValueError, OSError) as e: diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 196c3f1e..5e70e977 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -451,7 +451,7 @@ const bootsVms = b => Object.values((b || {}).options || {}).some(o => o.step === 'where' && Object.values(o.needs || {}).some(n => n && n.vm)); const vmMemory = (rec, b) => Math.max(0, ...Object.entries((b || {}).options || {}).filter(([, o]) => o.step === 'where') .map(([n, o]) => (((o.needs || {})[(rec.bench_options || {})[n] ?? o.default] || {}).vm || {}).memory_gb || 0)); - // Boat's sizes as the account offers them (nullius/standard/boat.py, SIZES), each with why it cannot be chosen: + // Boat's sizes as the account offers them (nullius/standard/backends/boat.py, SIZES), each with why it cannot be chosen: // the account cannot start one, or it is too small to boot the unit's own VM (boat.fits). const boatSizes = (rec, b) => { const mem = vmMemory(rec, b); return ((schema.standardHere || {}).boatSizes || []).map(z => z.why ? {...z, note: 'Not on this account', why: 'Not on this account: ' + z.why} diff --git a/app/tests/docker_tier.py b/app/tests/docker_tier.py index ea20c39c..1b675f31 100644 --- a/app/tests/docker_tier.py +++ b/app/tests/docker_tier.py @@ -7,7 +7,7 @@ import os import subprocess -from nullius.standard.containers import container +from nullius.standard.backends import container VAR = "NULLIUS_TEST_DOCKER" diff --git a/app/tests/fixtures/standard/computer_merge_driver.py b/app/tests/fixtures/standard/computer_merge_driver.py index d6209b72..67b5c0e7 100644 --- a/app/tests/fixtures/standard/computer_merge_driver.py +++ b/app/tests/fixtures/standard/computer_merge_driver.py @@ -10,8 +10,7 @@ import threading import time -from nullius.standard import computer_port as port -from nullius.standard.protocols import jsonl +from nullius.standard.protocols import computer_port as port, jsonl class Desktop: diff --git a/app/tests/test_computer_kit.py b/app/tests/test_computer_kit.py index eb4ef980..f883fb5f 100644 --- a/app/tests/test_computer_kit.py +++ b/app/tests/test_computer_kit.py @@ -23,7 +23,7 @@ import unittest from unittest import mock -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from tests import docker_tier diff --git a/app/tests/test_computer_kit_driver.py b/app/tests/test_computer_kit_driver.py index 449e7e16..e14672c9 100644 --- a/app/tests/test_computer_kit_driver.py +++ b/app/tests/test_computer_kit_driver.py @@ -28,8 +28,8 @@ import zlib from unittest import mock -from nullius.standard import computer_port as port, computer_pipe -from nullius.standard.containers import container +from nullius.standard.protocols import computer_port as port, computer_pipe +from nullius.standard.backends import container from nullius.standard.contract import definitions, ports from tests import docker_tier @@ -159,7 +159,7 @@ def test_the_port_names_the_kit_and_the_kit_its_checks(self): summary=kit["environments"]["desktop"]["summary"])) self.assertEqual(kit["mcp_servers"]["computer"]["command"], ["python3", "{here}/pipe.py"]) # a file of its folder pipe = _module("computer_kit_pipe_under_test", "pipe.py").PIPE - self.assertEqual(pipe, os.path.join(os.path.dirname(os.path.dirname(KIT)), "computer_pipe.py")) + self.assertEqual(pipe, os.path.join(os.path.dirname(os.path.dirname(KIT)), "protocols", "computer_pipe.py")) self.assertTrue(os.path.isfile(pipe)) def test_the_pipe_from_the_kits_folder_joins_stdio_to_the_socket(self): diff --git a/app/tests/test_computer_merge.py b/app/tests/test_computer_merge.py index 591f5ed4..710b4ee0 100644 --- a/app/tests/test_computer_merge.py +++ b/app/tests/test_computer_merge.py @@ -14,9 +14,10 @@ from unittest import mock from nullius.runs import artifacts, parse -from nullius.standard import boat, computer_pipe +from nullius.standard.backends import boat from nullius.standard.contract import definitions from nullius.standard.pages import recipe +from nullius.standard.protocols import computer_pipe from nullius.standard.requirements import install from nullius.standard.runner import run diff --git a/app/tests/test_constraints.py b/app/tests/test_constraints.py index 1a2e414e..db1618f3 100644 --- a/app/tests/test_constraints.py +++ b/app/tests/test_constraints.py @@ -18,7 +18,7 @@ from unittest import mock from nullius import constraints, prerequisites, settings -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.pages import recipe from nullius.standard.requirements import install @@ -320,7 +320,7 @@ def setUp(self): self.addCleanup(container.cap, {}) def test_every_container_a_run_starts_takes_the_machine_s_caps(self): - from nullius.standard.containers import setup_container + from nullius.standard.backends import setup_container container.cap({"cpus": 1.5, "memory_mb": 512, "concurrency": 2, "gpu_ids": [0]}) flags = ["--cpus", "1.5", "--memory", "512m", "--memory-swap", "512m"] tmp = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, tmp, True) diff --git a/app/tests/test_kit_check_isolation.py b/app/tests/test_kit_check_isolation.py index 238081f6..0ec995a7 100644 --- a/app/tests/test_kit_check_isolation.py +++ b/app/tests/test_kit_check_isolation.py @@ -17,7 +17,7 @@ import unittest from pathlib import Path -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.protocols import jsonl from tests import APP diff --git a/app/tests/test_network_requirements.py b/app/tests/test_network_requirements.py index 4bc348e8..f6f215db 100644 --- a/app/tests/test_network_requirements.py +++ b/app/tests/test_network_requirements.py @@ -4,7 +4,7 @@ from types import SimpleNamespace from unittest.mock import Mock, patch import tempfile -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.pages import recipe from nullius.standard.requirements import network_requirements as net diff --git a/app/tests/test_onboarding.py b/app/tests/test_onboarding.py index 6addb244..02761d39 100644 --- a/app/tests/test_onboarding.py +++ b/app/tests/test_onboarding.py @@ -10,7 +10,7 @@ from unittest import mock from nullius import onboarding -from nullius.standard.containers import container +from nullius.standard.backends import container NO_DOCKER = lambda: False diff --git a/app/tests/test_osworld1_agent_side.py b/app/tests/test_osworld1_agent_side.py index acaf560a..20cdfbef 100644 --- a/app/tests/test_osworld1_agent_side.py +++ b/app/tests/test_osworld1_agent_side.py @@ -203,7 +203,7 @@ def test_an_agents_calls_drive_the_upstreams_loop_to_done(self): self.assertEqual(setup["prompt"], TASK["instruction"] + "\n\nIf you need a password for sudo, the password of " "the computer is 'password'.") self.assertEqual([(m["name"], m["server"]) for m in setup["mcp"]], [("computer", "computer")]) - self.assertTrue(setup["mcp"][0]["args"][0].endswith(os.path.join("nullius", "standard", "computer_pipe.py"))) + self.assertTrue(setup["mcp"][0]["args"][0].endswith(os.path.join("nullius", "standard", "protocols", "computer_pipe.py"))) s = self.session(setup) self.assertEqual(base64.b64decode(s.call("screenshot")["content"][0]["data"])[:4], b"\x89PNG") self.assertEqual(value(s.call("click", x=10, y=20))["steps_left"], 4) diff --git a/app/tests/test_osworld1_entry_parts.py b/app/tests/test_osworld1_entry_parts.py index b6da97fb..6b1cdfe9 100644 --- a/app/tests/test_osworld1_entry_parts.py +++ b/app/tests/test_osworld1_entry_parts.py @@ -20,7 +20,7 @@ import unittest from unittest import mock -from nullius.standard import computer_port +from nullius.standard.protocols import computer_port ENTRY = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "catalogue", "benchmarks", "osworld1") @@ -630,7 +630,7 @@ def test_the_entrys_copy_holds_the_runner_and_the_package_the_ports_code(self): files = set(payload._entry(Path(ENTRY))) self.assertTrue({"driver.py", "agents.json", "nop.py", "runner.py"} <= files, sorted(files)) package = set(payload._python(payload.PACKAGE)) - self.assertTrue({"standard/computer_port.py", "standard/computer_pipe.py"} <= package) + self.assertTrue({"standard/protocols/computer_port.py", "standard/protocols/computer_pipe.py"} <= package) class FakeEnv: diff --git a/app/tests/test_osworld2_muse.py b/app/tests/test_osworld2_muse.py index e3f34ccd..40b8455e 100644 --- a/app/tests/test_osworld2_muse.py +++ b/app/tests/test_osworld2_muse.py @@ -18,8 +18,8 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest import mock +from nullius.standard.backends import container from nullius.standard.calls import relay -from nullius.standard.containers import container from nullius.standard.contract import definitions from nullius.standard.pages import recipe from nullius.standard.protocols import jsonl diff --git a/app/tests/test_prerequisites.py b/app/tests/test_prerequisites.py index 09e44b36..87383512 100644 --- a/app/tests/test_prerequisites.py +++ b/app/tests/test_prerequisites.py @@ -7,7 +7,7 @@ from unittest import mock from nullius import hosts, prerequisites -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.pages import recipe from nullius.standard.runner import run diff --git a/app/tests/test_sandbox.py b/app/tests/test_sandbox.py index b5f4381d..dd7de790 100644 --- a/app/tests/test_sandbox.py +++ b/app/tests/test_sandbox.py @@ -12,7 +12,7 @@ from unittest import mock from nullius import sandbox -from nullius.standard.containers import container +from nullius.standard.backends import container def done(code=0, out="", err=""): diff --git a/app/tests/test_search_kit.py b/app/tests/test_search_kit.py index 18885906..d8a25102 100644 --- a/app/tests/test_search_kit.py +++ b/app/tests/test_search_kit.py @@ -6,7 +6,7 @@ import tempfile import unittest from urllib.request import urlopen -from nullius.standard.containers import web_services +from nullius.standard.backends import web_services from nullius.standard.contract import definitions, match spec = importlib.util.spec_from_file_location('search_kit', Path(definitions.KITS) / 'agent-search-v1' / 'driver.py') @@ -109,7 +109,7 @@ def test_gaia_requires_search_and_unproven_agents_do_not_fit(self): from tests import docker_tier -from nullius.standard.containers import container +from nullius.standard.backends import container import subprocess import socket from unittest import mock diff --git a/app/tests/test_settings.py b/app/tests/test_settings.py index 1c8d67fd..2a19d0e1 100644 --- a/app/tests/test_settings.py +++ b/app/tests/test_settings.py @@ -30,8 +30,8 @@ def test_every_variable_the_application_reads_is_in_the_table(self): read -= {"LOCALAPPDATA"} # Windows's user directory, not a Nullius setting read -= {"OPENAI_BASE_URL"} # what a run's launcher hands it (execution.URL_NAMES), read by the run: standard cli --from-run read -= {"NULLIUS_LICENCE_DIR"} # the same: where a host's run writes a licence file (execution, standard cli) - read -= {"NULLIUS_FORWARD_TO"} # a licence server's forwarder's, in its own container (standard/containers/forward.py) - read -= {"NULLIUS_MCP_AT"} # the MCP bridge's, in the agent's container (standard/containers/mcp_bridge.py) + read -= {"NULLIUS_FORWARD_TO"} # a licence server's forwarder's, in its own container (standard/backends/forward.py) + read -= {"NULLIUS_MCP_AT"} # the MCP bridge's, in the agent's container (standard/backends/mcp_bridge.py) read -= {"DOCKER_CONFIG"} # docker's own: where it keeps a login (sandbox.py reads the username) read -= {"DOCKER_HOST", "DOCKER_CONTEXT"} # docker's own: when set, container.py leaves the current context to them read -= {"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"} # the user's session: where systemd-run finds its manager (constraints.session) diff --git a/app/tests/test_setup_container.py b/app/tests/test_setup_container.py index 43428ef0..49096f92 100644 --- a/app/tests/test_setup_container.py +++ b/app/tests/test_setup_container.py @@ -9,7 +9,7 @@ import unittest from unittest.mock import patch -from nullius.standard.containers import container, setup_container +from nullius.standard.backends import container, setup_container from nullius.standard.protocols import jsonl from tests import docker_tier @@ -148,7 +148,7 @@ def test_the_launcher_puts_the_credentials_in_the_drivers_environment(self): env = {'PATH': os.environ.get('PATH', ''), 'PYTHONPATH': APP, 'NULLIUS_HOME': root + '/profile'} def launch(*credentials): - return subprocess.run([sys.executable, '-m', 'nullius.standard.containers.setup_container', root + '/setup.json', + return subprocess.run([sys.executable, '-m', 'nullius.standard.backends.setup_container', root + '/setup.json', root + '/cache', 'run', *credentials], env=env, capture_output=True, text=True, timeout=60).stdout self.assertEqual(launch(root + '/credentials'), 'fixture-only') @@ -163,7 +163,7 @@ def test_the_container_starts_the_driver_with_the_command_a_host_run_starts(self with open(root + '/setup.json', 'w') as f: json.dump({'bench': bench, 'upstream': None, 'needs': []}, f) env = {'PATH': os.environ.get('PATH', ''), 'PYTHONPATH': APP, 'NULLIUS_HOME': root + '/profile'} - said = subprocess.run([sys.executable, '-m', 'nullius.standard.containers.setup_container', root + '/setup.json', + said = subprocess.run([sys.executable, '-m', 'nullius.standard.backends.setup_container', root + '/setup.json', root + '/cache', 'run'], env=env, capture_output=True, text=True, timeout=60).stdout command, extra = install.driver_argv(bench, root + '/cache') self.assertEqual((said, extra), (' '.join(command[1:]), {})) diff --git a/app/tests/test_standard_boat.py b/app/tests/test_standard_boat.py index c7a12971..206d2332 100644 --- a/app/tests/test_standard_boat.py +++ b/app/tests/test_standard_boat.py @@ -1,4 +1,4 @@ -"""The boat backend (``standard/boat.py``): its API client, a unit's VM, what it is sent, and a run +"""The boat backend (``standard/backends/boat.py``): its API client, a unit's VM, what it is sent, and a run whose agent goes to a VM - here a stand-in that runs it on this machine, so nothing reaches boat.dev.""" from __future__ import annotations @@ -14,7 +14,7 @@ import urllib.error from unittest import mock -from nullius.standard import boat +from nullius.standard.backends import boat from nullius.standard.contract import definitions from nullius.standard.pages import recipe from nullius.standard.runner import run diff --git a/app/tests/test_standard_boat_units.py b/app/tests/test_standard_boat_units.py index 39fcc4c9..d048d527 100644 --- a/app/tests/test_standard_boat_units.py +++ b/app/tests/test_standard_boat_units.py @@ -12,11 +12,11 @@ import unittest from nullius import secrets -from nullius.standard import boat_units, cli -from nullius.standard.containers import container +from nullius.standard import cli +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.pages import recipe -from nullius.standard.runner import run +from nullius.standard.runner import boat_units, run OSWORLD1 = definitions.get("benchmark", "osworld1") diff --git a/app/tests/test_standard_check_safety.py b/app/tests/test_standard_check_safety.py index 629f7759..e523f460 100644 --- a/app/tests/test_standard_check_safety.py +++ b/app/tests/test_standard_check_safety.py @@ -28,7 +28,7 @@ import urllib.request from unittest import mock -from nullius.standard.containers import container, egress +from nullius.standard.backends import container, egress from nullius.standard.contract import definitions from nullius.standard.runner import run from tests import docker_tier diff --git a/app/tests/test_standard_computer_pipe.py b/app/tests/test_standard_computer_pipe.py index b1ed2caa..2eb3e4b0 100644 --- a/app/tests/test_standard_computer_pipe.py +++ b/app/tests/test_standard_computer_pipe.py @@ -17,7 +17,7 @@ import unittest PIPE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "standard", - "computer_pipe.py") + "protocols", "computer_pipe.py") def pipe_module(): diff --git a/app/tests/test_standard_computer_port.py b/app/tests/test_standard_computer_port.py index 31aec25b..f1dc0fe8 100644 --- a/app/tests/test_standard_computer_port.py +++ b/app/tests/test_standard_computer_port.py @@ -1,4 +1,4 @@ -"""The computer port's shared code (``nullius.standard.computer_port``): the MCP server ``computer`` and its bridge to a +"""The computer port's shared code (``nullius.standard.protocols.computer_port``): the MCP server ``computer`` and its bridge to a benchmark's loop, on a fake desktop, with a scripted MCP client over the server's socket; the runner's ready file, lifeline and one stop. Once the agent is given its task, the desktop is reached through acting calls alone: one observation for each step, fixed as the step ends, which screenshot returns without a new picture; upload and prepare @@ -25,7 +25,7 @@ import unittest from unittest import mock -from nullius.standard import computer_port as cp +from nullius.standard.protocols import computer_port as cp FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures") APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -612,7 +612,7 @@ def test_every_tool_call_is_recorded_with_its_tool_times_and_failure_and_nothing RUNNER_CHILD = """ import os, signal, sys, threading, time sys.path.insert(0, sys.argv[1]) -from nullius.standard import computer_port as cp +from nullius.standard.protocols import computer_port as cp mode = sys.argv[2] stop = cp.Stop(float(sys.argv[3]), last=lambda: print("last resort", flush=True)) stop.install() @@ -1228,7 +1228,7 @@ def test_a_closed_connection_leaves_the_servers_list(self): else "") UPSTREAM_CHILD = """ import argparse, os, sys, tempfile, threading -from nullius.standard import computer_port as cp +from nullius.standard.protocols import computer_port as cp import lib_run_single from desktop_env.desktop_env import DesktopEnv diff --git a/app/tests/test_standard_conform.py b/app/tests/test_standard_conform.py index d81e92c5..cf7298b3 100644 --- a/app/tests/test_standard_conform.py +++ b/app/tests/test_standard_conform.py @@ -12,12 +12,12 @@ from types import SimpleNamespace from unittest import mock -from nullius.standard import cli, retries -from nullius.standard.containers import container +from nullius.standard import cli +from nullius.standard.backends import container from nullius.standard.contract import definitions, match from nullius.standard.proofs import conform from nullius.standard.requirements import install -from nullius.standard.runner import run +from nullius.standard.runner import retries, run FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard") diff --git a/app/tests/test_standard_container.py b/app/tests/test_standard_container.py index 4dee5da9..6307e9df 100644 --- a/app/tests/test_standard_container.py +++ b/app/tests/test_standard_container.py @@ -19,7 +19,7 @@ import urllib.request from unittest import mock -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.requirements import install from tests import docker_tier diff --git a/app/tests/test_standard_context_window.py b/app/tests/test_standard_context_window.py index 8f758517..738221d1 100644 --- a/app/tests/test_standard_context_window.py +++ b/app/tests/test_standard_context_window.py @@ -11,11 +11,10 @@ from unittest.mock import patch from nullius.runs import classify, parse -from nullius.standard import retries from nullius.standard.calls import relay from nullius.standard.contract import definitions from nullius.standard.requirements import install -from nullius.standard.runner import job, run +from nullius.standard.runner import job, retries, run FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") WORDS = "the gated task's own sentence" diff --git a/app/tests/test_standard_environments.py b/app/tests/test_standard_environments.py index e3a51434..722f1e2d 100644 --- a/app/tests/test_standard_environments.py +++ b/app/tests/test_standard_environments.py @@ -23,7 +23,7 @@ from nullius import secrets, settings from nullius.runs import classify, parse from nullius.standard import cli -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.requirements import install from nullius.standard.runner import run diff --git a/app/tests/test_standard_forward.py b/app/tests/test_standard_forward.py index 6dbd2563..0a308d9c 100644 --- a/app/tests/test_standard_forward.py +++ b/app/tests/test_standard_forward.py @@ -14,7 +14,7 @@ import unittest from unittest import mock -from nullius.standard.containers import forward +from nullius.standard.backends import forward def _greeter(greeting: bytes, host: str = "127.0.0.1") -> int: diff --git a/app/tests/test_standard_mcp_machine.py b/app/tests/test_standard_mcp_machine.py index 3820e692..34bc55df 100644 --- a/app/tests/test_standard_mcp_machine.py +++ b/app/tests/test_standard_mcp_machine.py @@ -1,5 +1,5 @@ """A benchmark's MCP server run on the machine, in the driver's environment -(``mcp_servers``; ``nullius.standard.containers.mcp_machine``): declared and checked; on +(``mcp_servers``; ``nullius.standard.backends.mcp_machine``): declared and checked; on the local backend the agent starts it from that environment; on docker a listener here, one door on the unit's network (``forward.py`` to a Unix socket) and a bridge in the agent's container. And the driver environment @@ -19,7 +19,7 @@ import unittest from unittest import mock -from nullius.standard.containers import container, mcp_machine +from nullius.standard.backends import container, mcp_machine from nullius.standard.contract import definitions from nullius.standard.requirements import install from nullius.standard.runner import run diff --git a/app/tests/test_standard_own_image.py b/app/tests/test_standard_own_image.py index 24f66117..237193fc 100644 --- a/app/tests/test_standard_own_image.py +++ b/app/tests/test_standard_own_image.py @@ -17,7 +17,7 @@ from nullius.runs import classify from tests import docker_tier -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.requirements import install from nullius.standard.runner import run diff --git a/app/tests/test_standard_recipe.py b/app/tests/test_standard_recipe.py index 8052ce8f..5630e073 100644 --- a/app/tests/test_standard_recipe.py +++ b/app/tests/test_standard_recipe.py @@ -465,7 +465,7 @@ 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 env = {"OPENAI_API_KEY": "sk-handed", "BOAT_API_KEY": "boat_handed", "PATH": "/bin"} self.assertEqual(cli.run_env("openai", env), {"OPENAI_API_KEY": "sk-handed", "BOAT_API_KEY": "boat_handed", "PATH": "/bin"}) - from nullius.standard import boat + from nullius.standard.backends import boat with patch.object(boat.secrets, "value", return_value=None): self.assertEqual(boat.key(cli.run_env("openai", env)), "boat_handed") diff --git a/app/tests/test_standard_retries.py b/app/tests/test_standard_retries.py index 62a730e0..c00b1b12 100644 --- a/app/tests/test_standard_retries.py +++ b/app/tests/test_standard_retries.py @@ -3,8 +3,7 @@ import time import unittest -from nullius.standard import retries -from nullius.standard.runner import pace +from nullius.standard.runner import pace, retries def ended(exception_type): diff --git a/app/tests/test_standard_run.py b/app/tests/test_standard_run.py index 0d9227fd..c702b0fc 100644 --- a/app/tests/test_standard_run.py +++ b/app/tests/test_standard_run.py @@ -18,8 +18,8 @@ from nullius import progress from nullius.runs import classify, live, parse +from nullius.standard.backends import container from nullius.standard.calls import ledger, relay -from nullius.standard.containers import container from nullius.standard.contract import definitions from nullius.standard.protocols import acp, jsonl from nullius.standard.requirements import install @@ -1264,7 +1264,7 @@ def test_a_simulator_is_only_for_a_conversation(self): def test_the_container_backend_needs_no_yes_but_a_usable_engine(self): from unittest import mock - from nullius.standard.containers import container + from nullius.standard.backends import container b = definitions.get("benchmark", "fakebench", ROOT) a = definitions.get("agent", "fake", ROOT) env = {"MODEL_API_URL": "http://127.0.0.1:9/v1"} @@ -1332,7 +1332,7 @@ def start(self, env, cwd, log, **kw): def test_on_the_docker_backend_the_agent_is_installed_in_the_base_image_whatever_this_machine(self): from unittest import mock - from nullius.standard.containers import container + from nullius.standard.backends import container from nullius.standard.requirements import install b = definitions.get("benchmark", "fakebench", ROOT) a = definitions.get("agent", "fake", ROOT) @@ -1354,7 +1354,7 @@ def test_on_the_docker_backend_the_agent_is_installed_in_the_base_image_whatever def test_a_model_door_that_fails_to_open_still_writes_the_jobs_result(self): from unittest import mock - from nullius.standard.containers import container + from nullius.standard.backends import container b = definitions.get("benchmark", "fakebench", ROOT) a = definitions.get("agent", "fake", ROOT) env = {"MODEL_API_URL": "http://127.0.0.1:9/v1"} diff --git a/app/tests/test_standard_served_by.py b/app/tests/test_standard_served_by.py index 751fce94..370e3a57 100644 --- a/app/tests/test_standard_served_by.py +++ b/app/tests/test_standard_served_by.py @@ -28,8 +28,8 @@ from nullius import progress from nullius.standard import cli +from nullius.standard.backends import container from nullius.standard.calls import relay -from nullius.standard.containers import container from nullius.standard.contract import definitions from nullius.standard.requirements import install from nullius.standard.runner import job, merge, run diff --git a/app/tests/test_standard_served_by_constraints.py b/app/tests/test_standard_served_by_constraints.py index 98ff2174..211cc74e 100644 --- a/app/tests/test_standard_served_by_constraints.py +++ b/app/tests/test_standard_served_by_constraints.py @@ -17,7 +17,7 @@ from nullius import constraints, progress from nullius.standard import cli -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.pages import recipe from nullius.standard.requirements import install diff --git a/app/tests/test_standard_setup_checks.py b/app/tests/test_standard_setup_checks.py index c5b6b9b6..669ae6ea 100644 --- a/app/tests/test_standard_setup_checks.py +++ b/app/tests/test_standard_setup_checks.py @@ -3,7 +3,7 @@ import unittest from unittest import mock -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.runner import run from tests.test_standard_setups import bench diff --git a/app/tests/test_standard_setups.py b/app/tests/test_standard_setups.py index 5e378e7a..fc1bb39c 100644 --- a/app/tests/test_standard_setups.py +++ b/app/tests/test_standard_setups.py @@ -231,13 +231,13 @@ def test_a_reply_with_no_text_is_said_as_the_models(self): def test_a_docker_setup_still_requires_a_working_daemon(self): o, _ = definitions.setup(self.b, "original") - with patch("nullius.standard.containers.container.unusable", return_value="daemon unavailable"): + with patch("nullius.standard.backends.container.unusable", return_value="daemon unavailable"): with self.assertRaisesRegex(run.Refused, "daemon unavailable"): run.Run(self.b, o, model="paper-1", provider="custom", jobs_root=self.tmp, env=self.env, backend="container") def test_docker_setup_runs_driver_and_linux_dependencies_with_scoped_credentials(self): from tests import docker_tier - from nullius.standard.containers import container + from nullius.standard.backends import container why = docker_tier.why_not() if why: self.skipTest(why) diff --git a/app/tests/test_standard_tools_kit.py b/app/tests/test_standard_tools_kit.py index 94d2e359..009f6206 100644 --- a/app/tests/test_standard_tools_kit.py +++ b/app/tests/test_standard_tools_kit.py @@ -241,7 +241,7 @@ def test_on_docker_the_server_is_started_by_the_images_python(self): """The agent starts it in its container: this machine's interpreter, mounted over the image's, would not run.""" tmp = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp, True) - from nullius.standard.containers import container + from nullius.standard.backends import container env = {"PATH": os.environ.get("PATH", ""), "PYTHONPATH": APP, "PYTHONDONTWRITEBYTECODE": "1", container.CHECK_IMAGE: "nullius/base:test"} d = jsonl.Proc([sys.executable, os.path.join(KIT, "driver.py")], KIT, env, os.path.join(tmp, "driver.log")).start() diff --git a/app/tests/test_standard_units.py b/app/tests/test_standard_units.py index 7ef25e89..856fb7be 100644 --- a/app/tests/test_standard_units.py +++ b/app/tests/test_standard_units.py @@ -23,7 +23,7 @@ from nullius import progress from nullius.harbor import feed from nullius.standard import cli -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.requirements import install from nullius.standard.runner import merge, pace as pacing, run, shard diff --git a/app/tests/test_standard_upstream_drivers.py b/app/tests/test_standard_upstream_drivers.py index 4f3915ad..bac3c7df 100644 --- a/app/tests/test_standard_upstream_drivers.py +++ b/app/tests/test_standard_upstream_drivers.py @@ -26,7 +26,7 @@ from unittest import mock from pathlib import Path -from nullius.standard.containers import container +from nullius.standard.backends import container from nullius.standard.contract import definitions from nullius.standard.protocols import jsonl from nullius.standard.requirements import install diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index 1156fbb4..f62c6281 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -598,7 +598,7 @@ def test_the_builder_gets_the_skills_and_a_benchmark_needing_one_says_who_lacks_ self.assertIn('decoys ✗', card[:card.index("")]) def test_the_builder_is_given_the_controls_their_proofs_and_whether_docker_runs_here(self): - from nullius.standard import boat + from nullius.standard.backends import boat self.fixture() with patch.object(boat, "unusable", lambda here=True: "no Boat API key: set it in Settings → Sandbox"): html = self.get("/new-run").get_data(as_text=True) @@ -615,7 +615,7 @@ def test_the_builder_is_given_the_controls_their_proofs_and_whether_docker_runs_ "boatSizes": sizes, "boatSlots": None, "boatKey": False, "licences": {}, "host": {}}) def test_the_builder_offers_the_boat_sizes_and_vms_at_once_its_account_says(self): - from nullius.standard import boat + from nullius.standard.backends import boat self.fixture() account = {"types": {"small": None, "default": None, "large": "not during the free trial"}, "slots": 2} with patch.object(boat, "unusable", lambda here=True: None), patch.object(web.execute, "boat_account", lambda: account): diff --git a/app/ui_tests/test_settings_page.py b/app/ui_tests/test_settings_page.py index d51f22ff..c27e95f7 100644 --- a/app/ui_tests/test_settings_page.py +++ b/app/ui_tests/test_settings_page.py @@ -1126,7 +1126,7 @@ def test_the_sandbox_is_asked_when_shown_and_a_login_goes_to_docker_only(self): def test_the_boat_key_is_saved_from_this_machines_browser_and_never_echoed(self): from nullius import secrets - from nullius.standard import boat + from nullius.standard.backends import boat with tempfile.TemporaryDirectory() as folder, patch.dict(os.environ, {"SECRETS_DIR": folder}): os.environ.pop(boat.NAME, None) headers = {"Origin": "http://localhost", "X-CSRF-Token": self.token()} diff --git a/app/web/builder.py b/app/web/builder.py index 36c44b23..50e85aa4 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -15,7 +15,7 @@ from nullius.catalogue import catalog from nullius.recipes import launch as command_builder from nullius.recipes import store as recipe_store -from nullius.standard import boat +from nullius.standard.backends import boat from nullius.standard.contract import definitions from nullius.standard.requirements import hostreq from nullius.standard.pages import recipe as standard_recipe diff --git a/app/web/catalogue.py b/app/web/catalogue.py index a7e1e969..31730854 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -13,8 +13,9 @@ from nullius import execution, paths, providers, secrets, settings from nullius.catalogue import catalog, citation, harbor_entry, sources, storage from nullius.standard.contract import definitions as standard_definitions -from nullius.standard.pages import howto, recipe as standard_recipe +from nullius.standard.pages import howto from nullius.standard.proofs import prove +from nullius.standard.pages import recipe as standard_recipe from .core import app from . import execute diff --git a/app/web/execute.py b/app/web/execute.py index 5c5f35b5..e67ec160 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -8,7 +8,7 @@ from flask import abort, jsonify, request, url_for from nullius import execution, hosts, prerequisites, prices, providers, settings from nullius.harbor import source as harbor_source -from nullius.standard import boat +from nullius.standard.backends import boat from nullius.standard.pages import recipe as standard_recipe from .core import app diff --git a/app/web/settings.py b/app/web/settings.py index bf24828a..c9002319 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -7,8 +7,7 @@ import socket from flask import abort, flash, jsonify, redirect, render_template, request, url_for from nullius import constraints, execution, hosts, paths, prerequisites, prices, providers, sandbox, secrets, settings -from nullius.standard import boat -from nullius.standard.containers import container +from nullius.standard.backends import boat, container from nullius.standard.pages import recipe as standard_recipe from nullius.judge import client diff --git a/docs/ports/agent-computer-v1.md b/docs/ports/agent-computer-v1.md index f0d8e3bd..c2dc987d 100644 --- a/docs/ports/agent-computer-v1.md +++ b/docs/ports/agent-computer-v1.md @@ -81,7 +81,7 @@ A step's `files` are read once its actions have run and their pauses have passed ## For a benchmark's runner -The shared code is `app/nullius/standard/computer_port.py`, with the standard library alone, and `computer_pipe.py` beside it. +The shared code is `app/nullius/standard/protocols/computer_port.py`, with the standard library alone, and `computer_pipe.py` beside it. | Piece | What the runner gives or does | | --- | --- | diff --git a/docs/settings/sandbox.md b/docs/settings/sandbox.md index 5c58244a..0dd01ece 100644 --- a/docs/settings/sandbox.md +++ b/docs/settings/sandbox.md @@ -8,4 +8,4 @@ Where agents run apart from this machine: Boat VMs. Under **Execution**. | Rule | | | --- | --- | -| Code | `app/nullius/standard/boat.py` | +| Code | `app/nullius/standard/backends/boat.py` | diff --git a/docs/standard.md b/docs/standard.md index d6c5654c..0a42ee92 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -143,7 +143,7 @@ record); verifier/reward.txt and score.json | Units | Run `-j` at a time, each with its own workspace (a git repository of its own), home and relay | | A relay per unit | Its record is the trial's `.work/relay`; the judge and simulated user are routes on it (`-judge`, `-simulator`). An option whose driver embeds gets a relay of the run's own before any unit, recorded in `.work/relay-benchmark` as the benchmark's cost. A 200 with no reply, not streamed, reaches the caller as a 502 (or the 429 or 402 its error held); the record keeps `answered: 200`. A call refused with 400, 413 or 422 records its inline images' types and sizes as `images`, never their bytes | | Job name | One run at a time per job name: another is refused before it writes anything. A later run under the same name moves each trial's earlier record aside to the trial's `.work/earlier.` | -| Backends (`--backend`) | `local`: processes on this machine. `container`: each unit's agent or capability in a container, its relay beside it (`standard/containers/container.py`), on Docker, or on Podman 4.7 or later where `docker` is missing, is podman under that name, or does not answer (`docker ps` fails) while `podman ps` succeeds. Podman needs no Docker API socket and no `containers.conf` change. Where neither answers, Nullius keeps `docker` and its reason says that podman is on the machine. A host is probed by the same rule. `docker`, the old name of `container`, is still accepted. For agent and capability runs the driver stays on the machine; Original setups instead containerize the driver and its answerer (`standard/containers/setup_container.py`); in a container a check that runs what the agent left (the workspace kit's test) runs it in a throwaway, network-less container of the unit's image (`container.check_argv`), and no check reads through a link the agent planted; `config.json` records the backend and the image. `boat`: each unit's agent or capability in a boat.dev VM of its own (`standard/boat.py`, [The boat backend](#the-boat-backend)) | +| Backends (`--backend`) | `local`: processes on this machine. `container`: each unit's agent or capability in a container, its relay beside it (`standard/backends/container.py`), on Docker, or on Podman 4.7 or later where `docker` is missing, is podman under that name, or does not answer (`docker ps` fails) while `podman ps` succeeds. Podman needs no Docker API socket and no `containers.conf` change. Where neither answers, Nullius keeps `docker` and its reason says that podman is on the machine. A host is probed by the same rule. `docker`, the old name of `container`, is still accepted. For agent and capability runs the driver stays on the machine; Original setups instead containerize the driver and its answerer (`standard/backends/setup_container.py`); in a container a check that runs what the agent left (the workspace kit's test) runs it in a throwaway, network-less container of the unit's image (`container.check_argv`), and no check reads through a link the agent planted; `config.json` records the backend and the image. `boat`: each unit's agent or capability in a boat.dev VM of its own (`standard/backends/boat.py`, [The boat backend](#the-boat-backend)) | | Progress | One line per stage on stderr and in `progress.jsonl`: `[nullius] stage=install agent=codex@2.2.2 state=done seconds=41 at=...` (`start`, `done`, `cached`, `failed`; a download's bytes every 5 s) for the base image, an environment, the upstream, a dataset, `driver.install` and the agent; then `stage=units n=10`, `stage=unit i=3 of=10 unit=... outcome=passed`, `stage=done`; `stage=refused` alone for a run refused first. From `stage=units` the job also writes `events.jsonl`, Harbor's live feed | | Outcomes | A last model call that got a 429 is `rate_limited` (calls in the order they began; a side model's later 200 does not cover the agent's own), a refused key an API error, both outside the agent's rate, unless the unit passed; a unit asked to stop (a `stop` beside its relay's records) keeps the score its driver gave despite the agent's own last 429; the agent's own last call over the model's context window is `ContextWindowExceededError`, the agent's; an agent past its limit for the unit, every turn included, is the agent's timeout ([time limits](cli/run.md#time-limits)). `"kind": "score"` leaves a score and no pass | | Rate limits | After a `rate_limited` end no unit starts for 60 s, or the provider's `Retry-After`, doubling to 300 s while units keep ending so | @@ -216,7 +216,7 @@ A benchmark whose tools are its upstream's own code declares `mcp_servers`, run "mcp": [{"name": "airline", "server": "domain", "env": {"TAU_DOMAIN": "airline", "TAU_AT": ""}}] ``` -The agent's session still gets a stdio server (`standard/containers/mcp_machine.py`): +The agent's session still gets a stdio server (`standard/backends/mcp_machine.py`): | Backend | How the agent reaches it | | --- | --- | @@ -283,7 +283,7 @@ An entry with `"provider": "huggingface"` is a `value` to the `driver`, read fro | --- | --- | --- | | `value` (default) | A key or access token, the variable `name` of its process | By name, never on an argument list | | `file` | A licence file; `env` names a variable holding its path, required on local processes | Mounted read-only at `path` (absolute, not under `/proc`, `/sys` or `/dev`) | -| `server` | A licence server, `host:port`, as the variable `name` | A forwarder beside the relay (`standard/containers/forward.py`) under the server's own name, the one address the agent may reach; an IPv4 address as `licence-server-`, `host.docker.internal` the machine the run is on. On a rootless engine or Podman on Linux, `host.docker.internal` is reached as `licence-server-` through a Unix socket | +| `server` | A licence server, `host:port`, as the variable `name` | A forwarder beside the relay (`standard/backends/forward.py`) under the server's own name, the one address the agent may reach; an IPv4 address as `licence-server-`, `host.docker.internal` the machine the run is on. On a rootless engine or Podman on Linux, `host.docker.internal` is reached as `licence-server-` through a Unix socket | | Rule | Detail | | --- | --- | @@ -340,7 +340,7 @@ A benchmark whose tasks are containers (their own Dockerfile and `FROM`) says so | Task internet ends before the check | When `internet: true`, `HTTP_PROXY`/`HTTPS_PROXY` name the proxy; internal relay and benchmark server aliases remain direct through `NO_PROXY`. `agent/egress.log` records allowed and refused traffic. The proxy is removed before verification, also after failed or cancelled work; failure to remove it prevents verification. Tasks without the flag retain their existing isolation | | The check runs where the work is | `score` is sent `verified: {exit, timed_out, output, dir, collected}`; the driver never runs docker. What changed in the container is `agent/container-changes.txt` | | Nothing of the agent runs during the check | Every process but init and the keep-alive is stopped, then killed; `verifier/stopped.txt` names each, one that cannot be stopped is a `VerifierError`. `keep_processes: true` lets them run on, free to alter the tests | -| The check's way out is a proxy | `network: true` adds a proxy container (`standard/containers/egress.py`) as `egress`, told to the check's command alone (`HTTP_PROXY`, `HTTPS_PROXY`); it connects only to global addresses, never `169.254.0.0/16`, `100.64.0.0/10`, private ranges, loopback or the docker bridge. `verifier/egress.log` keeps what it let through and refused. A download has to honour the proxy variables | +| The check's way out is a proxy | `network: true` adds a proxy container (`standard/backends/egress.py`) as `egress`, told to the check's command alone (`HTTP_PROXY`, `HTTPS_PROXY`); it connects only to global addresses, never `169.254.0.0/16`, `100.64.0.0/10`, private ranges, loopback or the docker bridge. `verifier/egress.log` keeps what it let through and refused. A download has to honour the proxy variables | | Controls | `nop` leaves the image as it is; `oracle` replies `{"answer": "", "solve": {copy, write, run, seconds}}`, run in the container. Neither needs the container backend, both need Docker or Podman | | Where it cannot run | An agent's unit needs the container backend (never `local_ok`); a capability benchmark has no own image | diff --git a/pyproject.toml b/pyproject.toml index ad4135cf..712019be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,7 +39,7 @@ include-package-data = false packages = [ "nullius", "nullius.catalogue", "nullius.compare", "nullius.harbor", "nullius.importers", "nullius.judge", "nullius.recipes", "nullius.runs", - "nullius.standard", "nullius.standard.calls", "nullius.standard.containers", + "nullius.standard", "nullius.standard.backends", "nullius.standard.calls", "nullius.standard.contract", "nullius.standard.pages", "nullius.standard.proofs", "nullius.standard.protocols", "nullius.standard.requirements", "nullius.standard.runner", "nullius.traces", "_nullius_app", "_nullius_app.web", From 97652d3600d3db425284e32b97b7ab1e15aea1b7 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Sun, 22 Nov 2026 15:05:26 +0100 Subject: [PATCH 08/14] fix(catalogue): give OSWorld1's runner the folder that holds the package The driver found that folder by going three folders up from the computer port's file. The port now sits one folder deeper, in protocols/, so the runner was started with the package's inside as its import path: its first import failed (No module named 'nullius'), and nullius/secrets.py stood in front of the standard library's. Every OSWorld1 unit run by an agent failed at setup; the controls and the Original setups start no runner. No test that runs without the upstream started the runner, so both suites stayed green. The folder is now asked of the package itself, and a test that needs no upstream starts a Python with the runner's import path. With the upstream's loop present (OSWORLD_DIR, OSWORLD_PYTHON), the 14 tests it gates give 13 passed, as on main; the one that fails, AgentSide.test_the_password_file_is_private_and_read_once, fails on main too. --- app/nullius/catalogue/benchmarks/osworld1/driver.py | 3 ++- app/tests/test_osworld1_entry_parts.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/app/nullius/catalogue/benchmarks/osworld1/driver.py b/app/nullius/catalogue/benchmarks/osworld1/driver.py index cba93655..2e73a49f 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/driver.py +++ b/app/nullius/catalogue/benchmarks/osworld1/driver.py @@ -430,7 +430,8 @@ def _option(name, default, kind): def _runner_env(): """The runner's environment: this driver's, its import path the upstream's folder and the nullius package's.""" - package = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(_port().__file__)))) + import nullius # asked of the package itself, wherever the port sits inside it + package = os.path.dirname(os.path.dirname(os.path.abspath(nullius.__file__))) return dict(os.environ, PYTHONPATH=os.pathsep.join([UP, package]), PYTHONIOENCODING="utf-8") diff --git a/app/tests/test_osworld1_entry_parts.py b/app/tests/test_osworld1_entry_parts.py index 6b1cdfe9..524a3fd7 100644 --- a/app/tests/test_osworld1_entry_parts.py +++ b/app/tests/test_osworld1_entry_parts.py @@ -231,6 +231,16 @@ def test_the_start_lock_is_shared_by_every_run_on_the_machine(self): env=dict(os.environ, TMPDIR=folder, NULLIUS_UPSTREAM=self.tmp)) self.assertEqual(got.stdout.strip(), "/tmp/nullius-osworld1-vm-start.lck", got.stderr[-2000:]) + def test_the_runners_import_path_holds_the_nullius_package_and_not_its_inside(self): + env = self.d._runner_env() + up, package = env["PYTHONPATH"].split(os.pathsep) + self.assertEqual(up, self.tmp) + code = "import secrets\nfrom nullius.standard.protocols import computer_port\nprint(secrets.__file__)\n" # as runner.py + got = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=60, cwd=self.tmp, + stdin=subprocess.DEVNULL, env={"PATH": os.environ["PATH"], "PYTHONPATH": env["PYTHONPATH"]}) + self.assertEqual(got.returncode, 0, got.stderr[-2000:]) + self.assertNotIn(os.path.join(package, ""), got.stdout) # the standard library's, not nullius/secrets.py + def test_an_already_reaped_runner_gets_no_signal(self): p = child("pass") p.wait() From 95cea1cacd73dc3afac1f8cd4406c0dedd3069ec Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Sun, 22 Nov 2026 15:05:26 +0100 Subject: [PATCH 09/14] fix: the shared file writer makes no folder and takes a name of any length Three things write_whole did that main's writers did not. It made a missing folder. Four writers refused one on main: a definition's save, a licence, a Harbor entry, the ledger. A proof that ended after its user entry was removed ("Use bundled entry") therefore brought the folder back holding the definition alone: the entry left the Benchmarks page and its own page answered 404. The folder is the caller's to make again: the nine callers that made theirs on main do, and a folder that is gone is an error, as it was. Its temporary name carried the file's own, so a file whose name was 217 to 255 bytes long could not be written: a migrated file, a judgement of a trial with a long name. The name is now as long for every file. It set the mode with fchmod even when the file already had it. Three files got 0600 from mkstemp alone on main (the constraints store, a Harbor entry, a judgement); where fchmod is refused they were written there and not here. The mode is set only when the umask took bits off, and a refusal no longer leaves a descriptor open. Tests hold each: a folder that is gone, a name as long as a name may be, a mode the umask leaves whole, a refused mode, the temporary file beside its path with its mode before the rename, and the mode of the three files. --- app/nullius/constraints.py | 4 ++- app/nullius/execution.py | 1 + app/nullius/harbor/source.py | 1 + app/nullius/judge/store.py | 1 + app/nullius/ondisk.py | 18 ++++++----- app/nullius/prices.py | 5 ++- app/nullius/providers.py | 4 ++- app/nullius/workspace.py | 3 ++ app/tests/test_catalogue_overlay.py | 12 ++++++++ app/tests/test_constraints.py | 1 + app/tests/test_harbor_entry.py | 1 + app/tests/test_judge.py | 1 + app/tests/test_ondisk.py | 48 +++++++++++++++++++++++++++-- 13 files changed, 87 insertions(+), 13 deletions(-) diff --git a/app/nullius/constraints.py b/app/nullius/constraints.py index d8699484..12be4382 100644 --- a/app/nullius/constraints.py +++ b/app/nullius/constraints.py @@ -627,7 +627,9 @@ def rekey(text: str, old: str, new: Optional[str]) -> Optional[str]: def _write(doc: dict, env=None) -> None: """The store, written whole to a file of its own, then renamed.""" - ondisk.write_whole(store_path(env), json.dumps(doc, indent=1, sort_keys=True), mode=0o600) + out = store_path(env) + os.makedirs(os.path.dirname(out), exist_ok=True) + ondisk.write_whole(out, json.dumps(doc, indent=1, sort_keys=True), mode=0o600) def engine_less(found: Optional[dict]) -> bool: diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 5c97e9c2..f2124627 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -497,6 +497,7 @@ def _save(self) -> None: "catalogue_on_target": self.catalogue_on_target, "workspace": self.workspace, "launched": self.launched, "seen_trials": [list(k) for k in sorted(self._seen_trials, key=str)]} try: + os.makedirs(self.dir, exist_ok=True) ondisk.write_whole(os.path.join(self.dir, RECORD), json.dumps(data, indent=1)) except OSError: pass diff --git a/app/nullius/harbor/source.py b/app/nullius/harbor/source.py index 326d0b7d..b0d8a7bf 100644 --- a/app/nullius/harbor/source.py +++ b/app/nullius/harbor/source.py @@ -444,6 +444,7 @@ def ensure(pin: dict, pins: str, run: Optional[Callable] = None, fetch: Optional def _write(directory: str, name: str, data: dict) -> None: + os.makedirs(directory, exist_ok=True) ondisk.write_whole(os.path.join(directory, name), json.dumps(data, indent=1)) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 6917cfe0..ce2be641 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -122,6 +122,7 @@ def save(ws_dir: str, job_id: str, trial_name: str, record: dict, lane: str = "d one file take turns; each writes through a temporary file of its own.""" paths = _paths(ws_dir, job_id, trial_name, lane) path = paths[0] + os.makedirs(os.path.dirname(path), exist_ok=True) with _lock(path): data = _read(paths) version = record.get("questions", Q.VERSION) diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py index c87d38ca..a653fea7 100644 --- a/app/nullius/ondisk.py +++ b/app/nullius/ondisk.py @@ -7,6 +7,7 @@ import contextlib import hashlib import os +import stat import uuid @@ -21,18 +22,21 @@ def write_whole(path, data, mode=None) -> None: FileNotFoundError, a 500 on the page. Whichever rename lands last wins, and both wrote a complete file. A write that fails leaves nothing behind. + The name is as long for every ``path``, so a file whose own name is as long + as a name may be is still written. + ``mode``: the file's permissions, from its first byte (0o600 for what only - its owner reads); this process's default when not given. The folder is made - when it is missing.""" + its owner reads); this process's default when not given. + + The folder is the caller's to make. A folder that is gone is an error, and + is not made again: a user entry removed while its proof ran stays removed.""" path = os.fspath(path) - folder = os.path.dirname(os.path.abspath(path)) - os.makedirs(folder, exist_ok=True) - part = os.path.join(folder, f".{os.path.basename(path)}.{uuid.uuid4().hex}.part") + part = os.path.join(os.path.dirname(os.path.abspath(path)), f".{uuid.uuid4().hex}.part") fd = os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode) try: - if mode is not None: - os.fchmod(fd, mode) # the mode asked for, whatever the umask with (os.fdopen(fd, "w", encoding="utf-8") if isinstance(data, str) else os.fdopen(fd, "wb")) as f: + if mode is not None and stat.S_IMODE(os.fstat(fd).st_mode) != mode: + os.fchmod(fd, mode) # the umask took bits off: the mode asked for, exactly f.write(data) os.replace(part, path) except BaseException: diff --git a/app/nullius/prices.py b/app/nullius/prices.py index e9be5055..efecae2d 100644 --- a/app/nullius/prices.py +++ b/app/nullius/prices.py @@ -29,6 +29,7 @@ import argparse import json +import os import time import urllib.request from typing import Callable, Dict, Iterable, Optional, Tuple @@ -76,7 +77,9 @@ def _number(v) -> bool: def save(doc: dict, env=None) -> None: """Written whole beside the file, then renamed: a reader never finds half a list.""" - ondisk.write_whole(path(env), json.dumps(doc, indent=1, sort_keys=True) + "\n") + out = path(env) + os.makedirs(os.path.dirname(out) or ".", exist_ok=True) + ondisk.write_whole(out, json.dumps(doc, indent=1, sort_keys=True) + "\n") def table(env=None) -> Dict[str, dict]: diff --git a/app/nullius/providers.py b/app/nullius/providers.py index 5ff8d036..03e7e4b5 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -584,7 +584,9 @@ def remember(results: dict, env=None) -> None: """Set (a result) or forget (None) the last test of each choice, the file written whole and renamed.""" with _TESTS_LOCK: kept = {k: v for k, v in {**tests(env), **results}.items() if v is not None} - ondisk.write_whole(_tests_file(env), json.dumps(kept, indent=1, sort_keys=True)) + out = _tests_file(env) + os.makedirs(os.path.dirname(out), exist_ok=True) + ondisk.write_whole(out, json.dumps(kept, indent=1, sort_keys=True)) def mark(result: dict) -> str: diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 96d01b60..3f798776 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -117,6 +117,7 @@ def _path(home_dir: str, name: str) -> str: def save(ws: Workspace) -> None: + os.makedirs(ws.dir, exist_ok=True) data = {k: v for k, v in asdict(ws).items() if k != "dir"} ondisk.write_whole(os.path.join(ws.dir, "workspace.json"), json.dumps(data, ensure_ascii=False, indent=1)) @@ -403,6 +404,7 @@ def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | No def _write_index(ws: Workspace, index: dict) -> None: + os.makedirs(ws.jobs_dir, exist_ok=True) ondisk.write_whole(_index_path(ws), json.dumps(index, ensure_ascii=False, indent=1)) @@ -428,6 +430,7 @@ def _read_cache(path: str, job_dir: str) -> tuple | None: def _write_cache(ws: Workspace, path: str, sig: str, head: str, job: parse.Job) -> None: + os.makedirs(ws.jobs_dir, exist_ok=True) ondisk.write_whole(path, json.dumps({"signature": sig, "head": head, "dir": job.dir, "cached": _now(), "job": job_to_dict(job)}, default=_encode, ensure_ascii=False)) diff --git a/app/tests/test_catalogue_overlay.py b/app/tests/test_catalogue_overlay.py index a55f6e44..af15cbbc 100644 --- a/app/tests/test_catalogue_overlay.py +++ b/app/tests/test_catalogue_overlay.py @@ -247,6 +247,18 @@ def test_proof_save_copies_bundle_and_preserves_other_version_and_files(self): self.assertEqual((path.parent / "template.toml").read_text(), "template contents") self.assertEqual(self.tree(self.bundle), before) + def test_a_proof_that_ends_after_use_bundled_does_not_bring_the_users_entry_back(self): + folder = self.definition(self.bundle, "agent", AGENT) + (folder / "agent.py").write_text("the agent") + definitions.save(definitions.get("agent", "bot"), lambda cur: cur.update(summary="proven once")) # copied whole + running = definitions.get("agent", "bot") # a second proof starts, on the user's copy + self.assertEqual(running["_here"], str(self.user / "agents" / "bot")) + storage.use_bundled("agents", "bot", str(self.bundle)) # meanwhile: Use bundled entry + with self.assertRaises(FileNotFoundError): + definitions.save(running, lambda cur: cur.update(summary="proven twice")) + self.assertFalse((self.user / "agents" / "bot").exists()) # not a folder holding the definition alone + self.assertEqual(definitions.get("agent", "bot")["_here"], str(folder)) + def test_flat_definition_save_and_explicit_fixture_save(self): self.definition(self.bundle, "capability", CAPABILITY) before = self.tree(self.bundle) diff --git a/app/tests/test_constraints.py b/app/tests/test_constraints.py index db1618f3..2886075d 100644 --- a/app/tests/test_constraints.py +++ b/app/tests/test_constraints.py @@ -303,6 +303,7 @@ def test_kept_per_machine(self): [t.start() for t in each]; [t.join() for t in each] self.assertEqual((failed, len(constraints.load(env))), ([], 24)) self.assertEqual([n for n in os.listdir(os.path.dirname(constraints.store_path(env))) if n.endswith(".part")], []) + self.assertEqual(os.stat(constraints.store_path(env)).st_mode & 0o777, 0o600) # its owner's alone constraints.save("local", {"enforced": ["cpus"]}, env); constraints.save("bench", {"enforced": []}, env) self.assertEqual(constraints.load(env)["local"]["enforced"], ["cpus"]) self.assertEqual(sorted(constraints.load(env))[:2], ["bench", "local"]) diff --git a/app/tests/test_harbor_entry.py b/app/tests/test_harbor_entry.py index d0b7279a..8b36884d 100644 --- a/app/tests/test_harbor_entry.py +++ b/app/tests/test_harbor_entry.py @@ -97,6 +97,7 @@ def test_the_form_becomes_an_entry_in_the_catalogues_shape(self): def test_saved_it_loads_and_passes_the_catalogue_checks(self): path = h.save(h.build(form()), self.root) self.assertEqual(path, os.path.join(self.root, "benchmarks", "code-bench", "benchmark.json")) + self.assertEqual(os.stat(path).st_mode & 0o777, 0o600) # its owner's alone cat = catalog.load(self.root) self.assertEqual(catalog.validate(cat), []) self.assertIn("code-bench", [b.key for b in cat.listed_benchmarks]) diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index 7df9052b..90944401 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -195,6 +195,7 @@ def test_save_load_merge_and_survive_a_reparse(self): store.save(self.ws.dir, "job-1", "task__abc/def", rec) path = Path(self.ws.dir) / "judgements" / "job-1" / (store.key("task__abc/def") + ".json") self.assertTrue(path.exists()); self.assertFalse((self.tmp / "jobs").exists()) # under the workspace, never the job tree + self.assertEqual(path.stat().st_mode & 0o777, 0o600) # its owner's alone self.assertEqual(store.load(self.ws.dir, "job-1", "task__abc/def")["answers"], {"task_completed": {"noul": 0.9}}) later = dict(rec, asked_at="2026-09-17T10:00:00Z", answers={"transcript_quality": {"score": 2.0, "legend": ["a", "b", "c"], "probabilities": {}, "confidence": 0.9}}) store.save(self.ws.dir, "job-1", "task__abc/def", later) diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index a18cec68..22eff73b 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -16,15 +16,15 @@ class Whole(unittest.TestCase): def setUp(self): self.tmp = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmp, True) - self.path = os.path.join(self.tmp, "deep", "file.json") + self.path = os.path.join(self.tmp, "file.json") def mode(self, path=None): return stat.S_IMODE(os.stat(path or self.path).st_mode) def left(self): - return sorted(os.listdir(os.path.dirname(self.path))) + return sorted(os.listdir(self.tmp)) - def test_text_and_bytes_land_whole_in_a_folder_made_for_them(self): + def test_text_and_bytes_land_whole(self): ondisk.write_whole(self.path, "é\nsecond line\n") with open(self.path, "rb") as f: self.assertEqual(f.read(), "é\nsecond line\n".encode()) @@ -43,6 +43,48 @@ def test_the_mode_is_the_process_default_unless_one_is_asked(self): ondisk.write_whole(self.path, "x", mode=0o644) self.assertEqual(self.mode(), 0o644) # the mode asked for, whatever the umask + def test_a_mode_the_umask_leaves_whole_is_the_files_from_its_creation(self): + with mock.patch.object(os, "fchmod", side_effect=PermissionError("no chmod here")): + ondisk.write_whole(self.path, "x", mode=0o600) # as mkstemp gives it: asked for when made, never set after + self.assertEqual(self.mode(), 0o600) + + def test_a_mode_that_is_refused_leaves_no_file_and_no_open_descriptor(self): + old = os.umask(0o027) + self.addCleanup(os.umask, old) + held = [] + def refuse(fd, mode): + held.append(fd) + raise PermissionError("no chmod here") + with mock.patch.object(os, "fchmod", refuse): + with self.assertRaises(PermissionError): + ondisk.write_whole(self.path, "x", mode=0o644) # the umask took a bit off: it has to be set + self.assertEqual(self.left(), []) + with self.assertRaises(OSError): + os.fstat(held[0]) + + def test_it_is_first_written_beside_its_path_under_a_name_of_its_own_with_its_mode(self): + seen, rename = [], os.replace + def spy(src, dst): + seen.append((os.path.dirname(src), os.path.basename(src), stat.S_IMODE(os.stat(src).st_mode))) + return rename(src, dst) + with mock.patch.object(os, "replace", spy): + ondisk.write_whole(self.path, "x", mode=0o600) + ondisk.write_whole(self.path, "y", mode=0o600) + self.assertEqual([s[0] for s in seen], [self.tmp, self.tmp]) # a rename within one folder, never across devices + self.assertNotEqual(seen[0][1], seen[1][1]) + self.assertEqual([s[2] for s in seen], [0o600, 0o600]) + + def test_a_file_whose_name_is_as_long_as_a_name_may_be_is_written(self): + path = os.path.join(self.tmp, "n" * os.pathconf(self.tmp, "PC_NAME_MAX")) + ondisk.write_whole(path, "x") + self.assertEqual(self.left(), [os.path.basename(path)]) + + def test_a_folder_that_is_gone_is_an_error_and_is_not_made_again(self): + gone = os.path.join(self.tmp, "gone") + with self.assertRaises(FileNotFoundError): + ondisk.write_whole(os.path.join(gone, "file.json"), "x") + self.assertEqual(self.left(), []) + def test_a_write_that_fails_leaves_the_file_as_it_was_and_nothing_beside_it(self): ondisk.write_whole(self.path, "kept") with mock.patch.object(os, "replace", side_effect=OSError("no rename")): From 7b76dfd933acc4a3a5520c0d6c7bb1d2c4276e40 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Sun, 22 Nov 2026 15:05:26 +0100 Subject: [PATCH 10/14] test(web): hold the run start's refusal on the two pages that gained it The Agents page's check and the Benchmarks page's proof refuse to start while a run of that name is going, since they start through execute.begin. Only the builder's route was tested for it. Both pages are now asked with such a run going: nothing starts, and the page comes back with the reason. The Agents test also counts one start, not at least one. --- app/ui_tests/test_agents.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index f62c6281..bbb7cd42 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -13,7 +13,7 @@ from contextlib import ExitStack from pathlib import Path from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import ANY, patch from nullius import execution from nullius.standard.contract import definitions @@ -332,11 +332,19 @@ def test_check_starts_the_kits_as_a_run_here(self): headers={"Origin": "http://localhost"}) self.addCleanup(r.close) self.assertEqual(r.status_code, 302) - plan = self.started[0] + (plan,) = self.started # started once self.assertEqual((plan.runner, plan.host, plan.key_var), ("standard", None, "OPENAI_API_KEY")) self.assertIn("conform fake --model gpt-5-mini --provider openai --stamp ", plan.script) self.assertNotIn("sk-test", plan.script) self.assertTrue(r.headers["Location"].endswith("/job/" + plan.jobs[0]["name"])) + going = SimpleNamespace(plan=SimpleNamespace(name=ANY), state="running") # a run of that very name, still going + with patch.dict(execution.EXECUTIONS, {"going": going}): + r = self.client.post("/agents/fake/check", data={"csrf": self.csrf(), "provider": "openai", "model": "gpt-5-mini", "unsandboxed": "yes"}, + headers={"Origin": "http://localhost"}) + self.addCleanup(r.close) + self.assertEqual((r.status_code, r.headers["Location"], len(self.started)), (302, "/agents/fake", 1)) # back to its page, nothing started + with self.client.session_transaction() as s: + self.assertTrue(any(kind == "error" and said.endswith(" is running already") for kind, said in s["_flashes"]), s["_flashes"]) def test_container_checks_require_an_engine_and_record_the_backend(self): from web import execute @@ -698,6 +706,13 @@ def test_prove_it_starts_cli_prove_here_handed_no_key(self): r = self.client.post("/benchmarks/gsm8k/prove", data={"dataset": "test"}); self.addCleanup(r.close) self.assertEqual(r.status_code, 403) # no form token self.assertEqual(len(self.started), 1) + going = SimpleNamespace(plan=SimpleNamespace(name=ANY), state="running") # a run of that very name, still going + with patch.dict(execution.EXECUTIONS, {"going": going}): + r = self.client.post("/benchmarks/gsm8k/prove", data={"csrf": csrf, "dataset": "test", "limit": "2"}, headers={"Origin": "http://localhost"}) + self.addCleanup(r.close) + self.assertEqual((r.status_code, r.headers["Location"], len(self.started)), (302, "/benchmarks/gsm8k#standard", 1)) # back to its page, nothing started + with self.client.session_transaction() as s: + self.assertTrue(any(kind == "error" and said.endswith(" is running already") for kind, said in s["_flashes"]), s["_flashes"]) if __name__ == "__main__": From 732e5e738ee39d6d6e4f0409ec54ff08ea112a26 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Sun, 22 Nov 2026 15:05:26 +0100 Subject: [PATCH 11/14] docs(standard): give five comments the moved modules' addresses standard.ledger and standard.relay are calls.ledger and calls.relay, and standard.retries is runner.retries. Three folder docstrings say what they left out: proofs/ also holds a check that proves nothing (pins), egress is also an agent's way to the public web, and requirements/ says how it differs from nullius.prerequisites. --- app/nullius/providers.py | 2 +- app/nullius/runs/classify.py | 4 ++-- app/nullius/standard/backends/__init__.py | 9 +++++---- app/nullius/standard/pages/recipe.py | 4 ++-- app/nullius/standard/proofs/__init__.py | 5 +++-- app/nullius/standard/requirements/__init__.py | 3 +++ app/tests/test_classify.py | 2 +- 7 files changed, 17 insertions(+), 12 deletions(-) diff --git a/app/nullius/providers.py b/app/nullius/providers.py index 03e7e4b5..e7bc8063 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -451,7 +451,7 @@ def decision_models(env=None, *, fetch: bool = True, opener=None, clock=time.tim # A model OpenRouter serves: its maker, a slash, its name (a variant after a colon: ``:free``). _ROUTED = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._:-]*") -# A serving provider's slug, as ``--served-by`` takes it (``standard.relay.SLUG``). +# A serving provider's slug, as ``--served-by`` takes it (``standard.calls.relay.SLUG``). _SLUG = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*(?:/[A-Za-z0-9._-]+)*") diff --git a/app/nullius/runs/classify.py b/app/nullius/runs/classify.py index 8346df4f..bbfcb37d 100644 --- a/app/nullius/runs/classify.py +++ b/app/nullius/runs/classify.py @@ -25,7 +25,7 @@ API_ERROR = "api_error" SETUP_ERROR = "setup_error" # The run's own spending cap refused a model call the unit needed (the -# standard's relay, ``standard.ledger``): the unit was cut off. Nothing +# standard's relay, ``standard.calls.ledger``): the unit was cut off. Nothing # failed, and no attempt was had: the money ran out, by the user's own word. SPENDING_CAP = "spending_cap" CANCELLED = "cancelled" @@ -66,7 +66,7 @@ "networkconnectionerror", # DNS, refused connection, TLS — transport, not skill "unknownapierror", # Harbor's own "some provider error"; an ApiError without the prefix } -# What a unit the run's spending cap cut off carries (``standard.ledger.ERROR``): recorded by the relay that +# What a unit the run's spending cap cut off carries (``standard.calls.ledger.ERROR``): recorded by the relay that # refused the call, never inferred. _CAP_EXCEPTION = "spendingcaperror" diff --git a/app/nullius/standard/backends/__init__.py b/app/nullius/standard/backends/__init__.py index 3696529b..5f9d4f31 100644 --- a/app/nullius/standard/backends/__init__.py +++ b/app/nullius/standard/backends/__init__.py @@ -5,10 +5,11 @@ one. ``boat`` runs each unit's agent or capability in a boat.dev VM of its own, its relay still on this machine. The rest is what crosses a container's boundary, one address at a time: ``forward`` (a licence server, or a server on -the machine), ``egress`` (an own image's check, to public addresses only), -``mcp_machine`` and ``mcp_bridge`` (a benchmark's MCP server run on the -machine, and the agent's bridge to it) and ``web_services`` (the HTTP fixtures -a driver's setup declares). +the machine), ``egress`` (public addresses only: an own image's check, or an +agent whose environment declares public web access), ``mcp_machine`` and +``mcp_bridge`` (a benchmark's MCP server run on the machine, and the agent's +bridge to it) and ``web_services`` (the HTTP fixtures a driver's setup +declares). ``forward.py``, ``egress.py`` and ``mcp_bridge.py`` are each mounted alone into a container and run there: they import nothing of this application, and diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 085b636c..fb3263d6 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -414,7 +414,7 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, key, and there the programs that reach a VM (a host's are its prerequisites); ``boat_size_problem``, why the account cannot start a VM of the size. - ``max_usd``: the run's spending cap (``standard.ledger``), one amount for + ``max_usd``: the run's spending cap (``calls.ledger``), one amount for the whole run: its jobs that call a model - each dataset with each participant, on each machine - take equal shares (``--max-usd``), so none spends another's and the amount typed is the most the run spends. @@ -609,7 +609,7 @@ def add(step, message, shown=False): repeat = 1 if lb and repeat < lb.get("repeat", 1): add("limits", f"Like the leaderboard runs each {(b.get('units') or {}).get('noun', 'unit')} at least {lb['repeat']} times.") - # each attempt run again up to N times when it ends in a failure a further try may mend (standard.retries) + # each attempt run again up to N times when it ends in a failure a further try may mend (runner.retries) retries = 0 if recipe.get("retries") in (None, "") else _int(recipe.get("retries"), 0, MAX_RETRIES) if retries is None: add("limits", f"Retries per attempt: a whole number from 0 to {MAX_RETRIES}.") diff --git a/app/nullius/standard/proofs/__init__.py b/app/nullius/standard/proofs/__init__.py index bf51bb9e..18a3c52d 100644 --- a/app/nullius/standard/proofs/__init__.py +++ b/app/nullius/standard/proofs/__init__.py @@ -1,7 +1,8 @@ -"""What is proven before it is offered. +"""What is proven, or checked, before it is offered. ``conform`` runs a port's kit against an agent or a capability. ``fidelity`` compares an agent driven over ACP with its own CLI. ``prove`` runs a benchmark's controls and checks. ``pins`` compares a benchmark's image pins -with their registry tags. The kits themselves are in ``standard/kits/``. +with their registry tags, and writes nothing. The kits themselves are in +``standard/kits/``. """ diff --git a/app/nullius/standard/requirements/__init__.py b/app/nullius/standard/requirements/__init__.py index 2571a8a5..6ba3eced 100644 --- a/app/nullius/standard/requirements/__init__.py +++ b/app/nullius/standard/requirements/__init__.py @@ -5,4 +5,7 @@ ``STANDARD_DIR``, once. ``hostreq`` checks the programs and the GPU memory a benchmark's ``host`` asks for, and says the commands that install them. ``network_requirements`` checks the public web access an environment declares. + +What Review asks of each machine before Run is ``nullius.prerequisites``, one +row per need; it asks ``hostreq`` here. """ diff --git a/app/tests/test_classify.py b/app/tests/test_classify.py index 960f2a2b..2cb66ffd 100644 --- a/app/tests/test_classify.py +++ b/app/tests/test_classify.py @@ -92,7 +92,7 @@ def test_both_boards_charge_the_infrastructure_as_the_classifier_does(self): self.assertIn(outcome(name), ("agent_error", "timeout")) def test_a_unit_the_runs_spending_cap_cut_off_has_its_own_outcome_outside_the_rate_on_both(self): - """The standard's own: its relay refused the call (``standard.ledger``), so the unit had no attempt. + """The standard's own: its relay refused the call (``standard.calls.ledger``), so the unit had no attempt. Not an API error: nothing failed. The live feed's word for it is ``budget``.""" from nullius.standard.calls import ledger from nullius.standard.runner import job From 014a86e46abbc8b689fa12662f8c66c7b1e9e9ff Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Sun, 22 Nov 2026 16:00:55 +0100 Subject: [PATCH 12/14] test(standard): keep modules in folders and folders importing one way main added five modules loose at the top of the package in five days. A test now keeps the sorting: only the cli and the kits sit at the top, and no folder imports one that imports it, at a module's top or inside a function. It reads the sources and imports none of them. One pair of folders imported each other: contract/definitions asked requirements/network_requirements for the check of an environment's network field, and requirements/install imports definitions. The check, twelve lines, moves beside the other field checks in definitions, where the host check already is; network_requirements keeps the connectivity check a run makes before its first unit. Same messages, same test cases. --- AGENTS.md | 5 +- app/nullius/standard/__init__.py | 3 + app/nullius/standard/contract/definitions.py | 19 ++++++- .../requirements/network_requirements.py | 14 ----- app/tests/test_layering.py | 55 ++++++++++++++++++- app/tests/test_network_requirements.py | 4 +- 6 files changed, 78 insertions(+), 22 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index db4fa865..3b2cecfc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,9 +62,10 @@ and its resources. The source layout stays under `app/`. `harbor/` (`source`: the Harbor a recipe pins - built, kept, scanned for its agents; `feed`: the live feed any Harbor writes, from its own trial hooks), `importers/` (`atif` ATIF, `otel` OpenTelemetry, and the `cli`), `judge/` (`questions`, `state`, `client`, `store`, `batch`, `reconcile`, `lanes`), - `standard/` (the Nullius standard, `docs/standard.md`, one folder per purpose: + `standard/` (the Nullius standard, `docs/standard.md`, one folder per purpose, a new module in the folder of its purpose + and the folders importing one way, which `test_layering.StandardFolders` checks: `contract/`: `ports`, `names` (capability vocabulary and legacy aliases), `definitions` (with an agent's or capability's versions), `match`; - `requirements/`, what a run needs of the machine: `install`, `hostreq` (what a benchmark's options need of the machine its driver runs on: the check and the install), `network_requirements` (an environment's declared public web access: the schema and the connectivity check); + `requirements/`, what a run needs of the machine: `install`, `hostreq` (what a benchmark's options need of the machine its driver runs on: the check and the install), `network_requirements` (an environment's declared public web access: the connectivity check before any unit); `protocols/`: `jsonl`, `acp`, `cancellation` (interruptible protocol waits), `computer_port` and `computer_pipe` (the computer port's MCP server, served by a desktop benchmark's runner over the benchmark's own loop, and the session's stdio pipe to it); `calls/`: `relay`, `ledger` (a run's spending cap); `backends/`: `container` (the container backend), `boat` (the boat backend: each unit's agent in a boat.dev VM), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `egress` (an own image's check's proxy to public addresses); diff --git a/app/nullius/standard/__init__.py b/app/nullius/standard/__init__.py index 102acc84..8314cb87 100644 --- a/app/nullius/standard/__init__.py +++ b/app/nullius/standard/__init__.py @@ -21,4 +21,7 @@ fidelity, a benchmark's controls) and ``pages`` (the builder's recipe, the How to add steps). ``cli`` is the shell command over all of them; ``kits/`` holds the conformance kits, each a benchmark. + +A new module goes in the folder of its purpose, not beside ``cli``, and no +folder imports one that imports it (``tests/test_layering.py``). """ diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 61ba3e26..087f6db1 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -91,6 +91,7 @@ import os import re from typing import Callable, Dict, List, Optional, Tuple +from urllib.parse import urlsplit from nullius.standard.contract import ports from nullius import ondisk, paths @@ -963,8 +964,7 @@ def _environments(envs, here: Optional[str]) -> List[str]: if "local_ok" in e and not isinstance(e["local_ok"], bool): bad.append(f"{w}.local_ok: true or false") if "network" in e: - from ..requirements import network_requirements - bad += [f"{w}.{message}" for message in network_requirements.problems(e["network"])] + bad += [f"{w}.{message}" for message in _network(e["network"])] bad += _secrets(w, e.get("needs_secrets"), bool(e.get("local_ok")), settings) kinds: Dict[str, set] = {} sources: Dict[str, set] = {} @@ -980,6 +980,21 @@ def _environments(envs, here: Optional[str]) -> List[str]: return bad +def _network(value) -> List[str]: + """An environment's ``network``: public web access for its agents, with the HTTPS URL a run + asks before its first unit (``requirements.network_requirements``).""" + if not isinstance(value, dict) or set(value) != {"access", "probe"}: + return ["network: {access: public, probe: an HTTPS URL}"] + try: + u = urlsplit(value["probe"]) + valid = (value["access"] == "public" and u.scheme == "https" and u.hostname + and not u.username and not u.password and not u.query and not u.fragment + and u.port in (None, 443)) + except (TypeError, ValueError, AttributeError): + valid = False + return [] if valid else ["network: public access with an HTTPS probe URL without credentials, query or fragment"] + + def _secrets(w: str, secrets, local_ok: bool, settings) -> List[str]: """An environment's ``needs_secrets``: [{name, to, kind?, summary?, path?, env?, provider?}]. ``kind`` (``value`` when unsaid): a ``value`` reaches its diff --git a/app/nullius/standard/requirements/network_requirements.py b/app/nullius/standard/requirements/network_requirements.py index 32561108..9b5c0ed3 100644 --- a/app/nullius/standard/requirements/network_requirements.py +++ b/app/nullius/standard/requirements/network_requirements.py @@ -3,23 +3,9 @@ Original setups and controls are separate protocols. A reachable HTTPS probe proves connectivity, not that an agent can search, browse or interpret media. """ -from urllib.parse import urlsplit from urllib.request import Request, urlopen -def problems(value): - if not isinstance(value, dict) or set(value) != {"access", "probe"}: - return ["network: {access: public, probe: an HTTPS URL}"] - try: - u = urlsplit(value["probe"]) - valid = (value["access"] == "public" and u.scheme == "https" and u.hostname - and not u.username and not u.password and not u.query and not u.fragment - and u.port in (None, 443)) - except (TypeError, ValueError, AttributeError): - valid = False - return [] if valid else ["network: public access with an HTTPS probe URL without credentials, query or fragment"] - - def required(bench, other): if other.get("_kind") != "agent": return [] diff --git a/app/tests/test_layering.py b/app/tests/test_layering.py index 2463a9ba..f64f2c88 100644 --- a/app/tests/test_layering.py +++ b/app/tests/test_layering.py @@ -1,5 +1,7 @@ -"""The backend imports no Flask: it is exercisable from a bare shell or a notebook -(AGENTS.md, Core Architecture).""" +"""Where code sits. The backend imports no Flask: it is exercisable from a bare shell or a +notebook (AGENTS.md, Core Architecture). The standard's modules sit in one folder per purpose, +and its folders import one way.""" +import ast import pathlib import unittest @@ -21,5 +23,54 @@ def test_no_backend_module_imports_the_web_stack(self): self.assertEqual(offenders, {}) +class StandardFolders(unittest.TestCase): + """``nullius/standard/`` is one folder per purpose; its ``__init__`` says what each is for.""" + + def setUp(self): + self.root = pathlib.Path(nullius.__file__).parent / "standard" + self.folders = sorted(d.name for d in self.root.iterdir() if (d / "__init__.py").is_file()) + self.assertGreater(len(self.folders), 5) + + def test_only_the_cli_and_the_kits_sit_at_the_top(self): + where = "a module of the standard goes in the folder of its purpose: " + ", ".join(self.folders) + self.assertEqual(sorted(p.name for p in self.root.glob("*.py")), ["__init__.py", "cli.py"], where) + beside = sorted(d.name for d in self.root.iterdir() if d.is_dir() and d.name not in self.folders + ["__pycache__"]) + self.assertEqual(beside, ["kits"], "a folder of modules is a package: it has an __init__.py that says what it is for") + + def named(self, node, folder): + """The folders an import statement in a module of ``folder`` names.""" + if isinstance(node, ast.Import): + names = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom): + # .x is this folder's, ..x the standard's, ...x the backend's + package = ["nullius", "standard", folder][:4 - node.level] if node.level else [] + base = ".".join(package + ([node.module] if node.module else [])) + names = [base] + [f"{base}.{a.name}" for a in node.names] + else: + return set() + parts = [n.split(".") for n in names] + return {p[2] for p in parts if p[:2] == ["nullius", "standard"] and len(p) > 2 and p[2] in self.folders} + + def test_the_folders_import_one_way(self): + """No folder imports one that imports it, at a module's top or inside a function, directly or + through others: each has what it uses below it, and a reader can take them in that order.""" + lines = {} # (a folder, the folder it imports) -> where + for folder in self.folders: + for path in sorted((self.root / folder).glob("*.py")): + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + for other in self.named(node, folder) - {folder}: + lines.setdefault((folder, other), []).append(f"{folder}/{path.name}:{node.lineno}") + self.assertGreater(len(lines), 10) + left = set(self.folders) # a folder that imports none of those left, or that + while True: # none of them imports, is taken away, again and + free = {f for f in left if not any(a == f and b in left for a, b in lines) # again: what stays is a circle + or not any(b == f and a in left for a, b in lines)} + if not free: + break + left -= free + circle = {f"{a} imports {b}": where for (a, b), where in sorted(lines.items()) if a in left and b in left} + self.assertEqual(circle, {}, "folders of the standard that import each other") + + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_network_requirements.py b/app/tests/test_network_requirements.py index f6f215db..58f43fef 100644 --- a/app/tests/test_network_requirements.py +++ b/app/tests/test_network_requirements.py @@ -20,12 +20,12 @@ def setUp(self): self.agent = {'_kind': 'agent'} def test_schema_rejects_missing_unknown_and_credential_fields(self): - self.assertEqual(net.problems(self.bench['environments']['web']['network']), []) + self.assertEqual(definitions._network(self.bench['environments']['web']['network']), []) for value in ('public', {}, {'access': 'private', 'probe': 'https://example.org/'}, {'access': 'public', 'probe': 'http://example.org/'}, {'access': 'public', 'probe': 'https://user:secret@example.org/'}, {'access': 'public', 'probe': 'https://example.org/?token=secret'}): - self.assertTrue(net.problems(value), value) + self.assertTrue(definitions._network(value), value) def test_a_container_run_is_refused_before_any_task_when_the_public_web_is_unreachable(self): opener = Mock(side_effect=OSError('offline')) From 16384237891b315045e6a105f4957a52b11316e4 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 23 Nov 2026 02:11:35 +0100 Subject: [PATCH 13/14] docs: cut this branch's comments to what changes what a reader does Each folder's description keeps its first line and the one constraint that binds a reader. ondisk, the reader's four modules, the layering test and a few test comments lose what restated a name or a line. Comments and docstrings only. --- .claude/rules/traces.md | 5 ++- AGENTS.md | 7 ++-- app/nullius/ondisk.py | 34 +++++-------------- app/nullius/standard/__init__.py | 14 ++------ app/nullius/standard/backends/__init__.py | 17 ++-------- app/nullius/standard/calls/__init__.py | 7 +--- app/nullius/standard/contract/__init__.py | 8 +---- app/nullius/standard/contract/definitions.py | 3 +- app/nullius/standard/pages/__init__.py | 8 +---- app/nullius/standard/proofs/__init__.py | 9 +---- app/nullius/standard/protocols/__init__.py | 9 ++--- app/nullius/standard/requirements/__init__.py | 9 +---- app/nullius/standard/runner/__init__.py | 12 +------ app/nullius/traces/breakdown.py | 8 +---- app/nullius/traces/fold.py | 8 +---- app/nullius/traces/spans.py | 14 +------- app/nullius/traces/trace.py | 4 +-- app/nullius/traces/waterfall.py | 5 +-- app/tests/test_catalogue_overlay.py | 4 +-- app/tests/test_constraints.py | 2 +- app/tests/test_harbor_entry.py | 2 +- app/tests/test_judge.py | 2 +- app/tests/test_layering.py | 19 +++++------ app/tests/test_ondisk.py | 15 ++++---- app/ui_tests/test_agents.py | 6 ++-- app/ui_tests/test_run_routes.py | 4 +-- app/web/execute.py | 5 ++- 27 files changed, 60 insertions(+), 180 deletions(-) diff --git a/.claude/rules/traces.md b/.claude/rules/traces.md index 7f4c1192..c0c645f0 100644 --- a/.claude/rules/traces.md +++ b/.claude/rules/traces.md @@ -1,8 +1,7 @@ ## Traces, as this application renders them -The reader itself is `app/nullius/traces/trace.py`, with the span tree and its -grouping in `spans.py`, the folding in `fold.py`, the time accounting in -`breakdown.py` and the waterfall's layout in `waterfall.py`. +The reader itself is `app/nullius/traces/trace.py`, with `spans.py` (the span tree, +grouping), `fold.py`, `breakdown.py` (time accounting) and `waterfall.py` (layout). Four things about a rendered trace are load-bearing: diff --git a/AGENTS.md b/AGENTS.md index cd63b7f0..addc492a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,7 +47,7 @@ and its resources. `feasibility`, `launches`, `verifier` - a verifier's report read by its benchmark's report block - `attempts`, a task's attempts in one job with their pass count and pass@k, and the `cli`), `traces/` (`trace`, the reader, with its span tree `spans`, - its `fold`, its time accounting `breakdown` and its layout `waterfall`; `trajectory`, + `fold`, time accounting `breakdown` and layout `waterfall`; `trajectory`, `conversation`, `charts`, `behavior`, `otel`), `compare/` (`comparison` and its `cli`), `catalogue/` (`catalog`, which loads one folder per benchmark under `catalogue/benchmarks/`, named by its key: its `benchmark.json` with its @@ -60,10 +60,9 @@ and its resources. `harbor/` (`source`: the Harbor a recipe pins - built, kept, scanned for its agents; `feed`: the live feed any Harbor writes, from its own trial hooks), `importers/` (`atif` ATIF, `otel` OpenTelemetry, and the `cli`), `judge/` (`questions`, `state`, `client`, `store`, `batch`, `reconcile`, `lanes`), - `standard/` (the Nullius standard, `docs/standard.md`, one folder per purpose, a new module in the folder of its purpose - and the folders importing one way, which `test_layering.StandardFolders` checks: + `standard/` (the Nullius standard, `docs/standard.md`, one folder per purpose, importing one way: `test_layering.StandardFolders`; `contract/`: `ports`, `names` (capability vocabulary and legacy aliases), `definitions` (with an agent's or capability's versions), `match`; - `requirements/`, what a run needs of the machine: `install`, `hostreq` (what a benchmark's options need of the machine its driver runs on: the check and the install), `network_requirements` (an environment's declared public web access: the connectivity check before any unit); + `requirements/`: `install`, `hostreq` (what a benchmark's options need of the machine its driver runs on: the check and the install), `network_requirements` (an environment's declared public web access: the connectivity check before any unit); `protocols/`: `jsonl`, `acp`, `cancellation` (interruptible protocol waits), `computer_port` and `computer_pipe` (the computer port's MCP server, served by a desktop benchmark's runner over the benchmark's own loop, and the session's stdio pipe to it); `calls/`: `relay`, `ledger` (a run's spending cap); `backends/`: `container` (the container backend), `boat` (the boat backend: each unit's agent in a boat.dev VM), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `egress` (an own image's check's proxy to public addresses); diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py index a653fea7..87b11c80 100644 --- a/app/nullius/ondisk.py +++ b/app/nullius/ondisk.py @@ -1,7 +1,4 @@ -"""A file written whole, a file held by one process at a time, a file's digest. - -Three things many modules need, each done here once. Standard library only. -""" +"""A file written whole, a lock, a digest.""" from __future__ import annotations import contextlib @@ -12,31 +9,18 @@ def write_whole(path, data, mode=None) -> None: - """``data``, text or bytes, as the whole of ``path`` - or ``path`` left as it was. - - It is written under a name of its own beside ``path``, then renamed over it: - a reader never finds half a file. The name is this write's alone, because two - writers of one file at once are ordinary here (a job's page and its live poll - both re-parse a job whose files keep changing): with one shared temporary - name the first rename took the file away and the second raised - FileNotFoundError, a 500 on the page. Whichever rename lands last wins, and - both wrote a complete file. A write that fails leaves nothing behind. - - The name is as long for every ``path``, so a file whose own name is as long - as a name may be is still written. - - ``mode``: the file's permissions, from its first byte (0o600 for what only - its owner reads); this process's default when not given. + """``data``, text or bytes, as the whole of ``path``, or ``path`` left as it was. - The folder is the caller's to make. A folder that is gone is an error, and - is not made again: a user entry removed while its proof ran stays removed.""" + Written beside ``path`` under a name of this write's own, then renamed over it: + of two writers at once, each writes a complete file and the last rename wins. + ``mode`` holds from the first byte. The folder is the caller's to make.""" path = os.fspath(path) part = os.path.join(os.path.dirname(os.path.abspath(path)), f".{uuid.uuid4().hex}.part") fd = os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode) try: with (os.fdopen(fd, "w", encoding="utf-8") if isinstance(data, str) else os.fdopen(fd, "wb")) as f: if mode is not None and stat.S_IMODE(os.fstat(fd).st_mode) != mode: - os.fchmod(fd, mode) # the umask took bits off: the mode asked for, exactly + os.fchmod(fd, mode) # the umask took bits off f.write(data) os.replace(part, path) except BaseException: @@ -47,9 +31,8 @@ def write_whole(path, data, mode=None) -> None: @contextlib.contextmanager def locked(path): - """One holder of ``path`` at a time, across processes: taken on the way in, - given back on the way out. The file is the lock alone and holds nothing.""" - import fcntl # POSIX; the pages import this module and take no lock + """One holder of ``path`` at a time, across processes. The file holds nothing.""" + import fcntl # POSIX only: imported where the lock is taken with open(path, "a") as f: fcntl.flock(f, fcntl.LOCK_EX) try: @@ -59,7 +42,6 @@ def locked(path): def sha256_of(path) -> str: - """The sha256 of a file's bytes, read a piece at a time.""" digest = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): diff --git a/app/nullius/standard/__init__.py b/app/nullius/standard/__init__.py index 8314cb87..1c21c471 100644 --- a/app/nullius/standard/__init__.py +++ b/app/nullius/standard/__init__.py @@ -13,15 +13,7 @@ Harbor's shape (``runner.job``) that the rest of the application reads unchanged. ``docs/standard.md`` is the design. -One folder per purpose: ``contract`` (what a definition may say, which pairs fit), -``requirements`` (what a run needs of the machine), ``protocols`` (ACP, JSON -lines, the computer port's server), ``calls`` (the relay and the spending cap), -``backends`` (a container or a Boat VM for each unit, and the doors through a -container), ``runner`` (a run, on one machine or several), ``proofs`` (kits, -fidelity, a benchmark's controls) and ``pages`` (the builder's recipe, the How -to add steps). ``cli`` is the shell command over all of them; ``kits/`` holds the -conformance kits, each a benchmark. - -A new module goes in the folder of its purpose, not beside ``cli``, and no -folder imports one that imports it (``tests/test_layering.py``). +One folder per purpose, its ``__init__`` saying which. A new module goes in a +folder, not beside ``cli``, and no folder imports one that imports it +(``tests/test_layering.py``). """ diff --git a/app/nullius/standard/backends/__init__.py b/app/nullius/standard/backends/__init__.py index 5f9d4f31..9995179f 100644 --- a/app/nullius/standard/backends/__init__.py +++ b/app/nullius/standard/backends/__init__.py @@ -1,17 +1,6 @@ """Where a unit runs when not among this machine's processes, and the doors through. -``container`` runs each unit's agent or capability in a container of its own, -its relay beside it; ``setup_container`` runs an Original setup's driver in -one. ``boat`` runs each unit's agent or capability in a boat.dev VM of its -own, its relay still on this machine. The rest is what crosses a container's -boundary, one address at a time: ``forward`` (a licence server, or a server on -the machine), ``egress`` (public addresses only: an own image's check, or an -agent whose environment declares public web access), ``mcp_machine`` and -``mcp_bridge`` (a benchmark's MCP server run on the machine, and the agent's -bridge to it) and ``web_services`` (the HTTP fixtures a driver's setup -declares). - -``forward.py``, ``egress.py`` and ``mcp_bridge.py`` are each mounted alone into -a container and run there: they import nothing of this application, and -``container`` and ``mcp_machine`` find them beside themselves. +``forward.py``, ``egress.py`` and ``mcp_bridge.py`` are each mounted alone into a +container: they import nothing of this application, and ``container`` and +``mcp_machine`` find them beside themselves. """ diff --git a/app/nullius/standard/calls/__init__.py b/app/nullius/standard/calls/__init__.py index 5bd24ead..ad5f4b4a 100644 --- a/app/nullius/standard/calls/__init__.py +++ b/app/nullius/standard/calls/__init__.py @@ -1,6 +1 @@ -"""A run's model calls: relayed, recorded, capped. - -``relay`` is the model endpoint every agent, driver and capability of a run is -given: it holds the key and records each call. ``ledger`` is the run's spending -cap, the one file every relay of a job books its calls in. -""" +"""A run's model calls: relayed, recorded, capped.""" diff --git a/app/nullius/standard/contract/__init__.py b/app/nullius/standard/contract/__init__.py index e9b008c3..444fc90b 100644 --- a/app/nullius/standard/contract/__init__.py +++ b/app/nullius/standard/contract/__init__.py @@ -1,7 +1 @@ -"""The contract: what a definition may say, and which pairs fit. - -``ports`` names each port of version 1 and the kit that proves it, ``names`` the -canonical vocabulary and the earlier names still read, ``definitions`` the three -definition files - a benchmark's, an agent's, a capability's - with what each -may say, and ``match`` which pairs fit and why the others do not. -""" +"""The contract: what a definition may say, and which pairs fit.""" diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index b3da7dfb..4e919433 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -987,8 +987,7 @@ def _environments(envs, here: Optional[str]) -> List[str]: def _network(value) -> List[str]: - """An environment's ``network``: public web access for its agents, with the HTTPS URL a run - asks before its first unit (``requirements.network_requirements``).""" + """An environment's ``network``, which ``requirements.network_requirements`` asks before a run's first unit.""" if not isinstance(value, dict) or set(value) != {"access", "probe"}: return ["network: {access: public, probe: an HTTPS URL}"] try: diff --git a/app/nullius/standard/pages/__init__.py b/app/nullius/standard/pages/__init__.py index ed85f282..6e0ea2ac 100644 --- a/app/nullius/standard/pages/__init__.py +++ b/app/nullius/standard/pages/__init__.py @@ -1,7 +1 @@ -"""The standard as the application's pages show it. - -``recipe`` gives the run builder its choices and compiles a recipe into the -command a run starts with, and the check or proof an Agents, Capabilities or -Benchmarks page starts. ``howto`` is the How to add steps of the Agents and -Capabilities tabs. -""" +"""The standard as the application's pages show it.""" diff --git a/app/nullius/standard/proofs/__init__.py b/app/nullius/standard/proofs/__init__.py index 18a3c52d..0fb6bd81 100644 --- a/app/nullius/standard/proofs/__init__.py +++ b/app/nullius/standard/proofs/__init__.py @@ -1,8 +1 @@ -"""What is proven, or checked, before it is offered. - -``conform`` runs a port's kit against an agent or a capability. ``fidelity`` -compares an agent driven over ACP with its own CLI. ``prove`` runs a -benchmark's controls and checks. ``pins`` compares a benchmark's image pins -with their registry tags, and writes nothing. The kits themselves are in -``standard/kits/``. -""" +"""What is proven, or checked, before it is offered.""" diff --git a/app/nullius/standard/protocols/__init__.py b/app/nullius/standard/protocols/__init__.py index 5b03b197..4ff622be 100644 --- a/app/nullius/standard/protocols/__init__.py +++ b/app/nullius/standard/protocols/__init__.py @@ -1,10 +1,5 @@ """How the programs of a run speak to each other. -``acp`` is the ACP client that drives an agent. ``jsonl`` is the JSON lines a -benchmark's driver and a capability are spoken to in, and ``serve``, the other -side, for one written in Python. ``cancellation`` is the wait both give up when -their run stops. ``computer_port`` is the computer port's MCP server, which a -desktop benchmark's runner serves over its own loop, and ``computer_pipe`` the -stdio server an agent's session starts to reach it, found beside it; neither -imports anything of this application. +``computer_port`` and ``computer_pipe`` run in a benchmark's own Python: they +import nothing of this application. """ diff --git a/app/nullius/standard/requirements/__init__.py b/app/nullius/standard/requirements/__init__.py index 6ba3eced..aa3a573a 100644 --- a/app/nullius/standard/requirements/__init__.py +++ b/app/nullius/standard/requirements/__init__.py @@ -1,11 +1,4 @@ """What a run needs of the machine before its first unit. -``install`` puts what a definition names - an agent's or a capability's -packages, a driver's environment, an upstream, a dataset - under -``STANDARD_DIR``, once. ``hostreq`` checks the programs and the GPU memory a -benchmark's ``host`` asks for, and says the commands that install them. -``network_requirements`` checks the public web access an environment declares. - -What Review asks of each machine before Run is ``nullius.prerequisites``, one -row per need; it asks ``hostreq`` here. +Review's rows are ``nullius.prerequisites``, which asks ``hostreq`` here. """ diff --git a/app/nullius/standard/runner/__init__.py b/app/nullius/standard/runner/__init__.py index c3d2b322..4cbea54b 100644 --- a/app/nullius/standard/runner/__init__.py +++ b/app/nullius/standard/runner/__init__.py @@ -1,11 +1 @@ -"""A run, from its units to its job, on one machine or several. - -``run`` sets each unit up, produces and scores it. ``job`` writes the result as -a job in Harbor's shape. ``pace`` slows the start of units when the provider -says the run goes too fast; ``retries`` says which failed attempt is tried -again, and how many times. ``shard`` and ``merge`` split one launch over -several machines and put its jobs back together; ``payload`` is the snapshot of -this runner a host is sent. ``boat_units`` sends that snapshot to a Boat VM per -unit, for a benchmark whose units boot a VM of their own, and merges what -comes back. -""" +"""A run, from its units to its job, on one machine or several.""" diff --git a/app/nullius/traces/breakdown.py b/app/nullius/traces/breakdown.py index f53181e5..62b66a0d 100644 --- a/app/nullius/traces/breakdown.py +++ b/app/nullius/traces/breakdown.py @@ -1,12 +1,6 @@ """Where a trace's time went: the producer's totals, and the same accounting done here. -``Totals`` is run-level time exactly as the producer reported it: displayed -verbatim, never recomputed from the tree. ``breakdown`` is the one arithmetic of -our own, every instant charged to exactly one category (``partition``). A view -that leaves spans out needs it, because hiding a span has to move its time -somewhere and the producer cannot be asked again; so do the producers that write -a trace's totals in the first place. ``Breakdown`` is its result, labelled as -derived wherever it is shown, and it never overwrites what the file said. +``Totals`` is shown verbatim; ``Breakdown`` is derived, and never overwrites it. """ from __future__ import annotations diff --git a/app/nullius/traces/fold.py b/app/nullius/traces/fold.py index f04fd04b..25460088 100644 --- a/app/nullius/traces/fold.py +++ b/app/nullius/traces/fold.py @@ -1,12 +1,6 @@ """A measured LLM call given the log spans for the reply it produced. -The producer writes one call twice when it has no request id to join on: once as -the exporter measured it, once from the agent's own log. ``fold_llm_requests`` -moves the log's request spans under the call they belong to. It moves rows and no -numbers. - -It runs before namespace grouping (``spans.mark_groups``), and the order is -load-bearing: ``trace`` says why. +It moves rows and no numbers, and runs before grouping: ``trace`` says why. """ from __future__ import annotations diff --git a/app/nullius/traces/spans.py b/app/nullius/traces/spans.py index edd76e76..bf0d1907 100644 --- a/app/nullius/traces/spans.py +++ b/app/nullius/traces/spans.py @@ -1,16 +1,4 @@ -"""The span tree of an agent trace: the model, the walks over it, what a span is called. - -``Span`` is one event as the pages read it, built from a raw span by ``_span`` and -redacted on the way. There are two walks, ``all_spans`` over parsed spans and -``raw_spans_of`` over the document's own dicts, and each guards against a parent -cycle rather than hanging. - -A span that is a *namespace* for its children rather than an event of its own is -re-kinded ``group`` (``mark_groups``). ``is_group`` says what qualifies and, more -importantly, the near misses that deliberately do not. - -Stdlib only, and no Flask. -""" +"""The span tree of an agent trace: the model, the walks over it, what a span is called.""" from __future__ import annotations diff --git a/app/nullius/traces/trace.py b/app/nullius/traces/trace.py index 569909bf..e22c1277 100644 --- a/app/nullius/traces/trace.py +++ b/app/nullius/traces/trace.py @@ -40,9 +40,7 @@ charges one of them nothing. Folding first leaves ``is_group`` only the wrappers fold could not match to a call, which is the case it is still needed for. -This module is the reader's front: ``Trace``, ``Filter``, ``parse``, ``load`` and the -saved view. The span tree is ``spans``, the fold ``fold``, the accounting -``breakdown``, the layout ``waterfall``. +The span tree is ``spans``, the fold ``fold``, the accounting ``breakdown``, the layout ``waterfall``. Everything is redacted at load, so templates hold display text only. Stdlib only, no Flask. """ diff --git a/app/nullius/traces/waterfall.py b/app/nullius/traces/waterfall.py index da785e11..70a7b44e 100644 --- a/app/nullius/traces/waterfall.py +++ b/app/nullius/traces/waterfall.py @@ -1,9 +1,6 @@ """A trace laid out as a waterfall: one global axis, one row per span. -``Extent`` is the window the axis covers, derived from the spans themselves. -``place`` puts a bar on it, ``flatten`` gives the rows depth first, ``ticks_for`` -labels the axis. A bar is positioned against the whole trace, never against its -parent: ``trace`` says why. +A bar is placed against the whole trace, never its parent: ``trace`` says why. """ from __future__ import annotations diff --git a/app/tests/test_catalogue_overlay.py b/app/tests/test_catalogue_overlay.py index af15cbbc..d0dcbb59 100644 --- a/app/tests/test_catalogue_overlay.py +++ b/app/tests/test_catalogue_overlay.py @@ -250,10 +250,10 @@ def test_proof_save_copies_bundle_and_preserves_other_version_and_files(self): def test_a_proof_that_ends_after_use_bundled_does_not_bring_the_users_entry_back(self): folder = self.definition(self.bundle, "agent", AGENT) (folder / "agent.py").write_text("the agent") - definitions.save(definitions.get("agent", "bot"), lambda cur: cur.update(summary="proven once")) # copied whole + definitions.save(definitions.get("agent", "bot"), lambda cur: cur.update(summary="proven once")) running = definitions.get("agent", "bot") # a second proof starts, on the user's copy self.assertEqual(running["_here"], str(self.user / "agents" / "bot")) - storage.use_bundled("agents", "bot", str(self.bundle)) # meanwhile: Use bundled entry + storage.use_bundled("agents", "bot", str(self.bundle)) with self.assertRaises(FileNotFoundError): definitions.save(running, lambda cur: cur.update(summary="proven twice")) self.assertFalse((self.user / "agents" / "bot").exists()) # not a folder holding the definition alone diff --git a/app/tests/test_constraints.py b/app/tests/test_constraints.py index 7a6b15a0..8531f157 100644 --- a/app/tests/test_constraints.py +++ b/app/tests/test_constraints.py @@ -303,7 +303,7 @@ def test_kept_per_machine(self): [t.start() for t in each]; [t.join() for t in each] self.assertEqual((failed, len(constraints.load(env))), ([], 24)) self.assertEqual([n for n in os.listdir(os.path.dirname(constraints.store_path(env))) if n.endswith(".part")], []) - self.assertEqual(os.stat(constraints.store_path(env)).st_mode & 0o777, 0o600) # its owner's alone + self.assertEqual(os.stat(constraints.store_path(env)).st_mode & 0o777, 0o600) constraints.save("local", {"enforced": ["cpus"]}, env); constraints.save("bench", {"enforced": []}, env) self.assertEqual(constraints.load(env)["local"]["enforced"], ["cpus"]) self.assertEqual(sorted(constraints.load(env))[:2], ["bench", "local"]) diff --git a/app/tests/test_harbor_entry.py b/app/tests/test_harbor_entry.py index 8b36884d..c97b0fef 100644 --- a/app/tests/test_harbor_entry.py +++ b/app/tests/test_harbor_entry.py @@ -97,7 +97,7 @@ def test_the_form_becomes_an_entry_in_the_catalogues_shape(self): def test_saved_it_loads_and_passes_the_catalogue_checks(self): path = h.save(h.build(form()), self.root) self.assertEqual(path, os.path.join(self.root, "benchmarks", "code-bench", "benchmark.json")) - self.assertEqual(os.stat(path).st_mode & 0o777, 0o600) # its owner's alone + self.assertEqual(os.stat(path).st_mode & 0o777, 0o600) cat = catalog.load(self.root) self.assertEqual(catalog.validate(cat), []) self.assertIn("code-bench", [b.key for b in cat.listed_benchmarks]) diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index 7e5bd29c..2936ac79 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -194,7 +194,7 @@ def test_save_load_merge_and_survive_a_reparse(self): store.save(self.ws.dir, "job-1", "task__abc/def", rec) path = Path(self.ws.dir) / "judgements" / "job-1" / (store.key("task__abc/def") + ".json") self.assertTrue(path.exists()); self.assertFalse((self.tmp / "jobs").exists()) # under the workspace, never the job tree - self.assertEqual(path.stat().st_mode & 0o777, 0o600) # its owner's alone + self.assertEqual(path.stat().st_mode & 0o777, 0o600) self.assertEqual(store.load(self.ws.dir, "job-1", "task__abc/def")["answers"], {"task_completed": {"noul": 0.9}}) later = dict(rec, asked_at="2026-09-17T10:00:00Z", answers={"transcript_quality": {"score": 2.0, "legend": ["a", "b", "c"], "probabilities": {}, "confidence": 0.9}}) store.save(self.ws.dir, "job-1", "task__abc/def", later) diff --git a/app/tests/test_layering.py b/app/tests/test_layering.py index f64f2c88..29295ccd 100644 --- a/app/tests/test_layering.py +++ b/app/tests/test_layering.py @@ -1,6 +1,5 @@ -"""Where code sits. The backend imports no Flask: it is exercisable from a bare shell or a -notebook (AGENTS.md, Core Architecture). The standard's modules sit in one folder per purpose, -and its folders import one way.""" +"""Where code sits: the backend imports no Flask; the standard's modules sit in one folder per +purpose, and its folders import one way.""" import ast import pathlib import unittest @@ -24,8 +23,6 @@ def test_no_backend_module_imports_the_web_stack(self): class StandardFolders(unittest.TestCase): - """``nullius/standard/`` is one folder per purpose; its ``__init__`` says what each is for.""" - def setUp(self): self.root = pathlib.Path(nullius.__file__).parent / "standard" self.folders = sorted(d.name for d in self.root.iterdir() if (d / "__init__.py").is_file()) @@ -52,8 +49,8 @@ def named(self, node, folder): return {p[2] for p in parts if p[:2] == ["nullius", "standard"] and len(p) > 2 and p[2] in self.folders} def test_the_folders_import_one_way(self): - """No folder imports one that imports it, at a module's top or inside a function, directly or - through others: each has what it uses below it, and a reader can take them in that order.""" + """No folder imports one that imports it: at a module's top or inside a function, directly or + through others.""" lines = {} # (a folder, the folder it imports) -> where for folder in self.folders: for path in sorted((self.root / folder).glob("*.py")): @@ -61,9 +58,11 @@ def test_the_folders_import_one_way(self): for other in self.named(node, folder) - {folder}: lines.setdefault((folder, other), []).append(f"{folder}/{path.name}:{node.lineno}") self.assertGreater(len(lines), 10) - left = set(self.folders) # a folder that imports none of those left, or that - while True: # none of them imports, is taken away, again and - free = {f for f in left if not any(a == f and b in left for a, b in lines) # again: what stays is a circle + # taken away, again and again: a folder that imports none of those left, or that none of them imports. + # What stays is a circle. + left = set(self.folders) + while True: + free = {f for f in left if not any(a == f and b in left for a, b in lines) or not any(b == f and a in left for a, b in lines)} if not free: break diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index 22eff73b..b64b5bd8 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -1,5 +1,4 @@ -"""A file written whole, a lock, a digest (``nullius.ondisk``): what every -module that keeps a file relies on.""" +"""``nullius.ondisk``: a file written whole, a lock, a digest.""" import hashlib import os import shutil @@ -37,15 +36,15 @@ def test_the_mode_is_the_process_default_unless_one_is_asked(self): old = os.umask(0o027) self.addCleanup(os.umask, old) ondisk.write_whole(self.path, "x") - self.assertEqual(self.mode(), 0o640) # 0666 less the umask, as open() gives + self.assertEqual(self.mode(), 0o640) # 0666 less the umask ondisk.write_whole(self.path, "x", mode=0o600) self.assertEqual(self.mode(), 0o600) ondisk.write_whole(self.path, "x", mode=0o644) - self.assertEqual(self.mode(), 0o644) # the mode asked for, whatever the umask + self.assertEqual(self.mode(), 0o644) def test_a_mode_the_umask_leaves_whole_is_the_files_from_its_creation(self): with mock.patch.object(os, "fchmod", side_effect=PermissionError("no chmod here")): - ondisk.write_whole(self.path, "x", mode=0o600) # as mkstemp gives it: asked for when made, never set after + ondisk.write_whole(self.path, "x", mode=0o600) self.assertEqual(self.mode(), 0o600) def test_a_mode_that_is_refused_leaves_no_file_and_no_open_descriptor(self): @@ -57,7 +56,7 @@ def refuse(fd, mode): raise PermissionError("no chmod here") with mock.patch.object(os, "fchmod", refuse): with self.assertRaises(PermissionError): - ondisk.write_whole(self.path, "x", mode=0o644) # the umask took a bit off: it has to be set + ondisk.write_whole(self.path, "x", mode=0o644) # the umask took a bit off self.assertEqual(self.left(), []) with self.assertRaises(OSError): os.fstat(held[0]) @@ -91,7 +90,7 @@ def test_a_write_that_fails_leaves_the_file_as_it_was_and_nothing_beside_it(self with self.assertRaises(OSError): ondisk.write_whole(self.path, "lost") with self.assertRaises(TypeError): - ondisk.write_whole(self.path, 42) # neither text nor bytes + ondisk.write_whole(self.path, 42) with open(self.path) as f: self.assertEqual(f.read(), "kept") self.assertEqual(self.left(), ["file.json"]) @@ -131,7 +130,7 @@ def second(): t.start() with ondisk.locked(path): inside.set() - t.join(0.3) # it waits while the lock is held + t.join(0.3) self.assertTrue(t.is_alive()) order.append("first") t.join(5) diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index ebe3f6ee..4cfbbf2a 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -332,7 +332,7 @@ def test_check_starts_the_kits_as_a_run_here(self): headers={"Origin": "http://localhost"}) self.addCleanup(r.close) self.assertEqual(r.status_code, 302) - (plan,) = self.started # started once + (plan,) = self.started self.assertEqual((plan.runner, plan.host, plan.key_var), ("standard", None, "OPENAI_API_KEY")) self.assertIn("conform fake --model gpt-5-mini --provider openai --stamp ", plan.script) self.assertNotIn("sk-test", plan.script) @@ -342,7 +342,7 @@ def test_check_starts_the_kits_as_a_run_here(self): r = self.client.post("/agents/fake/check", data={"csrf": self.csrf(), "provider": "openai", "model": "gpt-5-mini", "unsandboxed": "yes"}, headers={"Origin": "http://localhost"}) self.addCleanup(r.close) - self.assertEqual((r.status_code, r.headers["Location"], len(self.started)), (302, "/agents/fake", 1)) # back to its page, nothing started + self.assertEqual((r.status_code, r.headers["Location"], len(self.started)), (302, "/agents/fake", 1)) with self.client.session_transaction() as s: self.assertTrue(any(kind == "error" and said.endswith(" is running already") for kind, said in s["_flashes"]), s["_flashes"]) @@ -710,7 +710,7 @@ def test_prove_it_starts_cli_prove_here_handed_no_key(self): with patch.dict(execution.EXECUTIONS, {"going": going}): r = self.client.post("/benchmarks/gsm8k/prove", data={"csrf": csrf, "dataset": "test", "limit": "2"}, headers={"Origin": "http://localhost"}) self.addCleanup(r.close) - self.assertEqual((r.status_code, r.headers["Location"], len(self.started)), (302, "/benchmarks/gsm8k#standard", 1)) # back to its page, nothing started + self.assertEqual((r.status_code, r.headers["Location"], len(self.started)), (302, "/benchmarks/gsm8k#standard", 1)) with self.client.session_transaction() as s: self.assertTrue(any(kind == "error" and said.endswith(" is running already") for kind, said in s["_flashes"]), s["_flashes"]) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 0433ce1e..6340c0f1 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -166,9 +166,7 @@ def test_what_is_refused(self): self.assertFalse((self.tmp / "runs" / "x").exists()) def test_a_name_still_running_or_used_before_is_refused_and_nothing_starts(self): - """What every route that starts a run asks first (``execute.begin``): no run of - that name still going, no run folder of that name. Of several plans none - starts unless every one may.""" + """``execute.begin``, which every route that starts a run asks first.""" body = {"name": "twice", "script": "true", "where": "local"} going = SimpleNamespace(plan=SimpleNamespace(name="twice"), state="running") with patch.dict(execution.EXECUTIONS, {"going": going}): diff --git a/app/web/execute.py b/app/web/execute.py index 4e666d69..264c92dd 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -191,9 +191,8 @@ def docker_problem(): def begin(plans: list) -> tuple: - """Start ``plans``, every one checked before any starts: (the runs, "", 200), - or ([], why not, the status a JSON caller answers with) and nothing started. - Every route that starts a run comes through here.""" + """Start ``plans``, each checked before any starts: (the runs, "", 200), or + ([], why not, its status) and nothing started.""" for plan in plans: problem = plan.check() if problem: From 8a1814cc6e584d8f1945d14bc5d6dc22766f6e4c Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 23 Nov 2026 03:11:58 +0100 Subject: [PATCH 14/14] fix: the shared writer streams a function's text and stages where the path resolves A review found two places where ondisk.write_whole did not do what main did. The workspace's cache, index and record were serialised whole before the write, where main streamed them into the file: a 29 MB cache took 58 MB of memory to write, against 3 MB. write_whole takes a function that writes into the file, and the three calls pass main's own. The cache's concurrency test is main's again, since its gate is inside the write again. The temporary file was placed by a path Python had flattened, so a file written as link/../name was staged beside the link and not beside the file: a read-only folder there refused a write main accepted. It is staged by the path as given. --- app/nullius/ondisk.py | 13 +++++++++---- app/nullius/workspace.py | 8 ++++---- app/tests/test_ondisk.py | 34 ++++++++++++++++++++++++++++++++++ app/tests/test_workspace.py | 27 ++++++++++++++++++++------- 4 files changed, 67 insertions(+), 15 deletions(-) diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py index 87b11c80..0b16688b 100644 --- a/app/nullius/ondisk.py +++ b/app/nullius/ondisk.py @@ -9,19 +9,24 @@ def write_whole(path, data, mode=None) -> None: - """``data``, text or bytes, as the whole of ``path``, or ``path`` left as it was. + """``data`` as the whole of ``path``, or ``path`` left as it was: text, bytes, or a + function that writes text into the file it is given. Written beside ``path`` under a name of this write's own, then renamed over it: of two writers at once, each writes a complete file and the last rename wins. ``mode`` holds from the first byte. The folder is the caller's to make.""" path = os.fspath(path) - part = os.path.join(os.path.dirname(os.path.abspath(path)), f".{uuid.uuid4().hex}.part") + part = os.path.join(os.path.dirname(path), f".{uuid.uuid4().hex}.part") # the folder as the system resolves it fd = os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode) try: - with (os.fdopen(fd, "w", encoding="utf-8") if isinstance(data, str) else os.fdopen(fd, "wb")) as f: + text = isinstance(data, str) or callable(data) + with (os.fdopen(fd, "w", encoding="utf-8") if text else os.fdopen(fd, "wb")) as f: if mode is not None and stat.S_IMODE(os.fstat(fd).st_mode) != mode: os.fchmod(fd, mode) # the umask took bits off - f.write(data) + if callable(data): + data(f) + else: + f.write(data) os.replace(part, path) except BaseException: with contextlib.suppress(OSError): diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 6288e261..b0c0d1b3 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -116,7 +116,7 @@ def _path(home_dir: str, name: str) -> str: def save(ws: Workspace) -> None: os.makedirs(ws.dir, exist_ok=True) data = {k: v for k, v in asdict(ws).items() if k != "dir"} - ondisk.write_whole(os.path.join(ws.dir, "workspace.json"), json.dumps(data, ensure_ascii=False, indent=1)) + ondisk.write_whole(os.path.join(ws.dir, "workspace.json"), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1)) def load(home_dir: str, name: str) -> Workspace | None: @@ -400,7 +400,7 @@ def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | No def _write_index(ws: Workspace, index: dict) -> None: os.makedirs(ws.jobs_dir, exist_ok=True) - ondisk.write_whole(_index_path(ws), json.dumps(index, ensure_ascii=False, indent=1)) + ondisk.write_whole(_index_path(ws), lambda fh: json.dump(index, fh, ensure_ascii=False, indent=1)) # Jobs already decoded in this process, by cache file: (signature, Job, trial @@ -426,8 +426,8 @@ def _read_cache(path: str, job_dir: str) -> tuple | None: def _write_cache(ws: Workspace, path: str, sig: str, head: str, job: parse.Job) -> None: os.makedirs(ws.jobs_dir, exist_ok=True) - ondisk.write_whole(path, json.dumps({"signature": sig, "head": head, "dir": job.dir, "cached": _now(), "job": job_to_dict(job)}, - default=_encode, ensure_ascii=False)) + ondisk.write_whole(path, lambda fh: json.dump({"signature": sig, "head": head, "dir": job.dir, "cached": _now(), + "job": job_to_dict(job)}, fh, default=_encode, ensure_ascii=False)) def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict | None = None) -> tuple: diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index b64b5bd8..7db0a70e 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -84,6 +84,40 @@ def test_a_folder_that_is_gone_is_an_error_and_is_not_made_again(self): ondisk.write_whole(os.path.join(gone, "file.json"), "x") self.assertEqual(self.left(), []) + def test_a_path_through_a_links_parent_is_staged_where_the_system_puts_the_file(self): + os.makedirs(os.path.join(self.tmp, "target", "nested")) + os.mkdir(os.path.join(self.tmp, "beside")) + os.symlink(os.path.join(self.tmp, "target", "nested"), os.path.join(self.tmp, "beside", "link")) + seen, rename = [], os.replace + def spy(src, dst): + seen.append(os.path.realpath(os.path.dirname(src))) + return rename(src, dst) + with mock.patch.object(os, "replace", spy): + ondisk.write_whole(os.path.join(self.tmp, "beside", "link", "..", "file.json"), "x") + self.assertEqual(seen, [os.path.join(os.path.realpath(self.tmp), "target")]) # not "beside": link/.. is the link's target's parent + self.assertEqual(sorted(os.listdir(os.path.join(self.tmp, "target"))), ["file.json", "nested"]) + self.assertEqual(os.listdir(os.path.join(self.tmp, "beside")), ["link"]) + + def test_a_bare_name_is_written_in_the_current_folder(self): + self.addCleanup(os.chdir, os.getcwd()) + os.chdir(self.tmp) + ondisk.write_whole("bare.json", "x") + self.assertEqual(self.left(), ["bare.json"]) + + def test_a_function_is_handed_the_file_and_what_it_writes_lands_whole(self): + def two(f): + f.write("first\n") + f.write("é\n") + ondisk.write_whole(self.path, two, mode=0o600) + def stops(f): + f.write("half") + raise ValueError("stopped") + with self.assertRaises(ValueError): + ondisk.write_whole(self.path, stops) + with open(self.path, "rb") as f: + self.assertEqual(f.read(), "first\né\n".encode()) + self.assertEqual((self.mode(), self.left()), (0o600, ["file.json"])) + def test_a_write_that_fails_leaves_the_file_as_it_was_and_nothing_beside_it(self): ondisk.write_whole(self.path, "kept") with mock.patch.object(os, "replace", side_effect=OSError("no rename")): diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index b0122f85..330cbe3b 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -13,6 +13,7 @@ import tempfile import threading import time +import tracemalloc import unittest from dataclasses import replace from unittest.mock import patch @@ -241,21 +242,20 @@ def test_two_requests_writing_the_same_cache_at_once_both_return(self): changing, and both wrote the cache through one shared `.json.tmp`: the first rename took the file away and the second raised FileNotFoundError, a 500 on the page. Both writers are held with - their temp file written until the other has written its own, then released: + their temp file open until the other has opened its own, then released: each must finish, and the cache must be whole.""" gate = threading.Barrier(2, timeout=5) - cache, rename = workspace._cache_file(self.ws, self.job_dir), os.replace - def held_rename(src, dst): - if dst == cache: # the cache alone: the index is written after it, by one or both - gate.wait() # both have written their temp file, neither has renamed yet - return rename(src, dst) + stamp = workspace._now + def held_now(): + gate.wait() # both are inside the write, temp file open, nothing renamed yet + return stamp() results, errors = [], [] def load(): try: results.append(workspace.load_job(self.ws, self.job_dir)) except Exception as e: # noqa: BLE001 - the failure under test errors.append(e) - with patch.object(os, "replace", held_rename): + with patch.object(workspace, "_now", held_now): threads = [threading.Thread(target=load) for _ in range(2)] for t in threads: t.start() for t in threads: t.join(10) @@ -265,6 +265,19 @@ def load(): self.assertTrue(from_cache); self.assertEqual(job, results[0][0]) self.assertEqual([n for n in os.listdir(self.ws.jobs_dir) if n.endswith(".part")], []) + def test_the_cache_is_written_a_piece_at_a_time(self): + job, rows = parse.parse_job(self.job_dir), {"rows": ["x" * 100] * 20000} # about 2 MB as JSON + path = os.path.join(self.ws.jobs_dir, "large.json") + with patch.object(workspace, "job_to_dict", lambda job: rows): + tracemalloc.start() + try: + workspace._write_cache(self.ws, path, "sig", "head", job) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + self.assertGreater(os.path.getsize(path), 2_000_000) + self.assertLess(peak, os.path.getsize(path) / 2) # never the whole text in memory + def test_load_jobs_matches_load_all(self): _job_dir(self.root, "job-b", n=1) cached = workspace.load_jobs(self.ws, [self.root])