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 931d9ed7..497b4c2f 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/answers35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/answers35.py @@ -213,7 +213,13 @@ def measure(ctx: stages35.Ctx, rows: Sequence[Mapping[str, Any]]) -> dict[str, i class _SplitLog: - """The answer row file; a row's ``retrieval`` part goes to ``retrieval.jsonl`` first.""" + """The answer row file; a row's ``retrieval`` part goes to ``retrieval.jsonl`` first. + + A question whose search worked but whose answer call failed keeps its search line in + ``answer.searches.jsonl`` (one synced line, written before the error is recorded). A + closed-missing row has no ``retrieval`` part, so it takes that saved line instead + (section 12: a missing answer scores 0; section 15: only a failed search is incomplete). + """ def __init__(self, log: outputs35.RowFile) -> None: self._log = log @@ -228,6 +234,14 @@ def __init__(self, log: outputs35.RowFile) -> None: tmp.parent.mkdir(parents=True, exist_ok=True) tmp.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in keep), "utf-8") tmp.replace(self._extra) + self._searches_path = self._extra.with_name("answer.searches.jsonl") + self._searches = {str(r["qid"]): r for r in read_lines(self._searches_path)} + + def keep_search(self, line: Mapping[str, Any]) -> None: + """Save the search *line* of a question whose answer failed, once, before the error.""" + if line["qid"] not in self._searches: + append_line(self._searches_path, line) + self._searches[str(line["qid"])] = dict(line) def done_ids(self, field: str) -> set[str]: return self._log.done_ids(field) @@ -238,6 +252,8 @@ def mark_done(self, payload: Mapping[str, Any]) -> None: def append(self, row: Mapping[str, Any]) -> None: body = dict(row) extra = body.pop("retrieval", None) + if extra is None and body.get("missing"): + extra = self._searches.get(str(body["qid"])) if extra is not None: append_line(self._extra, extra) self._log.append(body) @@ -362,7 +378,8 @@ async def answer_stage(ctx: stages35.Ctx) -> int: say(f"[answer] {ctx.dataset}/{ctx.setup}/run{ctx.run}: done earlier, skipped") return 0 opened = stagekit35.open_checks(ctx) - kept = OrderedRows(_SplitLog(log), [q.qid for q in ctx.questions], trace=ctx.trace) + split = _SplitLog(log) + kept = OrderedRows(split, [q.qid for q in ctx.questions], trace=ctx.trace) gate = HostedGate( "answer", ctx.args.answer_concurrency, attempts=ctx.args.rate_limit_attempts ) @@ -372,7 +389,7 @@ async def answer_stage(ctx: stages35.Ctx) -> int: async def one(qid: str) -> None: question = by_id[qid] - error, usage = None, None + error, usage, line = None, None, None try: async with searching: found, line = await stagekit35.ranked(ctx, question.text) @@ -401,6 +418,8 @@ async def one(qid: str) -> None: except Exception as exc: # noqa: BLE001 - an error is not a result (section 12) error = stages35._error(ctx, exc) if error is not None: + if line is not None: + split.keep_search({"qid": qid, **line}) kept.fail(qid, error, _trace(ctx, qid, None, error), usage=usage) say(f"[answer] {qid}: ERROR {error}") return 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 15d7a16c..77bdcb07 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/claimstage35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/claimstage35.py @@ -117,9 +117,12 @@ def _items(run_dir: Path) -> dict[str, dict[str, Any]]: class _KindsLog: """The stage's ``RowFile`` with rows in ``claim-kinds.jsonl``; a closed row keeps its claim.""" - def __init__(self, log: outputs35.RowFile, items: Mapping[str, Mapping[str, Any]]) -> None: + def __init__( + self, log: outputs35.RowFile, items: Mapping[str, Mapping[str, Any]], version: str + ) -> None: self._log = log self._items = items + self._version = version self.stage = log.stage self.path = log.path.with_name(ROWS_FILE) if self.path.exists(): @@ -133,7 +136,8 @@ def done_ids(self, field: str) -> set[str]: def append(self, row: Mapping[str, Any]) -> None: if row.get("missing"): item = self._items[row["item"]] - row = {**_row(row["item"], item), "kind": None, **row} + # The version keeps the closed row valid under a passed gate (section 12). + row = {**_row(row["item"], item), "kind": None, "version": self._version, **row} with self.path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(dict(row), ensure_ascii=False) + "\n") handle.flush() @@ -219,7 +223,7 @@ async def claimkinds_stage( say(f"[claimkinds] {ctx.run_dir}: done earlier, skipped") return 0 items = _items(ctx.run_dir) - rows = OrderedRows(_KindsLog(log, items), list(items), id_field="item") + rows = OrderedRows(_KindsLog(log, items, version), list(items), id_field="item") limit = int(ctx.args.classify_concurrency) gate = HostedGate(ROLE, limit, attempts=int(ctx.args.rate_limit_attempts), sleep=sleep) slots = asyncio.Semaphore(limit) diff --git a/experiments/35-full-rag-benchmark-2026-11-01/factorial35.py b/experiments/35-full-rag-benchmark-2026-11-01/factorial35.py index bbc20c0b..64d2e1d2 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/factorial35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/factorial35.py @@ -47,7 +47,7 @@ from experiments._lib import stats_cluster from experiments._lib.stats_d6 import holm, paired_permutation from outputs35 import write_json -from verdicts35 import verdicts +from verdicts35 import row_sign, verdicts FB, FS, BQ = select35.CORE LEGAL = "legal" @@ -280,10 +280,10 @@ def _h8b_sensitivity( } fb, fs = out.get(FB, {}).get("estimates", {}), out.get(FS, {}).get("estimates", {}) # Protocol 0.14 item 65: each row must have that row's H8b sign on both datasets. - target = {} - for r in range(16, 20): - h8b = hypotheses["H8b"]["faithfulness" if r < 18 else "correctness"] - target[r] = h8b["sign"] if r in h8b["rows"] else 0 + target = { + r: row_sign(hypotheses["H8b"]["faithfulness" if r < 18 else "correctness"], r) + for r in range(16, 20) + } out["agrees"] = { r: target[r] != 0 and _sign(fb.get(r, 0.0)) == _sign(fs.get(r, 0.0)) == target[r] for r in range(16, 20) @@ -296,8 +296,9 @@ def _claims(hypotheses: Mapping[str, Any], sensitivity: Mapping[str, Any]) -> di claims: dict[str, str | None] = {} for outcome in ("faithfulness", "correctness"): h8a, h8b = hypotheses["H8a"][outcome], hypotheses["H8b"][outcome] + # Any holding row whose own H8b sign the sensitivity analysis repeats (section 7). itself = any( - sensitivity["sign"][r] != 0 and sensitivity["sign"][r] == h8b["sign"] + sensitivity["sign"][r] != 0 and sensitivity["sign"][r] == row_sign(h8b, r) for r in h8b["rows"] ) # Protocol 0.14 item 26: the registered claim names the fixed pre-assembly budget. diff --git a/experiments/35-full-rag-benchmark-2026-11-01/joinscores35.py b/experiments/35-full-rag-benchmark-2026-11-01/joinscores35.py index 69e5ef06..52e74bc6 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/joinscores35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/joinscores35.py @@ -180,7 +180,11 @@ def answer_scores( "faithfulness_glm_factual_uncited": sensitivity, CORRECT: _correctness(answer, ragas.get(qid)), "unjudged": unjudged, - "not_defined": [] if answer.get("missing") else _not_defined(ragas.get(qid)), + "not_defined": ( + [] + if answer.get("missing") or not answer.get("answer") + else _not_defined(ragas.get(qid)) + ), "unparseable_verdicts": unparseable, "segments": segments, "uncited_segments": uncited, diff --git a/experiments/35-full-rag-benchmark-2026-11-01/oracle35.py b/experiments/35-full-rag-benchmark-2026-11-01/oracle35.py index c6c3d30e..aecb7850 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/oracle35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/oracle35.py @@ -30,6 +30,8 @@ from experiments._lib.hosted_calls import HostedGate, RateLimitStop from experiments._lib.ordered_rows import OrderedRows +from omrs.core.answer.stages import EMPTY_REPLY_ERROR + say = outputs35.say #: Returns the text of one FinanceBench page: ``(document, page label) -> text``. PageReader = Callable[[str, str], str | None] @@ -169,7 +171,7 @@ async def oracle_stage(ctx: stages35.Ctx, pages: PageReader | None = None) -> in async def one(qid: str) -> None: rows, record = contexts[qid] kept.dispatch(qid) - error = None + error, usage = None, None started = stagekit35.clock() try: result = await gate.call( @@ -182,14 +184,18 @@ async def one(qid: str) -> None: ) ) ) - if result.get("answer") is None: + if result.get("answer") is None and result.get("error") == EMPTY_REPLY_ERROR: + # Protocol 0.14 item 66: a returned empty answer, final and never resent. + result = {**result, "answer": ""} + elif result.get("answer") is None: error = ctx.redact(str(result.get("error") or "no answer text"))[:500] + usage = answers35.failed_usage(result) except 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, answers35._trace(ctx, qid, None, error)) + kept.fail(qid, error, answers35._trace(ctx, qid, None, error), usage=usage) return seconds = round(stagekit35.clock() - started, 3) row = answers35.answer_row(ctx, by_id[qid], result, seconds) 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 6fb932fa..2c5f395e 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md +++ b/experiments/35-full-rag-benchmark-2026-11-01/preregistration.md @@ -165,7 +165,7 @@ A non-significant result means no difference was detected at this sample size. T ## 10. Smallest effect of interest and precision - **Smallest effect of interest (SESOI).** 0.02 nDCG@10, decided by the owner on 2026-11-14 (O2). The concept follows Lakens 2017. It changes no decision: every hypothesis is tested against zero, and each row's interval is read against plus and minus 0.02. No other endpoint has a SESOI; their intervals are reported without one. -- **Why 0.02.** No IR standard fixes this value; it is the authors' justified choice. (1) User terms: for a question with one gold unit, moving it from rank 2 to rank 1 raises nDCG@10 by 1 minus 1/log2(3), about 0.369. A mean gain of 0.02 is about one question in 18 with its gold unit moved from second to first place (0.02 / 0.369 = 0.054); 0.01 is about one in 37, and 0.05 about one in 7. Bringing a gold unit from outside the top 10 to rank 10 adds 1/log2(11), about 0.289, so 0.02 is about one question in 14. (2) Lower bound from the design: selection treats setups within 0.01 as tied (section 14.1) and the tolerance on another back end is 0.005 (section 15), so the SESOI must be above 0.01. (3) Cost: each factor step costs something real. A 4B to 8B model roughly doubles memory, a reranker scores 100 more pairs per query, and hybrid search adds an index. The authors judge that a gain which changes the top result for fewer than about one question in 20 does not pay for such a step for an OMRS user. (4) Published effects (Zhang et al. 2025; MTEB retrieval scores are nDCG@10 x 100): on MTEB(eng, v2) retrieval the 0.6B, 4B and 8B embedders score 61.83, 68.46 and 69.44 (steps about 0.066 and 0.010). On MTEB-R, from a 61.82 first stage, the 0.6B, 4B and 8B rerankers score 65.80, 69.76 and 69.02 (gains about 0.040, 0.079 and 0.072; size steps 0.040 and minus 0.007). These effects span about 0.01 to 0.08 in size, and 0.02 separates the two smallest steps from the rest. (5) Not set by power: the datasets are fixed, so the study chooses no sample size, and 0.02 was not chosen to match what the design can detect. The sensitivity power analysis below (A17) gives the smallest effect each test detects with power 0.80 (the MDE). On FreshStack and FinanceBench the MDE is about 0.04 to 0.08, so a true effect of 0.02 is not reliably detected there. On BioASQ it is about 0.02 to 0.03. A row whose interval cannot exclude 0.02 is reported as "cannot rule out a small effect". (6) Sensitivity: the report also reads every interval against 0.01 and 0.05. +- **Why 0.02.** No IR standard fixes this value; it is the authors' justified choice. (1) User terms: for a question with one gold unit, moving it from rank 2 to rank 1 raises nDCG@10 by 1 minus 1/log2(3), about 0.369. A mean gain of 0.02 is about one question in 18 with its gold unit moved from second to first place (0.02 / 0.369 = 0.054); 0.01 is about one in 37, and 0.05 about one in 7. Bringing a gold unit from outside the top 10 to rank 10 adds 1/log2(11), about 0.289, so 0.02 is about one question in 14. (2) Lower bound from the design: selection treats setups within 0.01 as tied (section 14.1) and the tolerance on another back end is 0.005 (section 15), so the SESOI must be above 0.01. (3) Cost: each factor step costs something real. A 4B to 8B model roughly doubles memory, a reranker scores 100 more pairs per query, and hybrid search adds an index. The authors judge that a gain which changes the top result for fewer than about one question in 20 does not pay for such a step for an OMRS user. (4) Published effects (Zhang et al. 2025; MTEB retrieval scores are nDCG@10 x 100): on MTEB(eng, v2) retrieval the 0.6B, 4B and 8B embedders score 61.83, 68.46 and 69.44 (steps about 0.066 and 0.010). On MTEB-R, from a 61.82 first stage, the 0.6B, 4B and 8B rerankers score 65.80, 69.76 and 69.02 (gains about 0.040, 0.079 and 0.072; size steps 0.040 and minus 0.007). These effects span about 0.01 to 0.08 in size, and 0.02 separates the two smallest steps from the rest. (5) Not set by power: the datasets are fixed, so the study chooses no sample size, and 0.02 was not chosen to match what the design can detect. The sensitivity power analysis below (A17) gives the smallest effect each test detects with power 0.80 (the MDE). On FreshStack and FinanceBench the MDE is about 0.04 to 0.08, so a true effect of 0.02 is not reliably detected there. On BioASQ it is about 0.02 to 0.03. A row whose interval cannot exclude 0.02 is read through cases 3 and 4 of A16 (next item). (6) Sensitivity: the report also reads every interval against 0.01 and 0.05. - **Precision (owner decision, 2026-11-26).** This study has no a priori power analysis, no pilot and no observed power. It reports one sensitivity power analysis (A17, below). Precision is reported through each row's 95% confidence interval. Amended 2026-11-26 (pre-freeze, owner; `plan.json` amendment A16): each interval is read against the SESOI of 0.02 nDCG@10 in four cases: 1. The interval is fully inside -0.02 to +0.02: no meaningful difference. 2. The interval is fully above +0.02, or fully below -0.02: a meaningful difference. diff --git a/experiments/35-full-rag-benchmark-2026-11-01/refusalreport35.py b/experiments/35-full-rag-benchmark-2026-11-01/refusalreport35.py index 9173de81..801e7482 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/refusalreport35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/refusalreport35.py @@ -105,7 +105,8 @@ def _load_run(folder: Path, version: str) -> dict[str, RunAnswer]: kinds_rows = read_rows(folder / "claim-kinds.jsonl") if any(r.get("version") != version for r in kinds_rows): raise ReportError(f"{folder}: a saved kind has another classifier version than {version}") - kinds = {r["claim_key"]: r["kind"] for r in kinds_rows} + # An uncited segment with the same text must not replace the cited claim's kind. + kinds = {r["claim_key"]: r["kind"] for r in kinds_rows if not r.get("uncited")} judges = {c: {r["qid"]: r for r in read_rows(folder / f"judge-{c}.jsonl")} for c in CHECKERS} where = "/".join(folder.parts[-4:]) out: dict[str, RunAnswer] = {} 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 1a1f56de..a250a542 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/reporttables35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/reporttables35.py @@ -78,7 +78,10 @@ SESOI = 0.02 READ_AGAINST = (0.01, 0.02, 0.05) -SMALL_EFFECT = "cannot rule out a small effect" +#: Cases 3 and 4 of Amendment A16 (section 10), in its own words. Cases 1 and 2 read "within" +#: and "beyond" (plus the SESOI in the registered reading). +SMALL_REAL = "a real difference that can be too small to matter" +CANNOT_TELL = "the test cannot tell" LENGTH_SOURCE = "distinct stored chunks in the saved top-100 search lists (pinned Qwen3 tokens)" #: The one sensitivity table set of section 21 (A5: no any-page or page-rule table). SENSITIVITY_TABLES = ( @@ -198,8 +201,15 @@ def h8b_token_totals(answer_records: Iterable[Mapping[str, Any]]) -> dict[str, A def _reading(low: float, high: float, t: float) -> str: + """Read a 95% interval against plus and minus ``t`` in the four cases of Amendment A16. + + The interval is closed: an endpoint on 0.0 includes zero, and an endpoint on plus or minus + ``t`` crosses ``t`` (so it is neither fully inside nor fully beyond). The four cases apply + to every ``t`` in ``READ_AGAINST``, because the rule only compares an interval with a + threshold. Section 10 registers the reading against 0.02, and (6) reads 0.01 and 0.05 alike. + """ if low <= t <= high or low <= -t <= high: - return "cannot exclude" + return CANNOT_TELL if low <= 0 <= high else SMALL_REAL return "within" if -t < low and high < t else "beyond" @@ -209,8 +219,10 @@ def sesoi_lines( """Return per row the SESOI reading and its marks (sections 10 and 21). Only nDCG@10 rows have a SESOI (0.02); their interval is read against plus - and minus 0.01, 0.02 and 0.05. An interval that cannot exclude 0.02 reads - "cannot rule out a small effect". Other rows get the marks only. + and minus 0.01, 0.02 and 0.05 in the four cases of Amendment A16: "within 0.02", + "beyond 0.02", "a real difference that can be too small to matter" (excludes zero, + crosses 0.02) and "the test cannot tell" (includes zero, crosses 0.02). The reading is + descriptive only. Other rows get the marks only. """ out: dict[str, list[dict[str, Any]]] = {} for dataset, rows in rows_by_dataset.items(): @@ -238,8 +250,8 @@ def sesoi_lines( line |= { "sesoi": SESOI, "readings": readings, - "sesoi_reading": SMALL_EFFECT - if main == "cannot exclude" + "sesoi_reading": main + if main in (SMALL_REAL, CANNOT_TELL) else f"{main} {SESOI}", } out.setdefault(dataset, []).append(line) diff --git a/experiments/35-full-rag-benchmark-2026-11-01/verdicts35.py b/experiments/35-full-rag-benchmark-2026-11-01/verdicts35.py index 7ca41ac8..13187bbe 100644 --- a/experiments/35-full-rag-benchmark-2026-11-01/verdicts35.py +++ b/experiments/35-full-rag-benchmark-2026-11-01/verdicts35.py @@ -27,10 +27,19 @@ def _both(counted: Mapping[str, Mapping[int, int]], rows: Sequence[int]) -> dict "holds": bool(holding), "rows": holding, "sign": signs.pop() if len(signs) == 1 else 0, + "row_signs": {r: fb[r] for r in holding}, "dataset_dependent": [r for r in rows if fb.get(r, 0) * fs.get(r, 0) < 0], } +def row_sign(held: Mapping[str, Any], row: int) -> int: + """Return the sign of a row inside a ``_both`` verdict: its own sign, 0 if it does not hold. + + A verdict without ``row_signs`` (the same-sign case, built by hand) falls back to ``sign``. + """ + return held.get("row_signs", {}).get(row, held["sign"]) if row in held["rows"] else 0 + + def verdicts(counted: Mapping[str, Mapping[int, int]]) -> dict[str, Any]: """Apply the per-hypothesis rules of section 7. diff --git a/tests/test_clean_base_tripwire.py b/tests/test_clean_base_tripwire.py index f636a167..23c00a64 100644 --- a/tests/test_clean_base_tripwire.py +++ b/tests/test_clean_base_tripwire.py @@ -568,7 +568,10 @@ # 9 in test_experiment35_hosted_usage, 2 in test_experiment35_run_arms, 1 in # test_experiment35_claimstage and 1 in test_experiment35_parallel_answers. # +1 (2026-11-28, freeze-check finding, by test-ID diff): 1 in test_experiment35_factorial. -_BASE_EXECUTED = 14512 +# +39 (2026-11-28, Exp 35 audit defects 1 to 7, by test-ID diff against v3 ddd3663a): 23 in +# test_experiment35_report_tables, 7 in _factorial, 3 in _parallel_answers, 2 in +# _refusal_report, 2 in _closedbook_oracle, 1 in _claimstage, 1 in _join_scores. None removed. +_BASE_EXECUTED = 14551 # 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 91d348f0..2b376471 100644 --- a/tests/test_experiment35_claimstage.py +++ b/tests/test_experiment35_claimstage.py @@ -17,6 +17,7 @@ claimstage35 = load("claimstage35") claimkinds35 = load("claimkinds35") +kindgate35 = load("kindgate35") outputs35 = load("outputs35") stages35 = load("stages35") @@ -158,6 +159,27 @@ async def failing(messages): assert (ctx.run_dir / ".done-claimkinds.json").exists() +def test_a_closed_row_carries_the_classifier_version_and_passes_the_kind_gate(tmp_path) -> None: + # Section 12: an unclassified claim stays in the denominator; a row without a version + # would make every gate consumer refuse the whole run folder. + async def failing(messages): + if "Fact one" in messages[-1]["content"] and "q1" in messages[-1]["content"]: + raise RuntimeError("boom") + return _reply() + + for attempt in range(3): + ctx = _ctx(tmp_path, failing, resume=attempt > 0) + try: + _run(ctx) + except claimstage35.StageIncomplete: + pass + rows = _rows(ctx) + assert rows[0]["missing"] is True and rows[0]["kind"] is None + assert rows[0]["version"] == "v1" + kinds = kindgate35.saved_kinds(ctx.run_dir, "v1") + assert kinds[(claimkinds35.claim_key("q1", "Fact one."), False)] is None + + def test_an_unreadable_reply_is_saved_as_unreadable(tmp_path) -> None: async def classifier(messages): return _reply("I am not sure") diff --git a/tests/test_experiment35_closedbook_oracle.py b/tests/test_experiment35_closedbook_oracle.py index 15fd0b88..615c3db1 100644 --- a/tests/test_experiment35_closedbook_oracle.py +++ b/tests/test_experiment35_closedbook_oracle.py @@ -21,7 +21,7 @@ stage_ctx, ) -from omrs.core.answer.stages import prepare_evidence +from omrs.core.answer.stages import EMPTY_REPLY_ERROR, prepare_evidence closedbook35 = load("closedbook35") datasets35 = load("datasets35") @@ -225,3 +225,53 @@ def test_each_closed_book_prompt_writes_its_own_trace(tmp_path: Path, asked: lis for kind in ("own", "rag"): folder = ctx.layout.run_dir("bioasq", f"closedbook-{kind}", SETUP, 1) assert [r["question_id"] for r in _lines(folder / "traces.jsonl")] == ["q0", "q1", "q2"] + + +class ScriptedEngine(Engine): + """Stub engine whose ``answer`` returns the next scripted result, then the normal reply.""" + + def __init__(self, script: list[dict[str, Any]]) -> None: + super().__init__() + self.script = list(script) + + async def answer(self, text: str, **kwargs: Any) -> dict[str, Any]: + if self.script: + self.answers.append(list(kwargs["rows"])) + return self.script.pop(0) + return await super().answer(text, **kwargs) + + +def _oracle_ctx(tmp_path: Path, prepared: tuple[Path, Path], engine: Engine, **kw: Any) -> Any: + root, passages = prepared + return _selected( + tmp_path, "oracle", SETUP, kind="oracle", engine=engine, args={"passages_dir": passages}, + questions=datasets35.load_questions("bioasq", root)[:1], **kw, + ) # fmt: skip + + +def test_an_oracle_empty_reply_error_is_a_final_empty_answer( + tmp_path: Path, prepared: tuple[Path, Path] +) -> None: + """Section 12: an empty reply is a returned empty answer, saved, never resent.""" + reply = {"status": "error", "answer": None, "error": EMPTY_REPLY_ERROR} + engine = ScriptedEngine([reply]) + ctx = _oracle_ctx(tmp_path, prepared, engine) + assert asyncio.run(oracle35.oracle_stage(ctx)) == 0 + (row,) = _lines(ctx.run_dir / "answer.jsonl") + assert row["answer"] == "" and not row.get("missing") + assert len(engine.answers) == 1 + assert not (ctx.run_dir / "answer.errors.jsonl").exists() + marker = json.loads((ctx.run_dir / ".done-answer.json").read_text(encoding="utf-8")) + assert marker["resent_calls"] == 0 and marker["closed_missing"] == [] + + +def test_a_billed_failed_oracle_attempt_keeps_its_usage_in_the_error_line( + tmp_path: Path, prepared: tuple[Path, Path] +) -> None: + usage = {"input_tokens": 40, "output_tokens": 5, "cost_usd": 0.25} + engine = ScriptedEngine([{"status": "error", "answer": None, "error": "bad", "usage": usage}]) + ctx = _oracle_ctx(tmp_path, prepared, engine) + with pytest.raises(stages35.StageIncomplete): + asyncio.run(oracle35.oracle_stage(ctx)) + (line,) = _lines(ctx.run_dir / "answer.errors.jsonl") + assert line["usage"] == usage diff --git a/tests/test_experiment35_factorial.py b/tests/test_experiment35_factorial.py index e276b6b4..ec88e55d 100644 --- a/tests/test_experiment35_factorial.py +++ b/tests/test_experiment35_factorial.py @@ -321,6 +321,7 @@ def test_two_sided_rule_needs_same_row_same_sign() -> None: "holds": True, "rows": [13], "sign": -1, + "row_signs": {13: -1}, "dataset_dependent": [], } assert same["H8a"]["correctness"]["holds"] is False @@ -375,6 +376,74 @@ def test_h8b_sensitivity_agrees_only_with_the_h8b_sign() -> None: assert claims["correctness"].startswith("chunk size changes correctness") +def _h8b_faithfulness_fixture(estimates: tuple[int, int]) -> tuple[list, dict]: + """Return answers and tables whose rows 16 and 17 have the given estimate signs.""" + fb, fs = select35.CORE[0], select35.CORE[1] + t20k = {c: select35.Setup("4b", c, "4b", "on", True).name for c in (512, 1024, 2048)} + level = {512: 0.0, 1024: 0.1 * estimates[0], 2048: 0.1 * (estimates[0] + estimates[1])} + cells = {name: {"q0": level[c], "q1": level[c]} for c, name in t20k.items()} + answers = [ + {"dataset": d, "setup": name, "qid": q, "run": 1, "cut_tokens": 20_000} + for d in (fb, fs) + for name in t20k.values() + for q in ("q0", "q1") + ] + tables = { + factorial35.FAITH: {fb: cells, fs: cells}, + factorial35.CORRECT: {fb: cells, fs: cells}, + "questions": {fb: ["q0", "q1"], fs: ["q0", "q1"]}, + } + return answers, tables + + +@pytest.mark.parametrize( + ("held", "estimates", "agrees", "claim"), + [ + # Same sign on both rows: the old behaviour, pinned. + ((1, 1), (1, 1), (True, True), True), + ((-1, -1), (-1, -1), (True, True), True), + # Opposite signs (an inverted U or a U at 1,024): each row is judged on its own sign. + ((1, -1), (1, -1), (True, True), True), + ((-1, 1), (-1, 1), (True, True), True), + # One row agrees, one reverses: the claim stands on the agreeing row (any-row rule). + ((1, -1), (1, 1), (True, False), True), + # Both rows reverse: disagreement. + ((1, -1), (-1, 1), (False, False), False), + ], +) +def test_h8b_rows_are_judged_against_their_own_sign( + held: tuple[int, int], + estimates: tuple[int, int], + agrees: tuple[bool, bool], + claim: bool, +) -> None: + """Section 7: agreement is per row against that row's own H8b sign.""" + fb, fs = select35.CORE[0], select35.CORE[1] + counted = {d: {16: held[0], 17: held[1]} for d in (fb, fs)} + hypotheses = factorial35.verdicts(counted) + assert hypotheses["H8b"]["faithfulness"]["row_signs"] == {16: held[0], 17: held[1]} + answers, tables = _h8b_faithfulness_fixture(estimates) + result = factorial35._h8b_sensitivity(answers, tables, hypotheses) + assert result["agrees"] == {16: agrees[0], 17: agrees[1], 18: False, 19: False} + assert result["sign"] == { + 16: held[0] if agrees[0] else 0, + 17: held[1] if agrees[1] else 0, + 18: 0, + 19: 0, + } + claims = factorial35._claims(hypotheses, result) + registered = "chunk size changes faithfulness at a fixed pre-assembly evidence budget" + assert claims["faithfulness"] == (registered if claim else None) + + +def test_opposite_signs_on_both_rows_keep_each_row_sign_in_the_verdict() -> None: + fb, fs = select35.CORE[0], select35.CORE[1] + got = factorial35.verdicts(_counted({fb: {16: 1, 17: -1}, fs: {16: 1, 17: -1}})) + h8b = got["H8b"]["faithfulness"] + assert h8b["holds"] is True and h8b["rows"] == [16, 17] and h8b["sign"] == 0 + assert h8b["row_signs"] == {16: 1, 17: -1} and h8b["dataset_dependent"] == [] + + def test_h6_financebench_sensitivity_table(planted: dict[str, Any]) -> None: table = planted["h6_financebench_sensitivity"] assert [r["row"] for r in table] == [9, 10] diff --git a/tests/test_experiment35_join_scores.py b/tests/test_experiment35_join_scores.py index 0dc3fad7..29f7c9a1 100644 --- a/tests/test_experiment35_join_scores.py +++ b/tests/test_experiment35_join_scores.py @@ -120,6 +120,18 @@ def test_an_empty_answer_scores_correctness_zero_and_is_not_unjudged(built) -> N assert scores["q1"][CORRECT] == 0.0 and scores["q1"]["unjudged"] == [] +def test_an_empty_answer_with_a_ragas_nan_is_not_flagged_not_defined(built) -> None: + # Section 12: the Ragas score of an empty answer is not used, NaN included. + out, _, _ = built + folder = _folder(out) + _edit(folder / "answer.jsonl", "q1", answer="") + metric = {"score": None, "not_defined": "score is NaN"} + _edit(folder / "ragas.jsonl", "q1", metrics={CORRECT: metric}) + scores = _scores(folder) + assert scores["q1"][CORRECT] == 0.0 + assert scores["q1"]["unjudged"] == [] and scores["q1"]["not_defined"] == [] + + def test_an_unparseable_verdict_counts_not_supported_and_is_counted(built) -> None: out, _, _ = built folder = _folder(out) diff --git a/tests/test_experiment35_parallel_answers.py b/tests/test_experiment35_parallel_answers.py index 30beeb06..c00f4df4 100644 --- a/tests/test_experiment35_parallel_answers.py +++ b/tests/test_experiment35_parallel_answers.py @@ -275,7 +275,8 @@ def test_an_error_result_is_resent_and_closes_missing_after_three(tmp_path: Path assert rows[2] == {"qid": "q2", "missing": True, "error": "Generation failed: timeout"} marker = json.loads((ctx.run_dir / ".done-answer.json").read_text(encoding="utf-8")) assert marker["resent_calls"] == 2 and marker["closed_missing"] == ["q2"] - assert [r["qid"] for r in _lines(ctx.run_dir / "retrieval.jsonl")] == ["q0", "q1", "q3"] + # Search worked for q2: its saved list stays (section 12; G1 marks only failed searches). + assert [r["qid"] for r in _lines(ctx.run_dir / "retrieval.jsonl")] == ["q0", "q1", "q2", "q3"] @pytest.mark.parametrize("step", ["refusal", "empty"]) @@ -363,3 +364,69 @@ def test_a_billed_failed_attempt_keeps_its_usage_in_the_error_line(tmp_path: Pat {"input_tokens": 40, "output_tokens": 5, "cost_usd": 0.25}, None, # no usage reported: the line carries none ] + + +# --- a closed-missing answer keeps its search list; a failed search keeps none (section 12, 15) --- + +determinism35 = load("determinism35") + + +def _g1(ctx: Any, engine: Engine) -> int: + """Run G1 on *ctx*'s answer run; the search stage's single run saved the stub's lists.""" + qids = [q.qid for q in ctx.questions] + ranked = [{"chunk_id": r["chunk_id"], "tokens": 1} for r in engine.search("x")] + search = ctx.layout.run_dir(ctx.dataset, "search", determinism35.search_setup(ctx.setup), 1) + search.mkdir(parents=True, exist_ok=True) + (search / "search.jsonl").write_text( + "".join(json.dumps({"qid": q, "chunks": ranked}) + "\n" for q in qids), encoding="utf-8" + ) + return asyncio.run(determinism35.determinism_stage(ctx)) + + +def test_a_closed_missing_answer_keeps_its_search_list_and_passes_g1(tmp_path: Path) -> None: + # Each run sends q2 once: two runs stop after one error, the third closes it missing. + engine = Engine(script={"question 2?": ["error", "error", "error"]}) + for n in range(2): + with pytest.raises(stages35.StageIncomplete): + _run(_ctx(tmp_path, engine, resume=n > 0)) + ctx = _ctx(tmp_path, engine, resume=True) + assert _run(ctx) == 0 + rows = _lines(ctx.run_dir / "answer.jsonl") + assert rows[2] == {"qid": "q2", "missing": True, "error": "Generation failed: timeout"} + kept = _lines(ctx.run_dir / "retrieval.jsonl") + assert [r["qid"] for r in kept] == ["q0", "q1", "q2", "q3"] + assert [c["chunk_id"] for c in kept[2]["chunks"]] == [f"ch{i}" for i in range(100)] + assert _g1(ctx, engine) == 0 + + +def test_a_stop_after_the_third_error_still_keeps_the_search_list(tmp_path: Path) -> None: + engine = Engine(script={"question 2?": ["error", "error"]}) + for n in range(2): + with pytest.raises(stages35.StageIncomplete): + _run(_ctx(tmp_path, engine, resume=n > 0)) + ctx = _ctx(tmp_path, engine, resume=True) + # The third error line is saved, then the run stops before the missing row is written. + errors = ctx.run_dir / "answer.errors.jsonl" + with errors.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"id": "q2", "error": "Generation failed: timeout"}) + "\n") + engine.searches.clear() + assert _run(ctx) == 0 + assert "question 2?" not in [t for t, _ in engine.searches] # closed with no new search + assert [r["qid"] for r in _lines(ctx.run_dir / "retrieval.jsonl")] == ["q0", "q1", "q2", "q3"] + assert _g1(ctx, engine) == 0 + + +def test_a_search_that_failed_three_times_keeps_no_list_and_fails_g1(tmp_path: Path) -> None: + engine = Engine() + engine.fail_search.add("question 2?") + for n in range(3): + ctx = _ctx(tmp_path, engine, resume=n > 0) + if n < 2: + with pytest.raises(stages35.StageIncomplete): + _run(ctx) + assert _run(ctx) == 0 + assert _lines(ctx.run_dir / "answer.jsonl")[2]["missing"] is True + assert [r["qid"] for r in _lines(ctx.run_dir / "retrieval.jsonl")] == ["q0", "q1", "q3"] + assert _g1(ctx, engine) == determinism35.EXIT_MISMATCH + report = json.loads((ctx.run_dir / "determinism.json").read_text(encoding="utf-8")) + assert [i["question_id"] for i in report["lists"]["incomplete"]] == ["q2"] diff --git a/tests/test_experiment35_refusal_report.py b/tests/test_experiment35_refusal_report.py index 442b3e88..c6a9869a 100644 --- a/tests/test_experiment35_refusal_report.py +++ b/tests/test_experiment35_refusal_report.py @@ -13,8 +13,10 @@ from __future__ import annotations +import asyncio import json from pathlib import Path +from types import SimpleNamespace from typing import Any import pytest @@ -25,6 +27,8 @@ report = load("refusalreport35") bootstrap35 = load("bootstrap35") claimkinds35 = load("claimkinds35") +claimstage35 = load("claimstage35") +outputs35 = load("outputs35") TEXT = { "F1": "Alpha is beta", @@ -168,6 +172,68 @@ def test_counts_claim_texts_with_different_kinds_in_different_runs(tmp_path: Pat assert _run(tmp_path)["kind_disagreements"] == {"bioasq": 1} # F2: factual and mixed +def _key(qid: str, claim: str) -> str: + texts = claimkinds35.answer_claims(answer_row(qid, [TEXT[claim]])) + return claimkinds35.claim_key(qid, texts[0]) + + +def test_an_uncited_segment_does_not_overwrite_the_kind_of_a_cited_claim(tmp_path: Path) -> None: + out = _build(tmp_path) + folder = out / "bioasq" / "answer" / S1 / "run1" + # The uncited row comes after the cited one, as the claim-kinds stage writes them. + extra = {"claim_key": _key("q1", "F1"), "qid": "q1", "index": 0, "uncited": True} + with (folder / "claim-kinds.jsonl").open("a") as handle: + handle.write(json.dumps({**extra, "kind": "refusal", "version": "v1"}) + "\n") + claims = report._load_run(folder, "v1")["q1"].claims + assert [c.kind for c in claims] == ["factual", "refusal"] + report.write_report(out, gate_path=tmp_path / "gate.json", n_boot=200) + r = json.loads((out / "refusals.json").read_text()) + # Same numbers as test_primary_faithfulness_uses_factual_and_mixed_claims_with_complete_cases. + assert _cell(r, "primary", "chat", S1)["mean"] == pytest.approx(0.75) + + +def test_a_claim_the_stage_closed_unclassified_stays_in_the_report(tmp_path: Path) -> None: + # Drive the real claim-kinds stage on S2 run 2, with q1's classifier call failing 3 times. + out = _build(tmp_path) + folder = out / "bioasq" / "answer" / S2 / "run2" + (folder / "claim-kinds.jsonl").unlink() + (folder / ".done-answer.json").write_text("{}") + + async def failing(messages: list[dict[str, str]]) -> Any: + if "Question: question q1" in messages[-1]["content"]: + raise RuntimeError("boom") + return SimpleNamespace(text="factual") + + async def no_wait(_: float) -> None: + return None + + for attempt in range(3): + args = SimpleNamespace( + classify_concurrency=4, rate_limit_attempts=1, prefreeze=False, smoke=False + ) + ctx = SimpleNamespace( + layout=outputs35.Layout(out), + run_dir=folder, + questions=[SimpleNamespace(qid=q, text=f"question {q}") for q in ("q1", "q2", "q3")], + key={"seed": 1}, + resume=attempt > 0, + args=args, + classifier=failing, + classifier_version="v1", + ) + try: + asyncio.run(claimstage35.claimkinds_stage(ctx, sleep=no_wait)) + except claimstage35.StageIncomplete: + pass + assert outputs35.read_rows(folder / "claim-kinds.jsonl")[0]["missing"] is True + assert [c.kind for c in report._load_run(folder, "v1")["q1"].claims] == [None] + report.write_report(out, gate_path=tmp_path / "gate.json", n_boot=200) + r = json.loads((out / "refusals.json").read_text()) + assert r["unclassified_claims"]["bioasq"][S2] == 1 + # The unclassified claim stays in the primary denominator: S2 run 2 q1 is still judged. + assert _cell(r, "primary", "chat", S2)["n"] == 2 + + # --- primary faithfulness and missing outcomes ----------------------------------------------- diff --git a/tests/test_experiment35_report_tables.py b/tests/test_experiment35_report_tables.py index e11bcee9..422eda63 100644 --- a/tests/test_experiment35_report_tables.py +++ b/tests/test_experiment35_report_tables.py @@ -20,6 +20,11 @@ reporttables35 = load("reporttables35") STEP = {512: 0, 1024: 1, 2048: 2} +# The four readings of Amendment A16 (pre-registration section 10), in its own words. +WITHIN = "within 0.02" # case 1: no meaningful difference +BEYOND = "beyond 0.02" # case 2: a meaningful difference +SMALL_REAL = "a real difference that can be too small to matter" # case 3 +CANNOT_TELL = "the test cannot tell" # case 4 def _write(path: Path, rows: list[dict]) -> None: @@ -116,6 +121,61 @@ def _row(number: int, metric: str, low: float, high: float, **extra: Any) -> dic } +@pytest.mark.parametrize( + ("low", "high", "reading"), + [ + # Case 1: fully inside -0.02 to +0.02. Zero inside or on an endpoint changes nothing. + (-0.01, 0.01, WITHIN), + (0.005, 0.015, WITHIN), + (0.0, 0.01, WITHIN), + (-0.01, 0.0, WITHIN), + # Case 2: fully above +0.02 or fully below -0.02. + (0.03, 0.05, BEYOND), + (-0.05, -0.03, BEYOND), + # Case 3: excludes zero, crosses +0.02 or -0.02. + (0.01, 0.03, SMALL_REAL), + (-0.03, -0.01, SMALL_REAL), + (0.0001, 0.03, SMALL_REAL), + (-0.03, -0.0001, SMALL_REAL), + # Case 4: includes zero, crosses +0.02 or -0.02. + (-0.01, 0.03, CANNOT_TELL), + (-0.03, 0.01, CANNOT_TELL), + (-0.03, 0.03, CANNOT_TELL), + # Boundary rule: the interval is closed. An endpoint of 0.0 includes zero ... + (0.0, 0.03, CANNOT_TELL), + (-0.03, 0.0, CANNOT_TELL), + # ... and an endpoint of +-0.02 crosses it (not fully inside, not fully beyond). + (0.005, 0.02, SMALL_REAL), + (0.02, 0.05, SMALL_REAL), + (-0.02, -0.005, SMALL_REAL), + (-0.05, -0.02, SMALL_REAL), + (0.0, 0.02, CANNOT_TELL), + (-0.02, 0.0, CANNOT_TELL), + (-0.02, 0.01, CANNOT_TELL), + ], +) +def test_sesoi_reading_follows_the_four_cases_of_amendment_a16( + low: float, high: float, reading: str +) -> None: + rows = {"financebench": [_row(1, "ndcg_at_10", low, high)]} + line = reporttables35.sesoi_lines(rows)["financebench"][0] + assert line["sesoi"] == 0.02 + assert line["sesoi_reading"] == reading + + +def test_sesoi_readings_map_applies_the_four_cases_to_every_sesoi() -> None: + # Section 10 (6): every interval is also read against 0.01 and 0.05, in the same four cases. + rows = { + "financebench": [ + _row(1, "ndcg_at_10", 0.03, 0.08), # excludes zero + _row(2, "ndcg_at_10", -0.03, 0.04), # includes zero + ] + } + lines = {r["row"]: r for r in reporttables35.sesoi_lines(rows)["financebench"]} + assert lines[1]["readings"] == {"0.01": "beyond", "0.02": "beyond", "0.05": SMALL_REAL} + assert lines[2]["readings"] == {"0.01": CANNOT_TELL, "0.02": CANNOT_TELL, "0.05": "within"} + + def test_sesoi_lines_per_row_carry_no_mde_line() -> None: # A10 removed the MDE table (2026-11-26): the lines hold the SESOI reading and marks only. rows = { @@ -129,9 +189,9 @@ def test_sesoi_lines_per_row_carry_no_mde_line() -> None: } lines = {r["row"]: r for r in reporttables35.sesoi_lines(rows)["freshstack"]} assert lines[1]["sesoi"] == 0.02 and lines[1]["sesoi_reading"] == "beyond 0.02" - assert lines[1]["readings"] == {"0.01": "beyond", "0.02": "beyond", "0.05": "cannot exclude"} + assert lines[1]["readings"] == {"0.01": "beyond", "0.02": "beyond", "0.05": SMALL_REAL} assert lines[2]["sesoi_reading"] == "within 0.02" - assert lines[3]["sesoi_reading"] == "cannot rule out a small effect" + assert lines[3]["sesoi_reading"] == SMALL_REAL # [0.01, 0.05]: excludes zero, crosses 0.02 assert lines[3]["status"] == "not testable" assert lines[12]["sesoi"] is None and lines[12]["readings"] is None assert lines[13]["status"] == "dropped"