From ef2a67cce0924f0059bff15c8581969ec3f5acdc Mon Sep 17 00:00:00 2001 From: aaronjmars Date: Mon, 26 Oct 2026 10:10:15 -0400 Subject: [PATCH] bench-kit v0.6.0: sweep ledger, auth-error check, secret scrub - STANDARD.md v2.5, new section 11 (sweeps). - bench-kit ledger: tracked per-sweep verdict file data/sweeps/.json (schema bench-sweep/1), merged on every call, exits 2 if the path is gitignored. - bench-kit check-run: flags provider auth failures (401, revoked or expired token, invalid API key) so the trial is recorded as an error, not scored; exit 3 after --stop-after N in a row; --require for missing-file checks. - bench-kit scrub: replaces secret values named by env var (globs) or a values file with ; --check verifies none is left. - lint BL012 (run record or data/sweeps/ gitignored), BL013 (auth-error rows in a complete run); BL001 validates bench-sweep/1 ledgers. --- NEXT.md | 9 +- README.md | 32 ++++- STANDARD.md | 114 ++++++++++++++- action.yml | 2 +- pyproject.toml | 2 +- schema/bench-sweep-1.schema.json | 56 ++++++++ src/bench_kit/__init__.py | 2 +- src/bench_kit/cli.py | 102 ++++++++++++- src/bench_kit/ledger.py | 173 ++++++++++++++++++++++ src/bench_kit/lint.py | 47 +++++- src/bench_kit/runcheck.py | 182 +++++++++++++++++++++++ src/bench_kit/scrub.py | 108 ++++++++++++++ tests/test_sweep_tools.py | 238 +++++++++++++++++++++++++++++++ uv.lock | 2 +- 14 files changed, 1051 insertions(+), 18 deletions(-) create mode 100644 schema/bench-sweep-1.schema.json create mode 100644 src/bench_kit/ledger.py create mode 100644 src/bench_kit/runcheck.py create mode 100644 src/bench_kit/scrub.py create mode 100644 tests/test_sweep_tools.py diff --git a/NEXT.md b/NEXT.md index 2ff6f0a..98eb509 100644 --- a/NEXT.md +++ b/NEXT.md @@ -1,6 +1,6 @@ # Next -Updated 2026-10-13. +Updated 2026-10-26. 1. Paired Bayes interval for small-n pass rates (Bowyer et al. 2025), next to the paired t. 2. Converters into manifest + samples: Harbor job/trial `result.json`, and EVMbench-style per-audit `grade.json` results. @@ -11,6 +11,13 @@ Updated 2026-10-13. 7. export-eee: carry sample transcripts into EEE `messages` for multi_turn and agentic runs (today an empty list). 8. Task filters: a negated match (`not_in`) and a lint warning when a filter keeps no task, if a bench needs them. +Done in 0.6.0 (2026-10-26): sweep hygiene, STANDARD.md section 11. Tracked sweep ledger +`data/sweeps/.json` (schema `bench-sweep/1`, `bench-kit ledger`); `bench-kit check-run` +marks provider auth failures (401, revoked token, invalid key) as errors and stops a sweep after N +in a row, plus a required-files check; `bench-kit scrub` replaces secret values named by env var or +values file and `--check` verifies none is left; lint BL012 (run record or ledger dir gitignored) +and BL013 (auth-error rows in a complete run), and BL001 validates `bench-sweep/1` ledgers. + Done in 0.5.1 (2026-10-13): tiny numbers print in e-notation below 1e-6 and a sign-test p below 0.001 prints as `p<0.001` (a 520-task comparison printed p as a 150-digit decimal). diff --git a/README.md b/README.md index 08b6f68..fcf9163 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A results standard for benchmark repos, with JSON Schemas, a renderer, small-sample stats, a linter and an Every Eval Ever exporter (STANDARD.md is the source of truth). ## Status -Updated 2026-10-13. State: active, v0.5.1. Next: see NEXT.md. +Updated 2026-10-26. State: active, v0.6.0. Next: see NEXT.md. ## Latest result bench-kit is tooling, not a bench, so it has no runs. The standard it enforces is in STANDARD.md. @@ -19,22 +19,42 @@ per task x subject x repeat. bench-kit then: per-metric task subsets (`task_filter`, e.g. recall over positive tasks only). - `bench-kit render`: regenerates the README latest block (between the `bench:latest` markers), RESULTS.md and runs/INDEX.md from all manifests. -- `bench-kit lint`: checks the repo against the standard, rules BL001-BL011 (`bench-kit rules`). +- `bench-kit lint`: checks the repo against the standard, rules BL001-BL013 (`bench-kit rules`). - `bench-kit export-eee [--org NAME]`: writes Every Eval Ever 0.3.0 aggregate + samples files and validates them against the vendored EEE schemas. +Sweep hygiene (STANDARD.md section 11), for the bench's runner to call: + +- `bench-kit ledger --run `: writes or updates the tracked sweep ledger + `data/sweeps/.json` (per-trial verdicts, schema `bench-sweep/1`). Raw transcripts + may stay gitignored; the ledger is committed. +- `bench-kit check-run ...`: flags trials that failed on provider auth (401, revoked or + expired token, invalid API key), so they are recorded as errors instead of scored, and exits 3 + after `--stop-after N` in a row so the sweep stops. `--require GLOB` checks the trial kept + every file the bench needs. +- `bench-kit scrub ... --env '*_API_KEY'`: replaces secret values (named by env var or a + `--values-file`) in run files with ``; `--check` exits 1 if any value is left. + ## Run it ```bash # from a bench repo checkout -uv tool install git+https://github.com/aaronjmars/bench-kit@v0.5.1 # or: pipx install git+https://... +uv tool install git+https://github.com/aaronjmars/bench-kit@v0.6.0 # or: pipx install git+https://... bench-kit stats && bench-kit render && bench-kit lint bench-kit export-eee --out eee-export --org "Your Org" + +# inside a sweep loop, after each trial +bench-kit check-run runs//raw/ --streak-file runs/.auth-streak.json # 2 = auth error row, 3 = stop +bench-kit scrub runs/ --env '*_API_KEY' --env '*_TOKEN' +bench-kit ledger --run --status running +# at sweep end +bench-kit scrub runs/ --env '*_API_KEY' --env '*_TOKEN' --check +bench-kit ledger --run --status finished && git add data/sweeps runs/ ``` In any repo's GitHub Actions CI: ```yaml - uses: actions/checkout@v4 -- uses: aaronjmars/bench-kit@v0.5.1 +- uses: aaronjmars/bench-kit@v0.6.0 with: args: --warn-only # drop once the repo is migrated ``` @@ -46,8 +66,8 @@ uv sync && uv run pytest && uv run ruff check . && uv run ruff format --check . ## Layout - `STANDARD.md`: the standard (files, README shape, manifest and samples fields, stats rules, lint rules) -- `schema/`: `bench-manifest-1.schema.json`, `bench-sample-1.schema.json`, and `eee/` (vendored Every Eval Ever 0.3.0 schemas, MIT, see `schema/eee/SOURCE.md`) -- `src/bench_kit/`: `stats.py`, `render.py`, `lint.py`, `export_eee.py`, `cli.py` +- `schema/`: `bench-manifest-1.schema.json`, `bench-sample-1.schema.json`, `bench-sweep-1.schema.json`, and `eee/` (vendored Every Eval Ever 0.3.0 schemas, MIT, see `schema/eee/SOURCE.md`) +- `src/bench_kit/`: `stats.py`, `render.py`, `lint.py`, `export_eee.py`, `ledger.py`, `runcheck.py`, `scrub.py`, `cli.py` - `action.yml`: composite action that installs bench-kit from the action checkout and runs `bench-kit lint` - `tests/`: pytest, including hand-computed stats checks diff --git a/STANDARD.md b/STANDARD.md index fef72d3..0f63398 100644 --- a/STANDARD.md +++ b/STANDARD.md @@ -1,4 +1,4 @@ -# Bench standard v2.4 (bench-kit 0.5.1) +# Bench standard v2.5 (bench-kit 0.6.0) One shape for every bench repo: how runs are recorded, checked and reported, whatever the bench measures (models, agent harnesses, prompts, CI runners, @@ -28,6 +28,13 @@ paired diff is equal (or there is 1 task, 1 shared task or 1 cluster), stats leaves out the interval and writes `uncertainty.no_interval_reason`, render prints `[CI n/a: ]`, and lint warns on a stored zero-width interval (BL011); every v2.3 manifest stays valid as `bench-manifest/1`. +v2.5 (bench-kit 0.6.0) adds sweep hygiene (section 11): a tracked sweep ledger +per sweep (`data/sweeps/.json`, schema `bench-sweep/1`, `bench-kit +ledger`), auth errors recorded as errors and a sweep stop after a few in a row +(`bench-kit check-run`), and a secret scrub of run files after every trial +(`bench-kit scrub`); lint warns when a run record or the ledger dir is +gitignored (BL012) or a complete run holds auth-error rows (BL013). Manifests and +samples are unchanged. Sources at the end. Note: every number, id and hash in the examples below is made up to show the @@ -54,7 +61,8 @@ shape. They are not results. |---|---|---| | `runs//manifest.json` | the run (or a human right after) | Source of truth for one run. Section 4. Required. | | `runs//samples.jsonl` | the run | One row per task x subject x repeat. Section 5. Required when any metric is computed from samples. | -| `runs//` other files | the run | Raw logs, transcripts, judge outputs, as the bench already writes them. If not committed, `raw.location` or `raw.reason` says why. | +| `runs//` other files | the run | Raw logs, transcripts, judge outputs, as the bench already writes them. If not committed, `raw.location` or `raw.reason` says why. Gitignore only these raw files (e.g. `runs/*/raw/`), never `manifest.json` or `samples.jsonl` (BL012). | +| `data/sweeps/.json` | the sweep runner (`bench-kit ledger`) | Sweep ledger: one record per trial with its verdict. Tracked in git, never gitignored. Section 11. | | `README.md` | human + generated block | Fixed sections, section 2. | | `RESULTS.md` | **generated** | Every run, newest first, from manifests. Section 3. | | `runs/INDEX.md` | **generated** | One line per run: id, date, question, verdict, status. | @@ -353,7 +361,10 @@ One JSON line per task x subject x repeat (EEE instance names where they exist): consistently within a run. - `error` is null or `{"source": "infra|agent|judge|task", "type", "message"}`. With `errors.counted_as: zero` an errored row with a null score counts as 0 - (and not correct); with `excluded` it is dropped. + (and not correct); with `excluded` it is dropped. A trial that failed on + provider auth (section 11) gets `"type": "auth"` (usually `"source": "infra"`) + and a null score; it is re-run, and a run that still holds such rows is not + `complete` (BL013). - Row count per subject must equal `n_completed x repeats.completed`, or that subject's entries in `source_data.n_completed_by_subject` and `repeats.completed_by_subject` when the manifest declares them. @@ -459,6 +470,7 @@ comparison must list what differs (`compared_with`). - Subject short form: `harness@version+model` (Harbor style), e.g. `omp@18.3.2+claude-haiku-5-5`. - Any number quoted outside the repo (tweet, blog, PR) carries run id and date. - Secrets come from a secret store at run time; never in repo, manifests, samples or logs. + Run files are scrubbed after every trial (section 11). - No em or en dashes anywhere. - GitHub: description = README one-liner; topic `bench`. @@ -474,6 +486,12 @@ Commands: - `bench-kit lint [--warn-only]`: GitHub `::error file=..::` annotations in CI - `bench-kit export-eee [--org NAME]`: EEE 0.3.0 aggregate + samples files, validated against the vendored EEE schemas +- `bench-kit ledger [--run ID] [--records FILE] [--status S]`: writes or + updates the tracked sweep ledger (section 11) +- `bench-kit check-run ... [--require GLOB] [--stop-after N]`: auth errors + and missing files in finished trials (section 11) +- `bench-kit scrub ... --env NAME|GLOB [--values-file FILE] [--check]`: + replaces secret values in run files (section 11) Rules (code, level): - BL001 error: manifest or samples fail JSON Schema, duplicate run id, or id differs from directory @@ -487,6 +505,8 @@ Rules (code, level): - BL009 warn: task-set version not in the METHOD.md changelog - BL010 warn: leftover TODO in docs, or `raw.kept` false without location or reason - BL011 warn: a stored confidence interval has zero width (lower equals upper), e.g. from an older bench-kit or a hand-written external metric (section 7 rule 13) +- BL012 warn: a path that must be tracked is gitignored: a run's `manifest.json` or `samples.jsonl`, or the `data/sweeps/` ledger dir (checked with `git check-ignore`, so tracked files never count; skipped outside a git work tree). BL001 also checks every `data/sweeps/*.json` that declares `bench-sweep/1` against its schema and its file name +- BL013 warn: a run with `status: complete` has sample rows with `error.type: "auth"` (section 11) Suppress in a markdown file with ``, in a manifest with `lint_ignore`, or repo-wide in `.bench-lint-ignore`. @@ -506,6 +526,94 @@ Legacy repos start with `--warn-only` and switch to errors once migrated. 5. Add the lint to CI with `--warn-only` first, then switch to errors once the repo is clean. +## 11. Sweeps: ledger, auth errors, secrets (bench-kit 0.6.0) + +A sweep is one launch of the bench's runner over many trials (task x subject x +repeat), often paid and often spread over several runs. Three rules keep a sweep +from being lost, misread or leaking a key. + +**1. Persist the sweep ledger.** Raw transcripts may stay out of git +(`runs/*/raw/` in `.gitignore`, kept elsewhere per `raw.location`), but each +sweep's per-trial verdicts go to a tracked file, `data/sweeps/.json` +(schema `bench-sweep/1`), and are committed with the run records. A paid sweep +whose only ledger sat in a gitignored folder cannot be re-read once that folder +is gone. The ledger holds verdicts, never outputs or transcripts: + +```json +{"schema_version": "bench-sweep/1", "sweep_id": "2026-01-15-ab-sweep", "bench": "example-bench", + "started_at": "2026-01-15T14:00:00Z", "updated_at": "2026-01-15T16:00:00Z", + "status": "halted", "halted": "3 consecutive auth errors on candidate", "note": null, + "runs": ["2026-01-15-summarizer-ab"], + "counts": {"records": 3, "scored": 1, "errored": 1, "skipped": 1, "auth_errors": 1}, + "records": [ + {"run_id": "2026-01-15-summarizer-ab", "sample_id": "task-0001", "subject": "baseline", "repeat": 1, + "status": "scored", "score": 3.2, "is_correct": null, "error": null}, + {"run_id": "2026-01-15-summarizer-ab", "sample_id": "task-0001", "subject": "candidate", "repeat": 1, + "status": "errored", "score": null, "is_correct": null, + "error": {"source": "infra", "type": "auth", "message": "auth error: 401 Unauthorized"}}, + {"run_id": null, "sample_id": "task-0002", "subject": "candidate", "repeat": 1, + "status": "skipped", "note": "sweep halted"}]} +``` + +- `status`: running | finished | stopped | halted; `halted` says why it stopped early. +- Record `status`: scored | errored | skipped. Records may carry more keys (cost, judge + votes, a proof field); error messages are cut to 300 characters. +- `bench-kit ledger --run ` adds every sample row of a run; + `--records ` adds records the runner wrote itself. Calls merge (the + newest record per run, task, subject and repeat wins, `started_at` is kept), so + a runner can call it after every trial and once more at the end with + `--status finished|stopped|halted`. It exits 2 if the ledger path is gitignored. + From Python: `bench_kit.ledger.write(root, sweep_id, runs=..., records=..., status=...)`. +- A bench that already keeps its own ledger format there is left alone: lint + checks only files that declare `bench-sweep/1`. + +**2. Fail loud on auth errors.** A trial whose output shows a provider auth +failure (HTTP 401, a revoked or expired token, an invalid API key, a lost +login) measured nothing. A clean exit code does not make it a result: it is +recorded as errored with `error.type: "auth"` and a null score, never scored, +and re-run once the login is fixed. Every later trial on the same login fails the +same way, so the sweep stops after a few in a row (default 3). + +- `bench-kit check-run ...` scans each finished trial (a dir or a file, in + run order) for generic auth-error wording and prints one status per trial: `ok`, + `incomplete`, or `auth-error` with the file, line and a masked excerpt (long + token-like strings print as ``). Exit 0 clean, 1 a required file is + missing, 2 an auth error (mark the trial errored), 3 the streak reached + `--stop-after N` (stop the sweep). `--streak-file` keeps the streak between + calls when the runner checks one trial at a time; a clean trial resets it. + `--json` prints the same for scripts. +- Agent transcripts of benches whose tasks call HTTP services can quote the + target's own 401 responses. Those benches point `--only` at the harness result + and error files, or `--skip` the transcript. `--pattern REGEX` adds a + bench-specific marker. +- From Python: `bench_kit.runcheck.check_trial(...)`, `AuthStreak`, and + `sample_error(check)` for the samples row's `error` object. +- A complete run must hold no auth-error rows (BL013): re-run them, or mark the run + `partial`. + +**3. Scrub secrets from run files.** Each trial scrubs its own files when it +ends, and the sweep scrubs all its run dirs again at the end, since a trial killed +mid-run skips its own scrub. The caller names the secrets; bench-kit never reads +a secret store: + +```bash +bench-kit scrub runs/ data/sweeps/.json --env '*_API_KEY' --env '*_TOKEN' +bench-kit scrub runs/ --values-file <(my-secret-tool export --names-and-values) # NAME=value lines +bench-kit scrub runs/ --env '*_API_KEY' --check # completeness: exit 1 if any value is left +``` + +- Each value is replaced with ``, longest first (a URL that holds a + key is masked whole), plus its JSON-escaped forms. Binary files are skipped, and + values shorter than 8 characters are skipped with a warning. +- Completeness has two halves: `scrub --check` finds no value left, and + `check-run --require ` finds every file the bench needs to judge the trial + later (result, log, transcript, verifier output, as the bench defines them). + +A sweep loop then reads, per trial: run it, `check-run` (2: write an auth error +row, 3: stop), `scrub`, then `ledger`; at the end `scrub` and `scrub --check` over +the sweep's run dirs, `ledger --status ...`, and commit `data/sweeps/` with the run +records. + ## Sources - Harbor job/trial results, lock, parity rules: https://github.com/harbor-framework/harbor (src/harbor/models/job/result.py, models/trial/result.py, models/job/lock.py, adapters/ADAPTER_CONTRIBUTING.md, scripts/validate_adapter.py) diff --git a/action.yml b/action.yml index af9cdad..3846914 100644 --- a/action.yml +++ b/action.yml @@ -1,5 +1,5 @@ name: bench-kit lint -description: Check a bench repo against the bench standard (bench-kit lint, rules BL001-BL011). +description: Check a bench repo against the bench standard (bench-kit lint, rules BL001-BL013). inputs: args: description: Extra arguments for bench-kit lint, e.g. --warn-only diff --git a/pyproject.toml b/pyproject.toml index 0353dde..239cbb9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "bench-kit" -version = "0.5.1" +version = "0.6.0" license = "MIT" description = "Shared standard, schema, renderer, stats and linter for bench repos" readme = "README.md" diff --git a/schema/bench-sweep-1.schema.json b/schema/bench-sweep-1.schema.json new file mode 100644 index 0000000..d4de88e --- /dev/null +++ b/schema/bench-sweep-1.schema.json @@ -0,0 +1,56 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://github.com/aaronjmars/bench-kit/schema/bench-sweep-1.schema.json", + "title": "bench-sweep/1", + "description": "A sweep ledger, data/sweeps/.json: one record per trial with its verdict, never outputs or transcripts. Tracked in git.", + "type": "object", + "required": ["schema_version", "sweep_id", "started_at", "status", "runs", "records"], + "properties": { + "schema_version": {"const": "bench-sweep/1"}, + "sweep_id": {"type": "string", "minLength": 1}, + "bench": {"type": ["string", "null"]}, + "started_at": {"type": "string"}, + "updated_at": {"type": ["string", "null"]}, + "status": {"enum": ["running", "finished", "stopped", "halted"]}, + "halted": {"type": ["string", "null"], "description": "Why the sweep stopped early, e.g. 3 consecutive auth errors."}, + "note": {"type": ["string", "null"]}, + "runs": {"type": "array", "items": {"type": "string"}, "description": "Run ids (directories under runs/) this sweep wrote."}, + "counts": { + "type": "object", + "properties": { + "records": {"type": "integer", "minimum": 0}, + "scored": {"type": "integer", "minimum": 0}, + "errored": {"type": "integer", "minimum": 0}, + "skipped": {"type": "integer", "minimum": 0}, + "auth_errors": {"type": "integer", "minimum": 0} + } + }, + "records": { + "type": "array", + "items": { + "type": "object", + "required": ["sample_id", "subject", "status"], + "properties": { + "run_id": {"type": ["string", "null"]}, + "sample_id": {"type": "string", "minLength": 1}, + "subject": {"type": "string", "minLength": 1}, + "repeat": {"type": ["integer", "null"], "minimum": 0}, + "status": {"enum": ["scored", "errored", "skipped"]}, + "score": {"type": ["number", "null"]}, + "is_correct": {"type": ["boolean", "null"]}, + "cost_usd": {"type": ["number", "null"]}, + "error": { + "type": ["object", "null"], + "required": ["message"], + "properties": { + "source": {"type": ["string", "null"]}, + "type": {"type": ["string", "null"]}, + "message": {"type": "string"} + } + }, + "note": {"type": ["string", "null"]} + } + } + } + } +} diff --git a/src/bench_kit/__init__.py b/src/bench_kit/__init__.py index 6c5e6f3..76caed0 100644 --- a/src/bench_kit/__init__.py +++ b/src/bench_kit/__init__.py @@ -1,3 +1,3 @@ """bench-kit: shared standard, schema, renderer, stats and linter for bench repos.""" -__version__ = "0.5.1" +__version__ = "0.6.0" diff --git a/src/bench_kit/cli.py b/src/bench_kit/cli.py index 961ee9d..df4152a 100644 --- a/src/bench_kit/cli.py +++ b/src/bench_kit/cli.py @@ -3,11 +3,12 @@ from __future__ import annotations import argparse +import json import os import sys from pathlib import Path -from . import __version__, export_eee, lint, render, stats +from . import __version__, export_eee, ledger, lint, render, runcheck, scrub, stats from .io import discover, dump_json @@ -66,6 +67,75 @@ def cmd_export(a) -> int: return 0 +def cmd_ledger(a) -> int: + records = [] + for f in a.records or []: + records += ledger.load_records(f) + try: + path = ledger.write(a.root, a.sweep_id, runs=a.run or [], records=records, status=a.status, halted=a.halted, note=a.note) + except (ValueError, OSError) as e: + print(f"bench-kit ledger: {e}", file=sys.stderr) + return 1 + rel = path.relative_to(a.root) if path.is_relative_to(a.root) else path + print(f"wrote {rel}") + hit = ledger.ignored(a.root, [str(rel)]) + if hit: + print(f"warning: {rel} is gitignored, so this ledger would not be committed (BL012)", file=sys.stderr) + return 2 + return 0 + + +def cmd_check_run(a) -> int: + streak = runcheck.AuthStreak(a.streak_file) + checks, stop = [], False + for t in a.trial: + c = runcheck.check_trial(t, require=a.require or [], only=a.only or [], skip=a.skip or [], extra_patterns=a.pattern or []) + checks.append(c) + if streak.update(c) >= a.stop_after: + stop = True + streak.save() + if a.json: + out = {"trials": [c.as_dict() for c in checks], "consecutive_auth_errors": streak.count, "stop_sweep": stop} + print(json.dumps(out, indent=2)) + else: + for c in checks: + print(f"{c.trial}: {c.status}") + for h in c.auth: + print(f" auth error: {h.text()}") + for m in c.missing: + print(f" missing: {m}") + if stop: + print(f"STOP SWEEP: {streak.count} consecutive auth errors (limit {a.stop_after}); fix the login or key, then resume") + if stop: + return 3 + if any(c.auth for c in checks): + return 2 + return 1 if any(c.missing for c in checks) else 0 + + +def cmd_scrub(a) -> int: + values = scrub.values_from_env(a.env or []) + for f in a.values_file or []: + values += scrub.values_from_file(f) + if not values: + print("bench-kit scrub: no secret values (give --env NAME or --values-file FILE; empty variables are skipped)", file=sys.stderr) + return 1 + res = scrub.scrub(a.path, values, check=a.check) + for label in sorted(set(res.skipped_short)): + print(f"warning: value of {label} is shorter than {scrub.MIN_LEN} characters, not scrubbed", file=sys.stderr) + for p, labels in res.hits.items(): + verb = "still holds" if a.check else "scrubbed" + print(f"{p}: {verb} {', '.join(sorted(set(labels)))}") + if a.check: + if res.hits: + print(f"bench-kit scrub --check: secrets left in {len(res.hits)} file(s)") + return 1 + print("bench-kit scrub --check: clean") + return 0 + print(f"scrubbed {len(res.files_changed)} file(s) with {len({v for v, _ in values if len(v) >= scrub.MIN_LEN})} secret value(s)") + return 0 + + def cmd_rules(_a) -> int: for code, (level, desc) in sorted(lint.RULES.items()): print(f"{code} {level}: {desc}") @@ -86,7 +156,7 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--run", action="append", help="only this run id (repeatable)") p.set_defaults(fn=cmd_stats) - p = sub.add_parser("lint", help="check the repo against the standard (BL001-BL011)") + p = sub.add_parser("lint", help="check the repo against the standard (BL001-BL013)") p.add_argument("root", nargs="?", type=Path, default=Path(".")) p.add_argument("--warn-only", action="store_true", help="report errors but exit 0") p.add_argument("--format", choices=["auto", "github", "plain"], default="auto") @@ -100,6 +170,34 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--org", help="organization that ran the eval (EEE source_organization_name); overrides the manifest") p.set_defaults(fn=cmd_export) + p = sub.add_parser("ledger", help="write or update the tracked sweep ledger data/sweeps/.json") + p.add_argument("sweep_id") + p.add_argument("--root", type=Path, default=Path(".")) + p.add_argument("--run", action="append", help="add every sample row of this run id as a record (repeatable)") + p.add_argument("--records", type=Path, action="append", help="add records from a JSONL file the bench's runner wrote (repeatable)") + p.add_argument("--status", choices=ledger.STATUSES, default="finished") + p.add_argument("--halted", help="why the sweep stopped early") + p.add_argument("--note") + p.set_defaults(fn=cmd_ledger) + + p = sub.add_parser("check-run", help="flag auth errors (401, revoked or invalid key) and missing files in finished trials") + p.add_argument("trial", nargs="+", type=Path, help="trial directory or file, in run order") + p.add_argument("--require", action="append", help="glob, relative to the trial dir, that must match a file (repeatable)") + p.add_argument("--only", action="append", help="scan only files matching this glob (repeatable)") + p.add_argument("--skip", action="append", help="do not scan files matching this glob, e.g. an agent transcript (repeatable)") + p.add_argument("--pattern", action="append", help="extra auth-error regex, case-insensitive (repeatable)") + p.add_argument("--stop-after", type=int, default=3, help="consecutive auth-error trials that stop the sweep (default 3)") + p.add_argument("--streak-file", type=Path, help="JSON file that keeps the streak across calls (one call per trial)") + p.add_argument("--json", action="store_true") + p.set_defaults(fn=cmd_check_run) + + p = sub.add_parser("scrub", help="replace secret values in run files with ") + p.add_argument("path", nargs="+", type=Path, help="files or directories to scrub") + p.add_argument("--env", action="append", help="environment variable name or glob whose value is secret, e.g. '*_API_KEY' (repeatable)") + p.add_argument("--values-file", type=Path, action="append", help="file of NAME=value lines or bare values (repeatable)") + p.add_argument("--check", action="store_true", help="only report files that still hold a secret; exit 1 if any") + p.set_defaults(fn=cmd_scrub) + p = sub.add_parser("rules", help="list lint rules") p.set_defaults(fn=cmd_rules) diff --git a/src/bench_kit/ledger.py b/src/bench_kit/ledger.py new file mode 100644 index 0000000..6aee5a1 --- /dev/null +++ b/src/bench_kit/ledger.py @@ -0,0 +1,173 @@ +"""Sweep ledgers (STANDARD.md section 11): one tracked file per sweep, `data/sweeps/.json`. + +Raw transcripts may stay out of git, but the per-trial verdicts of a sweep (what ran, what it +scored, what errored) are small and must be committed, so a paid sweep can be re-read after the +local run folders are gone. `write()` merges: call it after every trial (a crash then loses +nothing) and once more at sweep end with the final status. +""" + +from __future__ import annotations + +import json +import subprocess +from collections.abc import Iterable +from datetime import datetime, timezone +from pathlib import Path + +from jsonschema import Draft7Validator + +from .io import discover, dump_json, load_schema + +LEDGER_DIR = Path("data") / "sweeps" +SCHEMA = "bench-sweep/1" +STATUSES = ("running", "finished", "stopped", "halted") +MSG_MAX = 300 + + +def now() -> str: + return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") + + +def ledger_path(root: Path, sweep_id: str, ledger_dir: Path = LEDGER_DIR) -> Path: + if not sweep_id or "/" in sweep_id or sweep_id.startswith("."): + raise ValueError(f"bad sweep id {sweep_id!r}") + return Path(root) / ledger_dir / f"{sweep_id}.json" + + +def _key(r: dict) -> tuple: + return (r.get("run_id"), r.get("sample_id"), r.get("subject"), r.get("repeat")) + + +def _short_error(err) -> dict | None: + if not err: + return None + out = {k: err.get(k) for k in ("source", "type") if err.get(k) is not None} + out["message"] = str(err.get("message") or "")[:MSG_MAX] + return out + + +def records_from_samples(run_id: str, rows: Iterable[dict]) -> list[dict]: + """One ledger record per sample row: verdict fields only, never outputs or transcripts.""" + out = [] + for row in rows: + ev = row.get("evaluation") or {} + err = _short_error(row.get("error")) + rec = { + "run_id": run_id, + "sample_id": row.get("sample_id"), + "subject": row.get("subject"), + "repeat": row.get("repeat"), + "status": "errored" if err else "scored", + "score": ev.get("score"), + "is_correct": ev.get("is_correct"), + "error": err, + } + if row.get("cost_usd") is not None: + rec["cost_usd"] = row["cost_usd"] + out.append(rec) + return out + + +def load_records(path: Path) -> list[dict]: + """Records from a JSONL file the bench's own runner wrote (one object per line).""" + out = [] + for i, line in enumerate(Path(path).read_text().splitlines(), 1): + if line.strip(): + try: + rec = json.loads(line) + except json.JSONDecodeError as e: + raise ValueError(f"{path}:{i}: invalid JSON: {e.msg}") from e + if not isinstance(rec, dict): + raise ValueError(f"{path}:{i}: not a JSON object") + if rec.get("error"): + rec["error"] = _short_error(rec["error"]) + out.append(rec) + return out + + +def counts(records: list[dict]) -> dict: + c = {"records": len(records), "scored": 0, "errored": 0, "skipped": 0, "auth_errors": 0} + for r in records: + if r.get("status") in ("scored", "errored", "skipped"): + c[r["status"]] += 1 + if (r.get("error") or {}).get("type") == "auth": + c["auth_errors"] += 1 + return c + + +def write( + root: Path, + sweep_id: str, + runs: Iterable[str] = (), + records: Iterable[dict] = (), + status: str = "running", + halted: str | None = None, + note: str | None = None, + bench: str | None = None, + ledger_dir: Path = LEDGER_DIR, +) -> Path: + """Create or update the ledger: add the sample rows of `runs` (run ids under runs/) and the given + records, newest wins per (run_id, sample_id, subject, repeat). Writes atomically.""" + if status not in STATUSES: + raise ValueError(f"status must be one of {STATUSES}") + root = Path(root) + path = ledger_path(root, sweep_id, ledger_dir) + old = json.loads(path.read_text()) if path.is_file() else {} + merged = {_key(r): r for r in old.get("records", [])} + run_ids = list(old.get("runs", [])) + want = list(runs) + if want: + found = {r.dir.name: r for r in discover(root)} + for rid in want: + run = found.get(rid) + if run is None or run.samples is None: + raise ValueError(f"run {rid} has no runs/{rid}/samples.jsonl") + for rec in records_from_samples(rid, run.samples): + merged[_key(rec)] = rec + if bench is None: + bench = run.manifest.get("bench") + if rid not in run_ids: + run_ids.append(rid) + for rec in records: + merged[_key(rec)] = rec + rid = rec.get("run_id") + if rid and rid not in run_ids: + run_ids.append(rid) + recs = sorted(merged.values(), key=lambda r: tuple(str(x) for x in _key(r))) + data = { + "schema_version": SCHEMA, + "sweep_id": sweep_id, + "bench": bench or old.get("bench") or root.resolve().name, + "started_at": old.get("started_at") or now(), + "updated_at": now(), + "status": status, + "halted": halted if halted is not None else (old.get("halted") if status in ("halted", "stopped") else None), + "note": note if note is not None else old.get("note"), + "runs": run_ids, + "counts": counts(recs), + "records": recs, + } + errs = sorted(Draft7Validator(load_schema("bench-sweep-1.schema.json")).iter_errors(data), key=lambda e: list(e.absolute_path)) + if errs: + where = "/".join(str(x) for x in errs[0].absolute_path) or "(root)" + raise ValueError(f"ledger would not match {SCHEMA}: {where}: {errs[0].message}") + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(".json.tmp") + tmp.write_text(dump_json(data)) + tmp.replace(path) + return path + + +def ignored(root: Path, rel_paths: Iterable[str]) -> list[str] | None: + """Which of these repo-relative paths git would ignore (tracked files never count as ignored). + None when root is not in a git work tree or git is missing.""" + paths = [str(p) for p in rel_paths] + if not paths: + return [] + try: + r = subprocess.run(["git", "check-ignore", "--stdin"], cwd=root, input="\n".join(paths) + "\n", capture_output=True, text=True) + except OSError: + return None + if r.returncode not in (0, 1): + return None + return [x for x in r.stdout.splitlines() if x] diff --git a/src/bench_kit/lint.py b/src/bench_kit/lint.py index 204bdd0..ce02db2 100644 --- a/src/bench_kit/lint.py +++ b/src/bench_kit/lint.py @@ -1,8 +1,9 @@ -"""bench-lint: rules BL001-BL011 from STANDARD.md section 9.""" +"""bench-lint: rules BL001-BL013 from STANDARD.md section 9.""" from __future__ import annotations import fnmatch +import json import re import subprocess from dataclasses import dataclass @@ -10,7 +11,7 @@ from jsonschema import Draft7Validator -from . import render, stats +from . import ledger, render, stats from .io import Run, discover, load_schema RULES = { @@ -25,6 +26,8 @@ "BL009": ("warning", "task-set version missing from METHOD.md changelog"), "BL010": ("warning", "leftover TODO, or raw data not kept without location or reason"), "BL011": ("warning", "stored confidence interval has zero width (lower equals upper)"), + "BL012": ("warning", "a path that must be tracked is gitignored (run manifest or samples, or the data/sweeps/ ledger dir)"), + "BL013": ("warning", "auth-error rows (error.type auth) in a run whose status is complete"), } REQUIRED_FILES = ["README.md", "METHOD.md", "NEXT.md", "RESULTS.md", "runs/INDEX.md"] README_SECTIONS = ["Status", "Latest result", "How it works", "Run it", "Layout"] @@ -144,6 +147,20 @@ def bl001(self): self.add("BL001", r.samples_path, f"row {i}: {errs[0].message}", i) if bad > 20: self.add("BL001", r.samples_path, f"{bad - 20} more invalid rows not shown") + lv = Draft7Validator(load_schema("bench-sweep-1.schema.json")) + for p in sorted((self.root / ledger.LEDGER_DIR).glob("*.json")): + try: + data = json.loads(p.read_text()) + except json.JSONDecodeError as e: + self.add("BL001", p, f"invalid JSON: {e.msg} (line {e.lineno})") + continue + if not isinstance(data, dict) or data.get("schema_version") != ledger.SCHEMA: + continue # a bench's own ledger format; only bench-sweep/1 files are checked + for e in sorted(lv.iter_errors(data), key=lambda e: list(e.absolute_path))[:20]: + where = "/".join(str(x) for x in e.absolute_path) or "(root)" + self.add("BL001", p, f"{where}: {e.message}") + if data.get("sweep_id") and data["sweep_id"] != p.stem: + self.add("BL001", p, f"sweep_id {data['sweep_id']!r} differs from file name {p.stem!r}") def bl002(self): for f in REQUIRED_FILES: @@ -337,6 +354,32 @@ def bl011(self): " uncertainty.no_interval_reason", ) + def bl012(self): + probe = (ledger.LEDGER_DIR / "probe.json").as_posix() + want = {probe: f"{ledger.LEDGER_DIR.as_posix()}/"} + for r in self.runs: + for p in (r.manifest_path, r.samples_path): + if p.exists(): + want[self.rel(p)] = self.rel(p) + hit = ledger.ignored(self.root, want) + for path in hit or []: + if path == probe: + self.add("BL012", want[path], "sweep ledgers here are gitignored and would be lost; track data/sweeps/, ignore raw transcripts") + else: + self.add("BL012", want.get(path, path), "run record is gitignored; commit manifest.json and samples.jsonl, ignore only raw files") + + def bl013(self): + for r in self.runs: + if r.manifest.get("status") != "complete" or not r.samples: + continue + n = sum(1 for x in r.samples if ((x.get("error") or {}).get("type") or "") == "auth") + if n: + self.add( + "BL013", + r.samples_path, + f"{n} row(s) failed on auth (revoked or invalid key, 401) in a run marked complete; re-run them or set status partial", + ) + def run(self) -> list[Finding]: for rule in sorted(RULES): getattr(self, rule.lower())() diff --git a/src/bench_kit/runcheck.py b/src/bench_kit/runcheck.py new file mode 100644 index 0000000..9556593 --- /dev/null +++ b/src/bench_kit/runcheck.py @@ -0,0 +1,182 @@ +"""Check one finished trial before it is scored (STANDARD.md section 11). + +Two checks: + +1. Auth errors. A trial whose output shows a provider auth failure (HTTP 401, a revoked or + expired token, an invalid API key, a lost login) says nothing about the subject. It must be + recorded as errored (`error.type: "auth"`), never scored and never counted as a clean exit, + and a sweep stops after a few of them in a row, since every later trial on the same login + fails the same way. +2. Completeness. Every file the bench needs to judge the trial later is there (`--require`). + +Patterns are generic provider wording. Agent transcripts of benches whose tasks call HTTP +services can quote the target's own 401 responses: point `--only` at the harness result and +error files for those benches, or `--skip` the transcript. +""" + +from __future__ import annotations + +import fnmatch +import json +import re +from collections.abc import Iterable +from dataclasses import dataclass, field +from pathlib import Path + +AUTH_PATTERNS = [ + r"\b401\b[^\n]{0,60}?(unauthori[sz]ed|authentication_error|authentication failed|invalid[ _-]?(x-)?api[ _-]?key|revoked)", + r"(unauthori[sz]ed|authentication_error)[^\n]{0,60}?\b401\b", + r"[\"']?status(_?code)?[\"']?\s*[:=]\s*401\b", + r"\bHTTP(/[\d.]+)?\s+401\b", + r"(access|oauth|refresh|bearer|auth)[ _-]?token[^\n]{0,40}?(has been |was |is )?(revoked|expired|invalid)", + r"token (has been|was) revoked", + r"invalid[ _-]?(x-)?api[ _-]?key", + r"incorrect api key", + r"api[ _-]?key[^\n]{0,20}?(is )?(not valid|invalid|revoked|expired|disabled|rejected)", + r"authentication[ _](error|failed)", + r"invalid[ _]authentication", + r"bad credentials", + r"not logged in", + r"please run /?login\b", +] +SECRET_LIKE = re.compile(r"[A-Za-z0-9_\-.+/=]{24,}") +MAX_BYTES = 50_000_000 + + +@dataclass +class Hit: + path: str + line: int + excerpt: str + + def text(self) -> str: + return f"{self.path}:{self.line}: {self.excerpt}" + + +@dataclass +class TrialCheck: + trial: str + auth: list[Hit] = field(default_factory=list) + missing: list[str] = field(default_factory=list) + + @property + def status(self) -> str: + if self.auth: + return "auth-error" + return "incomplete" if self.missing else "ok" + + def as_dict(self) -> dict: + return { + "trial": self.trial, + "status": self.status, + "auth_errors": [h.__dict__ for h in self.auth], + "missing": self.missing, + } + + +def compile_patterns(extra: Iterable[str] = ()) -> re.Pattern: + return re.compile("|".join(f"(?:{p})" for p in [*AUTH_PATTERNS, *extra]), re.IGNORECASE) + + +def mask(text: str) -> str: + """Excerpt safe to print: long token-like strings (keys, JWTs) become .""" + return SECRET_LIKE.sub("", text.strip())[:160] + + +def _match(rel: str, globs: Iterable[str]) -> bool: + name = rel.rsplit("/", 1)[-1] + return any(fnmatch.fnmatch(rel, g) or fnmatch.fnmatch(name, g) for g in globs) + + +def _files(trial: Path, only: list[str], skip: list[str]): + if trial.is_file(): + yield trial, trial.name + return + for p in sorted(trial.rglob("*")): + if not p.is_file() or p.is_symlink(): + continue + rel = p.relative_to(trial).as_posix() + if only and not _match(rel, only): + continue + if skip and _match(rel, skip): + continue + yield p, rel + + +def auth_hits(text: str, pattern: re.Pattern, path: str = "", limit: int = 5) -> list[Hit]: + hits = [] + for i, line in enumerate(text.splitlines(), 1): + m = pattern.search(line) + if m: + start = max(0, m.start() - 40) + hits.append(Hit(path, i, mask(line[start : m.end() + 60]))) + if len(hits) >= limit: + break + return hits + + +def check_trial( + trial: Path, + require: Iterable[str] = (), + only: Iterable[str] = (), + skip: Iterable[str] = (), + extra_patterns: Iterable[str] = (), +) -> TrialCheck: + """Scan a trial (a directory or one file) for auth-error markers and missing required files. + require: globs relative to the trial dir, each must match at least one file.""" + trial = Path(trial) + pattern = compile_patterns(extra_patterns) + out = TrialCheck(str(trial)) + if not trial.exists(): + out.missing.append("(trial path)") + return out + for p, rel in _files(trial, list(only), list(skip)): + try: + if p.stat().st_size > MAX_BYTES: + continue + text = p.read_bytes().decode("utf-8") + except (UnicodeDecodeError, OSError): + continue + out.auth += auth_hits(text, pattern, rel) + if trial.is_dir(): + for g in require: + if not any(p.is_file() for p in trial.glob(g)): + out.missing.append(g) + return out + + +class AuthStreak: + """Consecutive auth-error trials, optionally kept in a small JSON file so a shell loop that calls + `bench-kit check-run` once per trial still sees the streak. A clean trial resets it.""" + + def __init__(self, path: Path | None = None): + self.path = Path(path) if path else None + self.count = 0 + self.last: list[str] = [] + if self.path and self.path.is_file(): + try: + saved = json.loads(self.path.read_text()) + self.count = int(saved.get("consecutive_auth_errors", 0)) + self.last = list(saved.get("trials", [])) + except (ValueError, TypeError, AttributeError): + self.count, self.last = 0, [] + + def update(self, check: TrialCheck) -> int: + if check.auth: + self.count += 1 + self.last = [*self.last, check.trial][-20:] + else: + self.count, self.last = 0, [] + return self.count + + def save(self) -> None: + if self.path: + self.path.parent.mkdir(parents=True, exist_ok=True) + self.path.write_text(json.dumps({"consecutive_auth_errors": self.count, "trials": self.last}, indent=2) + "\n") + + +def sample_error(check: TrialCheck, source: str = "infra") -> dict | None: + """The `error` object for this trial's samples.jsonl row(s), or None when the trial is clean.""" + if not check.auth: + return None + return {"source": source, "type": "auth", "message": "auth error: " + check.auth[0].excerpt} diff --git a/src/bench_kit/scrub.py b/src/bench_kit/scrub.py new file mode 100644 index 0000000..64f1d2d --- /dev/null +++ b/src/bench_kit/scrub.py @@ -0,0 +1,108 @@ +"""Scrub secret values out of run files (STANDARD.md section 11). + +The caller says which values are secret: names of environment variables (globs allowed, e.g. +`*_API_KEY`) and/or files of `NAME=value` lines. bench-kit never reads a secret store itself. +Each value found in a text file is replaced with ``, longest value first, so a +value that contains another (a URL holding a key) is masked whole. Values shorter than +MIN_LEN are skipped, since they are too likely to hit ordinary text. +""" + +from __future__ import annotations + +import fnmatch +import json +import os +import re +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from pathlib import Path + +MIN_LEN = 8 +NAME = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$") + + +@dataclass +class ScrubResult: + files_changed: list[Path] = field(default_factory=list) + hits: dict[Path, list[str]] = field(default_factory=dict) # file -> labels of values found + skipped_short: list[str] = field(default_factory=list) + + +def values_from_env(patterns: Iterable[str], environ: Mapping[str, str] | None = None) -> list[tuple[str, str]]: + """(value, label) for every environment variable whose name matches one of the patterns.""" + env = os.environ if environ is None else environ + out = [] + for name in sorted(env): + if any(fnmatch.fnmatchcase(name, p) for p in patterns) and env[name]: + out.append((env[name], name)) + return out + + +def values_from_file(path: Path) -> list[tuple[str, str]]: + """(value, label) from a file: `NAME=value` lines (an `export ` prefix and matching quotes are + dropped) or bare values (labeled `secret`). Blank lines and `#` comments are skipped.""" + out = [] + for line in Path(path).read_text().splitlines(): + s = line.strip() + if not s or s.startswith("#"): + continue + m = NAME.match(s) + name, value = (m.group(1), m.group(2)) if m else ("secret", s) + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + value = value[1:-1] + if value: + out.append((value, name)) + return out + + +def _prepare(values: Iterable[tuple[str, str]], result: ScrubResult) -> list[tuple[str, str]]: + keep = {} + for value, label in values: + if len(value) < MIN_LEN: + result.skipped_short.append(label) + continue + keep.setdefault(value, label) + escaped = json.dumps(value)[1:-1] # how the value appears inside a JSON string + for variant in (escaped, escaped.replace("/", "\\/")): # some encoders also escape "/" + if variant != value: + keep.setdefault(variant, label) + return sorted(keep.items(), key=lambda vl: len(vl[0]), reverse=True) + + +def _files(paths: Iterable[Path]): + for root in paths: + root = Path(root) + if root.is_file(): + yield root + elif root.is_dir(): + for p in sorted(root.rglob("*")): + if p.is_file() and not p.is_symlink(): + yield p + + +def scrub(paths: Iterable[Path], values: Iterable[tuple[str, str]], check: bool = False) -> ScrubResult: + """Replace every value in the text files under paths. check=True only reports (no writes): + use it as the completeness check after a scrub, it must find nothing.""" + result = ScrubResult() + vals = _prepare(values, result) + if not vals: + return result + for p in _files(paths): + try: + data = p.read_bytes() + text = data.decode("utf-8") + except (UnicodeDecodeError, OSError): + continue # binary or unreadable + if "\0" in text: + continue + new, found = text, [] + for value, label in vals: + if value in new: + found.append(label) + new = new.replace(value, f"") + if found: + result.hits[p] = found + if not check: + p.write_bytes(new.encode("utf-8")) + result.files_changed.append(p) + return result diff --git a/tests/test_sweep_tools.py b/tests/test_sweep_tools.py new file mode 100644 index 0000000..3cf7a63 --- /dev/null +++ b/tests/test_sweep_tools.py @@ -0,0 +1,238 @@ +import json +import subprocess + +import pytest +from conftest import manifest, samples, write_repo + +from bench_kit import cli, ledger, lint, runcheck, scrub + +KEY = "sk-test-" + "a1b2c3d4" * 5 +SHORTER = KEY[:20] + + +def codes(root): + return sorted({f.rule for f in lint.lint(root)}) + + +def git_init(root): + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + + +# ------------------------------------------------------------------ scrub + + +def test_scrub_env_glob_longest_first_and_json_escaped(tmp_path): + run = tmp_path / "run" + (run / "raw").mkdir(parents=True) + url = f"https://host.example/v1?key={KEY}" + (run / "raw" / "log.txt").write_text(f"calling {url}\nprefix {SHORTER}\n") + slashy = "abc/def/ghi/jkl/" + "x" * 10 + (run / "raw" / "t.json").write_text(json.dumps({"auth": slashy}).replace("/", "\\/") + "\n") + (run / "raw" / "blob.bin").write_bytes(b"\0\xff" + KEY.encode()) + env = {"DEMO_API_KEY": KEY, "DEMO_URL": url, "SHORT_TOKEN": "abc", "OTHER": "not-a-secret-at-all", "SLASHY_TOKEN": slashy} + vals = scrub.values_from_env(["*_API_KEY", "DEMO_URL", "*_TOKEN"], env) + assert {label for _, label in vals} == {"DEMO_API_KEY", "DEMO_URL", "SHORT_TOKEN", "SLASHY_TOKEN"} + vals.append((SHORTER, "PREFIX")) + res = scrub.scrub([run], vals) + assert res.skipped_short == ["SHORT_TOKEN"] + log = (run / "raw" / "log.txt").read_text() + assert "calling " in log and "" in log and KEY not in log + assert "" in (run / "raw" / "t.json").read_text() + assert (run / "raw" / "blob.bin").read_bytes().endswith(KEY.encode()) # binary left alone + assert scrub.scrub([run], vals, check=True).hits == {} + + +def test_scrub_values_file(tmp_path): + vf = tmp_path / "secrets.env" + vf.write_text(f"# comment\nexport A_KEY='{KEY}'\n\nB_TOKEN=\nbare-value-0123456789\n") + assert scrub.values_from_file(vf) == [(KEY, "A_KEY"), ("bare-value-0123456789", "secret")] + + +def test_scrub_cli_check_and_write(tmp_path, monkeypatch, capsys): + f = tmp_path / "out.jsonl" + f.write_text(json.dumps({"msg": f"key {KEY}"}) + "\n") + monkeypatch.setenv("BK_TEST_API_KEY", KEY) + assert cli.main(["scrub", str(f), "--env", "BK_TEST_*", "--check"]) == 1 + assert KEY in f.read_text() + assert cli.main(["scrub", str(f), "--env", "BK_TEST_*"]) == 0 + assert cli.main(["scrub", str(f), "--env", "BK_TEST_*", "--check"]) == 0 + assert "" in f.read_text() + out = capsys.readouterr().out + assert KEY not in out + assert cli.main(["scrub", str(f)]) == 1 # no values given + + +# ------------------------------------------------------------------ check-run + +AUTH_LINES = [ + '{"type":"error","error":{"type":"authentication_error","message":"OAuth access token has been revoked."}}', + "Error: 401 Unauthorized", + "openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided'}}", + '{"error": {"message": "User not found.", "code": 401}, "status": 401}', + "gh: Bad credentials (HTTP 401)", + "Invalid API key. Please run /login", + "codex: refresh token has expired, sign in again", +] +CLEAN_LINES = [ + '{"usage": {"input_tokens": 401, "output_tokens": 401, "total_tokens": 802}}', + "processed 401 tasks, token budget ok", + "the model said the key rotation design is invalid in two places", +] + + +@pytest.mark.parametrize("line", AUTH_LINES) +def test_auth_markers_found(line): + assert runcheck.auth_hits(line, runcheck.compile_patterns()) + + +@pytest.mark.parametrize("line", CLEAN_LINES) +def test_no_false_auth_on_ordinary_text(line): + assert runcheck.auth_hits(line, runcheck.compile_patterns()) == [] + + +def test_excerpt_masks_key(): + hits = runcheck.auth_hits(f"401 Unauthorized: invalid api key {KEY}", runcheck.compile_patterns(), "r.log") + assert hits and KEY not in hits[0].excerpt and "" in hits[0].excerpt + + +def trial(root, name, text="all good", files=("result.json",)): + d = root / name + d.mkdir(parents=True) + for f in files: + (d / f).write_text(json.dumps({"exit_code": 0, "log": text}) + "\n") + return d + + +def test_check_trial_auth_skip_only_require(tmp_path): + t = trial(tmp_path, "t1", files=("result.json",)) + (t / "agent").mkdir() + (t / "agent" / "transcript.jsonl").write_text('{"tool_output": "HTTP/1.1 401 Unauthorized from the target app"}\n') + assert runcheck.check_trial(t).status == "auth-error" + assert runcheck.check_trial(t, skip=["transcript.jsonl"]).status == "ok" + assert runcheck.check_trial(t, only=["result.json"]).status == "ok" + c = runcheck.check_trial(t, require=["result.json", "verifier/*.json"], skip=["agent/*"]) + assert c.status == "incomplete" and c.missing == ["verifier/*.json"] + err = runcheck.sample_error(runcheck.check_trial(t)) + assert err["source"] == "infra" and err["type"] == "auth" + assert runcheck.sample_error(runcheck.check_trial(t, skip=["agent/*"])) is None + + +def test_check_run_cli_exit_codes_and_streak(tmp_path, capsys): + ok = trial(tmp_path, "ok") + bad = [trial(tmp_path, f"bad{i}", text="AuthenticationError: invalid x-api-key") for i in range(3)] + assert cli.main(["check-run", str(ok)]) == 0 + assert cli.main(["check-run", str(ok), "--require", "missing.txt"]) == 1 + assert cli.main(["check-run", str(bad[0]), str(ok)]) == 2 # auth error, streak reset by the clean trial + assert cli.main(["check-run", *map(str, bad)]) == 3 # 3 in a row stops the sweep + sf = tmp_path / "streak.json" + assert cli.main(["check-run", str(bad[0]), "--streak-file", str(sf), "--stop-after", "2"]) == 2 + assert cli.main(["check-run", str(bad[1]), "--streak-file", str(sf), "--stop-after", "2"]) == 3 + assert cli.main(["check-run", str(ok), "--streak-file", str(sf), "--stop-after", "2"]) == 0 + assert json.loads(sf.read_text())["consecutive_auth_errors"] == 0 + capsys.readouterr() + assert cli.main(["check-run", str(bad[0]), "--json"]) == 2 + out = json.loads(capsys.readouterr().out) + assert out["trials"][0]["status"] == "auth-error" and out["stop_sweep"] is False + + +def test_check_run_extra_pattern(tmp_path): + t = trial(tmp_path, "t", text="provider said: SESSION_GONE") + assert runcheck.check_trial(t).status == "ok" + assert runcheck.check_trial(t, extra_patterns=[r"session_gone"]).status == "auth-error" + + +# ------------------------------------------------------------------ ledger + + +def test_ledger_from_run_merges_and_validates(tmp_path): + rows = samples() + rows[0]["error"] = {"source": "infra", "type": "auth", "message": "401 " + "x" * 500} + rows[0]["evaluation"]["score"] = None + write_repo(tmp_path, rows=rows) + p = ledger.write(tmp_path, "sweep-1", runs=["2026-10-09-ab"], status="running") + data = json.loads(p.read_text()) + assert p == tmp_path / "data" / "sweeps" / "sweep-1.json" + assert data["schema_version"] == "bench-sweep/1" and data["bench"] == "demo-bench" + assert data["counts"] == {"records": 12, "scored": 11, "errored": 1, "skipped": 0, "auth_errors": 1} + errored = [r for r in data["records"] if r["status"] == "errored"][0] + assert len(errored["error"]["message"]) == ledger.MSG_MAX + started = data["started_at"] + # a later call merges: same key replaced, new record added, started_at kept + fixed = {"run_id": "2026-10-09-ab", "sample_id": rows[0]["sample_id"], "subject": rows[0]["subject"], "repeat": rows[0]["repeat"]} + fixed.update(status="scored", score=1.0, error=None) + extra = {"run_id": None, "sample_id": "t9", "subject": "C", "repeat": 1, "status": "skipped", "note": "endpoint stopped"} + p = ledger.write(tmp_path, "sweep-1", records=[fixed, extra], status="halted", halted="3 consecutive auth errors") + data = json.loads(p.read_text()) + assert data["started_at"] == started and data["status"] == "halted" and data["halted"].startswith("3 consecutive") + assert data["counts"] == {"records": 13, "scored": 12, "errored": 0, "skipped": 1, "auth_errors": 0} + assert data["runs"] == ["2026-10-09-ab"] + assert codes(tmp_path) == ["BL013"] # ledger is valid bench-sweep/1; the auth row still flags the run + + +def test_ledger_rejects_bad_input(tmp_path): + write_repo(tmp_path) + with pytest.raises(ValueError): + ledger.write(tmp_path, "../x") + with pytest.raises(ValueError): + ledger.write(tmp_path, "s", runs=["no-such-run"]) + with pytest.raises(ValueError): + ledger.write(tmp_path, "s", records=[{"sample_id": "t1", "subject": "A", "status": "done"}]) + + +def test_ledger_cli_records_file_and_ignored_warning(tmp_path, capsys): + write_repo(tmp_path) + git_init(tmp_path) + rec = tmp_path / "records.jsonl" + rec.write_text(json.dumps({"run_id": "r1", "sample_id": "t1", "subject": "A", "repeat": 1, "status": "scored", "score": 1}) + "\n") + assert cli.main(["ledger", "s1", "--root", str(tmp_path), "--records", str(rec), "--run", "2026-10-09-ab"]) == 0 + data = json.loads((tmp_path / "data/sweeps/s1.json").read_text()) + assert data["status"] == "finished" and data["runs"] == ["2026-10-09-ab", "r1"] and data["counts"]["records"] == 13 + (tmp_path / ".gitignore").write_text("data/\n") + assert cli.main(["ledger", "s2", "--root", str(tmp_path), "--records", str(rec)]) == 2 + assert "gitignored" in capsys.readouterr().err + + +# ------------------------------------------------------------------ lint BL001 / BL012 / BL013 + + +def test_bl012_ignored_ledger_dir_and_runs(tmp_path): + write_repo(tmp_path) + git_init(tmp_path) + assert "BL012" not in codes(tmp_path) + (tmp_path / ".gitignore").write_text("runs/*/raw/\n") # raw transcripts ignored: fine + assert "BL012" not in codes(tmp_path) + (tmp_path / ".gitignore").write_text("/data/\n/runs/\n") + found = [f for f in lint.lint(tmp_path) if f.rule == "BL012"] + assert {f.path for f in found} == {"data/sweeps/", "runs/2026-10-09-ab/manifest.json", "runs/2026-10-09-ab/samples.jsonl"} + assert all(f.level == "warning" for f in found) + (tmp_path / ".bench-lint-ignore").write_text("BL012 * this repo keeps runs in an external store\n") + assert "BL012" not in codes(tmp_path) + + +def test_bl012_skipped_outside_git(tmp_path): + write_repo(tmp_path) + (tmp_path / ".gitignore").write_text("/data/\n") + assert "BL012" not in codes(tmp_path) + + +def test_bl013_auth_rows_in_complete_run(tmp_path): + rows = samples() + rows[3]["error"] = {"source": "infra", "type": "auth", "message": "OAuth access token has been revoked"} + write_repo(tmp_path, rows=rows) + found = [f for f in lint.lint(tmp_path) if f.rule == "BL013"] + assert len(found) == 1 and "1 row(s)" in found[0].message + other = tmp_path / "other" + other.mkdir() + write_repo(other, manifest(status="partial"), rows=rows) + assert "BL013" not in codes(other) + + +def test_bl001_bad_bench_sweep_ledger_and_foreign_format(tmp_path): + write_repo(tmp_path) + d = tmp_path / "data" / "sweeps" + d.mkdir(parents=True) + (d / "own-format.json").write_text(json.dumps({"header": {}, "records": [{"task": "x"}]})) + assert codes(tmp_path) == [] + (d / "s1.json").write_text(json.dumps({"schema_version": "bench-sweep/1", "sweep_id": "other", "status": "done"})) + msgs = [f.message for f in lint.lint(tmp_path) if f.rule == "BL001"] + assert any("status" in m for m in msgs) and any("differs from file name" in m for m in msgs) diff --git a/uv.lock b/uv.lock index 034db6a..997dca4 100644 --- a/uv.lock +++ b/uv.lock @@ -17,7 +17,7 @@ wheels = [ [[package]] name = "bench-kit" -version = "0.5.1" +version = "0.6.0" source = { editable = "." } dependencies = [ { name = "jsonschema" },