diff --git a/AGENTS.md b/AGENTS.md index b0a7c618..29c9b48d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,7 @@ and its resources. benchmark's report block - `attempts`, a task's attempts in one job with their pass count and pass@k, and the `cli`), `traces/` (`trace`, the reader, with its span tree `spans`, `fold`, time accounting `breakdown` and layout `waterfall`; `trajectory`, - `conversation`, `charts`, `behavior`, `otel`), `compare/` (`comparison` and its `cli`), + `conversation`, `calls` (a trial's conversation by model call, from its relay's records), `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 datasets nested in it, its `report` block and its `standard.json` when it runs on the standard; @@ -64,7 +64,7 @@ and its resources. `contract/`: `ports`, `names` (capability vocabulary and legacy aliases), `definitions` (with an agent's or capability's versions), `proofs` (generated evidence in sibling `proofs.json`), `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); + `calls/`: `relay`, `exchanges` (each model exchange of a unit's agent kept whole by its relay, and a request rebuilt from it), `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); diff --git a/app/nullius/runs/cli.py b/app/nullius/runs/cli.py index d82549a9..4accea49 100644 --- a/app/nullius/runs/cli.py +++ b/app/nullius/runs/cli.py @@ -6,6 +6,8 @@ PYTHONPATH=app python3 -m nullius.runs.cli show --json PYTHONPATH=app python3 -m nullius.runs.cli show # one trial: what /trial// shows PYTHONPATH=app python3 -m nullius.runs.cli show --json + PYTHONPATH=app python3 -m nullius.runs.cli show --call N --request # call N's request, rebuilt + PYTHONPATH=app python3 -m nullius.runs.cli show --calls # the conversation by model call ```` is anything ``app.py`` accepts as a job root: a Harbor job directory, a parent of several, or a tree the import CLI has already @@ -14,7 +16,14 @@ ones its table shows — from the files on disk, never from a workspace cache. With a trial name, ``show`` reads that trial the way the trial page does — the outcome and checks, the usage and cost, the exception, and the steps of -``agent/trajectory.json`` through ``traces.trajectory``. +``agent/trajectory.json`` through ``traces.trajectory``. With ``--call N +--request`` it prints the request the trial's agent sent in its call N, put +back together from the relay's store of its exchanges +(``standard/calls/exchanges.py``) as the bytes sent, unredacted, and says on stderr +whether their sha256 is the one recorded. With ``--calls`` it prints the +trial's model calls as the Conversation tab shows them (``traces.calls``): +what each sent that the call before had not, its answer whole, the steps +under it; redacted, pictures by their hash. Reading only: nothing is written, anywhere, and no socket is opened. The exit codes are the contract in ``docs/cli.md``, shared by every CLI here. @@ -29,12 +38,14 @@ from datetime import datetime from nullius.runs import parse -from nullius.traces import trajectory +from nullius.standard.calls import exchanges +from nullius.traces import calls as by_call, trajectory # Exit codes — docs/cli.md is the contract. 1 is left to Python itself: an uncaught exception is a bug, and # its traceback is the report. EXIT_OK = 0 EXIT_NOT_FOUND = 3 +EXIT_FAILED = 4 EPILOG = """\ examples: @@ -42,13 +53,15 @@ PYTHONPATH=app python3 -m nullius.runs.cli list jobs jobs_imported --json PYTHONPATH=app python3 -m nullius.runs.cli show jobs 2026-09-12__22-53-55 --json PYTHONPATH=app python3 -m nullius.runs.cli show jobs 2026-09-12__22-53-55 astropy__astropy-8707__agWFDYq + PYTHONPATH=app python3 -m nullius.runs.cli show jobs 2026-09-12__22-53-55 astropy__astropy-8707__agWFDYq --call 3 --request + PYTHONPATH=app python3 -m nullius.runs.cli show jobs 2026-09-12__22-53-55 astropy__astropy-8707__agWFDYq --calls exit codes: 0 done 1 unexpected error (a traceback: report it) 2 usage: a bad flag, a missing argument - 3 input not found: no such root, no job under it, no job of that id, no trial of that name - 4 the operation could not be completed + 3 input not found: no such root, no job under it, no job of that id, no trial of that name, no such call + 4 the operation could not be completed: a request that does not rebuild to its recorded sha256 With --json, stdout is exactly one JSON document; everything else goes to stderr. """ @@ -205,6 +218,31 @@ def _print_trial(job: parse.Job, trial: parse.Trial) -> None: print(f" {s['step_id']:>{width}} {s['source']:<6} {body}{dur}") +def _request(trial: parse.Trial, n: int) -> int: + """Call ``n`` of the trial's agent route rebuilt from its store: the bytes on stdout, the verdict on stderr.""" + folder = os.path.join(trial.dir, ".work", "relay", exchanges.FOLDER) + routes = exchanges.tags(folder) + tag = by_call.route_tag(trial.dir, routes) + if tag not in routes: + print(f"{trial.trial_name} kept no exchanges (a run before them, or --exchanges off)" if not routes + else f"{trial.trial_name} holds the exchanges of several routes: {', '.join(routes)}", file=sys.stderr) + return EXIT_NOT_FOUND + try: + got = exchanges.check(folder, tag, n) + except exchanges.Missing as e: + print(str(e), file=sys.stderr) + return EXIT_NOT_FOUND + if got["request"] is not None: + sys.stdout.buffer.write(got["request"] + b"\n") + sys.stdout.flush() + if got["same"]: + print(f"call {n}: sha256 {got['sha256']}, the recorded sent_sha256", file=sys.stderr) + return EXIT_OK + print(f"call {n}: " + (f"sha256 {got['sha256']}, not the recorded sent_sha256 {got['sent_sha256']}: " if got["sha256"] else "") + + got["why"], file=sys.stderr) + return EXIT_FAILED + + def _emit(doc) -> None: json.dump(doc, sys.stdout, ensure_ascii=False, indent=1, default=_stamp) sys.stdout.write("\n") @@ -247,11 +285,20 @@ def _show(args) -> int: return EXIT_NOT_FOUND if args.trial_name: trial = next((t for t in job.trials if t.trial_name == args.trial_name), None) + if trial is None and (args.call is not None or args.calls): + trial = next((t for current in job.trials for _, t in parse.tries(current) + if t.trial_name == args.trial_name), None) if trial is None: known = ", ".join(t.trial_name for t in job.trials) or "none" print(f"no trial named {args.trial_name!r} in {job.job_id} (trials there: {known})", file=sys.stderr) return EXIT_NOT_FOUND + if args.call is not None: + return _request(trial, args.call) + if args.calls: + traj = trajectory.load(trial.trajectory_path) if trial.has_trajectory else None + _emit(by_call.document(by_call.view(trial.dir, traj))) + return EXIT_OK if args.json: _emit(trial_detail(job, trial)) else: @@ -305,10 +352,22 @@ def main(argv=None) -> int: "checks, usage, exception and steps, as /trial// shows them") sh.add_argument("--json", action="store_true", help="the whole parsed job (or the one trial, with its steps) as one JSON document") + sh.add_argument("--call", type=int, metavar="N", + help="with --request and a trial: its agent's call N, as the call record numbers it (n)") + sh.add_argument("--request", action="store_true", + help="with --call: print the request that call sent, rebuilt from the trial's exchanges, and say " + "on stderr whether its sha256 is the recorded one") + sh.add_argument("--calls", action="store_true", + help="with a trial: its model calls as one JSON document, as the Conversation tab shows them") sh.set_defaults(run=_show) args = ap.parse_args(argv) if not args.command: ap.error("a command is required: list or show") + if args.command == "show" and (args.call is not None or args.request) and not (args.call is not None and args.request + and args.trial_name and not args.json): + sh.error("--call N and --request go together, with a trial, without --json") + if args.command == "show" and args.calls and (not args.trial_name or args.call is not None): + sh.error("--calls goes with a trial, without --call") return args.run(args) diff --git a/app/nullius/standard/backends/container.py b/app/nullius/standard/backends/container.py index 28936865..74672fe4 100644 --- a/app/nullius/standard/backends/container.py +++ b/app/nullius/standard/backends/container.py @@ -115,6 +115,7 @@ from typing import Dict, Iterable, List, Optional, Tuple from nullius import constraints, ondisk, paths +from nullius.standard.calls import exchanges as exchange_store from nullius.standard.contract import definitions from nullius.standard.contract.definitions import step_problems from nullius.standard.requirements import install @@ -729,7 +730,8 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi model: Optional[str], routes: Dict[str, str], prices: Optional[dict] = None, side_models=(), key_header: str = "authorization", hosts: Optional[Dict[str, str]] = None, ledger: Optional[str] = None, serving: Optional[Dict[str, List[str]]] = None, - timeout: Optional[int] = None, max_calls: Optional[int] = None) -> List[str]: + timeout: Optional[int] = None, max_calls: Optional[int] = None, exchanges: str = "off", + exchanges_max_mb: int = exchange_store.MAX_MB) -> List[str]: """``docker run`` for a unit's relay: on the default bridge (its way to the provider), its port published on 127.0.0.1 only. The key is never given: ``key_file``, its file, is mounted read-only at ``RELAY_KEY_IN`` with @@ -739,7 +741,9 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi ``ledger``: the file of the run's spending cap, its folder mounted so this relay books its calls where every other relay of the job does. ``serving``: by model, the serving providers that may answer it, as the - unit's own relay is given them (``relay.Relay``).""" + unit's own relay is given them (``relay.Relay``). ``exchanges`` and + ``exchanges_max_mb``: whether its calls are kept whole in its record + folder, and the bound, always said.""" a = [DOCKER, "run", "-d", "--name", name, "--label", f"{LABEL}={job}", *way_out(), *_userns(), "--user", _user(), "--cap-drop", "ALL", *_security_opt(), "--init", *capped(), *[w for n, ip in sorted((hosts or {}).items()) for w in ("--add-host", f"{n}:{ip}")], @@ -759,6 +763,7 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi a += ["--ledger", ledger] if max_calls: a += ["--max-calls", str(max_calls)] + a += ["--exchanges", exchanges, "--exchanges-max-mb", str(exchanges_max_mb)] for m in side_models: a += ["--side-model", m] # the pins of the models this relay sends; the run's other models (an option's embeddings) are another relay's @@ -1045,9 +1050,11 @@ def __init__(self, job: str, tag: str, record_dir: str, *, image: str, app: str, side_models=(), key_header: str = "authorization", servers: Iterable[str] = (), doors: Iterable[Tuple[str, int, str]] = (), hosts: Optional[Dict[str, str]] = None, ledger: Optional[str] = None, network_probe: Optional[str] = None, probe_now: bool = True, - serving: Optional[Dict[str, List[str]]] = None, timeout: Optional[int] = None, max_calls: Optional[int] = None): + serving: Optional[Dict[str, List[str]]] = None, timeout: Optional[int] = None, max_calls: Optional[int] = None, + exchanges: str = "off", exchanges_max_mb: int = exchange_store.MAX_MB): self.job, self.tag, self.dir, self.image, self.app = job, tag, record_dir, image, app self.max_calls = max_calls + self.exchanges, self.exchanges_max_mb = exchanges, exchanges_max_mb self.ledger = ledger self.serving = dict(serving or {}) # by model, the serving providers that may answer it self.timeout = timeout @@ -1077,7 +1084,8 @@ def start(self) -> "Unit": key_file=self._key_file(), base=self.base, model=self.model, routes=self.routes, prices=self.prices, side_models=self.side_models, key_header=self.key_header, hosts=self.hosts, ledger=self.ledger, serving=self.serving, - timeout=self.timeout, max_calls=self.max_calls) + timeout=self.timeout, max_calls=self.max_calls, + exchanges=self.exchanges, exchanges_max_mb=self.exchanges_max_mb) self.started.append(self.names["relay"]) _docker(argv[1:]) _docker(["network", "connect", "--alias", RELAY_ALIAS, self.names["network"], self.names["relay"]]) diff --git a/app/nullius/standard/calls/exchanges.py b/app/nullius/standard/calls/exchanges.py new file mode 100644 index 00000000..049c61fb --- /dev/null +++ b/app/nullius/standard/calls/exchanges.py @@ -0,0 +1,449 @@ +"""Each model exchange of a unit, kept whole: the request the relay sent and the reply that came back. + +A unit's relay (``relay.Relay``) writes, beside its call record, under ``/exchanges/``: + +- ``.jsonl``: one line per call it sent on an agent's route (``relay.agent_route``), its side calls + included: ``n``, the call's number on its route (the call record's ``n`` too), ``t0``, ``path``, + ``sent_sha256`` (the sha256 of the bytes sent), ``sent`` (the request after the relay's changes, its + parts by hash), ``headers`` (the values of the headers sent, credentials left out) and ``reply`` (its + status, whether it was streamed, its body as it arrived, as text); +- ``parts.jsonl``: each distinct part once, ``{"sha256": ..., "part": ...}``. A part is one item of + ``messages`` or ``input``, one tool, or the system text (``system``, ``instructions``); its hash is the + sha256 of its JSON. Inside a part, an inline base64 picture is ``{"blob": sha256, "type": ..., "bytes": + ..., "as": "data_url"|"base64"}`` and its bytes are in +- ``blobs/.``: each distinct picture once, as its bytes (png, jpeg, webp, gif). + +Each ``.jsonl`` file begins with the mark of its format, ``{"schema": "nullius.exchanges/v1"}`` (``HEADER``): a +line no reader takes for a call or a part. A file without it is in version 1, the format before the mark. A +picture is the bytes its name hashes and carries no mark: the lines that name it do. A reader refuses a file +marked with a later version or another format (:class:`Later`), naming both; it never guesses. + +What is stored is what was sent, the relay's key cut out of every string: a request that held the key +then no longer rebuilds to its hash, and its line says ``key_cut``. Nothing else is redacted, so a secret +an agent typed in a prompt or showed in a screenshot is in the store as it was sent. The modes +(``MODES``): ``whole``; ``text``, the same without the pictures' bytes (their hash, type and size stay); +``off``, no store. A unit's store is bounded (``max_mb``): once a call's new content would take it past +the bound, that call's line and every later one say ``cut``, and the call record goes on. Nothing here +stops or changes a reply: a failure is written in the call's line (``error``) when it can be, and dropped +when it cannot. + +:func:`rebuild` gives a recorded request's bytes back from its line; :func:`new_parts`, the parts a call +holds that the call before did not. +""" +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import os +import re +import threading +from typing import Dict, List, Optional + +from nullius import settings + +MODES = ("whole", "text", "off") +DEFAULT = "whole" +MAX_MB = 256 # a unit's store, in millions of bytes +FOLDER = "exchanges" +PARTS = "parts.jsonl" +BLOBS = "blobs" +# the fields of a request kept by part: a list's items each a part, a text one part +PART_FIELDS = ("system", "instructions", "tools", "messages", "input") +EXT = {"image/png": "png", "image/jpeg": "jpg", "image/jpg": "jpg", "image/webp": "webp", "image/gif": "gif"} +_DATA_URL = re.compile(r"data:(image/(?:png|jpeg|jpg|webp|gif));base64,") +_TEXT_DATA_URL = re.compile(r"data:(image/[^;,\s]+);base64,", re.IGNORECASE) +MARK = frozenset(("blob", "type", "bytes", "as")) # a picture's place in a stored part +LITERAL = "literal" +VERSION = 1 # the store's format, as this code writes and reads it +HEADER = json.dumps({"schema": f"nullius.exchanges/v{VERSION}"}) + "\n" # the first line of each .jsonl file +_SCHEMA = re.compile(r"nullius\.exchanges/v([1-9][0-9]*)") + + +class Missing(Exception): + """A request that cannot be rebuilt from the store: the message says what is missing.""" + + +class Later(Missing): + """A file of the store in a later version of its format than this code reads, or in another format.""" + + +def _picture(text: str, media: Optional[str] = None, text_only: bool = False) -> Optional[tuple]: + """(type, bytes, form) of an inline picture: a data URL, or a Messages source's base64 ``data`` of + type ``media``. Whole mode requires the bytes to encode back to the original text.""" + if media is None: + m = (_TEXT_DATA_URL if text_only else _DATA_URL).match(text) + if not m: + return None + kind, b64, form = m.group(1), text[m.end():], "data_url" + elif media in EXT or (text_only and media.lower().startswith("image/")): + kind, b64, form = media, text, "base64" + else: + return None + if text_only: + b64 = "".join(b64.split()) + b64 += "=" * (-len(b64) % 4) + try: + raw = base64.b64decode(b64, altchars=b"-_" if text_only else None, validate=True) + except (binascii.Error, ValueError): + return None + # the alphabet alone, padding at the end only (validate): every whole group encodes back to itself, so the + # text is the bytes' own encoding when its length is and its last group is + if not text_only and (len(b64) != 4 * ((len(raw) + 2) // 3) or + (raw and base64.b64encode(raw[-(len(raw) % 3 or 3):]).decode() != b64[-4:])): + return None + return kind, raw, form + + +def _mark(found: dict, kind: str, raw: bytes, form: str) -> dict: + h = hashlib.sha256(raw).hexdigest() + found[h] = (kind, raw) + return {"blob": h, "type": kind, "bytes": len(raw), "as": form} + + +def _lift(v, found: dict, text_only: bool = False): + """``v`` with each inline picture replaced by its mark, the picture in ``found`` by its hash.""" + if isinstance(v, str): + p = _picture(v, text_only=text_only) if v.lower().startswith("data:image/") else None + return _mark(found, *p) if p else v + if isinstance(v, list): + return [_lift(x, found, text_only) for x in v] + if isinstance(v, dict): + media = v.get("media_type") if v.get("type") == "base64" and isinstance(v.get("media_type"), str) else None + out = {} + for k, x in v.items(): + p = _picture(x, media, text_only) if media and k == "data" and isinstance(x, str) else None + out[k] = _mark(found, *p) if p else _lift(x, found, text_only) + return {LITERAL: out} if set(v) in (MARK, {LITERAL}) else out + return v + + +def secret_keys(keys): + """The keys to cut, longest first. A keyless provider's placeholder is not a secret.""" + return tuple(sorted({k for k in keys if k and k != settings.MODEL_KEY_PLACEHOLDER}, key=len, reverse=True)) + + +def _cut_key(v, keys): + """``v`` with each of ``keys`` cut out of every string, a mapping's keys too.""" + if isinstance(v, str): + for k in secret_keys(keys): + v = v.replace(k, "[REDACTED]") + return v + if isinstance(v, list): + return [_cut_key(x, keys) for x in v] + if isinstance(v, dict): + return {_cut_key(k, keys): _cut_key(x, keys) for k, x in v.items()} + return v + + +def _text_body(text: str) -> str: + """Remove inline pictures from a JSON body, an event stream or a data URL.""" + try: + value = json.loads(text) + except ValueError: + value = text + found = {} + lifted = _lift(value, found, True) + if found: + return json.dumps(lifted) + if isinstance(value, str): + return "".join("data:" + _text_body(row[5:].rstrip("\r\n")) + row[len(row.rstrip("\r\n")):] + if row.startswith("data:") else row for row in text.splitlines(keepends=True)) + return text + + +def split(req: dict, found: dict, parts: dict, text_only: bool = False) -> dict: + """A request's ``sent``: each part by its hash, the rest as it was. ``parts`` gains each part's + stored line by hash, ``found`` each picture's (type, bytes).""" + sent = {} + for k, v in req.items(): + if k not in PART_FIELDS: + sent[k] = _lift(v, found, text_only) + elif isinstance(v, list): + sent[k] = {"parts": [_part(x, found, parts, text_only) for x in v]} + elif isinstance(v, str): + sent[k] = {"part": _part(v, found, parts, text_only)} + else: + sent[k] = {"as_sent": _lift(v, found, text_only)} + return sent + + +def _part(x, found: dict, parts: dict, text_only: bool = False) -> str: + mine = {} + text = json.dumps(_lift(x, mine, text_only), separators=(",", ":")) + h = hashlib.sha256(text.encode()).hexdigest() + parts[h] = '{"sha256":"%s","part":%s}' % (h, text) + found.update(mine) + return h + + +class Store: + """One unit's store, written by its relay: the parts and pictures already written are known by + their hashes, so a call that resends its context adds only what is new.""" + + def __init__(self, record_dir: str, mode: str = DEFAULT, max_mb: int = MAX_MB, keys=()): + if mode not in MODES or mode == "off": + raise ValueError(f"exchanges {mode!r}: whole or text") + if isinstance(max_mb, bool) or not isinstance(max_mb, int) or max_mb < 1: + raise ValueError(f"exchanges_max_mb {max_mb!r}: a whole number of MB, at least 1") + self.dir, self.mode, self.max_mb, self.bound = os.path.join(record_dir, FOLDER), mode, max_mb, max_mb * 10 ** 6 + self.keys = secret_keys(keys) + self.parts: set = set() + self.blobs: set = set() + self.size = 0 + self.cut = False # the bound was met: every later call is cut + self.lock = threading.Lock() + + def write(self, tag: str, n: int, t0: float, path: str, req: Optional[dict], raw: bytes, headers: Dict[str, str], + status: int, streamed: bool, body: bytes) -> None: + """One call's line, its new parts and pictures. ``req``: the request whose ``json.dumps`` is + ``raw``, the bytes sent; None when the relay sent the body as it came (it is then kept whole as + ``sent_body``). ``headers``: those sent, the credentials already left out. Never raises.""" + head = {"n": n, "t0": t0, "path": path, "sent_sha256": None} + try: + head["path"] = _cut_key(path, self.keys) + head["sent_sha256"] = hashlib.sha256(raw).hexdigest() + held = any(k.encode() in raw for k in self.keys) + line = dict(head) + found, parts = {}, {} + if req is None: + line["sent_body"] = _cut_key(raw.decode("utf-8", "replace"), self.keys) + line["error"] = "the request's body is not a JSON object: it is kept whole, not by part" + else: + line["sent"] = split(_cut_key(req, self.keys) if held else req, found, parts, self.mode == "text") + if held: + line["key_cut"] = True + line["headers"] = _cut_key(headers, self.keys) + line["reply"] = {"status": status, "streamed": streamed, "body": _cut_key(body.decode("utf-8", "replace"), self.keys)} + if self.mode == "text": + line["headers"] = {k: _text_body(v) for k, v in line["headers"].items()} + line["reply"]["body"] = _text_body(line["reply"]["body"]) + if "sent_body" in line: + line["sent_body"] = _text_body(line["sent_body"]) + text = json.dumps(line) + self._keep(tag, head, text, parts, found) + except Exception as e: # nothing of the store may reach the caller's reply + self._failed(tag, head, e) + + def _keep(self, tag: str, head: dict, text: str, parts: dict, found: dict) -> None: + with self.lock: + new_parts = "".join(p + "\n" for h, p in parts.items() if h not in self.parts) + new_blobs = [(h, kind, raw) for h, (kind, raw) in found.items() if h not in self.blobs] if self.mode == "whole" else [] + paths = [os.path.join(self.dir, name) for name in [tag + ".jsonl"] + ([PARTS] if new_parts else [])] + marks = sum(len(HEADER) for path in paths if not os.path.exists(path) or not os.path.getsize(path)) + if self.cut or self.size + marks + len(new_parts) + sum(len(raw) for _, _, raw in new_blobs) + len(text) + 1 > self.bound: + self.cut = True + self._append(tag + ".jsonl", json.dumps(dict(head, cut=f"the store reached its bound of {self.max_mb} MB: " + "this call and every later one are not kept")) + "\n") + return + for h, kind, raw in new_blobs: # what a line names is written before it + self._put(os.path.join(BLOBS, f"{h}.{EXT[kind]}"), raw) + self.blobs.add(h) + if new_parts: + self._append(PARTS, new_parts) + self.parts.update(parts) + self._append(tag + ".jsonl", text + "\n") + + def _failed(self, tag: str, head: dict, e: Exception) -> None: + try: + said = _cut_key(f"{type(e).__name__}: {e}", self.keys)[:500] + with self.lock: + self._append(tag + ".jsonl", json.dumps(dict(head, error=said)) + "\n") + except Exception: + pass # a full disk: the call record still says the call + + def _append(self, name: str, text: str) -> None: + os.makedirs(self.dir, exist_ok=True) + path = os.path.join(self.dir, name) + before = os.path.getsize(path) if os.path.exists(path) else 0 + if not before: + text = HEADER + text # a new file begins with the mark of its format + try: + with open(path, "a") as f: + if f.write(text) != len(text): + raise OSError("the store append was incomplete") + except Exception: + if os.path.exists(path): + os.truncate(path, before) + raise + self.size += len(text) # ASCII: json.dumps escapes the rest + + def _put(self, name: str, data: bytes) -> None: + path = os.path.join(self.dir, name) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path + ".part", "wb") as f: + if f.write(data) != len(data): + raise OSError("the stored picture was incomplete") + os.replace(path + ".part", path) + self.size += len(data) + + +# -- reading a store --------------------------------------------------------------- +def _inside(folder: str, name: str) -> str: + path = os.path.realpath(os.path.join(folder, name)) + if os.path.commonpath((folder, path)) != folder: + raise Missing("the stored path resolves outside its folder") + return path + + +def _digest(value) -> str: + if not isinstance(value, str) or re.fullmatch(r"[0-9a-fA-F]{64}", value) is None: + raise Missing("the stored digest must be 64 hexadecimal digits") + return value + + +def _picture_path(folder: str, mark: dict) -> str: + name = f"{_digest(mark['blob'])}.{EXT.get(mark['type'], 'bin')}" + return _inside(os.path.join(os.path.realpath(folder), BLOBS), name) + + +def lines(folder: str, tag: str) -> List[dict]: + """The lines of route ``tag`` in the store at ``folder`` (``/exchanges``); a line that + cannot be read is left out.""" + return _jsonl(_inside(os.path.realpath(folder), tag + ".jsonl")) + + +def tags(folder: str) -> List[str]: + """The routes a store holds lines of.""" + try: + return sorted(n[:-6] for n in os.listdir(folder) if n.endswith(".jsonl") and n != PARTS) + except OSError: + return [] + + +def _jsonl(path: str) -> List[dict]: + out = [] + try: + with open(path) as f: + for row in f: + try: + got = json.loads(row) + except ValueError: + continue + if isinstance(got, dict): + out.append(got) + except OSError: + pass + return unmarked(out, os.path.basename(path)) + + +def unmarked(rows: List[dict], name: str) -> List[dict]: + """The rows of the store's file ``name`` without the mark of its format; a file without one is in + version 1. Raises :class:`Later` for a mark of a later version or of another format.""" + out = [] + for row in rows: + if set(row) != {"schema"}: + out.append(row) + continue + said = row["schema"] + m = _SCHEMA.fullmatch(said) if isinstance(said, str) else None + if m is None: + raise Later(f"{name} is marked {said!r:.80}, not a version of the exchange store's format; " + f"this Nullius reads its version {VERSION}") + if int(m.group(1)) > VERSION: + raise Later(f"{name} is in version {int(m.group(1))} of the exchange store's format; " + f"this Nullius reads version {VERSION}: read it with a later Nullius") + return out + + +def stored_parts(folder: str) -> Dict[str, dict]: + """Each readable part by its hash: {"part": ..., "as_sent": bool}. Damaged rows are left out.""" + parts = {} + for p in _jsonl(_inside(os.path.realpath(folder), PARTS)): + if "part" not in p: + continue + try: + h = _digest(p.get("sha256")) + if not p.get("as_sent"): + _drop(p["part"], lambda mark: _picture_path(folder, mark)) + except Missing: + continue + parts[h] = {"part": p.get("part"), "as_sent": bool(p.get("as_sent"))} + return parts + + +def _drop(v, picture): + """A stored part with each picture's mark replaced by ``picture(mark)``.""" + if isinstance(v, dict): + if set(v) == {LITERAL}: + return {k: _drop(x, picture) for k, x in v[LITERAL].items()} + if set(v) == MARK: + return picture(v) + return {k: _drop(x, picture) for k, x in v.items()} + if isinstance(v, list): + return [_drop(x, picture) for x in v] + return v + + +def rebuild(folder: str, line: dict, parts: Optional[Dict[str, dict]] = None) -> bytes: + """The bytes a recorded call sent, put back together from its line, its parts and its pictures: + what ``sent_sha256`` is the hash of when nothing was cut from them. Raises :class:`Missing` when + the store does not hold the request.""" + parts = stored_parts(folder) if parts is None else parts + if line.get("cut"): + raise Missing(f"call {line.get('n')} was not kept: {line['cut']}") + if "sent_body" in line: + return line["sent_body"].encode() + if not isinstance(line.get("sent"), dict): + raise Missing(f"call {line.get('n')} has no request in the store" + (f": {line['error']}" if line.get("error") else "")) + def part(h): + _digest(h) + if h not in parts: + raise Missing(f"the part {h} is not in the store") + got = parts[h] + return got["part"] if got["as_sent"] else _drop(got["part"], picture) + + def picture(mark): + name = _picture_path(folder, mark) + try: + with open(name, "rb") as f: + b64 = base64.b64encode(f.read()).decode("ascii") + except OSError: + raise Missing(f"the picture {mark['blob']} is not in the store (a store kept as text holds no pictures)") + return f"data:{mark['type']};base64,{b64}" if mark["as"] == "data_url" else b64 + + req = {} + for k, v in line["sent"].items(): + if k in PART_FIELDS and isinstance(v, dict) and set(v) == {"parts"}: + req[k] = [part(h) for h in v["parts"]] + elif k in PART_FIELDS and isinstance(v, dict) and set(v) == {"part"}: + req[k] = part(v["part"]) + elif k in PART_FIELDS and isinstance(v, dict) and set(v) == {"as_sent"}: + req[k] = _drop(v["as_sent"], picture) + else: + req[k] = _drop(v, picture) + return json.dumps(req).encode() + + +def check(folder: str, tag: str, n: int) -> dict: + """Call ``n`` of route ``tag`` rebuilt: {"request": bytes or None, "sha256", "sent_sha256", "same", + "why"}; ``why`` says what kept it from rebuilding or from matching. A file in a later format raises + :class:`Later`.""" + line = next((x for x in lines(folder, tag) if x.get("n") == n), None) + if line is None: + raise Missing(f"no call {n} in the store of {tag}") + try: + got = rebuild(folder, line) + except Later: + raise + except Missing as e: + return {"request": None, "sha256": None, "sent_sha256": line.get("sent_sha256"), "same": False, "why": str(e)} + sha = hashlib.sha256(got).hexdigest() + same = sha == line.get("sent_sha256") + why = None if same else ("the relay's key was cut out of the request" if line.get("key_cut") + else "the store's parts do not rebuild the bytes sent") + return {"request": got, "sha256": sha, "sent_sha256": line.get("sent_sha256"), "same": same, "why": why} + + +def new_parts(line: dict, before: Optional[dict] = None) -> List[str]: + """The parts call ``line`` holds that ``before``, the call before it, did not: their hashes, in the + request's order.""" + def held(x): + out = [] + for k, v in ((x or {}).get("sent") or {}).items(): + if k in PART_FIELDS and isinstance(v, dict): + out += list(v.get("parts") or []) + ([v["part"]] if isinstance(v.get("part"), str) else []) + return out + seen = set(held(before)) + return [h for h in held(line) if h not in seen] diff --git a/app/nullius/standard/calls/relay.py b/app/nullius/standard/calls/relay.py index d7b3161c..1f1b7f3b 100644 --- a/app/nullius/standard/calls/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -39,6 +39,12 @@ that model, in place of the caller's own, and records both, cleaned of credentials. Without a pin a request's body goes on as it did. +A run may also keep each call of an agent's route whole (``exchanges``): +the request as sent, by part, and the reply as it arrived, beside the call +record, which then numbers those calls (``n``). It is written before the +caller has the end of its reply, and a failure to write it never changes +nor stops that reply. + One answer is the relay's own: a run with a spending cap (``ledger``) books each call before it goes out, and a call that does not fit is not sent. Its caller gets a 402 that names the relay and the cap, and the record says @@ -62,7 +68,7 @@ from typing import Dict, List, Optional from nullius.redact import redact -from nullius.standard.calls import ledger as ledgers +from nullius.standard.calls import exchanges as exchange_store, ledger as ledgers PLACEHOLDER_KEY = "nullius-relay" _TAG = re.compile(r"^[A-Za-z0-9_-]{1,64}$") @@ -94,7 +100,7 @@ def _cut(text, n=4000): - if not isinstance(text, str) or len(text) <= n: + if not isinstance(text, str) or n is None or len(text) <= n: return text return text[: n // 4] + f"\n[... {len(text) - n} characters left out ...]\n" + text[-(3 * n // 4):] @@ -174,7 +180,7 @@ def _usage(u: Optional[dict]) -> Optional[dict]: return got -def _text_of_responses(resp: dict) -> (str, List[dict]): +def _text_of_responses(resp: dict, limit: Optional[int] = 2000) -> (str, List[dict]): text, calls = [], [] for item in resp.get("output") or []: if item.get("type") == "message": @@ -183,20 +189,36 @@ def _text_of_responses(resp: dict) -> (str, List[dict]): text.append(c.get("text") or "") elif item.get("type") in ("function_call", "custom_tool_call", "local_shell_call"): calls.append({"name": item.get("name") or item.get("type"), - "arguments": _cut(item.get("arguments") or item.get("input") or json.dumps(item.get("action")), 2000)}) + "arguments": _cut(item.get("arguments") or item.get("input") or json.dumps(item.get("action")), limit)}) return "".join(text), calls -def _text_of_messages(msg: dict) -> (str, List[dict]): +def _reasoning_of_responses(resp: dict) -> str: + """A Responses object's reasoning items: their text, else their summary.""" + out = [] + for item in resp.get("output") or []: + if isinstance(item, dict) and item.get("type") == "reasoning": + said = [c.get("text") or "" for c in item.get("content") or [] if isinstance(c, dict) and c.get("type") == "reasoning_text"] + out += said or [c.get("text") or "" for c in item.get("summary") or [] if isinstance(c, dict)] + return "".join(out) + + +def _text_of_messages(msg: dict, limit: Optional[int] = 2000) -> (str, List[dict]): text, calls = [], [] for c in msg.get("content") or []: if c.get("type") == "text": text.append(c.get("text") or "") elif c.get("type") in ("tool_use", "server_tool_use"): - calls.append({"name": c.get("name"), "arguments": _cut(json.dumps(c.get("input")), 2000)}) + calls.append({"name": c.get("name"), "arguments": _cut(json.dumps(c.get("input")), limit)}) return "".join(text), calls +def _chat_reasoning(m: dict) -> str: + """A chat message's or delta's reasoning: OpenRouter's ``reasoning``, or ``reasoning_content``.""" + said = m.get("reasoning") if isinstance(m.get("reasoning"), str) else m.get("reasoning_content") + return said if isinstance(said, str) else "" + + def _hollow(path: str, body: bytes) -> Optional[tuple]: """A 200 to a model call that holds no reply: the status it stands for, 429 or 402 when an error it held says so, else 502, and its kind alone, since its words can quote the request.""" @@ -216,8 +238,19 @@ def _hollow(path: str, body: bytes) -> Optional[tuple]: else (502, "no reply") -def read_reply(path: str, body: bytes, streamed: bool) -> dict: - """What a reply said: its text, its tool calls, its usage.""" +def read_reply(path: str, body: bytes, streamed: bool, reasoning: bool = False, whole: bool = False) -> dict: + """What a reply said: its text, its tool calls, its usage; with + ``reasoning``, also the reasoning text it gave (chat's ``reasoning`` or + ``reasoning_content``, Messages' thinking blocks, a Responses reasoning + item's text or summary). A tool call's arguments are cut to 2,000 + characters, as the call record keeps them, unless ``whole``.""" + got = _read_reply(path, body, streamed, reasoning, None if whole else 2000) + if not reasoning: + got.pop("reasoning", None) + return got + + +def _read_reply(path: str, body: bytes, streamed: bool, reasoning: bool, limit: Optional[int]) -> dict: if not streamed: try: got = json.loads(body) @@ -225,19 +258,20 @@ def read_reply(path: str, body: bytes, streamed: bool) -> dict: return {} if "choices" in got: m = ((got.get("choices") or [{}])[0].get("message")) or {} - calls = [{"name": (c.get("function") or {}).get("name"), "arguments": _cut((c.get("function") or {}).get("arguments"), 2000)} + calls = [{"name": (c.get("function") or {}).get("name"), "arguments": _cut((c.get("function") or {}).get("arguments"), limit)} for c in m.get("tool_calls") or []] - return {"text": m.get("content"), "tool_calls": calls, "usage": _usage(got.get("usage"))} + return {"text": m.get("content"), "tool_calls": calls, "usage": _usage(got.get("usage")), "reasoning": _chat_reasoning(m)} if got.get("type") == "message" and isinstance(got.get("content"), list): - text, calls = _text_of_messages(got) - return {"text": text, "tool_calls": calls, "usage": _usage(got.get("usage"))} + text, calls = _text_of_messages(got, limit) + return {"text": text, "tool_calls": calls, "usage": _usage(got.get("usage")), + "reasoning": "".join(c.get("thinking") or "" for c in got["content"] if isinstance(c, dict) and c.get("type") == "thinking")} if got.get("object") == "response" or "output" in got: - text, calls = _text_of_responses(got) - return {"text": text, "tool_calls": calls, "usage": _usage(got.get("usage"))} + text, calls = _text_of_responses(got, limit) + return {"text": text, "tool_calls": calls, "usage": _usage(got.get("usage")), "reasoning": _reasoning_of_responses(got)} if got.get("object") == "list" and path.split("?")[0].endswith("/embeddings"): # how many inputs, and the usage: never the vectors return {"embeddings": len(got.get("data") or []), "usage": _usage(got.get("usage"))} return {} - text, calls, usage, args = [], {}, None, {} + text, calls, usage, args, thought = [], {}, None, {}, [] told = None # Messages: the usage of message_start, then message_delta's on it for line in body.decode("utf-8", "replace").splitlines(): if not line.startswith("data:"): @@ -262,6 +296,8 @@ def read_reply(path: str, body: bytes, streamed: bool) -> dict: calls[i], args[i] = b.get("name"), "" elif b.get("text"): text.append(b["text"]) + elif b.get("type") == "thinking" and isinstance(b.get("thinking"), str): + thought.append(b["thinking"]) continue if kind == "content_block_delta": d, i = ev.get("delta") or {}, ev.get("index", 0) @@ -269,14 +305,19 @@ def read_reply(path: str, body: bytes, streamed: bool) -> dict: text.append(d.get("text") or "") elif d.get("type") == "input_json_delta": args[i] = args.get(i, "") + (d.get("partial_json") or "") + elif d.get("type") == "thinking_delta": + thought.append(d.get("thinking") or "") continue if kind in ("response.completed", "response.done", "response.incomplete", "response.failed"): - t, c = _text_of_responses(ev.get("response") or {}) - return {"text": t, "tool_calls": c, "usage": _usage((ev.get("response") or {}).get("usage"))} + t, c = _text_of_responses(ev.get("response") or {}, limit) + return {"text": t, "tool_calls": c, "usage": _usage((ev.get("response") or {}).get("usage")), + "reasoning": _reasoning_of_responses(ev.get("response") or {})} for ch in ev.get("choices") or []: d = ch.get("delta") or {} if d.get("content"): text.append(d["content"]) + if reasoning: + thought.append(_chat_reasoning(d)) for tc in d.get("tool_calls") or []: i = tc.get("index", 0) f = tc.get("function") or {} @@ -285,8 +326,8 @@ def read_reply(path: str, body: bytes, streamed: bool) -> dict: args[i] = args.get(i, "") + (f.get("arguments") or "") if ev.get("usage"): usage = _usage(ev["usage"]) - return {"text": "".join(text), "tool_calls": [{"name": calls[i], "arguments": _cut(args.get(i, ""), 2000)} for i in sorted(calls)], - "usage": _usage(told) if told is not None else usage} + return {"text": "".join(text), "tool_calls": [{"name": calls[i], "arguments": _cut(args.get(i, ""), limit)} for i in sorted(calls)], + "usage": _usage(told) if told is not None else usage, "reasoning": "".join(thought)} # -- serving providers: the pin a run sets, and what a reply says of who served it -- @@ -348,9 +389,8 @@ def _clean(value, secrets=()): if isinstance(value, list): return [_clean(v, secrets) for v in value] if isinstance(value, str): - for s in secrets: - if s: - value = value.replace(s, "[REDACTED]") + for s in exchange_store.secret_keys(secrets): + value = value.replace(s, "[REDACTED]") return redact(value) return value @@ -661,7 +701,8 @@ class Relay: def __init__(self, base: str, key: str, record_dir: str, prices: Optional[Dict[str, dict]] = None, model: Optional[str] = None, side_models=(), key_header: str = "authorization", fields: bool = False, ledger: Optional[str] = None, unit_caps: bool = True, serving: Optional[Dict[str, List[str]]] = None, - facts: Optional[bool] = None, timeout: float = TIMEOUT, max_calls: Optional[int] = None): + facts: Optional[bool] = None, timeout: float = TIMEOUT, max_calls: Optional[int] = None, + exchanges: str = "off", exchanges_max_mb: int = exchange_store.MAX_MB): """``base``: the provider's endpoint (``https://api.openai.com/v1``). ``model``: when given, every call is sent as this model, whatever the caller named - the run's model is the recipe's, not the agent's. A @@ -684,9 +725,18 @@ def __init__(self, base: str, key: str, record_dir: str, prices: Optional[Dict[s routing facts, where its reply names who served it; by default when ``base`` is OpenRouter's. ``timeout``: the seconds one call may wait. ``max_calls``: the most model calls the agent's own route of a unit - may make (:func:`agent_route`), each answered call counted.""" + may make (:func:`agent_route`), each answered call counted. + ``exchanges``: ``whole`` or ``text`` keeps each call of an agent's + route whole in ``/exchanges`` (``exchanges``), bounded at + ``exchanges_max_mb``, and numbers its calls in the record (``n``); + ``off``, the default, keeps the call record alone.""" self.fields = fields self.max_calls = max_calls + if exchanges not in exchange_store.MODES: + raise ValueError(f"exchanges {exchanges!r}: one of {', '.join(exchange_store.MODES)}") + self.exchanges = (exchange_store.Store(record_dir, exchanges, exchanges_max_mb, (key, (key or "").strip())) + if exchanges != "off" else None) + self.numbered: Dict[str, int] = {} # the calls each agent route was sent, for the record's n self.answered: Dict[str, int] = {} # the calls each agent route had answered, for max_calls self.serving = {m: list(s) for m, s in (serving or {}).items()} host = (urllib.parse.urlsplit(base).hostname or "").lower() @@ -749,7 +799,7 @@ def _said(self, e: Exception) -> str: quotes a header value it refuses (a key with a stray CR, a BOM), so the key itself is cut out of the text whatever else it says.""" text = f"{type(e).__name__}: {e}" - for k in {self.key, self.key.strip()} - {""}: + for k in exchange_store.secret_keys((self.key, self.key.strip())): text = text.replace(k, "[REDACTED]") return redact(text)[:200] @@ -793,9 +843,14 @@ def _forward(self, h: BaseHTTPRequestHandler): req = json.loads(raw) if raw else {} except ValueError: req = {} + number = None # a call of an agent's route kept whole: its number there, in its record and its line + if self.exchanges is not None and agent_route(tag) and h.command == "POST": + with self.lock: + number = self.numbered[tag] = self.numbered.get(tag, 0) + 1 asked = req.get("model") if isinstance(req, dict) else None side = False routing_asked, pinned = None, None + dumped = False # raw is json.dumps(req): what the store splits into parts if isinstance(req, dict) and req: if rest.split("?")[0] == "/embeddings" and self.embedding_models.get(tag): req["model"] = self.embedding_models[tag] @@ -812,7 +867,7 @@ def _forward(self, h: BaseHTTPRequestHandler): if pinned: routing_asked = req.get("provider") req["provider"] = routing(pinned) - raw = json.dumps(req).encode() + raw, dumped = json.dumps(req).encode(), True if not side and not self.models.get(tag) and self._asked(): h.send_error(400, "the unit was asked to stop") return @@ -821,7 +876,7 @@ def _forward(self, h: BaseHTTPRequestHandler): made = self.answered.get(tag, 0) if made >= self.max_calls: self._refuse(h, tag, rest, req, asked, f"the unit's cap of {self.max_calls} model calls was reached: " - "no further call of its agent is sent", "calls") + "no further call of its agent is sent", "calls", number=number) return booking = booked = None # a call that names its model is booked, whatever its route, but a token count, which costs nothing and @@ -838,16 +893,18 @@ def _forward(self, h: BaseHTTPRequestHandler): if by == "gone": # its caller hung up while it waited: nothing was booked, nothing is sent return if why: - self._refuse(h, tag, rest, req, asked, why, by) + self._refuse(h, tag, rest, req, asked, why, by, number=number) return t0 = time.time() conn, r, back, body = None, None, [], b"" cut = False # the reply was cut off: the call may have been billed + sent_headers: Dict[str, str] = {} cut_off = None try: # a Responses reply names its provider in the routing facts alone; a Messages reply names it of itself facts = bool(pinned) and self.facts and rest.split("?")[0].endswith(("/chat/completions", "/responses")) - conn, r = self.pool.send(h.command, rest, raw if h.command == "POST" else None, self._headers(h.headers, tag, facts)) + sent_headers = self._headers(h.headers, tag, facts) + conn, r = self.pool.send(h.command, rest, raw if h.command == "POST" else None, sent_headers) status, kind, back = r.status, r.getheader("Content-Type") or "application/json", returned(r.headers) except Exception as e: status, kind = 502, "application/json" @@ -924,12 +981,17 @@ def record(body): self.ledger.release(booking) except ledgers.Unavailable: pass # the booking stays held, against the cap + if number is not None: + rec = {"n": number, **rec} with self.lock: with open(os.path.join(self.dir, tag + ".jsonl"), "a") as f: - f.write(json.dumps(rec) + "\n") + f.write(json.dumps(exchange_store._cut_key(rec, self.exchanges.keys) if self.exchanges else rec) + "\n") if not side and not self.models.get(tag) and overflowed(rec): with open(os.path.join(self.dir, STOP), "a") as f: f.write(OVERFLOW + "\n") + if number is not None: # the exchange whole, after its record: it never raises + self.exchanges.write(tag, number, t0, rest, req if dumped else None, raw, + {k: v for k, v in sent_headers.items() if not _CREDENTIAL.search(k)}, status, streamed, body) h.send_response(status) if not any(n.lower() == "content-type" for n, _ in back): @@ -1006,18 +1068,22 @@ def _book(self, req: dict, raw: bytes, rest: str, tag: str = "", h: Optional[Bas amount = seen["amount"] return (booking, amount, None, None) if booking else (None, amount, ledgers.refusal(seen, amount), seen["by"]) - def _refuse(self, h: BaseHTTPRequestHandler, tag: str, rest: str, req, asked, why: str, by: str = "cap") -> None: + def _refuse(self, h: BaseHTTPRequestHandler, tag: str, rest: str, req, asked, why: str, by: str = "cap", + number: Optional[int] = None) -> None: """A call a capped run did not let out - at the run's cap (``by`` is ``cap``), at its unit's own (``unit``), or for want of a price (``price``): answered here and recorded as the relay's own - (``refused``), nothing sent.""" + (``refused``), nothing sent. ``number``: its ``n`` on a route whose + calls are kept whole; nothing sent, it has no line there.""" t = time.time() rec = {"t0": t, "t1": t, "path": rest, "model": req.get("model") if isinstance(req, dict) else None, "model_asked": asked, "status": 402, "refused": by, "error": why, "request": _request_tail(req) if isinstance(req, dict) else {}, "headers": sorted(k.lower() for k in forwarded(h.headers))} + if number is not None: + rec = {"n": number, **rec} with self.lock: with open(os.path.join(self.dir, tag + ".jsonl"), "a") as f: - f.write(json.dumps(rec) + "\n") + f.write(json.dumps(exchange_store._cut_key(rec, self.exchanges.keys) if self.exchanges else rec) + "\n") body = json.dumps({"type": "error", "error": {"type": "call_cap" if by == "calls" else "spending_cap", "code": {"unit": "unit_spending_cap", "price": "unpriced_model", "ledger": "ledger_unavailable", "calls": "unit_call_cap"}.get(by, "spending_cap"), @@ -1164,7 +1230,8 @@ def overflowed(call: dict) -> bool: def serve(argv=None) -> int: """``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...] ...]``. + [--public URL] [--prices JSON] [--ledger FILE] [--served-by MODEL=SLUG[,SLUG...] ...] + [--exchanges whole|text|off] [--exchanges-max-mb N]``. ``--base``: provider endpoint. ``--route``: send a tag as another model. ``--public``: address returned by ``url``. The real key is read from ``--key-file`` and nowhere else: an argument or @@ -1193,7 +1260,15 @@ def serve(argv=None) -> int: ap.add_argument("--routing", action="store_true", help="the endpoint at --base routes a model to several serving providers, as OpenRouter does") ap.add_argument("--timeout", type=float, default=TIMEOUT, help="seconds one call may wait for the provider's reply") + ap.add_argument("--exchanges", default="off", choices=exchange_store.MODES, + help="keep each call of an agent's route whole in the record's exchanges/ (whole), without " + "the pictures' bytes (text), or not (off, the default)") + ap.add_argument("--exchanges-max-mb", type=int, default=exchange_store.MAX_MB, metavar="N", + help=f"the most MB a unit's exchanges take: past it a call's line says cut (default {exchange_store.MAX_MB})") a = ap.parse_args(argv) + if a.exchanges_max_mb < 1: + print(json.dumps({"error": f"--exchanges-max-mb {a.exchanges_max_mb}: a whole number of MB, at least 1"}), flush=True) + return 2 serving, bad = parse_served_by(a.served_by, "") if serving and not bad: host = (urllib.parse.urlsplit(a.base).hostname or "").lower() @@ -1218,7 +1293,7 @@ def serve(argv=None) -> int: host, _, port = a.listen.rpartition(":") r = Relay(a.base, key, a.record, prices=json.loads(a.prices) if a.prices else None, model=a.model, side_models=a.side_model, key_header=a.key_header, ledger=a.ledger, serving=serving, - timeout=a.timeout, max_calls=a.max_calls) + timeout=a.timeout, max_calls=a.max_calls, exchanges=a.exchanges, exchanges_max_mb=a.exchanges_max_mb) for route in a.route: tag, _, model = route.partition("=") if not _TAG.match(tag) or not model: diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 5c5bf226..9449e5fe 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -7,7 +7,7 @@ PYTHONPATH=app python3 -m nullius.standard.cli new benchmark|agent|capability KEY [--family F] [--port P] PYTHONPATH=app python3 -m nullius.standard.cli new version KEY VERSION PYTHONPATH=app python3 -m nullius.standard.cli conform AGENT|CAPABILITY --model M [--provider P] [--port PORT ...] [--attempts K] [--option NAME=VALUE ...] [--unsandboxed | --backend container | --backend boat] - PYTHONPATH=app python3 -m nullius.standard.cli run BENCHMARK[@VERSION] AGENT|CAPABILITY --model M [--provider P] [--units FILE] [--limit N] [-j N] [--option NAME=VALUE ...] [--bench-option NAME=VALUE ...] [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H] ...] [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS ...] [--max-turns N] [--max-calls N] [--constraint KEY=VALUE ...] [--served-by [MODEL=]SLUG[,SLUG...] ...] [--unsandboxed | --backend container | --backend boat [--boat-size SIZE]] + PYTHONPATH=app python3 -m nullius.standard.cli run BENCHMARK[@VERSION] AGENT|CAPABILITY --model M [--provider P] [--units FILE] [--limit N] [-j N] [--option NAME=VALUE ...] [--bench-option NAME=VALUE ...] [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H] ...] [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS ...] [--max-turns N] [--max-calls N] [--constraint KEY=VALUE ...] [--served-by [MODEL=]SLUG[,SLUG...] ...] [--exchanges whole|text|off] [--exchanges-max-mb N] [--unsandboxed | --backend container | --backend boat [--boat-size SIZE]] PYTHONPATH=app python3 -m nullius.standard.cli run BENCHMARK[@VERSION] nop|oracle [--dataset D] [--units FILE] [--limit N] PYTHONPATH=app python3 -m nullius.standard.cli prove BENCHMARK[@VERSION] [--dataset D] [--limit N] [--bench-option NAME=VALUE ...] [--job nop|oracle=JOB_DIR ...] PYTHONPATH=app python3 -m nullius.standard.cli run ... --shard I/N [--launch ID] @@ -48,7 +48,10 @@ 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 a model on OpenRouter, in that order (``run.served_by``); each call's record -names the provider that served it. +names the provider that served it. ``--exchanges`` says what each unit's relay +keeps of its agent's calls (``standard/calls/exchanges.py``): ``whole`` by default, +``text`` without the pictures' bytes, or ``off``; ``--exchanges-max-mb`` bounds +a unit's. A run says each stage before its first unit, and each unit's end, as one ``[nullius] stage=...`` line on stderr and in the job's ``progress.jsonl`` (``nullius/progress.py``). @@ -82,6 +85,7 @@ settings.load(paths.settings_file()) from nullius.standard.backends import boat +from nullius.standard.calls import exchanges from nullius.standard.contract import definitions, match, ports, proofs from nullius.standard.proofs import conform, fidelity, pins, prove from nullius.standard.runner import job, merge, run, shard @@ -589,6 +593,7 @@ def cmd_run(a): prices=prices(a.price), max_usd=a.max_usd, max_usd_per_unit=a.max_usd_per_unit, prices_unreachable=unreachable, constraints=given, timeouts=timeouts(a.timeout), max_turns=a.max_turns, max_calls=a.max_calls, + exchanges=a.exchanges, exchanges_max_mb=a.exchanges_max_mb, **({"units_file": run.units_file(a.units)} if a.units is not None else {}), **({"served_by": run.served_by(a.served_by, a.model or "")} if a.served_by else {}), **({"env": run_env(a.provider)} if a.from_run else {})) @@ -878,6 +883,12 @@ def main(argv=None): p.add_argument("--max-calls", type=int, metavar="N", help="the most model calls a unit's agent may make, the whole unit through: past it the relay refuses " "the next call and the unit is the agent's error, as a timeout is") + p.add_argument("--exchanges", default=exchanges.DEFAULT, choices=exchanges.MODES, + help="what each unit's relay keeps of its agent's calls: the request as sent and the reply as it " + "arrived (whole, the default), the same without the pictures' bytes (text), or the call record alone (off)") + p.add_argument("--exchanges-max-mb", type=int, default=exchanges.MAX_MB, metavar="N", + help="a unit's bound on what it keeps of its calls, in MB: past it a call's line says cut and the call " + f"record goes on (default {exchanges.MAX_MB})") v = sub.add_parser("prove", help="prove a benchmark: its controls, its units, no leak; record what passed") v.add_argument("benchmark") v.add_argument("--dataset", help="one dataset (default: each)") diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 4d1cca13..c874550f 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -42,7 +42,7 @@ from nullius import constraints as limits, hosts, providers from nullius.providers import PROVIDERS, STEP from nullius.standard.backends import boat -from nullius.standard.calls import ledger, relay +from nullius.standard.calls import exchanges, ledger, relay from nullius.standard.contract import definitions, match, ports from nullius.standard.proofs import prove from nullius.standard.requirements import hostreq @@ -413,7 +413,10 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, ``timeouts``: {phase: minutes}, each phase's time limit forced on every job (``--timeout``), empty for the default; ``turns``: the most agent turns in a conversation (``--max-turns``); ``max_calls``: the most model - calls a unit's agent may make (``--max-calls``). + calls a unit's agent may make (``--max-calls``). ``exchanges`` and + ``exchanges_max_mb``: what each unit's relay keeps of its agent's calls + and its bound in MB (``--exchanges``, ``--exchanges-max-mb``), said on + the command only when not the default. ``max_usd_per_unit``: each unit's own cap (``--max-usd-per-unit``), given whole to every job that calls a model. ``unpriced``: asked, for a recipe with a cap, which of the models it @@ -664,6 +667,18 @@ def add(step, message, shown=False, field=None): elif _int(calls, 1, 1000000) is None: add("limits", "Model calls per unit: a whole number of at least 1, or empty for no cap.") calls = None + keep = recipe.get("exchanges") # what each unit's relay keeps of its agent's calls (run --exchanges) + if keep in ("", None): + keep = exchanges.DEFAULT + elif keep not in exchanges.MODES: + add("limits", "Model exchanges: whole, text or off, or empty for whole.") + keep = exchanges.DEFAULT + keep_mb = recipe.get("exchanges_max_mb") + if keep_mb in ("", None): + keep_mb = exchanges.MAX_MB + elif _int(keep_mb, 1) is None: + add("limits", f"Model exchanges per unit: a whole number of MB, at least 1, or empty for {exchanges.MAX_MB}.") + keep_mb = exchanges.MAX_MB turns = recipe.get("turns") if turns in ("", None) or "agent.conversation/v1" not in (b.get("needs") or []): # only a conversation has turns turns = None @@ -818,6 +833,8 @@ def command_for(d: dict, p: dict, index: int) -> str: *[w for k, v in forced.items() for w in ("--timeout", f"{k}={v:g}")], *(["--max-turns", str(turns)] if turns else []), *(["--max-calls", str(calls)] if calls and spends(p) and o.get("_kind") != "capability" else []), + *(["--exchanges", keep] if keep != exchanges.DEFAULT else []), + *(["--exchanges-max-mb", str(keep_mb)] if keep_mb != exchanges.MAX_MB else []), *(["--simulator-model", sim_model] if sim_model and not p["control"] else []), *(["--judge-model", judge_model] if judge_model else []), "--name", job_of(d, p, index), *[w for k, v in given.items() for w in ("--option", f"{k}={v}")], @@ -934,6 +951,8 @@ def row(p: dict) -> list: *([[STEP["limits"], "Time limits", " · ".join(f"{k} {v / 60:g} min" for k, v in forced.items())]] if forced else []), *([[STEP["limits"], "Turns per conversation", str(turns)]] if turns else []), *([[STEP["limits"], f"Model calls per {noun}", str(calls)]] if calls else []), + *([[STEP["limits"], "Model exchanges", keep + (f" · at most {keep_mb} MB per {noun}" if keep != "off" else "")]] + if (keep, keep_mb) != (exchanges.DEFAULT, exchanges.MAX_MB) else []), [STEP["where"], "Where", (f"Boat sandboxes · one {boat.SIZES[boat_size]['label']} VM per {noun}" if backend == "boat" else (f"{of} shards, one per machine: " if of > 1 else "") + ", ".join(where_label(t) for t in targets) + f" · {backend} backend") diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index 2b8e4870..aa903072 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -574,7 +574,8 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str retries: int = 0, bench_options: Optional[dict] = None, simulator: str = "", prices: Optional[dict] = None, units_file: Optional[dict] = None, constraints: Optional[dict] = None, timeouts: Optional[dict] = None, max_turns: Optional[int] = None, - max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None): + max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None, + exchanges: str = "", exchanges_max_mb: Optional[int] = None): """``unsandboxed`` is true for an agent on the local backend only: in a container (``backend``, ``image``) it is not. ``standard.options`` holds every option's value, the defaults included, so two runs read side by side @@ -595,7 +596,10 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str a unit's agent the run forced (``run --timeout``, ``--max-turns``, ``--max-calls``), when it forced any. ``served_by``: by model, the serving providers the run let answer it - (``--served-by``), said only for a run that pinned them.""" + (``--served-by``), said only for a run that pinned them. + ``exchanges`` and ``exchanges_max_mb``: what each unit's relay kept of + its agent's calls (``run --exchanges``) and its bound in MB, said for + every run that gives them.""" with open(os.path.join(job_dir, "config.json"), "w") as f: json.dump({"job_name": job, "runner": "standard", "runner_label": "Nullius", "standard": {"benchmark": bench["key"], **_version(bench), "plugged": other.get("_ref") or other["key"], "kind": other["_kind"], "provider": provider, @@ -610,7 +614,8 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str **({"constraints": constraints} if constraints else {}), **({"timeouts": timeouts} if timeouts else {}), **({"max_turns": max_turns} if max_turns else {}), **({"max_calls": max_calls} if max_calls else {}), - **({"served_by": dict(sorted(served_by.items()))} if served_by else {})}, + **({"served_by": dict(sorted(served_by.items()))} if served_by else {}), + **({"exchanges": exchanges, "exchanges_max_mb": exchanges_max_mb} if exchanges else {})}, "runner_items": [bench["units"]["noun"], bench["units"]["nouns"]], "n_concurrent_trials": concurrency, "agents": [{"name": agent_name(other), "model_name": model}], diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index eacf6226..6e17a586 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -11,7 +11,8 @@ failure stops every unit, and a network hop for a unit sandboxed elsewhere. One per unit costs a few megabytes and loses only a shared rate limit - each unit backs off on its own. Its record sits in the trial's -``.work/relay``. +``.work/relay``, and the agent's calls kept whole in its ``exchanges`` +(``exchanges``, unless the run is told ``off``). Backends (``backend``). ``local``: processes on this machine, which are not a sandbox - what an agent runs, it runs as the user (``docs/standard.md``, @@ -72,11 +73,11 @@ from contextlib import contextmanager from typing import Callable, Dict, List, Optional, Tuple -from nullius import constraints as limits, paths, prices as price_list, progress, providers +from nullius import constraints as limits, paths, prices as price_list, progress, providers, settings from nullius.redact import redact from nullius.harbor import feed as live_feed from nullius.standard.backends import boat, container, mcp_machine -from nullius.standard.calls import ledger as ledgers, relay +from nullius.standard.calls import exchanges as exchange_store, 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 @@ -159,7 +160,7 @@ def provider_endpoint(provider: str, env=os.environ) -> tuple: raise Refused(f"provider {provider!r} is not one of {list(providers.PROVIDERS)}") rec = providers.record(provider, env) base = rec["base"] - key = env.get(rec["key"]) or ("local" if provider == "custom" else "") + key = env.get(rec["key"]) or (settings.MODEL_KEY_PLACEHOLDER if provider == "custom" else "") if not base: raise Refused("MODEL_API_URL is not set in Settings") if not key: @@ -460,6 +461,8 @@ class Run: timeouts: Dict[str, float] = {} # the run's own time limits by phase (__init__) forced_turns: Optional[int] = None max_calls: Optional[int] = None # the run's cap on a unit's agent's model calls (__init__) + exchanges: str = "off" # whether a unit's relay keeps its agent's calls whole (__init__: whole by default) + exchanges_max_mb: int = exchange_store.MAX_MB def __init__(self, bench: dict, other: dict, *, model: str, provider: str, dataset: Optional[str] = None, limit: Optional[int] = None, concurrency: int = 4, jobs_root: str = "jobs", name: Optional[str] = None, turn_seconds: Optional[int] = None, say: Callable[[str], None] = print, env=os.environ, @@ -472,7 +475,9 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas max_usd_per_unit: Optional[float] = None, prices_unreachable: Optional[str] = None, units_file: Optional[dict] = None, constraints: Optional[dict] = None, timeouts: Optional[dict] = None, max_turns: Optional[int] = None, - max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None, boat_size: str = boat.SIZE, relay_container: bool = False): + max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None, boat_size: str = boat.SIZE, + relay_container: bool = False, exchanges: str = exchange_store.DEFAULT, + exchanges_max_mb: int = exchange_store.MAX_MB): """``proving``: the run is a conformance kit's, the one run that may start before the port it checks is proven - the family must still match. ``unsandboxed``: consent to execute code as the user: required for @@ -542,7 +547,12 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas (:func:`served_by`), put on every request sent as that model by the run's relays (``relay.routing``) and recorded in the job's config. Refused when the provider routes no model to several (only - ``openrouter`` does), or when it names a model the run does not call.""" + ``openrouter`` does), or when it names a model the run does not call. + ``exchanges``: what each unit's relay keeps of its agent's calls + (``exchanges``): ``whole``, the request as sent and the reply as it + arrived; ``text``, without the pictures' bytes; ``off``, the call + record alone. ``exchanges_max_mb``: a unit's bound on it, in MB. The + job's config records both.""" backend = definitions.names.backend(backend) if backend not in BACKENDS: raise Refused(f"backend {backend!r} is not one of {list(BACKENDS)}") @@ -745,6 +755,11 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas # a capability's route carries the benchmark's reader too (produce): the cap would charge its calls to the capability raise Refused("--max-calls caps an agent's model calls: a capability's unit route carries the benchmark's reader too") self.max_calls = max_calls + if exchanges not in exchange_store.MODES: + raise Refused(f"--exchanges {exchanges!r}: one of {', '.join(exchange_store.MODES)}") + if isinstance(exchanges_max_mb, bool) or not isinstance(exchanges_max_mb, int) or exchanges_max_mb < 1: + raise Refused(f"--exchanges-max-mb {exchanges_max_mb!r}: a whole number of MB, at least 1") + self.exchanges, self.exchanges_max_mb = exchanges, exchanges_max_mb self.max_turns = max_turns or (bench.get("limits") or {}).get("turns") or MAX_TURNS self.score_seconds = (bench.get("limits") or {}).get("score_seconds") or DRIVER_SECONDS self.call_seconds = (bench.get("limits") or {}).get("call_seconds") or relay.TIMEOUT @@ -931,6 +946,7 @@ def _start(self, lck, mine) -> str: if self.shard else None, units_file=self.units_file, repeat=self.repeat, retries=self.retries, prices=self.prices_record(), constraints=self.constraints, served_by=self.serving, timeouts=self.timeouts, max_turns=self.forced_turns, max_calls=self.max_calls, + exchanges=self.exchanges, exchanges_max_mb=self.exchanges_max_mb, simulator=self.simulator_model if self.other["_kind"] in ("agent", "upstream") and self.simulator_model else "") # every unit once, then every unit again: a repeat cut short still has each unit's first run work = [(i, u, r) for r in range(1, self.repeat + 1) for i, u in mine] @@ -1800,12 +1816,15 @@ def unit_relay(self, tag: str, trial: str, setup: dict, env_def: Optional[dict] if not self.base: return None # a control with no judge: no model is called record = os.path.join(trial, ".work", "relay") + # whether the relay keeps its agent's calls whole, and its bound: the class's defaults for a stand-in of a run + keep = {"exchanges": getattr(self, "exchanges", Run.exchanges), + "exchanges_max_mb": getattr(self, "exchanges_max_mb", Run.exchanges_max_mb)} side = tuple((self.other.get("model") or {}).get("side_models") or ()) key_header = self.key_header if self.backend in ("local", "boat") and not getattr(self, "relay_container", False): # boat: the agent reaches it through its VM's tunnel rl = relay.Relay(self.base, self.key, record, prices=getattr(self, "prices", None), model=self.model, side_models=side, key_header=key_header, ledger=self.ledger_file(), serving=getattr(self, "serving", None), - timeout=self.call_seconds, max_calls=self.max_calls).start() + timeout=self.call_seconds, max_calls=self.max_calls, **keep).start() rl.unit_url = rl.url(tag) return rl routes = {tag + "-judge": self.judge_model} if self.judge_model else {} @@ -1818,7 +1837,7 @@ def unit_relay(self, tag: str, trial: str, setup: dict, env_def: Optional[dict] routes=routes, side_models=side, key_header=key_header, prices=price_list.given(self.models_called(), getattr(self, "prices", None)), hosts=door.hosts if door else None, ledger=self.ledger_file(), - serving=self.serving, max_calls=self.max_calls, timeout=self.call_seconds).start() + serving=self.serving, max_calls=self.max_calls, timeout=self.call_seconds, **keep).start() rl.unit_url = rl.url(tag) # driver and agent run on this host, outside the relay container return rl doors, listeners = [], [] @@ -1845,7 +1864,7 @@ def unit_relay(self, tag: str, trial: str, setup: dict, env_def: Optional[dict] prices=price_list.given(self.models_called(), getattr(self, "prices", None)), # a sidecar's argv: its models' rows servers=self.agent_servers(env_def), doors=doors, hosts=door.hosts if door else None, ledger=self.ledger_file(), serving=getattr(self, "serving", None), max_calls=self.max_calls, - timeout=self.call_seconds if self.call_seconds != relay.TIMEOUT else None, + **keep, timeout=self.call_seconds if self.call_seconds != relay.TIMEOUT else None, network_probe=probe, probe_now=bool(probe) and self.first_probe()) rl.mcp_listeners = listeners try: diff --git a/app/nullius/traces/calls.py b/app/nullius/traces/calls.py new file mode 100644 index 00000000..aaee14a2 --- /dev/null +++ b/app/nullius/traces/calls.py @@ -0,0 +1,596 @@ +"""A trial's transcript by model call: what each call of its agent sent that +the call before had not, the answer whole, and the session's steps that began +under it. + +Read from the trial's own records: the relay's call record +(``agent/calls.jsonl``, else ``.work/relay/.jsonl``) and, when the run +kept one, the store of its exchanges (``.work/relay/exchanges``, +``nullius.standard.calls.exchanges``). Calls are in the order they started. A call +is numbered as the cap on a unit's calls counts them: each the provider +answered; a refused or failed call keeps its place, unnumbered. + +- **Sent**: the parts a call holds that the call before it (on the same + route, a side call apart) did not, in the request's order: tool results, + pictures by their sha256, a new user message. The first call also lists the + system text and the tools, folded. A part of the call before that this one + no longer holds, or holds changed, is counted in one folded line; the + answer of the call before, sent back to the model, is left out (it is that + call's Answer). +- **Answer**: the reply read whole (``relay.read_reply``): text, reasoning, + tool calls with their arguments, how it ended, who served it. +- **Steps**: the session's steps (``agent/trajectory.json``) that began after + the call started and before the next one did. Steps before the first call + are the view's ``before``. + +Without the store a call has its time, tokens, cost and the answer as the +call record abridged it; its Sent is not recorded. A trial with no call record +has no calls. A call the store cannot give back (a damaged part, a picture +name that is not a digest) is said unreadable and the others are read. A store +in a later format than this code reads is not read: each call says why, as the +store refused it, and is read from its call record. + +Every text a view holds went through ``redact``; a picture is its hash, type +and size, never its bytes (:func:`picture` reads one, for a page). No Flask. +""" +from __future__ import annotations + +import bisect +import hashlib +import json +import math +import os +import re +from datetime import datetime, timezone +from typing import Dict, List, Optional + +from nullius.redact import redact +from nullius.standard.calls import exchanges, relay +from nullius.traces import conversation, trajectory + +CALLS = os.path.join("agent", "calls.jsonl") +RELAY = os.path.join(".work", "relay") +PAGE_SIZE = conversation.PAGE_SIZE +STEPS_SHOWN = 100 # a call's steps listed on its page; the rest counted +# the types a picture is served as: the store's four, ``image/jpg`` as JPEG +IMAGES = {"image/png": "image/png", "image/jpeg": "image/jpeg", "image/jpg": "image/jpeg", + "image/webp": "image/webp", "image/gif": "image/gif"} +_SHA = re.compile(r"[0-9a-f]{64}") +_TRY = re.compile(r"\.try-[0-9]+$") +_IDS = ("tool_call_id", "tool_use_id", "call_id") +# what a part says besides its text: not shown as text +_NOT_TEXT = {"type", "role", "id", "name", "signature", "detail", "media_type", "cache_control", "status", *_IDS} +_LABEL = {"system": "System text", "tools": "Tools", "user": "User message", "tool result": "Tool result", + "answer": "Assistant message", "other": "Part"} +# Responses items that are the model's own output sent back +_ANSWER_ITEMS = {"function_call", "reasoning", "custom_tool_call", "local_shell_call", "computer_call", + "web_search_call", "file_search_call", "code_interpreter_call", "image_generation_call", "mcp_call"} + + +def _jsonl(path: str) -> List[dict]: + out = [] + try: + with open(path, encoding="utf-8", errors="replace") as f: + for row in f: + try: + got = json.loads(row) + except ValueError: + continue + if isinstance(got, dict): + out.append(got) + except OSError: + pass + return out + + +def _iso(t) -> Optional[str]: + try: + return datetime.fromtimestamp(float(t), timezone.utc).isoformat() if t else None + except (TypeError, ValueError, OverflowError, OSError): + return None + + +def _number(v) -> Optional[float]: + return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None + + +def store_folder(trial_dir: str) -> str: + return os.path.join(trial_dir, RELAY, exchanges.FOLDER) + + +def pictures_kept(trial_dir: str) -> Optional[dict]: + """The pictures the trial's store keeps, each sent to the model and kept once (``blobs/``): ``{count, bytes}``, + or None when it keeps none. A folder or a file reached through a link is not read.""" + folder = os.path.join(store_folder(os.path.realpath(trial_dir)), exchanges.BLOBS) + if os.path.realpath(folder) != folder or not os.path.isdir(folder): + return None + kinds, count, size = {"." + e for e in exchanges.EXT.values()}, 0, 0 + try: + with os.scandir(folder) as found: + for e in found: + if os.path.splitext(e.name)[1] in kinds and e.is_file(follow_symlinks=False): + count, size = count + 1, size + e.stat(follow_symlinks=False).st_size + except OSError: + return None + return {"count": count, "bytes": size} if count else None + + +def route_tag(trial_dir: str, routes: List[str]) -> str: + """The unit's route: the end of its trial's name (an earlier try's ``.try-N`` left off), else the store's one route.""" + tag = _TRY.sub("", os.path.basename(os.path.normpath(trial_dir))).rsplit("__", 1)[-1] + return tag if tag in routes or not routes else routes[0] if len(routes) == 1 else tag + + +def _record(trial_dir: str, tag: str) -> List[dict]: + rows = _jsonl(os.path.join(trial_dir, CALLS)) + if rows or not relay._TAG.match(tag): + return rows + return _jsonl(os.path.join(trial_dir, RELAY, tag + ".jsonl")) + + +def recorded(trial_dir: str) -> int: + """How many calls the trial's call record holds: 0 when it has none (a Harbor or imported trial, a control).""" + folder = store_folder(trial_dir) + return len(_record(trial_dir, route_tag(trial_dir, exchanges.tags(folder)))) + + +def signature(trial_dir: str, trajectory_path: str = "") -> tuple: + """What a view is read from, by size and time: a view kept for it holds while this is the same.""" + folder = store_folder(trial_dir) + tag = route_tag(trial_dir, exchanges.tags(folder)) + out = [] + for path in (os.path.join(trial_dir, CALLS), os.path.join(trial_dir, RELAY, tag + ".jsonl"), + os.path.join(folder, tag + ".jsonl"), os.path.join(folder, exchanges.PARTS), trajectory_path): + try: + st = os.stat(path) if path else None + out.append((path, st.st_size, st.st_mtime_ns) if st else None) + except OSError: + out.append(None) + return tuple(out) + + +# -- the store's parts, each line on its own -------------------------------------- +def _parts(folder: str) -> Dict[str, object]: + """Each part of the store by its hash. A line that is not JSON or whose hash is not a digest is left + out: only the calls that name it are then unreadable.""" + out = {} + try: + path = exchanges._inside(os.path.realpath(folder), exchanges.PARTS) + except exchanges.Missing: + return out + for p in exchanges.unmarked(_jsonl(path), exchanges.PARTS): + h = p.get("sha256") + if isinstance(h, str) and re.fullmatch(r"[0-9a-fA-F]{64}", h) and "part" in p: + out[h] = p["part"] + return out + + +def _marks(v, found: Dict[str, str]) -> None: + """Every picture's mark in ``v``: its hash and type, into ``found``.""" + if isinstance(v, dict): + if set(v) == {exchanges.LITERAL}: + for x in (v[exchanges.LITERAL] or {}).values() if isinstance(v[exchanges.LITERAL], dict) else (): + _marks(x, found) + return + if set(v) == exchanges.MARK: + if isinstance(v.get("blob"), str) and isinstance(v.get("type"), str): + found.setdefault(v["blob"], v["type"]) + return + for x in v.values(): + _marks(x, found) + elif isinstance(v, list): + for x in v: + _marks(x, found) + + +def _walk(v, texts: List[str], pictures: List[dict], check, media=None) -> None: + """A part's text and its pictures, in order. ``check(mark)``: the picture as a view holds it; it raises + ``exchanges.Missing`` for a mark that names no digest.""" + if isinstance(v, str): + inline = exchanges._picture(v, media, text_only=True) + if inline: + kind, raw, _ = inline + h = hashlib.sha256(raw).hexdigest() + pictures.append({"sha256": h, "type": kind, "bytes": len(raw), "stored": False}) + texts.append(f"[picture {h[:12]}]") + else: + texts.append(v) + elif isinstance(v, list): + for x in v: + _walk(x, texts, pictures, check) + elif isinstance(v, dict): + if set(v) == {exchanges.LITERAL} and isinstance(v[exchanges.LITERAL], dict): + v = v[exchanges.LITERAL] + elif set(v) == exchanges.MARK: + pictures.append(check(v)) + texts.append(f"[picture {str(v.get('blob'))[:12]}]") + return + media = v.get("media_type") if v.get("type") == "base64" and isinstance(v.get("media_type"), str) else None + for k, x in v.items(): + if k not in _NOT_TEXT: + _walk(x, texts, pictures, check, media if k == "data" else None) + + +def _kind(field: str, part) -> str: + if field == "tools": + return "tools" + if field in ("system", "instructions"): + return "system" + if isinstance(part, str): + return "user" + if not isinstance(part, dict): + return "other" + role, typ = part.get("role"), part.get("type") + if role in ("system", "developer"): + return "system" + if role == "tool" or (isinstance(typ, str) and typ.endswith("_output")): + return "tool result" + if role == "assistant" or typ in _ANSWER_ITEMS: + return "answer" + if role == "user": + c = part.get("content") + if isinstance(c, list) and any(isinstance(b, dict) and b.get("type") == "tool_result" for b in c): + return "tool result" + return "user" + return "other" + + +def _tool_name(part) -> str: + if not isinstance(part, dict): + return "" + f = part.get("function") if isinstance(part.get("function"), dict) else {} + return str(part.get("name") or f.get("name") or part.get("type") or "") + + +def _held(line: dict) -> List[tuple]: + """(field, hash) of each part a call's line names, in the request's order.""" + out = [] + for k, v in (line.get("sent") or {}).items(): + if k in exchanges.PART_FIELDS and isinstance(v, dict): + if isinstance(v.get("parts"), list): + out += [(k, h) for h in v["parts"]] + elif isinstance(v.get("part"), str): + out.append((k, v["part"])) + return out + + +class _Reader: + """One trial's store, read once for every call of a view.""" + + def __init__(self, folder: str): + self.folder = folder + self.parts = _parts(folder) + self.stored: Dict[str, bool] = {} + self.checked: dict = {} + + def picture(self, mark: dict) -> dict: + path = exchanges._picture_path(self.folder, mark) # Missing: a name that is not a digest, a path outside + h = mark["blob"] + if h not in self.stored: + self.stored[h] = os.path.isfile(path) + return {"sha256": h, "type": str(mark.get("type")), "bytes": _number(mark.get("bytes")), "stored": self.stored[h]} + + def item(self, field: str, h: str) -> dict: + exchanges._digest(h) + if h not in self.parts: + raise exchanges.Missing(f"the part {h} is not in the store") + part = self.parts[h] + kind = _kind(field, part) + texts, pictures = [], [] + if kind == "tools": + name = _tool_name(part) + _walk(part, [], pictures, self.picture) + text = exchanges._text_body(json.dumps(part, indent=1, ensure_ascii=False)) + return {"kind": kind, "sha256": h, "names": [name] if name else [], "text": text, "pictures": pictures} + _walk(part, texts, pictures, self.picture) + out = {"kind": kind, "sha256": h, "text": "\n".join(t for t in texts if t), "pictures": pictures} + ids = [part.get(k) for k in _IDS if isinstance(part, dict) and isinstance(part.get(k), str)] + if not ids and isinstance(part, dict) and isinstance(part.get("content"), list): + ids = [b.get("tool_use_id") for b in part["content"] if isinstance(b, dict) and isinstance(b.get("tool_use_id"), str)] + if kind == "tool result" and ids: + out["tool_call_id"] = ids[0] + return out + + def sent(self, line: dict, before: Optional[dict]) -> dict: + """A call's Sent: its items, and the folded line of what the call before held that it does not.""" + held = _held(line) + for k, h in held: + if (k, h) not in self.checked: + try: + self.checked[k, h] = self.item(k, h) + except exchanges.Missing as e: + self.checked[k, h] = e + if isinstance(self.checked[k, h], exchanges.Missing): + raise self.checked[k, h] + new = set(exchanges.new_parts(line, before)) + items: List[dict] = [] + if before is None: # the first: the system text and the tools, folded, then all of it + tools = [self.checked[k, h] for k, h in held if k == "tools"] + said = [self.checked[k, h] for k, h in held if k in ("messages", "input")] + items += [self.checked[k, h] for k, h in held if k in ("system", "instructions")] + [x for x in said if x["kind"] == "system"] + if tools: + items.append({"kind": "tools", "names": [n for t in tools for n in t["names"]], + "text": "\n\n".join(t["text"] for t in tools), "pictures": [p for t in tools for p in t["pictures"]]}) + items += [x for x in said if x["kind"] != "system"] + return {"recorded": True, "items": items, "rewritten": [], "dropped": 0} + had = {h for _, h in _held(before)} + msgs = [(i, h) for i, (k, h) in enumerate(held) if k in ("messages", "input")] + last_kept = max((i for i, h in msgs if h in had), default=-1) + rewritten, tools = [], [] + for i, (k, h) in enumerate(held): + if h not in new: + continue + got = self.checked[k, h] + if k == "tools": + tools.append(got) + elif k in ("messages", "input") and i < last_kept: + rewritten.append(got) # a part among those the call before held, changed + elif got["kind"] != "answer": # the call before's answer, sent back: its own Answer + items.append(got) + if tools: + items.insert(0, {"kind": "tools", "names": [n for t in tools for n in t["names"]], + "text": "\n\n".join(t["text"] for t in tools), "pictures": [p for t in tools for p in t["pictures"]]}) + now = {h for _, h in held} + return {"recorded": True, "items": items, "rewritten": rewritten, "dropped": len(had - now)} + + +def _answer_of_line(line: dict) -> Optional[dict]: + reply = line.get("reply") if isinstance(line.get("reply"), dict) else {} + body = reply.get("body") + if reply.get("status") != 200 or not isinstance(body, str): + return None + raw, streamed, path = body.encode("utf-8", "replace"), bool(reply.get("streamed")), str(line.get("path") or "") + try: + got = relay.read_reply(path, raw, streamed, reasoning=True, whole=True) + except Exception: # a body the reader does not know: shown as it came + got = {"text": body} + facts = relay.reply_facts(path, raw, streamed) + return {"text": got.get("text") or "", "reasoning": got.get("reasoning") or "", + "tool_calls": [{"name": str(c.get("name") or ""), "arguments": c.get("arguments") if isinstance(c.get("arguments"), str) + else json.dumps(c.get("arguments"))} for c in got.get("tool_calls") or [] if isinstance(c, dict)], + "end": facts.get("end"), "served_by": facts.get("served_by"), "error": facts.get("error"), "abridged": False} + + +def _answer_of_record(rec: dict) -> dict: + reply = rec.get("reply") if isinstance(rec.get("reply"), dict) else {} + return {"text": reply.get("text") or "", "reasoning": "", + "tool_calls": [{"name": str(c.get("name") or ""), "arguments": c.get("arguments") if isinstance(c.get("arguments"), str) + else json.dumps(c.get("arguments"))} for c in reply.get("tool_calls") or [] if isinstance(c, dict)], + "end": reply.get("end"), "served_by": reply.get("served_by"), "error": reply.get("error"), "abridged": True} + + +def _redacted(v): + if isinstance(v, str): + return redact(exchanges._text_body(v)) + if isinstance(v, list): + return [_redacted(x) for x in v] + if isinstance(v, dict): + return {k: _redacted(x) for k, x in v.items()} + return v + + +def view(trial_dir: str, traj=None) -> dict: + """The trial's calls: ``record`` says what they were read from (``exchanges``, ``calls`` or None), + ``calls`` each call, ``before`` the steps before the first one, ``pictures`` the store's pictures by + hash (their types). ``traj``: the trial's trajectory as ``trajectory.load`` reads it, for the steps.""" + folder = store_folder(trial_dir) + tag = route_tag(trial_dir, exchanges.tags(folder)) + records = _record(trial_dir, tag) + lines, reader, refused = {}, None, "" + try: + lines = {x["n"]: x for x in exchanges.lines(folder, tag) if isinstance(x.get("n"), int)} if relay._TAG.match(tag) else {} + reader = _Reader(folder) if lines else None + except exchanges.Later as e: # a later format: its calls from their record alone, each saying why + lines, reader, refused = {}, None, str(e) + except exchanges.Missing: + pass + seen = {r.get("n") for r in records} + records += [{"n": n, "t0": x.get("t0"), "path": x.get("path"), "status": (x.get("reply") or {}).get("status")} + for n, x in sorted(lines.items()) if n not in seen] # a call its record lost + order = sorted(range(len(records)), key=lambda i: (_number(records[i].get("t0")) or 0.0, i)) + pictures: Dict[str, str] = {} + if reader is not None: + for p in reader.parts.values(): + _marks(p, pictures) + for x in lines.values(): + if isinstance(x.get("sent"), dict): + _marks({k: v for k, v in x["sent"].items() if k not in exchanges.PART_FIELDS}, pictures) + out, counted, before = [], 0, {} + for i in order: + rec = records[i] + path = str(rec.get("path") or "") + answered = rec.get("status") == 200 and bool(rec.get("model")) and not relay._free(path) + counted += answered + usage = ((rec.get("reply") or {}).get("usage") or {}) if isinstance(rec.get("reply"), dict) else {} + t0, t1 = _number(rec.get("t0")), _number(rec.get("t1")) + call = {"position": len(out), "number": counted if answered else None, "n": rec.get("n"), + "label": f"Call {counted}" if answered else "Refused" if rec.get("refused") else + "Failed" if rec.get("status") != 200 else "Not counted", + "t0": t0, "time": _iso(t0), "seconds": round(t1 - t0, 3) if t0 is not None and t1 is not None else None, + "model": rec.get("model"), "side": bool(rec.get("side")), "path": path, "status": rec.get("status"), + "refused": rec.get("refused"), "error": rec.get("error"), + "tokens": {k: usage[k] for k in ("input", "output", "cached", "cache_write", "reasoning") if isinstance(usage.get(k), int)}, + "cost_usd": _number(rec.get("cost_usd")), "cost_from": rec.get("cost_from"), "steps": []} + line = lines.get(rec.get("n")) if isinstance(rec.get("n"), int) else None + if line is None: + call["sent"] = ({"recorded": False, "unreadable": True, "note": "Unreadable: " + refused} if refused and not rec.get("refused") + else {"recorded": False, "note": "Not sent: refused before it went out" if rec.get("refused") else "Not recorded"}) + call["answer"] = _answer_of_record(rec) if rec.get("status") == 200 else None + else: + call["answer"] = _answer_of_line(line) or (_answer_of_record(rec) if rec.get("status") == 200 else None) + if line.get("cut"): + call["sent"] = {"recorded": False, "note": "Not kept: " + str(line["cut"])} + elif "sent_body" in line: + call["sent"] = {"recorded": True, "items": [{"kind": "other", "text": str(line["sent_body"]), "pictures": []}], + "rewritten": [], "dropped": 0} + elif not isinstance(line.get("sent"), dict): + call["sent"] = {"recorded": False, "unreadable": True, + "note": "Unreadable: " + str(line.get("error") or "the store holds no request for this call")} + else: + side = bool(rec.get("side")) + try: + call["sent"] = reader.sent(line, before.get(side)) + except (exchanges.Missing, KeyError, TypeError, AttributeError) as e: + call["sent"] = {"recorded": False, "unreadable": True, "note": f"Unreadable: {e}"} + before[side] = line # what the next one is new against: its hashes, read or not + out.append(call) + early = [] + starts = [c["t0"] if c["t0"] is not None else float("-inf") for c in out] + for pos, st in enumerate(getattr(traj, "steps", None) or [] if traj is not None and not getattr(traj, "error", "") else []): + at = trajectory.parse_ts(st.timestamp) + if at is None: # a step with no clock is under no call: the flat list has it + continue + ref = {"position": pos, "step_id": st.step_id, "source": st.source, + "preview": conversation._preview(st.message if st.message and st.message != "(tool use)" else + ", ".join(c.get("name", "Tool") for c in st.tool_calls)) or "No message recorded"} + k = bisect.bisect_right(starts, at.timestamp()) - 1 + (out[k]["steps"] if k >= 0 else early).append(ref) + out = _redacted(out) + for c in out: + c["search"] = "\n".join(_texts_of(c)).casefold() + return {"record": "exchanges" if lines else "calls" if records else None, "calls": out, + "before": _redacted(early), "folder": folder, "pictures": pictures, "notice": redact(refused)} + + +def _texts_of(call: dict) -> List[str]: + out = [call.get("label") or "", call.get("error") or ""] + sent = call.get("sent") or {} + for item in (sent.get("items") or []) + (sent.get("rewritten") or []): + out += [item.get("text") or "", " ".join(item.get("names") or [])] + a = call.get("answer") or {} + out += [a.get("text") or "", a.get("reasoning") or ""] + for c in a.get("tool_calls") or []: + out += [c["name"], c["arguments"] or ""] + return [x for x in out if x] + + +# -- a page of the view, as the conversation reader pages steps ------------------- +def _item_label(item: dict) -> str: + label = _LABEL.get(item.get("kind"), "Part") + return label + (f" · {item['tool_call_id']}" if item.get("tool_call_id") else "") + + +def _preview_of(item: dict) -> str: + if item.get("kind") == "tools": + return ", ".join(item.get("names") or []) or "Tools" + said = conversation._preview(re.sub(r"\[picture [0-9a-fA-F]{12}\]", "", item.get("text") or "")) + n = len(item.get("pictures") or []) + return said or (f"{n} picture{'s' * (n != 1)}" if n else "Nothing recorded") + + +def _sections(call: dict) -> List[tuple]: + """(key, label, text, facts) of each text a call holds: its Sent, its folded line, its Answer.""" + out = [] + sent = call.get("sent") or {} + for i, item in enumerate(sent.get("items") or []): + out.append((f"sent-{i}", _item_label(item), item.get("text") or "", {"part": "sent"})) + if sent.get("rewritten") or sent.get("dropped"): + said = [f"{_item_label(x)} as sent now:\n{x.get('text') or ''}" for x in sent.get("rewritten") or []] + out.append(("folded", "Rewritten or dropped", "\n\n".join(said) or + f"{sent['dropped']} part{'s' * (sent['dropped'] != 1)} of the call before not sent again.", {"part": "sent"})) + a = call.get("answer") or {} + if a.get("reasoning"): + out.append(("reasoning", "Reasoning", a["reasoning"], {"part": "answer"})) + if a.get("text"): + out.append(("text", "Text", a["text"], {"part": "answer"})) + for i, c in enumerate(a.get("tool_calls") or []): + out.append((f"tool-{i}", c["name"] or "Tool call", c["arguments"] or "", {"part": "answer", "tool": c["name"]})) + if call.get("error") and call.get("status") != 200: + out.append(("error", "Error", call["error"], {"part": "answer"})) + return out + + +def _row(call: dict) -> dict: + a = call.get("answer") or {} + said = ", ".join(c["name"] for c in a.get("tool_calls") or [] if c.get("name")) + preview = conversation._preview(a.get("text")) or said or conversation._preview(call.get("error")) or "No answer recorded" + if said and a.get("text"): + preview = conversation._preview(f"{said} · {a['text']}") + return {"position": call["position"], "number": call["number"], "label": call["label"], "time": call["time"], + "status": call["status"], "tokens": call["tokens"], "cost_usd": call["cost_usd"], "preview": preview, + "steps": len(call["steps"]), "pictures": sum(len(i.get("pictures") or []) for i in (call.get("sent") or {}).get("items") or []), + "unreadable": bool((call.get("sent") or {}).get("unreadable"))} + + +def page(v: dict, *, query="", page=1, position=None, step=None, section=None, chunk=0) -> dict: + """Twelve calls of a view, and one selected whole: its Sent, its Answer, its steps and one window of + the text chosen (``section``, ``chunk``), as ``conversation.page`` gives a step's.""" + query = conversation._text(query).strip()[:500] + calls = v.get("calls") or [] + result = {"view": "calls", "query": query, "kind": "calls", "page_size": PAGE_SIZE, "page": 1, "pages": 1, + "total": len(calls), "matches": 0, "rows": [], "selected": None, "notice": "" if calls else v.get("notice") or "", "record": v.get("record")} + needle = query.casefold() + matching = [i for i, c in enumerate(calls) if not needle or needle in c["search"]] + result["matches"] = len(matching) + result["pages"] = max(1, math.ceil(len(matching) / PAGE_SIZE)) + number = min(max(1, conversation._integer(page, 1)), result["pages"]) + chosen = None + if step is not None: + chosen = next((i for i in matching if any(str(s["step_id"]) == str(step) for s in calls[i]["steps"])), None) + if chosen is None: + result["notice"] = result["notice"] or "No call in this search holds that source step." + elif position is not None: + wanted = conversation._integer(position, -1) + chosen = wanted if wanted in matching else None + if chosen is not None: + number = matching.index(chosen) // PAGE_SIZE + 1 + elif matching: + chosen = matching[(number - 1) * PAGE_SIZE] + result["page"] = number + result["rows"] = [_row(calls[i]) for i in matching[(number - 1) * PAGE_SIZE:number * PAGE_SIZE]] + if chosen is None: + result["notice"] = result["notice"] or "No calls match this search." + return result + call, at = calls[chosen], matching.index(chosen) + sections = _sections(call) + keys = [s[0] for s in sections] + wanted = section if section in keys else next((k for k in keys if not k.startswith(("sent-", "folded"))), keys[0] if keys else None) + sent = call.get("sent") or {} + a = call.get("answer") + result["selected"] = { + **{k: call[k] for k in ("position", "number", "label", "time", "seconds", "model", "side", "status", "refused", + "tokens", "cost_usd", "cost_from")}, + "match_number": at + 1, "previous": matching[at - 1] if at else None, + "next": matching[at + 1] if at + 1 < len(matching) else None, + "sent": {"recorded": bool(sent.get("recorded")), "note": sent.get("note") or "", "unreadable": bool(sent.get("unreadable")), + "items": [{"key": f"sent-{i}", "kind": item.get("kind"), "label": _item_label(item), "preview": _preview_of(item), + "characters": len(item.get("text") or ""), "pictures": [dict(x) for x in item.get("pictures") or []]} + for i, item in enumerate(sent.get("items") or [])], + "folded": ({"key": "folded", "rewritten": len(sent.get("rewritten") or []), "dropped": sent.get("dropped") or 0} + if sent.get("rewritten") or sent.get("dropped") else None)}, + "answer": {"recorded": a is not None, "end": (a or {}).get("end"), "served_by": (a or {}).get("served_by"), + "error": (a or {}).get("error"), "abridged": bool((a or {}).get("abridged")), + "items": [{"key": k, "label": label, "preview": conversation._preview(text, 100), "characters": len(text)} + for k, label, text, facts in sections if facts.get("part") == "answer"]}, + "steps": call["steps"][:STEPS_SHOWN], "more_steps": max(0, len(call["steps"]) - STEPS_SHOWN), + "before": (v.get("before") or [])[:STEPS_SHOWN] if chosen == 0 else [], + "sections": conversation._section_index(sections), + "content": conversation._content(sections, wanted, chunk) if sections else None} + return result + + +def document(v: dict) -> dict: + """The view as a command prints it: every call whole, the steps by their ids.""" + keep = lambda c: {k: x for k, x in c.items() if k not in ("search", "t0", "position")} + return {"record": v.get("record"), + "calls": [dict(keep(c), steps=[s["step_id"] for s in c["steps"]]) for c in v.get("calls") or []], + "before": [s["step_id"] for s in v.get("before") or []]} + + +def picture(v: dict, sha256: str) -> tuple: + """(bytes, media type) of a picture the trial's store lists, of one of the four image types, its bytes + the hash they are named by. ``LookupError`` for any other: not a digest, not listed, not an image, + not kept (a store kept as text), damaged.""" + if not isinstance(sha256, str) or not _SHA.fullmatch(sha256): + raise LookupError("not a sha256") + kind = (v.get("pictures") or {}).get(sha256) + if kind not in IMAGES: + raise LookupError("not a picture of this trial's store") + try: + path = exchanges._picture_path(v["folder"], {"blob": sha256, "type": kind}) + with open(path, "rb") as f: + data = f.read() + except (exchanges.Missing, OSError, KeyError): + raise LookupError("not kept") + if hashlib.sha256(data).hexdigest() != sha256: + raise LookupError("damaged") + return data, IMAGES[kind] diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index 88825f5f..3cf6c8c2 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -234,6 +234,9 @@ } if (Number.isInteger(raw.turns) && raw.turns >= 1) r.turns = raw.turns; if (Number.isInteger(raw.max_calls) && raw.max_calls >= 1) r.max_calls = raw.max_calls; // the most model calls of a unit's agent + // what each unit's relay keeps of its agent's calls, and its bound in MB (recipe.py: run --exchanges) + if (['whole', 'text', 'off'].includes(raw.exchanges)) r.exchanges = raw.exchanges; + if (Number.isInteger(raw.exchanges_max_mb) && raw.exchanges_max_mb >= 1) r.exchanges_max_mb = raw.exchanges_max_mb; for (const key of ['judge_model', 'simulator_model']) if (typeof raw[key] === 'string' && raw[key].trim()) r[key] = raw[key].trim(); // Served by: each field's serving providers, slugs in their order (the server checks them as --served-by) if (raw.served_by && typeof raw.served_by === 'object' && !Array.isArray(raw.served_by)) diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 3ffa42ab..6f4a9ee5 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -286,3 +286,9 @@ /* its outlined pills (Protocol, Proven) want more air than snug's text beside text; a phone keeps snug's, for the pinned name */ @media (min-width: 641px) { #nullius-builder :is(#nb-bench-grid, #nb-agent-grid) .grid.snug :is(th, td):not(.pick-col) { padding-left: .6rem; padding-right: .6rem; } } /* the card's ring (catalogue.css), not a box round the name */ #nullius-builder .st-search input:focus-visible { outline: none; } /* the search box draws the focus ring itself (style.css .st-search:focus-within), not its input */ + +/* Model-call retention uses the same type size as the adjacent form controls. */ +#nullius-builder .std-exchanges .std-val strong { font: 13px/1.5 var(--sans); } +#nullius-builder .std-exchanges-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; padding: 16px 0; border-bottom: 1px solid var(--nb-line); } +#nullius-builder .std-exchanges { display: flex; flex-wrap: wrap; gap: 8px; } +#nullius-builder .std-exchanges .std-val { flex: 0 0 auto; min-width: max-content; padding: 6px 11px; } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 60769ebe..7a48cc7e 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -806,11 +806,17 @@ + (C.standardKeyless(rec) || (b.needs || []).some(n => n.startsWith('cap.')) ? '' : field('Model calls per ' + u.noun, 'max_calls', rec.max_calls ?? '', {type: 'number', min: 1, placeholder: 'none'})) // the whole run's, shared by its jobs (recipe.py); a run that calls no model spends nothing: no cap to offer + (C.standardKeyless(rec) ? '' : field('Spending cap (USD)', 'max_usd', rec.max_usd ?? '', {type: 'number', min: 0, placeholder: 'none'}) - + field('Spending cap per ' + u.noun + ' (USD)', 'max_usd_per_unit', rec.max_usd_per_unit ?? '', {type: 'number', min: 0, placeholder: 'none'})) + + field('Spending cap per ' + u.noun + ' (USD)', 'max_usd_per_unit', rec.max_usd_per_unit ?? '', {type: 'number', min: 0, placeholder: 'none'}) + + exchangesKept(rec)) + standardTimeLimits(rec, b, u) + benchLimits(rec, b); } return ''; } + // What each unit's relay keeps of its agent's calls, read on the trial's Conversation tab (recipe.py: run --exchanges): + // the pictures and the text, the text alone (each picture's size and kind kept), or nothing; small cards, the first the default + const KEEPS = [['whole', 'Pictures and text'], ['text', 'Text alone'], ['off', 'Nothing']]; + const exchangesKept = rec => '
Model calls saved' + + `
${KEEPS.map(([v, t]) => ``).join('')}
`; // The bounds the benchmark's upstream has of its own (its steps, its errors: options with ``limit``), in a section // of the benchmark's name after the run's scope and its time limits: those the chosen datasets and participants // take, each empty at its default, shown greyed - an agent's own under ``by`` (OSWorld's agents' steps). @@ -1127,6 +1133,7 @@ // a provider taken out of a Served by. Its row's label does not then focus the field (its menu would open); by // key, the keyboard goes back to that field if(d.servedRemove!==undefined){event.preventDefault();C.removeServed(r(),d.servedRole,d.servedRemove);syncServed();refreshPlan();if(event.detail===0)root.querySelector(`input[data-served-by="${d.servedRole}"]`)?.focus();return;} + if(d.stdExchanges!==undefined){const rec=r();if(d.stdExchanges==='whole')delete rec.exchanges;else rec.exchanges=d.stdExchanges;renderForm();refreshPlan();return;} if(d.benchOpt!==undefined){const rec=r(),o=((C.standardBench(rec)||{}).options||{})[d.benchOpt]||{};rec.bench_options={...(rec.bench_options||{})};if(d.benchVal===o.default)delete rec.bench_options[d.benchOpt];else rec.bench_options[d.benchOpt]=d.benchVal;renderForm();refreshPlan();return;} if(d.hostreqCheck!==undefined){hostReq(d.hostreqCheck,'check',d.hostreqName);return;} if(d.hostreqInstall!==undefined){hostReq(d.hostreqInstall,'install',d.hostreqName);return;} diff --git a/app/static/traces/conversation.css b/app/static/traces/conversation.css index d7493bc6..b5dd6181 100644 --- a/app/static/traces/conversation.css +++ b/app/static/traces/conversation.css @@ -42,6 +42,22 @@ .reader-layout button:disabled,.reader-content-nav button:disabled{opacity:.4;cursor:default} .reader-layout button:focus-visible,.reader-toolbar button:focus-visible,.trial-tabs button:focus-visible{outline:2px solid var(--accent);outline-offset:2px} .wf-detail .reader-content{margin-top:18px}.wf-detail .reader-sections{margin-top:20px} +/* the view by model call: a call's Sent, Answer and steps, each a list of rows; pictures scaled to the row */ +.call-part{margin:0 0 20px}.call-part h4{margin:0 0 8px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--text-dim)} +.call-item{width:100%;display:flex;gap:10px;align-items:baseline;text-align:left;border:1px solid var(--border);border-radius:7px;background:var(--bg);color:var(--text);font:inherit;font-size:12px;padding:8px 11px;margin:0 0 6px;cursor:pointer;min-width:0} +.call-item[aria-pressed=true]{border-color:var(--accent)} +.call-item-kind{flex:none;font-size:11px;color:var(--text-dim)} +.call-item-preview{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.call-item-size{flex:none;font-size:10px;color:var(--text-dim)} +.call-pictures{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 8px} +.call-picture{display:block;max-width:100%;max-height:220px;width:auto;height:auto;border:1px solid var(--border);border-radius:6px;background:var(--surface)} +.call-picture-link{display:block;max-width:100%} +.picture-view{padding:0;border:0;background:transparent;max-width:96vw;max-height:96vh;overflow:visible} +.picture-view::backdrop{background:rgb(0 0 0 / .72)} +.picture-view-box{display:flex;flex-direction:column;align-items:flex-end;gap:8px;padding:10px;background:var(--surface);border:1px solid var(--border);border-radius:12px} +.picture-view-img{display:block;max-width:calc(96vw - 22px);max-height:calc(96vh - 72px);width:auto;height:auto;object-fit:contain;border-radius:6px} +.call-picture-kept{font-size:11px;color:var(--text-dim);border:1px dashed var(--border);border-radius:6px;padding:6px 9px} +.call-facts{font-size:11px;color:var(--text-dim);margin:0 0 8px} @media(max-width:850px){.reader-selected{padding:18px}.reader-layout{grid-template-columns:minmax(175px,30%) minmax(0,1fr)}.reader-step-nav{align-items:flex-start;flex-direction:column;gap:12px}} @media(max-width:600px){.reader-layout{grid-template-columns:minmax(0,1fr);min-height:0}.reader-index{border-right:0;border-bottom:1px solid var(--border)}.reader-rows{max-height:230px;overflow:auto}.reader-row{padding:10px 12px}.reader-row-preview{-webkit-line-clamp:1}.reader-selected{padding:16px}.reader-content pre{max-height:360px;padding:12px}.reader-search{gap:6px}.reader-toolbar{gap:10px}.reader-jump{width:100%}.reader-jump input{flex:1;min-width:0}.reader-content-nav{gap:6px;font-size:10px}.trial-tabs{gap:22px}.reader-filters{width:100%;justify-content:space-between}.reader-filters button{padding:7px 8px}} diff --git a/app/static/traces/conversation.js b/app/static/traces/conversation.js index 5e590258..fd891ee3 100644 --- a/app/static/traces/conversation.js +++ b/app/static/traces/conversation.js @@ -14,6 +14,21 @@ return node; }; const number = value => Number(value).toLocaleString(); + // A picture of the conversation over the page: one dialog, made at the first, closed by Close, Esc or a click + // outside the picture (on the backdrop, which is the dialog itself) + let viewer = null; + const viewPicture = (url, alt) => { + if (!viewer) { + viewer = el('dialog', 'picture-view'); viewer.setAttribute('aria-label', 'Picture'); + const box = el('div', 'picture-view-box'); + box.append(button('Close', () => viewer.close(), false, 'btn sm picture-view-close'), el('img', 'picture-view-img')); + viewer.append(box); + viewer.addEventListener('click', event => { if (event.target === viewer) viewer.close(); }); + document.body.append(viewer); + } + const img = viewer.querySelector('img'); img.src = url; img.alt = alt; + viewer.showModal(); + }; const readJSON = async (url, signal) => { const response = await nulliusFetch(url, {signal, headers: {'Accept': 'application/json'}, cache: 'no-store'}); if (!response.ok) throw new Error(response.status === 404 ? 'This evidence is no longer in the current workspace or trace view.' : 'Could not load this evidence. Try again.'); @@ -85,7 +100,7 @@ let loadConversation = () => {}; if (reader?.querySelector('.reader-layout')) { const urlState = new URL(location.href).searchParams; - let state = {q: urlState.get('c_q') || '', kind: urlState.get('c_kind') || 'all', + let state = {q: urlState.get('c_q') || '', kind: urlState.get('c_kind') || reader.dataset.defaultKind || 'all', page: urlState.get('c_page') || 1, position: urlState.get('c_position'), section: urlState.get('c_section'), chunk: urlState.get('c_chunk') || 0}; let controller, latest; @@ -96,6 +111,102 @@ const indexHost = reader.querySelector('.reader-rows'); const pages = reader.querySelector('.reader-pages'); const change = patch => { state = {...state, ...patch}; loadConversation(); }; + // The view by model call: one row a call, then what it sent, its answer and the steps under it. + const clock = iso => { const at = new Date(iso); return Number.isNaN(at.getTime()) ? '' : at.toLocaleTimeString(); }; + const size = value => value >= 1048576 ? `${(value / 1048576).toFixed(1)} MB` : `${number(Math.max(1, Math.round(value / 1024)))} KB`; + const said = value => typeof value === 'string' ? value : JSON.stringify(value); + const part = (title, children) => { const box = el('div', 'call-part'); box.append(el('h4', '', title), ...children); return box; }; + const picture = p => { + if (!p.url) return el('span', 'call-picture-kept', [p.type, p.bytes ? size(p.bytes) : '', 'not kept'].filter(Boolean).join(' · ')); + const link = el('a', 'call-picture-link'); link.href = p.url; link.target = '_blank'; link.rel = 'noopener'; + const img = el('img', 'call-picture'); img.src = p.url; img.alt = `Picture ${p.sha256.slice(0, 12)}, ${p.type}`; + img.loading = 'lazy'; img.decoding = 'async'; link.title = `sha256 ${p.sha256}`; + // a click opens it over the page; a click with a key held still opens it in a tab of its own + link.addEventListener('click', event => { + if (event.button || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); viewPicture(p.url, img.alt); + }); + link.append(img); return link; + }; + const item = (entry, selected) => { + const node = button('', () => change({section: entry.key, chunk: 0}), false, 'call-item'); + node.setAttribute('aria-pressed', String(selected === entry.key)); + node.append(el('span', 'call-item-kind', entry.label), el('span', 'call-item-preview', entry.preview)); + if (entry.characters) node.append(el('span', 'call-item-size mono', number(entry.characters))); + return node; + }; + const step = entry => { + const node = button('', () => { searchInput.value = ''; change({kind: 'all', q: '', step: String(entry.step_id), position: null, page: 1, section: null, chunk: 0}); }, false, 'call-item'); + node.append(el('span', 'call-item-kind mono', `#${entry.step_id} ${entry.source || ''}`), el('span', 'call-item-preview', entry.preview)); + return node; + }; + const textWindow = content => { + const block = el('div', 'reader-content'), head = el('div', 'reader-content-head'); + head.append(el('h4', '', content.label), el('span', 'mono', `${number(content.characters)} characters`)); + block.append(head); + if (content.text) { const pre = el('pre', '', content.text); pre.tabIndex = 0; pre.setAttribute('aria-label', content.label); block.append(pre); } + else block.append(el('p', 'muted', 'No content recorded.')); + const nav = el('nav', 'reader-content-nav'); nav.setAttribute('aria-label', 'Content pages'); + nav.append(button('← Previous', () => change({section: content.key, chunk: content.chunk - 1}), content.chunk === 0), + el('span', '', `Part ${number(content.chunk + 1)} / ${number(content.chunks)} · ${number(content.start + (content.characters ? 1 : 0))}–${number(content.end)}`), + button('Next →', () => change({section: content.key, chunk: content.chunk + 1}), content.chunk + 1 >= content.chunks)); + block.append(nav); return block; + }; + const renderCalls = data => { + status.textContent = `${number(data.matches)} of ${number(data.total)} calls${data.query ? ` match “${data.query}”` : ''}. ${data.notice || 'Select a call to see what it sent and answered.'}`; + indexHost.replaceChildren(); + data.rows.forEach(row => { + const node = button('', () => change({position: row.position, section: null, chunk: 0}), false, 'reader-row'); + node.setAttribute('aria-current', String(row.position === data.selected?.position)); + const meta = el('span', 'reader-row-meta'); + meta.append(el('span', 'mono', row.label)); + if (row.time) meta.append(el('span', '', clock(row.time))); + if (row.tokens && row.tokens.input !== undefined) meta.append(el('span', '', `${number(row.tokens.input)} in · ${number(row.tokens.output || 0)} out`)); + if (row.pictures) meta.append(el('span', '', `${row.pictures} picture${row.pictures === 1 ? '' : 's'}`)); + if (row.unreadable || row.status !== 200) meta.append(el('span', 'reader-error', '!')); + node.append(meta, el('span', 'reader-row-preview', row.preview)); indexHost.append(node); + }); + pages.querySelector('span').textContent = `${data.page} / ${data.pages}`; + pages.querySelector('[data-page=previous]').disabled = data.page <= 1; + pages.querySelector('[data-page=next]').disabled = data.page >= data.pages; + selectedHost.replaceChildren(); + const chosen = data.selected; + if (!chosen) { selectedHost.append(el('p', 'muted', data.notice || 'No calls match.')); return; } + const header = el('div', 'reader-step-nav'), info = el('div'); + info.append(el('h3', '', [chosen.label, chosen.model, chosen.side ? 'side call' : ''].filter(Boolean).join(' · '))); + const facts = [`${chosen.match_number} of ${data.matches} calls`]; + if (chosen.time) facts.push(chosen.time); + if (chosen.seconds !== null) facts.push(`${chosen.seconds.toFixed(2)}s`); + const t = chosen.tokens || {}; + if (t.input !== undefined) facts.push(`input ${number(t.input)}${t.cached ? ` (cached ${number(t.cached)})` : ''} · output ${number(t.output || 0)}${t.reasoning ? ` (reasoning ${number(t.reasoning)})` : ''}`); + if (chosen.cost_usd !== null) facts.push(`$${chosen.cost_usd.toFixed(4)}${chosen.cost_from === 'estimate' ? ' estimated' : ''}`); + info.append(el('p', '', facts.join(' · '))); + const actions = el('div', 'reader-step-actions'); + actions.append(button('← Previous', () => change({position: chosen.previous, section: null, chunk: 0}), chosen.previous === null), button('Next →', () => change({position: chosen.next, section: null, chunk: 0}), chosen.next === null)); + header.append(info, actions); selectedHost.append(header); + const selected = chosen.content?.key, sent = [], answer = []; + if (!chosen.sent.recorded) sent.push(el('p', chosen.sent.unreadable ? 'small bad' : 'muted', chosen.sent.note)); + else { + if (!chosen.sent.items.length && !chosen.sent.folded) sent.push(el('p', 'muted', 'Nothing the call before did not send.')); + chosen.sent.items.forEach(entry => { + sent.push(item(entry, selected)); + if (entry.pictures.length) { const row = el('div', 'call-pictures'); entry.pictures.forEach(p => row.append(picture(p))); sent.push(row); } + }); + const folded = chosen.sent.folded; + if (folded) sent.push(item({key: folded.key, label: 'Rewritten or dropped', preview: [folded.rewritten ? `${folded.rewritten} rewritten` : '', folded.dropped ? `${folded.dropped} dropped` : ''].filter(Boolean).join(' · ')}, selected)); + } + selectedHost.append(part('Sent', sent)); + const a = chosen.answer; + const ended = [a.end ? `ended ${said(a.end)}` : '', a.served_by ? `served by ${a.served_by}` : '', a.abridged ? 'abridged in the call record' : ''].filter(Boolean); + if (ended.length) answer.push(el('p', 'call-facts', ended.join(' · '))); + if (a.error) answer.push(el('p', 'small bad', `Error in the reply · ${a.error.message || said(a.error)}`)); + a.items.forEach(entry => answer.push(item(entry, selected))); + if (!a.items.length) answer.push(el('p', 'muted', chosen.refused ? 'Refused: nothing was sent.' : 'No answer recorded.')); + selectedHost.append(part('Answer', answer)); + if (chosen.content) selectedHost.append(textWindow(chosen.content)); + if (chosen.before.length) selectedHost.append(part('Before the first call', chosen.before.map(step))); + if (chosen.steps.length) selectedHost.append(part('Steps under it', [...chosen.steps.map(step), ...(chosen.more_steps ? [el('p', 'muted small', `and ${number(chosen.more_steps)} more`)] : [])])); + }; loadConversation = async () => { conversationStarted = true; controller?.abort(); controller = new AbortController(); @@ -118,6 +229,8 @@ else current.searchParams.delete(`c_${key}`); }); history.replaceState(null, '', current); + reader.querySelectorAll('[data-kind]').forEach(node => node.setAttribute('aria-pressed', String(node.dataset.kind === data.kind))); + if (data.view === 'calls') { renderCalls(data); return; } status.textContent = `${number(data.matches)} of ${number(data.total)} source steps${data.query ? ` match “${data.query}”` : ''}. ${data.notice || 'Select a row to keep its message and tools together.'}`; reader.querySelectorAll('[data-kind]').forEach(node => node.setAttribute('aria-pressed', String(node.dataset.kind === data.kind))); indexHost.replaceChildren(); @@ -180,6 +293,12 @@ if (next !== undefined) { event.preventDefault(); tabs[next].focus(); openTab(tabs[next].dataset.tab); } }); }); + // a link of the Artifacts tab to another tab of this page opens it in place + document.getElementById('trial-artifacts')?.addEventListener('click', event => { + const link = event.target.closest('a[data-open-tab]'); + if (!link || !tabs.some(tab => tab.dataset.tab === link.dataset.openTab)) return; + event.preventDefault(); openTab(link.dataset.openTab); document.getElementById('tab-' + link.dataset.openTab)?.focus(); + }); openTab(location.hash.startsWith('#span=') ? 'trace' : new URL(location.href).searchParams.get('tab') || 'overview', false); let spanController; diff --git a/app/templates/traces/_conversation.html b/app/templates/traces/_conversation.html index cb3863a4..f2344a02 100644 --- a/app/templates/traces/_conversation.html +++ b/app/templates/traces/_conversation.html @@ -1,12 +1,12 @@
- {% if traj and not traj.error %} + {% if (traj and not traj.error) or n_calls %}
- {{ traj.n_steps }} steps + {% if n_calls %}{{ n_calls }} call{{ 's' if n_calls != 1 }}{% if traj and not traj.error %} · {% endif %}{% endif %}{% if traj and not traj.error %}{{ traj.n_steps }} steps{% endif %}
{% endif %} - {% if not traj or traj.error %} + {% if (not traj or traj.error) and not n_calls %}

{% if traj and traj.error %}Trajectory unreadable: {{ traj.error }}{% elif trial.agent_type == 'control' %}This control has no recorded conversation.{% else %}No trajectory recorded for this trial.{% endif %}

{% else %}
- + {% if n_calls %} + {% endif %} diff --git a/app/templates/traces/trial.html b/app/templates/traces/trial.html index 1158dab0..7326fe78 100644 --- a/app/templates/traces/trial.html +++ b/app/templates/traces/trial.html @@ -581,9 +581,12 @@

Waterfall

{% include 'traces/_conversation.html' %}
- {% if artifacts %} + {% if artifacts or pictures %}
+ {#- the pictures sent to the model, each kept once in the record of its calls, read on the Conversation tab #} + {% if pictures %} + {% endif %} {#- the benchmark's own records, after Nullius's, under one heading row #} {% set seen = namespace(declared=false) %} {% for artifact in artifacts %} diff --git a/app/tests/test_standard_exchanges.py b/app/tests/test_standard_exchanges.py new file mode 100644 index 00000000..d65a0938 --- /dev/null +++ b/app/tests/test_standard_exchanges.py @@ -0,0 +1,1096 @@ +"""The relay's store of each model exchange: the request as sent, by part, each +part and picture written once, and the reply as it arrived; what it keeps in +each mode and under its bound; that it never stands in a reply's way and never +holds the relay's key; and the request rebuilt to the bytes sent. The provider +is a fake endpoint on loopback; no key, no network.""" +from __future__ import annotations + +import base64 +import contextlib +import hashlib +import io +import json +import os +import shutil +import subprocess +import sys +import tempfile +import threading +import unittest +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from unittest import mock + +from nullius.runs import cli as runs_cli, parse +from nullius.standard import cli as standard_cli +from nullius.standard.backends import container +from nullius.standard.calls import exchanges, relay +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +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") +APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +KEY = "sk-relay-real-0123" # a stand-in in the redaction's key shape, shorter than a real key + + +def picture(i: int, size: int = 3000, kind: bytes = b"\x89PNG\r\n\x1a\n") -> bytes: + """A picture's bytes, made up: a header and ``size`` bytes of its own.""" + seed = hashlib.sha256(str(i).encode()).digest() + return kind + (seed * (size // len(seed) + 1))[:size] + + +def b64(raw: bytes) -> str: + return base64.b64encode(raw).decode() + + +def data_url(raw: bytes, kind: str = "image/png") -> str: + return f"data:{kind};base64,{b64(raw)}" + + +PNG, JPEG = picture(1), picture(2, kind=b"\xff\xd8\xff\xe0") +TOOL = {"type": "object", "properties": {"x": {"type": "integer"}}} +# each API shape with inline pictures in its own form: (path, request, the pictures it holds as (bytes, extension)) +SHAPES = { + "chat": ("/chat/completions", + {"model": "m", "max_tokens": 100, "messages": [ + {"role": "system", "content": "be brief"}, + {"role": "user", "content": [{"type": "text", "text": "look"}, + {"type": "image_url", "image_url": {"url": data_url(PNG)}}]}, + {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", + "function": {"name": "click", "arguments": "{\"x\": 1}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": [{"type": "image_url", "image_url": {"url": data_url(JPEG, "image/jpeg")}}]}], + "tools": [{"type": "function", "function": {"name": "click", "parameters": TOOL}}]}, + [(PNG, "png"), (JPEG, "jpg")]), + "messages": ("/messages", + {"model": "m", "max_tokens": 100, "system": "be brief", + "tools": [{"name": "click", "input_schema": TOOL}], + "messages": [ + {"role": "user", "content": [{"type": "text", "text": "look"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64(PNG)}}]}, + {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "click", "input": {"x": 1}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [ + {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": b64(JPEG)}}]}]}]}, + [(PNG, "png"), (JPEG, "jpg")]), + "responses": ("/responses", + {"model": "m", "instructions": "be brief", "tools": [{"type": "function", "name": "click", "parameters": TOOL}], + "input": [{"role": "user", "content": [{"type": "input_text", "text": "look"}, + {"type": "input_image", "image_url": data_url(PNG), "detail": "auto"}]}, + {"type": "function_call", "call_id": "c1", "name": "click", "arguments": "{\"x\": 1}"}, + {"type": "function_call_output", "call_id": "c1", "output": "clicked"}, + {"role": "user", "content": [{"type": "input_image", "image_url": data_url(JPEG, "image/jpeg")}]}]}, + [(PNG, "png"), (JPEG, "jpg")]), +} + +# the replies, each with a reasoning text, streamed and not +CHAT = {"choices": [{"message": {"role": "assistant", "content": "ok", "reasoning": "I looked"}}], + "usage": {"prompt_tokens": 10, "completion_tokens": 2}} +CHAT_SSE = (b'data: {"choices":[{"delta":{"reasoning":"I "}}]}\n\n' + b'data: {"choices":[{"delta":{"reasoning":"looked"}}]}\n\n' + b'data: {"choices":[{"delta":{"content":"ok"}}]}\n\n' + b'data: {"choices":[],"usage":{"prompt_tokens":7,"completion_tokens":2}}\n\n' + b'data: [DONE]\n\n') +MESSAGE = {"type": "message", "role": "assistant", "stop_reason": "end_turn", + "content": [{"type": "thinking", "thinking": "I looked", "signature": "s"}, {"type": "text", "text": "ok"}], + "usage": {"input_tokens": 5, "output_tokens": 2}} +MESSAGE_SSE = (b'event: message_start\ndata: {"type":"message_start","message":{"usage":{"input_tokens":5,"output_tokens":1}}}\n\n' + b'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}\n\n' + b'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"I looked"}}\n\n' + b'event: content_block_start\ndata: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}\n\n' + b'event: content_block_delta\ndata: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"ok"}}\n\n' + b'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}\n\n' + b'event: message_stop\ndata: {"type":"message_stop"}\n\n') +RESPONSE = {"object": "response", "status": "completed", + "output": [{"type": "reasoning", "summary": [{"type": "summary_text", "text": "I looked"}]}, + {"type": "message", "content": [{"type": "output_text", "text": "ok"}]}], + "usage": {"input_tokens": 9, "output_tokens": 2}} +RESPONSE_SSE = (b'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"ok"}\n\n' + b'event: response.completed\ndata: ' + json.dumps({"type": "response.completed", "response": RESPONSE}).encode() + b'\n\n') + + +class Upstream(BaseHTTPRequestHandler): + """A model: each body as it arrived is kept, and every reply holds a reasoning text.""" + seen = [] # (path, headers, the body's bytes) + refuse = 0 # how many calls, from now, get a rate limit + + def log_message(self, *a): + pass + + def do_GET(self): # no list of models, as a provider without one + self.reply(404, b"", "application/json") + + def do_POST(self): + raw = self.rfile.read(int(self.headers["Content-Length"])) + Upstream.seen.append((self.path, dict(self.headers), raw)) + try: + body = json.loads(raw) + except ValueError: + return self.reply(400, b'{"error":{"message":"not JSON"}}', "application/json") + if Upstream.refuse > 0: + Upstream.refuse -= 1 + return self.reply(429, b'{"error":{"message":"Rate limit reached for requests"}}', "application/json") + stream = body.get("stream") + if self.path.endswith("/messages"): + return self.reply(200, MESSAGE_SSE, "text/event-stream") if stream else self.reply(200, json.dumps(MESSAGE).encode(), "application/json") + if self.path.endswith("/responses"): + return self.reply(200, RESPONSE_SSE, "text/event-stream") if stream else self.reply(200, json.dumps(RESPONSE).encode(), "application/json") + if stream: + return self.reply(200, CHAT_SSE, "text/event-stream") + said = body["messages"][-1]["content"] if isinstance(body.get("messages"), list) and body["messages"] else "" + got = dict(CHAT, choices=[{"message": dict(CHAT["choices"][0]["message"], + content="you said: " + (said if isinstance(said, str) else "pictures"))}]) + return self.reply(200, json.dumps(got).encode(), "application/json") + + def reply(self, status, body, kind): + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class WithUpstream(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.up = ThreadingHTTPServer(("127.0.0.1", 0), Upstream) + threading.Thread(target=cls.up.serve_forever, daemon=True).start() + cls.base = f"http://127.0.0.1:{cls.up.server_address[1]}/v1" + + @classmethod + def tearDownClass(cls): + cls.up.shutdown() + cls.up.server_close() + + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + Upstream.refuse = 0 + + def relay(self, mode="whole", **kw): + r = relay.Relay(self.base, KEY, os.path.join(self.tmp, f"rec-{len(os.listdir(self.tmp))}"), exchanges=mode, **kw).start() + self.addCleanup(r.stop) + return r + + def post(self, r, tag, path, body, headers=None, raw=None): + req = urllib.request.Request(r.url(tag) + path, data=raw if raw is not None else json.dumps(body).encode(), + headers={"Content-Type": "application/json", "Authorization": "Bearer " + relay.PLACEHOLDER_KEY, + **(headers or {})}) + try: + with urllib.request.urlopen(req) as got: + return got.status, got.read() + except urllib.error.HTTPError as e: + return e.code, e.read() + + @staticmethod + def store(r): + return os.path.join(r.dir, exchanges.FOLDER) + + @staticmethod + def files(folder): + out = {} + for root, _, names in os.walk(folder): + for n in names: + with open(os.path.join(root, n), "rb") as f: + out[os.path.relpath(os.path.join(root, n), folder)] = f.read() + return out + + +class StoreFiles(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def store(self, mode="whole"): + return exchanges.Store(tempfile.mkdtemp(dir=self.root), mode=mode, keys=(KEY,)) + + def keep(self, store, req, n=1, headers=None): + store.write("u0001", n, 1.0, "/messages", req, json.dumps(req).encode(), headers or {}, 200, False, b"{}") + + def test_only_real_keys_are_cut_from_nested_values_and_names(self): + _, placeholder = run.provider_endpoint("custom", {"MODEL_API_URL": "http://localhost:8000/v1"}) + value = {"localhost": ["local-model", {KEY: "localhost " + KEY}]} + expected = {"localhost": ["local-model", {"[REDACTED]": "localhost [REDACTED]"}]} + for clean in (exchanges._cut_key, relay._clean): + with self.subTest(clean=clean.__name__): + self.assertEqual(clean(value, ("", placeholder, KEY)), expected) + + def test_a_keyless_relay_keeps_localhost_in_records_and_messages(self): + base, key = run.provider_endpoint("custom", {"MODEL_API_URL": "http://localhost:8000/v1"}) + req = {"model": "local-model", "messages": [{"role": "user", "content": "localhost"}], + "provider": {"order": ["local-asked"]}} + body = json.dumps(dict(CHAT, provider="localhost", error={"message": "localhost unavailable"})).encode() + for mode in exchanges.MODES: + with self.subTest(mode=mode): + r = relay.Relay(base, key, str(self.root / mode), exchanges=mode, serving={"local-model": ["localhost"]}) + self.addCleanup(r.stop) + response = mock.Mock(status=200, headers={"Content-Type": "application/json"}) + response.getheader.return_value = "application/json" + response.read.return_value = body + raw = json.dumps(req).encode() + h = mock.Mock(path="/u0001/v1/chat/completions", command="POST", + headers={"Content-Length": str(len(raw))}, rfile=io.BytesIO(raw), wfile=io.BytesIO()) + with mock.patch.object(r.pool, "send", return_value=(mock.Mock(), response)), mock.patch.object(r.pool, "give"): + r._forward(h) + self.assertEqual(h.wfile.getvalue(), body) + call, = r.calls("u0001") + self.assertEqual(call["request"]["routing"], relay.routing(["localhost"])) + self.assertEqual(call["request"]["routing_asked"], req["provider"]) + self.assertEqual(call["reply"]["served_by"], "localhost") + self.assertEqual(call["reply"]["error"]["message"], "localhost unavailable") + self.assertEqual(r._said(OSError("localhost unavailable")), "OSError: localhost unavailable") + for p in Path(r.dir).rglob("*"): + if p.is_file(): + self.assertNotIn(b"[REDACTED]", p.read_bytes()) + + def test_empty_and_placeholder_keys_leave_exchanges_unchanged(self): + env = {"MODEL_API_URL": "http://localhost:8000/v1"} + _, placeholder = run.provider_endpoint("custom", env) + req = {"model": "local-model", "messages": [{"role": "user", "content": "localhost"}]} + raw = json.dumps(req).encode() + headers = {"X-local": "localhost"} + body = b'{"text":"localhost local-model"}' + for key in ("", placeholder): + for mode in ("whole", "text"): + with self.subTest(key=key, mode=mode): + job = self.root / f"{mode}-{key or 'empty'}" + store = exchanges.Store(str(job / "task__u0001" / ".work" / "relay"), mode=mode, keys=(key,)) + for n, request in enumerate((req, None), 1): + store.write("u0001", n, 1.0, "/chat/completions", request, raw, headers, 200, False, body) + line = exchanges.lines(store.dir, "u0001")[-1] + self.assertNotIn("key_cut", line) + self.assertEqual(line["headers"], headers) + self.assertEqual(line["reply"]["body"], body.decode()) + self.assertEqual(exchanges.rebuild(store.dir, line), raw) + self.assertTrue(exchanges.check(store.dir, "u0001", n)["same"]) + + def test_a_damaged_part_leaves_other_calls_rebuildable(self): + for damage in ("truncated", "digest", "picture", "missing"): + with self.subTest(damage=damage): + trial = mock.Mock(dir=str(self.root / damage / "task__u0001"), trial_name="task__u0001") + store = exchanges.Store(os.path.join(trial.dir, ".work", "relay")) + bad, good = {"messages": [data_url(PNG)]}, {"messages": ["still readable"]} + for n, req in enumerate((bad, good, bad), 1): + self.keep(store, req, n=n) + path = Path(store.dir) / exchanges.PARTS + rows = path.read_text().splitlines() + first = next(i for i, r in enumerate(rows) if '"part"' in r) # the first part, after the mark + row = json.loads(rows[first]) + if damage == "digest": + row["sha256"] = "invalid" + elif damage == "picture": + row["part"]["blob"] = "../outside" + elif damage == "missing": + del row["part"] + rows[first] = rows[first][:40] if damage == "truncated" else json.dumps(row) + path.write_text("\n".join(rows) + "\n") + for n in (1, 2, 3): + out, err = io.TextIOWrapper(io.BytesIO(), encoding="utf-8"), io.StringIO() + self.addCleanup(out.close) + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = runs_cli._request(trial, n) + out.flush() + result = exchanges.check(store.dir, "u0001", n) + self.assertEqual(result["same"], n == 2) + if n == 2: + self.assertEqual((code, out.buffer.getvalue()), (0, json.dumps(good).encode() + b"\n")) + self.assertIn("the recorded sent_sha256", err.getvalue()) + line = exchanges.lines(store.dir, "u0001")[1] + self.assertEqual(exchanges.rebuild(store.dir, line, exchanges.stored_parts(store.dir)), + json.dumps(good).encode()) + else: + self.assertEqual((code, out.buffer.getvalue()), (runs_cli.EXIT_FAILED, b"")) + self.assertIsNone(result["request"]) + + def assert_picture_rejected(self, store, line, parts): + self.assertEqual(exchanges.stored_parts(store.dir), {}) + for read in (lambda: exchanges.rebuild(store.dir, line), + lambda: exchanges.rebuild(store.dir, line, parts)): + with self.assertRaises(exchanges.Missing): + read() + result = exchanges.check(store.dir, "u0001", 1) + self.assertFalse(result["same"]) + self.assertIsNone(result["request"]) + + def test_picture_names_are_only_sha256_digests_in_every_part_reader(self): + outside = self.root / "outside.png" + outside.write_bytes(b"outside picture") + for name in (str(outside.with_suffix("")), "../../outside", "a" * 63, "a" * 65, + "g" * 64, "a" * 64 + "\n", "a" * 64 + ".png", None): + with self.subTest(name=name): + store = self.store() + self.keep(store, {"messages": [data_url(PNG)]}) + line, = exchanges.lines(store.dir, "u0001") + parts = exchanges.stored_parts(store.dir) + part, = parts.values() + part["part"]["blob"] = name + (Path(store.dir) / exchanges.PARTS).write_text("".join( + json.dumps(dict(sha256=h, **p)) + "\n" for h, p in parts.items())) + self.assert_picture_rejected(store, line, parts) + + def test_picture_links_must_resolve_inside_the_stores_own_blobs_folder(self): + outside = self.root / "outside.png" + outside.write_bytes(b"outside picture") + for linked in ("file", "directory"): + with self.subTest(linked=linked): + store = self.store() + req = {"messages": [data_url(PNG)]} + self.keep(store, req) + line, = exchanges.lines(store.dir, "u0001") + parts = exchanges.stored_parts(store.dir) + blobs = Path(store.dir) / exchanges.BLOBS + blob, = blobs.iterdir() + if linked == "file": + blob.unlink() + blob.symlink_to(outside) + else: + moved = self.root / "moved" + blobs.rename(moved) + blobs.symlink_to(moved, target_is_directory=True) + self.assert_picture_rejected(store, line, parts) + + store = self.store() + self.keep(store, req) + blobs = Path(store.dir) / exchanges.BLOBS + blob, = blobs.iterdir() + kept = blobs / ("0" * 64 + ".png") + blob.rename(kept) + blob.symlink_to(kept) + self.assertTrue(exchanges.check(store.dir, "u0001", 1)["same"]) + + def test_part_and_call_files_cannot_be_read_through_outside_links(self): + for name, read in ((exchanges.PARTS, exchanges.stored_parts), + ("u0001.jsonl", lambda folder: exchanges.lines(folder, "u0001"))): + with self.subTest(name=name): + store = self.store() + self.keep(store, {"messages": ["hello"]}) + path = Path(store.dir) / name + outside = self.root / name + path.rename(outside) + path.symlink_to(outside) + with self.assertRaises(exchanges.Missing): + read(store.dir) + + def test_header_names_and_values_both_cut_out_the_relay_key(self): + store = self.store() + self.keep(store, {"messages": ["hello"]}, headers={"X-Trace-" + KEY: "trace", "X-Value": KEY}) + for path in Path(store.dir).rglob("*"): + if path.is_file(): + self.assertNotIn(KEY.encode(), path.read_bytes()) + line, = exchanges.lines(store.dir, "u0001") + self.assertEqual(line["headers"], {"X-Trace-[REDACTED]": "trace", "X-Value": "[REDACTED]"}) + self.assertTrue(exchanges.check(store.dir, "u0001", 1)["same"]) + + @contextlib.contextmanager + def failed_write(self, target, failure): + original = open + failed = False + + @contextlib.contextmanager + def opened(path, mode="r", *args, **kwargs): + nonlocal failed + with original(path, mode, *args, **kwargs) as file: + if Path(path) != target or mode not in ("a", "wb") or failed: + yield file + return + failed = True + + def write(data): + count = file.write(data[:20]) + file.flush() + if failure == "write": + raise OSError(28, "No space left on device") + return count + + proxy = mock.Mock(wraps=file) + if failure != "close": + proxy.write.side_effect = write + yield proxy + if failure == "close": + raise OSError(28, "No space left on device") + + with mock.patch("builtins.open", side_effect=opened): + yield + self.assertTrue(failed) + + def test_failed_appends_restore_the_earlier_length_and_retry_whole_parts(self): + for name in (exchanges.PARTS, "u0001.jsonl"): + for failure in ("write", "short", "close"): + with self.subTest(name=name, failure=failure): + store = self.store() + self.keep(store, {"messages": ["earlier"]}) + path = Path(store.dir) / name + before = path.read_bytes() + req = {"messages": ["a later part"]} + with self.failed_write(path, failure): + with self.assertRaises(OSError): + store._append(name, '{"unfinished":"a long value"}\n') + self.assertEqual(path.read_bytes(), before) + if name == exchanges.PARTS: + prior_parts = set(store.parts) + with self.failed_write(path, failure): + self.keep(store, req, 2) + self.assertEqual(path.read_bytes(), before) + self.assertEqual(store.parts, prior_parts) + else: + with self.failed_write(path, failure): + self.keep(store, req, 2) + self.assertEqual(path.read_bytes()[:len(before)], before) + rows = exchanges.lines(store.dir, "u0001") + self.assertEqual([row["n"] for row in rows], [1, 2]) + self.assertIn("error", rows[1]) + for n in (3, 4): + self.keep(store, req, n) + self.assertTrue(exchanges.check(store.dir, "u0001", n)["same"]) + self.assertEqual(store.size, sum(p.stat().st_size for p in Path(store.dir).rglob("*") if p.is_file())) + + def test_incomplete_pictures_are_not_marked_stored_and_are_written_again(self): + for failure in ("write", "short", "close"): + with self.subTest(failure=failure): + store = self.store() + req = {"messages": [data_url(PNG)]} + blob = Path(store.dir) / exchanges.BLOBS / (hashlib.sha256(PNG).hexdigest() + ".png") + with self.failed_write(Path(str(blob) + ".part"), failure): + self.keep(store, req) + self.assertFalse(blob.exists()) + self.assertEqual((store.parts, store.blobs), (set(), set())) + line, = exchanges.lines(store.dir, "u0001") + self.assertIn("error", line) + self.keep(store, req, 2) + self.assertEqual(blob.read_bytes(), PNG) + self.assertTrue(exchanges.check(store.dir, "u0001", 2)["same"]) + + def test_literal_picture_marks_do_not_disable_picture_extraction(self): + literal = {"blob": "x", "type": "x", "bytes": 1, "as": "base64"} + tool = {"type": "object", "properties": { + "payload": {"default": literal}, "reference": {"default": data_url(PNG)}, + "nested": {"default": {"literal": {"literal": literal}}}}} + req = {"tools": [tool]} + for mode in ("whole", "text"): + with self.subTest(mode=mode): + store = self.store(mode) + self.keep(store, req) + self.assertNotIn(b64(PNG), (Path(store.dir) / exchanges.PARTS).read_text()) + result = exchanges.check(store.dir, "u0001", 1) + if mode == "whole": + self.assertEqual(result["request"], json.dumps(req).encode()) + self.assertTrue(result["same"]) + else: + self.assertFalse((Path(store.dir) / exchanges.BLOBS).exists()) + self.assertIsNone(result["request"]) + plain = {"tools": [literal, {"literal": literal}]} + self.keep(store, plain, 2) + self.assertEqual(exchanges.check(store.dir, "u0001", 2)["request"], json.dumps(plain).encode()) + + def test_text_omits_noncanonical_picture_encodings(self): + encoded = b64(PNG) + wrapped = "\n".join(encoded[i:i + 76] for i in range(0, len(encoded), 76)) + for kind, data in (("image/png", wrapped), ("image/png", encoded.rstrip("=")), + ("image/bmp", wrapped), ("image/png", "QR==")): + for form in ("data_url", "base64"): + with self.subTest(kind=kind, data=data[:10], form=form): + value = (f"data:{kind};base64,{data}" if form == "data_url" else + {"type": "base64", "media_type": kind, "data": data}) + store = self.store("text") + self.keep(store, {"messages": [value]}) + self.assertFalse((Path(store.dir) / exchanges.BLOBS).exists()) + for path in Path(store.dir).rglob("*"): + if path.is_file(): + self.assertNotIn(json.dumps(data)[1:-1].encode(), path.read_bytes()) + part, = exchanges.stored_parts(store.dir).values() + mark = part["part"] if form == "data_url" else part["part"]["data"] + raw = b"A" if data == "QR==" else PNG + self.assertEqual(mark, {"blob": hashlib.sha256(raw).hexdigest(), "type": kind, + "bytes": len(raw), "as": form}) + self.assertFalse(exchanges.check(store.dir, "u0001", 1)["same"]) + + def test_text_omits_pictures_from_the_call_line_too(self): + value = {"type": "base64", "media_type": "image/png", "data": b64(PNG)} + for streamed in (False, True): + for req in ({"metadata": data_url(PNG), "messages": value}, None): + with self.subTest(streamed=streamed, raw=req is None): + store = self.store("text") + reply = json.dumps({"image": value}) + body = ("data: " + reply + "\n\ndata: [DONE]\n\n" if streamed else reply).encode() + raw = json.dumps(req if req is not None else [value]).encode() + store.write("u0001", 1, 1.0, "/messages", req, raw, + {"X-Image": data_url(PNG)}, 200, streamed, body) + for path in Path(store.dir).rglob("*"): + if path.is_file(): + self.assertNotIn(b64(PNG).encode(), path.read_bytes()) + self.assertFalse((Path(store.dir) / exchanges.BLOBS).exists()) + + +class ByteForByte(WithUpstream): + def test_each_shape_rebuilds_to_the_bytes_sent_streamed_or_not_and_a_changed_part_fails(self): + for shape, (path, ask, pictures) in SHAPES.items(): + for stream in (False, True): + with self.subTest(shape=shape, stream=stream): + r = self.relay() + status, reply = self.post(r, "u0001", path, dict(ask, **({"stream": True} if stream else {}))) + self.assertEqual(status, 200) + sent = Upstream.seen[-1][2] + store = self.store(r) + (line,) = exchanges.lines(store, "u0001") + self.assertEqual((line["n"], r.calls("u0001")[-1]["n"]), (1, 1)) # the record and the line, one number + self.assertEqual(line["sent_sha256"], hashlib.sha256(sent).hexdigest()) + self.assertEqual(exchanges.rebuild(store, line), sent) + self.assertTrue(exchanges.check(store, "u0001", 1)["same"]) + # each picture a file of its own, its bytes as sent; no part holds its text + self.assertEqual(sorted(n for n in os.listdir(os.path.join(store, exchanges.BLOBS))), + sorted(f"{hashlib.sha256(p).hexdigest()}.{ext}" for p, ext in pictures)) + for p, ext in pictures: + with open(os.path.join(store, exchanges.BLOBS, f"{hashlib.sha256(p).hexdigest()}.{ext}"), "rb") as f: + self.assertEqual(f.read(), p) + texts = self.files(store) + self.assertFalse(any(b64(p).encode() in texts[n] for p, _ in pictures for n in texts if not n.startswith(exchanges.BLOBS))) + # the reply as it arrived, its reasoning read back + self.assertEqual((line["reply"]["status"], line["reply"]["streamed"], line["reply"]["body"].encode()), (200, stream, reply)) + self.assertEqual(relay.read_reply(path, line["reply"]["body"].encode(), stream, reasoning=True)["reasoning"], "I looked") + # a changed part: its bytes no longer the ones sent + parts = os.path.join(store, exchanges.PARTS) + with open(parts) as f: + text = f.read() + with open(parts, "w") as f: + f.write(text.replace('"look"', '"LOOK"')) + got = exchanges.check(store, "u0001", 1) + self.assertFalse(got["same"]) + self.assertIn("do not rebuild", got["why"]) + + def test_a_picture_whose_text_is_not_its_bytes_own_encoding_stays_in_its_part(self): + """Noncanonical pictures and literal marks rebuild as sent. Canonical pictures are files.""" + odd = ["data:image/png;base64,QR==", "data:image/png;base64,QQ", "data:image/png;base64,QQ==\n", "data:image/bmp;base64,QQ=="] + ask = {"model": "m", "messages": [ + {"role": "user", "content": [{"type": "image_url", "image_url": {"url": u}} for u in odd + ["data:image/png;base64,QQ=="]]}, + {"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "QR=="}}]}, + {"role": "user", "content": [{"blob": "x", "type": "t", "bytes": 1, "as": "data_url"}, + {"type": "image_url", "image_url": {"url": "data:image/png;base64,QUI="}}]}]} + r = self.relay() + self.assertEqual(self.post(r, "u0001", "/chat/completions", ask)[0], 200) + store = self.store(r) + (line,) = exchanges.lines(store, "u0001") + self.assertEqual(exchanges.rebuild(store, line), Upstream.seen[-1][2]) + self.assertEqual(sorted(os.listdir(os.path.join(store, exchanges.BLOBS))), + sorted(hashlib.sha256(raw).hexdigest() + ".png" for raw in (b"A", b"AB"))) + self.assertEqual(sum('"as_sent":true' in x for x in open(os.path.join(store, exchanges.PARTS))), 0) + + def test_the_relays_changes_are_what_is_kept(self): + """``sent`` is the request after the relay's changes: the model it forces, a stream's usage option.""" + r = self.relay(model="m-run") + self.post(r, "u0001", "/chat/completions", dict(SHAPES["chat"][1], model="asked", stream=True)) + (line,) = exchanges.lines(self.store(r), "u0001") + self.assertEqual((line["sent"]["model"], line["sent"]["stream_options"]), ("m-run", {"include_usage": True})) + self.assertEqual(exchanges.rebuild(self.store(r), line), Upstream.seen[-1][2]) + + +class StoredOnce(WithUpstream): + def test_a_unit_that_resends_its_context_writes_each_part_and_picture_once(self): + r = self.relay() + history = [{"role": "system", "content": "be brief"}] + sizes = 0 + for i in range(4): + history.append({"role": "user", "content": [{"type": "text", "text": f"step {i}"}, + {"type": "image_url", "image_url": {"url": data_url(picture(10 + i, 20_000))}}]}) + body = {"model": "m", "messages": history, "tools": [{"type": "function", "function": {"name": "click", "parameters": TOOL}}]} + self.assertEqual(self.post(r, "u0003", "/chat/completions", body)[0], 200) + sizes += len(Upstream.seen[-1][2]) + history.append({"role": "assistant", "content": f"did {i}"}) + store = self.store(r) + with open(os.path.join(store, exchanges.PARTS)) as f: + parts = exchanges.unmarked([json.loads(x) for x in f], exchanges.PARTS) + hashes = [p["sha256"] for p in parts] + self.assertEqual(len(hashes), len(set(hashes))) + self.assertEqual(len(hashes), 1 + 4 + 3 + 1) # the system text, four asks, three answers, the tool + self.assertEqual(len(os.listdir(os.path.join(store, exchanges.BLOBS))), 4) + lines = exchanges.lines(store, "u0003") + self.assertEqual([x["n"] for x in lines], [1, 2, 3, 4]) + for x in lines: # a call's line lists hashes alone + self.assertEqual(set(x["sent"]["messages"]), {"parts"}) + self.assertTrue(all(len(h) == 64 and h in hashes for h in x["sent"]["messages"]["parts"])) + self.assertTrue(exchanges.check(store, "u0003", x["n"])["same"]) + self.assertEqual(len(exchanges.new_parts(lines[1], lines[0])), 2) # the answer before it, and the new ask + self.assertEqual(exchanges.new_parts(lines[0]), lines[0]["sent"]["messages"]["parts"] + lines[0]["sent"]["tools"]["parts"]) + kept = sum(len(v) for v in self.files(store).values()) + self.assertLess(kept, sizes / 2) + + +class TextOnly(WithUpstream): + def test_text_keeps_each_pictures_hash_type_and_size_and_none_of_its_bytes(self): + r = self.relay("text") + path, ask, pictures = SHAPES["messages"] + self.assertEqual(self.post(r, "u0001", path, ask)[0], 200) + store = self.store(r) + self.assertFalse(os.path.exists(os.path.join(store, exchanges.BLOBS))) + texts = self.files(store) + for p, _ in pictures: + self.assertFalse(any(b64(p).encode() in t for t in texts.values())) + self.assertIn(json.dumps({"blob": hashlib.sha256(p).hexdigest(), "type": "image/png" if p is PNG else "image/jpeg", + "bytes": len(p), "as": "base64"}, separators=(",", ":")).encode(), texts[exchanges.PARTS]) + got = exchanges.check(store, "u0001", 1) + self.assertFalse(got["same"]) + self.assertIn("kept as text holds no pictures", got["why"]) + + +class Bound(WithUpstream): + def test_past_its_bound_a_units_lines_say_cut_and_its_calls_go_on_unchanged(self): + r = self.relay(exchanges_max_mb=1) + replies = [] + for i in range(5): + content = [{"type": "image_url", "image_url": {"url": data_url(picture(100 + i, 300_000))}}] if i < 4 else "a last word" + status, reply = self.post(r, "u0002", "/chat/completions", {"model": "m", "messages": [{"role": "user", "content": content}]}) + replies.append((status, json.loads(reply)["choices"][0]["message"]["content"])) + self.assertEqual(replies, [(200, "you said: pictures")] * 4 + [(200, "you said: a last word")]) + lines = exchanges.lines(self.store(r), "u0002") + self.assertEqual([x["n"] for x in lines], [1, 2, 3, 4, 5]) + self.assertEqual([bool(x.get("cut")) for x in lines], [False, False, False, True, True]) # the small last one too + self.assertIn("bound of 1 MB", lines[3]["cut"]) + self.assertEqual([(c["n"], c["status"]) for c in r.calls("u0002")], [(n, 200) for n in range(1, 6)]) + self.assertLessEqual(sum(len(v) for v in self.files(self.store(r)).values()), 10 ** 6 + 2000) + self.assertIn("not kept", exchanges.check(self.store(r), "u0002", 4)["why"]) + + +class Off(WithUpstream): + def test_off_keeps_no_store_and_the_call_record_of_before(self): + ask = SHAPES["chat"][1] + off, whole, default = self.relay("off"), self.relay("whole"), relay.Relay(self.base, KEY, os.path.join(self.tmp, "default")).start() + self.addCleanup(default.stop) + for r in (off, whole, default): + self.assertEqual(self.post(r, "u0001", "/chat/completions", ask)[0], 200) + self.assertFalse(os.path.exists(self.store(off))) + self.assertFalse(os.path.exists(self.store(default))) # the relay's own default: off + normalized = lambda c: {k: 0.0 if k in ("t0", "t1") else v for k, v in c.items()} + (a,), (b,), (c,) = off.calls("u0001"), whole.calls("u0001"), default.calls("u0001") + # every record holds the request's digest; keeping the exchange or not leaves it as it is + digests = {x["request"].pop("sha256") for x in (a, b, c)} + self.assertEqual(len(digests), 1) + expected = { + "t0": 0.0, "t1": 0.0, "path": "/chat/completions", "model": "m", "model_asked": "m", "status": 200, + "request": {"n_messages": 4, "last": [{"role": "assistant", "content": ""}, {"role": "tool", "content": ""}], + "stream": False, "reasoning_effort": None}, + "headers": ["content-type", "user-agent"], + "reply": {"text": "you said: pictures", "tool_calls": [], + "usage": {"input": 10, "output": 2, "cached": 0, "reasoning": 0}}, + } + self.assertEqual(normalized(a), expected) + self.assertEqual(normalized(c), expected) + self.assertEqual(normalized(b), dict(expected, n=1)) + + def test_the_judges_and_the_simulated_users_routes_keep_the_record_alone(self): + r = self.relay() + for tag in ("u0001-judge", "u0001-simulator"): + self.assertEqual(self.post(r, tag, "/chat/completions", SHAPES["chat"][1])[0], 200) + self.assertNotIn("n", r.calls(tag)[-1]) + self.assertEqual(exchanges.tags(self.store(r)), []) + + +class NeverInTheWay(WithUpstream): + def test_a_full_disk_neither_changes_nor_stops_the_reply_and_the_line_says_what_failed(self): + path, ask, _ = SHAPES["chat"] + clean = self.relay("off") + expected = self.post(clean, "u0001", path, ask) + r = self.relay() + full = OSError(28, "No space left on device") + with mock.patch.object(exchanges.Store, "_put", side_effect=full): + self.assertEqual(self.post(r, "u0001", path, ask), expected) + (line,) = exchanges.lines(self.store(r), "u0001") + self.assertIn("No space left on device", line["error"]) + with mock.patch.object(exchanges.Store, "_put", side_effect=full), mock.patch.object(exchanges.Store, "_append", side_effect=full): + self.assertEqual(self.post(r, "u0001", path, ask), expected) # nothing of the store written: the reply still whole + self.assertEqual([c["n"] for c in r.calls("u0001")], [1, 2]) # and the call record goes on + self.assertEqual(len(exchanges.lines(self.store(r), "u0001")), 1) + self.assertEqual(self.post(r, "u0001", path, ask), expected) # room again: the next call is kept whole + self.assertTrue(exchanges.check(self.store(r), "u0001", 3)["same"]) + + def test_a_part_that_cannot_be_split_and_a_body_that_is_not_json_are_said_in_the_line(self): + r = self.relay() + path, ask, _ = SHAPES["chat"] + with mock.patch.object(exchanges, "split", side_effect=TypeError("a part that is not JSON")): + status, reply = self.post(r, "u0001", path, ask) + self.assertEqual((status, json.loads(reply)["choices"][0]["message"]["content"]), (200, "you said: pictures")) + status, reply = self.post(r, "u0001", path, None, raw=b"not json at all") + self.assertEqual((status, reply), (400, b'{"error":{"message":"not JSON"}}')) + first, second = exchanges.lines(self.store(r), "u0001") + self.assertEqual(first["error"], "TypeError: a part that is not JSON") + self.assertIn("not a JSON object", second["error"]) + self.assertEqual(second["sent_body"], "not json at all") + self.assertTrue(exchanges.check(self.store(r), "u0001", 2)["same"]) # kept whole, it still rebuilds + + +class NoKey(WithUpstream): + def test_a_keyless_custom_endpoint_keeps_a_call_that_can_be_replayed(self): + env = {"MODEL_API_URL": self.base} + base, key = run.provider_endpoint("custom", env) + job = Path(self.tmp) / "job" + r = relay.Relay(base, key, str(job / "task__u0001" / ".work" / "relay"), exchanges="whole").start() + self.addCleanup(r.stop) + req = {"model": "local-model", "max_tokens": 100, "messages": [{"role": "user", "content": "localhost"}]} + status, body = self.post(r, "u0001", "/chat/completions", req, headers={"X-Trace-Id": "localhost"}) + self.assertEqual(status, 200) + raw = Upstream.seen[-1][2] + line, = exchanges.lines(self.store(r), "u0001") + self.assertNotIn("key_cut", line) + self.assertEqual(line["reply"]["body"], body.decode()) + self.assertEqual(exchanges.rebuild(self.store(r), line), raw) + + def test_the_relays_key_is_in_no_file_of_the_store(self): + r = self.relay() + ask = dict(SHAPES["messages"][1], system=f"the key is {KEY}, keep it", + tools=[{"name": "click", "description": f"say {KEY}", "input_schema": TOOL}]) + status, _ = self.post(r, "u0001", "/messages?k=" + KEY, ask, headers={"X-Trace-Id": KEY, "Authorization": "Bearer " + KEY}) + self.assertEqual(status, 200) + self.assertIn(KEY.encode(), Upstream.seen[-1][2]) # the agent sent it, and the relay sent it on + for name, data in self.files(self.store(r)).items(): + self.assertNotIn(KEY.encode(), data, name) + (line,) = exchanges.lines(self.store(r), "u0001") + self.assertTrue(line["key_cut"]) + self.assertEqual({k.lower(): v for k, v in line["headers"].items()}["x-trace-id"], "[REDACTED]") + self.assertFalse(any(k.lower() in ("authorization", "x-api-key") for k in line["headers"])) + got = exchanges.check(self.store(r), "u0001", 1) + self.assertFalse(got["same"]) + self.assertIn("key was cut out", got["why"]) + + +class TheSidecar(WithUpstream): + def test_the_sidecars_arguments_hold_both_values(self): + argv = container.relay_argv("img", name="r", job="j", app="/app", record="/rec", key_file="/k", base="b", model="m", routes={}, + exchanges="text", exchanges_max_mb=64) + self.assertEqual(argv[argv.index("--exchanges") + 1:argv.index("--exchanges") + 4], ["text", "--exchanges-max-mb", "64"]) + unit = container.Unit("job", "u0", os.path.join(self.tmp, "rec"), image="img", app="/app", base="b", key="k", model="m", + exchanges="whole", exchanges_max_mb=32) + ran = [] + + def docker(args, **kw): + ran.append(args) + if args[:1] == ["run"]: + raise container.Unavailable("no engine in this test") + return subprocess.CompletedProcess(args, 0, "", "") + with mock.patch.object(container, "_docker", docker), self.assertRaises(container.Unavailable): + unit.start() + (started,) = [a for a in ran if a[:1] == ["run"]] + self.assertEqual(started[started.index("--exchanges") + 1:started.index("--exchanges") + 4], ["whole", "--exchanges-max-mb", "32"]) + + def test_a_relay_container_beside_local_processes_is_given_them(self): + r = run.Run.__new__(run.Run) + r.base, r.key, r.model, r.name, r.image, r.key_header = "http://b", "k", "m", "job", "img", "authorization" + r.other, r.judge_model, r.simulator_model, r.backend, r.relay_container = {"_kind": "agent"}, "", "", "local", True + r.serving, r.max_calls, r.call_seconds, r.exchanges, r.exchanges_max_mb = {}, None, relay.TIMEOUT, "text", 64 + made = {} + + class Unit: + def __init__(self, *args, **kw): + made.update(kw) + + def start(self): + return self + + def url(self, tag): + return "http://relay/" + tag + with mock.patch.object(container, "Unit", Unit), mock.patch.object(run.Run, "ledger_file", return_value=None), \ + mock.patch.object(run.Run, "models_called", return_value=[]): + got = r.unit_relay("u0", os.path.join(self.tmp, "trial"), {}) + self.assertEqual(got.unit_url, "http://relay/u0") + self.assertEqual((made["exchanges"], made["exchanges_max_mb"]), ("text", 64)) + + def test_the_relays_own_command_takes_them(self): + """The sidecar's process: given ``text``, it keeps the call and none of its pictures' bytes.""" + key, record = os.path.join(self.tmp, "key"), os.path.join(self.tmp, "rec") + with open(key, "w") as f: + f.write(KEY) + command = [sys.executable, "-m", "nullius.standard.calls.relay", "serve", "--listen", "127.0.0.1:0", "--base", self.base, + "--record", record, "--key-file", key] + env = dict(os.environ, PYTHONPATH=APP) + bad = subprocess.run(command + ["--exchanges-max-mb", "0"], cwd=APP, env=env, capture_output=True, text=True, timeout=20) + self.assertEqual(bad.returncode, 2) + self.assertIn("at least 1", bad.stdout) + p = subprocess.Popen(command + ["--exchanges", "text", "--exchanges-max-mb", "8"], cwd=APP, env=env, + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + try: + at = json.loads(p.stdout.readline())["listening"] + path, ask, _ = SHAPES["messages"] + req = urllib.request.Request(f"{at}/u0001/v1{path}", data=json.dumps(ask).encode(), headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=20) as got: + self.assertEqual(got.status, 200) + finally: + p.terminate() + p.wait(timeout=20) + p.stdout.close() + store = os.path.join(record, exchanges.FOLDER) + self.assertEqual([x["n"] for x in exchanges.lines(store, "u0001")], [1]) + self.assertFalse(os.path.exists(os.path.join(store, exchanges.BLOBS))) + + +class TheRun(WithUpstream): + """A whole run of the fake agent, its first call refused: a retried try's store goes aside with it.""" + + def setUp(self): + super().setUp() + self._home = install.HOME + install.HOME = os.path.join(self.tmp, "home") + self.addCleanup(setattr, install, "HOME", self._home) + self.addCleanup(setattr, pacing, "FIRST", pacing.FIRST) + pacing.FIRST = 0.5 + self.env = {"MODEL_API_URL": self.base, "MODEL_API_KEY": KEY} + + def go(self, **kw): + b = dict(definitions.get("benchmark", "fakebench", ROOT), datasets=[{"id": "responding", "units": 3}]) + return run.run(b, definitions.get("agent", "fake", ROOT), model="m-1", provider="custom", jobs_root=os.path.join(self.tmp, "jobs"), + concurrency=1, env=self.env, say=lambda s: None, unsandboxed=True, dataset="responding", **kw) + + def test_a_retried_try_keeps_its_store_and_the_next_try_starts_an_empty_one(self): + Upstream.refuse = 1 + job_dir = self.go(retries=1) + (kept,) = os.listdir(os.path.join(job_dir, "retried")) + name = kept.rpartition(".try-")[0] + tag = name.rsplit("__", 1)[1] + before = os.path.join(job_dir, "retried", kept, ".work", "relay", exchanges.FOLDER) + now = os.path.join(job_dir, name, ".work", "relay", exchanges.FOLDER) + self.assertEqual([(x["n"], x["reply"]["status"]) for x in exchanges.lines(before, tag)], [(1, 429)]) + self.assertEqual([(x["n"], x["reply"]["status"]) for x in exchanges.lines(now, tag)], [(1, 200)]) + self.assertTrue(exchanges.check(now, tag, 1)["same"]) # its own parts: nothing read from the try before + with open(os.path.join(job_dir, "config.json")) as f: + said = json.load(f)["standard"] + self.assertEqual((said["exchanges"], said["exchanges_max_mb"]), ("whole", 256)) + for root, _, names in os.walk(job_dir): + for n in names: + with open(os.path.join(root, n), "rb") as f: + self.assertNotIn(KEY.encode(), f.read(), os.path.join(root, n)) + + # the command: the request rebuilt, on stdout as the bytes sent, the verdict on stderr + (j,) = parse.load_all([os.path.join(self.tmp, "jobs")]) + sent = [raw for _, _, raw in Upstream.seen if b"model hi" in raw][-1] + code, out, err = self.show(j.job_id, name, "--call", "1", "--request") + self.assertEqual((code, out), (0, sent + b"\n")) + self.assertIn("the recorded sent_sha256", err) + with open(os.path.join(now, exchanges.PARTS)) as f: + text = f.read() + with open(os.path.join(now, exchanges.PARTS), "w") as f: + f.write(text.replace("model hi", "model HI")) + code, out, err = self.show(j.job_id, name, "--call", "1", "--request") + self.assertEqual(code, runs_cli.EXIT_FAILED) + self.assertIn("not the recorded sent_sha256", err) + self.assertEqual(self.show(j.job_id, name, "--call", "9", "--request")[0], runs_cli.EXIT_NOT_FOUND) + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as usage: + runs_cli.main(["show", os.path.join(self.tmp, "jobs"), j.job_id, name, "--call", "1"]) + self.assertEqual(usage.exception.code, 2) + + def test_an_earlier_try_is_read_by_its_name_call_by_call_as_for_one_request(self): + # a try kept in retried/ goes by its folder's name (NAME.try-N): --calls reads it as --call N --request does + Upstream.refuse = 1 + job_dir = self.go(retries=1) + (kept,) = os.listdir(os.path.join(job_dir, "retried")) + name = kept.rpartition(".try-")[0] + (j,) = parse.load_all([os.path.join(self.tmp, "jobs")]) + statuses = {} + for trial in (kept, name): + code, out, err = self.show(j.job_id, trial, "--calls") + self.assertEqual(code, 0, err) + statuses[trial] = [c["status"] for c in json.loads(out)["calls"]] + self.assertEqual(statuses, {kept: [429], name: [200]}) # each try's own calls + self.assertEqual(self.show(j.job_id, kept, "--call", "1", "--request")[0], 0) + self.assertEqual(self.show(j.job_id, name + ".try-9", "--calls")[0], runs_cli.EXIT_NOT_FOUND) + + def show(self, job_id, trial, *more): + out, err = io.TextIOWrapper(io.BytesIO(), encoding="utf-8"), io.StringIO() + with mock.patch.object(sys, "stdout", out), contextlib.redirect_stderr(err): + code = runs_cli.main(["show", os.path.join(self.tmp, "jobs"), job_id, trial, *more]) + out.flush() + return code, out.buffer.getvalue(), err.getvalue() + + def test_off_and_a_bad_value_and_the_command_line(self): + job_dir = self.go(exchanges="off", name="off") + for root, dirs, _ in os.walk(job_dir): + self.assertNotIn(exchanges.FOLDER, dirs, root) + with open(os.path.join(job_dir, "config.json")) as f: + self.assertEqual(json.load(f)["standard"]["exchanges"], "off") + for bad in ({"exchanges": "all"}, {"exchanges_max_mb": 0}, {"exchanges_max_mb": True}, {"exchanges_max_mb": 1.5}): + with self.subTest(bad=bad), self.assertRaises(run.Refused): + self.go(name="bad", **bad) + given = {} + b, o = definitions.get("benchmark", "fakebench", ROOT), definitions.get("agent", "fake", ROOT) + with mock.patch.object(standard_cli, "_bench", return_value=b), mock.patch.object(standard_cli, "_other", return_value=o), \ + mock.patch.object(standard_cli, "licences", return_value=(None, None)), mock.patch.object(standard_cli, "_exit_on_term"), \ + mock.patch.object(standard_cli.run, "run_and_report", side_effect=lambda *a, **kw: given.update(kw) or ("job", False)), \ + mock.patch.object(standard_cli.progress, "ECHO", None), contextlib.redirect_stdout(io.StringIO()): + standard_cli.main(["run", "fakebench", "fake", "--model", "m-1", "--from-run"]) + self.assertEqual((given["exchanges"], given["exchanges_max_mb"]), ("whole", 256)) + standard_cli.main(["run", "fakebench", "fake", "--model", "m-1", "--from-run", "--exchanges", "text", "--exchanges-max-mb", "64"]) + self.assertEqual((given["exchanges"], given["exchanges_max_mb"]), ("text", 64)) + + +class Recipe(unittest.TestCase): + def test_a_recipe_takes_them_and_says_them_only_when_not_the_default(self): + defs = {k: definitions.load(k, ROOT)[0] for k in ("benchmark", "agent", "capability")} + base = {"version": 1, "harness": "standard", "name": "fake-0101-120000", "title": "t", "benchmark": "fakebench", "dataset": "all", + "other": "fake", "provider": "openai", "model": "gpt-5-mini", "limit": 2, "concurrency": 2, "unsandboxed": True, "where": "local"} + out = recipe.compile(base, defs) + self.assertEqual(out["errors"], []) + self.assertNotIn("--exchanges", out["script"]) + out = recipe.compile(dict(base, exchanges="text", exchanges_max_mb=64), defs) + self.assertEqual(out["errors"], []) + self.assertIn("--exchanges text --exchanges-max-mb 64 ", out["script"]) + self.assertIn(["Model exchanges", "text · at most 64 MB per task"], [row[1:] for row in out["review"]]) + for bad in ({"exchanges": "all"}, {"exchanges_max_mb": 0}, {"exchanges_max_mb": "x"}): + errors = recipe.compile(dict(base, **bad), defs)["errors"] + self.assertEqual([e["step"] for e in errors], [recipe.STEP["limits"]], bad) + + +class Reasoning(unittest.TestCase): + def test_read_reply_gives_the_reasoning_only_when_asked(self): + for path, body, streamed in (("/chat/completions", json.dumps(CHAT).encode(), False), ("/chat/completions", CHAT_SSE, True), + ("/messages", json.dumps(MESSAGE).encode(), False), ("/messages", MESSAGE_SSE, True), + ("/responses", json.dumps(RESPONSE).encode(), False), ("/responses", RESPONSE_SSE, True)): + with self.subTest(path=path, streamed=streamed): + got = relay.read_reply(path, body, streamed, reasoning=True) + self.assertEqual((got["text"], got["reasoning"]), ("ok", "I looked")) + self.assertNotIn("reasoning", relay.read_reply(path, body, streamed)) # the call record's reading, unchanged + thought = {"choices": [{"message": {"content": "ok", "reasoning_content": "deep"}}]} + self.assertEqual(relay.read_reply("/chat/completions", json.dumps(thought).encode(), False, reasoning=True)["reasoning"], "deep") + + +class Version(unittest.TestCase): + """Each file of a store names the version of its format on its first line; a store without it is version 1.""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + @staticmethod + def keep(record_dir): + store = exchanges.Store(record_dir) + for n, req in enumerate(({"messages": [data_url(PNG), "hello"]}, {"messages": [data_url(PNG), "hello", "again"]}), 1): + store.write("u0001", n, 1.0, "/messages", req, json.dumps(req).encode(), {}, 200, False, b"{}") + return store + + def test_a_new_store_holds_the_mark_and_grows_by_it_alone_and_reads_as_one_without_it(self): + marked = self.keep(str(self.root / "marked")) + with mock.patch.object(exchanges, "HEADER", ""): # the store as written before the mark + plain = self.keep(str(self.root / "plain")) + got, before = WithUpstream.files(marked.dir), WithUpstream.files(plain.dir) + self.assertEqual(exchanges.HEADER, '{"schema": "nullius.exchanges/v1"}\n') + self.assertEqual(sorted(got), sorted(before)) + for name in got: + self.assertEqual(got[name], (exchanges.HEADER.encode() if name.endswith(".jsonl") else b"") + before[name], name) + self.assertEqual(sum(map(len, got.values())) - sum(map(len, before.values())), 2 * len(exchanges.HEADER)) + self.assertEqual((marked.size, plain.size), (sum(map(len, got.values())), sum(map(len, before.values())))) + self.assertEqual(exchanges.lines(marked.dir, "u0001"), exchanges.lines(plain.dir, "u0001")) + self.assertEqual(exchanges.stored_parts(marked.dir), exchanges.stored_parts(plain.dir)) + for store in (marked, plain): + for n in (1, 2): + self.assertTrue(exchanges.check(store.dir, "u0001", n)["same"]) + + def test_pending_marks_count_towards_the_first_calls_bound(self): + probe = exchanges.Store(str(self.root / "probe")) + req = {"messages": ["x"]} + probe.write("u0001", 1, 1.0, "/messages", req, json.dumps(req).encode(), {}, 200, False, b"{}") + size = sum(map(len, WithUpstream.files(probe.dir).values())) + for extra in (0, 1, 2 * len(exchanges.HEADER.encode())): + with self.subTest(extra=extra): + store = exchanges.Store(str(self.root / str(extra)), max_mb=1) + req = {"messages": ["x" * (store.bound - size + 1 + extra)]} + store.write("u0001", 1, 1.0, "/messages", req, json.dumps(req).encode(), {}, 200, False, b"{}") + line, = exchanges.lines(store.dir, "u0001") + self.assertEqual("cut" in line, extra > 0) + self.assertEqual(store.size, sum(map(len, WithUpstream.files(store.dir).values()))) + if extra == 0: + self.assertEqual(store.size, store.bound) + self.assertTrue(exchanges.check(store.dir, "u0001", 1)["same"]) + else: + self.assertFalse((Path(store.dir) / exchanges.PARTS).exists()) + store.write("u0001", 2, 1.0, "/messages", {}, b"{}", {}, 200, False, b"{}") + self.assertIn("cut", exchanges.lines(store.dir, "u0001")[1]) + + def test_later_parts_are_refused_before_raw_cut_or_missing_requests(self): + trial = mock.Mock(dir=str(self.root / "task__u0001"), trial_name="task__u0001") + store = self.keep(os.path.join(trial.dir, ".work", "relay")) + store.write("u0001", 3, 1.0, "/messages", None, b"raw request", {}, 400, False, b"{}") + with open(Path(store.dir) / "u0001.jsonl", "a") as f: + f.write(json.dumps({"n": 4, "cut": "the store reached its bound"}) + "\n") + f.write(json.dumps({"n": 5, "error": "the request was not kept"}) + "\n") + path = Path(store.dir) / exchanges.PARTS + path.write_text(json.dumps({"schema": "nullius.exchanges/v2"}) + "\n" + path.read_text().split("\n", 1)[1]) + for n in (1, 3, 4, 5): + with self.subTest(n=n): + out, err = io.TextIOWrapper(io.BytesIO(), encoding="utf-8"), io.StringIO() + self.addCleanup(out.close) + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = runs_cli._request(trial, n) + out.flush() + self.assertEqual((code, out.buffer.getvalue()), (runs_cli.EXIT_NOT_FOUND, b"")) + self.assertIn("version 2", err.getvalue()) + self.assertIn("version 1", err.getvalue()) + + def test_a_later_version_or_another_format_is_refused_by_each_reader_naming_both(self): + for name in ("u0001.jsonl", exchanges.PARTS): + for said, words in (("nullius.exchanges/v2", ("version 2", "version 1")), + ("another.format/v1", ("'another.format/v1'", "version 1"))): + with self.subTest(name=name, said=said): + trial = mock.Mock(dir=str(self.root / name / said.replace("/", "-") / "task__u0001"), trial_name="task__u0001") + store = self.keep(os.path.join(trial.dir, ".work", "relay")) + path = Path(store.dir) / name + path.write_text(json.dumps({"schema": said}) + "\n" + path.read_text().split("\n", 1)[1]) + reads = [lambda: exchanges.check(store.dir, "u0001", 1)] + reads.append((lambda: exchanges.lines(store.dir, "u0001")) if name != exchanges.PARTS + else (lambda: exchanges.stored_parts(store.dir))) + for read in reads: + with self.assertRaises(exchanges.Later) as refused: + read() + for word in (name,) + words: + self.assertIn(word, str(refused.exception)) + out, err = io.TextIOWrapper(io.BytesIO(), encoding="utf-8"), io.StringIO() + self.addCleanup(out.close) + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = runs_cli._request(trial, 1) + out.flush() + self.assertEqual((code, out.buffer.getvalue()), (runs_cli.EXIT_NOT_FOUND, b"")) + for word in words: + self.assertIn(word, err.getvalue()) + + +class Unmarked: + """The tests again on stores written without the mark of their format, as before it: they read the same.""" + + def setUp(self): + patch = mock.patch.object(exchanges, "HEADER", "") + patch.start() + self.addCleanup(patch.stop) + super().setUp() + + +class UnmarkedStoreFiles(Unmarked, StoreFiles): + pass + + +class UnmarkedByteForByte(Unmarked, ByteForByte): + pass + + +class UnmarkedStoredOnce(Unmarked, StoredOnce): + pass + + +class UnmarkedTextOnly(Unmarked, TextOnly): + pass + + +class UnmarkedBound(Unmarked, Bound): + pass + + +class UnmarkedNeverInTheWay(Unmarked, NeverInTheWay): + pass + + +class UnmarkedNoKey(Unmarked, NoKey): + pass + + +class UnmarkedTheRun(Unmarked, TheRun): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_trace_calls.py b/app/tests/test_trace_calls.py new file mode 100644 index 00000000..1e6196a8 --- /dev/null +++ b/app/tests/test_trace_calls.py @@ -0,0 +1,621 @@ +"""The transcript by model call: what each call sent that the call before had +not, the answer whole, the steps under each call, and the pictures by hash. +Fixture trials are written with the relay's own store (``exchanges.Store``); +no relay runs, no network.""" +from __future__ import annotations + +import base64 +import contextlib +import hashlib +import io +import json +import os +import sys +import tempfile +import time +import unittest +from datetime import datetime, timezone +from unittest import mock + +from nullius.runs import cli as runs_cli, parse +from nullius.standard.calls import exchanges, relay +from nullius.traces import calls, trajectory + +T0 = 1_790_000_000.0 + + +def picture(i: int, size: int = 3000) -> bytes: + seed = hashlib.sha256(str(i).encode()).digest() + return b"\x89PNG\r\n\x1a\n" + (seed * (size // len(seed) + 1))[:size] + + +def data_url(raw: bytes, kind: str = "image/png") -> str: + return f"data:{kind};base64,{base64.b64encode(raw).decode()}" + + +def sha(raw: bytes) -> str: + return hashlib.sha256(raw).hexdigest() + + +def iso(t: float) -> str: + return datetime.fromtimestamp(t, timezone.utc).isoformat() + + +def chat_reply(text="ok", tool=None, reasoning="", provider="Prov"): + m = {"role": "assistant", "content": text} + if reasoning: + m["reasoning"] = reasoning + if tool: + m["tool_calls"] = [{"id": "c", "type": "function", "function": {"name": tool[0], "arguments": tool[1]}}] + return json.dumps({"choices": [{"message": m, "finish_reason": "tool_calls" if tool else "stop"}], "provider": provider, + "usage": {"prompt_tokens": 100, "completion_tokens": 10}}).encode() + + +def write_trial(folder: str, exchanges_kept, *, mode="whole", tag="u0001", steps=(), record_n=True): + """A trial at ``folder``: ``exchanges_kept`` is a list of calls, each a dict of ``path``, ``req``, ``status``, + ``body``, ``streamed`` and the call record's own fields (``refused``, ``error``, ``side``); a call with + ``req`` None was refused before it was sent. ``mode`` None keeps the call record alone.""" + record_dir = os.path.join(folder, ".work", "relay") + os.makedirs(os.path.join(folder, "agent"), exist_ok=True) + store = exchanges.Store(record_dir, mode) if mode else None + rows = [] + for n, c in enumerate(exchanges_kept, 1): + t0 = T0 + 10 * n + path, req, status = c.get("path", "/chat/completions"), c.get("req"), c.get("status", 200) + body, streamed = c.get("body", b""), c.get("streamed", False) + rec = {"t0": t0, "t1": t0 + 2, "path": path, "model": "m", "model_asked": "m", "status": status, + "request": relay._request_tail(req) if req else {}, "headers": []} + if record_n and store is not None: + rec = {"n": n, **rec} + for k in ("refused", "error", "side"): + if k in c: + rec[k] = c[k] + if status == 200: + rec["reply"] = relay.read_reply(path, body, streamed) + rec["reply"].update({k: v for k, v in relay.reply_facts(path, body, streamed).items() if k not in rec["reply"]}) + rec["cost_usd"], rec["cost_from"] = 0.001 * n, "provider" + elif "error" not in rec: + rec["error"] = relay._said(status, body) + rows.append(rec) + if store is not None and req is not None: + store.write(tag, n, t0, path, req, json.dumps(req).encode(), {"Content-Type": "application/json"}, + status, streamed, body) + with open(os.path.join(folder, "agent", "calls.jsonl"), "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in rows)) + with open(os.path.join(folder, "agent", "trajectory.json"), "w") as f: + json.dump({"steps": [{"step_id": i + 1, "source": src, "timestamp": iso(at), "message": msg} + for i, (src, at, msg) in enumerate(steps)]}, f) + return folder + + +def load(folder: str) -> dict: + return calls.view(folder, trajectory.load(os.path.join(folder, "agent", "trajectory.json"))) + + +SYSTEM = {"role": "system", "content": "be brief"} +TOOLS = [{"type": "function", "function": {"name": "click", "parameters": {}}}, + {"type": "function", "function": {"name": "type_text", "parameters": {}}}] +P1, P2, P3 = picture(1), picture(2), picture(3) + + +def history(): + """Four calls of a chat agent that resends its context; the fourth replaces an earlier picture.""" + user = {"role": "user", "content": [{"type": "text", "text": "open the file"}, {"type": "image_url", "image_url": {"url": data_url(P1)}}]} + a1 = {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "click", "arguments": "{\"x\": 1}"}}]} + r1 = {"role": "tool", "tool_call_id": "c1", "content": [{"type": "text", "text": "clicked"}, {"type": "image_url", "image_url": {"url": data_url(P2)}}]} + a2 = {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "type_text", "arguments": "{}"}}]} + r2 = {"role": "tool", "tool_call_id": "c2", "content": "typed"} + more = {"role": "user", "content": "and save it"} + r1_cut = {"role": "tool", "tool_call_id": "c1", "content": [{"type": "text", "text": "clicked"}, {"type": "text", "text": "[picture left out]"}]} + a3 = {"role": "assistant", "content": "saving"} + r3 = {"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url(P3)}}]} + reqs = [[SYSTEM, user], [SYSTEM, user, a1, r1], [SYSTEM, user, a1, r1, a2, r2, more], [SYSTEM, user, a1, r1_cut, a2, r2, more, a3, r3]] + replies = [chat_reply(tool=("click", "{\"x\": 1}")), chat_reply(tool=("type_text", "{}")), chat_reply("saving"), chat_reply("done")] + return [{"req": {"model": "m", "messages": msgs, "tools": TOOLS}, "body": body} for msgs, body in zip(reqs, replies)] + + +class Base(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="nullius-calls-") + self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, ignore_errors=True)) + + def trial(self, kept, name="task__u0001", **kw): + return write_trial(os.path.join(self.tmp, "job", name), kept, **kw) + + +class SentIsWhatIsNew(Base): + def test_search_finds_rewritten_text_in_the_folded_section(self): + kept = history() + kept[3]["req"]["messages"][3]["content"][1]["text"] = "unique-rewritten-marker" + v = load(self.trial(kept)) + page = calls.page(v, query="UNIQUE-REWRITTEN-MARKER", section="folded") + self.assertEqual(page["matches"], 1) + self.assertEqual(page["selected"]["number"], 4) + self.assertIn("unique-rewritten-marker", page["selected"]["content"]["text"]) + + def test_each_call_sends_only_what_the_call_before_lacked_pictures_by_hash(self): + v = load(self.trial(history())) + self.assertEqual(v["record"], "exchanges") + sent = [[(i["kind"], i.get("text"), [p["sha256"] for p in i["pictures"]]) for i in c["sent"]["items"]] for c in v["calls"]] + self.assertEqual([k for k, _, _ in sent[0]], ["system", "tools", "user"]) # the first: system text and tools, then the prompt + self.assertEqual(sent[0][0][1], "be brief") + self.assertEqual(v["calls"][0]["sent"]["items"][1]["names"], ["click", "type_text"]) + self.assertEqual(sent[0][2][2], [sha(P1)]) + self.assertEqual(sent[1], [("tool result", "clicked\n[picture " + sha(P2)[:12] + "]", [sha(P2)])]) # the answer sent back is left out + self.assertEqual([(k, t) for k, t, _ in sent[2]], [("tool result", "typed"), ("user", "and save it")]) + self.assertEqual(sent[3], [("user", "[picture " + sha(P3)[:12] + "]", [sha(P3)])]) + fourth = v["calls"][3]["sent"] + self.assertEqual((len(fourth["rewritten"]), fourth["dropped"]), (1, 1)) # the picture replaced: one folded line + self.assertEqual(fourth["rewritten"][0]["text"], "clicked\n[picture left out]") + self.assertEqual(v["calls"][1]["sent"]["items"][0]["tool_call_id"], "c1") + text = json.dumps(calls.document(v)) + for raw in (P1, P2, P3): + self.assertNotIn(base64.b64encode(raw).decode()[:40], text) # named by hash, never inlined + self.assertEqual(set(v["pictures"]), {sha(P1), sha(P2), sha(P3)}) + page = calls.page(v, position=3)["selected"] + self.assertEqual([s["key"] for s in page["sections"]][-2:], ["folded", "text"]) + self.assertEqual(page["sent"]["folded"], {"key": "folded", "rewritten": 1, "dropped": 1}) + + def test_the_three_shapes_name_their_tool_results_and_new_prompts(self): + tool = {"type": "object"} + messages = [ + {"path": "/messages", "req": {"model": "m", "system": "sys", "tools": [{"name": "click", "input_schema": tool}], + "messages": [{"role": "user", "content": "go"}]}, + "body": json.dumps({"type": "message", "content": [{"type": "tool_use", "id": "t1", "name": "click", "input": {}}], + "stop_reason": "tool_use", "usage": {"input_tokens": 1, "output_tokens": 1}}).encode()}, + {"path": "/messages", "req": {"model": "m", "system": "sys", "tools": [{"name": "click", "input_schema": tool}], + "messages": [{"role": "user", "content": "go"}, + {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "click", "input": {}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [ + {"type": "image", "source": {"type": "base64", "media_type": "image/png", + "data": base64.b64encode(P1).decode()}}]}]}]}, + "body": json.dumps({"type": "message", "content": [{"type": "text", "text": "done"}], "stop_reason": "end_turn", + "usage": {"input_tokens": 1, "output_tokens": 1}}).encode()}] + v = load(self.trial(messages)) + self.assertEqual([i["kind"] for i in v["calls"][0]["sent"]["items"]], ["system", "tools", "user"]) + (result,) = v["calls"][1]["sent"]["items"] + self.assertEqual((result["kind"], result["tool_call_id"], [p["sha256"] for p in result["pictures"]]), ("tool result", "t1", [sha(P1)])) + responses = [ + {"path": "/responses", "req": {"model": "m", "instructions": "sys", "input": [{"role": "user", "content": "go"}]}, + "body": json.dumps({"object": "response", "status": "completed", + "output": [{"type": "function_call", "call_id": "c1", "name": "click", "arguments": "{}"}]}).encode()}, + {"path": "/responses", "req": {"model": "m", "instructions": "sys", "input": [ + {"role": "user", "content": "go"}, {"type": "function_call", "call_id": "c1", "name": "click", "arguments": "{}"}, + {"type": "function_call_output", "call_id": "c1", "output": "clicked"}]}, + "body": json.dumps({"object": "response", "status": "completed", "output": []}).encode()}] + v = load(self.trial(responses, name="task__u0002", tag="u0002")) + self.assertEqual([i["kind"] for i in v["calls"][0]["sent"]["items"]], ["system", "user"]) + self.assertEqual([(i["kind"], i["text"], i["tool_call_id"]) for i in v["calls"][1]["sent"]["items"]], [("tool result", "clicked", "c1")]) + + def test_a_side_call_is_compared_with_the_side_call_before_it(self): + kept = history()[:2] + kept.insert(1, {"req": {"model": "m", "messages": [{"role": "user", "content": "summarise"}]}, "body": chat_reply("short"), "side": True}) + v = load(self.trial(kept)) + self.assertEqual([i["kind"] for i in v["calls"][1]["sent"]["items"]], ["user"]) + self.assertEqual([i["kind"] for i in v["calls"][2]["sent"]["items"]], ["tool result"]) + + +LONG = json.dumps({"text": "x" * 3000}) + + +def answers(): + """(path, body, streamed) of a reply with reasoning, text and a tool call of more than 2,000 characters, by shape.""" + chat = json.dumps({"choices": [{"message": {"content": "ok", "reasoning": "I looked", "tool_calls": [ + {"function": {"name": "type_text", "arguments": LONG}}]}, "finish_reason": "tool_calls"}], "provider": "Prov", + "usage": {"prompt_tokens": 5, "completion_tokens": 2}}).encode() + chat_sse = b"".join(b"data: " + json.dumps(e).encode() + b"\n\n" for e in [ + {"provider": "Prov", "choices": [{"delta": {"reasoning": "I looked"}}]}, + {"choices": [{"delta": {"content": "ok"}}]}, + {"choices": [{"delta": {"tool_calls": [{"index": 0, "function": {"name": "type_text", "arguments": LONG[:1500]}}]}}]}, + {"choices": [{"delta": {"tool_calls": [{"index": 0, "function": {"arguments": LONG[1500:]}}]}, "finish_reason": "tool_calls"}]}, + {"choices": [], "usage": {"prompt_tokens": 5, "completion_tokens": 2}}]) + b"data: [DONE]\n\n" + msg = json.dumps({"type": "message", "provider": "Prov", "stop_reason": "tool_use", "content": [ + {"type": "thinking", "thinking": "I looked", "signature": "s"}, {"type": "text", "text": "ok"}, + {"type": "tool_use", "id": "t", "name": "type_text", "input": {"text": "x" * 3000}}], + "usage": {"input_tokens": 5, "output_tokens": 2}}).encode() + events = [{"type": "message_start", "message": {"provider": "Prov", "usage": {"input_tokens": 5}}}, + {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}, + {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I looked"}}, + {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}, + {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "ok"}}, + {"type": "content_block_start", "index": 2, "content_block": {"type": "tool_use", "id": "t", "name": "type_text", "input": {}}}, + {"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": LONG[:1500]}}, + {"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": LONG[1500:]}}, + {"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 2}}] + msg_sse = b"".join(f"event: {e['type']}\ndata: ".encode() + json.dumps(e).encode() + b"\n\n" for e in events) + response = {"object": "response", "status": "completed", "provider": "Prov", "output": [ + {"type": "reasoning", "summary": [{"type": "summary_text", "text": "I looked"}]}, + {"type": "message", "content": [{"type": "output_text", "text": "ok"}]}, + {"type": "function_call", "call_id": "c", "name": "type_text", "arguments": LONG}], + "usage": {"input_tokens": 5, "output_tokens": 2}} + resp_sse = b"event: response.completed\ndata: " + json.dumps({"type": "response.completed", "response": response}).encode() + b"\n\n" + return [("/chat/completions", chat, False, "tool_calls"), ("/chat/completions", chat_sse, True, "tool_calls"), + ("/messages", msg, False, "tool_use"), ("/messages", msg_sse, True, "tool_use"), + ("/responses", json.dumps(response).encode(), False, "completed"), ("/responses", resp_sse, True, "completed")] + + +class AnswerIsWhole(Base): + def test_reasoning_text_whole_arguments_end_and_provider_for_each_shape_streamed_or_not(self): + for i, (path, body, streamed, end) in enumerate(answers()): + with self.subTest(path=path, streamed=streamed): + req = {"model": "m", "stream": streamed, **({"input": "go"} if path == "/responses" else {"messages": [{"role": "user", "content": "go"}]})} + v = load(self.trial([{"path": path, "req": req, "body": body, "streamed": streamed}], name=f"t__u{i:04d}", tag=f"u{i:04d}")) + a = v["calls"][0]["answer"] + self.assertEqual((a["text"], a["reasoning"], a["end"], a["served_by"], a["abridged"]), ("ok", "I looked", end, "Prov", False)) + (tool,) = a["tool_calls"] + self.assertEqual(json.loads(tool["arguments"]), {"text": "x" * 3000}) # whole: the call record cut it to 2,000 + page = calls.page(v)["selected"] + self.assertEqual([x["label"] for x in page["answer"]["items"]], ["Reasoning", "Text", "type_text"]) + tail = calls.page(v, section="tool-0", chunk=9)["selected"]["content"] + self.assertTrue(tail["text"].endswith("x" * 50 + "\"}")) + + +class Numbering(Base): + def test_answered_calls_count_up_and_a_refused_or_failed_call_keeps_its_place_unnumbered(self): + h = history() + kept = [h[0], {"req": h[1]["req"], "status": 429, "body": b'{"error": {"message": "slow down"}}'}, + {"req": None, "status": 402, "refused": "calls", "error": "the unit's cap of 1 model calls was reached"}, h[1]] + v = load(self.trial(kept)) + self.assertEqual([(c["number"], c["label"]) for c in v["calls"]], [(1, "Call 1"), (None, "Failed"), (None, "Refused"), (2, "Call 2")]) + self.assertEqual(v["calls"][2]["sent"], {"recorded": False, "note": "Not sent: refused before it went out"}) + self.assertIsNone(v["calls"][1]["answer"]) + self.assertEqual(calls.page(v, position=1)["selected"]["sections"][-1]["label"], "Error") + # the failed call's request is Sent against the call before; the next answered one against the failed one + self.assertEqual([i["kind"] for i in v["calls"][3]["sent"]["items"]], []) + + +class StepsUnderCalls(Base): + def test_a_prompt_with_several_calls_has_each_step_under_the_call_before_it(self): + steps = [("user", T0 + 1, "open the file"), ("agent", T0 + 11, "looking"), ("agent", T0 + 15, "(tool use)"), + ("agent", T0 + 21, "typing"), ("agent", T0 + 35, "saved"), ("agent", T0 + 45, "done")] + v = load(self.trial(history(), steps=steps)) + self.assertEqual([s["step_id"] for s in v["before"]], [1]) + self.assertEqual([[s["step_id"] for s in c["steps"]] for c in v["calls"]], [[2, 3], [4], [5], [6]]) + page = calls.page(v, position=0)["selected"] + self.assertEqual([s["step_id"] for s in page["before"]], [1]) + self.assertEqual(calls.page(v, step="5")["selected"]["number"], 3) + + +class ThreeKinds(Base): + def test_a_trial_with_the_call_record_alone_or_with_none(self): + alone = load(self.trial(history(), mode=None)) + self.assertEqual(alone["record"], "calls") + first = alone["calls"][0] + self.assertEqual(first["sent"], {"recorded": False, "note": "Not recorded"}) + self.assertEqual((first["number"], first["answer"]["abridged"], first["answer"]["tool_calls"][0]["name"]), (1, True, "click")) + self.assertEqual(first["tokens"], {"input": 100, "output": 10, "cached": 0, "reasoning": 0}) + self.assertEqual((first["cost_usd"], first["seconds"]), (0.001, 2.0)) + self.assertEqual(alone["calls"][2]["answer"]["text"], "saving") + selected = calls.page(alone, position=2, section="text")["selected"] + self.assertTrue(selected["answer"]["abridged"]) + self.assertEqual(selected["content"]["text"], "saving") + none = os.path.join(self.tmp, "harbor", "task__x") + os.makedirs(os.path.join(none, "agent")) + self.assertEqual((calls.recorded(none), load(none)["record"], load(none)["calls"]), (0, None, [])) + with open(os.path.join(none, "agent", "calls.jsonl"), "w"): + pass # a control: its record is empty + self.assertEqual(calls.view(none)["record"], None) + + def test_text_keeps_each_pictures_type_and_size_and_no_bytes(self): + v = load(self.trial(history(), mode="text")) + (pic,) = v["calls"][0]["sent"]["items"][2]["pictures"] + self.assertEqual(pic, {"sha256": sha(P1), "type": "image/png", "bytes": len(P1), "stored": False}) + with self.assertRaises(LookupError): + calls.picture(v, sha(P1)) + + +class LaterVersion(Base): + def test_a_later_store_without_call_records_keeps_its_refusal_on_the_page(self): + for name in ("u0001.jsonl", exchanges.PARTS): + with self.subTest(name=name): + folder = self.trial(history(), name=name.split(".")[0] + "__u0001") + os.unlink(os.path.join(folder, calls.CALLS)) + self.assertFalse(os.path.exists(os.path.join(folder, calls.RELAY, "u0001.jsonl"))) + self.assertEqual(len(load(folder)["calls"]), 4) + path = os.path.join(calls.store_folder(folder), name) + with open(path) as f: + rows = f.read().split("\n", 1) + with open(path, "w") as f: + f.write(json.dumps({"schema": "nullius.exchanges/v2"}) + "\n" + rows[1]) + v = load(folder) + self.assertEqual((v["calls"], v["pictures"]), ([], {})) + for page in (calls.page(v), calls.page(v, query="missing", step=1)): + self.assertEqual((page["total"], page["rows"], page["selected"]), (0, [], None)) + self.assertIn("version 2", page["notice"]) + self.assertIn("version 1", page["notice"]) + self.assertEqual(page["notice"], v["notice"]) + + def test_a_store_in_a_later_format_is_not_read_and_each_call_says_both_versions(self): + for name in ("u0001.jsonl", exchanges.PARTS): + with self.subTest(name=name): + folder = self.trial(history(), name=name.split(".")[0] + "__u0001") + path = os.path.join(calls.store_folder(folder), name) + with open(path) as f: + rows = f.read().split("\n", 1) + self.assertEqual(rows[0] + "\n", exchanges.HEADER) + with open(path, "w") as f: + f.write(json.dumps({"schema": "nullius.exchanges/v2"}) + "\n" + rows[1]) + v = load(folder) + self.assertEqual((v["record"], v["pictures"], len(v["calls"])), ("calls", {}, 4)) + for c in v["calls"]: + self.assertEqual(c["sent"], {"recorded": False, "unreadable": True, "note": + f"Unreadable: {name} is in version 2 of the exchange store's format; " + "this Nullius reads version 1: read it with a later Nullius"}) + self.assertEqual((v["calls"][3]["answer"]["text"], v["calls"][3]["answer"]["abridged"]), ("done", True)) + self.assertIn("version 2", calls.page(v)["selected"]["sent"]["note"]) + # each call says why: the page's own notices stay as they were + self.assertEqual([calls.page(v, **ask)["notice"] for ask in ({}, {"query": "zzzz"}, {"step": "none"})], + ["", "No calls match this search.", "No call in this search holds that source step."]) + with self.assertRaises(LookupError): + calls.picture(v, sha(P1)) + + +class Unreadable(Base): + def test_every_call_naming_a_damaged_part_is_unreadable(self): + for damage in ("truncated", "picture"): + with self.subTest(damage=damage): + kept = history()[:2] + [{"req": {"messages": [{"role": "user", "content": "fresh"}]}, + "body": chat_reply("done")}] + folder = self.trial(kept, name=damage + "__u0001") + parts = os.path.join(calls.store_folder(folder), exchanges.PARTS) + with open(parts) as f: + rows = f.read().splitlines() + rows = [(row[:40] if damage == "truncated" else row.replace(sha(P1), "../outside")) + if sha(P1) in row else row for row in rows] + with open(parts, "w") as f: + f.write("\n".join(rows) + "\n") + v = load(folder) + self.assertEqual([c["sent"].get("unreadable", False) for c in v["calls"]], [True, True, False]) + self.assertEqual([r["unreadable"] for r in calls.page(v)["rows"]], [True, True, False]) + self.assertEqual(v["calls"][0]["sent"]["note"], v["calls"][1]["sent"]["note"]) + self.assertEqual(v["calls"][2]["sent"]["items"][0]["text"], "fresh") + + def test_a_damaged_part_or_a_bad_picture_name_makes_that_call_unreadable_and_the_others_are_read(self): + kept = history() + kept[3]["req"]["messages"] = [m for m in kept[3]["req"]["messages"] if m.get("content") != "typed"] + folder = self.trial(kept) + parts = os.path.join(calls.store_folder(folder), exchanges.PARTS) + with open(parts) as f: + rows = f.read().splitlines() + r2 = next(i for i, r in enumerate(rows) if '"typed"' in r) + p3 = next(i for i, r in enumerate(rows) if sha(P3) in r) + rows[r2] = rows[r2][:40] # damaged + rows[p3] = rows[p3].replace(sha(P3), "../../../outside") # a picture name that is not a digest + with open(parts, "w") as f: + f.write("\n".join(rows) + "\n") + v = load(folder) + said = [(c["sent"].get("unreadable", False), c["sent"].get("note", "")) for c in v["calls"]] + self.assertEqual([u for u, _ in said], [False, False, True, True]) + self.assertIn("is not in the store", said[2][1]) + self.assertIn("64 hexadecimal digits", said[3][1]) + self.assertEqual(v["calls"][3]["answer"]["text"], "done") # its answer still reads + self.assertTrue(calls.page(v)["rows"][2]["unreadable"]) + + +class Pictures(Base): + def test_inline_encodings_are_picture_metadata_in_every_display(self): + encoded = base64.b64encode(P1).decode() + variants = [encoded + "\n", encoded[:40] + " \n" + encoded[40:], encoded.rstrip("="), + base64.urlsafe_b64encode(P1).decode()] + for i, value in enumerate(variants): + for source in (False, True): + with self.subTest(variant=i, source=source): + image = ({"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": value}} + if source else {"type": "image_url", "image_url": {"url": "data:image/png;base64," + value}}) + req = {"messages": [{"role": "user", "content": [image]}], + "tools": [{"name": "look", "input_schema": {"default": image}}]} + folder = self.trial([{"req": req, "body": chat_reply(json.dumps(image))}], name=f"inline-{i}-{source}__u0001") + v = load(folder) + for item in v["calls"][0]["sent"]["items"]: + self.assertEqual(item["pictures"], [{"sha256": sha(P1), "type": "image/png", + "bytes": len(P1), "stored": False}]) + for shown in (v, calls.document(v), calls.page(v, section="sent-0"), + calls.page(v, section="sent-1"), calls.page(v, section="text")): + self.assertNotIn(value[:40], json.dumps(shown)) + self.assertTrue(exchanges.check(calls.store_folder(folder), "u0001", 1)["same"]) + + def test_a_listed_picture_is_given_with_its_type_and_any_other_is_refused(self): + v = load(self.trial(history())) + self.assertEqual(calls.picture(v, sha(P2)), (P2, "image/png")) + for bad in (sha(b"nothing"), "A" * 64, "../" + sha(P2)[3:], sha(P2)[:63]): + with self.subTest(bad=bad), self.assertRaises(LookupError): + calls.picture(v, bad) + folder = self.trial(history()[:1], name="other__u0001") + with self.assertRaises(LookupError): + calls.picture(load(folder), sha(P2)) # another trial's + # a blob whose type is not an image: listed in a part, its bytes there, never given + store = calls.store_folder(folder) + page = b"" + h = sha(page) + with open(os.path.join(store, exchanges.BLOBS, h + ".bin"), "wb") as f: + f.write(page) + with open(os.path.join(store, exchanges.PARTS), "a") as f: + f.write(json.dumps({"sha256": "f" * 64, "part": {"x": {"blob": h, "type": "text/html", "bytes": len(page), "as": "base64"}}}) + "\n") + again = load(folder) + self.assertEqual(again["pictures"][h], "text/html") + with self.assertRaises(LookupError): + calls.picture(again, h) + self.assertEqual(calls.picture(again, sha(P1)), (P1, "image/png")) + with open(os.path.join(store, exchanges.BLOBS, sha(P1) + ".png"), "r+b") as f: + f.write(b"damaged") + with self.assertRaises(LookupError): + calls.picture(again, sha(P1)) # bytes that are not their hash + + +class Weight(Base): + def test_sixty_calls_with_sixty_pictures_page_twelve_calls_and_no_bytes(self): + msgs, kept = [SYSTEM, {"role": "user", "content": "start"}], [] + for i in range(60): + kept.append({"req": {"model": "m", "messages": list(msgs), "tools": TOOLS}, "body": chat_reply(tool=("click", "{}"))}) + msgs += [{"role": "assistant", "content": None, "tool_calls": [{"id": f"c{i}", "type": "function", "function": {"name": "click", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": f"c{i}", "content": [{"type": "image_url", "image_url": {"url": data_url(picture(100 + i, 200_000))}}]}] + folder = self.trial(kept, steps=[("agent", T0 + 10 * n + 5, f"step {n}") for n in range(1, 61)]) + started = time.perf_counter() + v = load(folder) + took = time.perf_counter() - started + print(f"\nthe reader on 60 calls, 60 pictures of 200 kB: {took:.3f} s", file=sys.stderr) + self.assertEqual(len(v["calls"]), 60) + self.assertEqual(sum(len(i["pictures"]) for c in v["calls"] for i in c["sent"]["items"]), 59) + data = json.dumps(calls.page(v, position=59)) + self.assertEqual(len(calls.page(v)["rows"]), 12) + self.assertLess(len(data), 20_000) + self.assertNotIn(base64.b64encode(picture(158, 200_000)).decode()[:40], data) + + +class NothingSecret(Base): + def test_texts_pass_through_the_pages_redaction(self): + kept = [{"req": {"model": "m", "messages": [{"role": "user", "content": "use sk-live-01234567 please"}]}, + "body": chat_reply("key is sk-live-01234567")}] + v = load(self.trial(kept)) + text = json.dumps(calls.document(v)) + json.dumps(calls.page(v, section="sent-0")) + self.assertNotIn("sk-live-01234567", text) + self.assertIn("[REDACTED]", text) + + +class Tries(Base): + def test_each_try_reads_its_own_calls(self): + job = os.path.join(self.tmp, "job") + self.trial(history()[:1], name=os.path.join("retried", "task__u0001.try-1")) + self.trial(history(), name="task__u0001") + first = load(os.path.join(job, "retried", "task__u0001.try-1")) + last = load(os.path.join(job, "task__u0001")) + self.assertEqual((len(first["calls"]), len(last["calls"])), (1, 4)) + + +class TheCommand(Base): + def test_request_reads_the_route_of_each_try(self): + root = os.path.join(self.tmp, "jobs") + job = os.path.join(root, "job-a") + kept = history() + names = ("task__u0001.try-1", "task__u0001") + for i, name in enumerate(names): + folder = os.path.join(job, "retried", name) if i == 0 else os.path.join(job, name) + write_trial(folder, [kept[i]]) + with open(os.path.join(folder, "result.json"), "w") as f: + json.dump({"task_name": "d/task", "trial_name": "task__u0001", "source": "d", + "standard": {"retries": i}}, f) + other = {"messages": ["another route"]} + exchanges.Store(os.path.join(folder, calls.RELAY)).write( + "other", 1, T0, "/messages", other, json.dumps(other).encode(), {}, 200, False, b"{}") + with open(os.path.join(job, "config.json"), "w") as f: + json.dump({"agents": [{"name": "a", "model_name": "m"}], "datasets": [{"name": "d", "n_tasks": 1}]}, f) + with open(os.path.join(job, "result.json"), "w") as f: + json.dump({"stats": {"n_trials": 1}}, f) + (j,) = parse.load_all([root]) + tries = parse.tries(j.trials[0]) + self.assertEqual([t.trial_name for _, t in tries], list(names)) + for i, (_, trial) in enumerate(tries): + for entry in ("request", "command"): + with self.subTest(trial=i, entry=entry): + out, err = io.TextIOWrapper(io.BytesIO(), encoding="utf-8"), io.StringIO() + self.addCleanup(out.close) + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = (runs_cli._request(trial, 1) if entry == "request" else + runs_cli.main(["show", root, j.job_id, trial.trial_name, "--call", "1", "--request"])) + out.flush() + self.assertEqual((code, out.buffer.getvalue()), (0, json.dumps(kept[i]["req"]).encode() + b"\n")) + self.assertIn("the recorded sent_sha256", err.getvalue()) + self.assertEqual(load(trial.dir)["calls"][0]["answer"]["tool_calls"][0]["name"], + "click" if i == 0 else "type_text") + + def test_runs_show_calls_prints_the_view_as_json(self): + root = os.path.join(self.tmp, "jobs") + job = os.path.join(root, "job-a") + os.makedirs(job) + with open(os.path.join(job, "config.json"), "w") as f: + json.dump({"agents": [{"name": "a", "model_name": "m"}], "datasets": [{"name": "d", "n_tasks": 1}]}, f) + with open(os.path.join(job, "result.json"), "w") as f: + json.dump({"stats": {"n_trials": 1}}, f) + kept = history() + kept[0]["req"]["messages"][1]["content"][1]["image_url"]["url"] += "\n" + trial = write_trial(os.path.join(job, "task__u0001"), kept, steps=[("agent", T0 + 11, "looking")]) + with open(os.path.join(trial, "result.json"), "w") as f: + json.dump({"task_name": "d/task", "trial_name": "task__u0001", "source": "d"}, f) + (j,) = parse.load_all([root]) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = runs_cli.main(["show", root, j.job_id, "task__u0001", "--calls"]) + self.assertEqual(code, 0, err.getvalue()) + doc = json.loads(out.getvalue()) + self.assertNotIn(base64.b64encode(P1).decode()[:40], out.getvalue()) + self.assertEqual((doc["record"], [c["number"] for c in doc["calls"]], doc["calls"][0]["steps"]), ("exchanges", [1, 2, 3, 4], [1])) + self.assertEqual(doc["calls"][1]["sent"]["items"][0]["pictures"][0]["sha256"], sha(P2)) + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as usage: + runs_cli.main(["show", root, j.job_id, "--calls"]) + self.assertEqual(usage.exception.code, 2) + + +class PicturesKept(Base): + """The pictures a trial's store keeps, for the row the Artifacts tab gives them: each counted once, with its bytes.""" + + def test_each_picture_sent_is_counted_once_with_its_bytes_and_nothing_else(self): + folder = self.trial(history()) + self.assertEqual(calls.pictures_kept(folder), {"count": 3, "bytes": len(P1) + len(P2) + len(P3)}) + with open(os.path.join(calls.store_folder(folder), exchanges.BLOBS, "a" * 64 + ".bin"), "wb") as f: + f.write(b"not a picture") + self.assertEqual(calls.pictures_kept(folder)["count"], 3) + for name, mode in (("text__u0001", "text"), ("none__u0001", None)): # the text alone, or no store: none + with self.subTest(mode=mode): + self.assertIsNone(calls.pictures_kept(self.trial(history(), name=name, mode=mode))) + linked = self.trial([], name="linked__u0001", mode=None) # a store reached through a link is not read + os.makedirs(os.path.join(linked, ".work", "relay"), exist_ok=True) + os.symlink(calls.store_folder(folder), calls.store_folder(linked)) + self.assertIsNone(calls.pictures_kept(linked)) + + +class Unmarked: + """The tests again on stores written without the mark of their format, as before it: they read the same.""" + + def setUp(self): + patch = mock.patch.object(exchanges, "HEADER", "") + patch.start() + self.addCleanup(patch.stop) + super().setUp() + + +class UnmarkedSentIsWhatIsNew(Unmarked, SentIsWhatIsNew): + pass + + +class UnmarkedAnswerIsWhole(Unmarked, AnswerIsWhole): + pass + + +class UnmarkedNumbering(Unmarked, Numbering): + pass + + +class UnmarkedStepsUnderCalls(Unmarked, StepsUnderCalls): + pass + + +class UnmarkedThreeKinds(Unmarked, ThreeKinds): + pass + + +class UnmarkedUnreadable(Unmarked, Unreadable): + pass + + +class UnmarkedPictures(Unmarked, Pictures): + pass + + +class UnmarkedWeight(Unmarked, Weight): + pass + + +class UnmarkedNothingSecret(Unmarked, NothingSecret): + pass + + +class UnmarkedTries(Unmarked, Tries): + pass + + +class UnmarkedTheCommand(Unmarked, TheCommand): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_builder_limits.py b/app/ui_tests/test_builder_limits.py new file mode 100644 index 00000000..5854667e --- /dev/null +++ b/app/ui_tests/test_builder_limits.py @@ -0,0 +1,71 @@ +"""The standard's Limits step as the page draws it: its fields, their hints and the defaults they show.""" +import json +import re +import subprocess + +from ui_tests.builder_support import APP, CompilerCase + + +class LimitsStep(CompilerCase): + def form(self, key, edit=""): + """standardForm on the Limits step and what it calls, cut from the page script, run against the core, with + the recipe ``r`` made and changed by ``edit``: the program, to which a test adds what it asks.""" + page = (APP / "static/builder/command-builder.js").read_text(encoding="utf-8") + cut = lambda start, end: page[page.index(start):page.index(end, page.index(start))] + line = lambda name: re.search(r"^ const %s = .*$" % name, page, re.M).group(0) + "\n" + schema = dict(self.schema, hosts=[], standardHere={"docker": None, "licences": {}, "host": {}}) + return ("const schema=" + json.dumps(schema) + ";const C=require(" + json.dumps(str(APP / "static/builder/command-builder-core.js")) + ")(schema);\n" + + "const S=C.STEP,REVIEW=S.review;let step=S.limits;\n" + + line("esc") + line("button") + cut(" const unitsOf = ", " // the first clause") + line("words") + + line("field") + line("fixed") + line("note") + cut(" function standardForm(", " function compileRunner(") + + "const r=C.createStandard(" + json.dumps(key) + ");" + edit) + + def draw(self, key, edit=""): + """The Limits step's html (:meth:`form`).""" + program = self.form(key, edit) + "process.stdout.write(JSON.stringify(standardForm(r)));" + return json.loads(subprocess.run([self.node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + + def click(self, key, edit, labels): + """Each card of ``labels`` in turn, found by its name in the step drawn again and clicked through the page's + own click handler on the builder (its buttons' data attributes as their dataset): the recipe after each.""" + page = (APP / "static/builder/command-builder.js").read_text(encoding="utf-8") + start = page.index(" root.addEventListener('click',async event=>{") + handler = page[start:page.index("\n });\n", start) + len("\n });\n")] + program = (self.form(key, edit) + + "const chosen=r,root={listeners:{},addEventListener(kind,fn){this.listeners[kind]=fn;}};let drawn=0;\n" + + "{const r=()=>chosen,renderForm=()=>{drawn++;},refreshPlan=()=>{};\n" + handler + "}\n" + + "const press=async label=>{const card=[...standardForm(chosen).matchAll(/', kept) + self.assertIn("4 calls · 3 steps", kept) + data = self.get("/trial/calls-run/kept__u0001/conversation", query_string={"kind": "calls", "position": 1}).get_json() + self.assertEqual((data["view"], data["record"], data["total"]), ("calls", "exchanges", 4)) + (result,) = data["selected"]["sent"]["items"] + self.assertEqual((result["label"], result["pictures"][0]["sha256"]), ("Tool result · c1", sha(P2))) + self.assertEqual(result["pictures"][0]["url"], f"/trial/calls-run/kept__u0001/picture/{sha(P2)}") + self.assertEqual([s["step_id"] for s in data["selected"]["steps"]], [3]) + flat = self.get("/trial/calls-run/kept__u0001/conversation", query_string={"kind": "all"}).get_json() + self.assertEqual((flat["kind"], flat["total"]), ("all", 3)) # the flat list of steps, kept as a filter + + record, _ = self.tab("record__u0002") + self.assertIn('data-kind="calls"', record) + data = self.get("/trial/calls-run/record__u0002/conversation", query_string={"kind": "calls"}).get_json() + self.assertEqual((data["record"], data["selected"]["sent"]["note"], data["selected"]["answer"]["abridged"]), + ("calls", "Not recorded", True)) + self.assertEqual(data["rows"][0]["tokens"]["input"], 100) + + plain, _ = self.tab("plain__u0003") + for mark in ("data-default-kind", 'data-kind="calls"', " calls"): + self.assertNotIn(mark, plain) + self.assertIn('3 steps', plain) + self.assertIn('', plain) + steps = self.get("/trial/calls-run/plain__u0003/conversation", query_string={"kind": "calls"}).get_json() + self.assertNotIn("view", steps) # no call is inferred: the steps, as today + self.assertEqual(steps["total"], 3) + + def test_the_artifacts_tab_counts_the_pictures_sent_and_links_the_conversation(self): + _, html = self.tab("kept__u0001") + tab = re.search(r'
', html, re.S).group(0) + row = re.search(r'
(.*?)', tab, re.S).group(1) + self.assertIn("Pictures sent to the model · 3", row) + self.assertIn(f"{3 * len(P1) / 1024:.2f} KB", row) + self.assertIn('href="/trial/calls-run/kept__u0001?tab=conversation" data-open-tab="conversation">Conversation', row) + _, plain = self.tab("record__u0002") # a call record with no store keeps no picture + self.assertNotIn("artifact-pictures", plain) + script = (Path(__file__).resolve().parents[1] / "static/traces/conversation.js").read_text(encoding="utf-8") + self.assertIn("document.getElementById('trial-artifacts')?.addEventListener('click', event => {\n" + " const link = event.target.closest('a[data-open-tab]');", script) # the link opens the tab in place + + def test_a_picture_opens_over_the_page_and_closes_by_close_or_a_click_outside(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the picture viewer") + script = (Path(__file__).resolve().parents[1] / "static/traces/conversation.js").read_text(encoding="utf-8") + cut = (script[script.index(" const el = "):script.index(" let viewer = null;")] + + script[script.index(" let viewer = null;"):script.index(" const readJSON")] + + script[script.index(" const size = value =>"):script.index(" const said = ")] + + script[script.index(" const picture = p => {"):script.index(" const item = (entry, selected) => {")]) + program = r""" +const assert = require('node:assert/strict'); +function node(tag) { + return {tagName: tag.toUpperCase(), children: [], listeners: {}, attrs: {}, className: '', open: false, + append(...c) { this.children.push(...c); }, setAttribute(k, v) { this.attrs[k] = v; }, + addEventListener(e, f) { (this.listeners[e] = this.listeners[e] || []).push(f); }, + querySelector(tag) { const walk = n => n.tagName === tag.toUpperCase() ? n : n.children.map(walk).find(Boolean); return this.children.map(walk).find(Boolean) || null; }, + showModal() { this.open = true; }, close() { this.open = false; }}; +} +const body = node('body'), document = {createElement: node, body}; +const click = (on, target) => (on.listeners.click || []).forEach(f => f({target})); +// a click as the browser sends it, with the keys held: whether the page kept the link from opening its new tab +const press = (on, keys = {}) => { let kept = false; + (on.listeners.click || []).forEach(f => f({target: on, button: 0, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, ...keys, + preventDefault() { kept = true; }})); + return kept; }; +""" + cut + r""" +const link = picture({url: '/p/1', sha256: 'abc'.padEnd(64, '0'), type: 'image/png', bytes: 2048}); +assert.equal(link.tagName, 'A'); assert.equal(link.target, '_blank'); +assert.equal(press(link, {ctrlKey: true}), false); assert.equal(body.children.length, 0); // a key held: its own tab +assert.equal(press(link), true); // a plain click: over the page +const dialog = body.children[0], box = dialog.children[0], close = box.children[0]; +assert.equal(dialog.tagName, 'DIALOG'); assert.ok(dialog.open); assert.equal(dialog.attrs['aria-label'], 'Picture'); +assert.deepEqual([dialog.querySelector('img').src, dialog.querySelector('img').alt], ['/p/1', 'Picture abc000000000, image/png']); +assert.equal(close.textContent, 'Close'); +click(close, close); assert.ok(!dialog.open); +viewPicture('/p/2', 'b'); assert.equal(body.children.length, 1); assert.equal(dialog.querySelector('img').src, '/p/2'); +click(dialog, box); assert.ok(dialog.open); // on the picture: it stays +click(dialog, dialog); assert.ok(!dialog.open); // outside it, on the backdrop +""" + got = subprocess.run([node, "-"], input=program, capture_output=True, text=True, timeout=10) + self.assertEqual(got.returncode, 0, got.stderr) + + def test_the_picture_route(self): + r = self.get(f"/trial/calls-run/kept__u0001/picture/{sha(P2)}") + self.assertEqual((r.data, r.mimetype), (P2, "image/png")) + self.assertIn("max-age=31536000", r.headers["Cache-Control"]) + self.assertEqual(r.headers["X-Content-Type-Options"], "nosniff") + for bad in (sha(b"none"), sha(P2).upper(), sha(P2)[:-1], "not-a-digest"): + self.get(f"/trial/calls-run/kept__u0001/picture/{bad}", status=404) + self.get(f"/trial/calls-run/record__u0002/picture/{sha(P2)}", status=404) # a trial that does not list it + self.get(f"/trial/other-run/kept__u0001/picture/{sha(P2)}", status=404) # another trial's store lacks it + self.get(f"/trial/calls-run/kept__u0001/picture/{sha(P1)}") + # a blob the store lists under a type that is not an image + store = Path(self.job.trials[0].dir).parent / "kept__u0001" / ".work" / "relay" / "exchanges" + page = b"" + (store / "blobs" / (sha(page) + ".bin")).write_bytes(page) + with open(store / "parts.jsonl", "a") as f: + f.write(json.dumps({"sha256": "e" * 64, "part": {"x": {"blob": sha(page), "type": "text/html", "bytes": len(page), "as": "base64"}}}) + "\n") + self.get(f"/trial/calls-run/kept__u0001/picture/{sha(page)}", status=404) + + def test_a_long_trial_pages_twelve_calls_and_holds_no_picture_bytes(self): + _, html = self.tab("long__u0004") + data = self.get("/trial/calls-run/long__u0004/conversation", query_string={"kind": "calls"}) + for body in (html.encode(), data.data): + self.assertNotIn(base64.b64encode(picture(530, 50_000))[:40], body) + self.assertNotIn(b";base64,", body) + doc = data.get_json() + self.assertEqual((doc["total"], len(doc["rows"]), doc["pages"]), (60, 12, 5)) + self.assertLess(len(data.data), 20_000) + + def test_each_try_shows_its_own_calls(self): + last = self.get("/trial/calls-run/retry__u0005/conversation", query_string={"kind": "calls"}).get_json() + first = self.get("/trial/calls-run/retry__u0005.try-1/conversation", query_string={"kind": "calls"}).get_json() + self.assertEqual((last["total"], first["total"]), (4, 1)) + tab, _ = self.tab("retry__u0005.try-1") + self.assertIn("1 call · 3 steps", tab) + self.get(f"/trial/calls-run/retry__u0005.try-1/picture/{sha(P1)}") + self.get(f"/trial/calls-run/retry__u0005.try-1/picture/{sha(P2)}", status=404) + + def test_a_later_store_without_call_records_shows_its_refusal(self): + for name in ("later-route__u0007", "later-parts__u0008"): + with self.subTest(name=name): + _, html = self.tab(name) + self.assertIn('
', html) + self.assertIn("version 2", html) + self.assertIn("version 1", html) + data = self.get(f"/trial/calls-run/{name}/conversation", query_string={"kind": "calls"}).get_json() + self.assertEqual((data["view"], data["total"], data["selected"]), ("calls", 0, None)) + self.assertIn("version 2", data["notice"]) + self.assertIn("version 1", data["notice"]) + + def test_a_store_in_a_later_format_is_refused_naming_both_versions(self): + tab, _ = self.tab("later__u0006") + self.assertIn("4 calls · 3 steps", tab) + data = self.get("/trial/calls-run/later__u0006/conversation", query_string={"kind": "calls"}).get_json() + self.assertEqual((data["record"], data["total"], data["selected"]["sent"]["unreadable"]), ("calls", 4, True)) + self.assertEqual(data["selected"]["sent"]["note"], "Unreadable: parts.jsonl is in version 2 of the exchange store's " + "format; this Nullius reads version 1: read it with a later Nullius") + self.get(f"/trial/calls-run/later__u0006/picture/{sha(P1)}", status=404) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/web/traces.py b/app/web/traces.py index ee9159db..82a2d0fa 100644 --- a/app/web/traces.py +++ b/app/web/traces.py @@ -12,7 +12,7 @@ from flask import abort, flash, g, jsonify, redirect, render_template, request, url_for from markupsafe import Markup, escape from werkzeug.http import quote_header_value -from nullius.traces import behavior, charts, conversation, trace, trajectory +from nullius.traces import behavior, calls, charts, conversation, trace, trajectory from nullius.runs import artifacts, attempts as task_attempts, evidence, parse from nullius import importers as harnesses @@ -171,6 +171,45 @@ def _parsed_trace(path, filt): return tr +# A trial's calls read for a view (``calls.view``): every page of them, every picture asked for, would +# parse its store again. Kept by the files read (size, mtime), a few trials at a time; a view is not +# changed once read. +_CALLS: "OrderedDict" = OrderedDict() +_CALLS_MAX = 8 + + +def _calls_view(trial, traj=None): + path = trial.trajectory_path if trial.has_trajectory else "" + key = (os.path.realpath(trial.dir), calls.signature(trial.dir, path)) + with _PARSED_LOCK: + if key in _CALLS: + _CALLS.move_to_end(key) + return _CALLS[key] + if traj is None and path: + traj = trajectory.load(path) + got = calls.view(trial.dir, traj) + with _PARSED_LOCK: + _CALLS[key] = got + while len(_CALLS) > _CALLS_MAX: + _CALLS.popitem(last=False) + return got + + +@app.route("/trial///picture/") +def trial_picture(job_id, trial_name, sha256): + """A picture the trial's agent sent its model, by its sha256: only one its own store lists, of an + image type. Its content is its hash's, so the browser may keep it for good.""" + _, t = _trial_evidence(job_id, trial_name, tries=True) + try: + data, kind = calls.picture(_calls_view(t), sha256) + except LookupError: + abort(404) + response = app.response_class(data, mimetype=kind) + response.headers["Cache-Control"] = "private, max-age=31536000, immutable" + response.headers["X-Content-Type-Options"] = "nosniff" + return response + + @app.route("/trial///artifact/") def artifact_page(job_id, trial_name, key): job, trial = _trial_evidence(job_id, trial_name, tries=True) @@ -215,6 +254,19 @@ def artifact_download(job_id, trial_name, key): def conversation_data(job_id, trial_name): _, t = _trial_evidence(job_id, trial_name, tries=True) traj = trajectory.load(t.trajectory_path) if t.has_trajectory else None + view = _calls_view(t, traj) if request.args.get("kind") == "calls" else None + if view is not None and (view["calls"] or view.get("notice")): + payload = calls.page(view, query=request.args.get("q", ""), page=request.args.get("page", 1), + position=request.args.get("position"), step=request.args.get("step"), + section=request.args.get("section"), chunk=request.args.get("chunk", 0)) + for item in ((payload["selected"] or {}).get("sent") or {}).get("items") or []: + for pic in item["pictures"]: + if pic["stored"]: + pic["url"] = url_for("trial_picture", job_id=job_id, trial_name=trial_name, sha256=pic["sha256"], + workspace=request.args.get("workspace")) + response = jsonify(payload) + response.headers["Cache-Control"] = "no-store" + return response payload = conversation.page( traj, query=request.args.get("q", ""), kind=request.args.get("kind", "all"), page=request.args.get("page", 1), position=request.args.get("position"), @@ -301,11 +353,18 @@ def trial(job_id, trial_name): key=record["key"], workspace=request.args.get("workspace")) record["download"] = url_for("artifact_download", job_id=job_id, trial_name=trial_name, key=record["key"], workspace=request.args.get("workspace")) + pictures = calls.pictures_kept(t.dir) # the pictures sent to the model, a row of their own + n_calls = calls.recorded(t.dir) + if not n_calls and os.path.isdir(calls.store_folder(t.dir)): + notice = _calls_view(t, traj).get("notice") + if notice: + flash(notice, "error") return render_template( "traces/trial.html", job=j, trial=t, traj=traj, loc=loc, bench_parts=bench_parts, detail=detail, evidence=rows, trace=tr, charts=ch, viewing=viewing, imported_from=_imported_from(j), chart_filter=cfilt, default_save_name=SAVED_TRACE_DEFAULT, - artifacts=records, attempt=attempt, attempts=task_attempts.of(j, attempt), tries=_tries(attempt), + artifacts=records, pictures=pictures, attempt=attempt, attempts=task_attempts.of(j, attempt), tries=_tries(attempt), + n_calls=n_calls, # an earlier try is evidence only: the job counts its last, and only that is judged judgement=_judgement_panel(j, t) if attempt is t else None, llm_judgement=_judgement_panel(j, t, "llm") if attempt is t else None, csrf=shared._csrf_token(), diff --git a/docs/builder.md b/docs/builder.md index bfe209c7..e4c9d867 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -27,7 +27,7 @@ Then [read its results](results.md). | Dataset | One or more; each dataset with each agent is a job of its own. A benchmark option its datasets need is asked here, for the datasets it applies to. | | Agent (*Memory* on a memory benchmark) | Reference agents first, or **No agent · Original** for a direct-model benchmark. A benchmark with [agents of its own](standard.md#a-benchmarks-own-agents) (OSWorld's) lists them first, in place of its Original tile; several may be chosen, a job each. Memory benchmarks offer **Original memory** alongside compatible memory capabilities. | | Model | **Like the paper** keeps what the paper fixed: the model picker shows only documented paper models when the benchmark lists them, and the user simulator and judge are their official models. A benchmark that lists no paper models but has an official simulator or judge leaves the model to you. **Like the leaderboard**, on a benchmark that declares its leaderboard's rules, leaves the model to you and fixes what the leaderboard does: its user simulator and judge, the options it sets and at least its attempts per unit. **Any of your choice** opens the provider's full list and lets the simulator and judge be changed. Nothing fixed by the paper: the paper choice is disabled. **Served by**, on OpenRouter, chooses the serving providers that may answer that model, tried in their order and no other ([Run a benchmark](cli/run.md#serving-providers)). Empty: any of them. | -| Limits | Task limit (empty is every task), a task-name glob, concurrency, attempts per unit (each one scored), retries after an error (never after a failed task), timeouts in minutes. On the Nullius runner, a [spending cap](cli/run.md#a-spending-cap) for the run and one per unit, turns per conversation for a benchmark that holds conversations, a [cap on model calls](cli/run.md#a-cap-on-model-calls) per unit, [time limits](cli/run.md#time-limits) per phase in minutes, forced on every participant (empty: the benchmark's or agent's own value, else Nullius's default), then the benchmark's own bounds; a [list of units](cli/run.md#a-list-of-units) is set only on the command line | +| Limits | Task limit (empty is every task), a task-name glob, concurrency, attempts per unit (each one scored), retries after an error (never after a failed task), timeouts in minutes. On the Nullius runner, a [spending cap](cli/run.md#a-spending-cap) for the run and one per unit, turns per conversation for a benchmark that holds conversations, a [cap on model calls](cli/run.md#a-cap-on-model-calls) per unit, what each trial keeps of its model calls ([`--exchanges`](cli/run.md#the-exchange-record)), [time limits](cli/run.md#time-limits) per phase in minutes, forced on every participant (empty: the benchmark's or agent's own value, else Nullius's default), then the benchmark's own bounds; a [list of units](cli/run.md#a-list-of-units) is set only on the command line | | Where | **Hosts**: this machine or Settings hosts. **Sandboxes**: Boat VMs, within the account’s sizes and capacity. Choose isolation where available; VM benchmarks keep their own VM provider | | Review | One row per decision and the prerequisites. **Run** | diff --git a/docs/cli/pages.md b/docs/cli/pages.md index a536cee9..7caed9c2 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -9,6 +9,7 @@ Each page's command, or why there is none. | `/runs` | `nullius runs list ... [--json]` | | `/job/` | `nullius runs show [--json]` | | `/trial//` | `nullius runs show [--json]` | +| A trial's Conversation, by call | `nullius runs show --calls` | | `/import`, `/use-path` | `nullius import -o [--json]`; `--list` | | `/compare` | `nullius compare ... [--matched] [--json]` | | `/workspaces/open/` | `nullius serve ...`, `WORKSPACE=` | @@ -28,6 +29,7 @@ Each page's command, or why there is none. | --- | --- | | The live board | `/job//live` | | A trial's conversation, spans, artifacts | `/trial/…/conversation`, `/trial/…/trace-span`, `/trial/…/artifact/`, `/trial/…/artifact//download` | +| A picture the agent sent its model | `/trial/…/picture/` | | One task side by side | `/compare/task/` | ## No command yet diff --git a/docs/cli/read-jobs.md b/docs/cli/read-jobs.md index e33a4a3d..c3e19dfd 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -5,6 +5,8 @@ List the jobs under a root, open one, compare several, list the workspaces. ```bash title="The reading commands" nullius runs list ... [--json] nullius runs show [] [--json] +nullius runs show --call N --request +nullius runs show --calls nullius compare ... [--matched] [--json] nullius workspace list [--home DIR] [--json] nullius standard traces [--dry-run] @@ -39,6 +41,8 @@ nullius standard traces [--dry-run] | `nullius runs list ...` | The runs, as `/runs` lists them | | `nullius runs show ` | A job: trials, outcomes, counts, solve rates, mean scores | | `nullius runs show ` | A trial: outcome, checks, usage, exception, steps. Tool arguments and observations stay on the page | +| `nullius runs show --call N --request` | Call N's request as sent, rebuilt from the [exchange record](run.md#the-exchange-record); exit 4 when its hash differs | +| `nullius runs show --calls` | The trial's Conversation by model call, as JSON, redacted | | `nullius compare ... [--matched]` | `/compare`'s cohort: whole, or matched on the tasks every job ran | | `nullius workspace list [--home DIR]` | The workspaces, as `/workspaces` lists them | diff --git a/docs/cli/run.md b/docs/cli/run.md index ca998236..0161cd4c 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -7,7 +7,7 @@ nullius standard run [@version] [--model M] [--dataset D] [-- [--unsandboxed | --backend container|boat] [--option NAME=VALUE]... [--bench-option NAME=VALUE]... \ [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]]... [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS]... [--max-turns N] [--max-calls N] \ [--constraint KEY=VALUE]... \ - [--served-by [MODEL=]SLUG[,SLUG...]]... \ + [--served-by [MODEL=]SLUG[,SLUG...]]... [--exchanges whole|text|off] [--exchanges-max-mb N] \ [--attempts K] [--retries N] [--remove-images] [--judge-model M] [--simulator-model M] [--name NAME] [--jobs DIR] [--provider P] ``` @@ -38,6 +38,7 @@ nullius standard run locomo model --model gpt-4o-mini | `--max-calls N` | The most model calls a unit's agent may make: [below](#a-cap-on-model-calls) | | `--constraint KEY=VALUE` | What the machine allows the run (repeatable): `cpus`, `memory_mb`, `processes`, `cpu_set`, `concurrency`, `gpu_ids` (indices, empty for none); [constraints](../settings/run-hosts.md#constraints). A recipe passes each machine's own | | `--served-by [MODEL=]SLUG[,SLUG...]` | On OpenRouter, the serving providers that may answer a model (repeatable): [below](#serving-providers) | +| `--exchanges MODE`, `--exchanges-max-mb N` | What each unit's relay keeps of its agent's calls, and its bound ([below](#the-exchange-record)) | | `--attempts K` | Each unit K times; `result.json` carries `pass_hat_k` | | `--retries N` | Run a failed attempt again, up to N times: [below](#retries) | | `--remove-images` | Remove each image the run pulls or builds when its last unit ends (never with `--attempts`); by default they stay for the next run | @@ -85,6 +86,18 @@ Each phase of a unit has a time limit. `--timeout PHASE=SECONDS` (repeatable) fo | The upstream's own | A step limit of the benchmark's (τ³-bench's `--max-steps`, an OSWorld agent's `--max_steps`) still holds; this cap is on top | | The result | `config.json` records it under `standard.max_calls` | +## The exchange record + +`--exchanges whole` (default) saves each agent call in the trial's `.work/relay/exchanges/`, each part and picture once. Saving uses disk space, not extra model tokens. Prompts and pictures are stored as sent, unredacted; only the relay's key is cut out. + +| Rule | Detail | +| --- | --- | +| `text` | Every call without the pictures' bytes, kept by their hash, type and size. | +| `off` | No exchange record: the call record in `agent/calls.jsonl` alone. | +| The bound | `--exchanges-max-mb`, 256 MB a unit by default; later calls are marked `cut`. | +| Not kept | The judge's and the simulated user's calls: their call record alone. | +| The result | `config.json`: `standard.exchanges` and `standard.exchanges_max_mb`. | + ## A spending cap `--max-usd 5` stops a run at 5 USD and `--max-usd-per-unit 0.50` one unit at 0.50. diff --git a/docs/standard.md b/docs/standard.md index 083c5593..3c162aed 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -138,6 +138,7 @@ record); verifier/reward.txt and score.json | --- | --- | | Units | Run `-j` at a time, each with its own workspace (a git repository of its own), home and relay | | A relay per unit | Its record is the trial's `.work/relay`; the judge and simulated user are routes on it (`-judge`, `-simulator`). An embedding option's relay is recorded in `.work/relay-benchmark` as the benchmark's cost. A call refused with 400, 413 or 422 records its inline images' types and sizes as `images`, never their bytes | +| The exchange record (`--exchanges`) | Each call of a unit's agent, kept whole and unredacted by its relay ([Run a benchmark](cli/run.md#the-exchange-record)) | | Job name | One run at a time per job name: another is refused before it writes anything. A later run under the same name moves each trial's earlier record aside to the trial's `.work/earlier.` | | Backends (`--backend`) | `local`: processes on this machine. `container`: each unit's agent or capability in a container, its relay beside it, on Docker, else Podman 4.7 or later. Podman needs no Docker API socket and no `containers.conf` change. `docker` is accepted as an alias for `container`. For agent and capability runs the driver stays on the machine; Original setups instead containerize the driver and its answerer; in a container a check that runs what the agent left (the workspace kit's test) runs it in a throwaway, network-less container of the unit's image, and no check reads through a link the agent planted; `config.json` records the backend and the image. `boat`: each unit's agent or capability in a boat.dev VM of its own ([The boat backend](#the-boat-backend)) | | Progress | One line per stage on stderr and in `progress.jsonl`: `[nullius] stage=install agent=codex@2.2.2 state=done seconds=41 at=...` (`start`, `done`, `cached`, `failed`; a download's bytes every 5 s) for the base image, an environment, the upstream, a dataset, `driver.install` and the agent; then `stage=units n=10`, `stage=unit i=3 of=10 unit=... outcome=passed`, `stage=done`; `stage=refused` alone for a run refused first. From `stage=units` the job also writes `events.jsonl`, Harbor's live feed |
RecordSize
Pictures sent to the model · {{ pictures.count }}{{ '%.2f'|format(pictures.bytes / 1024) }} KBConversation