diff --git a/AGENTS.md b/AGENTS.md index 2b17e07b..b0a7c618 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,7 +43,7 @@ and its resources. and Capabilities tabs and conformance Kits catalogue). Cross-module names are reached as attributes (`shared.STATE`, `traces._trial_evidence`): patch one, patched for all. - `app/nullius/` — its backend, one package per purpose: `runs/` (reading one - Harbor job tree: `parse`, `classify`, `live`, `artifacts`, + Harbor job tree: `parse`, `classify`, `live`, `artifacts`, `evidence`, `feasibility`, `failure_analysis` - a job's failure labels and task flags, beside its result.json, written by `flags_cli` too -, `launches`, `verifier` - a verifier's report read by its benchmark's report block - `attempts`, a task's attempts in one job with their pass count and pass@k, and the `cli`), `traces/` (`trace`, the reader, with its span tree `spans`, diff --git a/app/nullius/catalogue/benchmarks/gaia/benchmark.json b/app/nullius/catalogue/benchmarks/gaia/benchmark.json index a89a7011..66b1b625 100644 --- a/app/nullius/catalogue/benchmarks/gaia/benchmark.json +++ b/app/nullius/catalogue/benchmarks/gaia/benchmark.json @@ -68,5 +68,11 @@ ], "citation": "@misc{mialon2023gaia,\n title={GAIA: a benchmark for General AI Assistants},\n author={Grégoire Mialon and Clémentine Fourrier and Craig Swift and Thomas Wolf and Yann LeCun and Thomas Scialom},\n year={2023},\n eprint={2311.12983},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}", "citation_source": "https://huggingface.co/spaces/gaia-benchmark/leaderboard/blob/9f133d71362e77b3539f1514f31b9c101a545fec/content.py", - "task_count": 165 + "task_count": 165, + "evidence": [ + { + "label": "Answer", + "path": "model_answer" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json b/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json index d85fd3e3..f6ee2806 100644 --- a/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json +++ b/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json @@ -43,5 +43,19 @@ "Answers must end with a line '#### '. The number is compared as text, so 18.00 does not match 18.", "The test split is run. The Socratic variant has the same questions and answers, with different worked explanations.", "GSM8K-Platinum is the test split with its errors cleaned. A problem has the same number in both, so the two runs compare problem by problem." + ], + "evidence": [ + { + "label": "Extracted answer", + "path": "extracted" + }, + { + "label": "Expected answer", + "path": "expected" + }, + { + "label": "Reply", + "path": "answer" + } ] } diff --git a/app/nullius/catalogue/benchmarks/humaneval/benchmark.json b/app/nullius/catalogue/benchmarks/humaneval/benchmark.json index 95ab2185..4cd92694 100644 --- a/app/nullius/catalogue/benchmarks/humaneval/benchmark.json +++ b/app/nullius/catalogue/benchmarks/humaneval/benchmark.json @@ -32,5 +32,23 @@ "citation_source": "https://github.com/openai/human-eval", "good_to_know": [ "One attempt per problem gives pass@1. With n attempts per problem, the run reports pass@1 to pass@n. The paper sampled 200." + ], + "evidence": [ + { + "label": "Why", + "path": "why" + }, + { + "label": "Result", + "path": "result" + }, + { + "label": "Not tested", + "path": "not_tested" + }, + { + "label": "solution.py", + "path": "solution.py" + } ] } diff --git a/app/nullius/catalogue/benchmarks/locomo/benchmark.json b/app/nullius/catalogue/benchmarks/locomo/benchmark.json index eaf8a1e0..3460beb4 100644 --- a/app/nullius/catalogue/benchmarks/locomo/benchmark.json +++ b/app/nullius/catalogue/benchmarks/locomo/benchmark.json @@ -39,5 +39,19 @@ } ], "citation": "@article{maharana2024evaluating,\n title={Evaluating very long-term conversational memory of llm agents},\n author={Maharana, Adyasha and Lee, Dong-Ho and Tulyakov, Sergey and Bansal, Mohit and Barbieri, Francesco and Fang, Yuwei},\n journal={arXiv preprint arXiv:2402.17753},\n year={2024}\n}", - "citation_source": "https://github.com/snap-research/locomo" + "citation_source": "https://github.com/snap-research/locomo", + "evidence": [ + { + "label": "Question", + "path": "question" + }, + { + "label": "Answer", + "path": "answer" + }, + { + "label": "Expected answer", + "path": "reference" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json b/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json index 2775d622..d23a9ac7 100644 --- a/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json +++ b/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json @@ -63,5 +63,20 @@ } ], "citation": "@article{wu2024longmemeval,\n title={LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory},\n author={Di Wu and Hongwei Wang and Wenhao Yu and Yuwei Zhang and Kai-Wei Chang and Dong Yu},\n year={2024},\n eprint={2410.10813},\n archivePrefix={arXiv},\n primaryClass={cs.CL},\n url={https://arxiv.org/abs/2410.10813},\n}", - "citation_source": "https://github.com/xiaowu0162/LongMemEval" + "citation_source": "https://github.com/xiaowu0162/LongMemEval", + "evidence": [ + { + "label": "Answer", + "path": "answer", + "reply": true + }, + { + "label": "Expected answer", + "path": "reference" + }, + { + "label": "Judge said", + "path": "judge_said" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/open-telco/benchmark.json b/app/nullius/catalogue/benchmarks/open-telco/benchmark.json index 829563e6..57890e5a 100644 --- a/app/nullius/catalogue/benchmarks/open-telco/benchmark.json +++ b/app/nullius/catalogue/benchmarks/open-telco/benchmark.json @@ -202,5 +202,19 @@ ], "task_count": 20588, "citation": "@misc{maatouk2023teleqna,\n title={TeleQnA: A Benchmark Dataset to Assess Large Language Models Telecommunications Knowledge},\n author={Maatouk, Ali and Ayed, Fadhel and Piovesan, Nicola and De Domenico, Antonio and Debbah, Merouane and Luo, Zhi-Quan},\n year={2023}, eprint={2310.15051}, archivePrefix={arXiv}\n}\n\n@misc{ezzakri2025teletables,\n title={TeleTables: A Benchmark for Large Language Models in Telecom Table Interpretation},\n author={Ezzakri, Anas and Piovesan, Nicola and Sana, Mohamed and De Domenico, Antonio and Ayed, Fadhel and Zhang, Haozhe},\n year={2025}, eprint={2601.04202}, archivePrefix={arXiv}\n}\n\n@misc{colle2025telemath,\n title={TeleMath: A Benchmark for Large Language Models in Telecom Mathematical Problem Solving},\n author={Colle, Vincenzo and Sana, Mohamed and Piovesan, Nicola and De Domenico, Antonio and Ayed, Fadhel and Debbah, Merouane},\n year={2025}, eprint={2506.10674}, archivePrefix={arXiv}\n}\n\n@misc{sana2025telelogs,\n title={Reasoning Language Models for Root Cause Analysis in 5G Wireless Networks},\n author={Sana, Mohamed and Piovesan, Nicola and De Domenico, Antonio and Kang, Yibin and Zhang, Haozhe and Debbah, Merouane and Ayed, Fadhel},\n year={2025}, eprint={2507.21974}, archivePrefix={arXiv}\n}\n\n@misc{zou2024telecomgpt,\n title={TelecomGPT: A Framework to Build Telecom-Specific Large Language Models},\n author={Zou, Hang and Zhao, Qiyang and Tian, Yu and Bariah, Lina and Bader, Faouzi and Lestable, Thierry and Debbah, Merouane},\n year={2024}, eprint={2407.09424}, archivePrefix={arXiv}\n}\n\n@misc{gajjar2024oranbench,\n title={ORAN-Bench-13K: An Open Source Benchmark for Assessing LLMs in Open Radio Access Networks},\n author={Gajjar, Pranshav and Shah, Vijay K.},\n year={2024}, eprint={2407.06245}, archivePrefix={arXiv}\n}\n\n@misc{gajjar2025oransight2,\n title={ORANSight-2.0: Foundational LLMs for O-RAN},\n author={Gajjar, Pranshav and Shah, Vijay K.},\n year={2025}, eprint={2503.05200}, archivePrefix={arXiv}\n}\n\n@misc{ferrag2026sixgbench,\n title={6G-Bench: An Open Benchmark for Semantic Communication and Network-Level Reasoning with Foundation Models in AI-Native 6G Networks},\n author={Ferrag, Mohamed Amine and Lakas, Abderrahmane and Debbah, Merouane},\n year={2026}, eprint={2602.08675}, archivePrefix={arXiv}\n}", - "citation_source": "https://huggingface.co/datasets/GSMA/ot-full" + "citation_source": "https://huggingface.co/datasets/GSMA/ot-full", + "evidence": [ + { + "label": "Extracted answer", + "path": "extracted" + }, + { + "label": "Expected answer", + "path": "target" + }, + { + "label": "Reply", + "path": "answer" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/osworld1/benchmark.json b/app/nullius/catalogue/benchmarks/osworld1/benchmark.json index 795f0d91..29f7c24d 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/benchmark.json +++ b/app/nullius/catalogue/benchmarks/osworld1/benchmark.json @@ -86,5 +86,6 @@ } } } - } + }, + "evidence": [] } diff --git a/app/nullius/catalogue/benchmarks/osworld2/benchmark.json b/app/nullius/catalogue/benchmarks/osworld2/benchmark.json index 5ad19c7c..b6b1f26d 100644 --- a/app/nullius/catalogue/benchmarks/osworld2/benchmark.json +++ b/app/nullius/catalogue/benchmarks/osworld2/benchmark.json @@ -62,5 +62,19 @@ } ], "citation": "@misc{yuan26osworld2,\n title={OSWorld 2.0: Benchmarking Computer Use Agents on Long-Horizon Real-World Tasks}, \n author={Mengqi Yuan and Zilong Zhou and Xinzhuang Xiong and Weiming Wu and Jiayang Sun and Jiamin Song and Kaiqian Cui and Bowen Wang and Haoyuan Wu and Yitong Li and Dunjie Lu and Haikong Lu and Qi Zhen and Xinyuan Wang and Jiaqi Deng and Yuhao Yang and Cheng Chen and Boyuan Zheng and Alex Su and Xiao Yu and Hao Zou and Saaket Agashe and Xing Han Lu and Manpreet Kaur and Zhengyang Qi and Vincent Sunn Chen and Frederic Sala and Dayiheng Liu and Junyang Lin and Zhou Yu and Yu Su and Siva Reddy and Xin Eric Wang and Peng Qi and Tianbao Xie and Tao Yu},\n year={2026},\n eprint={2606.29537},\n archivePrefix={arXiv},\n primaryClass={cs.AI},\n url={https://arxiv.org/abs/2606.29537}, \n}", - "citation_source": "https://github.com/xlang-ai/OSWorld-V2" + "citation_source": "https://github.com/xlang-ai/OSWorld-V2", + "evidence": [ + { + "label": "Safety checks failed", + "path": "safety.failed" + }, + { + "label": "Safety checks", + "path": "safety.checks" + }, + { + "label": "Penalty", + "path": "safety.total_penalty" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json b/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json index 789b156c..980b8712 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json +++ b/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json @@ -83,5 +83,22 @@ } }, "citation": "@inproceedings{\n jimenez2024swebench,\n title={{SWE}-bench: Can Language Models Resolve Real-world Github Issues?},\n author={Carlos E Jimenez and John Yang and Alexander Wettig and Shunyu Yao and Kexin Pei and Ofir Press and Karthik R Narasimhan},\n booktitle={The Twelfth International Conference on Learning Representations},\n year={2024},\n url={https://openreview.net/forum?id=VTF8yNQM66}\n}", - "citation_source": "https://github.com/SWE-bench/SWE-bench" + "citation_source": "https://github.com/SWE-bench/SWE-bench", + "evidence": [ + { + "label": "Why", + "path": "why" + }, + { + "label": "Infrastructure failure", + "path": "infra_failure" + }, + { + "label": "Timed out", + "path": "timed_out", + "unless": [ + "no" + ] + } + ] } diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json b/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json index 72871ecc..ca621f81 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json +++ b/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json @@ -45,5 +45,44 @@ "verify": 300 }, "citation": "@misc{barres2025tau2,\n title={$\\tau^2$-Bench: Evaluating Conversational Agents in a Dual-Control Environment},\n author={Victor Barres and Honghua Dong and Soham Ray and Xujie Si and Karthik Narasimhan},\n year={2025},\n eprint={2506.07982},\n archivePrefix={arXiv},\n primaryClass={cs.AI},\n url={https://arxiv.org/abs/2506.07982},\n}\n\n@misc{yao2024tau,\n title={$\\tau$-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains},\n author={Shunyu Yao and Noah Shinn and Pedram Razavi and Karthik Narasimhan},\n year={2024},\n eprint={2406.12045},\n archivePrefix={arXiv},\n primaryClass={cs.AI},\n url={https://arxiv.org/abs/2406.12045},\n}\n\n@article{shi2026tau,\n title={$\\tau$-Knowledge: Evaluating Conversational Agents over Unstructured Knowledge},\n author={Shi, Quan and Zytek, Alexandra and Razavi, Pedram and Narasimhan, Karthik and Barres, Victor},\n journal={arXiv preprint arXiv:2603.04370},\n year={2026}\n}", - "citation_source": "https://github.com/sierra-research/tau2-bench" + "citation_source": "https://github.com/sierra-research/tau2-bench", + "evidence": [ + { + "label": "Checks", + "path": "reward_info.reward_breakdown", + "names": { + "DB": "Database", + "COMMUNICATE": "Communication", + "ACTION": "Actions", + "ENV_ASSERTION": "Environment", + "NL_ASSERTION": "Assertions" + }, + "values": { + "1.0": "Pass", + "0.0": "Fail" + } + }, + { + "label": "Ended by", + "path": "termination", + "values": { + "user_stop": "User", + "agent_stop": "Agent", + "max_steps": "Step limit", + "timeout": "Timeout", + "too_many_errors": "Too many errors", + "agent_error": "Agent error", + "user_error": "User error", + "context_window_exceeded": "Context window exceeded", + "unexpected_error": "Unexpected error" + } + }, + { + "label": "Tool errors", + "path": "tool_errors", + "unless": [ + "0" + ] + } + ] } diff --git a/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json b/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json index 6b51590c..e213beb9 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json +++ b/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json @@ -68,5 +68,30 @@ } }, "citation": "@inproceedings{merrill2026terminalbench,\n title={Terminal-Bench: Benchmarking Agents on Hard, Realistic Tasks in Command Line Interfaces},\n author={Mike A Merrill and Alexander Glenn Shaw and Nicholas Carlini and Boxuan Li and Harsh Raj and Ivan Bercovich and Lin Shi and Jeong Yeon Shin and Thomas Walshe and E. Kelly Buchanan and Junhong Shen and Guanghao Ye and Haowei Lin and Jason Poulos and Maoyu Wang and Jenia Jitsev and Marianna Nezhurina and Di Lu and Orfeas Menis Mastromichalakis and Zhiwei Xu and Zizhao Chen and Yue Liu and Robert Zhang and Leon Liangyu Chen and Anurag Kashyap and Jan-Lucas Uslu and Jeffrey Li and Jianbo Wu and Minghao Yan and Song Bian and Vedang Sharma and Ke Sun and Steven Dillmann and Akshay Anand and Andrew Lanpouthakoun and Bardia Koopah and Changran Hu and Etash Kumar Guha and Gabriel H. S. Dreiman and Jiacheng Zhu and Karl Krauth and Li Zhong and Niklas Muennighoff and Robert Kwesi Amanfu and Shangyin Tan and Shreyas Pimpalgaonkar and Tushar Aggarwal and Xiangning Lin and Xin Lan and Xuandong Zhao and Yiqing Liang and Yuanli Wang and Zilong Wang and Changzhi Zhou and David Heineman and Hange Liu and Harsh Trivedi and John Yang and Junhong Lin and Manish Shetty and Michael Yang and Nabil Omi and Negin Raoof and Shanda Li and Terry Yue Zhuo and Wuwei Lin and Yiwei Dai and Yuxin Wang and Wenhao Chai and Shang Zhou and Dariush Wahdany and Ziyu She and Jiaming Hu and Zhikang Dong and Yuxuan Zhu and Sasha Cui and Ahson Saiyed and Arinbj{\\\"o}rn Kolbeinsson and Christopher Michael Rytting and Ryan Marten and Yixin Wang and Alex Dimakis and Andy Konwinski and Ludwig Schmidt},\n booktitle={The Fourteenth International Conference on Learning Representations},\n year={2026},\n url={https://openreview.net/forum?id=a7Qa4CcHak}\n}", - "citation_source": "https://github.com/laude-institute/terminal-bench" + "citation_source": "https://github.com/laude-institute/terminal-bench", + "evidence": [ + { + "label": "Why", + "path": "why" + }, + { + "label": "Tests failed", + "path": "tests.failed" + }, + { + "label": "Tests passed", + "path": "tests.passed" + }, + { + "label": "Timed out", + "path": "timed_out", + "unless": [ + "no" + ] + }, + { + "label": "Test output", + "path": "output" + } + ] } diff --git a/app/nullius/catalogue/catalog.py b/app/nullius/catalogue/catalog.py index c8f45593..1222ce61 100644 --- a/app/nullius/catalogue/catalog.py +++ b/app/nullius/catalogue/catalog.py @@ -16,6 +16,10 @@ order is the folders', and nothing depends on it. ``layout`` is the check on the tree itself - a folder named after its key - and ``validate`` runs it. +An optional ``records`` lists what the benchmark's verifier leaves in a +trial beside Nullius's own records, each a label and a path under the trial's +``verifier/``: a trial's Artifacts tab lists and serves those that exist. + An optional ``task_count`` gives the number of distinct tasks when datasets overlap, such as a full split beside difficulty subsets. It controls the benchmark headline only; every dataset keeps its own count. @@ -98,6 +102,13 @@ class Benchmark: #: the file, the fields that say pass or fail, the words the pages use; empty #: when the reward is all there is report: dict = field(default_factory=dict) + #: records its verifier leaves in a trial, each a ``label`` and a ``path`` under + #: the trial's ``verifier/`` (a file, or a folder whose files are listed): the + #: trial's Artifacts tab lists those that exist (``nullius.runs.artifacts``) + records: list = field(default_factory=list) + #: what of its score's detail a trial that fell short shows, in order + #: (``nullius.runs.evidence``); None shows the whole detail + evidence: list | None = None #: how to cite it: the BibTeX its official repository gives, else its paper's citation: str = "" citation_source: str = "" @@ -177,6 +188,28 @@ class Dataset: notes: str = "" +def valid_record(record) -> bool: + """A declared record's shape (``Benchmark.records``): a label, and a path + under ``verifier/`` with no empty, ``.`` or ``..`` part and no backslash.""" + if not isinstance(record, dict) or not isinstance(record.get("label"), str) or not record["label"].strip(): + return False + path = record.get("path") + if not isinstance(path, str) or "\\" in path or "\0" in path: + return False + parts = path.split("/") + return len(parts) > 1 and parts[0] == "verifier" and all(p not in ("", ".", "..") for p in parts[1:]) + + +def valid_evidence(entry) -> bool: + """A declared evidence row's shape (``nullius.runs.evidence``).""" + words = lambda x: isinstance(x, dict) and all(isinstance(v, str) for v in x.values()) + return (isinstance(entry, dict) and set(entry) <= {"label", "path", "values", "names", "unless", "reply"} + and all(isinstance(entry.get(k), str) and entry[k].strip() for k in ("label", "path")) + and words(entry.get("values", {})) and words(entry.get("names", {})) + and isinstance(entry.get("unless", []), list) and all(isinstance(x, str) for x in entry.get("unless", [])) + and isinstance(entry.get("reply", False), bool)) + + def sort_key(title: str) -> str: """Alphabetical as a reader expects: a title starting with τ files under T.""" return title.replace("τ", "t").replace("³", "3").lower() @@ -404,6 +437,10 @@ def validate(cat: Catalog) -> list: bad.append(f"{b.key}: published is {{agent: a Harbor agent's name, says: why it is the published one}}") if not b.category: bad.append(f"{b.key}: no category") + if not isinstance(b.records, list) or not all(valid_record(r) for r in b.records): + bad.append(f"{b.key}: records are each {{label, path under verifier/}}") + if b.evidence is not None and not (isinstance(b.evidence, list) and all(valid_evidence(e) for e in b.evidence)): + bad.append(f"{b.key}: evidence rows are each {{label, path}}, with values, names, unless or reply") for h in b.harness: if h not in dict(HARNESSES): bad.append(f"{b.key}: harness {h!r} is not one of {[k for k, _ in HARNESSES]}") diff --git a/app/nullius/runs/artifacts.py b/app/nullius/runs/artifacts.py index 99557c16..ddc13138 100644 --- a/app/nullius/runs/artifacts.py +++ b/app/nullius/runs/artifacts.py @@ -1,7 +1,18 @@ -"""Bounded, redacted views of named trial records. No writes or arbitrary paths.""" +"""Bounded, redacted views of named trial records. No writes or arbitrary paths. + +Nullius's own records are ``FILES``. A benchmark may declare its own in its +``benchmark.json`` (``records``: each a ``label`` and a ``path`` under the +trial's ``verifier/``, a file or a folder whose files are listed, one level; +text files alone): +``declared`` finds them by the trial's source, and each is addressed by its +place in that list (``r0``, or ``r0-NAME`` for a file of a folder). A declared +record is opened one folder at a time from the trial's own, no link followed: +it never leads outside the trial.""" from __future__ import annotations import os +import re +import stat from nullius.redact import redact @@ -27,6 +38,96 @@ } CHUNK_SIZE = 8_000 MAX_READ = 16 * 1024 * 1024 +FOLDER_FILES = 200 # the most files a declared folder lists +SNIFF = 8192 # a declared file with a NUL byte this far in is not text: not a record +DECLARED_KEY = re.compile(r"r(?P0|[1-9][0-9]{0,2})(?:-(?P.+))?", re.S) +_DIR = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + + +_CACHE: dict = {} + + +def declared(source) -> list: + """The records the benchmark of a trial's *source* declares, in its order: + found by the benchmark's key, a dataset's or a source its report block + names. Empty when it declares none.""" + from nullius.catalogue import catalog + sig = catalog.signature() + if _CACHE.get("sig") != sig: + table = {} + for b in catalog.load().benchmarks: + records = [dict(label=r["label"].strip(), path=r["path"]) for r in b.records or [] + if catalog.valid_record(r)] if isinstance(b.records, list) else [] + if records: + for name in [b.key, *b.datasets, *((b.report or {}).get("sources") or [])]: + table.setdefault(str(name).strip().lower(), records) + _CACHE.update(sig=sig, table=table) + return list(_CACHE["table"].get((source or "").strip().lower(), ())) + + +def _declared(key, records): + """(label, the path in the trial, the record's own path) of a declared record's key: a file of a declared folder + is labelled by the folder's label and its own name.""" + m = DECLARED_KEY.fullmatch(key or "") + if not m or int(m["n"]) >= len(records): + raise LookupError(key) + record = records[int(m["n"])] + name = m["name"] + if name is not None and (name in (".", "..") or "/" in name or not _plain_name(name)): + raise LookupError(key) + label = record["label"] if name is None else f"{record['label']}: {name}" + return label, record["path"] + ("/" + name if name is not None else ""), record["path"] + + +def _plain_name(name) -> bool: + """Whether a file's name in a declared folder can be listed and served: printable text alone. A name that is not + valid UTF-8 comes back from the system with a surrogate in it, which is not printable, as no control character is; + such a file is neither listed nor read.""" + return name.isprintable() + + +def _open_under(trial_dir, path, flags): + """A descriptor of *path* under the trial's folder, each part opened from the one before it, no link followed.""" + *folders, last = path.split("/") + fd = os.open(trial_dir, os.O_RDONLY | os.O_DIRECTORY) + try: + for part in folders: + child = os.open(part, _DIR, dir_fd=fd) + os.close(fd) + fd = child + return os.open(last, flags | os.O_NOFOLLOW, dir_fd=fd) + finally: + os.close(fd) + + +def _open_record(trial_dir, key, records): + """An open regular file of a key, fixed or declared.""" + if key in FILES: + path = path_for(trial_dir, key) + fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK) + else: + fd = _open_under(trial_dir, _declared(key, records)[1], os.O_RDONLY | os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode) or (key not in FILES and not _text(fd)): + os.close(fd) + raise LookupError(key) + return fd + + +def _text(fd) -> bool: + """Whether an open file reads as text: no NUL byte in its first ``SNIFF`` bytes. It is read from its start + again after.""" + try: + return b"\0" not in os.pread(fd, SNIFF, 0) + except OSError: + return False + + +def describe(key, records=()): + """(label, filename) of a key: a fixed record's, or a declared one's, its path in the trial.""" + if key in FILES: + return FILES[key] + label, path, _ = _declared(key, records) + return label, path def path_for(trial_dir, key): @@ -39,8 +140,58 @@ def path_for(trial_dir, key): return path -def listing(trial_dir): - records = [] +def _declared_rows(trial_dir, records): + """The declared records that exist: a file, or each file of a folder, by name, one level, no link; each row + says it is ``declared``.""" + rows = [] + for n, record in enumerate(records): + try: + fd = _open_under(trial_dir, record["path"], os.O_RDONLY | os.O_NONBLOCK) + except OSError: + continue + entries = None + try: + info = os.fstat(fd) + if stat.S_ISREG(info.st_mode): + if _text(fd): + rows.append(dict(key=f"r{n}", label=record["label"], filename=record["path"], part="", + exists=True, size=info.st_size, declared=True)) + elif stat.S_ISDIR(info.st_mode): + entries = os.scandir(fd) + names = (e.name for e in entries if e.is_file(follow_symlinks=False)) + first, more = len(rows), False + count = 0 + for name in names: + if not _plain_name(name): + continue + try: + one = os.open(name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, dir_fd=fd) + except OSError: + continue + try: + info = os.fstat(one) + if stat.S_ISREG(info.st_mode) and _text(one): + if count == FOLDER_FILES: + more = True + break + rows.append(dict(key=f"r{n}-{name}", label=record["label"], part=name, exists=True, + filename=f"{record['path']}/{name}", size=info.st_size, declared=True)) + count += 1 + finally: + os.close(one) + rows[first:] = sorted(rows[first:], key=lambda row: row["part"]) + if more: + rows[-1]["more"] = True + finally: + if entries is not None: + entries.close() + os.close(fd) + return rows + + +def listing(trial_dir, records=()): + """Every fixed record, said whether it exists, then the declared ones that exist.""" + out = [] for key, (label, filename) in FILES.items(): try: path = path_for(trial_dir, key) @@ -48,22 +199,22 @@ def listing(trial_dir): size = os.path.getsize(path) if exists else None except (OSError, LookupError): exists, size = False, None - records.append(dict(key=key, label=label, filename=filename, exists=exists, size=size)) - return records + out.append(dict(key=key, label=label, filename=filename, part="", exists=exists, size=size)) + return out + _declared_rows(trial_dir, records) -def whole(trial_dir, key): +def whole(trial_dir, key, records=()): """The record redacted, up to ``MAX_READ``, and whether it was cut there: what a download or a copy carries, never more than the reader shows.""" - path = path_for(trial_dir, key) - with open(path, encoding="utf-8", errors="replace") as handle: + fd = _open_record(trial_dir, key, records) + with open(fd, encoding="utf-8", errors="replace") as handle: raw = handle.read(MAX_READ + 1) return redact(raw[:MAX_READ]), len(raw) > MAX_READ -def read(trial_dir, key, page=1): +def read(trial_dir, key, page=1, records=()): # Redact before slicing so credentials cannot straddle visible chunks. - text, truncated = whole(trial_dir, key) + text, truncated = whole(trial_dir, key, records) pages = max(1, (len(text) + CHUNK_SIZE - 1) // CHUNK_SIZE) try: page = int(page) @@ -71,7 +222,8 @@ def read(trial_dir, key, page=1): page = 1 page = min(pages, max(1, page)) start = (page - 1) * CHUNK_SIZE - return dict(key=key, label=FILES[key][0], filename=FILES[key][1], page=page, + label, filename = describe(key, records) + return dict(key=key, label=label, filename=filename, page=page, pages=pages, text=text[start:start + CHUNK_SIZE], empty=not text, truncated=truncated, characters=len(text), start=start, end=min(start + CHUNK_SIZE, len(text))) diff --git a/app/nullius/runs/evidence.py b/app/nullius/runs/evidence.py new file mode 100644 index 00000000..a6a91f1b --- /dev/null +++ b/app/nullius/runs/evidence.py @@ -0,0 +1,74 @@ +"""What a benchmark recorded about a trial that fell short: the Failure analysis tab's rows. + +A benchmark's ``benchmark.json`` may name them (``evidence``), in order:: + + {"label": "Expected answer", + "path": "reward_info.reward", a dotted path in the score's detail; an object gives a row per plain value + "values": {"1.0": "Pass"}, a value as the page says it + "names": {"DB": "Database"}, an object's keys as the page says them + "unless": ["no"], values that say nothing: no row + "reply": true} the trial's last reply when the detail holds no such value + +An empty list shows nothing. A benchmark without the block shows its whole +detail (``parse.score_detail``).""" +from __future__ import annotations + +from nullius.redact import redact + +from . import parse + +_CACHE: dict = {} + + +def declared(source) -> list | None: + """The rows the benchmark of a trial's *source* names, or None when it names none.""" + from nullius.catalogue import catalog + sig = catalog.signature() + if _CACHE.get("sig") != sig: + table = {} + for b in catalog.load().benchmarks: + if isinstance(b.evidence, list): + rows = [r for r in b.evidence if catalog.valid_evidence(r)] + for name in [b.key, *b.datasets, *((b.report or {}).get("sources") or [])]: + table.setdefault(str(name).strip().lower(), rows) + _CACHE.update(sig=sig, table=table) + return _CACHE["table"].get((source or "").strip().lower()) + + +def _at(detail, path): + """(found, value) at a dotted path; a key may hold dots itself.""" + if not isinstance(detail, dict): + return False, None + if path in detail: + return True, detail[path] + for i, c in enumerate(path): + if c == "." and path[:i] in detail: + found, value = _at(detail[path[:i]], path[i + 1:]) + if found: + return True, value + return False, None + + +def rows(trial_dir: str, spec: list, reply: str = "") -> list: + """``{label, text}`` per row *spec* names that the trial's score has, redacted.""" + detail = parse.read_detail(trial_dir) or {} + out = [] + + def add(label, value, entry): + text = parse._shown(value) + if text not in entry.get("unless", ()): + out.append({"label": redact(str(label)), "text": redact(entry.get("values", {}).get(text, text))}) + + for entry in spec: + found, value = _at(detail, entry["path"]) + if not found and entry.get("reply") and reply: + found, value = True, reply + if not found: + continue + if isinstance(value, dict): + for key, v in value.items(): + if parse._plain(v): + add(entry.get("names", {}).get(key, key), v, entry) + else: + add(entry["label"], value, entry) + return out diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index 16fabbfa..1597a461 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -8,9 +8,12 @@ from __future__ import annotations import functools +import json import os import re import shlex +import stat +from contextlib import ExitStack from dataclasses import dataclass, field, replace from datetime import datetime, timezone @@ -72,6 +75,102 @@ def _retries_of(res: dict) -> int: return n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else 0 +SCORE_BYTES = 1024 * 1024 + + +def _read_score(trial_dir: str): + """Read at most SCORE_BYTES from a regular score file without following links inside the trial.""" + try: + with ExitStack() as opened: + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + trial = os.open(trial_dir, flags) + opened.callback(os.close, trial) + folder = os.open("verifier", flags, dir_fd=trial) + opened.callback(os.close, folder) + fd = os.open("score.json", os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) + opened.callback(os.close, fd) + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > SCORE_BYTES: + return None + raw = os.read(fd, SCORE_BYTES + 1) + return json.loads(raw) if 0 < len(raw) <= SCORE_BYTES else None + except (OSError, ValueError): + return None + + +# A value of a score's detail longer than this is cut on the trial's page, its whole text a click away +DETAIL_CELL = 200 + + +def _plain(value) -> bool: + return value is None or isinstance(value, (str, int, float, bool)) + + +def _shown(value) -> str: + """A value of a score's detail as the page writes it: text as written, a boolean as yes or no, none for null or + empty text, a list of plain values joined, anything deeper as its JSON.""" + if isinstance(value, bool): + return "yes" if value else "no" + if value is None or value == "": + return "none" + if isinstance(value, (str, int, float)): + return str(value) + if isinstance(value, list) and all(_plain(x) for x in value): + return ", ".join(_shown(x) for x in value) if value else "none" + return json.dumps(value, ensure_ascii=False) + + +def read_detail(trial_dir: str) -> dict | None: + """The detail beside a score's reward, redacted, or None.""" + said = _read_score(trial_dir) + detail = said.get("detail") if isinstance(said, dict) else None + return _options(detail) if isinstance(detail, dict) else None + + +def score_detail(trial_dir: str, leave_out=(), shown=None) -> dict | None: + """Redacted score evidence for display. Nested objects become named groups, + structured lists become numbered groups; no object is rendered as raw JSON. + ``leave_out`` excludes top-level metadata; ``shown`` suppresses duplicate numbers + by their full path. Long text keeps a preview and its full value.""" + detail = read_detail(trial_dir) + if detail is None: + return None + fields, groups = [], [] + + def cell(name, value): + text = redact(_shown(value)) + return {"name": redact(str(name)), "text": text, + "cut": text[:DETAIL_CELL] if len(text) > DETAIL_CELL else ""} + + def visit(values, path=""): + flags = [] + for name, value in values.items(): + full = f"{path}.{name}" if path else str(name) + if (not path and name in leave_out) or ( + isinstance(value, (int, float)) and not isinstance(value, bool) + and value in (shown or {}).get(full, ())): + continue + if isinstance(value, dict): + visit(value, full) + elif isinstance(value, list) and not all(_plain(x) for x in value): + visit({str(i + 1): x for i, x in enumerate(value)}, full) + elif path: + item = cell(name, value) + if not item["cut"]: + item.pop("cut") + item["held"] = value if isinstance(value, bool) else None + if isinstance(value, bool): + item["text"] = "" + flags.append(item) + else: + fields.append(cell(name, value)) + if flags: + groups.append({"name": redact(path), "flags": flags}) + + visit(detail) + return {"fields": fields, "groups": groups} if fields or groups else None + + def count_rate_limits(path: str) -> int | None: """Rate-limit records in a gateway log, or None when there is no log. diff --git a/app/static/traces/conversation.css b/app/static/traces/conversation.css index cd4ca46e..d7493bc6 100644 --- a/app/static/traces/conversation.css +++ b/app/static/traces/conversation.css @@ -66,3 +66,8 @@ .usage-tools-table{overflow-x:auto} #task-tools .tool-names td:first-child{white-space:normal;overflow-wrap:anywhere} @media(max-width:1000px){.task-activity{grid-template-columns:minmax(0,1fr)}} +/* Failure analysis: what the benchmark recorded */ +table.grid.trial-evidence{width:auto;max-width:100%} +#trial-evidence .test-list li{overflow-wrap:anywhere} +.trial-evidence td{vertical-align:top;white-space:normal;overflow-wrap:anywhere}.trial-evidence td.muted{overflow-wrap:normal} +.trial-evidence pre{margin:0} diff --git a/app/templates/traces/trial.html b/app/templates/traces/trial.html index 6762b2e3..1158dab0 100644 --- a/app/templates/traces/trial.html +++ b/app/templates/traces/trial.html @@ -64,32 +64,13 @@
{{ cells }}
{% endif %} +{% set fell_short = evidence or detail or trial.is_regression or trial.f2p_failures %}
-{% if trial.is_regression %} -
-

