diff --git a/.claude/rules/traces.md b/.claude/rules/traces.md index a3c13592..c0c645f0 100644 --- a/.claude/rules/traces.md +++ b/.claude/rules/traces.md @@ -1,7 +1,7 @@ ## Traces, as this application renders them -The reader itself — folding, grouping, normalisation — is -`app/nullius/traces/trace.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/.claude/skills/docs-drift/SKILL.md b/.claude/skills/docs-drift/SKILL.md index 7ce87bfd..b2529b88 100644 --- a/.claude/skills/docs-drift/SKILL.md +++ b/.claude/skills/docs-drift/SKILL.md @@ -47,7 +47,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; `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`; 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 e0a259e8..b69d33ca 100644 --- a/.claude/skills/import-agent/SKILL.md +++ b/.claude/skills/import-agent/SKILL.md @@ -38,7 +38,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()) @@ -132,7 +133,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 d6d25858..16217c9c 100644 --- a/.claude/skills/import-capability/SKILL.md +++ b/.claude/skills/import-capability/SKILL.md @@ -39,7 +39,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()) @@ -76,7 +77,7 @@ below. CLI mutations protect bundled resources in source checkouts too. why, and what it changes about what is measured; ask with the question 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** (see `app/nullius/standard/ports.py`) is a generic change: a new port with a +- **A kind with no port yet** (see `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. ## 1. Read the input (minutes, no install) @@ -134,7 +135,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 a7a471d0..79c770bc 100644 --- a/.claude/skills/import-standard/SKILL.md +++ b/.claude/skills/import-standard/SKILL.md @@ -55,7 +55,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__) @@ -144,7 +145,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 is a source contribution. - **An agent or a capability never writes `offers` by hand.** `cli conform` does. diff --git a/.github/scripts/judge_pr.py b/.github/scripts/judge_pr.py index 044e8f9d..e11c624a 100644 --- a/.github/scripts/judge_pr.py +++ b/.github/scripts/judge_pr.py @@ -319,7 +319,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 0eb391e9..ec6fcb28 100644 --- a/.github/workflows/docker-tests.yml +++ b/.github/workflows/docker-tests.yml @@ -31,7 +31,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.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 5237e29e..addc492a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,7 +46,8 @@ and its resources. Harbor job tree: `parse`, `classify`, `live`, `artifacts`, `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`, `trajectory`, + their pass count and pass@k, and the `cli`), `traces/` (`trace`, the reader, with its span tree `spans`, + `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 @@ -59,9 +60,16 @@ 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`: `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), `retries` (what an attempt is tried again after, and how many times), `pace` (how soon the next unit starts after a rate limit), `pins` (image digests checked against registry tags), `install`, `run`, `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), `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), `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, 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/`: `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); + `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 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 @@ -74,7 +82,7 @@ and its resources. (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 and before a capped 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 and before a capped 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` (the Docker Hub login Data providers uses), `charts` (categorical charts, bars, dots and a scatter, and their style registry: Compare's Chart view) and `redact` at the top. - `app/templates/`, `app/static/` — the interface, grouped by the same capability @@ -132,7 +140,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.** `test_charts.NoFlask` checks every module. If a test in `app/tests` needs Flask, the layering +- **`app/nullius/` imports no Flask.** `test_layering.NoFlask` checks every module. If a test in `app/tests` needs Flask, the layering has broken, not the test. - **One name, one implementation per interpreter.** `app/tests/test_dependency_surface.py` counts *providers* of `nullius` and diff --git a/app/nullius/catalogue/benchmarks/humaneval/driver.py b/app/nullius/catalogue/benchmarks/humaneval/driver.py index 19caef0a..5f3d5f4d 100644 --- a/app/nullius/catalogue/benchmarks/humaneval/driver.py +++ b/app/nullius/catalogue/benchmarks/humaneval/driver.py @@ -56,7 +56,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.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 9b034696..d8b89765 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/driver.py +++ b/app/nullius/catalogue/benchmarks/osworld1/driver.py @@ -406,7 +406,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 @@ -427,7 +427,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/nullius/catalogue/benchmarks/osworld1/runner.py b/app/nullius/catalogue/benchmarks/osworld1/runner.py index b77adee6..e2a98670 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] @@ -135,7 +135,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 448d03d2..27c390ee 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/driver.py b/app/nullius/catalogue/benchmarks/tau3-bench/driver.py index c4b10918..f6656314 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/driver.py +++ b/app/nullius/catalogue/benchmarks/tau3-bench/driver.py @@ -118,7 +118,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 bf1b06d0..3b07099c 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py +++ b/app/nullius/catalogue/benchmarks/tau3-bench/mcp_server.py @@ -18,7 +18,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.backends.mcp_machine``). """ import contextlib import copy diff --git a/app/nullius/catalogue/harbor_entry.py b/app/nullius/catalogue/harbor_entry.py index 902378a6..ed3400da 100644 --- a/app/nullius/catalogue/harbor_entry.py +++ b/app/nullius/catalogue/harbor_entry.py @@ -23,11 +23,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" @@ -209,17 +210,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 267bf623..832ead05 100644 --- a/app/nullius/constraints.py +++ b/app/nullius/constraints.py @@ -36,7 +36,7 @@ there may run on (``WALK``). Local processes land in the user's cgroup (a scope's, else the probe's own); containers land where the engine puts them, which a probe container in the host's cgroup namespace reads. 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 @@ -48,14 +48,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 @@ -616,14 +615,7 @@ 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(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 dded88f3..aa4d58d3 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -30,7 +30,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 @@ -40,7 +40,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/``. @@ -118,11 +118,12 @@ from datetime import datetime, timezone from typing import Callable, Dict, List, Optional -from nullius import hosts, paths, prices as price_list, progress, providers, redact, secrets, settings, workspace +from nullius import hosts, ondisk, paths, prices as price_list, progress, providers, redact, secrets, settings, workspace from nullius.judge import store as judgements from nullius.runs import parse from nullius.harbor import source as harbor_source -from nullius.standard import container, payload as standard_payload +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) # The names the launcher gives a run's key and its endpoint (_launch), read @@ -139,7 +140,7 @@ UV_INSTALL = "curl -LsSf https://astral.sh/uv/install.sh | sh" RECORD = "run.json" LOCK = ".lock" # in the runs root, held by the one process that follows its runs -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_.-]") @@ -249,7 +250,7 @@ class Plan: jobs: List[dict] = field(default_factory=list) # the job directories the script writes: [{"name", "agent", "dataset"}], a shard's also its "launch" 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 - 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); {}: 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 @@ -342,7 +343,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: @@ -388,7 +389,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 @@ -481,10 +482,7 @@ def _save(self) -> None: "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 2a106f95..627c2c0d 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,10 +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/hosts.py b/app/nullius/hosts.py index b8deca42..f5d6af38 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.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/importers/atif.py b/app/nullius/importers/atif.py index 38c56133..2a9129fe 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -58,7 +58,6 @@ """ from __future__ import annotations -import hashlib import json import os import re @@ -66,7 +65,7 @@ import shutil from datetime import timezone -from nullius import importers +from nullius import importers, ondisk from nullius.redact import redact from nullius.traces.trajectory import parse_ts @@ -272,13 +271,6 @@ def _dump(path: str, data) -> bool: return importers.write_if_changed(path, json.dumps(data, indent=2).encode()) -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 ──────────────────────────────────────────────── @@ -310,7 +302,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/importers/otel.py b/app/nullius/importers/otel.py index f15ff2bc..0ad31e8d 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -52,7 +52,7 @@ from nullius import importers 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" @@ -140,7 +140,7 @@ def _dump(path: str, data) -> bool: 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/judge/store.py b/app/nullius/judge/store.py index f2155c87..c80c5c42 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -16,10 +16,11 @@ import json import os import re -import tempfile import threading from typing import Optional +from nullius import ondisk + from . import client, questions as Q _SAFE = re.compile(r"[^A-Za-z0-9._@+-]") @@ -132,14 +133,7 @@ def save(ws_dir: str, job_id: str, trial_name: str, record: dict, lane: str = "d if "hygiene" in earlier or "hygiene" in record: merged["hygiene"] = {**(earlier.get("hygiene") or {}), **(record.get("hygiene") or {})} data[version] = merged - fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=os.path.basename(path) + ".", suffix=".tmp") - try: - with os.fdopen(fd, "w", encoding="utf-8") as fh: - json.dump(data, fh, indent=1) - os.replace(tmp, path) - except BaseException: - os.unlink(tmp) - raise + ondisk.write_whole(path, json.dumps(data, indent=1), mode=0o600) return merged diff --git a/app/nullius/migrate.py b/app/nullius/migrate.py index 99316158..5def150f 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 provider_records(values: dict) -> dict: diff --git a/app/nullius/onboarding.py b/app/nullius/onboarding.py index aff7a91e..b256325c 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.backends import container CONTROLS = ("nop", "oracle") diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py new file mode 100644 index 00000000..0b16688b --- /dev/null +++ b/app/nullius/ondisk.py @@ -0,0 +1,54 @@ +"""A file written whole, a lock, a digest.""" +from __future__ import annotations + +import contextlib +import hashlib +import os +import stat +import uuid + + +def write_whole(path, data, mode=None) -> None: + """``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(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: + 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 + if callable(data): + data(f) + else: + 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. 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: + yield + finally: + fcntl.flock(f, fcntl.LOCK_UN) + + +def sha256_of(path) -> str: + 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/prerequisites.py b/app/nullius/prerequisites.py index ce78e04b..3e6cf07e 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.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/prices.py b/app/nullius/prices.py index 19c8d957..efecae2d 100644 --- a/app/nullius/prices.py +++ b/app/nullius/prices.py @@ -34,7 +34,7 @@ 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 @@ -79,11 +79,7 @@ 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(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 34aa5833..870c8e71 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -27,7 +27,7 @@ import urllib.request from typing import List, Optional -from nullius import paths, settings +from nullius import ondisk, paths, settings # --- the registry: protocols, presets and each provider's record ------------------------------------ # @@ -215,7 +215,7 @@ def protocol_for(choice: str, apis, env=None) -> str: def auth(protocol: str, key: str) -> dict: """The headers that carry ``key`` in ``protocol``: a bearer header, or Anthropic's ``x-api-key``.""" if PROTOCOLS[protocol]["auth"] == "x-api-key": - from nullius.standard.relay import ANTHROPIC_VERSION + from nullius.standard.calls.relay import ANTHROPIC_VERSION return {"x-api-key": key, "anthropic-version": ANTHROPIC_VERSION} return {"Authorization": "Bearer " + key} if key else {} @@ -448,7 +448,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._-]+)*") @@ -583,10 +583,7 @@ def remember(results: dict, env=None) -> None: 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(out, json.dumps(kept, indent=1, sort_keys=True)) def mark(result: dict) -> str: diff --git a/app/nullius/recipes/launch.py b/app/nullius/recipes/launch.py index a718af54..92a1ff9f 100644 --- a/app/nullius/recipes/launch.py +++ b/app/nullius/recipes/launch.py @@ -53,7 +53,7 @@ def parameter(key, label, group, kind, default=None, *, help="", **extra): def payload(cat, jobs): 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 "" @@ -65,7 +65,7 @@ def payload(cat, jobs): "runnerGone": providers.GONE, # the providers a run is sent to, from the registry "providers": providers.run_choices(), - # 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/classify.py b/app/nullius/runs/classify.py index fbd097c8..b1a84cc8 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" @@ -65,7 +65,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/runs/launches.py b/app/nullius/runs/launches.py index 23a985b2..e4bcd6c1 100644 --- a/app/nullius/runs/launches.py +++ b/app/nullius/runs/launches.py @@ -31,7 +31,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/runs/parse.py b/app/nullius/runs/parse.py index cc0eeb96..337cd4c1 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -994,7 +994,7 @@ def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job: def _own_agent_key(bench: str, upstream: str) -> str: """The key of the benchmark's own agent the upstream names ``upstream`` (its ``agents.json``, ``start.driver.agent``); empty for a benchmark without, or a name none has.""" - from nullius.standard import definitions # the catalogue, read only for a job from before + from nullius.standard.contract import definitions # the catalogue, read only for a job from before folder = definitions.entry_dir("benchmark", bench) if re.fullmatch(r"[a-z][a-z0-9-]{0,39}", bench) else None path = os.path.join(folder, definitions.AGENTS_FILE) if folder else "" return _own_keys(path, os.path.getmtime(path)).get(upstream, "") if path and os.path.isfile(path) else "" diff --git a/app/nullius/sandbox.py b/app/nullius/sandbox.py index 3e0e18f7..1aecf88a 100644 --- a/app/nullius/sandbox.py +++ b/app/nullius/sandbox.py @@ -17,7 +17,7 @@ import subprocess from typing import List, Optional -from nullius.standard 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/secrets.py b/app/nullius/secrets.py index 034485ad..44f5a060 100644 --- a/app/nullius/secrets.py +++ b/app/nullius/secrets.py @@ -19,10 +19,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" @@ -63,18 +62,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 bc2ec864..9c964a97 100644 --- a/app/nullius/settings.py +++ b/app/nullius/settings.py @@ -25,11 +25,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_.-]+$") @@ -532,26 +533,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/__init__.py b/app/nullius/standard/__init__.py index a0b0f822..1c21c471 100644 --- a/app/nullius/standard/__init__.py +++ b/app/nullius/standard/__init__.py @@ -1,15 +1,19 @@ """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, 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 new file mode 100644 index 00000000..9995179f --- /dev/null +++ b/app/nullius/standard/backends/__init__.py @@ -0,0 +1,6 @@ +"""Where a unit runs when not among this machine's processes, and the doors through. + +``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/boat.py b/app/nullius/standard/backends/boat.py similarity index 99% rename from app/nullius/standard/boat.py rename to app/nullius/standard/backends/boat.py index ce7cde06..939592ec 100644 --- a/app/nullius/standard/boat.py +++ b/app/nullius/standard/backends/boat.py @@ -52,7 +52,7 @@ from typing import Callable, Dict, Iterable, List, Optional, Sequence from nullius import paths, secrets -from nullius.standard import install +from nullius.standard.requirements import install API = "https://boat.dev/api/v1" STORE, NAME = "sandbox-provider-boat", "BOAT_API_KEY" diff --git a/app/nullius/standard/container.py b/app/nullius/standard/backends/container.py similarity index 99% rename from app/nullius/standard/container.py rename to app/nullius/standard/backends/container.py index 35b3b640..c34dd8d9 100644 --- a/app/nullius/standard/container.py +++ b/app/nullius/standard/backends/container.py @@ -30,7 +30,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 @@ -114,8 +114,9 @@ from secrets import compare_digest, token_hex from typing import Dict, Iterable, List, Optional, Tuple -from nullius import constraints, paths -from nullius.standard import definitions, install +from nullius import constraints, ondisk, paths +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 @@ -745,7 +746,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] @@ -1163,7 +1164,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.backends import forward nonce = token_hex(32) class Handler(socketserver.BaseRequestHandler): def handle(self): @@ -1428,7 +1429,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 @@ -1527,7 +1528,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/egress.py b/app/nullius/standard/backends/egress.py similarity index 100% rename from app/nullius/standard/egress.py rename to app/nullius/standard/backends/egress.py diff --git a/app/nullius/standard/forward.py b/app/nullius/standard/backends/forward.py similarity index 100% rename from app/nullius/standard/forward.py rename to app/nullius/standard/backends/forward.py diff --git a/app/nullius/standard/mcp_bridge.py b/app/nullius/standard/backends/mcp_bridge.py similarity index 100% rename from app/nullius/standard/mcp_bridge.py rename to app/nullius/standard/backends/mcp_bridge.py diff --git a/app/nullius/standard/mcp_machine.py b/app/nullius/standard/backends/mcp_machine.py similarity index 99% rename from app/nullius/standard/mcp_machine.py rename to app/nullius/standard/backends/mcp_machine.py index a8a9737b..f730c475 100644 --- a/app/nullius/standard/mcp_machine.py +++ b/app/nullius/standard/backends/mcp_machine.py @@ -38,7 +38,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/backends/setup_container.py similarity index 97% rename from app/nullius/standard/setup_container.py rename to app/nullius/standard/backends/setup_container.py index 89409291..fd392d7e 100644 --- a/app/nullius/standard/setup_container.py +++ b/app/nullius/standard/backends/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.backends 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.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/web_services.py b/app/nullius/standard/backends/web_services.py similarity index 100% rename from app/nullius/standard/web_services.py rename to app/nullius/standard/backends/web_services.py diff --git a/app/nullius/standard/calls/__init__.py b/app/nullius/standard/calls/__init__.py new file mode 100644 index 00000000..ad5f4b4a --- /dev/null +++ b/app/nullius/standard/calls/__init__.py @@ -0,0 +1 @@ +"""A run's model calls: relayed, recorded, capped.""" diff --git a/app/nullius/standard/ledger.py b/app/nullius/standard/calls/ledger.py similarity index 97% rename from app/nullius/standard/ledger.py rename to app/nullius/standard/calls/ledger.py index ca5c81a9..6eb85de8 100644 --- a/app/nullius/standard/ledger.py +++ b/app/nullius/standard/calls/ledger.py @@ -47,13 +47,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: an agent error, counted against the agent (runs.classify) @@ -130,12 +131,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}") @@ -148,10 +145,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/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 e1162372..d7b3161c 100644 --- a/app/nullius/standard/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -62,7 +62,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}$") @@ -1162,7 +1162,7 @@ def overflowed(call: dict) -> bool: # -- 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] [--served-by MODEL=SLUG[,SLUG...] ...]``. @@ -1173,7 +1173,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") @@ -1240,5 +1240,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 0e194084..229ca2fc 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -18,14 +18,14 @@ an agent's run or conformance check there is refused without ``--unsandboxed``. ``--backend container`` (``docker`` alias) 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/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 -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 @@ -38,12 +38,12 @@ each check K times, held by a majority); ``run`` runs a benchmark into a job under ``--jobs`` (``jobs_standard/``); ``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. ``--served-by [MODEL=]SLUG[,SLUG...]`` lets only those serving providers answer @@ -54,7 +54,7 @@ (``nullius/progress.py``). Keys come from the process environment, then the saved user settings. Nothing is printed of them. With ``--from-run`` (a run -the builder or a page started, ``standard/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 @@ -74,14 +74,17 @@ 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. if __name__ == "__main__" and "--from-run" not in sys.argv[1:]: settings.load(paths.settings_file()) -from nullius.standard import boat, conform, definitions, fidelity, job, match, merge, pins, ports, prove, run, shard +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 ENV_FILE = paths.settings_file() @@ -144,7 +147,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 [] @@ -612,7 +615,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/contract/__init__.py b/app/nullius/standard/contract/__init__.py new file mode 100644 index 00000000..444fc90b --- /dev/null +++ b/app/nullius/standard/contract/__init__.py @@ -0,0 +1 @@ +"""The contract: what a definition may say, and which pairs fit.""" diff --git a/app/nullius/standard/definitions.py b/app/nullius/standard/contract/definitions.py similarity index 98% rename from app/nullius/standard/definitions.py rename to app/nullius/standard/contract/definitions.py index bf25f383..4e919433 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 @@ -92,15 +92,16 @@ import os import re from typing import Callable, Dict, List, Optional, Tuple +from urllib.parse import urlsplit -from nullius.standard import ports -from nullius import paths +from nullius.standard.contract import ports +from nullius import ondisk, 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"}, @@ -969,8 +970,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 - 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] = {} @@ -986,6 +986,20 @@ def _environments(envs, here: Optional[str]) -> List[str]: return bad +def _network(value) -> List[str]: + """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: + 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 @@ -1828,15 +1842,10 @@ def path_of(d: dict) -> str: @contextlib.contextmanager def _locked(path: str): """One writer of a definition file at a time, across processes.""" - 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: @@ -1882,7 +1891,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/match.py b/app/nullius/standard/contract/match.py similarity index 95% rename from app/nullius/standard/match.py rename to app/nullius/standard/contract/match.py index a8ca4934..6f43d683 100644 --- a/app/nullius/standard/match.py +++ b/app/nullius/standard/contract/match.py @@ -12,9 +12,9 @@ from typing import Dict, List -from nullius.standard import ports -from nullius.standard import definitions -from nullius.standard.definitions import CONTROLS, port_skills, ref_of, skills_shown +from nullius.standard.contract import ports +from nullius.standard.contract import definitions +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-computer-v1/desktop.py b/app/nullius/standard/kits/agent-computer-v1/desktop.py index 8b91aa25..83f0ab0e 100644 --- a/app/nullius/standard/kits/agent-computer-v1/desktop.py +++ b/app/nullius/standard/kits/agent-computer-v1/desktop.py @@ -36,7 +36,7 @@ import threading from typing import Dict, List, Optional -from nullius.standard 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 722074d8..80e74e92 100644 --- a/app/nullius/standard/kits/agent-computer-v1/driver.py +++ b/app/nullius/standard/kits/agent-computer-v1/driver.py @@ -41,9 +41,9 @@ import threading import time -from nullius.standard import computer_port as port -from nullius.standard import container -from nullius.standard.jsonl import serve +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-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..a455beda 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.backends.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 ebb8a4ac..c0ae41e0 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.backends.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..b247cdcf 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.backends.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..6e0ea2ac --- /dev/null +++ b/app/nullius/standard/pages/__init__.py @@ -0,0 +1 @@ +"""The standard as the application's pages show it.""" 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 f9f52347..b6266a3e 100644 --- a/app/nullius/standard/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -41,8 +41,13 @@ from nullius import constraints as limits, hosts, providers from nullius.providers import PROVIDERS, STEP -from nullius.standard import boat, hostreq, definitions, ledger, match, ports, prove, relay, run -from nullius.standard.retries import MAX_RETRIES +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.runner.retries import MAX_RETRIES CHOOSE_PROVIDER = "Choose a provider: OpenRouter, OpenAI, Anthropic or a custom provider." HARNESS = "standard" @@ -263,7 +268,7 @@ def entries(kind: str, benches: Optional[List[dict]] = None, every: bool = False """The agents (or capabilities) as the Agents page and the builder's Agent step list them, each with its ports and its fits (``match.fit``) on ``benches`` (default: every benchmark of its family, default versions), and the definitions with problems. ``own``: and the benchmarks' own agents (``definitions.benchmark_agents``).""" - from nullius.standard import conform + from nullius.standard.proofs import conform others, bad = definitions.load(kind, every=every) loaded = definitions.load("benchmark")[0] benches = [b for b in loaded if b["family"] == kind] if benches is None else benches @@ -399,7 +404,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. @@ -594,7 +599,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}.") @@ -978,7 +983,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..0fb6bd81 --- /dev/null +++ b/app/nullius/standard/proofs/__init__.py @@ -0,0 +1 @@ +"""What is proven, or checked, before it is offered.""" 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 4751e7a3..6985320b 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, retries, run +from nullius.standard.contract import definitions, ports +from nullius.standard.runner import retries, 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 cbcc9908..8f9edd11 100644 --- a/app/nullius/standard/fidelity.py +++ b/app/nullius/standard/proofs/fidelity.py @@ -28,7 +28,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 99% rename from app/nullius/standard/prove.py rename to app/nullius/standard/proofs/prove.py index 1e8644e4..0a522a80 100644 --- a/app/nullius/standard/prove.py +++ b/app/nullius/standard/proofs/prove.py @@ -50,7 +50,10 @@ import time from typing import Callable, Dict, List, Optional -from nullius.standard import definitions, install, job, jsonl, retries, 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 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 new file mode 100644 index 00000000..4ff622be --- /dev/null +++ b/app/nullius/standard/protocols/__init__.py @@ -0,0 +1,5 @@ +"""How the programs of a run speak to each other. + +``computer_port`` and ``computer_pipe`` run in a benchmark's own Python: they +import nothing of this application. +""" 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 0a51e1e6..245c1545 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/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/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 0925d18b..b710e944 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..aa3a573a --- /dev/null +++ b/app/nullius/standard/requirements/__init__.py @@ -0,0 +1,4 @@ +"""What a run needs of the machine before its first unit. + +Review's rows are ``nullius.prerequisites``, which asks ``hostreq`` here. +""" 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 97% rename from app/nullius/standard/install.py rename to app/nullius/standard/requirements/install.py index 5fd61275..90269d5e 100644 --- a/app/nullius/standard/install.py +++ b/app/nullius/standard/requirements/install.py @@ -32,7 +32,6 @@ from __future__ import annotations import contextlib -import fcntl import hashlib import json import os @@ -41,9 +40,9 @@ import subprocess from typing import Callable, Dict, List, Optional -from nullius.standard import definitions +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" @@ -100,12 +99,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: @@ -374,14 +369,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 @@ -394,7 +381,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 @@ -446,7 +433,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/standard/network_requirements.py b/app/nullius/standard/requirements/network_requirements.py similarity index 68% rename from app/nullius/standard/network_requirements.py rename to app/nullius/standard/requirements/network_requirements.py index 32561108..9b5c0ed3 100644 --- a/app/nullius/standard/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/nullius/standard/runner/__init__.py b/app/nullius/standard/runner/__init__.py new file mode 100644 index 00000000..4cbea54b --- /dev/null +++ b/app/nullius/standard/runner/__init__.py @@ -0,0 +1 @@ +"""A run, from its units to its job, on one machine or several.""" diff --git a/app/nullius/standard/boat_units.py b/app/nullius/standard/runner/boat_units.py similarity index 98% rename from app/nullius/standard/boat_units.py rename to app/nullius/standard/runner/boat_units.py index 3cbb337e..8a4875f2 100644 --- a/app/nullius/standard/boat_units.py +++ b/app/nullius/standard/runner/boat_units.py @@ -29,7 +29,10 @@ from typing import Callable, Dict, List, Optional from nullius import paths, secrets -from nullius.standard import boat, definitions, hostreq, merge, payload, shard +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 RUNPY = "import json, os, runpy, sys; os.environ.update(json.loads(sys.stdin.readline())); sys.path.insert(0, sys.argv.pop(1)); runpy.run_module('nullius.standard.cli', run_name='__main__', alter_sys=True)" SHARDS = ".boat" # the shards' jobs, under the jobs root, until they are merged 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 e404cad4..2b8e4870 100644 --- a/app/nullius/standard/job.py +++ b/app/nullius/standard/runner/job.py @@ -29,8 +29,9 @@ from datetime import datetime, timezone from typing import Dict, List, Optional -from nullius.standard import ledger -from nullius.traces import otel, trace +from nullius.standard.calls import ledger +from nullius.traces import otel +from nullius.traces.breakdown import breakdown def iso(t: Optional[float]) -> Optional[str]: @@ -357,11 +358,11 @@ 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"}, - "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/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 9c532f79..1f4b49a9 100644 --- a/app/nullius/standard/merge.py +++ b/app/nullius/standard/runner/merge.py @@ -36,8 +36,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 edacd97c..55fc16b6 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/retries.py b/app/nullius/standard/runner/retries.py similarity index 96% rename from app/nullius/standard/retries.py rename to app/nullius/standard/runner/retries.py index e4fba12c..3ecac553 100644 --- a/app/nullius/standard/retries.py +++ b/app/nullius/standard/runner/retries.py @@ -21,7 +21,8 @@ from typing import Optional -from nullius.standard import ledger, pace, relay +from nullius.standard.calls import ledger, relay +from nullius.standard.runner import pace RETRIES = 0 MAX_RETRIES = 9 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 fcb6d6c6..f234a140 100644 --- a/app/nullius/standard/run.py +++ b/app/nullius/standard/runner/run.py @@ -75,8 +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 acp, boat, container, definitions, hostreq, install, job, jsonl, ledger as ledgers, match, mcp_machine, pace as pacing, relay, shard as shards -from nullius.standard.retries import RETRIES, retryable +from nullius.standard.backends import boat, container, mcp_machine +from nullius.standard.calls import ledger as ledgers, relay +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.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") @@ -84,7 +89,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: @@ -1171,7 +1176,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 BenchmarkRefused("; ".join(why)) @@ -1221,7 +1226,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.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")) @@ -1817,7 +1822,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 . import web_services + from ..backends 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/nullius/traces/breakdown.py b/app/nullius/traces/breakdown.py new file mode 100644 index 00000000..62b66a0d --- /dev/null +++ b/app/nullius/traces/breakdown.py @@ -0,0 +1,284 @@ +"""Where a trace's time went: the producer's totals, and the same accounting done here. + +``Totals`` is shown verbatim; ``Breakdown`` is derived, and never overwrites it. +""" + +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. + + 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. + """ + 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. + """ + 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 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. + + ``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. + """ + + 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*. + + 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 e2be2609..3b545bbd 100644 --- a/app/nullius/traces/charts.py +++ b/app/nullius/traces/charts.py @@ -31,7 +31,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. @@ -66,7 +66,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 @@ -790,7 +790,7 @@ def charts_of(samples: tuple, total: int, excluded: int, filt: "ChartFilter | None" = None) -> Charts: """The same four charts over an already-extracted population. - :func:`trace.all_spans` deduplicates by + :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..25460088 --- /dev/null +++ b/app/nullius/traces/fold.py @@ -0,0 +1,207 @@ +"""A measured LLM call given the log spans for the reply it produced. + +It moves rows and no numbers, and runs before grouping: ``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. + + 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. + """ + 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. + + 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 58d26e78..1f1e1396 100644 --- a/app/nullius/traces/otel.py +++ b/app/nullius/traces/otel.py @@ -77,7 +77,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. Spans are ``timing_quality: measured``: these are the producer's clocks, not this @@ -104,7 +104,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 @@ -417,7 +418,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: @@ -520,7 +521,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) @@ -551,7 +552,7 @@ def build(trace_id: str, records: list, limit: int = DEFAULT_MAX_CONTENT, "note": "wall_ns is the trace's own window, first start to last end", }, "spans": roots, - "totals": trace.breakdown(roots, wall_ns).as_totals(), + "totals": breakdown(roots, wall_ns).as_totals(), "import": { "format": FORMAT, "conventions": CONVENTIONS, @@ -564,7 +565,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 "".""" - 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..bf0d1907 --- /dev/null +++ b/app/nullius/traces/spans.py @@ -0,0 +1,393 @@ +"""The span tree of an agent trace: the model, the walks over it, what a span is called.""" + +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`, and `_KIND_CATEGORY` omits groups so they accrue 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. +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. +_BRACKET_KINDS = ("session", "subagent", GROUP_KIND) + +# The OTel span for one API call, and the log-derived span for one *record* of +# the reply. Without a request ID, Harbor can leave duplicate call spans for `fold_llm_requests` to join. +_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. + """ + 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. + + 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.""" + 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`? + + 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; this sees what it could not match. + + Everything else with children stays what it is. 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: they never claim to be work. + + 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. 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 bd570a3a..e22c1277 100644 --- a/app/nullius/traces/trace.py +++ b/app/nullius/traces/trace.py @@ -15,309 +15,48 @@ 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`. +See :func:`spans.is_group`. 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. +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. """ 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`, and `_KIND_CATEGORY` omits groups so they accrue 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. -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. -_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. Without a request ID, Harbor can leave duplicate call spans for `fold_llm_requests` to join. -_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. - - 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. - """ - 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. - """ - 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 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. - - ``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. - """ - - 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*. - - 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.""" @@ -408,45 +147,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. - """ - 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 = "" @@ -531,333 +231,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. - - 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.""" - 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`? - - 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; this sees what it could not match. - - Everything else with children stays what it is. 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: they never claim to be work. - - 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. 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. @@ -901,206 +274,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. - - 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. - """ - 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. - - 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. @@ -1131,81 +304,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)" @@ -1266,108 +364,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. - """ - 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). The template renders every row so the browser can expand descendants locally. - - *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..70a7b44e --- /dev/null +++ b/app/nullius/traces/waterfall.py @@ -0,0 +1,162 @@ +"""A trace laid out as a waterfall: one global axis, one row per span. + +A bar is placed against the whole trace, never 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. + """ + 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). The template renders every row so the browser can expand descendants locally. + + *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/nullius/workspace.py b/app/nullius/workspace.py index 9f08c61b..b0c0d1b3 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -40,7 +40,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 @@ -113,28 +113,10 @@ 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. 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"), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1)) def load(home_dir: str, name: str) -> Workspace | None: @@ -418,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) - _write_atomically(_index_path(ws), lambda fh: json.dump(index, fh, 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 @@ -444,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) - _write_atomically(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)) + 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/packaging/verify.py b/app/packaging/verify.py index b4169e8d..8df53432 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 1feb9238..dd54a9a8 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; diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index ff28e217..f6110117 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -426,7 +426,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]; }; // short: a proof that met a bound short of the full mark (prove.short_of) - its tick is not green, its bound on hover @@ -449,7 +449,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} @@ -464,7 +464,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/static/style.css b/app/static/style.css index 2e0aabbe..7bf7d7bf 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -735,7 +735,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/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index 9cdd2d2c..4a57c4fc 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -42,7 +42,7 @@ {%- macro vattr(y, cls='') %} class="{{ (cls ~ ' std-version')|trim }}"{% if y.version %} data-version="{{ y.version }}"{% endif %}{% if not y.current %} hidden{% endif %}{% endmacro %} {% if std %} - {#- The standard's proofs of it, per dataset (standard/prove.py): its controls as chips, their source in the title, then its units and leak checks; and Prove it, cli prove as a run. -#} + {#- The standard's proofs of it, per dataset (standard/proofs/prove.py): its controls as chips, their source in the title, then its units and leak checks; and Prove it, cli prove as a run. -#} {% macro proof(rec, failed, expect, short='') -%} {%- if rec %}{% set notes = [short, ('over the first ' ~ rec.limit) if rec.limit, ('shard ' ~ rec.shard) if rec.shard]|select|list %}✓ {{ rec.passed }}{% if rec.limit %} · first {{ rec.limit }}{% endif %} {%- elif failed and failed.value is defined %}{% set e = (failed.expect or expect or {'at_least': 1}) %}{% set k = e|list|first %}✕ {{ failed.value }} {{ '>' if k == 'at_most' else '<' }} {{ e[k] }} diff --git a/app/tests/catalogue_docs.py b/app/tests/catalogue_docs.py index 32d44d85..29572adc 100644 --- a/app/tests/catalogue_docs.py +++ b/app/tests/catalogue_docs.py @@ -27,7 +27,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..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 import container +from nullius.standard.backends import container VAR = "NULLIUS_TEST_DOCKER" diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index 3fa0b57a..4e9b7523 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -56,6 +56,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", @@ -445,47 +471,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", @@ -502,21 +488,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", @@ -586,6 +572,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": [ "closed", diff --git a/app/tests/field_contract.py b/app/tests/field_contract.py index 81035214..3ffce213 100644 --- a/app/tests/field_contract.py +++ b/app/tests/field_contract.py @@ -40,7 +40,8 @@ PACKAGE_OF = { "parse": "nullius.runs", "classify": "nullius.runs", "artifacts": "nullius.runs", "attempts": "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/fixtures/standard/computer_merge_driver.py b/app/tests/fixtures/standard/computer_merge_driver.py index a293c817..67b5c0e7 100644 --- a/app/tests/fixtures/standard/computer_merge_driver.py +++ b/app/tests/fixtures/standard/computer_merge_driver.py @@ -10,7 +10,7 @@ import threading import time -from nullius.standard import computer_port as port, jsonl +from nullius.standard.protocols import computer_port as port, jsonl class Desktop: 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_benchmark_agents.py b/app/tests/test_benchmark_agents.py index ee8afcf6..62a81f41 100644 --- a/app/tests/test_benchmark_agents.py +++ b/app/tests/test_benchmark_agents.py @@ -10,7 +10,9 @@ import unittest from nullius.runs import parse -from nullius.standard import definitions, job, match, recipe +from nullius.standard.contract import definitions, match +from nullius.standard.pages import recipe +from nullius.standard.runner import job BENCHES = os.path.join(definitions.CATALOGUE, "benchmarks") diff --git a/app/tests/test_benchmark_listing.py b/app/tests/test_benchmark_listing.py index 3601a5c6..385e0165 100644 --- a/app/tests/test_benchmark_listing.py +++ b/app/tests/test_benchmark_listing.py @@ -5,7 +5,7 @@ import unittest from nullius.catalogue import catalog -from nullius.standard import recipe +from nullius.standard.pages import recipe class Listing(unittest.TestCase): 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 d53d4bc8..9bdc0055 100644 --- a/app/tests/test_catalog.py +++ b/app/tests/test_catalog.py @@ -11,7 +11,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..d0dcbb59 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 @@ -246,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")) + 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)) + 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_catalogue_sources.py b/app/tests/test_catalogue_sources.py index dd33de45..f7ea2304 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_charts.py b/app/tests/test_charts.py index 7bcaf846..7713c1d4 100644 --- a/app/tests/test_charts.py +++ b/app/tests/test_charts.py @@ -12,10 +12,8 @@ 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 from .tracedata import DEGRADED, RICH, doc, raw, span @@ -294,11 +292,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) @@ -519,21 +517,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_classify.py b/app/tests/test_classify.py index 48f2ae1d..059a2ce2 100644 --- a/app/tests/test_classify.py +++ b/app/tests/test_classify.py @@ -77,7 +77,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: @@ -90,9 +90,10 @@ 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 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) @@ -101,7 +102,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_computer_kit.py b/app/tests/test_computer_kit.py index 9c550be5..3b70f99c 100644 --- a/app/tests/test_computer_kit.py +++ b/app/tests/test_computer_kit.py @@ -23,7 +23,8 @@ import unittest from unittest import mock -from nullius.standard import container, definitions +from nullius.standard.backends import container +from nullius.standard.contract import definitions from tests import docker_tier KIT = os.path.join(definitions.KITS, "agent-computer-v1") @@ -673,7 +674,7 @@ def test_the_five_operations(self): self.assertEqual(sudo["output"].strip(), "None") def test_a_failed_prepare_action_says_its_exit_code_and_cause_without_pyautoguis_warnings(self): - from nullius.standard import computer_port as cp + from nullius.standard.protocols import computer_port as cp bridge = cp.Bridge(self.d, 3, 0, desktop.SCREEN, "/tmp/agent", window=True) bridge._begin(None) self.addCleanup(bridge.finish) diff --git a/app/tests/test_computer_kit_driver.py b/app/tests/test_computer_kit_driver.py index 0aa71b1a..0021759d 100644 --- a/app/tests/test_computer_kit_driver.py +++ b/app/tests/test_computer_kit_driver.py @@ -28,8 +28,9 @@ import zlib from unittest import mock -from nullius.standard import computer_port as port, computer_pipe -from nullius.standard import container, definitions, ports +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 KIT = os.path.join(definitions.KITS, "agent-computer-v1") @@ -159,7 +160,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 4bdc8bb8..710b4ee0 100644 --- a/app/tests/test_computer_merge.py +++ b/app/tests/test_computer_merge.py @@ -14,7 +14,12 @@ from unittest import mock from nullius.runs import artifacts, parse -from nullius.standard import boat, computer_pipe, definitions, install, recipe, run +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 FIX = Path(__file__).parent / "fixtures/standard" diff --git a/app/tests/test_constraints.py b/app/tests/test_constraints.py index 0a4cfbfa..8531f157 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.backends 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]} @@ -299,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) 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"]) @@ -316,7 +321,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.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_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_dependency_surface.py b/app/tests/test_dependency_surface.py index ba5a4134..0c29a6fe 100644 --- a/app/tests/test_dependency_surface.py +++ b/app/tests/test_dependency_surface.py @@ -76,7 +76,7 @@ def test_every_backend_package_is_shipped_once(self): def test_every_file_a_bundled_definition_runs_is_shipped(self): """Every file a host's snapshot takes of a bundled entry is package data too.""" - from nullius.standard import payload + from nullius.standard.runner import payload shipped = tomllib.loads((REPO / "pyproject.toml").read_text(encoding="utf-8"))["tool"]["setuptools"]["package-data"] def covered(package, relative): 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 e1deeb80..2bb9307a 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -829,7 +829,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_execution_job_state.py b/app/tests/test_execution_job_state.py index 0ec5c256..f75e9442 100644 --- a/app/tests/test_execution_job_state.py +++ b/app/tests/test_execution_job_state.py @@ -6,7 +6,7 @@ from pathlib import Path from nullius import execution -from nullius.standard import job +from nullius.standard.runner import job class SharedStep(unittest.TestCase): diff --git a/app/tests/test_harbor_entry.py b/app/tests/test_harbor_entry.py index d0b7279a..c97b0fef 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) 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_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 292cee25..2936ac79 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -194,6 +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) 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) @@ -773,7 +774,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..0ec995a7 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.backends 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_layering.py b/app/tests/test_layering.py new file mode 100644 index 00000000..29295ccd --- /dev/null +++ b/app/tests/test_layering.py @@ -0,0 +1,75 @@ +"""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 + +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, {}) + + +class StandardFolders(unittest.TestCase): + 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.""" + 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) + # 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 + 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_locomo_rag.py b/app/tests/test_locomo_rag.py index 53ac8d1f..beb6e227 100644 --- a/app/tests/test_locomo_rag.py +++ b/app/tests/test_locomo_rag.py @@ -15,7 +15,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..58f43fef 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.backends 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 @@ -18,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')) @@ -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..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 import container +from nullius.standard.backends import container NO_DOCKER = lambda: False diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py new file mode 100644 index 00000000..7db0a70e --- /dev/null +++ b/app/tests/test_ondisk.py @@ -0,0 +1,188 @@ +"""``nullius.ondisk``: a file written whole, a lock, a digest.""" +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, "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(self.tmp)) + + 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()) + 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 + 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) + + 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) + 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 + 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_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")): + with self.assertRaises(OSError): + ondisk.write_whole(self.path, "lost") + with self.assertRaises(TypeError): + ondisk.write_whole(self.path, 42) + 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)] + 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) + 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) + 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) + 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_osworld1_agent_side.py b/app/tests/test_osworld1_agent_side.py index f8db11a1..20cdfbef 100644 --- a/app/tests/test_osworld1_agent_side.py +++ b/app/tests/test_osworld1_agent_side.py @@ -23,7 +23,7 @@ import time import unittest -from nullius.standard import jsonl +from nullius.standard.protocols import jsonl APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ENTRY = os.path.join(APP, "nullius", "catalogue", "benchmarks", "osworld1") @@ -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 e85094d0..b4bf5e59 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") @@ -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() @@ -344,7 +354,7 @@ def stand_in_runner(self): self.addCleanup(lambda: [self.d._reap_runner(w, seconds=0) for w in list(self.d.RUNNERS)]) def test_the_step_option_reaches_the_runner_with_the_port_default(self): - from nullius.standard import definitions + from nullius.standard.contract import definitions self.stand_in_runner() open(self.go, "w").close() ws = os.path.join(self.tmp, "job", "trial", "workspace") @@ -625,11 +635,11 @@ class Snapshot(unittest.TestCase): def test_the_entrys_copy_holds_the_runner_and_the_package_the_ports_code(self): from pathlib import Path - from nullius.standard import payload + from nullius.standard.runner import payload 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_api_logs.py b/app/tests/test_osworld2_api_logs.py index 1c1815bb..c9fdd70f 100644 --- a/app/tests/test_osworld2_api_logs.py +++ b/app/tests/test_osworld2_api_logs.py @@ -376,7 +376,7 @@ class Snapshot(unittest.TestCase): def test_a_hosts_snapshot_carries_the_packer(self): from pathlib import Path - from nullius.standard import payload + from nullius.standard.runner import payload self.assertIn("api_logs.py", payload._entry(Path(HERE))) diff --git a/app/tests/test_osworld2_gitlab.py b/app/tests/test_osworld2_gitlab.py index c3d1f54c..f7709ca7 100644 --- a/app/tests/test_osworld2_gitlab.py +++ b/app/tests/test_osworld2_gitlab.py @@ -428,7 +428,7 @@ def test_the_sites_that_serve_gitlab_are_checked_among_what_a_vm_start_needs(sel def test_a_hosts_snapshot_carries_the_module(self): from pathlib import Path - from nullius.standard import payload + from nullius.standard.runner import payload tmp = Path(tempfile.mkdtemp(prefix="nullius-osworld2-")) self.addCleanup(shutil.rmtree, tmp, True) with mock.patch.dict(os.environ, {"NULLIUS_HOME": str(tmp / "profile"), "NULLIUS_CATALOGUE": str(tmp / "catalogue")}): diff --git a/app/tests/test_osworld2_judge.py b/app/tests/test_osworld2_judge.py index dc18215d..45580071 100644 --- a/app/tests/test_osworld2_judge.py +++ b/app/tests/test_osworld2_judge.py @@ -21,7 +21,9 @@ from unittest import mock from nullius import providers -from nullius.standard import definitions, relay, run +from nullius.standard.calls import relay +from nullius.standard.contract import definitions +from nullius.standard.runner import run APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) HERE = os.path.join(APP, "nullius", "catalogue", "benchmarks", "osworld2") diff --git a/app/tests/test_osworld2_muse.py b/app/tests/test_osworld2_muse.py index aa2d6f01..40b8455e 100644 --- a/app/tests/test_osworld2_muse.py +++ b/app/tests/test_osworld2_muse.py @@ -18,7 +18,12 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest import mock -from nullius.standard import container, definitions, job, jsonl, recipe, relay, run +from nullius.standard.backends import container +from nullius.standard.calls import relay +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.protocols import jsonl +from nullius.standard.runner import job, run APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) HERE = os.path.join(APP, "nullius", "catalogue", "benchmarks", "osworld2") diff --git a/app/tests/test_osworld2_nop.py b/app/tests/test_osworld2_nop.py index 734e0e0d..e476294a 100644 --- a/app/tests/test_osworld2_nop.py +++ b/app/tests/test_osworld2_nop.py @@ -15,7 +15,8 @@ import unittest from unittest import mock -from nullius.standard import definitions, run +from nullius.standard.contract import definitions +from nullius.standard.runner import run HERE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "catalogue", "benchmarks", "osworld2") diff --git a/app/tests/test_osworld2_stop.py b/app/tests/test_osworld2_stop.py index 9c984674..aa808386 100644 --- a/app/tests/test_osworld2_stop.py +++ b/app/tests/test_osworld2_stop.py @@ -22,7 +22,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest import mock -from nullius.standard import relay +from nullius.standard.calls import relay HERE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "catalogue", "benchmarks", "osworld2") diff --git a/app/tests/test_osworld2_websites.py b/app/tests/test_osworld2_websites.py index 3b550fd2..ee35fccf 100644 --- a/app/tests/test_osworld2_websites.py +++ b/app/tests/test_osworld2_websites.py @@ -641,7 +641,7 @@ def test_the_sites_are_checked_among_what_a_vm_start_needs(self): def test_a_hosts_snapshot_carries_the_module_and_the_override(self): from pathlib import Path - from nullius.standard import payload + from nullius.standard.runner import payload tmp = Path(tempfile.mkdtemp(prefix="nullius-osworld2-")) self.addCleanup(shutil.rmtree, tmp, True) with mock.patch.dict(os.environ, {"NULLIUS_HOME": str(tmp / "profile"), "NULLIUS_CATALOGUE": str(tmp / "catalogue")}): diff --git a/app/tests/test_osworld2_write_limit.py b/app/tests/test_osworld2_write_limit.py index abf2d935..b55c4977 100644 --- a/app/tests/test_osworld2_write_limit.py +++ b/app/tests/test_osworld2_write_limit.py @@ -14,7 +14,8 @@ from pathlib import Path from unittest import mock -from nullius.standard import definitions, run +from nullius.standard.contract import definitions +from nullius.standard.runner import run APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) HERE = os.path.join(APP, "nullius", "catalogue", "benchmarks", "osworld2") @@ -539,7 +540,7 @@ def test_the_original_setups_turn_holds_500_steps(self): class Snapshot(unittest.TestCase): def test_a_hosts_snapshot_carries_the_startup_file(self): - from nullius.standard import payload + from nullius.standard.runner import payload tmp = Path(tempfile.mkdtemp(prefix="nullius-osworld2-")) self.addCleanup(shutil.rmtree, tmp, True) with mock.patch.dict(os.environ, {"NULLIUS_HOME": str(tmp / "profile"), "NULLIUS_CATALOGUE": str(tmp / "catalogue")}): 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_prerequisites.py b/app/tests/test_prerequisites.py index d47e5be4..87383512 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.backends 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 90aafd02..b4afaf6b 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_provider_pins.py b/app/tests/test_provider_pins.py index c0f2c7d6..7cccb86e 100644 --- a/app/tests/test_provider_pins.py +++ b/app/tests/test_provider_pins.py @@ -8,7 +8,10 @@ from unittest.mock import Mock, patch from nullius import providers -from nullius.standard import cli, recipe, relay, run +from nullius.standard import cli +from nullius.standard.calls import relay +from nullius.standard.pages import recipe +from nullius.standard.runner import run from tests import test_standard_recipe_served_by as recipes from tests import test_standard_served_by as calls diff --git a/app/tests/test_provider_registry.py b/app/tests/test_provider_registry.py index 56138b01..4448257f 100644 --- a/app/tests/test_provider_registry.py +++ b/app/tests/test_provider_registry.py @@ -13,7 +13,7 @@ from nullius.judge import client from nullius.recipes.launch import payload from nullius.catalogue import catalog -from nullius.standard import run +from nullius.standard.runner import run KEYS = {"OPENROUTER_API_KEY": "sk-or-fixture-0001", "OPENAI_API_KEY": "sk-oa-fixture-0002", "ANTHROPIC_API_KEY": "sk-ant-fixture-0003", "MODEL_GW_API_KEY": "sk-gw-fixture-0004"} 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 de4771c8..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 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 7f8d0644..d8a25102 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.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') 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.backends 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 e51a965c..1fb109f9 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") @@ -57,7 +57,8 @@ def test_a_run_reads_a_data_providers_token_from_its_provider_alone(self): self.assertEqual(held.get("HF_TOKEN"), {"kind": "value", "value": "shared-synthetic"}) def test_a_headless_run_takes_a_data_providers_token_from_its_environment_first(self): - from nullius.standard import cli, run + from nullius.standard import cli + 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"}]}}} env = {"HF_TOKEN": "env-synthetic", "LICENSE_KEY": "env-licence-synthetic"} @@ -75,7 +76,8 @@ def test_a_headless_run_takes_a_data_providers_token_from_its_environment_first( self.assertEqual(cli.licences(bench, env=handed)[0].get("HF_TOKEN"), {"kind": "value", "value": "handed-synthetic"}) def test_a_benchmark_that_declares_no_provider_takes_nothing_from_the_environment(self): - from nullius.standard import cli, run + from nullius.standard import cli + from nullius.standard.runner import run bench = {"key": "bench-a", "environments": {"e": {"needs_secrets": [{"name": "HF_TOKEN", "to": "driver"}]}}} held = cli.licences(bench, env={"HF_TOKEN": "env-synthetic"})[0] self.assertEqual(held.environ, {}) @@ -148,7 +150,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()} @@ -189,7 +191,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) @@ -198,7 +200,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) @@ -214,7 +216,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 c2a80c52..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/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/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 60c73c83..49096f92 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.backends 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.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') 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.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:]), {})) @@ -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 801bd2e2..58936654 100644 --- a/app/tests/test_standard_acp.py +++ b/app/tests/test_standard_acp.py @@ -8,7 +8,7 @@ import time 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") @@ -112,7 +112,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 197b4b46..4020ba51 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") @@ -152,7 +155,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_boat.py b/app/tests/test_standard_boat.py index cf106a93..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,13 +14,17 @@ import urllib.error from unittest import mock -from nullius.standard import boat, definitions, recipe, run +from nullius.standard.backends import boat +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.runner import run from .test_standard_recipe import a_recipe, defs from .test_standard_run import ROOT, Echo from http.server import ThreadingHTTPServer from nullius.runs import parse -from nullius.standard import install, job +from nullius.standard.requirements import install +from nullius.standard.runner import job class Answer: diff --git a/app/tests/test_standard_boat_units.py b/app/tests/test_standard_boat_units.py index 6c862248..d048d527 100644 --- a/app/tests/test_standard_boat_units.py +++ b/app/tests/test_standard_boat_units.py @@ -12,7 +12,11 @@ import unittest from nullius import secrets -from nullius.standard import boat_units, cli, definitions, recipe, run, 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 boat_units, run OSWORLD1 = definitions.get("benchmark", "osworld1") 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 f70081f5..dca3f5e7 100644 --- a/app/tests/test_standard_check_safety.py +++ b/app/tests/test_standard_check_safety.py @@ -16,7 +16,9 @@ import urllib.request from unittest import mock -from nullius.standard import container, definitions, egress, run +from nullius.standard.backends 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_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 da3a1b5a..9f1d1739 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 699750af..95a4fa87 100644 --- a/app/tests/test_standard_conform.py +++ b/app/tests/test_standard_conform.py @@ -12,7 +12,12 @@ from types import SimpleNamespace from unittest import mock -from nullius.standard import cli, conform, container, definitions, install, match, retries, run +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 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 6efe48fa..792ed1e8 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.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 b25ff1b2..738221d1 100644 --- a/app/tests/test_standard_context_window.py +++ b/app/tests/test_standard_context_window.py @@ -11,7 +11,10 @@ from unittest.mock import patch from nullius.runs import classify, parse -from nullius.standard import definitions, install, job, relay, retries, run +from nullius.standard.calls import relay +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +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" @@ -21,7 +24,7 @@ AGENT_OK = {"status": 200} OVERFLOW = {"status": 400, "error": OPENROUTER} SIDE_EMPTY = {"status": 400, "error": EMPTY, "side": True} -ANSWERING = '''from nullius.standard.jsonl import serve +ANSWERING = '''from nullius.standard.protocols.jsonl import serve def answer(unit, dir, setup, model, base_url, key, **_): raise RuntimeError("the upstream's runner ended on its simulated user's error") serve({"units": lambda dataset, setup=None: {"units": ["a"]}, "setup": lambda unit, dir: {"prompt": "hi"}, @@ -30,7 +33,7 @@ def answer(unit, dir, setup, model, base_url, key, **_): STOPPED = ANSWERING.replace('raise RuntimeError("the upstream\'s runner ended on its simulated user\'s error")', 'return {"answer": "DONE"}').replace('{"reward": 0.0, "detail": {}}', '{"reward": 0.5, "detail": {}, "stopped": "context window"}') -UNREAD = '''from nullius.standard.jsonl import serve +UNREAD = '''from nullius.standard.protocols.jsonl import serve class VerifierError(RuntimeError): pass def score(unit, dir, **_): diff --git a/app/tests/test_standard_controls.py b/app/tests/test_standard_controls.py index 2adc3e6f..7f7b1107 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) @@ -167,7 +171,7 @@ def test_a_standard_job_named_oracle_without_the_record_is_no_control(self): SLOW_SCORE = '''import os, time -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve CHECKED = os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), "checked")) def setup(unit, dir): return dict({"prompt": "hi"}, **({"verify": {"run": "true"}} if CHECKED else {})) @@ -301,7 +305,7 @@ def test_the_result_has_every_check_and_its_jobs_and_proven_is_written_without_t 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"]) @@ -455,7 +459,7 @@ def test_an_option_whose_value_needs_a_program_this_machine_lacks_is_refused_bef self.assertFalse(os.path.exists(self.jobs)) def test_a_job_is_not_recorded_when_the_units_check_fails(self): - from nullius.standard import merge + from nullius.standard.runner import merge whole = merge.merge([self.nop_shard(i, 4, "a") for i in (1, 3)], os.path.join(self.jobs, "nop-merged"))["out"] self.b["datasets"][0]["units"] = 4 got = self.prove(dataset="kit", bench_options={"sites": "on"}, jobs={"nop": whole})["kit"] @@ -481,7 +485,7 @@ def test_a_control_is_not_run_nor_kept_when_the_units_check_fails(self): self.assertFalse(os.path.exists(self.jobs) and any("prove-" in x for x in os.listdir(self.jobs))) def test_a_trial_of_another_job_cannot_be_merged_into_a_proof(self): - from nullius.standard import merge + from nullius.standard.runner import merge shards = [self.nop_shard(i, 4, "a") for i in (1, 3)] trial = next(t for t in sorted(os.listdir(shards[0])) if os.path.isfile(os.path.join(shards[0], t, "result.json"))) path = os.path.join(shards[0], trial, "result.json") @@ -500,7 +504,7 @@ def test_a_trial_of_another_job_cannot_be_merged_into_a_proof(self): r["problems"]) def test_a_merge_of_merges_keeps_what_any_of_them_was_merged_despite(self): - from nullius.standard import merge + from nullius.standard.runner import merge good_shard, bad_shard = (self.nop_shard(i, 4, "a") for i in (1, 3)) trial = next(t for t in sorted(os.listdir(bad_shard)) if os.path.isfile(os.path.join(bad_shard, t, "result.json"))) path = os.path.join(bad_shard, trial, "result.json") @@ -536,7 +540,7 @@ def test_the_cli_hands_its_options_and_jobs_to_the_proof(self): cli.main(["prove", "agent-task-v1", "--from-run", "--job", "reference=/x"]) def test_a_merged_launch_is_held_to_the_bound_as_one_job_and_must_cover_every_unit(self): - from nullius.standard import merge + from nullius.standard.runner import merge shards = [self.nop_shard(i, 4, lane) for i, lane in ((1, "a"), (3, "b"))] whole = merge.merge(shards, os.path.join(self.jobs, "nop-merged"))["out"] before = sorted(os.listdir(self.jobs)) @@ -581,7 +585,7 @@ class HeldJob(unittest.TestCase): """A control's job held to its bound, read from each trial's own record.""" def setUp(self): - from nullius.standard import job + from nullius.standard.runner import job self.tmp = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, self.tmp, True) self.dir = os.path.join(self.tmp, "nop-job") os.makedirs(self.dir) @@ -631,7 +635,7 @@ def test_a_trial_another_run_wrote_is_refused(self): self.assertIn(f"whose own record names another {k} than the job", said) -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): @@ -652,7 +656,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"]} @@ -747,7 +751,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 75aa33aa..6e8e85a9 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_driver_hooks.py b/app/tests/test_standard_driver_hooks.py index 515edcaa..1776d32e 100644 --- a/app/tests/test_standard_driver_hooks.py +++ b/app/tests/test_standard_driver_hooks.py @@ -14,7 +14,12 @@ from unittest import mock -from nullius.standard import definitions, install, jsonl, prove, recipe, run +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.proofs import prove +from nullius.standard.protocols import jsonl +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") BENCH = { @@ -27,7 +32,7 @@ } # A driver that records what setup was told, in the unit's trial folder. DRIVER = '''import json, os -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def setup(unit, dir, **told): with open(os.path.join(os.path.dirname(dir), "told.json"), "w") as f: json.dump(told, f) @@ -466,7 +471,7 @@ def test_setup_gets_the_benchmarks_own_limit(self): # A driver that is told when the agent is given its task: it marks the trial, and records each score's answer. GIVEN_DRIVER = '''import json, os, time -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def setup(unit, dir, **told): with open(os.path.join(os.path.dirname(dir), "told.json"), "w") as f: json.dump(told, f) diff --git a/app/tests/test_standard_environments.py b/app/tests/test_standard_environments.py index df70a626..c3d0a2fb 100644 --- a/app/tests/test_standard_environments.py +++ b/app/tests/test_standard_environments.py @@ -22,7 +22,11 @@ from nullius import secrets, settings from nullius.runs import classify, parse -from nullius.standard import cli, container, definitions, install, run +from nullius.standard import cli +from nullius.standard.backends 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..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 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_gated.py b/app/tests/test_standard_gated.py index f5f35b8a..3d0b40c7 100644 --- a/app/tests/test_standard_gated.py +++ b/app/tests/test_standard_gated.py @@ -8,19 +8,22 @@ import unittest from unittest.mock import patch -from nullius.standard import definitions, install, relay, run +from nullius.standard.calls import relay +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", "catalogue") CONTROLS = {"nop": {"source": "nullius", "from": "Nothing runs; the answer is empty."}} WORDS = "the gated task's own sentence" -FAILING = '''from nullius.standard.jsonl import serve +FAILING = '''from nullius.standard.protocols.jsonl import serve def score(unit, dir, transcript, answer, **_): raise RuntimeError("the LLM grader's endpoint answered 500, and the task was scored without it") serve({"units": lambda dataset: {"units": ["a"]}, "setup": lambda unit, dir: {"prompt": "hi"}, "score": score}) ''' -ANSWERING = '''from nullius.standard.jsonl import serve +ANSWERING = '''from nullius.standard.protocols.jsonl import serve def answer(unit, dir, setup, model, base_url, key, **_): raise RuntimeError("the upstream's grader said: status 500: " + %r) serve({"units": lambda dataset, setup=None: {"units": ["a"]}, "setup": lambda unit, dir: {"prompt": "hi"}, 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..417c7459 100644 --- a/app/tests/test_standard_install.py +++ b/app/tests/test_standard_install.py @@ -10,7 +10,8 @@ import unittest from unittest import mock -from nullius.standard import install +from nullius import ondisk +from nullius.standard.requirements import install class UpstreamTest(unittest.TestCase): @@ -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_ledger.py b/app/tests/test_standard_ledger.py index c1fa974a..7fb2069e 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} @@ -246,7 +246,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 6fa46700..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.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,10 @@ import unittest from unittest import mock -from nullius.standard import container, definitions, install, mcp_machine, run +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 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 9c35789c..e24cc67c 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 609e024e..90f5e720 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.backends 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 318af120..2a2d6888 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 9150fde7..0d533808 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 6653fd43..5630e073 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") @@ -462,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_recipe_served_by.py b/app/tests/test_standard_recipe_served_by.py index a24a99e6..0b8ef2ae 100644 --- a/app/tests/test_standard_recipe_served_by.py +++ b/app/tests/test_standard_recipe_served_by.py @@ -12,7 +12,8 @@ import urllib.error from nullius import providers -from nullius.standard import definitions, recipe +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") NOP = {"nop": {"source": "nullius", "from": "nothing said"}} diff --git a/app/tests/test_standard_relay.py b/app/tests/test_standard_relay.py index fc44bdfd..4cf50c6e 100644 --- a/app/tests/test_standard_relay.py +++ b/app/tests/test_standard_relay.py @@ -21,7 +21,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}}} @@ -674,7 +676,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) @@ -717,7 +719,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()) @@ -1028,7 +1030,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}) @@ -1038,7 +1040,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_retries.py b/app/tests/test_standard_retries.py index dda11ead..c00b1b12 100644 --- a/app/tests/test_standard_retries.py +++ b/app/tests/test_standard_retries.py @@ -3,7 +3,7 @@ import time import unittest -from nullius.standard import pace, retries +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 07495cc6..16ee1103 100644 --- a/app/tests/test_standard_run.py +++ b/app/tests/test_standard_run.py @@ -18,12 +18,17 @@ from nullius import progress from nullius.runs import classify, live, parse -from nullius.standard import acp, container, definitions, install, jsonl, ledger, pace as pacing, relay, run +from nullius.standard.backends import container +from nullius.standard.calls import ledger, relay +from nullius.standard.contract import definitions +from nullius.standard.protocols import acp, jsonl +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"]) @@ -42,7 +47,7 @@ def turn(unit, dir, transcript, simulator=None): ''' SLOW_CHAT_DRIVER = '''import time -from nullius.standard.jsonl import serve +from nullius.standard.protocols.jsonl import serve def turn(unit, dir, transcript): time.sleep(0.6) # each reply quick, the user slow: the conversation never ends by itself return {"message": "more"} @@ -50,7 +55,7 @@ def turn(unit, dir, transcript): "score": lambda unit, dir, transcript, answer: {"reward": 1.0, "passed": True, "detail": {}}}) ''' -CALLING_CHAT_DRIVER = '''from nullius.standard.jsonl import serve +CALLING_CHAT_DRIVER = '''from nullius.standard.protocols.jsonl import serve def turn(unit, dir, transcript): if sum(1 for t in transcript if t["role"] == "user") >= 4: return {"done": True} @@ -60,7 +65,7 @@ def turn(unit, dir, transcript): ''' 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()) @@ -70,7 +75,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") @@ -79,7 +84,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": {}}}) ''' @@ -89,11 +94,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": {}}}) ''' @@ -1034,7 +1039,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"] = { @@ -1256,7 +1261,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.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"} @@ -1324,7 +1329,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.backends 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"} @@ -1345,7 +1351,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.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 b7d4c379..d5bb3c57 100644 --- a/app/tests/test_standard_served_by.py +++ b/app/tests/test_standard_served_by.py @@ -27,7 +27,12 @@ from unittest import mock from nullius import progress -from nullius.standard import cli, container, definitions, install, job, merge, relay, run +from nullius.standard import cli +from nullius.standard.backends import container +from nullius.standard.calls import relay +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import job, merge, run ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -375,7 +380,7 @@ def test_the_relays_own_command_refuses_a_pin_it_cannot_take(self): for given in (["m=bad slug"], ["m=prov-a,prov-a"], ["m="], ["m=prov-a", "m=prov-b"], ["prov-a"]): with self.subTest(given=given): # a process of its own, bounded: a relay that took the pin would serve until stopped - got = subprocess.run([sys.executable, "-m", "nullius.standard.relay", "serve", "--listen", "127.0.0.1:0", + got = subprocess.run([sys.executable, "-m", "nullius.standard.calls.relay", "serve", "--listen", "127.0.0.1:0", "--base", self.base, "--record", os.path.join(self.tmp, "rec"), "--key-file", key, *[w for g in given for w in ("--served-by", g)]], cwd=APP, env=dict(os.environ, PYTHONPATH=APP), capture_output=True, text=True, timeout=20) @@ -386,7 +391,7 @@ def test_the_relay_as_a_process_of_its_own_puts_the_pin_on_its_requests(self): key = os.path.join(self.tmp, "key") with open(key, "w") as f: f.write("or-test") - p = subprocess.Popen([sys.executable, "-m", "nullius.standard.relay", "serve", "--listen", "127.0.0.1:0", "--base", self.base, + p = subprocess.Popen([sys.executable, "-m", "nullius.standard.calls.relay", "serve", "--listen", "127.0.0.1:0", "--base", self.base, "--record", os.path.join(self.tmp, "rec"), "--key-file", key, "--model", "m-run", "--served-by", "m-run=prov-a,prov-b/fp8", "--routing"], cwd=APP, env=dict(os.environ, PYTHONPATH=APP), stdout=subprocess.PIPE, text=True) diff --git a/app/tests/test_standard_served_by_constraints.py b/app/tests/test_standard_served_by_constraints.py index 25aacdd0..d200384c 100644 --- a/app/tests/test_standard_served_by_constraints.py +++ b/app/tests/test_standard_served_by_constraints.py @@ -15,7 +15,12 @@ from unittest import mock from nullius import constraints, progress -from nullius.standard import cli, container, definitions, install, job, merge, recipe, run +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.requirements import install +from nullius.standard.runner import job, merge, run from tests import test_standard_recipe_served_by as recipes diff --git a/app/tests/test_standard_setup_checks.py b/app/tests/test_standard_setup_checks.py index d4d106d6..669ae6ea 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.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 83a6a2c7..fc1bb39c 100644 --- a/app/tests/test_standard_setups.py +++ b/app/tests/test_standard_setups.py @@ -13,12 +13,16 @@ from unittest.mock import patch from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from nullius.standard import definitions, hostreq, install, match, recipe, run +from nullius import ondisk +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 +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.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 import container + from nullius.standard.backends import container why = docker_tier.why_not() if why: self.skipTest(why) @@ -250,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") @@ -419,7 +423,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 37a29399..cfedc7f7 100644 --- a/app/tests/test_standard_shard.py +++ b/app/tests/test_standard_shard.py @@ -17,7 +17,8 @@ from nullius import workspace from nullius.runs import launches, parse -from nullius.standard import job, merge, prove, shard +from nullius.standard.proofs import prove +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 a89dba2f..f807292d 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 6bf9dcc9..dfc01b90 100644 --- a/app/tests/test_standard_tau3_bench.py +++ b/app/tests/test_standard_tau3_bench.py @@ -18,7 +18,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..009f6206 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.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() @@ -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 ee0c3d32..58dec018 100644 --- a/app/tests/test_standard_trace.py +++ b/app/tests/test_standard_trace.py @@ -9,8 +9,9 @@ import unittest from unittest import mock -from nullius.standard import job +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"} @@ -268,7 +269,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_standard_ui.py b/app/tests/test_standard_ui.py index a3de3af5..2a757a2f 100644 --- a/app/tests/test_standard_ui.py +++ b/app/tests/test_standard_ui.py @@ -12,7 +12,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 585a4767..7189c2c4 100644 --- a/app/tests/test_standard_units.py +++ b/app/tests/test_standard_units.py @@ -21,7 +21,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.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 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..bac3c7df 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.backends 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 1c860879..be658b82 100644 --- a/app/tests/test_standard_versions.py +++ b/app/tests/test_standard_versions.py @@ -13,7 +13,10 @@ import unittest from unittest.mock import patch -from nullius.standard import cli, conform, definitions, match +from nullius import ondisk +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 +272,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 +288,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 +365,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") @@ -370,15 +373,15 @@ 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)) 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 a2413bc7..227e34a5 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_trace.py b/app/tests/test_trace.py index 6c0063b4..1f5699c9 100644 --- a/app/tests/test_trace.py +++ b/app/tests/test_trace.py @@ -15,11 +15,12 @@ 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 +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 @@ -34,37 +35,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) @@ -153,7 +123,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 @@ -184,7 +154,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): @@ -212,7 +182,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) @@ -232,14 +202,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): @@ -294,7 +264,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"): @@ -342,13 +312,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): @@ -448,7 +418,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): @@ -578,14 +548,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 d87d3518..7ca725ba 100644 --- a/app/tests/test_trace_filter.py +++ b/app/tests/test_trace_filter.py @@ -21,6 +21,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 @@ -47,7 +50,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): @@ -208,7 +211,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): @@ -223,7 +226,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): @@ -232,12 +235,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) @@ -319,7 +322,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) @@ -329,13 +332,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): @@ -391,7 +394,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): @@ -421,8 +424,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 85cc1e83..04b3a32d 100644 --- a/app/tests/test_trace_fold.py +++ b/app/tests/test_trace_fold.py @@ -32,6 +32,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 @@ -118,11 +122,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): @@ -270,20 +274,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) @@ -291,20 +295,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): @@ -312,7 +316,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) @@ -321,7 +325,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/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/tests/test_workspace.py b/app/tests/test_workspace.py index aff3f7ea..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 @@ -262,7 +263,20 @@ 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_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) 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 ff80abe1..4cfbbf2a 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -13,10 +13,10 @@ 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 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") @@ -125,7 +125,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) 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 +623,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): @@ -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)) + 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__": diff --git a/app/ui_tests/test_capped_job.py b/app/ui_tests/test_capped_job.py index 57fdfd96..fd799b52 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 7bc74f13..198a3c6c 100644 --- a/app/ui_tests/test_every_route.py +++ b/app/ui_tests/test_every_route.py @@ -30,6 +30,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` from nullius import gitrefs @@ -124,7 +125,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 "" @@ -165,10 +166,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 298f9cf9..de020c38 100644 --- a/app/ui_tests/test_launch_shards.py +++ b/app/ui_tests/test_launch_shards.py @@ -21,7 +21,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 848b5f7f..a4dfe079 100644 --- a/app/ui_tests/test_live_board.py +++ b/app/ui_tests/test_live_board.py @@ -24,7 +24,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_run_routes.py b/app/ui_tests/test_run_routes.py index 43a11e22..6340c0f1 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, hosts, workspace @@ -164,6 +165,21 @@ 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): + """``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}): + 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") @@ -1025,7 +1041,7 @@ def test_a_delete_it_cannot_do_says_why(self): self.assertEqual(web.runs._undeletable([self.ex]), "") def test_runs_and_checks_are_counted_alike_on_both_pages(self): - from nullius.standard import merge + from nullius.standard.runner import merge from tests.test_standard_shard import write_shard key = self.sharded() s1 = next(e for e in execution.EXECUTIONS.values() if e.plan.name == "s1") diff --git a/app/ui_tests/test_runs_by_launch.py b/app/ui_tests/test_runs_by_launch.py index 570c7e53..0f4207d1 100644 --- a/app/ui_tests/test_runs_by_launch.py +++ b/app/ui_tests/test_runs_by_launch.py @@ -143,7 +143,7 @@ def test_a_part_held_back_by_a_pause_or_an_ended_run_reads_not_run(self): self.assertIn(says, block) def test_finished_kits_do_not_inherit_the_shared_process_state(self): - from nullius.standard import job + from nullius.standard.runner import job with tempfile.TemporaryDirectory() as root: plan = execution.Plan(name="kits", script="conform", runner="standard", jobs=[{"name": "kit-conversation"}, {"name": "kit-tools"}, {"name": "kit-computer"}]) diff --git a/app/ui_tests/test_settings_page.py b/app/ui_tests/test_settings_page.py index e09e39c4..2112772d 100644 --- a/app/ui_tests/test_settings_page.py +++ b/app/ui_tests/test_settings_page.py @@ -1120,7 +1120,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()} @@ -1143,7 +1143,8 @@ def test_the_boat_key_is_saved_from_this_machines_browser_and_never_echoed(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 4fe75d1a..2489444a 100644 --- a/app/web/agents.py +++ b/app/web/agents.py @@ -4,7 +4,7 @@ Each entry is its definition in the catalogue (``catalogue/agents//``, ``catalogue/capabilities//``, ``docs/standard.md``): its port proofs and benchmark compatibility drive the page. *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. A versioned entry is one card; ``?v=`` picks the version its page shows. @@ -21,14 +21,15 @@ 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, ports -from nullius.standard import recipe as standard_recipe +from nullius.standard.contract import definitions, ports +from nullius.standard.pages import howto +from nullius.standard.proofs import conform +from nullius.standard.pages import recipe as standard_recipe from .core import app from . import shared from . import execute from .filters import agent_mark_url -from . import settings as settings_web def _page(kind: str): @@ -103,7 +104,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") @@ -132,7 +133,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 {})) @@ -151,12 +152,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 87eb8f4c..8269e2a3 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -9,14 +9,16 @@ import urllib.request from concurrent.futures import ThreadPoolExecutor from flask import abort, jsonify, render_template, request -from nullius.standard import ports +from nullius.standard.contract import ports from nullius import constraints, settings, execution, gitrefs, hosts, prerequisites, providers from nullius.harbor import source as harbor_source 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, definitions, hostreq -from nullius.standard import recipe as standard_recipe +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 from .core import app from .filters import agent_mark_url @@ -200,7 +202,7 @@ def _builder_data() -> dict: "why": types.get(k)} for k, z in boat.SIZES.items() if not types or k in types], "boatSlots": account.get("slots"), "boatKey": bool(boat.key()), "licences": _licence_states(), "host": host} data["csrf"] = shared._csrf_token() - data["local"] = shared_local_client() + data["local"] = shared._local_client() data["recipesWhy"] = WRITE_HERE return data @@ -236,7 +238,7 @@ def new_run_prerequisites(): label, rows}], ready, notes}. 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 {} @@ -311,7 +313,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: @@ -332,7 +334,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: @@ -348,7 +350,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): @@ -366,7 +368,7 @@ def _licence_states() -> dict: def _recipe_write(): shared._require_csrf() - if not shared_local_client(): + if not shared._local_client(): abort(403, description=WRITE_HERE) if request.content_length and request.content_length > 10 * recipe_store.MAX_BYTES: abort(413) @@ -415,15 +417,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: @@ -574,7 +571,7 @@ def new_run_endpoints(): """The serving providers OpenRouter lists for one model, for the Model step's Served by; asked as the model list is, with the key kept 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 @@ -591,7 +588,7 @@ def new_run_endpoints(): 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 da117e28..b3b9ea7f 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -12,9 +12,10 @@ 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 +from nullius.standard.proofs import prove +from nullius.standard.pages import recipe as standard_recipe from .core import app from . import execute @@ -111,14 +112,14 @@ def benchmark_page(key): editable=entry is not None and not harbor_entry.not_editable(entry), std=std, std_jobs=jobs, versions=versions, views=views, 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: @@ -139,7 +140,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.") version = request.form.get("version", "") back = url_for("benchmark_page", key=key, **({"v": version} if version else {})) + "#standard" @@ -155,12 +156,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) @@ -177,7 +176,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") @@ -230,7 +229,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.") @@ -300,7 +299,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 b8f9d106..264c92dd 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -8,11 +8,11 @@ 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, recipe as standard_recipe +from nullius.standard.backends import boat +from nullius.standard.pages import recipe as standard_recipe from .core import app from . import shared -from . import settings as settings_web @app.route("/run", methods=["POST"]) @@ -22,7 +22,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 {} @@ -139,16 +139,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()) @@ -197,19 +190,29 @@ 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``, 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: + 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. - 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/") @@ -226,7 +229,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: @@ -238,7 +241,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/filters.py b/app/web/filters.py index 8c8530bc..217cdacb 100644 --- a/app/web/filters.py +++ b/app/web/filters.py @@ -11,7 +11,8 @@ from nullius.judge import client as judge_client 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/judge.py b/app/web/judge.py index 43a97ea3..3247a817 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -15,7 +15,6 @@ from .core import app from . import shared -from . import settings as settings_web from . import traces def key(lane: str = "decision") -> client.Judge: @@ -269,7 +268,7 @@ def judge_trial(job, trial, api_key: str, post=None, calibration=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/runs.py b/app/web/runs.py index 43f3caf6..d8d8c2a0 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -23,11 +23,10 @@ from nullius.redact import redact from nullius.runs import attempts, classify, feasibility, launches, live, parse from nullius import workspace -from nullius.standard import definitions as standard_definitions +from nullius.standard.contract import definitions as standard_definitions from .core import app from . import shared -from . import settings as settings_web @@ -247,7 +246,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, @@ -737,7 +736,7 @@ def launch_add(key): """Add a launch's job roots to the workspace the form names, or, when it names none, to a new workspace called the form's ``label`` and opened.""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403) g = next((g for g in _every()[1] if g.key == key), None) name = request.form.get("workspace", "") @@ -762,7 +761,7 @@ def launch_delete(key): each shard's copy on its own host when ticked. A launch with a run still going, or with a job from elsewhere, is refused. ``back=launches`` returns to the Launches page.""" shared._require_csrf() - if not settings_web._local_client(): + if not shared._local_client(): abort(403) every = request.form.get("back") == "launches" if shared.STATE["workspace"] is None and not every: diff --git a/app/web/settings.py b/app/web/settings.py index 9ebe747a..74541853 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -7,21 +7,14 @@ 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, container -from nullius.standard import recipe as standard_recipe +from nullius.standard.backends import boat, container +from nullius.standard.pages import recipe as standard_recipe from nullius.judge import client from .core import app 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 @@ -43,7 +36,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()), @@ -83,7 +76,7 @@ def settings_decision_judge_models(): """Decision's models on OpenRouter for its card, asked after the page has loaded: OpenRouter's public list of decision models, kept in the cache (``client.decision_judge_models``).""" shared._require_csrf() - if not _local_client(): + if not shared._local_client(): abort(403) return jsonify(ok=True, models=[{"id": m, "name": m} for m in client.decision_judge_models("openrouter", fetch=True)]) @@ -165,7 +158,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: @@ -211,7 +204,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: @@ -232,7 +225,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() @@ -328,7 +321,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.") @@ -531,7 +524,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 d7dd3b1c..a47855ad 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -561,6 +561,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.""" diff --git a/app/web/workspaces.py b/app/web/workspaces.py index 6b80e79e..c8f94213 100644 --- a/app/web/workspaces.py +++ b/app/web/workspaces.py @@ -14,7 +14,6 @@ from .core import app from . import shared from . import runs as runs_web -from . import settings as settings_web def _not_a_run(real) -> str: @@ -242,7 +241,7 @@ def workspace_root_delete(name): ended (``_root``), as its launch's Delete does - its roots in every workspace, parsed runs and judgements go with it.""" ws, root = _named_root(name) - if not settings_web._local_client(): + if not shared._local_client(): abort(403) info = _root(root, runs_web._held_launches(), {}) if info["why"]: diff --git a/docs/agents/add-manually.md b/docs/agents/add-manually.md index 4621e4eb..00ed78af 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 26e53306..00d9a1f1 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/benchmarks/osworld2-machine.md b/docs/benchmarks/osworld2-machine.md index 57e4c404..7b0a54da 100644 --- a/docs/benchmarks/osworld2-machine.md +++ b/docs/benchmarks/osworld2-machine.md @@ -49,7 +49,8 @@ All 108 tasks of release `osworld-v2.1` run on the docker provider, but 103 and ```bash title="The driver's environment (ENV), OSWorld-V2's clone (UP) and the benchmark's folder (HERE)" 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", "osworld2") print("ENV=" + shlex.quote(install.driver_dir(b))) print("UP=" + shlex.quote(install.upstream_dir(b))) @@ -87,7 +88,8 @@ All 108 tasks of release `osworld-v2.1` run on the docker provider, but 103 and ```bash title="Clone and install" 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", "osworld2") print(install.driver_packages(b)) ' diff --git a/docs/ports/agent-computer-v1.md b/docs/ports/agent-computer-v1.md index c009681d..b1b6bdc0 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`, and `computer_pipe.py` beside it. +The shared code is `app/nullius/standard/protocols/computer_port.py`, and `computer_pipe.py` beside it. | Piece | What the runner gives or does | | --- | --- | diff --git a/pyproject.toml b/pyproject.toml index b949829f..712019be 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.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", ] [tool.setuptools.package-dir]