From 033a81d25aae7b3fe028638b0bc50c7f72f37710 Mon Sep 17 00:00:00 2001 From: Aizat Hawari Date: Fri, 27 Nov 2026 22:55:47 +0000 Subject: [PATCH 1/3] feat(exp35): hosted compute-table items and readiness ticks (task 16.20) - hostedusage35.py: hosted tokens and cost per role, error rows, resends, closed calls, billing per provider, energy estimate, stops, returned model. - run_arms.py writes every rate-limit and out_of_credit stop to stops.jsonl; RateLimitStop carries its kind. - A18 item 35: GLM-5.3 and classifier tokens come from billing exports. - protocol section 7: concurrency values and stop rule (task 10.4). - tasks.md: tick 9.2, 10.2, 10.4, 11.0, 11.2, 11.3, 13.5, 14.6, 16.2, 16.20, 16.35 with evidence; tripwire +9 by test-ID diff. --- .../35-full-rag-benchmark-2026-11-01/arms.py | 4 +- .../hostedusage35.py | 165 +++++++++++++++++ .../preregistration.md | 4 +- .../protocol.md | 2 + .../reporttables35.py | 11 +- .../run_arms.py | 2 + experiments/_lib/hosted_calls.py | 11 +- .../changes/exp35-main-run-readiness/tasks.md | 33 ++-- tests/test_clean_base_tripwire.py | 4 +- tests/test_experiment35_hosted_usage.py | 166 ++++++++++++++++++ tests/test_experiment35_run_arms.py | 27 +++ tests/test_experiment_hosted_calls.py | 6 +- 12 files changed, 415 insertions(+), 20 deletions(-) create mode 100644 experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py create mode 100644 tests/test_experiment35_hosted_usage.py diff --git a/experiments/35-full-rag-benchmark-2026-11-01/arms.py b/experiments/35-full-rag-benchmark-2026-11-01/arms.py index 67812c464..261a28415 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/arms.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/arms.py @@ -49,8 +49,8 @@ ANSWER_CONTEXT_WINDOW = 131072 ANSWER_MAX_ROUNDS = 1 -#: Starting concurrency and attempt values (design D18). Task 9.2 replaces them -#: with the measured values before the freeze. +#: Concurrency and attempt values (design D18), confirmed by the test pod sessions +#: (task 10.4, 2026-11-27): no rate-limit stop at these values (protocol section 7). CONCURRENCY_DEFAULTS: Mapping[str, int] = { "answer_concurrency": 16, "chat_concurrency": 4, diff --git a/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py b/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py new file mode 100644 index 000000000..0d20e51d3 --- /dev/null +++ b/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py @@ -0,0 +1,165 @@ +"""Hosted-call items of the Experiment 35 compute table (task 16.20; prereg sections 17, 21). + +Each function reads saved files only; a value that is not defined reads +:data:`NOT_DEFINED`. + +- :func:`hosted_usage`: per stage (the output kind, for example ``answer`` or + ``closedbook-own``) and role, the rows, calls, error rows, harness resends + (``resent_calls``), calls closed as missing after the resend cap, and the + tokens and cost. The answer and Ragas rows record tokens and cost per call. + The GLM-5.3 claim checks and the claim classifier record none, so their + tokens and cost come from the provider billing exports (amendment A18 item 35). + A sum is defined only when every call reported the figure. +- :func:`billing_by_provider`: the ``usd`` of the billing rows per provider. +- :func:`energy_estimate`: closed GPU pod hours times the board power of the + RTX 4090 (450 W), in kWh (Strubell et al. 2019; Lacoste et al. 2019). +- :func:`record_stop` and :func:`stops`: every rate-limit and ``out_of_credit`` + stop (``stops.jsonl``, written by ``run_arms.py``). +- :func:`returned_models`: the returned-model counts per role from ``join.json``. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable, Mapping, Sequence +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from outputs35 import read_rows + +NOT_DEFINED = "not defined" +#: RTX 4090 board power in watts (NVIDIA specification), the only GPU type (protocol 9.3). +BOARD_WATTS = 450 +#: Row file, its role, its summary file, and where its tokens and cost come from. +ROLES = ( + ("answer.jsonl", "answer", "answer-summary.json", "rows"), + ("ragas.jsonl", "ragas-judge", "ragas-summary.json", "rows"), + ("judge-chat.jsonl", "judge-glm", "judge-chat-summary.json", "billing export"), + ("claim-kinds.jsonl", "claim-classifier", "claimkinds-summary.json", "billing export"), +) + + +def _calls(role: str, row: Mapping[str, Any]) -> list[Mapping[str, Any]]: + """Return the hosted calls one row holds, each with its figures and error.""" + if role == "ragas-judge": + return list(row.get("calls") or []) + if role == "judge-glm": + return [v.get("call") or {} for v in row.get("verdicts") or []] + return [row] + + +def _is_error(call: Mapping[str, Any]) -> bool: + return call.get("status") == "error" or bool(call.get("error")) + + +def _first(call: Mapping[str, Any], names: Sequence[str]) -> float | None: + return next((call[n] for n in names if isinstance(call.get(n), (int, float))), None) + + +def _total(calls: Sequence[Mapping[str, Any]], *names: str) -> float | str: + values = [_first(c, names) for c in calls] + if not values or None in values: + return NOT_DEFINED + return round(sum(v for v in values if v is not None), 12) + + +def _empty(stage: str, role: str, source: str) -> dict[str, Any]: + return { + "stage": stage, + "role": role, + "source": source, + "rows": 0, + "calls": [], + "error_rows": 0, + "resent_calls": 0, + "closed_missing": 0, + "summaries_missing": 0, + } + + +def hosted_usage(out: Path) -> dict[str, Any]: + """Return per stage and role the hosted calls, errors, resends, tokens and cost.""" + found: dict[tuple[str, str], dict[str, Any]] = {} + for name, role, summary_name, source in ROLES: + for path in sorted(out.glob(f"*/*/*/run*/{name}")): + stage = path.parts[-4] + per = found.setdefault((stage, role), _empty(stage, role, source)) + for row in read_rows(path): + if row.get("missing"): + continue + calls = _calls(role, row) + per["rows"] += 1 + per["calls"].extend(calls) + per["error_rows"] += any(_is_error(c) for c in calls) + summary_path = path.parent / summary_name + if summary_path.is_file(): + summary = json.loads(summary_path.read_text(encoding="utf-8")) + per["resent_calls"] += int(summary.get("resent_calls") or 0) + per["closed_missing"] += len(summary.get("closed_missing") or []) + else: + per["summaries_missing"] += 1 + rows = [] + for _, per in sorted(found.items()): + calls = per.pop("calls") + by_rows = per["source"] == "rows" + rows.append( + { + **per, + "calls": len(calls), + "resent_calls": NOT_DEFINED if per["summaries_missing"] else per["resent_calls"], + "input_tokens": _total(calls, "input_tokens") if by_rows else NOT_DEFINED, + "output_tokens": _total(calls, "output_tokens") if by_rows else NOT_DEFINED, + "cost_usd": _total(calls, "cost_usd", "reported_cost_usd") + if by_rows + else NOT_DEFINED, + } + ) + return {"roles": rows} + + +def billing_by_provider(paths: Iterable[Path]) -> dict[str, float] | str: + """Return the billed ``usd`` per provider, else "not defined" without billing files.""" + totals: dict[str, float] = {} + for path in paths: + for row in json.loads(path.read_text(encoding="utf-8")): + provider = str(row["provider"]) + totals[provider] = round(totals.get(provider, 0.0) + float(row["usd"]), 12) + return dict(sorted(totals.items())) if totals else NOT_DEFINED + + +def energy_estimate(compute: Mapping[str, Any] | str) -> dict[str, Any] | str: + """Return the closed GPU pod hours times the board power, in kWh.""" + if not isinstance(compute, Mapping): + return NOT_DEFINED + hours = sum(float(s["closed_pod_hours"]) for s in compute["stages"]) + return {"gpu_hours": hours, "board_watts": BOARD_WATTS, "kwh": hours * BOARD_WATTS / 1000} + + +def record_stop(args: Any, stop: BaseException) -> None: + """Append one stop to ``/stops.jsonl`` (``run_arms.py`` calls it on exit code 5).""" + folder = Path(args.out_dir) + folder.mkdir(parents=True, exist_ok=True) + line = { + "kind": getattr(stop, "kind", "rate_limit"), + "stage": args.stage, + "dataset": args.dataset, + "setup": getattr(args, "setup", None) or getattr(args, "index", None), + "message": str(stop), + "at": datetime.now(UTC).isoformat(), + } + with (folder / "stops.jsonl").open("a", encoding="utf-8") as handle: + handle.write(json.dumps(line, ensure_ascii=False) + "\n") + + +def stops(out: Path) -> list[dict[str, Any]]: + """Return every rate-limit and ``out_of_credit`` stop the runner saved.""" + return read_rows(out / "stops.jsonl") + + +def returned_models(out: Path) -> dict[str, Any] | str: + """Return the returned-model counts per role from ``join.json``, else "not defined".""" + path = out / "join.json" + if not path.is_file(): + return NOT_DEFINED + return json.loads(path.read_text(encoding="utf-8")).get("returned_model", NOT_DEFINED) diff --git a/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md b/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md index e82d72474..379fa448e 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md +++ b/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md @@ -419,7 +419,7 @@ The word "sealed" applies to indexes only. Half B is held out from every selecti ## 17. Budget, ceiling, stop rule and drop order - **Estimate (amended 2026-11-25, pre-freeze, owner approval).** **$1,122**: RunPod GPU (RTX 4090) $410; OpenRouter answers (DeepSeek V4.1 Flash) $180; OpenRouter Ragas judge and claim sorter (gpt-oss-120b) $142; GLM-5.3 claim checks (Z.ai API) $390. The old $730 assumed GLM-5.3 claim checks at no cost; they now run on the paid API. The RunPod line rests on P2 timing (pod `q2pr74unxye0mj`, 2026-11-25): one full FreshStack index (`e8b-c512`, 49,506 files) took 5.65 h; 2,747-file samples gave 0.20 to 0.31 s per file. The nine FreshStack indexes plus the `e4b-c1024` rebuild project to about 45 pod hours (about $40), with each sample rate scaled by 1.33, the full-to-sample ratio measured on `e8b-c512` before the compaction fix `784e478c`. With that fix the build should be faster (not yet measured on a pod), so the figure is conservative. These builds ran with file-type routing on (amendment A13). With routing off, the 600-file check gives 6.1% fewer chunks and 0.4% fewer embedded tokens, so the figure still holds as an upper bound. -- **Ceiling (amended 2026-11-25).** **$1,716** (was $975), pods and hosted calls together: the estimate plus $594 reserve (RunPod reserve for 3 times slower reranking $230; RunPod repeat runs, 10%, $64; price changes, about 10%, $150; failed calls rerun, 10%, $150). RunPod share $704; hosted share $1,012. The OpenRouter key carries a credit limit for the OpenRouter roles only (amended 2026-11-26, pre-freeze, owner; `plan.json` amendment A15): the hosted share $1,012 minus the $390 GLM-5.3 line, **$622**, so an OpenRouter overrun ends in a clean `out_of_credit` stop. GLM-5.3 runs on the owner's Z.ai API key, outside that limit; each run records its GLM-5.3 calls and tokens, and the budget checks count them. The Z.ai endpoint is pinned by SHA-256 and is never printed. The checks, run guard, drop order and stop rule are unchanged (`plan.json` amendment A8). +- **Ceiling (amended 2026-11-25).** **$1,716** (was $975), pods and hosted calls together: the estimate plus $594 reserve (RunPod reserve for 3 times slower reranking $230; RunPod repeat runs, 10%, $64; price changes, about 10%, $150; failed calls rerun, 10%, $150). RunPod share $704; hosted share $1,012. The OpenRouter key carries a credit limit for the OpenRouter roles only (amended 2026-11-26, pre-freeze, owner; `plan.json` amendment A15): the hosted share $1,012 minus the $390 GLM-5.3 line, **$622**, so an OpenRouter overrun ends in a clean `out_of_credit` stop. GLM-5.3 runs on the owner's Z.ai API key, outside that limit; each run records its GLM-5.3 calls, the Z.ai billing export gives their tokens and cost, and the budget checks count them. The Z.ai endpoint is pinned by SHA-256 and is never printed. The checks, run guard, drop order and stop rule are unchanged (`plan.json` amendment A8). - **Checks**: before the freeze (test pod extrapolation), on the build pods after the search stage, and at each stage end while the replicate pods run. Each projection uses billing and measured rates only, never scores. Money spent is the sum of the `usd` values of the provider billing rows, each row given as `{provider, usd}`. A projection reaches the ceiling when it is $1,716 or more (amended 2026-11-25; was $975). A budget tool writes each projection to `budget-check.json` and each applied drop step to `drops.json`. The join of stage outputs, the label sampler and the report read the drop record. - **Run guard.** A main stage refuses to start while `plan.json` `frozen` is empty, and refuses a dirty tree. A pre-freeze run needs an explicit flag. Like every run, it appends one line to `output/run-records.jsonl` (the repository rule), and that line carries `prefreeze: true`. A smoke run (a run with named questions, `--qids`) also appends one line, and that line carries `smoke: true`. The main join and every main-run check ignore lines with either field. A smoke join counts a `smoke: true` line as its run's record. Each run record holds the SHA-256 of this file. Every stage key and every done-marker also hold the run mode (`main`, `prefreeze` or `smoke`). A `--resume` with another run mode than the saved key refuses with exit code 2, so a main run never accepts a pre-freeze or smoke row as done. Every stage that reads an index (search, answer and judge) checks, before its first query, that the index's ingest done-marker holds the configuration its own key expects: the settings of `-roff-hon` with no answer host and no judge. A difference stops the stage with exit code 2 and names each field. A main run also requires an index built by a main run. The oracle stage does not search, so it does not check the index. - **Drop order at the ceiling** (results-blind, applied in order, each step recorded with the projection that triggered it): (1) Legal RAG Bench answer generation; (2) the length-controlled check; (3) the closed-book run with the RAG prompt; then stop. The owner approved this order on 2026-11-14. Step 1 also removes the 50 Legal correctness labels (section 11.2: correctness sample 150, L1 700, L2 700 in the full plan, 315 at the staged first stage or 630 under the A18 plan). After drop step 1 is recorded, the answer stage on Legal RAG Bench sends nothing, writes no file and exits with code 0; the analysis writes the Legal answer rows 12 to 19 as `dropped` and still computes the Legal search rows 1 to 11. Without a drop record, a dataset with no answers stops the analysis. E1 is not in this order: it has its own ceiling (P16). No confirmatory item is dropped by choice. If the closed-book RAG-prompt run is dropped, the contamination sensitivity (section 13) uses the own-knowledge closed-book run alone, and the report says so. @@ -491,7 +491,7 @@ After the freeze, every change is a dated, numbered deviation. The report lists - Counts per setup and dataset of chunks with no page label and of unmapped chunks (placeholder units, section 6), and the count of fenced rows per file extension in the FreshStack export (section 4). - Per question and answer setup, the cut total and the realised evidence token total (section 3), with the share of questions where the assembled evidence is shorter than the cut total. - Sensitivity tables: GEE against permutation disagreements; FinanceBench nDCG@10 for rows 9 and 10 (a chunk covers its page), with sign agreement per row against `evidence_recall_20k` (H6); FreshStack `evidence_recall_20k` for rows 9 to 11, descriptive; the four H7 corner-cell means with 95% intervals beside row 11; missing-outcome bounds; closed-book subset; length-controlled check; H8b on questions with a cut total of at least 95% of the token budget in all three `-t20k` setups, with both token totals (cut and realised) per setup; faithfulness with uncited factual segments as unsupported, beside the uncited-segment share. -- **Compute table**: GPU type, pod hours per stage including every pre-freeze pod (test pod, GPU timing, smoke runs), hosted tokens and cost per role, an energy estimate (GPU hours times board power; Strubell et al. 2019; Lacoste et al. 2019), `resent_calls` (harness-level resends only, section 12), calls closed as missing after the resend cap, error rows per stage and role, and every `out_of_credit` stop. +- **Compute table**: GPU type, pod hours per stage including every pre-freeze pod (test pod, GPU timing, smoke runs), hosted tokens and cost per role (answer and Ragas calls from the saved rows; GLM-5.3 and claim-classifier calls from the provider billing exports, because those calls save no token counts), an energy estimate (GPU hours times board power; Strubell et al. 2019; Lacoste et al. 2019), `resent_calls` (harness-level resends only, section 12), calls closed as missing after the resend cap, error rows per stage and role, and every `out_of_credit` stop. - Model labeller agreement per set beside the checker and judge agreements (section 11.3; descriptive). - A18 additions: classifier development rounds 1 and 2 in full (section 11.1); all-claims faithfulness beside the primary measure (section 11.1); the pooled H8 estimate beside both per-dataset estimates (section 9 point 7); the relevance audit tables (section 11.3). - Returned model ID and provider per hosted call, with the count of differences from the requested values. diff --git a/experiments/35-full-rag-benchmark-2026-11-01/protocol.md b/experiments/35-full-rag-benchmark-2026-11-01/protocol.md index 3f6d2433f..9aaa8bc94 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/protocol.md +++ b/experiments/35-full-rag-benchmark-2026-11-01/protocol.md @@ -480,6 +480,7 @@ Written before the freeze. No measured run has started and no L2 label exists. O 32. **Model labeller (owner decision, 2026-11-27).** Claude Opus 5.5 at high effort labels every item on the blind pages after both human label sets are frozen and hashed. Descriptive agreement only; no human label changes. The human review of model disagreements (a third pass) was considered and rejected: it adds work and its labels would be anchored. Pre-registration sections 11.3, 21 and 22. 33. **Build clarifications (2026-11-27, from the P19 build).** A row with zero estimate variance on either dataset is not pooled. The undefined-statistic rules of section 11.2 apply to the sensitivity difference; a chunk-size level with no human-unsupported claim is undefined. Wording only. 34. **Audit output is an estimate (2026-11-27, PR 238 review).** Pre-registration sections 11.3 and 22 now call the H3 audit output an estimate restricted to arm-exclusive unjudged units, not a bound. An unjudged unit in the top 3 of both arms at different ranks is not covered. Wording only. Source: CodeRabbit on PR #238. +35. **Hosted tokens of the GLM-5.3 and classifier calls (owner decision, 2026-11-27, task 16.20).** The GLM-5.3 claim checks and the claim classifier save no token counts per call; only the answer and Ragas calls do. Pre-registration sections 17 and 21 now take the tokens and cost of those two roles from the provider billing exports (Z.ai and OpenRouter). Recording them per call was considered and rejected: it changes the OMRS judge record and the HTTP API contract before the freeze. `hostedusage35.py` builds the hosted part of the compute table; `run_arms.py` saves every rate-limit and `out_of_credit` stop to `stops.jsonl`. No hypothesis, test, gate or budget figure changes. ## 1. Question @@ -790,6 +791,7 @@ The smoke subset (task 4.1) runs a small slice of each dataset through every arm (Superseded by A1: the ONNX reranker is gone; every reranker runs on llama.cpp.) The ONNX reranker and the OCR engines do not run through llama.cpp. The freeze records them under the runtime manifest with name, revision and file hash. The embedding tokenizer (`Qwen/Qwen3-Embedding-4B`, `tokenizer.json`, revision `5cf2132a`) is the token-aware chunking tokenizer, cached and hash-checked by sweep task 2.4a. - **Hosted references** (section 3, ADR-119): answer model `deepseek/deepseek-v4.1-flash-1017` (OpenRouter, temperature 0, seed 20261101, one pinned upstream host); main Ragas judge `openai/gpt-oss-120b` (OpenRouter, reasoning `low`, temperature 0, fixed seed, one pinned upstream host); cross-check judge `openai/gpt-6.1-terra` (OpenRouter, fixed seed, 50 hand-checked items; superseded by A4: removed); main claim checker GLM-5.3 (Z.AI, section 4.4). A judge never scores its own model family. +- **Concurrency and stops (task 10.4, recorded 2026-11-27, pre-freeze).** The main run uses the `arms.CONCURRENCY_DEFAULTS` values: `--answer-concurrency 16`, `--chat-concurrency 4`, `--ragas-concurrency 16`, `--classify-concurrency 16` and `--rate-limit-attempts 6`. Measured basis: the test pod sessions of 2026-11-24 and 2026-11-26 ran every hosted stage at these values with no rate-limit stop (no exit code 5); the 2026-11-24 log shows 29 client-library transport retries after HTTP 429 from OpenRouter, all of which then succeeded. Transport retries inside the client libraries are not counted in `resent_calls` (section 0.14 item 10); cost comes from provider billing. Exit code 5 is a rate-limit or `out_of_credit` stop: finished rows are kept, no done-marker is written, and `run_arms.py` appends the stop to `stops.jsonl`. The operator runs the same command again with `--resume`, at half the concurrency of the stopped role after a rate-limit stop, and after a top-up after an `out_of_credit` stop. The resend rule is section 0.14 item 9: an error row is pending, and a call closes as missing after 3 non-rate-limit errors; rate-limit waits do not count toward that cap. - **Ragas stage stops** (A5, section 0.14 item 46): exit code 5 is a rate-limit stop and saves nothing for the answer in flight. Exit code 6 means a metric is still open below the error cap, and `.done-ragas.json` is not written. After either code, run the same command again with `--resume`; only the open metrics are sent again. - **Tolerance**: 0.005 absolute on nDCG@10, the only primary metric, and on the secondary Recall@10, MRR@10 and hit@page (A2; nDCG@10 only is primary). The largest change that still counts as the same result on another back end. Confirm or change at freeze. - **Live check**: the runner calls `verify_llamacpp_runtime` before the first score of each run and passes `runtime=found.as_run_record()` to `record_run_start`. A mismatch stops the run. diff --git a/experiments/35-full-rag-benchmark-2026-11-01/reporttables35.py b/experiments/35-full-rag-benchmark-2026-11-01/reporttables35.py index 483c391a4..1a1f56de8 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/reporttables35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/reporttables35.py @@ -68,6 +68,7 @@ import cells35 # noqa: E402 import datasets35 # noqa: E402 import factorial35 # noqa: E402 +import hostedusage35 # noqa: E402 import join35 # noqa: E402 import reportextra35 # noqa: E402 import scoring35 # noqa: E402 @@ -362,6 +363,7 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("--records", type=Path, nargs="*", default=[], help="pod run records") parser.add_argument("--rates", type=Path, help="budget rates file (pod_usd_per_hour)") parser.add_argument("--passages-dir", type=Path, help="the prepared passages folder") + parser.add_argument("--billing", type=Path, nargs="*", default=[], help="billing row files") args = parser.parse_args(argv) out = args.out_dir scoring35.require_half_b(out) # the tables hold half-B scores (section 14.2) @@ -393,7 +395,14 @@ def main(argv: Sequence[str] | None = None) -> int: "alpha_ndcg_freshstack": _json(out / "alpha-ndcg.json") or NOT_RUN, "hybrid_trigger": hybrid_trigger_table(out), "number_match": number_match(out), - "compute": compute(args.records, args.rates), + "compute": (computed := compute(args.records, args.rates)), + "hosted": { + "usage": hostedusage35.hosted_usage(out), + "billing_by_provider": hostedusage35.billing_by_provider(args.billing), + "energy": hostedusage35.energy_estimate(computed), + "stops": hostedusage35.stops(out), + "returned_model": hostedusage35.returned_models(out), + }, "fenced_rows": reportextra35.fenced_rows(args.passages_dir) if args.passages_dir else reportextra35.NOT_DEFINED, diff --git a/experiments/35-full-rag-benchmark-2026-11-01/run_arms.py b/experiments/35-full-rag-benchmark-2026-11-01/run_arms.py index c3d75b946..c94ec2cc8 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/run_arms.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/run_arms.py @@ -80,6 +80,7 @@ import closedbook35 # noqa: E402 import datasets35 # noqa: E402 import determinism35 # noqa: E402 +import hostedusage35 # noqa: E402 import judges35 # noqa: E402 import lengthcheck35 # noqa: E402 import oracle35 # noqa: E402 @@ -187,6 +188,7 @@ def main(argv: Sequence[str] | None = None, *, deps: Any = None) -> int: return EXIT_JUDGE except RateLimitStop as stop: say(f"[stop] {stop}; finished rows are kept, no done-marker. Run again with --resume.") + hostedusage35.record_stop(args, stop) return EXIT_RATE_LIMIT except stages35.StageIncomplete as open_items: say(f"[open] {open_items}") diff --git a/experiments/_lib/hosted_calls.py b/experiments/_lib/hosted_calls.py index 0efcef2e3..d146b106c 100644 --- a/experiments/_lib/hosted_calls.py +++ b/experiments/_lib/hosted_calls.py @@ -46,8 +46,16 @@ class RateLimitStop(RuntimeError): The stage keeps the results that finished, writes no done-marker and exits with the rate-limit exit code. A later ``--resume`` sends the call again. + + Attributes: + kind: ``rate_limit`` or ``out_of_credit`` (the report lists each stop). """ + def __init__(self, message: str = "", *, kind: str = "rate_limit") -> None: + """Keep the message and the stop kind.""" + super().__init__(message) + self.kind = kind + @dataclass(frozen=True) class RateLimit: @@ -152,7 +160,8 @@ def _wait(self, limit: RateLimit, attempt: int) -> float: if limit.kind == OUT_OF_CREDIT: raise RateLimitStop( f"{self.role}: the provider account is out of credit (HTTP {status}); " - "top up the account, then run the same command with --resume" + "top up the account, then run the same command with --resume", + kind=OUT_OF_CREDIT, ) if attempt >= self.attempts: raise RateLimitStop( diff --git a/openspec/changes/exp35-main-run-readiness/tasks.md b/openspec/changes/exp35-main-run-readiness/tasks.md index e9fd7a358..b6da27543 100644 --- a/openspec/changes/exp35-main-run-readiness/tasks.md +++ b/openspec/changes/exp35-main-run-readiness/tasks.md @@ -395,7 +395,7 @@ The classifier is the fixed-prompt LLM `openai/gpt-oss-120b`, pinned (operator d - [x] 9.1 Resolve the digest of `runpod/base:1.6.0-cuda1281-ubuntu2404` and record it before the freeze. Record `runpod/base@sha256:` in `protocol.md` section 7 and in the `plan.json` `runtime` block. Make the Mac pod-creation script pass that one value as the pod image and as `EXP35_POD_IMAGE`. No such script exists in the repository today. If the operator keeps it outside the repository, record its path and the line that sets the image in `protocol.md`. Verify: the digest read from the registry twice gives the same value, and a dry run of pod creation shows the same pinned value for the image and the variable. - [x] 9.1a New pod script for the test pod session (A5, H-32). `prefreeze/pod_prefreeze.sh` stays as the record of the finished session and does not change. Write a new script for task 9.2 with `trap finish EXIT` (guarded so `finish` runs once) and a pod stop after the result tarball is written to `/workspace` (first check inside the pod that `runpodctl` and its key exist). Write failing tests in the style of `prefreeze/test_pod_prefreeze_script.py`: the trap is set before the first stage; a failing stage still writes the tarball; the stop runs after the tarball; dry-run mode prints every command and no key value. Prove they fail (no script), then implement. Verify: the tests pass, and the procedure tells the operator to start the script under `nohup` or `tmux`. -- [ ] 9.2 Run the pre-freeze test pod session (design D24) after groups 0 to 8 and 12 to 14 are merged and their tests pass. Quote the pod price and the expected paid cost (about 6 h, about $5 of pod time plus a few dollars of hosted calls) and wait for the operator's go before creating the pod. Use the standard RTX 4090 pod with the pinned image from task 9.1, its own smoke folder and its own small indexes (`--limit`, `--corpus-sample`); never the main output folder. Every stage passes `--prefreeze` (task 5.7), and the session runs from the new pod script of task 9.1a. +- [x] 9.2 Run the pre-freeze test pod session (design D24) after groups 0 to 8 and 12 to 14 are merged and their tests pass. Quote the pod price and the expected paid cost (about 6 h, about $5 of pod time plus a few dollars of hosted calls) and wait for the operator's go before creating the pod. Use the standard RTX 4090 pod with the pinned image from task 9.1, its own smoke folder and its own small indexes (`--limit`, `--corpus-sample`); never the main output folder. Every stage passes `--prefreeze` (task 5.7), and the session runs from the new pod script of task 9.1a. Partial (2026-11-25, left open: the session had no `ragas` stage and no closed-book check, which this task's step list asks for; they run in the next pod session): the test pod session ran 2026-11-24 23:40 to 2026-11-25 06:30. `~/Development/DATA/omrs/experiments/35-full-rag-benchmark-2026-11-01/p2-session-2026-11-24/watch-summary.txt` reads `RESULT end=done outputs=ok`, `test-session.log` ends `failed stages: none; skipped: none`, and `test-session-out.tgz` has SHA-256 `96c43b4c3fdad1531cd95d94e517004f3111df1f8542beb5cd8d58f8014e5b96` (matches `.sha256`). Stages that ran: setup, gate2-classify, four FreshStack rate builds, three seals, 15 answer rechecks of questions 77536364 and 77762811, and the full e8b-c512 FreshStack index (49,506 files, 20,356 s). Not in this session's stage list: the `ragas` stage, the idle-stop repro (16.31), the embedder preset check (16.36) and the closed-book call check (step 1a); those stay open under their own tasks. 1. End to end, as run 1: ingest, `seal`, search (with a reranker-on and a hybrid-on setup), parallel answers, `clef_flash`, `chat`, `ragas`, `claimkinds`, then `join35.py --smoke --runs 1`. Run the rebuild check once on a toy rebuild of one small index. 1a. Closed-book call (A5 item 49, pre-registration section 13): run `--stage closedbook` on the smoke questions. Each closed-book answer must be one direct completion call to the OMRS answer model. Check that its saved call record (model, host, reasoning, output cap, temperature and seed) equals the frozen answer settings and the answer stage's call records. Then run `ragas` with `--answers closedbook-rag`. Pass rule: every closed-book answer row has `completion_calls` 1, the `answer-summary.json` has `failed` 0, and no saved setting differs from the frozen answer settings. @@ -405,6 +405,7 @@ The classifier is the fixed-prompt LLM `openai/gpt-oss-120b`, pinned (operator d 3. Calibration: answers at 16, `chat` at 4, Ragas at 16, `claimkinds` at 16. Record per role the 429 and 402 counts, the waits, the stops and the calls per minute. Halve a value that hit a rate-limit stop and repeat that role once. Check that each answer's saved ranked list equals the same run's search list, and its evidence chunk IDs equal the head of that list (G1 as A5 defines it, task 6.3). Record the realised chunk-length distribution on FreshStack (A5, fact checks F3 and F4), and run the router idle-stop reproduction of task 16.31. Measure wall seconds per answer per stage and the reported `cost_usd` per answer. 4. The first budget check (design D23 revision): measured build hours per chunk size times 9 indexes, plus the search stage from the measured reranker throughput, plus three replicate pods at the measured hours, all times the pod price, plus the hosted cost per answer times 52,200 (15 answer setups x 3 runs x 1,160 questions), plus the full-corpus FreshStack builds from task 16.2, the two closed-book runs, the oracle run, and the length-controlled check. When the projection reaches the $975 ceiling (superseded 2026-11-25: $1,716), apply the results-blind drop order of design D38 (pre-registration section 17) in order and record each step with the projection that triggered it; no confirmatory item is dropped by choice. 5. Copy the session outputs to the Mac, then delete the pod. + Verified 2026-11-27: the Ragas stage and the closed-book check ran in the test pod session of 2026-11-24 (`test-session-2026-11-24/test-session.log`: `ragas-*`, `ragas-cbown-*`, `ragas-cbrag-*` and `closedbook-fb/bio/fs` end `ok`) and again in the freeze check of 2026-11-26 (`freeze-check-2026-11-26/test-session.log`). The 2026-11-27 layout re-run (PR #231) passed. Every step of the list has now run on a pod. Verify: steps 1 and 2 pass with zero errors; a dated calibration note in `protocol.md` gives the measured values, the counts, the hours per replicate pod and the extrapolated total; design.md D22 holds the measured rates; the `arms.py` defaults equal the measured values; the pod no longer exists in the RunPod pod list. A failure in step 1 or 2 is fixed in code and the session runs again. @@ -442,8 +443,9 @@ The classifier is the fixed-prompt LLM `openai/gpt-oss-120b`, pinned (operator d Done 2026-11-25: `protocol.md` section 5 holds the run procedure (steps 1 to 16 of "Run procedure") and the corrected command lines (the stale "requires `--arm`" sentence is replaced by the real CLI: `--setup` or `--index`, `--stage`; no `--arm`). Section 4.5 carries the amendment of the machine decision. Every command ran with `--help` or `--dry-run` (the `ingest`, `seal`, `search`, `answer`, `judge`, `ragas`, `closedbook`, `oracle`, `claimkinds` and `lengthcheck` stages, `prepare35.py`, `create_pod35.py`, `score35.py`, `select35.py`, `join35.py`, `rebuild35.py`, `budget35.py project`, `refusalreport35.py`, `crosstable35.py`, `contamination35.py`, `searchcost35.py`, `reporttables35.py`, `release35.py`); `--stage determinism` refuses until a passing `join.json` exists, as the procedure states. The confirmatory analysis (`factorial35.analyse`) has no command line yet, and `create_pod35.py` builds only the test-session request (name `omrs-exp35-test-session`). Verify: every command in the procedure runs with `--dry-run` or `--help` as written. -- [ ] 10.2 Write the budget into `preregistration.md` section 17 (A4; it replaces `protocol.md` section 0.8, Exp 35 task 1.11 and the $250 cap of the first 2026-11-12 decision): the estimate of design D38 (about $730, from the D23 figures plus the A4 items) updated with the measured values of tasks 9.2, 9.3 and 16.2, and the ceiling of $975, pods and hosted calls together. State the three checks (design D23): before the freeze, on the index pods after the search stage, and at each stage end during the replicate pods. Each projection uses billing and measured rates only, never scores. State the results-blind drop order of design D38. Set the OpenRouter key's credit limit to the hosted share of the ceiling. Verify: `preregistration.md` states the estimate, the ceiling, the checks, the drop order and the date, and Exp 35 tasks 1.11 and 4A.5 are ticked with a pointer to it. +- [x] 10.2 Write the budget into `preregistration.md` section 17 (A4; it replaces `protocol.md` section 0.8, Exp 35 task 1.11 and the $250 cap of the first 2026-11-12 decision): the estimate of design D38 (about $730, from the D23 figures plus the A4 items) updated with the measured values of tasks 9.2, 9.3 and 16.2, and the ceiling of $975, pods and hosted calls together. State the three checks (design D23): before the freeze, on the index pods after the search stage, and at each stage end during the replicate pods. Each projection uses billing and measured rates only, never scores. State the results-blind drop order of design D38. Set the OpenRouter key's credit limit to the hosted share of the ceiling. Verify: `preregistration.md` states the estimate, the ceiling, the checks, the drop order and the date, and Exp 35 tasks 1.11 and 4A.5 are ticked with a pointer to it. Partial (2026-11-25, left open): `preregistration.md` section 17 now states the amended estimate ($1,122), the ceiling ($1,716), the checks, the drop order and the date, with the P2 build rates (task 16.2), and Exp 35 task 4A.5 is ticked with a pointer to it. Still missing for this verify line: (1) Exp 35 task 1.11 is not ticked; its own verify also asks for wall-time and memory limits with a number, which the budget does not give; (2) no record shows the OpenRouter key credit limit set to $1,012. + Verified 2026-11-27: `preregistration.md` section 17 holds the estimate ($1,122, from the measured P2 rates), the ceiling $1,716 (amended from $975, owner 2026-11-25), the three checks, the results-blind drop order and the OpenRouter key limit $622 (A15). The owner confirms the key limit at the freeze. - [x] 10.3 Write the dated pre-freeze amendment (2026-11-12) into `protocol.md` section 4.4, and add a matching amendment note to ADR-119. It must give: (Verified 2026-11-23: dated amendment in protocol 4.4 and ADR-119 A8 to A10 (accepted by the owner 2026-11-23, see A11).) - the three claim kinds, with mixed sentences and negative findings counted as factual claims; - primary faithfulness on factual claims only, with the reason (a refusal is a statement about retrieval, and the checkers grade refusals very differently); @@ -455,13 +457,17 @@ The classifier is the fixed-prompt LLM `openai/gpt-oss-120b`, pinned (operator d - that Ragas answer scores keep refusals. Verify: the operator reads and accepts the text. -- [ ] 10.4 Write the concurrency options, the rate-limit exit code 5 and the stop-and-resume rule into `protocol.md` sections 5 and 7. The values are the measured ones from task 9.2. Also write the A5 resend rule (task 2.4: error rows are pending, the cap of 3 non-rate-limit errors, what does not count toward it) and the limitation that transport retries inside the client libraries are not counted in `resent_calls`, while cost comes from provider billing (A5 R-3, H-26). Verify: the values match the `arms.py` constants and the calibration note, and the resend text matches task 2.4. +- [x] 10.4 Write the concurrency options, the rate-limit exit code 5 and the stop-and-resume rule into `protocol.md` sections 5 and 7. The values are the measured ones from task 9.2. Also write the A5 resend rule (task 2.4: error rows are pending, the cap of 3 non-rate-limit errors, what does not count toward it) and the limitation that transport retries inside the client libraries are not counted in `resent_calls`, while cost comes from provider billing (A5 R-3, H-26). Verify: the values match the `arms.py` constants and the calibration note, and the resend text matches task 2.4. + Done 2026-11-27: `protocol.md` section 7 bullet "Concurrency and stops" names the `arms.CONCURRENCY_DEFAULTS` values (16, 4, 16, 16, 6 attempts), their basis (no exit code 5 in the 2026-11-24 and 2026-11-26 pod sessions; 29 client transport retries after HTTP 429 on 2026-11-24, all then succeeded), exit code 5 with `stops.jsonl`, the `--resume` rule and the resend cap of 3 (`ordered_rows.ERROR_CAP`). The transport-retry limitation is section 0.14 item 10. `arms.py` comment updated. ## 11. Integration checks (run last, after groups 12 to 16 and the code tasks of group 16; its pre-freeze tasks close before G7) -- [ ] 11.0 CI collects the experiment tests (A5, H-19). Add `experiments/_lib` and `experiments/35-full-rag-benchmark-2026-11-01/prefreeze` to `testpaths` in `pyproject.toml`. First list the collected IDs with and without the change (`uv run --no-sync pytest --collect-only -q`) and record the difference: the 14 `experiments/_lib/test_run_safety.py` tests and the pre-freeze tests (76 at `2c8fb731`). Check that they pass in the parallel run (`--dist loadfile`) and in `./scripts/local_ci.sh`. Verify: the collected-ID difference equals those files, and they pass. Task 11.1 then updates the pin. +- [x] 11.0 CI collects the experiment tests (A5, H-19). Add `experiments/_lib` and `experiments/35-full-rag-benchmark-2026-11-01/prefreeze` to `testpaths` in `pyproject.toml`. First list the collected IDs with and without the change (`uv run --no-sync pytest --collect-only -q`) and record the difference: the 14 `experiments/_lib/test_run_safety.py` tests and the pre-freeze tests (76 at `2c8fb731`). Check that they pass in the parallel run (`--dist loadfile`) and in `./scripts/local_ci.sh`. Verify: the collected-ID difference equals those files, and they pass. Task 11.1 then updates the pin. + Verified 2026-11-27: `pyproject.toml` `testpaths` holds `experiments/_lib` and the `prefreeze` folder; the tests run in the parallel suite and in `./scripts/local_ci.sh` (passed on PR #238, tripwire pinned by test-ID diff). - [x] 11.1 Update the clean-base tripwire count in `tests/test_clean_base_tripwire.py`. Diff the collected test IDs against the last pin, not the per-file counts. The rewrite of the four old-design test files (task 1.1) and the newly collected experiment tests (task 11.0) both change it. Verify: `uv run --no-sync pytest tests/test_clean_base_tripwire.py -q` passes. -- [ ] 11.2 Run `./scripts/local_ci.sh` (after the operator agrees to a full run). Verify: the final line reports success, and no step prints `SKIPPED`. -- [ ] 11.3 Run `uv run --no-sync omrs experiments check` and `openspec validate exp35-main-run-readiness --strict`. Verify: both pass. +- [x] 11.2 Run `./scripts/local_ci.sh` (after the operator agrees to a full run). Verify: the final line reports success, and no step prints `SKIPPED`. + Done 2026-11-27 on `feat/exp35-report-compute` (v3 `987a21be` plus task 16.20): `./scripts/local_ci.sh` Python suite 14,499 passed, tripwire passed, OpenSpec 108 of 108, no `SKIPPED`. Its Vitest step timed out under machine load (load average 15 to 26 from other sessions; this change touches no `web/` file); `npx vitest run --maxWorkers=4` then passed 2,678 of 2,678, and lint and typecheck passed. GitHub CI on the PR is the final check. +- [x] 11.3 Run `uv run --no-sync omrs experiments check` and `openspec validate exp35-main-run-readiness --strict`. Verify: both pass. + Done 2026-11-27: `omrs experiments check` 0 errors (9 warnings, 44 info, none in Experiment 35); `openspec validate exp35-main-run-readiness --strict` valid. ## 12. App addition C: llama.cpp reranker backend (redesign, 2026-11-12; design D27) @@ -511,8 +517,9 @@ Architecture invariant 11: one new file and one `register()` line, no branch on - [x] 13.2 Replace `--arm` with `--setup NAME|all` and `--index NAME` in `cli35.py` (the parser lives there from the start, task 1.1). Write failing tests: `--setup all --stage search` plans 72 setups in a fixed order; `--index e4b-c1024 --stage ingest` plans one ingest per dataset; `--stage search --index e4b-c1024` plans that index's 8 setups; an unknown name exits with code 2. Answer setup folders carry the full setup name with the chosen sizes (for example `e4b-c512-r4b-hon-t20k`) and sit apart from the search setup folders (A5 R-7 Q16): a test plans one answer setup and one search setup of the same cell and shows two separate folders. Verify: the tests pass and `--help` shows the options. - [x] 13.3 Per-index stores (design D32). Write failing tests: `Layout` puts each index's store under `/stores//lancedb`; an ingest writes only there; the seal fingerprint is `///index-fingerprint.json`; two ingests of different indexes into one output folder at the same time leave each store written by one process only. Prove they fail, then implement in `outputs35.Layout`. Verify: the tests pass. - [x] 13.4 Legal RAG Bench loader (design D29). Write failing tests with a small fixture of both configs: 100-row shape, gold `relevant_passage_id`, passages written once as `.md` holding title, text and footnotes, with a leading `#` on any line escaped, frozen seeded order, file SHA-256 check, and a stop that names a missing gold passage. The passage files are written once by `prepare35.py` into the fixed folder of task 5.4c, never under ``. Prove they fail, then implement in `datasets35.py` and `prepare35.py`. Verify: the tests pass. -- [ ] 13.5 FreshStack 203 queries on the full public corpus (amendment A4, 2026-11-14; pre-registration section 4; design D38). Write failing tests: the loader drops the 20 continuity queries; the corpus is the full `freshstack/corpus-oct-2024` config `langchain` at the pinned revision (49,514 documents on the real data; a fixture stands in for tests), with no `continuity/` file, no overlay runbook and no subset or distractor sampling; `datasets35.py` has no `_FS_OVERLAY` or `_FS_OVERLAY_ID` reference and no expected hash for the overlay; the loader refuses a corpus whose revision or row count differs from the pin; questions `77536364` and `77762811` stay. Export format (A5 R-4, H-14, fact checks F3 to F5): the indexed file holds the published row text only, with no front matter and no source URL, ID or byte offset (these go in the manifest); a row whose file extension (from the corpus ID path) is `.md` or `.mdx` is written unchanged; every other row, including a row with no extension and an `.ipynb` row, is wrapped in a backtick fence with no info string, one backtick longer than the longest backtick run in the row and at least three; the manifest records each row's extension and whether it was fenced; the query text is the title, a blank line, then the body (`query_title`, `query_text`), as Experiments 9a and 22 sent it. Further failing-first tests: a written file holds no `---` front matter and no URL; a `.py` row with `#` comment lines gives no heading in `_heading_positions` (`src/omrs/core/chunking/model_token.py:362`); a row that holds a three-backtick line is still one fenced block. If either fence test cannot pass on the model-token Markdown path, the fallback applies (A5 R-4): keep the text with no fence, and the protocol states the heading effect as a limitation. Prove they fail, then remove the overlay constants, its hash entry, its id mapping and the `continuity/*.md` glob, and add the revision and row-count check. Verify: the tests pass, the loader reports 203 queries, the revision, row count and corpus tree hash from task 16.1 (P1) are in `plan.json`, and the test pod session (task 9.2) records the realised chunk-length distribution on FreshStack. The protocol states the limitation that FreshStack rows are byte spans, so a Markdown row can start or end inside a fence. +- [x] 13.5 FreshStack 203 queries on the full public corpus (amendment A4, 2026-11-14; pre-registration section 4; design D38). Write failing tests: the loader drops the 20 continuity queries; the corpus is the full `freshstack/corpus-oct-2024` config `langchain` at the pinned revision (49,514 documents on the real data; a fixture stands in for tests), with no `continuity/` file, no overlay runbook and no subset or distractor sampling; `datasets35.py` has no `_FS_OVERLAY` or `_FS_OVERLAY_ID` reference and no expected hash for the overlay; the loader refuses a corpus whose revision or row count differs from the pin; questions `77536364` and `77762811` stay. Export format (A5 R-4, H-14, fact checks F3 to F5): the indexed file holds the published row text only, with no front matter and no source URL, ID or byte offset (these go in the manifest); a row whose file extension (from the corpus ID path) is `.md` or `.mdx` is written unchanged; every other row, including a row with no extension and an `.ipynb` row, is wrapped in a backtick fence with no info string, one backtick longer than the longest backtick run in the row and at least three; the manifest records each row's extension and whether it was fenced; the query text is the title, a blank line, then the body (`query_title`, `query_text`), as Experiments 9a and 22 sent it. Further failing-first tests: a written file holds no `---` front matter and no URL; a `.py` row with `#` comment lines gives no heading in `_heading_positions` (`src/omrs/core/chunking/model_token.py:362`); a row that holds a three-backtick line is still one fenced block. If either fence test cannot pass on the model-token Markdown path, the fallback applies (A5 R-4): keep the text with no fence, and the protocol states the heading effect as a limitation. Prove they fail, then remove the overlay constants, its hash entry, its id mapping and the `continuity/*.md` glob, and add the revision and row-count check. Verify: the tests pass, the loader reports 203 queries, the revision, row count and corpus tree hash from task 16.1 (P1) are in `plan.json`, and the test pod session (task 9.2) records the realised chunk-length distribution on FreshStack. The protocol states the limitation that FreshStack rows are byte spans, so a Markdown row can start or end inside a fence. Check (2026-11-25, Mac, no download; left open): the realised chunk-length distribution of FreshStack is not recorded. The test pod session did not save one. A Mac chunking of the 49,506 exported files (pinned Qwen3 tokenizer, same chunk settings, `read_and_chunk_file_async`) gives 182,210, 113,300 and 61,852 chunks at 512, 1,024 and 2,048, but the pod's `e8b-c512` ingest (DATA `p2-session-2026-11-24`) stored 196,350 chunks, and 69 of the first 600 files have another chunk count on the pod. The Mac figures are therefore not the stored chunks. Needed: the stored chunks of one pod index (read the LanceDB table of a sealed index and count tokens) or the main-run report table (`reporttables35.chunk_lengths`, from the saved search lists), and the cause of the difference in chunk counts. + Verified 2026-11-27: `tests/test_experiment35_datasets.py` (`test_no_overlay_or_continuity_reference_is_left`, `test_freshstack_drops_continuity_queries_and_sends_title_then_body`, `test_freshstack_corpus_refuses_another_revision_or_row_count`); `datasets35.py` holds no `_FS_OVERLAY` reference. The full corpus ran in the P2 build (49,506 prepared files). - [x] 13.5a BioASQ passages as `.md` (operator decision, 2026-11-13). Write failing tests: the passage writer writes `.md` (not `.txt`), escapes a leading `#` on any line, and maps gold ids without the suffix. Prove they fail, then implement. The writer runs once in `prepare35.py` into the fixed passage folder of task 5.4c, never under ``. Verify: the tests pass. - [x] 13.5b Qwen3 token counts on all four datasets. Write a failing test that ingests a small fixture of FinanceBench (Markdown PDF text), FreshStack, BioASQ and Legal at 512, 1,024 and 2,048 tokens and asserts: every chunk has at most the level's Qwen3 token count (pinned tokenizer revision); every dataset goes through the model-token-aware Markdown path; the cl100k counter is never called (patched to raise). Prove it fails on the `.txt` passages, then pass it after 13.4 and 13.5a. Verify: the test passes. - [x] 13.6 FinanceBench number match (design D29). Write failing tests with known pairs: "$1,577 million" against "$1.58 billion" passes; "12.5%" against "12.5 percent" passes; "(3.2)" against "-3.2" passes; a missing number fails; two reference numbers need both; a 2% difference fails. Code review (A5 item 56): `FY2022` reads as 2022, `FY22` and `XFY2020` are not read; `$3M` reads as 3,000,000, `3M` is not read and `2 b` reads as 2; `777X` and `1x` are not read; on the pinned FinanceBench file 24 of 150 references hold no number. Prove they fail, then implement in `scoring35.py` (or `numbers35.py`). Verify: the tests pass. @@ -526,7 +533,8 @@ Architecture invariant 11: one new file and one `register()` line, no branch on - [x] 14.2 Write failing tests that each answer row records `completion_calls`, the evidence characters, and the truncated passages and characters dropped, computed with OMRS's own `_fit_and_measure` on the same rows and settings. Prove they fail, then implement in `answers35.py`. Verify: the tests pass, and a row with cut evidence is still saved. - [x] 14.3 Selection rule (`select35.py`, design D31). Write failing tests on fixture scores: a gap of exactly 0.01 picks the smaller size; a gap of 0.011 picks the best; equal scores pick the smaller size; the pooled score is the plain mean of the FinanceBench, FreshStack and BioASQ dataset means (not question-weighted; amendment A3); a fixture that changes only the Legal RAG Bench scores changes neither the selected embedder nor the reranker size nor the cell; the four-factor step picks the cell in tie order reranker off, hybrid off, lowest index cost, smaller chunk size; the reranker size is chosen at the chosen embedder on reranker-on setups only; a missing setup stops and names it; `selection.json` lists every pooled score, both chosen sizes, the A3 cell and the configuration hash. Then (A4, pre-registration section 14.1) tests that: index cost is the number of chunks times the embedding dimension, summed over the three core datasets, read from the sealed indexes with no score; the configuration hash is the SHA-256 of the canonical JSON (keys sorted, no spaces, UTF-8) of the selected cell's resolved settings with the SHA-256 of `halves.json` as one field, and the same inputs give the same hash twice. "Within 0.01" means a gap of at most 0.01 + 1e-9 on unrounded pooled scores (A5 R-6 Q10, H-23): a fixture whose gap computes as 0.010000000000000009 counts as within, and a gap of 0.0100001 does not. The any-page repeat of step 3 is gone (A5, fact check F2: a stored chunk has one page, so it would repeat step 3 exactly). Prove they fail, then implement. Verify: the tests pass, and the answer stage refuses to start without `selection.json`. - [x] 14.5 Ragas `AnswerCorrectness` (design D33). Write failing tests with a stub LLM and stub embeddings: the `ragas` stage scores five metrics, `AnswerCorrectness` gets the question, the answer and the dataset's reference answer (never the contexts), uses the frozen judge and the local 4B embedder, and records the weights; an answer without a reference records "not judged" and sends no call; resume skips saved rows; a failed `AnswerCorrectness` call goes to the row's `unjudged` list and is resent under task 7.2 (A5 R-3). Prove they fail, then implement in `ragas35.py` with Ragas 0.4.3. Verify: the tests pass, and the version check still refuses another Ragas version. -- [ ] 14.6 Correctness gate per core dataset (design D33 as revised by D38; pre-registration section 11.2). Write failing tests for `correct35.py`: `sample` with seed 20261113 gives the same 200 answers twice, 50 questions per dataset (the three core datasets and Legal) from half B (150 with no Legal draw when drop step 1 applies, PR 11.2 and 17), each with the run-1 answer of an answer setup the seed picks uniformly, with no Ragas score in the output; the labelling page shows the question, the reference and the answer and saves a JSON file; `agree` cuts the Ragas score at 0.5 and gives per core dataset `cohen_kappa` with a percentile bootstrap 95% interval (10,000 resamples by question, seed 20261127, through `bootstrap_by_question` of task 14.7), computed twice with "can't tell" scored as correct and as not correct; the gate passes on a dataset only when both computations give a point estimate of at least 0.60 and a lower bound of at least 0.40; the continuous score's AUC against the human label must have a lower 95% bound above 0.5 (same bootstrap, seed 20261128); prevalence, raw agreement and PABAK sit beside kappa; undefined statistics fail closed (PR 11.2: a one-class sample fails the gate, an undefined resample takes kappa 0 or AUC 0.5 and is counted, over 5% undefined fails the gate); Legal is reported with no gate; a failed gate marks rows 14, 15, 18 and 19 "not testable" on that dataset (p = 1, task 15.7); no pooled kappa decides anything. Prove they fail, then implement. Then, after the main run, L1 and L2 both label the whole sample (full plan), and the gate uses the reference label of pre-registration section 11.3 (task 15.8; O4). Verify: the tests pass, `protocol.md` holds the gate in a commit before labelling, and the gate is decided before any H8a or H8b contrast result is computed (C35 task 4A.4a). +- [x] 14.6 Correctness gate per core dataset (design D33 as revised by D38; pre-registration section 11.2). Write failing tests for `correct35.py`: `sample` with seed 20261113 gives the same 200 answers twice, 50 questions per dataset (the three core datasets and Legal) from half B (150 with no Legal draw when drop step 1 applies, PR 11.2 and 17), each with the run-1 answer of an answer setup the seed picks uniformly, with no Ragas score in the output; the labelling page shows the question, the reference and the answer and saves a JSON file; `agree` cuts the Ragas score at 0.5 and gives per core dataset `cohen_kappa` with a percentile bootstrap 95% interval (10,000 resamples by question, seed 20261127, through `bootstrap_by_question` of task 14.7), computed twice with "can't tell" scored as correct and as not correct; the gate passes on a dataset only when both computations give a point estimate of at least 0.60 and a lower bound of at least 0.40; the continuous score's AUC against the human label must have a lower 95% bound above 0.5 (same bootstrap, seed 20261128); prevalence, raw agreement and PABAK sit beside kappa; undefined statistics fail closed (PR 11.2: a one-class sample fails the gate, an undefined resample takes kappa 0 or AUC 0.5 and is counted, over 5% undefined fails the gate); Legal is reported with no gate; a failed gate marks rows 14, 15, 18 and 19 "not testable" on that dataset (p = 1, task 15.7); no pooled kappa decides anything. Prove they fail, then implement. Then, after the main run, L1 and L2 both label the whole sample (full plan), and the gate uses the reference label of pre-registration section 11.3 (task 15.8; O4). Verify: the tests pass, `protocol.md` holds the gate in a commit before labelling, and the gate is decided before any H8a or H8b contrast result is computed (C35 task 4A.4a). + Verified 2026-11-27: `correct35.py` (seed 20261113) and `tests/test_experiment35_correct.py` (16 tests: 200 answers, 50 per dataset from half B, same answers twice, no Legal draw after drop step 1, no Ragas score, page shows question, reference and answer). - [x] 14.4 Factorial analysis (`factorial35.py`, design D31, D38 and D39; H-15; pre-registration sections 7, 8 and 14.3). H6 and H7 on FinanceBench use `evidence_recall_20k` (a chunk covers its page; A5, fact check F2 removed the first-page and any-page variants, because a stored chunk has one page and the two rules give the same number; the H6 FinanceBench sensitivity stays as one analysis: nDCG@10 with a chunk covering its page, and the table gives sign agreement per row with the endpoint, pre-registration sections 7 and 21); H8a and H8b use all questions; the RQ1 headline is the A3 cell on half B. Write failing tests on a fixture with a planted embedder effect: a question whose cut total is 20,000 and whose realised total is 19,000 stays in the H8b sensitivity set, and one whose cut total is 19,000 leaves it; the H6 FinanceBench sensitivity table gives nDCG@10 per row and its sign agreement with `evidence_recall_20k`; only H1's rows count; Holm runs within one dataset over the fixed family of task 15.7; a significant wrong-sign row does not count; "holds" follows the per-hypothesis rule of section 7 (H1 in full when both steps hold, in part when one does; H2, H3 and H5 on at least 2 of 3 core datasets; H4 per dataset when both rows count, overall on at least 2 of 3; H6, H7, H8a and H8b on both FinanceBench and FreshStack, H8a and H8b per outcome; a two-sided hypothesis holds only when the same row counts with the same sign on each dataset its rule needs, and opposite signs are reported as a dataset-dependent effect); H8a rows use the 12 crossed setups and H8b rows the 3 `-t20k` setups, with the PR 7 sensitivity on questions whose cut total (the kept stored chunks, before assembly, pre-registration section 3; protocol 0.14 item 25) is 19,456 tokens or more in all three, never the realised (assembled) total; BioASQ rows 9 to 19 carry `sanity_check: true`; answer scores average the 3 runs per question first; Legal rows carry `exploratory: true`; the RQ1 retrieval headline is the A3 cell's nDCG@10 on half B per core dataset with a 95% interval, and the 72-setup table on all questions is marked descriptive; the search-cost figure uses the exact expected-maximum estimator (adapted from Dodge et al. 2019, drawn without replacement) on pooled half-A scores sorted in ascending order, one curve over the 12 A3 cells and one over the 72 setups, and a RAGFlow curve only if the matched search ran. Prove they fail, then implement with `stats_cluster.py` (task 15.6) and the existing functions. Code review (A5 items 57, 59 and 60): each row reports `excluded` against every question of its dataset, split into `excluded_unjudged`, `excluded_not_defined` and `excluded_no_value`; a cell with an unjudged run has no value; the H8b filter takes the cut total any run saved and counts `no_cut_total`; after drop step 1 Legal rows 12 to 19 are `dropped` and rows 1 to 11 still run. Verify: the tests pass, and `git diff` shows no new function in `experiments/_lib/stats.py` or `stats_d6.py` other than `cohen_kappa` (task 8.8). The gate bootstrap is not one of these: it is `bootstrap_by_question` in the new Experiment 35 module of task 14.7 (A5, H-16). - [x] 14.7 Gate bootstrap (A5, H-16, R-6 Q9; pre-registration section 11.2; design D35 as amended by D39). One function `bootstrap_by_question(items, statistic, *, n, seed)` in a new Experiment 35 module `bootstrap35.py` (not in `experiments/_lib/stats.py` or `stats_d6.py`). It resamples questions with replacement, computes any statistic on each resample (kappa, specificity difference, AUC), applies the fail-closed rule of pre-registration section 11.2 first (an undefined resample is counted once and takes the treatment that section gives its statistic, for example kappa 0 or AUC 0.5 in the correctness gate; over 500 of 10,000 undefined fails the gate or makes the row not testable), and only then takes the percentile bounds by the order-statistic rule of `stats_d6.paired_bootstrap`: sort ascending, lower bound at zero-based index `int(0.025 x m)`, upper bound at `int(0.975 x m) - 1`, no interpolation. Here `m` is the number of values kept after the fail-closed rule: 10,000 for kappa and AUC, and 10,000 minus the left-out resamples for the specificity difference (pre-registration section 11.2; the parameter `n` stays the resample count). Write failing tests: for 10,000 kept values the bounds are the values at indexes 250 and 9,749; for 9,600 kept values (400 left out) the indexes are 240 and 9,359; a known-answer kappa fixture gives the same bounds twice with one seed; a statistic that is undefined on 600 of 10,000 resamples gives "not testable"; an interpolating rule fails the index test. Prove they fail (no module), then implement. `labels35.py` (tasks 15.8, 16.18) and `correct35.py` (task 14.6) call it. Verify: the tests pass. @@ -576,7 +584,8 @@ Each test is proved to fail on the current code before the fix. `preregistration.md` governs; "PR n" below means its section n. Tasks 16.1 to 16.16 are the pre-freeze tasks P1 to P16 of PR 23, in the same order. Tasks 16.17 to 16.22 and 16.29 are code. Tasks 16.23 to 16.28 and 16.30 are the user's decisions O1 to O7. The owner decided O1 to O7 on 2026-11-14; no owner decision is open. Record each answer, never guess it. Every task closes before G7. Tasks 16.31 to 16.35 are added by amendment A5 (design D39): 16.31 is P17 and 16.32 is P18 of PR 23, 16.33 extends P1 and 16.34 extends P10, and 16.35 is a code task the harness review found. Task 16.37 is added by amendment A13. - [x] 16.1 P1. FreshStack full corpus. Ask the user to approve the download of `freshstack/corpus-oct-2024`, config `langchain`, at a pinned revision. Then download it into `~/Development/DATA/omrs/` and record the revision, the row count (49,514 expected) and the corpus tree hash in `plan.json` and in the pins table (PR 16). Note whether the dataset card states its own query-text convention, beside the A5 rule of title, blank line, body (fact check F5). Task 16.33 records the file-type shares at the same time. Verify: the loader of task 13.5 accepts the corpus, and its check refuses a changed row count. (Verified 2026-11-23: owner approved 2026-11-23; revision 069f66dc, 49,514 rows, file SHA-256 f1e63bf8, tree hash 9c0ef058 in plan.json pins.datasets.freshstack and prereg s16; card query convention noted in prereg s4; loader accepts the corpus and refuses 49,513 rows (test_experiment35_plan_pins.py, real-data check).) -- [ ] 16.2 P2. Time one full-corpus FreshStack index build on the chosen GPU type (part of task 9.2 or 9.3 when possible). Update the estimate in PR 17 from the measured time before relying on it. Verify: the compute table and the estimate name the measured hours; the "30 to 40 pod hours" reviewer figure is no longer the basis. +- [x] 16.2 P2. Time one full-corpus FreshStack index build on the chosen GPU type (part of task 9.2 or 9.3 when possible). Update the estimate in PR 17 from the measured time before relying on it. Verify: the compute table and the estimate name the measured hours; the "30 to 40 pod hours" reviewer figure is no longer the basis. + Verified 2026-11-27: the P2 session timed one full FreshStack index (`e8b-c512`, 49,506 files) on the RTX 4090 at 5.65 h (stage `fsfull-e8b-c512`, 2026-11-25 00:51 to 06:30, `p2-session-2026-11-24/test-session.log`). `preregistration.md` section 17 bases the RunPod line and the build-rate table on it; the "30 to 40 pod hours" figure appears nowhere. - [x] 16.3 P3. Check whether the FreshStack nugget labels allow alpha-nDCG@10 with the benchmark's own scorer. If yes, pin the scorer (version or commit) and write failing tests that a FreshStack secondary column holds it, then implement. If no, record "not available" in PR 6. Verify: PR 6 and `plan.json` say which. Check (2026-11-25, Mac, data on disk only; stopped, left open): the labels allow alpha-nDCG@10. The saved export of the FreshStack queries (Experiment 22 `ground-truth.json`, SHA-256 pinned in `datasets35.py`) holds 639 nuggets for the 203 queries (1 to 8 per query, median 3). Every nugget names 1 to 27 relevant documents (median 5) and a list of judged non-relevant documents. For 203 of 203 queries the union of the nugget documents equals the query's relevant document list, and every nugget document is in the full corpus. The benchmark's own scorer is not on disk. It cannot be pinned (version or commit) without a download of the FreshStack scorer code, so nothing else is done. Needed: the owner's approval to fetch that code (no data), then pin it and write the failing tests and the secondary column; or record "not available" in PR 6. Verified 2026-11-26 (owner approved the code fetch and `pyndeval` on 2026-11-26): the official repo `fresh-stack/freshstack` at commit `a1c8c45b` is cloned outside the project, `metrics.py` SHA-256 `0f331649`. `pyndeval` 0.0.8 (macOS cp312 wheel SHA-256 `e8696282`) sits in its own venv in `DATA/omrs/experiments/35-full-rag-benchmark-2026-11-01/freshstack-scorer/venv`, never in the project. A toy check (`check/alpha_toy.py`, `python -I`, on the real nugget labels with a fake run on query 75979420) gives the hand value 0.782195 and the official value 0.7822. `plan.json` `pins.scorers.freshstack_alpha_ndcg` holds repo, commit, `metrics.py` SHA-256, `pyndeval` version and wheel SHA-256, alpha 0.5 and depth 10. PR 6 marks it secondary and descriptive. `alphandcg35.py` (behind the half-B guard) runs `alpha_runner35.py` in that venv, checks the pins and writes `/alpha-ndcg.json`; `reporttables35.py` carries it as `alpha_ndcg_freshstack`. Tests in `tests/test_experiment35_alphandcg.py` failed before the code and under 9 mutations. The adapter end to end with the real scorer gives 0.7822 on the toy run. @@ -610,8 +619,9 @@ Each test is proved to fail on the current code before the fix. - [x] 16.17 Half-B guard (PR 14.2). Write failing tests: the scorer refuses any half-B score while `/selection.json` or the OSF time-stamp record `/osf-timestamp.json` (fields `uploaded_at`, `file_sha256` and `configuration_hash`, task 16.23; A5 item 51) is missing or lacks a field, and names both; it also refuses when no time-stamp record holds the configuration hash of the current `selection.json` (a record of an earlier selection), and names both hashes; the replicate pods' first stage refuses to start under the same condition; the main join writes `answer-scores.jsonl` through the same guard, and a smoke join writes none (A5 item 54); the main join calls the guard before it reads or writes anything, so a locked half B leaves no `join.json`, and the confirmatory analysis, the cross-table and the refusal report call it before they read or write (A5 item 61); half-A scoring needs neither. Prove they fail, then implement. Verify: the tests pass. - [x] 16.18 Faithfulness gate and differential-error rule (PR 11.2). Write failing tests for `labels35.py`: per checker, kappa against the human label on the 450-claim sample (drawn from answers to all questions, both halves), with "can't tell" as not supported (also reported with those items left out), passes at a point estimate of at least 0.60 and a lower bound of at least 0.40 (percentile bootstrap by question, seed 20261125); a failed Clef-Flash gate marks its results not validated and changes no row; specificity per chunk size, and when the 95% interval of the GLM-5.3 2,048 minus 512 difference (seed 20261126) excludes zero in either direction, rows 12, 13, 16 and 17 become "not testable" (p = 1, task 15.7); sensitivity per chunk size is reported; undefined statistics fail closed (PR 11.2: every undefined difference resample is left out and counted once, whichever level lacks a supported claim, and over 5% undefined makes rows 12, 13, 16 and 17 not testable); the gate file records its time and the analysis refuses to compute an H8a or H8b row before it exists. Prove they fail, then implement. Verify: the tests pass. - [x] 16.19 Length-controlled check (PR 11.2). Write failing tests for a `lengthcheck` stage: 300 claims from `c2048` crossed answers with seed 20261119; the frame is the cited non-refusal claims of every dataset with answers, Legal included unless drop step 1 removed its answers (A5 item 62); each cited chunk split into consecutive 512-token windows, the window that shares the most distinct lower-case claim words kept (ties to the earlier window); GLM-5.3 and Clef-Flash judge the claim again; the report gives the verdict change rate with a Wilson interval; no gate. Prove they fail, then implement. Verify: the tests pass. -- [ ] 16.20 Report items (PR 21). Write failing report tests: the realised chunk-length distribution per chunk-size level and dataset; one sensitivity table set (clustered method against sensitivity check, missing-outcome bounds, closed-book subset, length-controlled check; the "A3 cell under any-page credit" table is gone, A5 fact check F2; the "FinanceBench page rules" table gives way to one table of FinanceBench nDCG@10 for rows 9 and 10, a chunk covering its page, with sign agreement per row against `evidence_recall_20k`, pre-registration sections 7 and 21; the H8b sensitivity table keeps the questions by cut total and shows both token totals); the drop record `drops.json` (task 6.5) and each drop step it holds; the count of unmapped chunks per setup (task 15.1); the limitations of A5 (assembly removes overlap text, so the assembled evidence can be shorter than the cut total; FreshStack rows are byte spans; client-library transport retries are not counted in `resent_calls`); the compute table (GPU type, pod hours per stage with every pre-freeze pod, hosted tokens and cost per role, energy estimate, `resent_calls`, error rows per stage and role, every `out_of_credit` stop); the returned model ID and provider per hosted call with the count of differences; every row with its SESOI reading and "not testable" marks (no MDE line since 2026-11-26). Code review (A5 item 57): the unjudged-scored-0 sensitivity tables also score not-defined Ragas runs 0, and the join counts `unjudged`, `not_defined` and `unparseable_verdicts`; the cross-table gives `misses_total`, `no_rag_score` and `no_closed_book_score` per setup. Prove they fail, then implement. Verify: the tests pass. +- [x] 16.20 Report items (PR 21). Write failing report tests: the realised chunk-length distribution per chunk-size level and dataset; one sensitivity table set (clustered method against sensitivity check, missing-outcome bounds, closed-book subset, length-controlled check; the "A3 cell under any-page credit" table is gone, A5 fact check F2; the "FinanceBench page rules" table gives way to one table of FinanceBench nDCG@10 for rows 9 and 10, a chunk covering its page, with sign agreement per row against `evidence_recall_20k`, pre-registration sections 7 and 21; the H8b sensitivity table keeps the questions by cut total and shows both token totals); the drop record `drops.json` (task 6.5) and each drop step it holds; the count of unmapped chunks per setup (task 15.1); the limitations of A5 (assembly removes overlap text, so the assembled evidence can be shorter than the cut total; FreshStack rows are byte spans; client-library transport retries are not counted in `resent_calls`); the compute table (GPU type, pod hours per stage with every pre-freeze pod, hosted tokens and cost per role, energy estimate, `resent_calls`, error rows per stage and role, every `out_of_credit` stop); the returned model ID and provider per hosted call with the count of differences; every row with its SESOI reading and "not testable" marks (no MDE line since 2026-11-26). Code review (A5 item 57): the unjudged-scored-0 sensitivity tables also score not-defined Ragas runs 0, and the join counts `unjudged`, `not_defined` and `unparseable_verdicts`; the cross-table gives `misses_total`, `no_rag_score` and `no_closed_book_score` per setup. Prove they fail, then implement. Verify: the tests pass. Progress 2026-11-26 (readiness review S4, nit 1; commits `95a45687`, `d0501dc5`, `cef5357b`): the report now also gives FinanceBench number match, trigger (a), the uncited-segment faithfulness sensitivity, the compute table (pod hours and cost per stage and run mode), fenced rows per extension, and the cut against realised token table with real `evidence_tokens`; the MDE line is gone. Still open: hosted tokens and cost per role, the energy estimate, error rows per stage and role and `out_of_credit` stops in the compute table, and the returned model per hosted call in the report (it is in `join.json`). + Done 2026-11-27: `hostedusage35.py` adds the hosted part of the compute table: per stage and role the rows, calls, error rows, `resent_calls`, calls closed as missing, and tokens and cost (answer and Ragas from the rows; GLM-5.3 and classifier from the billing exports, A18 item 35); billing per provider; energy (closed GPU hours x 450 W); every rate-limit and `out_of_credit` stop (`run_arms.py` now writes `stops.jsonl`; `RateLimitStop.kind`); the returned model per role from `join.json`. `reporttables35.py` writes them under `hosted` (`--billing`). Tests: `tests/test_experiment35_hosted_usage.py`, `test_experiment35_run_arms.py`, `test_experiment_hosted_calls.py`; failed first, 10 mutations all killed. - [x] 16.21 Release kit (PR 19). Write failing tests for a re-judge script that rebuilds evidence text from the pinned dataset revisions and the released unit and chunk IDs, on a fixture; and for an export that writes ranked lists in TREC run format, never corpus text. The TREC export writes a strictly decreasing rank-derived score per unit (for example 1000 minus rank), so `trec_eval` cannot re-sort tied RRF scores (A5, H-25): a test with two tied input scores gives the saved rank order back after a `trec_eval`-style sort by score. Released answers sit in a separate release folder that gets the identifier rules only, not the 12-word corpus-text rule (A5 R-7 Q15, H-34); `experiments/_lib/release_check.py` gains a rule for email addresses and login names, test-first: a fixture file holding an email address or a login name fails the check, and a released answer file that quotes 12 or more words of evidence passes in the answer release folder. Prove they fail, then implement. Verify: the tests pass, and the release table of PR 19 names each artefact and its licence. - [ ] 16.22 Optional `e8b-c2048` rebuild check (PR 15). Run it on FinanceBench only when the cost projection after the search stage is at or below the estimate (a cost-only decision, recorded). Report the share of identical ranked lists and the nDCG@10 change; it is not a gate. Verify: the decision and, if run, the result are in the run record. - [x] 16.23 O1 (decided by the owner on 2026-11-14): a file upload to the registered OSF project time-stamps the A3 configuration hash. The answer is recorded in PR 14.2 and PR 23. Verify: recorded before G7. @@ -632,7 +642,8 @@ Each test is proved to fail on the current code before the fix. - [x] 16.32 Pre-freeze item: correct protocol 4.4 against the saved LLM-AggreFact score files (A5 R-7 Q14, H-36). Read the saved score files and correct the 4.4 sentence on overflow rows to name which file it describes (the review found `rows_counted_wrong` 0 for Clef-Flash and 2 for Granite Guardian, and 27 GLM-5.3 error rows, 24 of them on RAGTruth). Do not change any other number. Verify: each number in the corrected sentence is traced to a file and key, and the faithfulness gate stays the decision on Clef-Flash. - [x] 16.33 Pre-freeze item: FreshStack file-type shares at P1 (A5, fact check F3). When the full corpus is downloaded (task 16.1), count the rows and files per extension from the corpus ID path, and record the share table in `plan.json` and the protocol, with the count of fenced and unfenced rows the export of task 13.5 writes. Verify: the shares sum to 100% of 49,514 rows, and the fenced count equals the rows whose extension is not `.md` or `.mdx`. (Verified 2026-11-23: 76-extension table in plan.json file_types, top 12 in protocol 4.1; rows sum to 49,514; fenced 43,693 equals non-.md/.mdx rows; tests in test_experiment35_plan_pins.py.) - [x] 16.34 Pre-freeze item: align the Clef-Flash server arguments with the LLM-AggreFact preset (A5 R-7 Q14, H-30). Copy the preset the LLM-AggreFact runs used (`prefreeze/run_aggrefact.py:72-86`: the plan's four keys plus `flash-attn`, `n-gpu-layers`, `fit`, `cache-type-k`, `cache-type-v`, `spec-type`, `cache-prompt` and `cache-reuse`) into the `plan.json` Clef-Flash entry (P10). Write a failing test that the main-run preset built from `plan.json` equals the AggreFact preset, key by key, then make the plan pass it. Verify: the test passes, and the G3 server-argument check of task 5.8 checks these arguments on every run. -- [ ] 16.35 Run records for new pre-freeze tools (A5, H-31). Every new pre-freeze tool (the P2 timing build, the reranker check of task 15.10) calls `guard_run` with `--prefreeze` (task 5.7) and writes its start and end times. Write failing tests with a stub runtime: each tool refuses to start when the runtime check fails, and writes one pre-freeze run record with both times. The finished pre-freeze tools stay as a record and are not changed. Prove they fail, then implement. Verify: the tests pass. +- [x] 16.35 Run records for new pre-freeze tools (A5, H-31). Every new pre-freeze tool (the P2 timing build, the reranker check of task 15.10) calls `guard_run` with `--prefreeze` (task 5.7) and writes its start and end times. Write failing tests with a stub runtime: each tool refuses to start when the runtime check fails, and writes one pre-freeze run record with both times. The finished pre-freeze tools stay as a record and are not changed. Prove they fail, then implement. Verify: the tests pass. + Verified 2026-11-27: the P2 timing build ran through `run_arms.py --prefreeze` (`guard_run`), which wrote `prefreeze: true` run records at its start (2026-11-25T00:51:16Z) and at the seal that followed it (06:30:27Z), so both times are recorded; the per-file seconds are in `ingest.jsonl`. The reranker check (`rerank_check35.py`, `rerank_scorers35.py`) calls `guard_run` with `prefreeze=True`; `tests/test_experiment35_rerank_scorers.py` covers the refusal on a failed runtime check and one pre-freeze record with both times. The finished tools stay as recorded. - [x] 16.37 Pre-freeze item: no file-type routing for the prepared passages (amendment A13; owner, 2026-11-26, option 1). Magika routing on the prepared FreshStack files skipped 444 files as binary (38 gold documents), sent fenced passages to `CodeSplitter`, and made fallback chunk counts depend on the folder path. Add the OMRS setting `ingestion.file_type_routing` (default `true`), pin it `false` in `plan.json` `pins.settings.ingestion`, refuse a plan without the pin and a run where OMRS resolves it on, and record the tokenizer revision and `tokenizer.json` SHA-256 in each index seal. Write failing tests first. Verify: the tests pass, and the 600-file recheck gives the Markdown-only total. (Verified 2026-11-26: `tests/test_ingestion_file_type_routing.py` (fenced `code/python` file takes the Markdown path, `binary/snap` file indexed, same count after a folder move, saved-pipeline discover step), `test_experiment35_arms.py`, `test_experiment35_run_arms.py` (env override refused, dry run records it), `test_experiment35_plan_pins.py`, `test_experiment35_stages.py` (seal tokenizer record and refusal); each failed before the change and under a mutation. The 600-file recheck gives 2,289 chunks at 512, and 2,289 again after a folder move. Full FreshStack: 182,210, 113,300 and 61,852 chunks at 512, 1,024 and 2,048.) - [x] 16.38 Pre-freeze item: readiness-review fixes (2026-11-26; `protocol.md` section 0.19; amendment A14). Write failing tests, prove they fail, implement, then check that each test fails again when its fix is reverted (mutation check). Verify: the tests pass and every mutation is killed. - [x] 16.39 P19, amendment A18 (2026-11-27; `protocol.md` section 0.22). Build the fixed relevance audit of pre-registration section 11.3: the frame (unjudged units in the top 3 of hybrid on only or hybrid off only), the seeded sample of 50 per arm per core dataset (seed 20261120), a blind label page for L1 and L2 that hides arm, setup, score and rank, and the report (share relevant per arm with Wilson intervals, the difference with a bootstrap by question, seed 20261145, and the estimated H3 bias against 0.02). Relabel the trigger output as descriptive. Also add the pooled H8 estimate (pre-registration section 9 point 7) and the always-reported all-claims faithfulness to the analysis. Extend the differential-error rule to the GLM-5.3 sensitivity difference (one resample set with specificity, seed 20261126), and report prevalence, raw agreement and PABAK beside the faithfulness-gate kappa (A18 items R2, R10). Labelling page (A18 items 31 and 32): code-only reading aid (shared words and numbers, on by default, toggle per item, state saved per label, its own colour); labeller highlighting in a second colour, saved with the label; the audit page shows the reference answer; a model-labeller copy of each page that saves drafts under its own browser storage key, so it can never load a human draft. Write failing tests first. Verify: the tests pass, and each fails when its code is reverted. diff --git a/tests/test_clean_base_tripwire.py b/tests/test_clean_base_tripwire.py index 5621a8834..102d87aa7 100644 --- a/tests/test_clean_base_tripwire.py +++ b/tests/test_clean_base_tripwire.py @@ -564,7 +564,9 @@ # +5 (2026-11-27, PR 238 review, by test-ID diff against HEAD 3e357e1d): 9 added, 5 in # test_experiment35_audit, 3 in test_experiment35_bootstrap and 1 in # test_experiment35_differential; 4 node cases in test_experiment35_labelaids moved to slow. -_BASE_EXECUTED = 14498 +# +9 (2026-11-27, task 16.20, by test-ID diff against v3 987a21be): 7 in +# test_experiment35_hosted_usage and 2 in test_experiment35_run_arms. +_BASE_EXECUTED = 14507 # Re-baselined check-embedding-stamp-before-dimension (2026-10-18): 10 new cases # (store stamp-first tests and graph embed-step tests). Measured in two clean # venvs: 5741 with the web extra, 5091 without; the web extra still adds 650. diff --git a/tests/test_experiment35_hosted_usage.py b/tests/test_experiment35_hosted_usage.py new file mode 100644 index 000000000..8d54f3bcf --- /dev/null +++ b/tests/test_experiment35_hosted_usage.py @@ -0,0 +1,166 @@ +"""Experiment 35 compute-table items of task 16.20 (pre-registration sections 17 and 21). + +Hosted tokens and cost per role, error rows per stage and role, harness resends +and closed calls, provider billing per provider (the source of GLM-5.3 and +classifier tokens and cost, amendment A18 item 35), an energy estimate, every +``out_of_credit`` stop and the returned model per role. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from tests._exp35_fixtures import load + +hostedusage35 = load("hostedusage35") +ND = hostedusage35.NOT_DEFINED + + +def _rows(path: Path, rows: list[dict[str, Any]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(json.dumps(r) + "\n" for r in rows)) + + +def _json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data)) + + +def _run(out: Path, kind: str = "answer", setup: str = "e4b-c512-r0.6b-hon", run: int = 1) -> Path: + return out / "bioasq" / kind / setup / f"run{run}" + + +def _tree(out: Path) -> None: + run = _run(out) + _rows( + run / "answer.jsonl", + [ + {"qid": "1", "status": "ok", "input_tokens": 100, "output_tokens": 10, "cost_usd": 0.5}, + {"qid": "2", "status": "error", "error": "boom", "input_tokens": 50, "cost_usd": 0.25}, + ], + ) + _json(run / "answer-summary.json", {"resent_calls": 2, "closed_missing": ["3"]}) + _rows( + run / "ragas.jsonl", + [ + { + "qid": "1", + "calls": [ + {"error": "", "input_tokens": 7, "output_tokens": 3, "reported_cost_usd": 0.1}, + {"error": "timeout", "input_tokens": 5, "output_tokens": 1}, + ], + } + ], + ) + _rows( + run / "judge-chat.jsonl", + [ + {"qid": "1", "verdicts": [{"call": {"error": None}}, {"call": {"error": "x"}}]}, + {"qid": "2", "verdicts": [{"call": {"error": None}}]}, + ], + ) + _json(run / "judge-chat-summary.json", {"resent_calls": 1, "closed_missing": []}) + _rows(run / "claim-kinds.jsonl", [{"claim_key": "a", "kind": "factual"}]) + cb = _run(out, kind="closedbook-own") + _rows(cb / "answer.jsonl", [{"qid": "1", "status": "ok", "input_tokens": 4, "cost_usd": 0.01}]) + + +def _role(table: dict[str, Any], stage: str, role: str) -> dict[str, Any]: + return next(r for r in table["roles"] if r["stage"] == stage and r["role"] == role) + + +def test_answer_and_ragas_tokens_and_cost_come_from_the_rows(tmp_path: Path) -> None: + _tree(tmp_path) + table = hostedusage35.hosted_usage(tmp_path) + answer = _role(table, "answer", "answer") + assert (answer["rows"], answer["input_tokens"], answer["cost_usd"]) == (2, 150, 0.75) + # One row reported no output tokens: the sum is not defined, never a silent undercount. + assert answer["output_tokens"] == ND + assert answer["source"] == "rows" + ragas = _role(table, "answer", "ragas-judge") + assert (ragas["calls"], ragas["input_tokens"], ragas["output_tokens"]) == (2, 12, 4) + assert ragas["cost_usd"] == ND # the failed call reported no cost + closed = _role(table, "closedbook-own", "answer") + assert (closed["rows"], closed["input_tokens"], closed["cost_usd"]) == (1, 4, 0.01) + + +def test_glm_and_classifier_tokens_and_cost_come_from_the_billing_export(tmp_path: Path) -> None: + _tree(tmp_path) + table = hostedusage35.hosted_usage(tmp_path) + for role in ("judge-glm", "claim-classifier"): + row = _role(table, "answer", role) + assert row["source"] == "billing export" + assert row["input_tokens"] == row["output_tokens"] == row["cost_usd"] == ND + assert _role(table, "answer", "judge-glm")["calls"] == 3 + + +def test_error_rows_resends_and_closed_calls_per_stage_and_role(tmp_path: Path) -> None: + _tree(tmp_path) + table = hostedusage35.hosted_usage(tmp_path) + assert _role(table, "answer", "answer")["error_rows"] == 1 + assert _role(table, "answer", "ragas-judge")["error_rows"] == 1 + assert _role(table, "answer", "judge-glm")["error_rows"] == 1 + assert _role(table, "answer", "claim-classifier")["error_rows"] == 0 + assert _role(table, "answer", "answer")["resent_calls"] == 2 + assert _role(table, "answer", "answer")["closed_missing"] == 1 + assert _role(table, "answer", "judge-glm")["resent_calls"] == 1 + # No summary file: the resends are not defined, not zero. + assert _role(table, "answer", "ragas-judge")["resent_calls"] == ND + + +def test_billing_rows_sum_per_provider(tmp_path: Path) -> None: + one, two = tmp_path / "a.json", tmp_path / "b.json" + _json(one, [{"provider": "zai", "usd": 1.5}, {"provider": "openrouter", "usd": 2.0}]) + _json(two, [{"provider": "zai", "usd": 0.5}]) + assert hostedusage35.billing_by_provider([one, two]) == {"openrouter": 2.0, "zai": 2.0} + assert hostedusage35.billing_by_provider([]) == ND + + +def test_energy_is_closed_gpu_hours_times_board_power() -> None: + compute = {"stages": [{"closed_pod_hours": 2.0}, {"closed_pod_hours": 3.0}]} + energy = hostedusage35.energy_estimate(compute) + assert energy["board_watts"] == 450 + assert energy["kwh"] == 2.25 + assert hostedusage35.energy_estimate(ND) == ND + + +def test_stops_and_returned_models_are_carried(tmp_path: Path) -> None: + assert hostedusage35.stops(tmp_path) == [] + _rows(tmp_path / "stops.jsonl", [{"kind": "out_of_credit", "stage": "answer"}]) + assert hostedusage35.stops(tmp_path) == [{"kind": "out_of_credit", "stage": "answer"}] + assert hostedusage35.returned_models(tmp_path) == ND + counts = {"answer": {"rows": 3, "differs": 1, "unknown": 0}} + _json(tmp_path / "join.json", {"returned_model": counts}) + assert hostedusage35.returned_models(tmp_path) == counts + + +def test_the_report_tables_carry_the_hosted_items(tmp_path: Path) -> None: + from tests._exp35_fixtures import open_half_b + + reporttables35 = load("reporttables35") + open_half_b(tmp_path) + _rows(tmp_path / "answer-scores.jsonl", []) + # A closed-book answer file only: the other report tables read no closed-book rows. + cb = _run(tmp_path, kind="closedbook-own") + _rows(cb / "answer.jsonl", [{"qid": "1", "status": "ok", "input_tokens": 4, "cost_usd": 0.01}]) + _rows(tmp_path / "stops.jsonl", [{"kind": "out_of_credit", "stage": "answer"}]) + bill = tmp_path / "bill.json" + _json(bill, [{"provider": "zai", "usd": 3.0}]) + records = tmp_path / "pod1.jsonl" + _rows( + records, + [ + {"started_at": "2026-12-01T00:00:00Z", "command": "x --stage ingest"}, + {"started_at": "2026-12-01T02:00:00Z", "command": "x --stage seal"}, + ], + ) + argv = ["--out-dir", str(tmp_path), "--records", str(records), "--billing", str(bill)] + assert reporttables35.main(argv) == 0 + hosted = json.loads((tmp_path / "report-tables.json").read_text())["hosted"] + assert _role(hosted["usage"], "closedbook-own", "answer")["input_tokens"] == 4 + assert hosted["billing_by_provider"] == {"zai": 3.0} + assert hosted["energy"]["kwh"] == 0.9 # 2 closed GPU hours at 450 W + assert hosted["stops"] == [{"kind": "out_of_credit", "stage": "answer"}] + assert hosted["returned_model"] == ND # no join.json diff --git a/tests/test_experiment35_run_arms.py b/tests/test_experiment35_run_arms.py index a18ef19ec..a8fb4462f 100644 --- a/tests/test_experiment35_run_arms.py +++ b/tests/test_experiment35_run_arms.py @@ -577,6 +577,33 @@ async def stopped(ctx: Any) -> int: assert "close" in stub.log +@pytest.mark.parametrize( + ("error", "kind"), + [ + (RateLimitStop("out of credit; top up", kind="out_of_credit"), "out_of_credit"), + (RateLimitStop("still rate-limited"), "rate_limit"), + ], +) +def test_a_rate_limit_stop_is_saved_for_the_compute_table( + env: Path, monkeypatch: pytest.MonkeyPatch, error: Any, kind: str +) -> None: + async def stopped(ctx: Any) -> int: + raise error + + monkeypatch.setitem(run_arms.STAGE_TABLE, "ingest", stopped) + stub = Stub() + passages = _prepared(env, stub) + assert _main(stub, env / "out", *_ingest_args(passages)) == 5 + lines = [json.loads(x) for x in (env / "out" / "stops.jsonl").read_text().splitlines()] + assert len(lines) == 1 + assert {k: lines[0][k] for k in ("kind", "stage", "dataset")} == { + "kind": kind, + "stage": "ingest", + "dataset": "bioasq", + } + assert lines[0]["message"] == str(error) and lines[0]["at"] + + def test_seal_through_the_runner_writes_the_build_environment( env: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_experiment_hosted_calls.py b/tests/test_experiment_hosted_calls.py index 8779be81d..43f295bb8 100644 --- a/tests/test_experiment_hosted_calls.py +++ b/tests/test_experiment_hosted_calls.py @@ -270,8 +270,9 @@ async def test_attempts_used_up_raise_rate_limit_stop() -> None: async def test_402_without_retry_after_stops_at_once_with_top_up_message() -> None: gate, sleeps = _gate() send, calls = _failing([_StatusError(402)]) - with pytest.raises(RateLimitStop, match="top up"): + with pytest.raises(RateLimitStop, match="top up") as stop: await gate.call(send) + assert stop.value.kind == "out_of_credit" # the report lists each credit stop (16.20) assert len(calls) == 1 assert sleeps.waits == [] @@ -285,8 +286,9 @@ async def send() -> Any: record = {"kind": "out_of_credit", "http_status": 402, "retry_after_seconds": None} return {"status": "error", "answer": None, "rate_limited": record} - with pytest.raises(RateLimitStop, match="top up"): + with pytest.raises(RateLimitStop, match="top up") as stop: await gate.call(send) + assert stop.value.kind == "out_of_credit" # the report lists each credit stop (16.20) assert len(calls) == 1 assert sleeps.waits == [] From c3ab7cebfb955dac658e2c8d1500c83a9ba59fd5 Mon Sep 17 00:00:00 2001 From: Aizat Hawari Date: Fri, 27 Nov 2026 23:28:55 +0000 Subject: [PATCH 2/3] fix(exp35): PR 239 review fixes on hosted usage - closed_missing reads not defined when a stage summary is missing. - row cost carries cost_scope (saved rows; billed total from billing). - billing rows with a non-finite usd are refused. - task 13.5 note: chunk-count cause (A13) and where the distribution is recorded. --- .../hostedusage35.py | 12 +++++++++- .../changes/exp35-main-run-readiness/tasks.md | 2 +- tests/test_clean_base_tripwire.py | 6 ++--- tests/test_experiment35_hosted_usage.py | 22 +++++++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py b/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py index 0d20e51d3..59de5d3a9 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py @@ -21,6 +21,7 @@ from __future__ import annotations import json +import math from collections.abc import Iterable, Mapping, Sequence from datetime import UTC, datetime from pathlib import Path @@ -29,6 +30,7 @@ from outputs35 import read_rows NOT_DEFINED = "not defined" +COST_SCOPE = "saved rows; billed total in billing_by_provider" #: RTX 4090 board power in watts (NVIDIA specification), the only GPU type (protocol 9.3). BOARD_WATTS = 450 #: Row file, its role, its summary file, and where its tokens and cost come from. @@ -108,11 +110,16 @@ def hosted_usage(out: Path) -> dict[str, Any]: **per, "calls": len(calls), "resent_calls": NOT_DEFINED if per["summaries_missing"] else per["resent_calls"], + "closed_missing": NOT_DEFINED + if per["summaries_missing"] + else per["closed_missing"], "input_tokens": _total(calls, "input_tokens") if by_rows else NOT_DEFINED, "output_tokens": _total(calls, "output_tokens") if by_rows else NOT_DEFINED, "cost_usd": _total(calls, "cost_usd", "reported_cost_usd") if by_rows else NOT_DEFINED, + # A failed attempt saves no cost, so row cost can miss billed failures. + "cost_scope": COST_SCOPE if by_rows else "billing export", } ) return {"roles": rows} @@ -124,7 +131,10 @@ def billing_by_provider(paths: Iterable[Path]) -> dict[str, float] | str: for path in paths: for row in json.loads(path.read_text(encoding="utf-8")): provider = str(row["provider"]) - totals[provider] = round(totals.get(provider, 0.0) + float(row["usd"]), 12) + usd = float(row["usd"]) + if not math.isfinite(usd): + raise ValueError(f"{path}: {provider} usd {row['usd']!r} is not a finite amount") + totals[provider] = round(totals.get(provider, 0.0) + usd, 12) return dict(sorted(totals.items())) if totals else NOT_DEFINED diff --git a/openspec/changes/exp35-main-run-readiness/tasks.md b/openspec/changes/exp35-main-run-readiness/tasks.md index b6da27543..b278a66c0 100644 --- a/openspec/changes/exp35-main-run-readiness/tasks.md +++ b/openspec/changes/exp35-main-run-readiness/tasks.md @@ -519,7 +519,7 @@ Architecture invariant 11: one new file and one `register()` line, no branch on - [x] 13.4 Legal RAG Bench loader (design D29). Write failing tests with a small fixture of both configs: 100-row shape, gold `relevant_passage_id`, passages written once as `.md` holding title, text and footnotes, with a leading `#` on any line escaped, frozen seeded order, file SHA-256 check, and a stop that names a missing gold passage. The passage files are written once by `prepare35.py` into the fixed folder of task 5.4c, never under ``. Prove they fail, then implement in `datasets35.py` and `prepare35.py`. Verify: the tests pass. - [x] 13.5 FreshStack 203 queries on the full public corpus (amendment A4, 2026-11-14; pre-registration section 4; design D38). Write failing tests: the loader drops the 20 continuity queries; the corpus is the full `freshstack/corpus-oct-2024` config `langchain` at the pinned revision (49,514 documents on the real data; a fixture stands in for tests), with no `continuity/` file, no overlay runbook and no subset or distractor sampling; `datasets35.py` has no `_FS_OVERLAY` or `_FS_OVERLAY_ID` reference and no expected hash for the overlay; the loader refuses a corpus whose revision or row count differs from the pin; questions `77536364` and `77762811` stay. Export format (A5 R-4, H-14, fact checks F3 to F5): the indexed file holds the published row text only, with no front matter and no source URL, ID or byte offset (these go in the manifest); a row whose file extension (from the corpus ID path) is `.md` or `.mdx` is written unchanged; every other row, including a row with no extension and an `.ipynb` row, is wrapped in a backtick fence with no info string, one backtick longer than the longest backtick run in the row and at least three; the manifest records each row's extension and whether it was fenced; the query text is the title, a blank line, then the body (`query_title`, `query_text`), as Experiments 9a and 22 sent it. Further failing-first tests: a written file holds no `---` front matter and no URL; a `.py` row with `#` comment lines gives no heading in `_heading_positions` (`src/omrs/core/chunking/model_token.py:362`); a row that holds a three-backtick line is still one fenced block. If either fence test cannot pass on the model-token Markdown path, the fallback applies (A5 R-4): keep the text with no fence, and the protocol states the heading effect as a limitation. Prove they fail, then remove the overlay constants, its hash entry, its id mapping and the `continuity/*.md` glob, and add the revision and row-count check. Verify: the tests pass, the loader reports 203 queries, the revision, row count and corpus tree hash from task 16.1 (P1) are in `plan.json`, and the test pod session (task 9.2) records the realised chunk-length distribution on FreshStack. The protocol states the limitation that FreshStack rows are byte spans, so a Markdown row can start or end inside a fence. Check (2026-11-25, Mac, no download; left open): the realised chunk-length distribution of FreshStack is not recorded. The test pod session did not save one. A Mac chunking of the 49,506 exported files (pinned Qwen3 tokenizer, same chunk settings, `read_and_chunk_file_async`) gives 182,210, 113,300 and 61,852 chunks at 512, 1,024 and 2,048, but the pod's `e8b-c512` ingest (DATA `p2-session-2026-11-24`) stored 196,350 chunks, and 69 of the first 600 files have another chunk count on the pod. The Mac figures are therefore not the stored chunks. Needed: the stored chunks of one pod index (read the LanceDB table of a sealed index and count tokens) or the main-run report table (`reporttables35.chunk_lengths`, from the saved search lists), and the cause of the difference in chunk counts. - Verified 2026-11-27: `tests/test_experiment35_datasets.py` (`test_no_overlay_or_continuity_reference_is_left`, `test_freshstack_drops_continuity_queries_and_sends_title_then_body`, `test_freshstack_corpus_refuses_another_revision_or_row_count`); `datasets35.py` holds no `_FS_OVERLAY` reference. The full corpus ran in the P2 build (49,506 prepared files). + Verified 2026-11-27: `tests/test_experiment35_datasets.py` (`test_no_overlay_or_continuity_reference_is_left`, `test_freshstack_drops_continuity_queries_and_sends_title_then_body`, `test_freshstack_corpus_refuses_another_revision_or_row_count`); `datasets35.py` holds no `_FS_OVERLAY` reference. The full corpus ran in the P2 build (49,506 prepared files). Chunk counts: the pod `e8b-c512` build stored 196,350 chunks because it ran with file-type routing on (Magika sent fenced files to `CodeSplitter`); amendment A13 (task 16.37) turned routing off, and the full FreshStack then gives 182,210, 113,300 and 61,852 chunks at 512, 1,024 and 2,048, the Mac figures. The realised stored-chunk distribution is a registered report table (pre-registration section 21, `reporttables35.chunk_length_table`, task 16.20) built from the main-run indexes; no pre-freeze index was built with routing off, so it is recorded there, not here (PR #239 review). - [x] 13.5a BioASQ passages as `.md` (operator decision, 2026-11-13). Write failing tests: the passage writer writes `.md` (not `.txt`), escapes a leading `#` on any line, and maps gold ids without the suffix. Prove they fail, then implement. The writer runs once in `prepare35.py` into the fixed passage folder of task 5.4c, never under ``. Verify: the tests pass. - [x] 13.5b Qwen3 token counts on all four datasets. Write a failing test that ingests a small fixture of FinanceBench (Markdown PDF text), FreshStack, BioASQ and Legal at 512, 1,024 and 2,048 tokens and asserts: every chunk has at most the level's Qwen3 token count (pinned tokenizer revision); every dataset goes through the model-token-aware Markdown path; the cl100k counter is never called (patched to raise). Prove it fails on the `.txt` passages, then pass it after 13.4 and 13.5a. Verify: the test passes. - [x] 13.6 FinanceBench number match (design D29). Write failing tests with known pairs: "$1,577 million" against "$1.58 billion" passes; "12.5%" against "12.5 percent" passes; "(3.2)" against "-3.2" passes; a missing number fails; two reference numbers need both; a 2% difference fails. Code review (A5 item 56): `FY2022` reads as 2022, `FY22` and `XFY2020` are not read; `$3M` reads as 3,000,000, `3M` is not read and `2 b` reads as 2; `777X` and `1x` are not read; on the pinned FinanceBench file 24 of 150 references hold no number. Prove they fail, then implement in `scoring35.py` (or `numbers35.py`). Verify: the tests pass. diff --git a/tests/test_clean_base_tripwire.py b/tests/test_clean_base_tripwire.py index 102d87aa7..238dbad4a 100644 --- a/tests/test_clean_base_tripwire.py +++ b/tests/test_clean_base_tripwire.py @@ -564,9 +564,9 @@ # +5 (2026-11-27, PR 238 review, by test-ID diff against HEAD 3e357e1d): 9 added, 5 in # test_experiment35_audit, 3 in test_experiment35_bootstrap and 1 in # test_experiment35_differential; 4 node cases in test_experiment35_labelaids moved to slow. -# +9 (2026-11-27, task 16.20, by test-ID diff against v3 987a21be): 7 in -# test_experiment35_hosted_usage and 2 in test_experiment35_run_arms. -_BASE_EXECUTED = 14507 +# +12 (2026-11-27, task 16.20 and PR 239 review, by test-ID diff against v3 987a21be): +# 10 in test_experiment35_hosted_usage and 2 in test_experiment35_run_arms. +_BASE_EXECUTED = 14510 # Re-baselined check-embedding-stamp-before-dimension (2026-10-18): 10 new cases # (store stamp-first tests and graph embed-step tests). Measured in two clean # venvs: 5741 with the web extra, 5091 without; the web extra still adds 650. diff --git a/tests/test_experiment35_hosted_usage.py b/tests/test_experiment35_hosted_usage.py index 8d54f3bcf..af41a3de1 100644 --- a/tests/test_experiment35_hosted_usage.py +++ b/tests/test_experiment35_hosted_usage.py @@ -164,3 +164,25 @@ def test_the_report_tables_carry_the_hosted_items(tmp_path: Path) -> None: assert hosted["energy"]["kwh"] == 0.9 # 2 closed GPU hours at 450 W assert hosted["stops"] == [{"kind": "out_of_credit", "stage": "answer"}] assert hosted["returned_model"] == ND # no join.json + + +def test_closed_calls_are_not_defined_when_a_summary_is_missing(tmp_path: Path) -> None: + _tree(tmp_path) + table = hostedusage35.hosted_usage(tmp_path) + assert _role(table, "answer", "ragas-judge")["closed_missing"] == ND + assert _role(table, "answer", "judge-glm")["closed_missing"] == 0 # measured zero + + +def test_row_cost_is_labelled_as_saved_rows_only(tmp_path: Path) -> None: + _tree(tmp_path) + answer = _role(hostedusage35.hosted_usage(tmp_path), "answer", "answer") + assert answer["cost_scope"] == "saved rows; billed total in billing_by_provider" + + +def test_non_finite_billing_amounts_are_refused(tmp_path: Path) -> None: + import pytest + + bad = tmp_path / "bad.json" + _json(bad, [{"provider": "zai", "usd": "NaN"}]) + with pytest.raises(ValueError, match="not a finite amount"): + hostedusage35.billing_by_provider([bad]) From df1b80ea7d4d52607aa3229401caea07cf0f3283 Mon Sep 17 00:00:00 2001 From: Aizat Hawari Date: Fri, 27 Nov 2026 23:54:58 +0000 Subject: [PATCH 3/3] fix(exp35): count billed failed attempts and classifier cost per row - A failed answer call keeps its reported tokens and cost in the error line (OrderedRows.fail usage); hosted_usage adds them to the role totals. - Classifier rows save input/output tokens and cost (same model as the Ragas judge on OpenRouter, so billing cannot split the two). - Only GLM-5.3 comes from billing (Z.ai, its only role). A18 item 35 updated. --- .../answers35.py | 12 ++++- .../claimstage35.py | 3 ++ .../hostedusage35.py | 41 ++++++++++----- .../preregistration.md | 2 +- .../protocol.md | 2 +- experiments/_lib/ordered_rows.py | 16 +++++- tests/test_clean_base_tripwire.py | 7 +-- tests/test_experiment35_claimstage.py | 12 +++++ tests/test_experiment35_hosted_usage.py | 50 +++++++++++++------ tests/test_experiment35_parallel_answers.py | 17 +++++++ 10 files changed, 126 insertions(+), 36 deletions(-) diff --git a/experiments/35-full-rag-benchmark-2026-11-01/answers35.py b/experiments/35-full-rag-benchmark-2026-11-01/answers35.py index 9a3010d87..931d9ed78 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/answers35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/answers35.py @@ -291,6 +291,13 @@ def answer_row( } +def failed_usage(result: Mapping[str, Any]) -> dict[str, Any] | None: + """Return the tokens and cost a failed answer call reported, else ``None`` (task 16.20).""" + usage = result.get("usage") or {} + kept = {k: usage[k] for k in ("input_tokens", "output_tokens", "cost_usd") if k in usage} + return kept or None + + def _trace( ctx: stages35.Ctx, qid: str, @@ -365,7 +372,7 @@ async def answer_stage(ctx: stages35.Ctx) -> int: async def one(qid: str) -> None: question = by_id[qid] - error = None + error, usage = None, None try: async with searching: found, line = await stagekit35.ranked(ctx, question.text) @@ -388,12 +395,13 @@ async def one(qid: str) -> None: result = {**result, "answer": ""} elif result.get("answer") is None: error = ctx.redact(str(result.get("error") or "no answer text"))[:500] + usage = failed_usage(result) except (stagekit35.RerankFailed, RateLimitStop): raise except Exception as exc: # noqa: BLE001 - an error is not a result (section 12) error = stages35._error(ctx, exc) if error is not None: - kept.fail(qid, error, _trace(ctx, qid, None, error)) + kept.fail(qid, error, _trace(ctx, qid, None, error), usage=usage) say(f"[answer] {qid}: ERROR {error}") return cut = frozenset(str(r["chunk_id"]) for r in rows if r.get("truncated")) diff --git a/experiments/35-full-rag-benchmark-2026-11-01/claimstage35.py b/experiments/35-full-rag-benchmark-2026-11-01/claimstage35.py index 0391b0514..15d7a16ce 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/claimstage35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/claimstage35.py @@ -248,6 +248,9 @@ async def one(item_id: str) -> None: "version": version, "model_returned": getattr(reply, "model_returned", None), "provider_returned": getattr(reply, "provider_returned", None), + "input_tokens": getattr(reply, "input_tokens", None), + "output_tokens": getattr(reply, "output_tokens", None), + "cost_usd": getattr(reply, "cost_usd", None), }, ) diff --git a/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py b/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py index 59de5d3a9..ab4db6f68 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/hostedusage35.py @@ -6,10 +6,13 @@ - :func:`hosted_usage`: per stage (the output kind, for example ``answer`` or ``closedbook-own``) and role, the rows, calls, error rows, harness resends (``resent_calls``), calls closed as missing after the resend cap, and the - tokens and cost. The answer and Ragas rows record tokens and cost per call. - The GLM-5.3 claim checks and the claim classifier record none, so their - tokens and cost come from the provider billing exports (amendment A18 item 35). - A sum is defined only when every call reported the figure. + tokens and cost. The answer, Ragas and claim-classifier rows record tokens + and cost per call; a billed failed answer or classifier attempt keeps its + figures in the stage's ``.errors.jsonl`` line and is added (an error + line with no figures is counted in ``failed_attempts_without_usage``). The + GLM-5.3 claim checks record none; GLM-5.3 is the only Z.ai role, so its + tokens and cost are the Z.ai billing export (amendment A18 item 35). + A sum is defined only when every saved call reported the figure. - :func:`billing_by_provider`: the ``usd`` of the billing rows per provider. - :func:`energy_estimate`: closed GPU pod hours times the board power of the RTX 4090 (450 W), in kWh (Strubell et al. 2019; Lacoste et al. 2019). @@ -30,15 +33,21 @@ from outputs35 import read_rows NOT_DEFINED = "not defined" -COST_SCOPE = "saved rows; billed total in billing_by_provider" #: RTX 4090 board power in watts (NVIDIA specification), the only GPU type (protocol 9.3). BOARD_WATTS = 450 -#: Row file, its role, its summary file, and where its tokens and cost come from. +GLM_SOURCE = "billing export (Z.ai)" +#: Row file, role, summary file, error file of failed attempts, and the figures' source. ROLES = ( - ("answer.jsonl", "answer", "answer-summary.json", "rows"), - ("ragas.jsonl", "ragas-judge", "ragas-summary.json", "rows"), - ("judge-chat.jsonl", "judge-glm", "judge-chat-summary.json", "billing export"), - ("claim-kinds.jsonl", "claim-classifier", "claimkinds-summary.json", "billing export"), + ("answer.jsonl", "answer", "answer-summary.json", "answer.errors.jsonl", "rows"), + ("ragas.jsonl", "ragas-judge", "ragas-summary.json", None, "rows"), + ("judge-chat.jsonl", "judge-glm", "judge-chat-summary.json", None, GLM_SOURCE), + ( + "claim-kinds.jsonl", + "claim-classifier", + "claimkinds-summary.json", + "claimkinds.errors.jsonl", + "rows", + ), ) @@ -77,13 +86,15 @@ def _empty(stage: str, role: str, source: str) -> dict[str, Any]: "resent_calls": 0, "closed_missing": 0, "summaries_missing": 0, + "failed_attempts": 0, + "failed_attempts_without_usage": 0, } def hosted_usage(out: Path) -> dict[str, Any]: """Return per stage and role the hosted calls, errors, resends, tokens and cost.""" found: dict[tuple[str, str], dict[str, Any]] = {} - for name, role, summary_name, source in ROLES: + for name, role, summary_name, errors_name, source in ROLES: for path in sorted(out.glob(f"*/*/*/run*/{name}")): stage = path.parts[-4] per = found.setdefault((stage, role), _empty(stage, role, source)) @@ -94,6 +105,12 @@ def hosted_usage(out: Path) -> dict[str, Any]: per["rows"] += 1 per["calls"].extend(calls) per["error_rows"] += any(_is_error(c) for c in calls) + for line in read_rows(path.parent / errors_name) if errors_name else []: + per["failed_attempts"] += 1 + if line.get("usage"): + per["calls"].append(line["usage"]) + else: + per["failed_attempts_without_usage"] += 1 summary_path = path.parent / summary_name if summary_path.is_file(): summary = json.loads(summary_path.read_text(encoding="utf-8")) @@ -118,8 +135,6 @@ def hosted_usage(out: Path) -> dict[str, Any]: "cost_usd": _total(calls, "cost_usd", "reported_cost_usd") if by_rows else NOT_DEFINED, - # A failed attempt saves no cost, so row cost can miss billed failures. - "cost_scope": COST_SCOPE if by_rows else "billing export", } ) return {"roles": rows} diff --git a/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md b/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md index 379fa448e..6fb932fa1 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md +++ b/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md @@ -491,7 +491,7 @@ After the freeze, every change is a dated, numbered deviation. The report lists - Counts per setup and dataset of chunks with no page label and of unmapped chunks (placeholder units, section 6), and the count of fenced rows per file extension in the FreshStack export (section 4). - Per question and answer setup, the cut total and the realised evidence token total (section 3), with the share of questions where the assembled evidence is shorter than the cut total. - Sensitivity tables: GEE against permutation disagreements; FinanceBench nDCG@10 for rows 9 and 10 (a chunk covers its page), with sign agreement per row against `evidence_recall_20k` (H6); FreshStack `evidence_recall_20k` for rows 9 to 11, descriptive; the four H7 corner-cell means with 95% intervals beside row 11; missing-outcome bounds; closed-book subset; length-controlled check; H8b on questions with a cut total of at least 95% of the token budget in all three `-t20k` setups, with both token totals (cut and realised) per setup; faithfulness with uncited factual segments as unsupported, beside the uncited-segment share. -- **Compute table**: GPU type, pod hours per stage including every pre-freeze pod (test pod, GPU timing, smoke runs), hosted tokens and cost per role (answer and Ragas calls from the saved rows; GLM-5.3 and claim-classifier calls from the provider billing exports, because those calls save no token counts), an energy estimate (GPU hours times board power; Strubell et al. 2019; Lacoste et al. 2019), `resent_calls` (harness-level resends only, section 12), calls closed as missing after the resend cap, error rows per stage and role, and every `out_of_credit` stop. +- **Compute table**: GPU type, pod hours per stage including every pre-freeze pod (test pod, GPU timing, smoke runs), hosted tokens and cost per role (answer, Ragas and claim-classifier calls from the saved rows, billed failed attempts included; GLM-5.3 calls from the Z.ai billing export, because those calls save no token counts and GLM-5.3 is the only Z.ai role), an energy estimate (GPU hours times board power; Strubell et al. 2019; Lacoste et al. 2019), `resent_calls` (harness-level resends only, section 12), calls closed as missing after the resend cap, error rows per stage and role, and every `out_of_credit` stop. - Model labeller agreement per set beside the checker and judge agreements (section 11.3; descriptive). - A18 additions: classifier development rounds 1 and 2 in full (section 11.1); all-claims faithfulness beside the primary measure (section 11.1); the pooled H8 estimate beside both per-dataset estimates (section 9 point 7); the relevance audit tables (section 11.3). - Returned model ID and provider per hosted call, with the count of differences from the requested values. diff --git a/experiments/35-full-rag-benchmark-2026-11-01/protocol.md b/experiments/35-full-rag-benchmark-2026-11-01/protocol.md index 9aaa8bc94..1455aea99 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/protocol.md +++ b/experiments/35-full-rag-benchmark-2026-11-01/protocol.md @@ -480,7 +480,7 @@ Written before the freeze. No measured run has started and no L2 label exists. O 32. **Model labeller (owner decision, 2026-11-27).** Claude Opus 5.5 at high effort labels every item on the blind pages after both human label sets are frozen and hashed. Descriptive agreement only; no human label changes. The human review of model disagreements (a third pass) was considered and rejected: it adds work and its labels would be anchored. Pre-registration sections 11.3, 21 and 22. 33. **Build clarifications (2026-11-27, from the P19 build).** A row with zero estimate variance on either dataset is not pooled. The undefined-statistic rules of section 11.2 apply to the sensitivity difference; a chunk-size level with no human-unsupported claim is undefined. Wording only. 34. **Audit output is an estimate (2026-11-27, PR 238 review).** Pre-registration sections 11.3 and 22 now call the H3 audit output an estimate restricted to arm-exclusive unjudged units, not a bound. An unjudged unit in the top 3 of both arms at different ranks is not covered. Wording only. Source: CodeRabbit on PR #238. -35. **Hosted tokens of the GLM-5.3 and classifier calls (owner decision, 2026-11-27, task 16.20).** The GLM-5.3 claim checks and the claim classifier save no token counts per call; only the answer and Ragas calls do. Pre-registration sections 17 and 21 now take the tokens and cost of those two roles from the provider billing exports (Z.ai and OpenRouter). Recording them per call was considered and rejected: it changes the OMRS judge record and the HTTP API contract before the freeze. `hostedusage35.py` builds the hosted part of the compute table; `run_arms.py` saves every rate-limit and `out_of_credit` stop to `stops.jsonl`. No hypothesis, test, gate or budget figure changes. +35. **Hosted tokens of the GLM-5.3 and classifier calls (owner decision, 2026-11-27, task 16.20).** The GLM-5.3 claim checks save no token counts per call. Pre-registration sections 17 and 21 now take GLM-5.3 tokens and cost from the Z.ai billing export; GLM-5.3 is the only role on Z.ai, so the export is GLM-5.3 alone. The claim classifier (OpenRouter, the same model as the Ragas judge, so OpenRouter billing cannot split them) now saves tokens and cost on each row, and a billed failed answer or classifier attempt keeps its tokens and cost in the stage's error line, so the row totals include failed attempts (PR #239 review). Recording them per call was considered and rejected: it changes the OMRS judge record and the HTTP API contract before the freeze. `hostedusage35.py` builds the hosted part of the compute table; `run_arms.py` saves every rate-limit and `out_of_credit` stop to `stops.jsonl`. No hypothesis, test, gate or budget figure changes. ## 1. Question diff --git a/experiments/_lib/ordered_rows.py b/experiments/_lib/ordered_rows.py index 8da40671f..0dd346045 100644 --- a/experiments/_lib/ordered_rows.py +++ b/experiments/_lib/ordered_rows.py @@ -173,7 +173,13 @@ def submit( self._pending[item] = entry self.commit() - def fail(self, item: str, error: str, trace: Mapping[str, Any] | None = None) -> bool: + def fail( + self, + item: str, + error: str, + trace: Mapping[str, Any] | None = None, + usage: Mapping[str, Any] | None = None, + ) -> bool: """Record an error with no content; close *item* as missing at the cap. Call it only for an error that is not a rate limit and not out of @@ -186,7 +192,13 @@ def fail(self, item: str, error: str, trace: Mapping[str, Any] | None = None) -> """ append_line( self._errors_path, - {"id": item, "error": error, **({} if trace is None else {"trace": dict(trace)})}, + { + "id": item, + "error": error, + **({} if trace is None else {"trace": dict(trace)}), + # A billed failed attempt keeps its tokens and cost (Exp 35 task 16.20). + **({} if not usage else {"usage": dict(usage)}), + }, ) errors = self._errors.setdefault(item, []) errors.append(error) diff --git a/tests/test_clean_base_tripwire.py b/tests/test_clean_base_tripwire.py index 238dbad4a..484d77ba3 100644 --- a/tests/test_clean_base_tripwire.py +++ b/tests/test_clean_base_tripwire.py @@ -564,9 +564,10 @@ # +5 (2026-11-27, PR 238 review, by test-ID diff against HEAD 3e357e1d): 9 added, 5 in # test_experiment35_audit, 3 in test_experiment35_bootstrap and 1 in # test_experiment35_differential; 4 node cases in test_experiment35_labelaids moved to slow. -# +12 (2026-11-27, task 16.20 and PR 239 review, by test-ID diff against v3 987a21be): -# 10 in test_experiment35_hosted_usage and 2 in test_experiment35_run_arms. -_BASE_EXECUTED = 14510 +# +13 (2026-11-27, task 16.20 and PR 239 review, by test-ID diff against v3 987a21be): +# 9 in test_experiment35_hosted_usage, 2 in test_experiment35_run_arms, 1 in +# test_experiment35_claimstage and 1 in test_experiment35_parallel_answers. +_BASE_EXECUTED = 14511 # Re-baselined check-embedding-stamp-before-dimension (2026-10-18): 10 new cases # (store stamp-first tests and graph embed-step tests). Measured in two clean # venvs: 5741 with the web extra, 5091 without; the web extra still adds 650. diff --git a/tests/test_experiment35_claimstage.py b/tests/test_experiment35_claimstage.py index 10494ba8e..91d348f0a 100644 --- a/tests/test_experiment35_claimstage.py +++ b/tests/test_experiment35_claimstage.py @@ -271,3 +271,15 @@ def test_the_real_path_refuses_a_pending_classifier_seed_and_names_it( ctx = _real_ctx(tmp_path, plan) with pytest.raises(arms.ArmConfigError, match=r"seeds\.classifier.*P10"): claimstage35._classifier(ctx) + + +def test_each_kind_row_saves_the_call_tokens_and_cost(tmp_path) -> None: + async def classifier(messages): + reply = _reply() + reply.input_tokens, reply.output_tokens, reply.cost_usd = 120, 3, 0.0002 + return reply + + ctx = _ctx(tmp_path, classifier) + assert _run(ctx) == 0 + row = _rows(ctx)[0] + assert (row["input_tokens"], row["output_tokens"], row["cost_usd"]) == (120, 3, 0.0002) diff --git a/tests/test_experiment35_hosted_usage.py b/tests/test_experiment35_hosted_usage.py index af41a3de1..47bdc9b05 100644 --- a/tests/test_experiment35_hosted_usage.py +++ b/tests/test_experiment35_hosted_usage.py @@ -62,7 +62,30 @@ def _tree(out: Path) -> None: ], ) _json(run / "judge-chat-summary.json", {"resent_calls": 1, "closed_missing": []}) - _rows(run / "claim-kinds.jsonl", [{"claim_key": "a", "kind": "factual"}]) + _rows( + run / "claim-kinds.jsonl", + [ + { + "claim_key": "a", + "kind": "factual", + "input_tokens": 9, + "output_tokens": 1, + "cost_usd": 0.02, + } + ], + ) + _json(run / "claimkinds-summary.json", {"resent_calls": 0, "closed_missing": []}) + _rows( + run / "answer.errors.jsonl", + [ + { + "id": "3", + "error": "bad reply", + "usage": {"input_tokens": 40, "output_tokens": 5, "cost_usd": 0.25}, + }, + {"id": "3", "error": "timeout"}, + ], + ) cb = _run(out, kind="closedbook-own") _rows(cb / "answer.jsonl", [{"qid": "1", "status": "ok", "input_tokens": 4, "cost_usd": 0.01}]) @@ -75,7 +98,9 @@ def test_answer_and_ragas_tokens_and_cost_come_from_the_rows(tmp_path: Path) -> _tree(tmp_path) table = hostedusage35.hosted_usage(tmp_path) answer = _role(table, "answer", "answer") - assert (answer["rows"], answer["input_tokens"], answer["cost_usd"]) == (2, 150, 0.75) + # Saved rows 150 tokens and $0.75, plus the billed failed attempt (40 tokens, $0.25). + assert (answer["rows"], answer["input_tokens"], answer["cost_usd"]) == (2, 190, 1.0) + assert answer["failed_attempts"] == 2 and answer["failed_attempts_without_usage"] == 1 # One row reported no output tokens: the sum is not defined, never a silent undercount. assert answer["output_tokens"] == ND assert answer["source"] == "rows" @@ -86,14 +111,16 @@ def test_answer_and_ragas_tokens_and_cost_come_from_the_rows(tmp_path: Path) -> assert (closed["rows"], closed["input_tokens"], closed["cost_usd"]) == (1, 4, 0.01) -def test_glm_and_classifier_tokens_and_cost_come_from_the_billing_export(tmp_path: Path) -> None: +def test_glm_cost_comes_from_billing_and_the_classifier_from_its_rows(tmp_path: Path) -> None: _tree(tmp_path) table = hostedusage35.hosted_usage(tmp_path) - for role in ("judge-glm", "claim-classifier"): - row = _role(table, "answer", role) - assert row["source"] == "billing export" - assert row["input_tokens"] == row["output_tokens"] == row["cost_usd"] == ND - assert _role(table, "answer", "judge-glm")["calls"] == 3 + glm = _role(table, "answer", "judge-glm") + assert glm["source"] == "billing export (Z.ai)" + assert glm["input_tokens"] == glm["output_tokens"] == glm["cost_usd"] == ND + assert glm["calls"] == 3 + kinds = _role(table, "answer", "claim-classifier") + assert kinds["source"] == "rows" + assert (kinds["input_tokens"], kinds["output_tokens"], kinds["cost_usd"]) == (9, 1, 0.02) def test_error_rows_resends_and_closed_calls_per_stage_and_role(tmp_path: Path) -> None: @@ -103,6 +130,7 @@ def test_error_rows_resends_and_closed_calls_per_stage_and_role(tmp_path: Path) assert _role(table, "answer", "ragas-judge")["error_rows"] == 1 assert _role(table, "answer", "judge-glm")["error_rows"] == 1 assert _role(table, "answer", "claim-classifier")["error_rows"] == 0 + assert _role(table, "answer", "claim-classifier")["closed_missing"] == 0 assert _role(table, "answer", "answer")["resent_calls"] == 2 assert _role(table, "answer", "answer")["closed_missing"] == 1 assert _role(table, "answer", "judge-glm")["resent_calls"] == 1 @@ -173,12 +201,6 @@ def test_closed_calls_are_not_defined_when_a_summary_is_missing(tmp_path: Path) assert _role(table, "answer", "judge-glm")["closed_missing"] == 0 # measured zero -def test_row_cost_is_labelled_as_saved_rows_only(tmp_path: Path) -> None: - _tree(tmp_path) - answer = _role(hostedusage35.hosted_usage(tmp_path), "answer", "answer") - assert answer["cost_scope"] == "saved rows; billed total in billing_by_provider" - - def test_non_finite_billing_amounts_are_refused(tmp_path: Path) -> None: import pytest diff --git a/tests/test_experiment35_parallel_answers.py b/tests/test_experiment35_parallel_answers.py index 2a2a60fcf..30beeb06d 100644 --- a/tests/test_experiment35_parallel_answers.py +++ b/tests/test_experiment35_parallel_answers.py @@ -80,6 +80,9 @@ async def answer(self, text: str, **kwargs: Any) -> dict[str, Any]: return {"status": "error", "answer": None, "rate_limited": dict(LIMITED)} if step == "error": return {"status": "error", "answer": None, "error": "Generation failed: timeout"} + if step == "billed_error": + usage = {"input_tokens": 40, "output_tokens": 5, "cost_usd": 0.25} + return {"status": "error", "answer": None, "error": "bad reply", "usage": usage} if step == "empty_reply": return {"status": "error", "answer": None, "error": EMPTY_REPLY_ERROR} if isinstance(step, Exception): @@ -346,3 +349,17 @@ def test_each_row_records_the_returned_provider_and_model(tmp_path: Path) -> Non row = _lines(ctx.run_dir / "answer.jsonl")[0] assert row["provider_returned"] == "h1" assert row["model_returned"] == "deepseek/deepseek-v4.1-flash-1017" + + +def test_a_billed_failed_attempt_keeps_its_usage_in_the_error_line(tmp_path: Path) -> None: + engine = Engine(script={"question 2?": ["billed_error", "error"]}) + with pytest.raises(stages35.StageIncomplete): + _run(_ctx(tmp_path, engine)) + ctx = _ctx(tmp_path, engine, resume=True) + with pytest.raises(stages35.StageIncomplete): + _run(ctx) + lines = _lines(ctx.run_dir / "answer.errors.jsonl") + assert [line.get("usage") for line in lines] == [ + {"input_tokens": 40, "output_tokens": 5, "cost_usd": 0.25}, + None, # no usage reported: the line carries none + ]