⚠ This patch broke {{ trial.p2p_fail }} previously-passing test{{ '' if trial.p2p_fail == 1 else 's' }}

-

These passed before the patch was applied and fail after it — a - regression, not just a missed fix.

-
    - {% for name in trial.p2p_failures %}
  • {{ name }}
  • {% endfor %} -
-
-{% endif %} - -{% if trial.f2p_failures %} -
-

Tests that had to pass, still failing

-
    - {% for name in trial.f2p_failures %}
  • {{ name }}
  • {% endfor %} -
-
-{% endif %} - {% if trial.exception_type %}

{{ trial.exception_type }}

@@ -230,6 +211,42 @@

{{ job.runner }}'s score gives the {% if failure is not none %}
{% include "traces/_failure.html" %}
{% endif %} +{# What the benchmark recorded of a trial that fell short: its named rows, else its whole detail. #} +{% macro recorded(text) %}{% if '\n' in text or text|length > 200 %}
{{ text }}
{% else %}{{ text }}{% endif %}{% endmacro %} +{% if fell_short %}
+{% if trial.is_regression %} +
+

⚠ This patch broke {{ trial.p2p_fail }} previously-passing test{{ '' if trial.p2p_fail == 1 else 's' }}

+

These passed before the patch was applied and fail after it — a + regression, not just a missed fix.

+
    + {% for name in trial.p2p_failures %}
  • {{ name }}
  • {% endfor %} +
+
+{% endif %} + +{% if trial.f2p_failures %} +
+

Tests that had to pass, still failing

+
    + {% for name in trial.f2p_failures %}
  • {{ name }}
  • {% endfor %} +
+
+{% endif %} +{% if evidence or (detail and detail.fields) %} + {% for r in evidence %} + {% endfor %} + {% for f in (detail.fields if detail else []) %} + {% endfor %} +
{{ r.label }}{{ recorded(r.text) }}
{{ f.name[:1]|upper }}{{ f.name[1:]|replace("_", " ") }}{{ recorded(f.text) }}
{% endif %} +{% if detail %}{% for g in detail.groups %} +

{{ g.name|replace("_", " ")|replace(".", " / ") }}

+
    + {% for x in g.flags %}
  • {% if x.held is sameas true %}✓{% elif x.held is sameas false %}×{% else %}·{% endif %} {{ x.name|replace("_", " ") }}{% if x.text %}: {% if x.cut %}
    {{ x.cut }}…{{ x.text }}
    {% else %}{{ x.text }}{% endif %}{% endif %}
  • + {% endfor %} +
+{% endfor %}{% endif %} +
{% endif %}
{# The task's instruction, scored on its own text: once per dataset and task, the same for every attempt, nothing of any run read. The score changes no outcome. #} @@ -567,9 +584,13 @@

Waterfall

{% if artifacts %}
+ {#- the benchmark's own records, after Nullius's, under one heading row #} + {% set seen = namespace(declared=false) %} {% for artifact in artifacts %} - + {% if artifact.declared and not seen.declared %}{% set seen.declared = true %}{% endif %} + + {% if artifact.more %}{% endif %} {% endfor %}
RecordSize
{{ artifact.label }}{{ '%.2f'|format(artifact.size / 1024) }} KB
The benchmark's own records
{{ artifact.label }}{% if artifact.part %} {{ artifact.part }}{% endif %}{{ '%.2f'|format(artifact.size / 1024) }} KB ReadDownload
More records in {{ artifact.label }}.
diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index b811ae52..39c6dd85 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -91,6 +91,7 @@ "citation_source", "datasets", "domain", + "evidence", "good_to_know", "harness", "key", @@ -98,6 +99,7 @@ "limitations", "origin", "published", + "records", "report", "route_case", "routes", @@ -151,8 +153,10 @@ "y2" ], "Metric": [ + "bounds", "fmt", "label", + "size", "values" ], "Panel": [ diff --git a/app/tests/test_artifacts.py b/app/tests/test_artifacts.py index d40e68d6..018c0a97 100644 --- a/app/tests/test_artifacts.py +++ b/app/tests/test_artifacts.py @@ -1,9 +1,14 @@ """Evidence views are bounded, redacted, and confined to named trial files.""" import json +import os +import subprocess +import sys import tempfile import unittest from pathlib import Path +from unittest import mock +from nullius.catalogue import catalog from nullius.runs import artifacts @@ -79,5 +84,178 @@ def test_the_artifact_manifest_is_listed_and_read_redacted(self): artifacts.read(self.trial, "artifacts/manifest.json") +class DeclaredRecords(unittest.TestCase): + """A benchmark's own records, as its benchmark.json declares them: listed after Nullius's when they exist, + read like them, and never a way out of the trial.""" + + RECORDS = [{"label": "The summary", "path": "verifier/own/out.json"}, {"label": "Its folder", "path": "verifier/own"}, + {"label": "Never written", "path": "verifier/later.txt"}] + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.trial = Path(self.tmp.name) / "trial" + (self.trial / "verifier" / "own").mkdir(parents=True) + (self.trial / "verifier" / "own" / "out.json").write_text('{"rank": 7}') + (self.trial / "verifier" / "own" / "events.jsonl").write_text("a\nb\n") + (self.trial / "verifier" / "own" / "deeper").mkdir() + self.outside = Path(self.tmp.name) / "outside.txt" + self.outside.write_text("not of the trial") + + def own(self): + return [r for r in artifacts.listing(self.trial, self.RECORDS) if r["key"] not in artifacts.FILES] + + def test_the_files_and_a_folders_files_are_listed_after_nullius_s_and_read_like_them(self): + rows = artifacts.listing(self.trial, self.RECORDS) + self.assertEqual([r["key"] for r in rows[:len(artifacts.FILES)]], list(artifacts.FILES)) + self.assertEqual([(r["key"], r["label"], r["part"], r["filename"], r["size"]) for r in self.own()], [ + ("r0", "The summary", "", "verifier/own/out.json", 11), + ("r1-events.jsonl", "Its folder", "events.jsonl", "verifier/own/events.jsonl", 4), + ("r1-out.json", "Its folder", "out.json", "verifier/own/out.json", 11)]) + page = artifacts.read(self.trial, "r1-events.jsonl", 1, self.RECORDS) + self.assertEqual((page["label"], page["filename"], page["text"]), ("Its folder: events.jsonl", "verifier/own/events.jsonl", "a\nb\n")) + self.assertEqual(artifacts.whole(self.trial, "r0", self.RECORDS), ('{"rank": 7}', False)) + self.assertEqual(artifacts.describe("r0", self.RECORDS), ("The summary", "verifier/own/out.json")) + + def test_a_declared_record_is_redacted_as_the_others_are(self): + (self.trial / "verifier" / "own" / "out.json").write_text("key sk-abcdefgh12345") + self.assertNotIn("abcdefgh", artifacts.read(self.trial, "r0", 1, self.RECORDS)["text"]) + + def test_no_key_leaves_the_record_or_the_list(self): + for key in ("r1-..", "r1-.", "r1-../own/out.json", "r1-deeper", "r3", "r9", "r01", "r0-x", "r", "verifier/own/out.json"): + with self.subTest(key=key), self.assertRaises((LookupError, OSError)): + artifacts.read(self.trial, key, 1, self.RECORDS) + with self.assertRaises(LookupError): + artifacts.read(self.trial, "r0") # no record declared: no key of one + + def test_a_link_anywhere_on_the_way_is_not_followed(self): + own = self.trial / "verifier" / "own" + (own / "linked.txt").symlink_to(self.outside) + (own / "inside.txt").symlink_to(own / "out.json") + self.assertEqual([r["part"] for r in self.own()], ["", "events.jsonl", "out.json"]) + for key in ("r1-linked.txt", "r1-inside.txt"): + with self.subTest(key=key), self.assertRaises(OSError): + artifacts.read(self.trial, key, 1, self.RECORDS) + (own / "out.json").unlink() + (own / "out.json").symlink_to(self.outside) + self.assertEqual([r["key"] for r in self.own()], ["r1-events.jsonl"]) + with self.assertRaises(OSError): + artifacts.whole(self.trial, "r0", self.RECORDS) + elsewhere = Path(self.tmp.name) / "elsewhere" + (self.trial / "verifier").rename(elsewhere) + (self.trial / "verifier").symlink_to(elsewhere) # the verifier folder itself a link + self.assertEqual(self.own(), []) + with self.assertRaises(OSError): + artifacts.whole(self.trial, "r1-events.jsonl", self.RECORDS) + + def test_a_pipe_is_neither_listed_nor_waited_on(self): + os.mkfifo(self.trial / "verifier" / "own" / "pipe") + records = self.RECORDS + [{"label": "A pipe", "path": "verifier/own/pipe"}] + self.assertNotIn("r1-pipe", [r["key"] for r in artifacts.listing(self.trial, records)]) + self.assertNotIn("r3", [r["key"] for r in artifacts.listing(self.trial, records)]) + got = subprocess.run([sys.executable, "-c", "import sys; from nullius.runs import artifacts\n" + "try:\n artifacts.whole(sys.argv[1], 'r0', [{'label': 'p', 'path': 'verifier/own/pipe'}])\n" + "except LookupError:\n print('refused')", str(self.trial)], + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=5, + env=dict(os.environ, PYTHONPATH=str(Path(artifacts.__file__).parents[2]))) + self.assertEqual(got.stdout.strip(), "refused", got.stderr) + + def test_a_file_that_is_not_text_is_neither_listed_nor_read(self): + own = self.trial / "verifier" / "own" + (own / "packed.zip").write_bytes(b"PK\x03\x04" + b"\0" * 32) + (own / "late.bin").write_bytes(b"x" * artifacts.SNIFF + b"\0") # a NUL past the look: read as text + records = self.RECORDS + [{"label": "Packed", "path": "verifier/own/packed.zip"}] + keys = [r["key"] for r in artifacts.listing(self.trial, records)] + self.assertNotIn("r1-packed.zip", keys) + self.assertNotIn("r3", keys) + self.assertIn("r1-late.bin", keys) + for key in ("r1-packed.zip", "r3"): + with self.subTest(key=key), self.assertRaises(LookupError): + artifacts.whole(self.trial, key, records) + self.assertEqual(artifacts.whole(self.trial, "r1-out.json", records), ('{"rank": 7}', False)) + + def test_a_name_that_is_not_printable_or_not_utf8_is_neither_listed_nor_read(self): + own = os.fsencode(self.trial / "verifier" / "own") + for name in (b"bad-\xff.txt", b"two\nlines.txt", b"tab\there.txt"): + with open(os.path.join(own, name), "w") as f: + f.write("x\n") + keys = [r["key"] for r in self.own()] + self.assertEqual(keys, ["r0", "r1-events.jsonl", "r1-out.json"]) + for name in ("bad-\udcff.txt", "two\nlines.txt", "tab\there.txt"): + with self.subTest(name=name), self.assertRaises(LookupError): + artifacts.whole(self.trial, f"r1-{name}", self.RECORDS) + + def test_a_folder_lists_at_most_its_bound(self): + for i in range(5): + (self.trial / "verifier" / "own" / f"f{i}.txt").write_text("x") + with mock.patch.object(artifacts, "FOLDER_FILES", 3): + rows = self.own() + self.assertEqual(len(rows), 4) + self.assertEqual(rows[0]["part"], "") + self.assertEqual([r["part"] for r in rows[1:]], sorted(r["part"] for r in rows[1:])) + + def test_binary_files_do_not_use_the_text_record_allowance(self): + own = self.trial / "verifier" / "own" + for i in range(artifacts.FOLDER_FILES): + (own / f"image-{i:04d}.png").write_bytes(b"PNG\0") + self.assertIn("r1-out.json", [r["key"] for r in self.own()]) + + def test_a_folder_says_when_more_text_records_exist(self): + with mock.patch.object(artifacts, "FOLDER_FILES", 1): + rows = self.own() + self.assertEqual(len(rows), 2) + self.assertTrue(rows[-1].get("more")) + self.assertFalse(any(r.get("more") for r in self.own())) + (self.trial / "verifier" / "own" / "packed.bin").write_bytes(b"\0") + with mock.patch.object(artifacts, "FOLDER_FILES", 2): + self.assertFalse(any(r.get("more") for r in self.own())) + + def test_folder_scanning_stops_after_one_extra_text_record(self): + own = self.trial / "verifier" / "own" + for i in range(5): + (own / f"file-{i}.txt").write_text("x") + with os.scandir(own) as entries: + files = [e for e in entries if e.is_file()] + + def bounded(): + yield from files[:4] + self.fail("the scan passed the first extra text record") + + scan = mock.MagicMock() + scan.__enter__.return_value = scan + scan.__iter__.side_effect = bounded + with mock.patch.object(artifacts, "FOLDER_FILES", 3), \ + mock.patch.object(artifacts.os, "scandir", return_value=scan): + rows = self.own()[1:] + self.assertEqual([r["part"] for r in rows], sorted(e.name for e in files[:3])) + self.assertTrue(rows[-1].get("more")) + + def test_the_benchmark_is_found_by_its_key_its_datasets_and_its_report_sources(self): + good = {"label": " Its summary ", "path": "verifier/own/out.json"} + bench = catalog.Benchmark(key="bench", title="B", datasets=["bench-small"], report={"sources": ["Bench-Harbor"]}, + records=[good, {"label": "", "path": "verifier/x"}]) + other = catalog.Benchmark(key="other", title="O") + with mock.patch.object(catalog, "load", return_value=catalog.Catalog([bench, other], [])), \ + mock.patch.object(catalog, "signature", return_value=("declared-test",)): + for source in ("bench", "bench-small", "bench-harbor", " BENCH "): + with self.subTest(source=source): + self.assertEqual(artifacts.declared(source), [{"label": "Its summary", "path": "verifier/own/out.json"}]) + for source in ("other", "", None): + with self.subTest(source=source): + self.assertEqual(artifacts.declared(source), []) + + def test_the_catalogue_takes_only_a_label_and_a_path_under_verifier(self): + for path in ("verifier/a", "verifier/a/b.json"): + self.assertTrue(catalog.valid_record({"label": "A", "path": path}), path) + for record in ({"label": "A", "path": p} for p in ("verifier", "verifier/", "verifier/../x", "verifier/./x", + "verifier//x", "/verifier/x", "agent/x", "verifier\\x", + "../verifier/x", 3)): + self.assertFalse(catalog.valid_record(record), record) + for record in ({"path": "verifier/x"}, {"label": " ", "path": "verifier/x"}, "verifier/x"): + self.assertFalse(catalog.valid_record(record), record) + bench = catalog.Benchmark(key="bench", title="B", category="C", records=[{"label": "A", "path": "verifier/../x"}]) + self.assertIn("bench: records are each {label, path under verifier/}", catalog.validate(catalog.Catalog([bench], []))) + + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_evidence.py b/app/tests/test_evidence.py new file mode 100644 index 00000000..91e17ae8 --- /dev/null +++ b/app/tests/test_evidence.py @@ -0,0 +1,52 @@ +"""The rows a benchmark names for a trial that fell short (``nullius.runs.evidence``).""" +from __future__ import annotations + +import json +import os +import tempfile +import unittest + +from nullius.catalogue import catalog +from nullius.runs import evidence + + +class Evidence(unittest.TestCase): + def rows(self, detail, *spec, reply=""): + with tempfile.TemporaryDirectory() as d: + os.makedirs(os.path.join(d, "verifier")) + with open(os.path.join(d, "verifier", "score.json"), "w") as f: + json.dump({"detail": detail}, f) + return [(r["label"], r["text"]) for r in evidence.rows(d, list(spec), reply)] + + def test_paths_reach_nested_values_and_keys_that_hold_dots(self): + detail = {"a": {"b.c": 1}, "solution.py": "x", "gone": None} + got = self.rows(detail, *({"label": p, "path": p} for p in ("a.b.c", "solution.py", "gone", "missing", "a.z"))) + self.assertEqual(got, [("a.b.c", "1"), ("solution.py", "x"), ("gone", "none")]) + + def test_an_object_is_a_row_per_plain_value_under_its_names(self): + got = self.rows({"basis": {"DB": 1.0, "OTHER": 0.0, "deep": {}}}, { + "label": "Checks", "path": "basis", "names": {"DB": "Database"}, "values": {"1.0": "Pass", "0.0": "Fail"}}) + self.assertEqual(got, [("Database", "Pass"), ("OTHER", "Fail")]) + + def test_values_that_say_nothing_have_no_row(self): + spec = {"label": "Timed out", "path": "t", "unless": ["no"]} + self.assertEqual(self.rows({"t": False}, spec), []) + self.assertEqual(self.rows({"t": True}, spec), [("Timed out", "yes")]) + + def test_the_reply_stands_in_only_when_nothing_is_recorded_and_is_redacted(self): + spec = {"label": "Answer", "path": "answer", "reply": True} + self.assertEqual(self.rows({"answer": "said"}, spec, reply="other"), [("Answer", "said")]) + self.assertEqual(self.rows({}, spec), []) + key = "sk-" + "a1B2c3D4e5F6g7H8i9J0" * 2 + self.assertNotIn(key, str(self.rows({}, spec, reply=key))) + self.assertNotIn("hunter2hunter2", str(self.rows({"password": "hunter2hunter2"}, {"label": "P", "path": "password"}))) + + def test_the_catalogue_refuses_a_malformed_row(self): + for rows in ({}, [{"label": "A"}], [{"label": "A", "path": "a", "values": {"x": 1}}], [{"label": "A", "path": "a", "odd": 1}]): + with self.subTest(rows=rows): + bench = catalog.Benchmark(key="bench", title="B", category="C", evidence=rows) + self.assertTrue(any("evidence rows" in m for m in catalog.validate(catalog.Catalog([bench], [])))) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_score_detail.py b/app/tests/test_score_detail.py new file mode 100644 index 00000000..08a98f30 --- /dev/null +++ b/app/tests/test_score_detail.py @@ -0,0 +1,103 @@ +"""A standard trial's detail as its page shows it (``parse.score_detail``): the driver's plain values with their +names and nested evidence as groups, without benchmark-specific parsing.""" +from __future__ import annotations + +import json +import os +import shutil +import tempfile +import unittest + +from nullius.runs import parse + + +class ScoreDetail(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True) + os.makedirs(os.path.join(self.dir, "verifier")) + + def detail(self, detail, leave_out=(), shown=None): + with open(os.path.join(self.dir, "verifier", "score.json"), "w") as f: + json.dump({"reward": 0.0, "detail": detail}, f) + return parse.score_detail(self.dir, leave_out, shown) + + def test_plain_values_keep_their_names_and_order_and_read_as_written(self): + got = self.detail({"zeta": "as written", "count": 3, "share": 0.45, "seen": True, "missed": False, "gone": None, + "names": ["a", 2, None], "empty": [], "blank": ""}) + self.assertEqual([(f["name"], f["text"]) for f in got["fields"]], + [("zeta", "as written"), ("count", "3"), ("share", "0.45"), ("seen", "yes"), ("missed", "no"), + ("gone", "none"), ("names", "a, 2, none"), ("empty", "none"), ("blank", "none")]) + self.assertEqual(got["groups"], []) + + def test_an_object_of_plain_values_is_a_list_of_flags(self): + got = self.detail({"first": 1, "checks": {"b": True, "a": False, "c": "not taken", "d": None}}) + self.assertEqual([f["name"] for f in got["fields"]], ["first"]) + self.assertEqual(got["groups"], [{"name": "checks", "flags": [ + {"name": "b", "held": True, "text": ""}, {"name": "a", "held": False, "text": ""}, + {"name": "c", "held": None, "text": "not taken"}, {"name": "d", "held": None, "text": "none"}]}]) + + def test_nested_objects_and_structured_lists_are_groups_and_long_text_is_cut(self): + deep = {"inner": {"list": [1, {"x": 2}]}} + got = self.detail({"deep": deep, "rows": [{"kind": "front"}], "long": "x" * (parse.DETAIL_CELL + 1), + "short": "y" * parse.DETAIL_CELL, "nothing": {}}) + cells = {f["name"]: f for f in got["fields"]} + groups = {g["name"]: g["flags"] for g in got["groups"]} + self.assertEqual(groups["deep.inner.list.2"], [{"name": "x", "text": "2", "held": None}]) + self.assertEqual(groups["deep.inner.list"], [{"name": "1", "text": "1", "held": None}]) + self.assertEqual(groups["rows.1"], [{"name": "kind", "text": "front", "held": None}]) + self.assertEqual((cells["long"]["text"], cells["long"]["cut"]), ("x" * (parse.DETAIL_CELL + 1), "x" * parse.DETAIL_CELL)) + self.assertEqual(cells["short"]["cut"], "") + self.assertNotIn("nothing", cells) + + def test_the_names_the_page_shows_elsewhere_are_left_out(self): + got = self.detail({"steps": 3, "steps_limit": 10, "ended": "done", "rank": 7}, ("steps", "steps_limit", "ended")) + self.assertEqual([f["name"] for f in got["fields"]], ["rank"]) + self.assertIsNone(self.detail({"steps": 3}, ("steps",))) + shown = {"result": [1.0], "steps": [2]} # the numbers the page shows above + got = self.detail({"result": 1.0, "steps": 2, "rank": 7}, shown=shown) + self.assertEqual([f["name"] for f in got["fields"]], ["rank"]) + for said in ("failed: AssertionError", True, None, 0.0): # text, or a number not shown, stays + with self.subTest(result=said): + got = self.detail({"result": said, "steps": 15}, shown=shown) + self.assertEqual([f["name"] for f in got["fields"]], ["result", "steps"]) + + def test_a_long_nonboolean_flag_has_a_preview_and_full_redacted_text(self): + secret = "sk-" + "example123456789012345" + text = "x" * 100_000 + " " + secret + flag = self.detail({"flags": {"explanation": text}})["groups"][0]["flags"][0] + self.assertEqual(flag.get("cut"), "x" * parse.DETAIL_CELL) + self.assertEqual(flag["text"], "x" * 100_000 + " [REDACTED]") + self.assertIsNone(flag["held"]) + + def test_no_detail_no_view(self): + for detail in (None, {}, [1, 2], "said"): + with self.subTest(detail=detail): + self.assertIsNone(self.detail(detail)) + os.remove(os.path.join(self.dir, "verifier", "score.json")) + self.assertIsNone(parse.score_detail(self.dir)) + + def test_a_linked_score_is_not_read(self): + outside = os.path.join(self.dir, "outside.json") + with open(outside, "w") as f: + json.dump({"detail": {"rank": 1}}, f) + os.symlink(outside, os.path.join(self.dir, "verifier", "score.json")) + self.assertIsNone(parse.score_detail(self.dir)) + + def test_credentials_are_redacted_by_shape_and_scrubbed_by_name_at_every_displayed_depth(self): + key = "sk-" + "a1B2c3D4e5F6g7H8i9J0" * 2 + self.assertNotIn(key, json.dumps(self.detail({"said": f"the key {key}", "flags": {key: True}}))) + hidden = "example12345678901234567890" + for detail in ({"api_key": hidden}, {"credentials": {"password": hidden}}, + {"flags": {"password": hidden, "held": True}}, + {"deep": {"inner": {"Authorization": hidden}}}, + {"rows": [{"access_token": hidden}]}, {"secret": [hidden]}): + with self.subTest(detail=detail): + self.assertNotIn(hidden, json.dumps(self.detail(detail))) + got = self.detail({"input_tokens": 12, "flags": {"token_count": 4, "held": True}}) + self.assertEqual(got["fields"][0]["text"], "12") + self.assertEqual(got["groups"][0]["flags"][0]["text"], "4") + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_trial_detail.py b/app/ui_tests/test_trial_detail.py new file mode 100644 index 00000000..950a1e40 --- /dev/null +++ b/app/ui_tests/test_trial_detail.py @@ -0,0 +1,175 @@ +"""Trial evidence renders as escaped, redacted fields and nested groups, without +execution metadata or duplicate scores. Fixtures never execute a benchmark.""" +from __future__ import annotations + +import json +import os +import re +import shutil +import tempfile +import unittest +from contextlib import ExitStack +from html import unescape +from unittest.mock import patch + +from nullius.runs import parse +from .test_routes import APP_DIR, web + +NATIVE = APP_DIR / "tests" / "fixtures" / "native" + + +def text_of(html): + return " ".join(unescape(re.sub(r"<[^>]+>", " ", html)).split()) + + +class TrialDetail(unittest.TestCase): + def setUp(self): + self.stack = ExitStack() + self.addCleanup(self.stack.close) + self.stack.enter_context(patch.dict(web.app.config, TESTING=True)) + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = os.path.join(tmp.name, "parts-arm") + shutil.copytree(NATIVE / "parts-arm", self.root) + self.client = web.app.test_client() + + def page(self, detail, standard=None, score=None, source=None, reward=None): + """The trial page's HTML with ``detail`` as t1's score's detail; ``standard``, its record's standard block.""" + with open(os.path.join(self.root, "t1", "verifier", "score.json"), "w") as f: + json.dump({"reward": 0.0, "detail": detail}, f) + if score is not None or source is not None or reward is not None: + at = os.path.join(self.root, "t1", "result.json") + with open(at) as f: + res = json.load(f) + if source is not None: + res["source"] = source + if score is not None or reward is not None: + res["verifier_result"] = {"rewards": {"score": score} if reward is None else {"reward": reward}} + if reward is not None: + with open(os.path.join(self.root, "t1", "verifier", "reward.txt"), "w") as f: + f.write(str(reward)) + with open(at, "w") as f: + json.dump(res, f) + if standard is not None: + at = os.path.join(self.root, "t1", "result.json") + with open(at) as f: + res = json.load(f) + with open(at, "w") as f: + json.dump(dict(res, standard=standard), f) + job = parse.parse_job(self.root) + with patch.object(web.shared, "_jobs_for_request", return_value=[job]): + response = self.client.get(f"/trial/{job.job_id}/t1") + self.addCleanup(response.close) + self.assertEqual(response.status_code, 200) + return response.get_data(as_text=True) + + def panel(self, html): + self.assertIn('id="tab-evidence"', html) + return html.split('id="trial-evidence"', 1)[1].split('>', 1)[1].split('
', 1)[0] + + def test_plain_values_are_a_table_and_flags_a_list_under_the_drivers_names(self): + html = self.panel(self.page({"variant": "the second", "result": 0.5, "by": "run.py, evaluate", "tool_calls": 21, + "steps": 2, "score": 0.5, "rank": 42, "cached": False, + "checks": {"saved": True, "closed": False}, "notes": {"cursor": "not taken"}})) + said = text_of(html) + self.assertIn("Variant the second Rank 42 Cached no", said) # nothing the page says elsewhere + self.assertNotIn("tool_calls", said); self.assertNotIn("run.py", said) + self.assertIn("Result timed out Steps 15 Score 0.25", # text, or a number the head does not show + text_of(self.panel(self.page({"result": "timed out", "steps": 15, "score": 0.25})))) + self.assertIn("checks ✓ saved × closed notes · cursor: not taken", said) + self.assertRegex(html, r'✓ saved') + self.assertRegex(html, r'× closed') + lists = re.findall(r"]*>", html) + self.assertEqual(len(lists), 2) + for ul in lists: # each flag's mark is its only one: no bullet before it + self.assertIn("list-style:none", ul) + + def test_nested_scoring_evidence_excludes_configuration_and_duplicate_reward(self): + detail = {"domain": "airline", "termination": "user_stop", "tool_errors": 0, + "evaluation": "all", "max_steps": 200, "max_errors": 10, "seed": 626729, + "trial": 0, "split": "base", "attempts": 1, + "reward_info": {"reward": 0.5, "db_check": {"db_match": True, "db_reward": 1.0}, + "reward_breakdown": {"DB": 1.0, "COMMUNICATE": 0.0}}} + html = self.panel(self.page(detail)) + said = text_of(html) + for name in ("evaluation", "max steps", "max errors", "seed", "trial", "split", "attempts"): + self.assertNotIn(name, said) + self.assertIn("Domain airline Termination user_stop Tool errors 0", said) + self.assertIn("reward info / db check ✓ db match", said) + self.assertIn("COMMUNICATE: 0.0", said) + self.assertNotIn("0.5", said) + self.assertNotIn("{", said) + self.assertNotIn(""", html) + + def test_a_long_value_is_whole_in_a_block_and_a_long_flag_is_behind_a_disclosure(self): + long, text = "word " * 60, "x" * 100_000 + "" + html = self.panel(self.page({"why": long, "flags": {"explanation": text}})) + self.assertIn(f'
{long}
', html) + self.assertIn(f'
{text[:parse.DETAIL_CELL]}…' + + "x" * 100_000 + "<end>
", html) + self.assertNotIn("

", 1)[0] + self.assertIn("The task's text", tab.replace("'", "'")) + self.assertIn('Its folder brief.md', tab) + self.assertIn('Its folder <i>odd<i>.log', tab) + self.assertNotIn("odd", tab) + self.assertIn(f"/trial/{self.job.job_id}/t1/artifact/r0", tab) + self.assertIn(f"/trial/{self.job.job_id}/t1/artifact/r1-brief.md/download", tab) + head = 'The benchmark\'s own records' + self.assertEqual(tab.replace("'", "'").count(head), 1) # one heading, between Nullius's and its own + before, after = tab.replace("'", "'").split(head) + self.assertIn("Result record", before) + self.assertNotIn("Its folder", before) + self.assertIn("The task's text", after.replace("'", "'")) + + def test_the_tab_says_when_a_folder_has_more_records(self): + path = f"/trial/{self.job.job_id}/t1" + with patch.object(artifacts, "FOLDER_FILES", 1): + html = self.get(path).get_data(as_text=True) + tab = html.split('id="trial-artifacts"', 1)[1].split("", 1)[0] + self.assertIn("More records in Its folder.", tab) + self.assertNotIn("More records in", self.get(path).get_data(as_text=True)) + with patch.object(artifacts, "declared", return_value=[]): + plain = self.get(path).get_data(as_text=True) + self.assertNotIn("More records in", plain) + self.assertNotIn("Its folder", plain) + + def test_a_declared_record_is_read_and_downloaded_by_its_key(self): + page = self.get(f"/trial/{self.job.job_id}/t1/artifact/r1-brief.md") + self.assertEqual(page.status_code, 200) + html = page.get_data(as_text=True) + self.assertIn("verifier/own/brief.md", html) + self.assertIn("Its folder: brief.md", html) # a folder's file under its own name + self.assertIn("Set the field, then press Apply.", html) + got = self.get(f"/trial/{self.job.job_id}/t1/artifact/r0/download") + self.assertEqual((got.status_code, got.headers["Content-Disposition"]), (200, 'attachment; filename="brief.md"')) + self.assertEqual(got.get_data(as_text=True), "Set the field, then press Apply.\n") + + def test_download_names_are_quoted_without_controls_and_keep_unicode(self): + for name, clean in [('a"quoted\\name.txt', 'a"quoted\\name.txt'), + ('résumé-文件.txt', 'résumé-文件.txt')]: + with self.subTest(name=name): + with open(os.path.join(self.root, "t1", "verifier", "own", name), "w") as handle: + handle.write("record") + response = self.get(f"/trial/{self.job.job_id}/t1/artifact/{quote('r1-' + name, safe='')}/download") + self.assertEqual(response.status_code, 200) + header = response.headers["Content-Disposition"] + self.assertTrue(header.startswith('attachment; filename="')) + self.assertFalse(any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in header)) + self.assertEqual(parse_options_header(header), ("attachment", {"filename": clean})) + if not clean.isascii(): + self.assertIn("filename*=UTF-8''", header) + self.assertTrue(header.isascii()) + self.assertEqual(response.get_data(as_text=True), "record") + + def test_a_key_outside_the_declaration_or_of_a_name_not_printable_is_not_found(self): + own = os.fsencode(os.path.join(self.root, "t1", "verifier", "own")) + for name in (b"bad-\xff.txt", b"line\nbreak\r\t\x01\x7f\x85.txt"): + with open(os.path.join(own, name), "w") as handle: + handle.write("record") + page = self.get(f"/trial/{self.job.job_id}/t1") + self.assertEqual(page.status_code, 200) + tab = page.get_data(as_text=True).split('id="trial-artifacts"', 1)[1].split("</section>", 1)[0] + self.assertIn("/artifact/r1-brief.md", tab) + self.assertNotIn("/artifact/r1-bad", tab) # a name not printable, or not UTF-8, is left out + self.assertNotIn("/artifact/r1-line", tab) + for key in ("r2", "r1-..", "r1-%2E%2E", "r1-missing.md", + quote(b"r1-bad-\xff.txt"), quote("r1-line\nbreak\r\t\x01\x7f\x85.txt", safe="")): + with self.subTest(key=key): + self.assertEqual(self.get(f"/trial/{self.job.job_id}/t1/artifact/{key}").status_code, 404) + self.assertEqual(self.get(f"/trial/{self.job.job_id}/t1/artifact/{key}/download").status_code, 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/web/traces.py b/app/web/traces.py index 6d2e809c..ee9159db 100644 --- a/app/web/traces.py +++ b/app/web/traces.py @@ -6,11 +6,14 @@ import os import re import threading +import unicodedata from collections import OrderedDict +from urllib.parse import quote 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.runs import artifacts, attempts as task_attempts, parse +from nullius.runs import artifacts, attempts as task_attempts, evidence, parse from nullius import importers as harnesses from .core import app @@ -172,7 +175,7 @@ def _parsed_trace(path, filt): def artifact_page(job_id, trial_name, key): job, trial = _trial_evidence(job_id, trial_name, tries=True) try: - record = artifacts.read(trial.dir, key, request.args.get("page", 1)) + record = artifacts.read(trial.dir, key, request.args.get("page", 1), artifacts.declared(trial.source)) except (LookupError, OSError): abort(404) response = app.make_response(render_template("traces/artifact.html", job=job, trial=trial, @@ -187,17 +190,22 @@ def artifact_download(job_id, trial_name, key): and Copy puts on the clipboard. One past the reader's limit is cut there, as its page says, and saved under a name that says so.""" _, trial = _trial_evidence(job_id, trial_name, tries=True) + declared = artifacts.declared(trial.source) try: - text, truncated = artifacts.whole(trial.dir, key) + text, truncated = artifacts.whole(trial.dir, key, declared) except (LookupError, OSError): abort(404) - name = os.path.basename(artifacts.FILES[key][1]) + name = re.sub(r"[\x00-\x1f\x7f-\x9f]", "", os.path.basename(artifacts.describe(key, declared)[1])) if truncated: stem, ext = os.path.splitext(name) name = f"{stem}.partial{ext}" response = app.response_class(text, mimetype="application/json" if name.endswith(".json") else "text/plain") if not request.args.get("inline"): - response.headers["Content-Disposition"] = f'attachment; filename="{name}"' + fallback = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode("ascii") + disposition = f'attachment; filename={quote_header_value(fallback, allow_token=False)}' + if not name.isascii(): + disposition += "; filename*=UTF-8''" + quote(name, safe="") + response.headers["Content-Disposition"] = disposition response.headers["Cache-Control"] = "no-store" response.headers["X-Content-Type-Options"] = "nosniff" # a run's own text, shown as text whatever it holds return response @@ -264,6 +272,17 @@ def trial(job_id, trial_name): bench_parts["shows"] = list(dict.fromkeys(k for x in bench_parts["parts"] if isinstance(x.get("shows"), dict) for k in x["shows"])) except (OSError, ValueError): pass + # What the benchmark recorded of a trial that fell short: the rows its entry names, else its whole detail, + # excluding execution metadata and numbers already shown above. + short = bool(j.runner) and t.outcome != "resolved" and not (t.score is not None and t.score >= 1) + named = evidence.declared(t.source) + head = [x for x in (t.reward, t.score) if x is not None] + shown = {"result": head, "score": head, "reward_info.reward": head, "steps": [traj.n_steps] if ok else []} + detail = parse.score_detail(t.dir, leave_out=("by", "tool_calls", "max_steps", "max_errors", + "seed", "trial", "split", "attempts", "agent", "judge", "evaluation"), + shown=shown) if short and named is None else None + reply = next((s.message for s in reversed(traj.steps) if s.source == "agent" and s.message), "") if ok else "" + rows = evidence.rows(t.dir, named, reply) if short and named else [] loc = _gold_localization(j, t, traj) if ok else None # `trace` opens a @@ -275,14 +294,15 @@ def trial(job_id, trial_name): # filtered view by construction, so there is one definition of "which spans # are in this view" and it is still the query string. ch = charts.charts_for(tr.roots, cfilt) if tr and tr.visible else None - records = [r for r in artifacts.listing(t.dir) if r["exists"]] # a record never written has no row + # a record never written has no row; the benchmark's own declared records after Nullius's + records = [r for r in artifacts.listing(t.dir, artifacts.declared(t.source)) if r["exists"]] for record in records: record["url"] = url_for("artifact_page", job_id=job_id, trial_name=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")) return render_template( - "traces/trial.html", job=j, trial=t, traj=traj, loc=loc, bench_parts=bench_parts, + "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), diff --git a/docs/examples/new-benchmark/README.md b/docs/examples/new-benchmark/README.md index fca74ba9..d39758cc 100644 --- a/docs/examples/new-benchmark/README.md +++ b/docs/examples/new-benchmark/README.md @@ -40,6 +40,8 @@ folder replaces the entire bundled entry of the same key, and survives upgrades. | `limitations` | Nullius's own: where running it here differs, or what is not offered yet | | `datasets` | `key`, `title`, `tasks`, `official` (upstream link), `source` (a phrase), `registry` (`name@version`) or `hub` (`org/name`), `verifier` | | `report` | Optional: how the verifier's report is read, shaped by `app/nullius/runs/verifier.py` | +| `records` | Optional: `{label, path}` entries under `verifier/`; text files or folders (one level, up to 200 files, printable names only) | +| `evidence` | Optional: `{label, path}` rows of the score's `detail`, shown when a trial falls short; shaped by `app/nullius/runs/evidence.py` | | `citation`, `citation_source` | BibTeX, and its source | Full rules: the docstring of `app/nullius/catalogue/catalog.py`. diff --git a/docs/standard.md b/docs/standard.md index b101a269..083c5593 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -430,7 +430,7 @@ local proof records; saved runs and credentials remain. | `turn` | The transcript so far; `simulator: {model, base_url, key}` when there is one; `judge` for an upstream that grades as the conversation ends; `attempt` with `limits.attempts` | The next message, `{done: true}`, or `restart` | | `produce` | A capability benchmark's recall, `base_url` and `key` | The reading, through the relay | | `answer` | `unit, dir, setup, model, base_url, key` | `{answer}`: the upstream's own answerer, for a [setup](#setups-as-published-your-model-your-agent-or-capability) | -| `score` | `unit, dir, transcript, answer`, `setup`, `verified` for an own image, `judge: {model, base_url, key}` when judged | `{reward, detail}`, and `passed` when the benchmark passes or fails; `parts: {n, by, parts}` when the reward is a mean over several parts (a conversation's questions), so the job's mean weighs it by `n` and breaks it down by `by`; `stopped`, the reason of a stop asked while the unit ran, kept as `verifier_result.stopped` | +| `score` | `unit, dir, transcript, answer`, `setup`, `verified` for an own image, `judge: {model, base_url, key}` when judged | `{reward, detail}`, and `passed` when the benchmark passes or fails; `parts: {n, by, parts}` when the reward is a mean over several parts (a conversation's questions); the job's mean weighs it by `n` and breaks it down by `by`; `stopped`, the reason of a stop asked while the unit ran, kept as `verifier_result.stopped`; `detail` holds benchmark-specific evidence, redacted for display | | `oracle` | `{unit, dir}` | `{answer}`, the reference; a workspace benchmark also writes it into `dir` | | `end` | `{unit, dir}`, with `driver.unit_end`, once a unit an agent ran has ended, also after a stop, when its `setup` was sent and the driver still runs with no request left unanswered | `{}` | | `task_given` | `{unit, dir}`, with `driver.task_given`, just before an agent is sent its task: its first prompt, or its command | `{}` once the benchmark's side has taken it; a failure ends the unit before the task is sent |