From 04ef31e4c15663995d492839145c7b53c451754b Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 25 Nov 2026 21:37:36 -0800 Subject: [PATCH 01/40] feat(eval): expected_outcome: ask, graded by its own rubric A question that expects the assistant to ask back (a missing version, target, or meaning) is marked `expected_outcome: ask`. The answer rubric scores such a reply as a poor answer, so these records are judged by an ask rubric (clarifying question, targets the ambiguity, avoids guessing) with its own prompt hash, ASK_JUDGE_PROMPT_SHA256. JUDGE_PROMPT_SHA256 is unchanged, so answer-mode results keep their stamp. - The value is parsed in dokimi.records (default answer) and stored on answers records (only when ask) and on every eval row. - The rubric judges (Judge, the panel, arms --judge, judge validity) route on it. - Paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, RAGAS) refuse an ask record that has an answer to judge, naming the question id, before any judge call (the PR #81 pattern). - questions.v2 and eval.v1 declare the field; questions.v2 is not bumped. Signed-off-by: Nikolay Petrov --- ...25_130000_napetrov_expected-outcome-ask.md | 14 + dokimi/docs/methodology.md | 14 + dokimi/dokimi/eval/answerer.py | 3 + dokimi/dokimi/eval/arm_record.py | 2 + dokimi/dokimi/eval/arm_runner.py | 3 + dokimi/dokimi/eval/ask_outcome.py | 134 +++++++ dokimi/dokimi/eval/checklist.py | 3 + dokimi/dokimi/eval/cross_judge.py | 9 +- dokimi/dokimi/eval/degrade.py | 2 + dokimi/dokimi/eval/judge.py | 59 +++ dokimi/dokimi/eval/pairwise.py | 2 + dokimi/dokimi/eval/panel.py | 58 ++- dokimi/dokimi/eval/ragas_eval.py | 3 + dokimi/dokimi/records.py | 48 +++ dokimi/dokimi/schemas/eval.v1.json | 5 + dokimi/dokimi/schemas/questions.v2.json | 5 + dokimi/tests/test_expected_outcome.py | 351 ++++++++++++++++++ dokimi/tests/test_record_readers.py | 2 +- 18 files changed, 700 insertions(+), 17 deletions(-) create mode 100644 dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md create mode 100644 dokimi/dokimi/eval/ask_outcome.py create mode 100644 dokimi/tests/test_expected_outcome.py diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md new file mode 100644 index 0000000000..9150729fcd --- /dev/null +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -0,0 +1,14 @@ + + +### Added + +- **`expected_outcome: ask`: a question that expects the assistant to ask back is judged by its own rubric.** + A question record may carry `expected_outcome` (`answer`, the default, or `ask`). An `ask` record is graded + by the ask rubric (clarifying question, targets the ambiguity, avoids guessing) with its own prompt hash + (`ASK_JUDGE_PROMPT_SHA256`); `JUDGE_PROMPT_SHA256` is unchanged. The value is stored on answers records + and on every eval row. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, + RAGAS) refuse an `ask` record that has an answer to judge, before any judge call. See + `docs/methodology.md` (questions that expect an ask). diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index 40a6a21174..e6fb72bab1 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -105,6 +105,8 @@ Question records preserve source fields such as `source_type`, `question_source` Each question may carry `version` (the author's revision, a non-empty string or an integer; a float such as `1.0` is malformed) and `provenance` (`source`, `reviewed_by`, `status` as `candidate`, `validated` or `frozen`). Every key is optional and an absent one is unknown. `eval questions generate` writes `source` as `generated:dokimi-questions-persona@`, and the pipeline's chunk-grounded questions carry `generated:dokimi-questions-chunk@`; a hand-written set is `hand-written` by convention. Both shapes are checked when the set is read: a malformed one is a warning, never a refusal, so files written before the key existed still load. +`expected_outcome` is `answer` (the default, absent when unset) or `ask`, which says a correct reply asks the user back instead of answering; see [Questions that expect an ask](#questions-that-expect-an-ask). + A question set is a JSON object with a `questions` list. The framework writes it as `questions.v2` (`dokimi/schemas/questions.v2.json`, where every field is documented); `questions.v1` files are still read. - **v2 (written):** each record needs `id` and a non-empty `question`. A v2 record may not also carry `text`, so no record holds two question texts that readers could disagree on. @@ -202,6 +204,18 @@ RAGAS meta-evaluation (`eval score ragas`, or `answers generate --ragas`) can be - `context_precision`: whether the retrieved documents were useful in reaching the `with_docs` answer, with the useful ones ranked first. It is ragas's reference-free `LLMContextPrecisionWithoutReference`: the judge compares the documents with the answer, not with a reference answer. - `context_recall`, which the commands leave out and `RagasEvaluator(metrics=[...])` computes on request: how much of the question's `ground_truth_chunk` the retrieved documents cover; answers without one get no `context_recall` score. +### Questions that expect an ask + +A question with `expected_outcome: ask` is one a good assistant answers by asking back, because a detail the answer depends on is missing: a version, a target, or which of two meanings is meant. The answer rubric scores such a reply as a poor answer, so these records are judged by a separate ask rubric: + +- **Clarifying question**: does the reply ask the user for information before it answers. +- **Targets the ambiguity** (weight 2): is the question the one that resolves the missing detail. +- **Avoids guessing** (weight 2): does the reply leave the detail open, rather than pick a value and do the work on it. + +The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_PROMPT_SHA256` does not change, so answer-mode results keep their stamp. A judged ask row carries `expected_outcome: ask` and the ask rubric's hash; the rubric judges (the single judge, the panel, `arms run --judge`, and judge validity) route on the value. + +The paths that compare answers with each other or with expected points (pairwise, checklist, cross-judge, degradation pairs, RAGAS) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. + ## Trust And Reproducibility Every serious run should answer "Can we trust this run?" before interpreting deltas. The trust gate checks: diff --git a/dokimi/dokimi/eval/answerer.py b/dokimi/dokimi/eval/answerer.py index 0e72b66f39..2bb9922499 100644 --- a/dokimi/dokimi/eval/answerer.py +++ b/dokimi/dokimi/eval/answerer.py @@ -15,6 +15,7 @@ from dokimi.utils import question_id from dokimi.artifacts import save_artifact +from dokimi.eval.ask_outcome import outcome_fields from dokimi.defaults import ( ANSWERING_METHOD_VERSION, DEFAULT_ANSWER_MODEL, @@ -193,6 +194,7 @@ def _process(idx: int, q: Dict) -> None: "without_docs": None, **done_conditions, **_ground_truth_fields(q), # a kept context answer is graded with its question's rubric + **outcome_fields(q), } elapsed = time.time() - t0 with lock: @@ -310,6 +312,7 @@ def _generate_answer_pair( "without_docs": without_docs_answer, } result.update(_ground_truth_fields(question)) + result.update(outcome_fields(question)) # an ask question is judged by the ask rubric return result def _retrieve_docs( diff --git a/dokimi/dokimi/eval/arm_record.py b/dokimi/dokimi/eval/arm_record.py index e674131c4f..b41e93d47c 100644 --- a/dokimi/dokimi/eval/arm_record.py +++ b/dokimi/dokimi/eval/arm_record.py @@ -5,6 +5,7 @@ from typing import Any, Dict +from dokimi.eval.ask_outcome import outcome_fields from dokimi.eval.question_text import ground_truth_from_topics @@ -21,6 +22,7 @@ def question_record( "persona": q.get("persona"), "arms": arms, } + rec.update(outcome_fields(q)) if turns is not None: rec["session_turns"] = len(turns) # Selection label: present-and-None means "no skill should load", which is diff --git a/dokimi/dokimi/eval/arm_runner.py b/dokimi/dokimi/eval/arm_runner.py index 8b6b363296..17802a7073 100644 --- a/dokimi/dokimi/eval/arm_runner.py +++ b/dokimi/dokimi/eval/arm_runner.py @@ -30,6 +30,7 @@ summarize_agentic_usage, summarize_skill_selection, unjudged_cell, ) from dokimi.eval.cells import Cell +from dokimi.eval.ask_outcome import ASK from dokimi.eval.question_text import question_text_of, require_question_texts from dokimi.eval.arm_record import question_record from dokimi.eval.arm_stop import Halted, RunStopped, halt_if_stopped, mark_not_asked, stop_question @@ -650,6 +651,7 @@ def _score(rec: Record) -> Dict[str, Any]: answer=answer.text, context=context, ground_truth=gt, + **({"expected_outcome": ASK} if rec.expected_outcome == ASK else {}), ) except Exception as exc: logger.exception("Judging arm %s failed", arm_name) @@ -671,6 +673,7 @@ def _score(rec: Record) -> Dict[str, Any]: "difficulty": rec.difficulty, "scores": scores, "deltas_vs_baseline": deltas, + "expected_outcome": rec.expected_outcome, } if delta_errors: row["delta_errors"] = delta_errors diff --git a/dokimi/dokimi/eval/ask_outcome.py b/dokimi/dokimi/eval/ask_outcome.py new file mode 100644 index 0000000000..6694be7789 --- /dev/null +++ b/dokimi/dokimi/eval/ask_outcome.py @@ -0,0 +1,134 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""``expected_outcome``: whether a question should be answered or asked back. + +A question with ``expected_outcome: ask`` is one the assistant should not answer +directly, because a detail the answer depends on is missing (a version, a target, +which of two meanings). The answer rubric scores such a reply as a poor answer, +so a correct clarifying question would score low. Those records are graded by +:data:`ASK_JUDGE_PROMPT` instead, which has its own identity +(:data:`ASK_JUDGE_PROMPT_SHA256`) and is stamped only on the records it judged. + +Absent means ``answer``, so every existing question set and artifact keeps its +meaning. The judge paths that have an ask rubric route on this value; the paths +that compare answers to each other or to expected points refuse such a record +before any judge call (:func:`require_judgeable_outcome`), rather than grading it +on the answer rubric. +""" + +from __future__ import annotations + +import hashlib +import re +from collections.abc import Iterable, Mapping +from typing import Any + +from dokimi.records import ANSWER, ASK, AskOutcomeError, outcome_of +from dokimi.records import record as as_record + +__all__ = ["ANSWER", "ASK", "AskOutcomeError", "outcome_of", "outcome_fields", "require_judgeable_outcome", + "ASK_DIMS", "ASK_WEIGHTS", "ASK_JUDGE_PROMPT", "ASK_JUDGE_PROMPT_SHA256", + "ask_weighted_aggregate", "render_ask_prompt"] + + +def outcome_fields(question: Mapping[str, Any]) -> dict[str, str]: + """What an answers record carries about its question's outcome. + + Only ``ask`` is written: an answer-mode record stays byte-identical to the + records written before this field existed, and a reader defaults to ``answer``. + """ + return {"expected_outcome": ASK} if outcome_of(question) == ASK else {} + + +def _has_answer_to_judge(record: Mapping[str, Any]) -> bool: + return any(a.text for a in as_record(record).answers.values()) + + +def require_judgeable_outcome(records: Iterable[Mapping[str, Any]], path: str) -> None: + """Refuse an ask record on a path that has no ask rubric, before any judge call. + + Only a record with an answer to judge is refused; one the path would skip anyway + is not. ``path`` names the judge in the message. + """ + for i, record in enumerate(records): + if outcome_of(record, i) == ASK and _has_answer_to_judge(record): + qid = record.get("question_id") + where = f"question {qid!r}" if qid is not None else f"record #{i}" + raise AskOutcomeError( + f"{where} expects an ask (expected_outcome: ask); {path} grades answers against " + "each other or expected points and has no rubric for a clarifying question. " + "Drop the record or judge it with the rubric judge (eval judge, arms run --judge)" + ) + + +#: The ask rubric's dimensions, in output order. Each is 0-100 like the answer rubric's. +ASK_DIMS = ("clarifying_question", "targets_ambiguity", "avoids_guessing") +#: Aggregate weights. Targeting the ambiguity and not guessing it are what separate a +#: useful question from a bare "could you clarify?", so they carry twice the weight. +ASK_WEIGHTS = {"clarifying_question": 1.0, "targets_ambiguity": 2.0, "avoids_guessing": 2.0} + +ASK_JUDGE_PROMPT = """You are evaluating a reply to a request that is missing a detail it depends on. + +The assistant was expected to ASK for that detail, not to answer or do the work. A good reply asks the one question that resolves the ambiguity, and does not choose the missing detail on the user's behalf. + +**Request:** __QUESTION__ + +**Reply:** __ANSWER__ + +**Context (retrieved from docs, if available):** +__CONTEXT__ + +**Evaluation criteria:** + +1. **Clarifying question (0-100):** Does the reply ask the user for information before it answers? + - 100: it asks at least one direct question and does no work beyond asking + - 50: it asks, but also does part of the work on a value it picked itself + - 0: it answers or does the work without asking anything +2. **Targets the ambiguity (0-100):** Is the question the right one? It should ask for the detail the request actually depends on (for example the version, the platform, or which of several meanings is intended), not something the request already states or something unrelated. + - 100: it asks for exactly the missing detail + - 50: it asks about something related, but not the detail the answer turns on + - 0: it asks about something unrelated, or about something the request already states +3. **Avoids guessing (0-100):** Does the reply leave the missing detail open? + - 100: it assumes nothing beyond what the request states + - 50: it names an assumption and goes on to do the work on it + - 0: it silently picks a value for the missing detail and produces the full result + +**Instructions:** +- Replace every N with an integer 0-100, picked from the levels above +- Score each dimension independently; do not round them toward each other +- Python computes the aggregate — do NOT compute it yourself, set aggregate=0 +- Provide brief reasoning for each score + +**Output format (JSON only, no other text):** +{ + "clarifying_question": N, + "targets_ambiguity": N, + "avoids_guessing": N, + "aggregate": 0, + "reasoning": { + "clarifying_question": "", + "targets_ambiguity": "", + "avoids_guessing": "" + } +}""" + +#: Identity of the ask rubric. Separate from ``JUDGE_PROMPT_SHA256``: adding it must not +#: change the stamp on any answer-mode artifact. +ASK_JUDGE_PROMPT_SHA256 = "sha256:" + hashlib.sha256(ASK_JUDGE_PROMPT.encode("utf-8")).hexdigest() + + +def ask_weighted_aggregate(scores: Mapping[str, float]) -> float: + """The ask rubric's aggregate: a weighted mean, computed in Python, never by the judge.""" + total = sum(ASK_WEIGHTS.values()) + return round(sum(float(scores[d]) * w for d, w in ASK_WEIGHTS.items()) / total, 1) + + +_PLACEHOLDER = re.compile(r"__([A-Z_]+)__") + + +def render_ask_prompt(question: str, answer: str, context: str, library_name: str) -> str: + """The ask rubric with its placeholders filled, in one pass: text put in for one + placeholder is never scanned for another, so a reply that names one stays as written.""" + values = {"QUESTION": question, "ANSWER": answer, "CONTEXT": context, "LIBRARY_NAME": library_name} + return _PLACEHOLDER.sub(lambda m: values.get(m.group(1), m.group(0)), ASK_JUDGE_PROMPT) diff --git a/dokimi/dokimi/eval/checklist.py b/dokimi/dokimi/eval/checklist.py index 63aaa561fb..73dc9d1273 100644 --- a/dokimi/dokimi/eval/checklist.py +++ b/dokimi/dokimi/eval/checklist.py @@ -38,6 +38,7 @@ from dokimi.eval.pairwise import standalone_verdict from dokimi.llm import Unparseable from dokimi.judged import judged_reply +from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.question_text import require_question_text from dokimi.records import RecordLike, arm_answers, records as as_records from dokimi.eval.stats import mean_ci @@ -308,6 +309,8 @@ def checklist_jobs( pending = [(arm, a.text) for arm, a in arm_answers(rec).items() if a.text and (arms is None or arm in arms)] # Only a record that would be judged must carry a question; the others keep what they have. + if pending: + require_judgeable_outcome([rec.raw], "checklist") question = require_question_text(rec.raw, i) if pending else rec.question_text if report is not None: report.questions[qid] = question diff --git a/dokimi/dokimi/eval/cross_judge.py b/dokimi/dokimi/eval/cross_judge.py index c1afb3ef13..b2965d038c 100644 --- a/dokimi/dokimi/eval/cross_judge.py +++ b/dokimi/dokimi/eval/cross_judge.py @@ -61,6 +61,7 @@ from dokimi.eval.judge_context import ( JUDGE_CONTEXT_BASELINE, PROTOCOL_WITHHELD, SOURCE_STORED, SOURCE_WITHHELD, JudgeContextStore, ) +from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.question_text import require_question_text from dokimi.records import Answer, Record, RecordError, RecordLike, Run, arm_answers, arm_scores from dokimi.records import record as as_record @@ -358,13 +359,19 @@ def scored_answers( skipped, not refused. """ return [ - (r, arm, a, require_question_text(r.raw, i)) + (r, arm, a, _judged_question(r, i)) for i, r in enumerate(as_records(records, source="answers", kind="answers")) for arm, a in arm_answers(r).items() if a.text and (arms is None or arm in arms) ] +def _judged_question(r: Record, i: int) -> str: + """The question of a record whose answer is about to be judged; refused if it has none, or expects an ask.""" + require_judgeable_outcome([r.raw], "the cross-judge score") + return require_question_text(r.raw, i) + + def score_measure( records: Sequence[RecordLike], scorer: Scorer, *, name: str, library: str, arms: Optional[Sequence[str]] = None, concurrency: int = 1, diff --git a/dokimi/dokimi/eval/degrade.py b/dokimi/dokimi/eval/degrade.py index a445334cd9..6d8f908903 100644 --- a/dokimi/dokimi/eval/degrade.py +++ b/dokimi/dokimi/eval/degrade.py @@ -48,6 +48,7 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Sequence from dokimi.code_spans import LINE_BREAK, replace_code_spans +from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.question_text import require_question_text from dokimi.records import RecordLike, records @@ -653,6 +654,7 @@ def build_pairs( # row that can become a base is checked (not only the drawn bases), so the outcome does not # depend on the seed; a row dropped for missing judge material is never judged. for row in long_answers: + require_judgeable_outcome([row["_record"][0]], "the degradation pairs") if not row["question_text"].strip(): require_question_text(*row["_record"]) bases = long_answers[:n_bases] diff --git a/dokimi/dokimi/eval/judge.py b/dokimi/dokimi/eval/judge.py index 2ee2ec495c..b9bdf59159 100644 --- a/dokimi/dokimi/eval/judge.py +++ b/dokimi/dokimi/eval/judge.py @@ -24,6 +24,10 @@ from dokimi.llm import LANGCHAIN_AVAILABLE from dokimi.eval.diagnoser import diagnose from dokimi.eval.question_text import require_question_texts +from dokimi.eval.ask_outcome import ( + ANSWER, ASK, ASK_DIMS, ASK_JUDGE_PROMPT_SHA256, ASK_WEIGHTS, ask_weighted_aggregate, + render_ask_prompt, +) from dokimi.records import (BASELINE, CONTEXT, NO_RETRIEVAL_SOURCES, Record, RecordLike, is_knowledge_run, knowledge_only, records) from dokimi.defaults import ANSWERING_METHOD_VERSION, DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER @@ -327,6 +331,7 @@ def _process(idx: int, answer: Record) -> None: "with_docs": None, "without_docs": None, "delta": None, + "expected_outcome": answer.expected_outcome, # What retrieval returned does not depend on the judge: the trust # gate's coverage floor must not count this row as unrecorded. "retrieval_hit": answer.retrieval_hit, @@ -377,6 +382,7 @@ def _evaluate_answer_pair( require_question_texts([answer.raw]) question_text = answer.question_text ground_truth = answer.ground_truth # present for chunk-grounded questions + outcome = answer.expected_outcome # an ask question is graded by the ask rubric context_answer = answer.answer(CONTEXT) baseline_answer = answer.answer(BASELINE) @@ -391,6 +397,7 @@ def _evaluate_answer_pair( answer=context_answer.text, context=self._format_context(context_answer.context), ground_truth=ground_truth, + expected_outcome=outcome, ) # Evaluate baseline @@ -402,6 +409,7 @@ def _evaluate_answer_pair( answer=baseline_answer.text, context="(No documentation provided)", ground_truth=ground_truth, + expected_outcome=outcome, ) # Calculate delta @@ -418,6 +426,8 @@ def _evaluate_answer_pair( "with_docs": with_docs_eval, "without_docs": without_docs_eval, "delta": delta, + # Stored on every row, so a reader can count the asks without reading the judge scores. + "expected_outcome": outcome, } # Classify retrieval outcome (why docs helped or didn't). One condition by design only in a declared @@ -494,14 +504,23 @@ def _judge_answer( context: str, ground_truth: Optional[str] = None, draw: int = 0, + expected_outcome: str = ANSWER, ) -> Dict[str, Any]: """Judge a single answer, optionally using a ground-truth doc chunk. ``draw`` selects an independent sample of the same judgement (see :func:`dokimi.llm.llm_call_with_usage`); 0 is the ordinary call. + + ``expected_outcome`` ``ask`` grades the reply with the ask rubric + (:mod:`dokimi.eval.ask_outcome`) instead: that call is stamped with the + ask rubric's hash, and an answer-mode call is not stamped at all, so its + artifacts are the same as before the rubric existed. """ from dokimi.llm import extract_json_object + if expected_outcome == ASK: + return self._judge_ask(library_name, question, answer, context, draw=draw) + grounded = bool(ground_truth) if grounded: @@ -562,6 +581,44 @@ def redrawn() -> None: return scores + def _judge_ask(self, library_name: str, question: str, answer: str, context: str, + *, draw: int = 0) -> Dict[str, Any]: + """Grade a reply to an ``expected_outcome: ask`` question with the ask rubric. + + No ground truth and no figure check: the rubric is about whether the reply asks the right + question, which an excerpt of the answer would not change. + """ + prompt = render_ask_prompt(question, answer, context, library_name) + required = set(ASK_DIMS) + + def parse(raw: str) -> "tuple[Dict[str, Any], float]": + from dokimi.llm import extract_json_object + + scores = extract_json_object(raw) + missing = required - scores.keys() + if missing: + raise ValueError(f"Missing keys in judge response: {missing}") + self._check_scores(scores, ASK_WEIGHTS.keys()) + return scores, ask_weighted_aggregate(scores) + + def send(text: str, *, draw: int, cache_if: Callable[[str], bool]) -> str: + response = self.llm.invoke(text, draw=draw, cache_if=cache_if) + self._accumulate_usage(getattr(response, "usage", None)) + return response.content if hasattr(response, "content") else str(response) + + def redrawn() -> None: + with self._usage_lock: + self._redrawn_judgements += 1 + + (scores, aggregate), _ = judged_reply( + send, prompt, parse, pinned=self.temperature is not None or self.seed is not None, + draw=draw, label="Judge response", reminder=FORMAT_REMINDER, on_redraw=redrawn) + # Python computes the aggregate; the judge's own figure, if any, is replaced. + scores["aggregate"] = aggregate + scores["expected_outcome"] = ASK + scores["judge_prompt_sha256"] = ASK_JUDGE_PROMPT_SHA256 + return scores + def score_answer( self, library_name: str, @@ -570,6 +627,7 @@ def score_answer( context: str = "(No documentation retrieved)", ground_truth: Optional[str] = None, draw: int = 0, + expected_outcome: str = ANSWER, ) -> Dict[str, Any]: """Public single-answer scorer — reused by the treatment-arm runner.""" return self._judge_answer( @@ -579,6 +637,7 @@ def score_answer( context=context, ground_truth=ground_truth, draw=draw, + expected_outcome=expected_outcome, ) @staticmethod diff --git a/dokimi/dokimi/eval/pairwise.py b/dokimi/dokimi/eval/pairwise.py index 5f84ca817f..e8e0626f54 100644 --- a/dokimi/dokimi/eval/pairwise.py +++ b/dokimi/dokimi/eval/pairwise.py @@ -59,6 +59,7 @@ from dokimi.eval.binary_stats import exact_binomial_two_sided from dokimi.llm import ATTEMPTS, Unparseable from dokimi.judged import judged_reply +from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.question_text import require_question_text from dokimi.records import RecordLike, arm_answers, records as as_records @@ -273,6 +274,7 @@ def pairwise_jobs( base = base_answer.text if base_answer is not None else None if not base: continue + require_judgeable_outcome([rec.raw], "pairwise") for arm, a in by_arm.items(): if arm != baseline_arm and a.text and (arms is None or arm in arms): jobs.append((arm, rec.question_id, require_question_text(rec.raw, i), a.text, base)) diff --git a/dokimi/dokimi/eval/panel.py b/dokimi/dokimi/eval/panel.py index eda971ffa6..a901b0ebc6 100644 --- a/dokimi/dokimi/eval/panel.py +++ b/dokimi/dokimi/eval/panel.py @@ -32,6 +32,9 @@ from dokimi.defaults import DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER from dokimi.eval.judge import MAX_GROUND_TRUTH_CHARS, _clip_ground_truth from dokimi.eval.question_text import require_question_texts +from dokimi.eval.ask_outcome import ( + ANSWER, ASK, ASK_DIMS, ASK_JUDGE_PROMPT_SHA256, ask_weighted_aggregate, render_ask_prompt, +) # The panel had no numeric-claims criterion (see `eval/rubric.py`) until it was # measured against the gate's own `wrong_numbers` degradation (Haiku 4.5, 3 # roles, 60 bases): 0.604 -> 0.792 on Sonnet's answers and 0.590 -> 0.795 on @@ -205,6 +208,8 @@ class PanelVerdict: #: Valid votes needed for a verdict (a majority of the panelists); 0 = no rule. quorum: int = 0 grounded: bool = False + #: ``ask`` when the votes were cast with the ask rubric (its dimensions, its hash). + expected_outcome: str = ANSWER @property def valid_votes(self) -> List[JudgeVote]: @@ -305,7 +310,9 @@ def provider(self) -> str: def _build_prompt(self, role: str, question: str, answer: str, library_name: str, context: str, - ground_truth: Optional[str] = None) -> str: + ground_truth: Optional[str] = None, expected_outcome: str = ANSWER) -> str: + if expected_outcome == ASK: # every role asks the same question of the reply: the ask rubric + return render_ask_prompt(question, answer, context or "(No documentation provided)", library_name) template = JUDGE_ROLES.get(role, JUDGE_ROLES["technical_expert"]) template = template.replace("__GROUND_BLOCK__", _GROUND_BLOCK if ground_truth else "") values = { @@ -332,20 +339,22 @@ def _extract_json(text: str) -> Dict: def _call_judge(self, config: JudgeConfig, question: str, answer: str, library_name: str, context: str, - ground_truth: Optional[str] = None) -> JudgeVote: + ground_truth: Optional[str] = None, expected_outcome: str = ANSWER) -> JudgeVote: prompt = self._build_prompt(config.role, question, answer, library_name, context, - ground_truth) + ground_truth, expected_outcome) + asking = expected_outcome == ASK + dims = ASK_DIMS if asking else SCORE_FIELDS def parse(raw: str) -> "tuple[Dict[str, Any], Dict[str, float]]": data = self._extract_json(raw) if not isinstance(data, dict): raise ValueError("judge reply is not a JSON object") - missing = [k for k in SCORE_FIELDS if k not in data] + missing = [k for k in dims if k not in data] if missing: raise ValueError(f"Missing keys in judge response: {missing}") # A non-numeric ("N/A"), boolean or non-finite dimension is a # formatting failure too; the clamp alone would turn NaN into 100. - raw_scores = {k: data[k] for k in SCORE_FIELDS} + raw_scores = {k: data[k] for k in dims} if any(isinstance(v, bool) or not _finite_after_float(v) for v in raw_scores.values()): raise ValueError("judge reply has a non-numeric or non-finite score") @@ -363,6 +372,12 @@ def send(text: str, *, draw: int, cache_if: Callable[[str], bool]) -> str: (data, scores), _ = judged_reply( send, prompt, parse, pinned=config.temperature is not None or config.seed is not None, label=f"Judge '{config.role}' reply", reminder=FORMAT_REMINDER) + if asking: # no figures to check in a clarifying question; the ask aggregate is Python's + return JudgeVote( + role=config.role, model=config.model, provider=config.provider, + scores=scores, reasoning=str(data.get("reasoning", "")), + aggregate=ask_weighted_aggregate(scores), + ) # Hold the prompt's wrong-figure cap in Python, with the single # judge's own rule, so the two cannot disagree about what it means. capped: Dict[str, Any] = {"correctness": scores["correctness"], @@ -392,6 +407,7 @@ def score_answer( answer: str, context: str = "(No documentation retrieved)", ground_truth: Optional[str] = None, + expected_outcome: str = ANSWER, ) -> Dict[str, Any]: """Score one answer, shaped like :meth:`Judge.score_answer`. @@ -409,6 +425,7 @@ def score_answer( verdict = self.evaluate( question=question, answer=answer, library_name=library_name, context=context, ground_truth=ground_truth, + expected_outcome=expected_outcome, ) out: Dict[str, Any] = dict(verdict.mean_dimensions) out["aggregate"] = verdict.mean_aggregate @@ -427,25 +444,30 @@ def score_answer( for v in verdict.votes ], } + if verdict.expected_outcome == ASK: + out["expected_outcome"] = ASK + out["judge_prompt_sha256"] = ASK_JUDGE_PROMPT_SHA256 error = _verdict_error(verdict) if error: out["error"] = error return out def evaluate(self, question: str, answer: str, library_name: str, - context: str = "", ground_truth: Optional[str] = None) -> PanelVerdict: + context: str = "", ground_truth: Optional[str] = None, + expected_outcome: str = ANSWER) -> PanelVerdict: votes: List[JudgeVote] = [] with ThreadPoolExecutor(max_workers=self.concurrency) as pool: futures = { pool.submit(self._call_judge, cfg, question, answer, library_name, context, - ground_truth): cfg + ground_truth, expected_outcome): cfg for cfg in self.judges } for future in as_completed(futures): votes.append(future.result()) - return self._aggregate(votes, grounded=bool(ground_truth)) + return self._aggregate(votes, grounded=bool(ground_truth), expected_outcome=expected_outcome) - def _aggregate(self, votes: List[JudgeVote], grounded: bool = False) -> PanelVerdict: + def _aggregate(self, votes: List[JudgeVote], grounded: bool = False, + expected_outcome: str = ANSWER) -> PanelVerdict: # One vote per panelist, errors included; a verdict needs a majority of # valid votes, else insufficient evidence. quorum = len(votes) // 2 + 1 @@ -459,17 +481,19 @@ def _aggregate(self, votes: List[JudgeVote], grounded: bool = False) -> PanelVer std_agg = round(statistics.stdev(aggs), 1) if len(aggs) > 1 else None agreement = round(max(0.0, 1.0 - std_agg / 50.0), 3) if std_agg is not None else None mean_dims: Dict[str, float] = {} - for dim in SCORE_FIELDS: + for dim in (ASK_DIMS if expected_outcome == ASK else SCORE_FIELDS): vals = [v.scores[dim] for v in valid if dim in v.scores] if vals: mean_dims[dim] = round(statistics.mean(vals), 1) return PanelVerdict(votes=votes, mean_aggregate=mean_agg, std_aggregate=std_agg, agreement_score=agreement, - mean_dimensions=mean_dims, quorum=quorum, grounded=grounded) + mean_dimensions=mean_dims, quorum=quorum, grounded=grounded, + expected_outcome=expected_outcome) def _score_answer_entry(self, answer: Optional[Answer], question: str, library_name: str, - ground_truth: Optional[str] = None) -> Optional[PanelVerdict]: + ground_truth: Optional[str] = None, + expected_outcome: str = ANSWER) -> Optional[PanelVerdict]: if answer is None or not answer.text: return None # answers.v1 keeps only each doc's 200-char ``snippet``; the full text the @@ -477,7 +501,7 @@ def _score_answer_entry(self, answer: Optional[Answer], question: str, # shows (``Judge._format_context``), so both judges see the same material. ctx = "\n".join(answer.context) return self.evaluate(question, answer.text, library_name, ctx, - ground_truth=ground_truth) + ground_truth=ground_truth, expected_outcome=expected_outcome) def evaluate_answers(self, answers: List[RecordLike], library_name: str, output_path: Optional[Path] = None, @@ -494,9 +518,9 @@ def evaluate_answers(self, answers: List[RecordLike], library_name: str, question = rec.question_text print(f"[{i}/{n}] Panel: {q_id}…", flush=True) with_v = self._score_answer_entry(rec.answer(CONTEXT), question, library_name, - rec.ground_truth) + rec.ground_truth, rec.expected_outcome) without_v = self._score_answer_entry(rec.answer(BASELINE), question, library_name, - rec.ground_truth) + rec.ground_truth, rec.expected_outcome) delta = None if (with_v and with_v.mean_aggregate is not None and without_v and without_v.mean_aggregate is not None): @@ -509,6 +533,7 @@ def evaluate_answers(self, answers: List[RecordLike], library_name: str, "without_docs": _verdict_to_dict(without_v), "delta": delta, "retrieval_hit": rec.retrieval_hit, + "expected_outcome": rec.expected_outcome, }) if output_path: _save_incremental(results, output_path, library_name, self, run_metadata) @@ -564,6 +589,9 @@ def _verdict_to_dict(v: Optional[PanelVerdict]) -> Optional[Dict[str, Any]]: for vt in v.votes ], } + if v.expected_outcome == ASK: + out["expected_outcome"] = ASK + out["judge_prompt_sha256"] = ASK_JUDGE_PROMPT_SHA256 # A cell with no score carries its reason, as score_answer's does, so readers that count Score.error see it. error = _verdict_error(v) if error: diff --git a/dokimi/dokimi/eval/ragas_eval.py b/dokimi/dokimi/eval/ragas_eval.py index 0364647e84..034dcd6071 100644 --- a/dokimi/dokimi/eval/ragas_eval.py +++ b/dokimi/dokimi/eval/ragas_eval.py @@ -25,6 +25,7 @@ import os from typing import List, Dict, Any, Optional, Tuple +from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.question_text import require_question_text from dokimi.defaults import DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER from dokimi.llm import credential_env_var, resolve_api_key @@ -149,6 +150,7 @@ def evaluate( wd = rec.answer(CONTEXT) if wd is not None and wd.text and wd.context: # Rows are all built before the first RAGAS call: refuse, do not grade against "". + require_judgeable_outcome([rec.raw], "RAGAS") require_question_text(rec.raw, i) row: Dict[str, Any] = { "user_input": q, @@ -164,6 +166,7 @@ def evaluate( if include_without_docs and "answer_relevancy" in self._requested: wod = rec.answer(BASELINE) if wod is not None and wod.text: + require_judgeable_outcome([rec.raw], "RAGAS") require_question_text(rec.raw, i) rows_without.append({ "user_input": q, diff --git a/dokimi/dokimi/records.py b/dokimi/dokimi/records.py index 70f4a0695a..6aff663063 100644 --- a/dokimi/dokimi/records.py +++ b/dokimi/dokimi/records.py @@ -77,6 +77,39 @@ QuestionId = Union[str, int] +ANSWER = "answer" +ASK = "ask" +#: The values ``expected_outcome`` may take (questions.v2 declares the same set). +EXPECTED_OUTCOMES = (ANSWER, ASK) + + +class AskOutcomeError(InputError): + """A record's ``expected_outcome`` is not a known value, or the path cannot judge it. + + An :class:`~dokimi.utils.InputError`: the CLI reports ``Error: ...`` with exit 2. + """ + + +def outcome_of(record: Mapping[str, Any], index: Optional[int] = None) -> str: + """The record's expected outcome: ``ask`` or ``answer`` (the default when absent or null). + + Raises :class:`AskOutcomeError` for any other value, so a typo cannot silently grade as an answer. + """ + value = record.get("expected_outcome") + if value is None: + return ANSWER + if isinstance(value, str) and value in EXPECTED_OUTCOMES: + return value + where = f"record #{index}" if index is not None else "a record" + qid = record.get("question_id") + if qid is not None: + where = f"question {qid!r}" + raise AskOutcomeError( + f"{where} has expected_outcome {value!r}; it must be one of " + f"{', '.join(EXPECTED_OUTCOMES)} (or absent, which means answer)" + ) + + class RecordError(InputError): """An artifact or record that is not one of the shapes this module reads (an :class:`InputError`).""" @@ -166,6 +199,9 @@ class Record: #: ``expected_skill``: the acceptable skill names, ``()`` when no skill should #: load, ``None`` when the record carries no label (not scored for selection). expected_skills: Optional[tuple[str, ...]] = None + #: ``answer`` (absent in the record) or ``ask``: what the question expects the reply to do. + #: Routes the judge to the answer or the ask rubric (dokimi.eval.ask_outcome). + expected_outcome: str = "answer" #: The persisted record, for fields this module does not model. Read-only by #: convention. A joined record's is the answers record over the evaluation. raw: Mapping[str, Any] = field(default_factory=dict) @@ -362,6 +398,7 @@ def record(item: RecordLike, *, source: str = "", index: int = 0, kind: O diagnosis=diagnosis if isinstance(diagnosis, Mapping) else None, retrieval_hit=hit if isinstance(hit, bool) else _retrieval_hit(answers.get(CONTEXT), conditions), expected_skills=_expected_skills(item, where), + expected_outcome=_expected_outcome(item, where), raw=item, ) @@ -409,6 +446,8 @@ def join( diagnosis=e.diagnosis or a.diagnosis, retrieval_hit=e.retrieval_hit if e.retrieval_hit is not None else a.retrieval_hit, expected_skills=a.expected_skills if a.expected_skills is not None else e.expected_skills, + # The answers record copies its question's outcome; it is the one the question set sets. + expected_outcome=a.expected_outcome, raw={**e.raw, **a.raw}, )) out.extend(e for e in evs if e.key not in seen) @@ -614,6 +653,15 @@ def _expected_skills(item: Mapping[str, Any], where: str) -> Optional[tuple[str, return tuple(n for n in names if n) +def _expected_outcome(item: Mapping[str, Any], where: str) -> str: + # Imported here: dokimi.eval's package init imports the judges, which import this module. + + try: + return outcome_of(item) + except AskOutcomeError as exc: + raise RecordError(f"{where}: {exc}") from None + + def _looks_judged(item: Mapping[str, Any]) -> bool: """A bare binary record is an evaluation when it carries a delta or a score block.""" if "delta" in item: diff --git a/dokimi/dokimi/schemas/eval.v1.json b/dokimi/dokimi/schemas/eval.v1.json index 376639c78c..5ad239f645 100644 --- a/dokimi/dokimi/schemas/eval.v1.json +++ b/dokimi/dokimi/schemas/eval.v1.json @@ -91,6 +91,11 @@ }, "retrieval_hit": { "description": "Whether retrieval put at least one document into the context-arm prompt (dokimi.records, from the answer's retrieved_docs and doc_source); null when the record has no context arm. Read by the trust gate." + }, + "expected_outcome": { + "description": "The question's expected outcome, copied from the question record: `answer` or `ask` (dokimi.eval.ask_outcome). Written on every row by the rubric judges; an evaluation from before the field existed is `answer`.", + "type": "string", + "enum": ["answer", "ask"] } } } diff --git a/dokimi/dokimi/schemas/questions.v2.json b/dokimi/dokimi/schemas/questions.v2.json index 82708147e3..ada33160f9 100644 --- a/dokimi/dokimi/schemas/questions.v2.json +++ b/dokimi/dokimi/schemas/questions.v2.json @@ -192,6 +192,11 @@ "description": "`verbatim`: the answerer sends `question` as written, without its expert-answer wrapper (set by `eval import`, whose graders score the reply to the original prompt).", "type": "string" }, + "expected_outcome": { + "description": "What a correct reply does. `answer` (the default when absent) is graded by the answer rubric. `ask` marks a question with a missing detail the answer depends on: the reply should ask for it, and is graded by the ask rubric (dokimi.eval.ask_outcome). Judge paths with no ask rubric refuse an `ask` record.", + "type": "string", + "enum": ["answer", "ask"] + }, "grading": { "description": "Format-neutral reference checks from an imported eval (`eval import`): `checks` (match, exact, fuzzy, regex, choice, json, judge, unsupported), optional `threshold`, `source_format`, `native_scorer`. Scored by `eval score reference`; see dokimi.eval.reference_checks.", "type": "object", diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py new file mode 100644 index 0000000000..132d55c96c --- /dev/null +++ b/dokimi/tests/test_expected_outcome.py @@ -0,0 +1,351 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""``expected_outcome: ask``: the ask rubric on every judge path that has one, a refusal on the rest. + +A question the assistant should ask back is graded by its own rubric, stamped with its own +prompt hash, and the answer rubric's hash does not change. Each path that cannot grade a +clarifying question refuses such a record before any judge call. +""" + +from __future__ import annotations + +import json +import threading +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from dokimi.artifacts import ArtifactValidationError, validate_artifact +from dokimi.eval.ask_outcome import ( + ASK, ANSWER, ASK_JUDGE_PROMPT, ASK_JUDGE_PROMPT_SHA256, AskOutcomeError, outcome_fields, outcome_of, + render_ask_prompt, require_judgeable_outcome, +) +from dokimi.eval.arm_record import question_record +from dokimi.eval.arm_runner import ArmRunner +from dokimi.eval.checklist import run_checklist +from dokimi.eval.cross_judge import score_measure +from dokimi.eval.degrade import build_pairs +from dokimi.eval.judge import JUDGE_PROMPT_SHA256, Judge +from dokimi.eval.pairwise import run_arm_pairwise +from dokimi.eval.panel import JudgeConfig, JudgePanel +from dokimi.records import RecordError, record + +#: The answer rubric's identity as it was before this feature. Pinned: an ask rubric must not move it. +PRE_FEATURE_JUDGE_PROMPT_SHA256 = "sha256:034292bdc6b360e52d98d0f3424e48fea41c9c8ca16a44c4b938476fc85a8499" + +REPLY = "Which version of the library are you on? The fit call differs between 1.x and 2.x." +ANSWER_TEXT = "Call fit() on the estimator, then predict(). " * 8 +ASK_QUESTION = "How do I set the default number of workers?" + + +def _ask_reply(**over): + scores = {"clarifying_question": 95, "targets_ambiguity": 90, "avoids_guessing": 100} + scores.update(over) + return json.dumps({**scores, "aggregate": 0, "reasoning": {k: "ok" for k in scores}}) + + +def _answer_reply(**over): + scores = {"correctness": 80, "completeness": 80, "specificity": 80, "code_quality": 80, + "actionability": 80} + scores.update(over) + return json.dumps({**scores, "aggregate": 0, "reasoning": {k: "ok" for k in scores}}) + + +class _FakeLLM: + """Returns a fixed reply and keeps every prompt it was sent.""" + + def __init__(self, reply): + self.reply = reply + self.prompts = [] + + def invoke(self, text, draw=0, cache_if=None): + self.prompts.append(text) + return SimpleNamespace(content=self.reply, usage=None) + + +def _judge(reply): + judge = Judge.__new__(Judge) + judge.llm = _FakeLLM(reply) + judge.temperature = judge.seed = None + judge.prompt_template = None + judge.model, judge.provider = "fake-judge", "openai" + judge.run_metadata, judge.answers_method_version, judge.judge_placeholder = {}, 2, False + judge.prompt_sha256 = JUDGE_PROMPT_SHA256 + judge._usage_lock, judge._redrawn_judgements = threading.Lock(), 0 + judge._resolved_models = set() + judge._accumulate_usage = lambda usage: None + return judge + + +def _answers_record(qid, text, outcome=None, **arms): + rec = {"question_id": qid, "question_text": text, + # A retrieved context answer: the no-retrieval placeholder is left unjudged by default. + "with_docs": {"answer": ANSWER_TEXT, "retrieved_docs": [{"snippet": "s"}], "doc_source": "context7"}, + "without_docs": {"answer": ANSWER_TEXT}} + if outcome is not None: + rec["expected_outcome"] = outcome + rec.update(arms) + return rec + + +def _arms_record(qid, text, outcome=None): + rec = {"question_id": qid, "question_text": text, + "arms": {"baseline": {"answer": ANSWER_TEXT}, "skill": {"answer": ANSWER_TEXT + "x"}}} + if outcome is not None: + rec["expected_outcome"] = outcome + return rec + + +# ── the vocabulary and the rubric ──────────────────────────────────────── + +def test_answer_rubric_hash_is_unchanged_by_the_ask_rubric(): + assert JUDGE_PROMPT_SHA256 == PRE_FEATURE_JUDGE_PROMPT_SHA256 + + +def test_ask_rubric_has_its_own_hash(): + assert ASK_JUDGE_PROMPT_SHA256.startswith("sha256:") + assert ASK_JUDGE_PROMPT_SHA256 != JUDGE_PROMPT_SHA256 + + +@pytest.mark.parametrize("record, expected", [ + ({}, ANSWER), + ({"expected_outcome": None}, ANSWER), + ({"expected_outcome": "answer"}, ANSWER), + ({"expected_outcome": "ask"}, ASK), +]) +def test_outcome_defaults_to_answer(record, expected): + assert outcome_of(record) == expected + + +@pytest.mark.parametrize("value", ["refuse", "Ask", "", 1, ["ask"], True]) +def test_unknown_outcome_is_refused_not_graded_as_an_answer(value): + with pytest.raises(AskOutcomeError, match="expected_outcome"): + outcome_of({"question_id": "q1", "expected_outcome": value}) + + +def test_outcome_fields_writes_only_ask(): + assert outcome_fields({"expected_outcome": "ask"}) == {"expected_outcome": "ask"} + assert outcome_fields({"expected_outcome": "answer"}) == {} + assert outcome_fields({}) == {} + + +def test_render_keeps_a_placeholder_written_in_the_question(): + text = render_ask_prompt("write __ANSWER__ here", "reply", "ctx", "lib") + assert "Request:** write __ANSWER__ here" in text + assert "Reply:** reply" in text + assert "Correctness" not in text and "Clarifying question (0-100)" in ASK_JUDGE_PROMPT + + +def test_schema_accepts_ask_and_absent_and_refuses_other_values(): + base = {"schema_version": "questions.v2", "questions": [{"id": "q1", "question": "How?"}]} + validate_artifact("questions", base) + validate_artifact("questions", {**base, "questions": [{"id": "q1", "question": "How?", + "expected_outcome": "ask"}]}) + with pytest.raises(ArtifactValidationError): + validate_artifact("questions", {**base, "questions": [{"id": "q1", "question": "How?", + "expected_outcome": "refuse"}]}) + + +# ── records ─────────────────────────────────────────────────────────────── + +def test_record_carries_the_outcome_and_defaults_to_answer(): + assert record(_answers_record("q1", "How?", "ask")).expected_outcome == "ask" + assert record(_answers_record("q1", "How?")).expected_outcome == "answer" + + +def test_record_refuses_an_unknown_outcome(): + with pytest.raises(RecordError, match="expected_outcome"): + record(_answers_record("q1", "How?", "refuse")) + + +# ── the answerer and the arms question record write it ─────────────────── + +def test_question_record_writes_ask_and_leaves_answer_records_alone(): + asked = question_record("lib", {"expected_outcome": "ask"}, "q1", "How?", None, {}, grounded_from_topics=False) + plain = question_record("lib", {}, "q1", "How?", None, {}, grounded_from_topics=False) + assert asked["expected_outcome"] == "ask" + assert "expected_outcome" not in plain + + +def test_answerer_pair_carries_the_outcome_of_its_question(): + from dokimi.eval.answerer import Answerer + + answerer = Answerer.__new__(Answerer) + answerer.mcp_client = None + answerer.model, answerer.provider = "m", "openai" + answerer._generate_without_docs = lambda question, verbatim=False: {"answer": "x", "token_usage": {}} + pair = answerer._generate_answer_pair("lib", "lib/id", {"question": ASK_QUESTION, "id": "q1", + "expected_outcome": "ask"}, 100) + assert pair["expected_outcome"] == "ask" + plain = answerer._generate_answer_pair("lib", "lib/id", {"question": ASK_QUESTION, "id": "q1"}, 100) + assert "expected_outcome" not in plain + + +# ── Judge: the rubric is routed on the record's outcome ────────────────── + +def test_judge_asks_the_ask_rubric_and_stamps_its_hash(): + judge = _judge(_ask_reply()) + result = judge._judge_answer("lib", ASK_QUESTION, REPLY, "(none)", expected_outcome=ASK) + assert "Clarifying question (0-100)" in judge.llm.prompts[0] + assert "Correctness (0-100)" not in judge.llm.prompts[0] + assert result["expected_outcome"] == ASK + assert result["judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 + assert result["aggregate"] == round((95 + 2 * 90 + 2 * 100) / 5, 1) + + +def test_judge_answer_mode_is_unchanged_and_unstamped(): + judge = _judge(_answer_reply()) + result = judge._judge_answer("lib", ASK_QUESTION, ANSWER_TEXT, "(none)") + assert "Correctness (0-100)" in judge.llm.prompts[0] + assert "expected_outcome" not in result and "judge_prompt_sha256" not in result + + +def test_judge_ask_reply_missing_a_dimension_is_redrawn_not_scored(): + judge = _judge(_answer_reply()) # an answer-rubric reply to an ask question: no ask dimensions + with pytest.raises(ValueError, match="Missing keys"): + judge._judge_answer("lib", ASK_QUESTION, REPLY, "(none)", expected_outcome=ASK) + + +class _RoutingLLM(_FakeLLM): + """Replies in the shape of whichever rubric the prompt asks for.""" + + def invoke(self, text, draw=0, cache_if=None): + self.reply = _ask_reply() if "Clarifying question (0-100)" in text else _answer_reply() + return super().invoke(text, draw, cache_if) + + +def test_evaluate_answers_routes_each_record_and_stores_its_outcome(): + judge = _judge(_ask_reply()) + judge.llm = _RoutingLLM(None) + rows = judge.evaluate_answers("lib", [_answers_record("q1", ASK_QUESTION, "ask"), + _answers_record("q2", "How do I fit?")]) + by_id = {r["question_id"]: r for r in rows} + assert by_id["q1"]["expected_outcome"] == "ask" + assert by_id["q1"]["with_docs"]["expected_outcome"] == "ask" + assert by_id["q1"]["with_docs"]["judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 + assert by_id["q2"]["expected_outcome"] == "answer" + assert "judge_prompt_sha256" not in by_id["q2"]["with_docs"] + + +def test_score_answer_takes_the_outcome(): + judge = _judge(_ask_reply()) + out = judge.score_answer(library_name="lib", question=ASK_QUESTION, answer=REPLY, expected_outcome=ASK) + assert out["expected_outcome"] == ASK + + +# ── JudgePanel: the ask rubric on every role ───────────────────────────── + +def _panel(monkeypatch, reply): + import dokimi.eval.panel as panel_mod + + prompts = [] + + def fake_llm_call(text, **kwargs): + prompts.append(text) + return reply + + monkeypatch.setattr(panel_mod, "llm_call", fake_llm_call) + panel = JudgePanel(judges=[JudgeConfig(role="technical_expert", model="m", provider="openai")]) + return panel, prompts + + +def test_panel_scores_an_ask_with_the_ask_rubric(monkeypatch): + panel, prompts = _panel(monkeypatch, _ask_reply()) + out = panel.score_answer(library_name="lib", question=ASK_QUESTION, answer=REPLY, expected_outcome=ASK) + assert "Clarifying question (0-100)" in prompts[0] + assert out["expected_outcome"] == ASK + assert out["judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 + assert out["targets_ambiguity"] == 90.0 + assert out["aggregate"] == round((95 + 2 * 90 + 2 * 100) / 5, 1) + + +def test_panel_answer_mode_is_unchanged(monkeypatch): + panel, prompts = _panel(monkeypatch, _answer_reply()) + out = panel.score_answer(library_name="lib", question="How?", answer=ANSWER_TEXT) + assert '"correctness"' in prompts[0] and "Clarifying question" not in prompts[0] + assert "expected_outcome" not in out and "judge_prompt_sha256" not in out + + +def test_panel_evaluate_answers_stamps_the_verdict_rows(monkeypatch): + panel, _ = _panel(monkeypatch, _ask_reply()) + rows = panel.evaluate_answers([_answers_record("q1", ASK_QUESTION, "ask")], "lib") + assert rows[0]["expected_outcome"] == "ask" + assert rows[0]["with_docs"]["judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 + assert rows[0]["with_docs"]["dimensions"]["targets_ambiguity"] == 90.0 + + +# ── ArmRunner.judge ─────────────────────────────────────────────────────── + +def test_arm_runner_routes_an_ask_record_and_stores_its_outcome(): + runner = ArmRunner.__new__(ArmRunner) + runner.judge_context = MagicMock() + runner.judge_context.resolve_with_source.return_value = ("ctx", "none") + runner.judge_context.digest_of.return_value = None + judge = MagicMock() + judge.score_answer.return_value = {"aggregate": 90.0, "expected_outcome": "ask"} + rows = runner.judge(judge, "lib", [_arms_record("q1", ASK_QUESTION, "ask"), + _arms_record("q2", "How do I fit?")]) + by_id = {r["question_id"]: r for r in rows} + assert by_id["q1"]["expected_outcome"] == "ask" + assert by_id["q2"]["expected_outcome"] == "answer" + kwargs_by_question = {c.kwargs["question"]: c.kwargs for c in judge.score_answer.call_args_list} + assert kwargs_by_question[ASK_QUESTION]["expected_outcome"] == ASK + assert "expected_outcome" not in kwargs_by_question["How do I fit?"] + + +# ── paths with no ask rubric refuse before any judge call ──────────────── + +def test_pairwise_refuses_an_ask_record_before_judging(): + judge = MagicMock() + with pytest.raises(AskOutcomeError, match="'q1'"): + run_arm_pairwise([_arms_record("q1", ASK_QUESTION, "ask")], judge) + judge.compare.assert_not_called() + + +def test_checklist_refuses_an_ask_record_before_judging(): + ask = MagicMock() + with pytest.raises(AskOutcomeError, match="'q1'"): + run_checklist([_arms_record("q1", ASK_QUESTION, "ask")], {"q1": ["fit"]}, ask) + ask.assert_not_called() + + +def test_score_measure_refuses_an_ask_record_before_judging(): + scorer = MagicMock(return_value=50.0) + with pytest.raises(AskOutcomeError, match="'q1'"): + score_measure([_arms_record("q1", ASK_QUESTION, "ask")], scorer, name="j", library="lib") + scorer.assert_not_called() + + +def test_degradation_pairs_refuse_an_ask_record_before_judging(): + answers = [_arms_record(f"q{i}", f"question {i}?") for i in range(4)] + answers.append(_arms_record("q9", ASK_QUESTION, "ask")) + with pytest.raises(AskOutcomeError, match="'q9'"): + build_pairs(answers, n_bases=5, min_chars=10) + + +def test_ragas_refuses_an_ask_record_before_any_call(monkeypatch): + import dokimi.eval.ragas_eval as ragas_mod + + ragas_evaluate = MagicMock() + monkeypatch.setattr(ragas_mod, "_import_ragas_runtime", lambda: (MagicMock(), ragas_evaluate)) + ev = ragas_mod.RagasEvaluator.__new__(ragas_mod.RagasEvaluator) + ev._requested = {"faithfulness", "answer_relevancy"} + ev._metric_objects, ev._ragas_llm = [], MagicMock() + rec = {"question_id": "q2", "question_text": ASK_QUESTION, "expected_outcome": "ask", + "with_docs": {"answer": "a", "retrieved_docs": [{"snippet": "s"}]}, "without_docs": {"answer": "b"}} + with pytest.raises(AskOutcomeError, match="'q2'"): + ev.evaluate([rec]) + ragas_evaluate.assert_not_called() + + +def test_refusal_skips_a_record_with_nothing_to_judge(): + unanswered = {"question_id": "q2", "expected_outcome": "ask", "error": "timeout", + "with_docs": None, "without_docs": None} + assert require_judgeable_outcome([unanswered], "pairwise") is None + + +def test_refusal_names_the_path(): + with pytest.raises(AskOutcomeError, match="pairwise"): + require_judgeable_outcome([_answers_record("q1", "x", "ask")], "pairwise") diff --git a/dokimi/tests/test_record_readers.py b/dokimi/tests/test_record_readers.py index 03b96d7fc7..fe5827eb7b 100644 --- a/dokimi/tests/test_record_readers.py +++ b/dokimi/tests/test_record_readers.py @@ -39,7 +39,7 @@ def _panel_eval(failed=()): panel = JudgePanel.__new__(JudgePanel) panel.judges = [object(), object()] - def evaluate(question, answer, library_name, context="", ground_truth=None): + def evaluate(question, answer, library_name, context="", ground_truth=None, expected_outcome=None): dead = answer.startswith("context") and any(question.endswith(f" {i}?") for i in failed) agg = None if dead else float(60 + len(answer) % 7 + (10 if answer.startswith("context") else 0)) return PanelVerdict(votes=[], mean_aggregate=agg, std_aggregate=None if dead else 1.0, From 553d69ae3ed204ad073f8230f5cccd243c458250 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 25 Nov 2026 21:48:31 -0800 Subject: [PATCH 02/40] fix(eval): refuse an ask record in eval score reference; review nits Self-review found that `eval score reference` judged an ask record with no refusal and dropped the outcome from its row. It now refuses before any judge call, like the other comparison paths. Also: pairwise refuses only inside the arm loop (an arm filter that leaves nothing to judge is not refused), records.py uses the ANSWER constant and loses a stale comment, and methodology lists judge validity with the refusing paths. Signed-off-by: Nikolay Petrov --- dokimi/docs/methodology.md | 4 ++-- dokimi/dokimi/eval/pairwise.py | 2 +- dokimi/dokimi/eval/reference_run.py | 3 +++ dokimi/dokimi/records.py | 4 +--- dokimi/tests/test_expected_outcome.py | 13 +++++++++++++ 5 files changed, 20 insertions(+), 6 deletions(-) diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index e6fb72bab1..39bd9f309e 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -212,9 +212,9 @@ A question with `expected_outcome: ask` is one a good assistant answers by askin - **Targets the ambiguity** (weight 2): is the question the one that resolves the missing detail. - **Avoids guessing** (weight 2): does the reply leave the detail open, rather than pick a value and do the work on it. -The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_PROMPT_SHA256` does not change, so answer-mode results keep their stamp. A judged ask row carries `expected_outcome: ask` and the ask rubric's hash; the rubric judges (the single judge, the panel, `arms run --judge`, and judge validity) route on the value. +The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_PROMPT_SHA256` does not change, so answer-mode results keep their stamp. A judged ask row carries `expected_outcome: ask` and the ask rubric's hash; the rubric judges (the single judge, the panel, `arms run --judge`) route on the value. -The paths that compare answers with each other or with expected points (pairwise, checklist, cross-judge, degradation pairs, RAGAS) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. +The paths that compare answers with each other or with expected points (pairwise, checklist, cross-judge, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. ## Trust And Reproducibility diff --git a/dokimi/dokimi/eval/pairwise.py b/dokimi/dokimi/eval/pairwise.py index e8e0626f54..a852c32306 100644 --- a/dokimi/dokimi/eval/pairwise.py +++ b/dokimi/dokimi/eval/pairwise.py @@ -274,9 +274,9 @@ def pairwise_jobs( base = base_answer.text if base_answer is not None else None if not base: continue - require_judgeable_outcome([rec.raw], "pairwise") for arm, a in by_arm.items(): if arm != baseline_arm and a.text and (arms is None or arm in arms): + require_judgeable_outcome([rec.raw], "pairwise") jobs.append((arm, rec.question_id, require_question_text(rec.raw, i), a.text, base)) return jobs diff --git a/dokimi/dokimi/eval/reference_run.py b/dokimi/dokimi/eval/reference_run.py index c03ab3d2ee..c4ca12bc41 100644 --- a/dokimi/dokimi/eval/reference_run.py +++ b/dokimi/dokimi/eval/reference_run.py @@ -22,6 +22,7 @@ from typing import Any, Mapping, Optional from dokimi.caching import is_empty_reply +from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.reference_checks import Ask, Grade, grade, validate_grading from dokimi.records import NO_RETRIEVAL_SOURCES, Answer, Record, Run, read @@ -123,6 +124,8 @@ def score(data: Any, questions: list[Mapping[str, Any]], *, ask: Optional[Ask] = gradings = grading_by_id(questions) graded = [r for r in run if r.key in gradings] missing = [r.key for r in run if r.key not in gradings] + # Refused before any judge call: the checklist judge has no rubric for a clarifying question. + require_judgeable_outcome([r.raw for r in graded], "eval score reference") with ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool: grades = list(pool.map(lambda r: _grade_record(r, gradings[r.key], ask), graded)) diff --git a/dokimi/dokimi/records.py b/dokimi/dokimi/records.py index 6aff663063..aabba4a0cb 100644 --- a/dokimi/dokimi/records.py +++ b/dokimi/dokimi/records.py @@ -201,7 +201,7 @@ class Record: expected_skills: Optional[tuple[str, ...]] = None #: ``answer`` (absent in the record) or ``ask``: what the question expects the reply to do. #: Routes the judge to the answer or the ask rubric (dokimi.eval.ask_outcome). - expected_outcome: str = "answer" + expected_outcome: str = ANSWER #: The persisted record, for fields this module does not model. Read-only by #: convention. A joined record's is the answers record over the evaluation. raw: Mapping[str, Any] = field(default_factory=dict) @@ -654,8 +654,6 @@ def _expected_skills(item: Mapping[str, Any], where: str) -> Optional[tuple[str, def _expected_outcome(item: Mapping[str, Any], where: str) -> str: - # Imported here: dokimi.eval's package init imports the judges, which import this module. - try: return outcome_of(item) except AskOutcomeError as exc: diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 132d55c96c..39aa9b629f 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -349,3 +349,16 @@ def test_refusal_skips_a_record_with_nothing_to_judge(): def test_refusal_names_the_path(): with pytest.raises(AskOutcomeError, match="pairwise"): require_judgeable_outcome([_answers_record("q1", "x", "ask")], "pairwise") + + +def test_reference_scoring_refuses_an_ask_record_before_judging(): + from dokimi.eval.reference_run import score + + ask = MagicMock(return_value="yes") + data = {"answers": [{"question_id": "q1", "question_text": ASK_QUESTION, "expected_outcome": "ask", + "without_docs": {"answer": "Sure: set workers to 4 in the config file."}}]} + questions = [{"id": "q1", "question": ASK_QUESTION, "grading": {"checks": [ + {"type": "judge", "criterion": "The reply asks which version or platform the user means"}]}}] + with pytest.raises(AskOutcomeError, match="'q1'"): + score(data, questions, ask=ask) + ask.assert_not_called() From 0e3c6be682663b525b2e53fa7a5c52a61bc12504 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 25 Nov 2026 21:58:30 -0800 Subject: [PATCH 03/40] feat(eval): ask rows stay out of the arm headline; own count, mean and rubric stamp Answer rows alone feed the arm means, paired deltas, significance and interactions. Ask rows (expected_outcome: ask) report their count and per-arm means in an ask block, and a run with ask rows carries ask_judge_prompt_sha256. Panel docs: ask agreement is sampling noise. Signed-off-by: Nikolay Petrov --- ...25_130000_napetrov_expected-outcome-ask.md | 3 +- dokimi/docs/methodology.md | 4 ++ dokimi/dokimi/eval/arm_runner.py | 22 +++---- dokimi/dokimi/eval/arm_summary.py | 35 ++++++++++- dokimi/tests/test_expected_outcome.py | 61 +++++++++++++++++++ 5 files changed, 112 insertions(+), 13 deletions(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index 9150729fcd..e9cf24395e 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -9,6 +9,7 @@ SPDX-License-Identifier: Apache-2.0 A question record may carry `expected_outcome` (`answer`, the default, or `ask`). An `ask` record is graded by the ask rubric (clarifying question, targets the ambiguity, avoids guessing) with its own prompt hash (`ASK_JUDGE_PROMPT_SHA256`); `JUDGE_PROMPT_SHA256` is unchanged. The value is stored on answers records - and on every eval row. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, + and on every eval row. An arm summary's headline (means, deltas, significance) covers answer rows only; ask + rows report their count and means in an `ask` block, and a run with ask rows stamps `ask_judge_prompt_sha256`. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, RAGAS) refuse an `ask` record that has an answer to judge, before any judge call. See `docs/methodology.md` (questions that expect an ask). diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index 39bd9f309e..33da5a09e9 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -216,6 +216,10 @@ The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_P The paths that compare answers with each other or with expected points (pairwise, checklist, cross-judge, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. +**Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask rows were judged) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. + +**Panel agreement.** Every panel role gets the same ask prompt, so agreement between roles on ask rows measures sampling noise on one prompt, not independent judgement. Read it as a noise floor, not as evidence that the ask rubric is reliable. + ## Trust And Reproducibility Every serious run should answer "Can we trust this run?" before interpreting deltas. The trust gate checks: diff --git a/dokimi/dokimi/eval/arm_runner.py b/dokimi/dokimi/eval/arm_runner.py index 17802a7073..a039f4a4df 100644 --- a/dokimi/dokimi/eval/arm_runner.py +++ b/dokimi/dokimi/eval/arm_runner.py @@ -26,8 +26,8 @@ from dokimi.eval import stats as arm_stats from dokimi.eval.interactions import interaction_significance from dokimi.eval.arm_summary import ( - cell_values, cost_summary, empty_reply_cell, mean_in_range, question_deltas, refusal_kept, - summarize_agentic_usage, summarize_skill_selection, unjudged_cell, + ask_stamp, ask_summary, cell_values, cost_summary, empty_reply_cell, per_arm_block, question_deltas, refusal_kept, + split_outcomes, summarize_agentic_usage, summarize_skill_selection, unjudged_cell, ) from dokimi.eval.cells import Cell from dokimi.eval.ask_outcome import ASK @@ -737,6 +737,7 @@ def build_output( if evaluations is not None: out["evaluations"] = evaluations out["summary"] = self._summarize(evaluations, baseline_arm) + out.update(ask_stamp(out["summary"])) sources = [ s.raw.get("judge_context_source") for ev in as_records(evaluations, source="evaluations", kind="evaluations") @@ -761,17 +762,14 @@ def build_output( def _summarize( self, evaluations: List[Dict[str, Any]], baseline_arm: str ) -> Dict[str, Any]: - per_arm, errors = cell_values(evaluations, self.arm_names) - - summary: Dict[str, Any] = {"per_arm": {}} - for arm_name, vals in per_arm.items(): - avg = round(mean_in_range(vals), 1) if vals else None - summary["per_arm"][arm_name] = {"avg_aggregate": avg, "n": len(vals), "errors": errors.get(arm_name, 0)} + answers, asks = split_outcomes(evaluations) + per_arm, errors = cell_values(answers, self.arm_names) + summary: Dict[str, Any] = {"per_arm": per_arm_block(per_arm, errors)} # Paired over the questions both arms scored. Null for the baseline, an arm with no such # question, and an arm whose score range is refused, which says why in its own delta_error (#750). for arm_name, stats in summary["per_arm"].items(): stats["delta_vs_baseline"] = None if arm_name == baseline_arm else refusal_kept( - stats, "delta_error", partial(arm_stats.paired_delta, evaluations, baseline_arm, arm_name) + stats, "delta_error", partial(arm_stats.paired_delta, answers, baseline_arm, arm_name) ) # Paired statistics. Every arm is tested against the *same* baseline @@ -780,16 +778,18 @@ def _summarize( # kept as-is for artifact compatibility. arm_names = list(summary["per_arm"].keys()) significance = refusal_kept(summary, "significance_error", lambda: arm_stats.arm_significance( - evaluations, baseline_arm, arm_names, correction=self.stats_correction)) + answers, baseline_arm, arm_names, correction=self.stats_correction)) for arm_name, sig in (significance or {}).items(): summary["per_arm"].setdefault(arm_name, {})["significance"] = sig # Interaction contrasts are their own hypothesis family, corrected # among themselves rather than pooled with the arm comparisons above. interactions = refusal_kept(summary, "interactions_error", lambda: interaction_significance( - evaluations, arm_names, baseline_arm, correction=self.stats_correction)) + answers, arm_names, baseline_arm, correction=self.stats_correction)) if interactions: summary["interactions"] = interactions + if asks: + summary["ask"] = ask_summary(asks, self.arm_names) return summary diff --git a/dokimi/dokimi/eval/arm_summary.py b/dokimi/dokimi/eval/arm_summary.py index ce0aefb6d3..6275c39188 100644 --- a/dokimi/dokimi/eval/arm_summary.py +++ b/dokimi/dokimi/eval/arm_summary.py @@ -20,7 +20,9 @@ from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple from dokimi.metrics.usage import to_record -from dokimi.records import Answer, RecordLike +from dokimi.eval.ask_outcome import ASK_JUDGE_PROMPT_SHA256 +from dokimi.records import ASK, Answer, RecordLike +from dokimi.records import record as as_record from dokimi.records import records as as_records from dokimi.spend import Spend @@ -342,3 +344,34 @@ def cell_values(evaluations: Iterable[Any], arm_names: Sequence[str]) -> Tuple[D elif cell is not None and cell.error: errors[arm_name] = errors.get(arm_name, 0) + 1 return values, errors + + +def per_arm_block(values: Mapping[str, List[float]], errors: Mapping[str, int]) -> Dict[str, Dict[str, Any]]: + """The per-arm mean, count and error count for the aggregates :func:`cell_values` returned.""" + return {name: {"avg_aggregate": round(mean_in_range(vals), 1) if vals else None, "n": len(vals), + "errors": errors.get(name, 0)} for name, vals in values.items()} + + +def split_outcomes(evaluations: Iterable[Any]) -> Tuple[List[Any], List[Any]]: + """The answer rows and the ask rows of an evaluations list (``expected_outcome``). + + An ask row is graded by the ask rubric, a different question from the answer rubric, so the + headline never pools the two. Rows keep their order and their own dict. + """ + answers: List[Any] = [] + asks: List[Any] = [] + for ev in evaluations: + (asks if as_record(ev, source="evaluations", kind="evaluations").expected_outcome == ASK + else answers).append(ev) + return answers, asks + + +def ask_summary(asks: Sequence[Any], arm_names: Sequence[str]) -> Dict[str, Any]: + """The ask rows reported apart from the headline: how many, and each arm's mean over them.""" + values, errors = cell_values(asks, arm_names) + return {"cells": len(asks), "per_arm": per_arm_block(values, errors)} + + +def ask_stamp(summary: Mapping[str, Any]) -> Dict[str, Any]: + """The ask rubric's hash, stamped on the run when its summary carries an ask block.""" + return {"ask_judge_prompt_sha256": ASK_JUDGE_PROMPT_SHA256} if "ask" in summary else {} diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 39aa9b629f..d0c1115ff9 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -23,6 +23,7 @@ render_ask_prompt, require_judgeable_outcome, ) from dokimi.eval.arm_record import question_record +from dokimi.eval import arm_runner as arm_runner_module from dokimi.eval.arm_runner import ArmRunner from dokimi.eval.checklist import run_checklist from dokimi.eval.cross_judge import score_measure @@ -362,3 +363,63 @@ def test_reference_scoring_refuses_an_ask_record_before_judging(): with pytest.raises(AskOutcomeError, match="'q1'"): score(data, questions, ask=ask) ask.assert_not_called() + + +# ── headline stats exclude ask cells; ask cells get their own block ────── + +def _judged_row(qid, outcome, baseline, skill): + return {"question_id": qid, "question_text": "q", "expected_outcome": outcome, + "scores": {"baseline": {"aggregate": baseline}, "skill": {"aggregate": skill}}, + "deltas_vs_baseline": {}} + + +def _summarizing_runner(): + runner = ArmRunner.__new__(ArmRunner) + runner.treatments = [SimpleNamespace(name="baseline"), SimpleNamespace(name="skill")] + runner.turn_reminder = None + runner.stats_correction = "holm" + return runner + + +def test_headline_means_and_deltas_are_the_answer_rows_alone(): + answers = [_judged_row("a1", "answer", 80, 60), _judged_row("a2", "answer", 70, 50)] + asks = [_judged_row("k1", "ask", 10, 90)] + mixed = _summarizing_runner()._summarize(answers + asks, "baseline") + alone = _summarizing_runner()._summarize(answers, "baseline") + assert mixed["per_arm"] == alone["per_arm"] + assert mixed["per_arm"]["baseline"] == {"avg_aggregate": 75.0, "n": 2, "errors": 0, + "delta_vs_baseline": None} + + +def test_ask_cells_get_their_own_block_with_count_and_mean(): + rows = [_judged_row("a1", "answer", 80, 60), _judged_row("k1", "ask", 10, 90), + _judged_row("k2", "ask", 30, 70)] + summary = _summarizing_runner()._summarize(rows, "baseline") + assert summary["ask"] == {"cells": 2, "per_arm": { + "baseline": {"avg_aggregate": 20.0, "n": 2, "errors": 0}, + "skill": {"avg_aggregate": 80.0, "n": 2, "errors": 0}, + }} + + +def test_no_ask_cells_leaves_the_summary_without_an_ask_block(): + summary = _summarizing_runner()._summarize([_judged_row("a1", "answer", 80, 60)], "baseline") + assert "ask" not in summary + + +def test_run_stamps_the_ask_rubric_hash_only_when_ask_cells_are_present(monkeypatch): + judge = SimpleNamespace(prompt_sha256=JUDGE_PROMPT_SHA256, model="m", provider="p", temperature=0) + runner = _summarizing_runner() + runner.model, runner.provider, runner.harness = "m", "p", "h" + runner.plugin_set = {"plugin_set": "none", "plugin_set_id": "x", "plugins": []} + runner.grounded_from_topics, runner.session_turns, runner.judge_context = False, None, None + runner.matrix_cell = None + for name in ("_run_config", "_cost_summary", "_summarize_agentic_usage"): + monkeypatch.setattr(runner, name, lambda *a, **k: {}) + monkeypatch.setattr(arm_runner_module, "cite_judge_materials", lambda *a: {}) + answers_only = runner.build_output("lib", [], [_judged_row("a1", "answer", 80, 60)], + judge=judge) + assert "ask_judge_prompt_sha256" not in answers_only + assert answers_only["judge_prompt_sha256"] == JUDGE_PROMPT_SHA256 + with_ask = runner.build_output("lib", [], [_judged_row("k1", "ask", 10, 90)], judge=judge) + assert with_ask["ask_judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 + assert with_ask["judge_prompt_sha256"] == JUDGE_PROMPT_SHA256 From 7830a59fc1001d1b2dfafaca7cb32c8e4ebcab5a Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 28 Nov 2026 20:37:01 -0800 Subject: [PATCH 04/40] fix(arms): ask rows stay out of every reader's statistics, and show their own block to_binary (the answers.v1/eval.v1 bridge), the plugin delta, eval report, report generate and model-compare pool evaluations; they now leave ask rows out, and to_binary and eval report say so. arms report and the arms run console print the summary's ask block apart from the headline. Signed-off-by: Nikolay Petrov --- ...25_130000_napetrov_expected-outcome-ask.md | 2 +- dokimi/docs/methodology.md | 2 +- dokimi/dokimi/commands/arms.py | 8 ++ dokimi/dokimi/eval/arms_adapter.py | 14 +++- dokimi/dokimi/eval/plugin_delta.py | 7 +- dokimi/dokimi/report/arms_report.py | 33 ++++++-- dokimi/dokimi/report/eval_report.py | 15 +++- dokimi/dokimi/report/generator.py | 6 +- dokimi/dokimi/report/model_compare.py | 4 +- dokimi/tests/test_ask_readers.py | 75 +++++++++++++++++++ 10 files changed, 147 insertions(+), 19 deletions(-) create mode 100644 dokimi/tests/test_ask_readers.py diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index e9cf24395e..3fbe591e46 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -10,6 +10,6 @@ SPDX-License-Identifier: Apache-2.0 by the ask rubric (clarifying question, targets the ambiguity, avoids guessing) with its own prompt hash (`ASK_JUDGE_PROMPT_SHA256`); `JUDGE_PROMPT_SHA256` is unchanged. The value is stored on answers records and on every eval row. An arm summary's headline (means, deltas, significance) covers answer rows only; ask - rows report their count and means in an `ask` block, and a run with ask rows stamps `ask_judge_prompt_sha256`. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, + rows report their count and means in an `ask` block, and a run with ask rows stamps `ask_judge_prompt_sha256`. The readers that pool evaluations (`arms report`, `arms run` console, `eval report`, `report generate`, `report model-compare`, the plugin delta, the arms-to-binary bridge) leave ask rows out of their statistics; `arms report` and `eval report` say how many were left out. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, RAGAS) refuse an `ask` record that has an answer to judge, before any judge call. See `docs/methodology.md` (questions that expect an ask). diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index 33da5a09e9..bceddc0bf3 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -216,7 +216,7 @@ The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_P The paths that compare answers with each other or with expected points (pairwise, checklist, cross-judge, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. -**Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask rows were judged) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. +**Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask questions the run has, errored ones included) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it; `arms report` and the `arms run` console print the block apart. The binary payloads (`to_binary`, which feed `answers.v1`/`eval.v1`) and the plugin delta leave ask questions out, and warn when they do. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. **Panel agreement.** Every panel role gets the same ask prompt, so agreement between roles on ask rows measures sampling noise on one prompt, not independent judgement. Read it as a noise floor, not as evidence that the ask rubric is reliable. diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index 97703dc195..7422715680 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -15,6 +15,7 @@ from dokimi import cli_flags from dokimi.commands.novelty_budget import fresh_partial_destination from dokimi.exit_codes import EXIT_FAILURE, EXIT_USAGE +from dokimi.report.arms_report import ask_summary_lines from dokimi.llm import ANSWER_PROVIDERS from dokimi.utils import InputError, question_id from dokimi.write_probe import can_write @@ -74,6 +75,12 @@ def _exit_if_terminated(output: dict) -> None: sys.exit(EXIT_FAILURE) +def _print_ask_block(output: dict) -> None: + """The ask questions' own count and means, printed apart from the summary above.""" + if output.get("summary", {}).get("ask"): + print("\n" + "\n".join(ask_summary_lines(output["summary"]["ask"], output["arms"]))) + + def cmd_arms_run(args: argparse.Namespace) -> None: """Run an N-arm treatment comparison and optionally judge it.""" from dokimi.eval.arms_run import LibraryIdError, ProbeError, prepare_arms, run_prepared @@ -119,6 +126,7 @@ def cmd_arms_run(args: argparse.Namespace) -> None: delta_s = f" (delta not computed: {stats['delta_error']})" err_s = f" ({stats['errors']} errors)" if stats.get("errors") else "" print(f" {arm:<24} {avg_s}{delta_s}{err_s}") + _print_ask_block(output) _exit_if_terminated(output) diff --git a/dokimi/dokimi/eval/arms_adapter.py b/dokimi/dokimi/eval/arms_adapter.py index a5cb135c75..ef1f2e60b0 100644 --- a/dokimi/dokimi/eval/arms_adapter.py +++ b/dokimi/dokimi/eval/arms_adapter.py @@ -32,16 +32,19 @@ from __future__ import annotations +import logging from typing import Any, Dict, List, Mapping, Optional, Tuple from dokimi.caching import is_empty_reply from dokimi.eval.diagnoser import diagnose from dokimi.records import ( - BASELINE, CONTEXT, KNOWLEDGE_INTENT, PAIRED_INTENT, Answer, Record, RecordError, Run, arm_scores, knowledge_only, + ASK, BASELINE, CONTEXT, KNOWLEDGE_INTENT, PAIRED_INTENT, Answer, Record, RecordError, Run, arm_scores, knowledge_only, read, record, ) from dokimi.utils import same_evaluator +logger = logging.getLogger(__name__) + #: The ``arm_kind`` of a ``DocTreatment`` arm (``treatments/factory.py``): retrieval into the prompt. _DOC_KINDS = frozenset({"docs", "mcp_doc"}) #: Top-level fields of an arms run that its eval file carries under the same name. @@ -66,7 +69,12 @@ def to_binary(data: Mapping[str, Any], *, source: str = "") -> Tuple[Dict[ stop = _stop_block(data) context, baseline = _binary_arms(run, source, stopped=stop is not None) intent = KNOWLEDGE_INTENT if context is None else PAIRED_INTENT - answers = [_answers_record(r, context, baseline) for r in run] + # Ask questions have their own rubric and no answers headline: they are left out of both payloads, and said so. + rows = [r for r in run if r.expected_outcome != ASK] + if len(rows) != len(run): + logger.warning("%s: %d ask question(s) left out of the answers and eval payloads (own rubric, not in the " + "headline); the arms file keeps them", source, len(run) - len(rows)) + answers = [_answers_record(r, context, baseline) for r in rows] answers_out: Dict[str, Any] = { **_present(data, "generated_at", "method_version"), "run_intent": intent, @@ -87,7 +95,7 @@ def to_binary(data: Mapping[str, Any], *, source: str = "") -> Tuple[Dict[ "run_intent": intent, **({"terminated": stop} if stop is not None else {}), } - evaluations = [_eval_record(r, a, context, baseline, meta) for r, a in zip(run, answers, strict=True)] + evaluations = [_eval_record(r, a, context, baseline, meta) for r, a in zip(rows, answers, strict=True)] return answers_out, { # The arms file is assembled after its judging, so its time is the eval's. **({"evaluated_at": data["generated_at"]} if "generated_at" in data else {}), diff --git a/dokimi/dokimi/eval/plugin_delta.py b/dokimi/dokimi/eval/plugin_delta.py index 69f084a503..0e1afd4ac0 100644 --- a/dokimi/dokimi/eval/plugin_delta.py +++ b/dokimi/dokimi/eval/plugin_delta.py @@ -13,7 +13,7 @@ from typing import Any, Dict -from dokimi.records import Record, RecordError, profile_prompt_digests, records +from dokimi.records import ASK, Record, RecordError, profile_prompt_digests, records class PluginDeltaError(ValueError): @@ -214,8 +214,9 @@ def _section(artifact: Dict[str, Any], section: str) -> list[Record]: def _score_deltas(control: Dict[str, Any], plugin: Dict[str, Any], arms: list[str]) -> dict[str, Any]: - control_scores = {r.key: r for r in _section(control, "evaluations")} - plugin_scores = {r.key: r for r in _section(plugin, "evaluations")} + # Ask rows are graded by their own rubric: the answer rows alone are paired, as the arm headline has them. + control_scores = {r.key: r for r in _section(control, "evaluations") if r.expected_outcome != ASK} + plugin_scores = {r.key: r for r in _section(plugin, "evaluations") if r.expected_outcome != ASK} out: dict[str, Any] = {} for arm in arms: pairs: list[tuple[float, float]] = [] diff --git a/dokimi/dokimi/report/arms_report.py b/dokimi/dokimi/report/arms_report.py index 3277ae6328..e6819419c2 100644 --- a/dokimi/dokimi/report/arms_report.py +++ b/dokimi/dokimi/report/arms_report.py @@ -3,10 +3,10 @@ """Render an N-arm treatment comparison as Markdown.""" -from typing import Any, Dict, List +from typing import Any, Dict, List, Mapping from dokimi.eval.arm_summary import TOOL_COUNTS -from dokimi.records import read +from dokimi.records import ASK, read from dokimi.report import fmt from dokimi.report.stop_note import stop_note @@ -131,6 +131,30 @@ def _interaction_lines(summary: Dict[str, Any]) -> List[str]: return lines +def ask_summary_lines(ask: Mapping[str, Any], arms: List[str]) -> List[str]: + """The ask block of a summary, shown apart from the headline: how many ask questions, each arm's mean over them.""" + cells = ask.get("cells", 0) + lines = [f"{cells} ask question{'s' if cells != 1 else ''}, graded by the ask rubric; not in the headline above:"] + for arm in arms: + stats = ask.get("per_arm", {}).get(arm, {}) + errors = stats.get("errors", 0) + err_s = f", {errors} error{'s' if errors != 1 else ''}" if errors else "" + lines.append(f" {arm}: avg {fmt.fixed(stats.get('avg_aggregate'))} over n={stats.get('n', 0)}{err_s}") + return lines + + +def _ask_block(summary: Mapping[str, Any], arms: List[str]) -> List[str]: + if not summary.get("ask"): + return [] + return ["## Ask questions (own rubric)", "", *ask_summary_lines(summary["ask"], arms), ""] + + +def _short_question(ev: Any) -> str: + q = ev.question_text + short = (q[:60] + "…") if len(q) > 60 else q + return short + (" (ask)" if ev.expected_outcome == ASK else "") + + def render_arms_report(data: Dict[str, Any]) -> str: """Render the artifact produced by ``ArmRunner.build_output`` as Markdown.""" lines: List[str] = [] @@ -166,6 +190,7 @@ def render_arms_report(data: Dict[str, Any]) -> str: lines.append("") lines.extend(_significance_lines(summary, arms, baseline)) lines.extend(_interaction_lines(summary)) + lines.extend(_ask_block(summary, arms)) else: lines.append("_No evaluations available (answers were not judged)._") lines.append("") @@ -271,9 +296,7 @@ def render_arms_report(data: Dict[str, Any]) -> str: lines.append(header) lines.append(sep) for ev in evaluations: - q = ev.question_text - q_short = (q[:60] + "…") if len(q) > 60 else q - q_short = _md_cell(q_short) + q_short = _md_cell(_short_question(ev)) cells = [fmt.fixed(ev.score(arm), 0) for arm in arms] lines.append(f"| {q_short} | " + " | ".join(cells) + " |") lines.append("") diff --git a/dokimi/dokimi/report/eval_report.py b/dokimi/dokimi/report/eval_report.py index 2ca587e795..4951c523ed 100755 --- a/dokimi/dokimi/report/eval_report.py +++ b/dokimi/dokimi/report/eval_report.py @@ -27,7 +27,7 @@ from dokimi.process_io import text_file_bytes # This module defines a local ``stats()`` helper, hence the ``eval_stats`` alias. from dokimi.eval import stats as eval_stats -from dokimi.records import BASELINE, CONTEXT, Record, RecordError, record, records +from dokimi.records import ASK, BASELINE, CONTEXT, Record, RecordError, record, records from dokimi.report.stop_note import stop_note, with_stop try: @@ -276,10 +276,20 @@ def _sibling_answers_path(eval_path: str) -> str: return re.sub(r"(^|[\\/])eval(?=[\\/][^\\/]*$)", r"\1answers", eval_path, count=1) +def _ask_note(count: int) -> list[str]: + if not count: + return [] + noun = "question" if count == 1 else "questions" + return [f"_{count} ask {noun}, graded by the ask rubric, are not in the statistics below._", ""] + + def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = None): data = _load_eval(eval_path) - evals = records(data["evaluations"], source=eval_path, kind="evaluations") + all_evals = records(data["evaluations"], source=eval_path, kind="evaluations") + # Ask questions are graded by their own rubric: the statistics are the answer rows, the count is shown. + ask_count = sum(1 for e in all_evals if e.expected_outcome == ASK) + evals = [e for e in all_evals if e.expected_outcome != ASK] meta = data.get("run_metadata", {}) library = os.path.basename(eval_path).replace(".json", "") @@ -308,6 +318,7 @@ def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = Non f"_Generated: {datetime.now(tz=_TZ).strftime('%Y-%m-%d %H:%M %Z') if _TZ else datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}_", "", *stop_note(data), + *_ask_note(ask_count), "## Run Configuration", "| | |", "|---|---|", diff --git a/dokimi/dokimi/report/generator.py b/dokimi/dokimi/report/generator.py index fa20d055d2..1008246147 100644 --- a/dokimi/dokimi/report/generator.py +++ b/dokimi/dokimi/report/generator.py @@ -15,7 +15,7 @@ DIAGNOSIS_DESCRIPTIONS, ) from dokimi.eval.stats import paired_summary -from dokimi.records import BASELINE, CONTEXT, Record, records +from dokimi.records import ASK, BASELINE, CONTEXT, Record, records from dokimi.report import fmt #: The persisted condition key each report column reads. @@ -56,7 +56,9 @@ def generate_report( multirun_with_averages: Per-run context-arm means from N-run mode trust_thresholds: Override default trust gate thresholds """ - evaluations = records(eval_data.get("evaluations", []), source="evaluations", kind="evaluations") + # Ask questions are graded by their own rubric: every statistic below is over the answer rows. + evaluations = [e for e in records(eval_data.get("evaluations", []), source="evaluations", kind="evaluations") + if e.expected_outcome != ASK] questions = questions_data.get("questions", []) # Build question lookup diff --git a/dokimi/dokimi/report/model_compare.py b/dokimi/dokimi/report/model_compare.py index 55718d8bce..b0c5c0a13e 100644 --- a/dokimi/dokimi/report/model_compare.py +++ b/dokimi/dokimi/report/model_compare.py @@ -36,7 +36,7 @@ from typing import Any from dokimi import atomic_write, process_io -from dokimi.records import Record, arm_answers, arm_names, arm_scores, profile_prompt_digests, read +from dokimi.records import ASK, Record, arm_answers, arm_names, arm_scores, profile_prompt_digests, read from dokimi.eval.judge_context import PROTOCOL_MIXED as JUDGE_CONTEXT_MIXED from dokimi.eval import finite_delta, stats as arm_stats from dokimi.report import fmt @@ -447,7 +447,7 @@ def extract_scores( if not isinstance(baseline_arm, str) or not baseline_arm: return [] - for evaluation in _section(run_data, "evaluations"): + for evaluation in (e for e in _section(run_data, "evaluations") if e.expected_outcome != ASK): qid = evaluation.question_id if not evaluation.conditions or baseline_arm not in evaluation.conditions: continue diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py new file mode 100644 index 0000000000..0ea8c33871 --- /dev/null +++ b/dokimi/tests/test_ask_readers.py @@ -0,0 +1,75 @@ +"""Readers of an arms run's evaluations pool answer rows only; ask rows are shown apart (expected_outcome: ask).""" + +from dokimi.eval.arms_adapter import to_binary +from dokimi.eval.plugin_delta import _score_deltas +from dokimi.report.arms_report import ask_summary_lines, render_arms_report +from test_arms_adapter import _arms, _cell, _question, _scores + + +def _ev(qid, arm_scores, outcome=None): + row = {"question_id": qid, "question_text": "How?", + "scores": {a: {"aggregate": v} for a, v in arm_scores.items()}} + if outcome is not None: + row["expected_outcome"] = outcome + return row + + +def _ask_question(qid): + return {**_question(qid, baseline=_cell(kind="baseline"), docs=_cell(kind="docs")), "expected_outcome": "ask"} + + +def test_to_binary_leaves_ask_questions_out_of_both_payloads(): + answers, evaluation = to_binary(_arms( + _question("q1", baseline=_cell(kind="baseline"), docs=_cell(kind="docs")), _ask_question("k1"), + evaluations=[_scores("q1", baseline={"aggregate": 60.0}, docs={"aggregate": 70.0}), + {**_scores("k1", baseline={"aggregate": 10.0}, docs={"aggregate": 90.0}), + "expected_outcome": "ask"}])) + assert [a["question_id"] for a in answers["answers"]] == ["q1"] + assert [e["question_id"] for e in evaluation["evaluations"]] == ["q1"] + + +def test_plugin_delta_pairs_answer_rows_only(): + control = {"evaluations": [_ev("q1", {"docs": 50}), _ev("k1", {"docs": 10}, "ask")]} + plugin = {"evaluations": [_ev("q1", {"docs": 70}), _ev("k1", {"docs": 90}, "ask")]} + assert _score_deltas(control, plugin, ["docs"])["docs"] == { + "n": 1, "baseline_avg_aggregate": 50.0, "plugin_avg_aggregate": 70.0, "aggregate_delta": 20.0} + + +def test_ask_summary_lines_name_the_count_and_each_arms_mean_and_errors(): + summary_ask = {"cells": 2, "per_arm": {"baseline": {"avg_aggregate": 20.0, "n": 2, "errors": 0}, + "docs": {"avg_aggregate": 80.0, "n": 1, "errors": 1}}} + text = "\n".join(ask_summary_lines(summary_ask, ["baseline", "docs"])) + assert "2 ask questions" in text + assert "docs" in text and "80.0" in text and "1 error" in text + + +def test_arms_report_shows_the_ask_block_and_labels_ask_rows(): + data = { + "schema_version": "arms.v1", "library_name": "lib", "model": "m", "provider": "openai", + "arms": ["baseline", "docs"], "baseline_arm": "baseline", "total_questions": 2, + "summary": { + "per_arm": {"baseline": {"avg_aggregate": 60.0, "n": 1, "errors": 0, "delta_vs_baseline": None}, + "docs": {"avg_aggregate": 70.0, "n": 1, "errors": 0, "delta_vs_baseline": 10.0}}, + "ask": {"cells": 1, "per_arm": {"baseline": {"avg_aggregate": 10.0, "n": 1, "errors": 0}, + "docs": {"avg_aggregate": 90.0, "n": 1, "errors": 0}}}}, + "evaluations": [_ev("q1", {"baseline": 60, "docs": 70}), + {**_ev("k1", {"baseline": 10, "docs": 90}, "ask"), "question_text": "Which one?"}], + } + text = render_arms_report(data) + assert "Ask questions" in text and "90.0" in text + assert "Which one? (ask)" in text + + +def test_model_compare_extracts_answer_rows_only(): + from dokimi.report.model_compare import extract_scores + run = {"baseline_arm": "baseline", "evaluations": [ + _ev("q1", {"baseline": 60, "docs": 70}), + _ev("k1", {"baseline": 10, "docs": 90}, "ask")]} + assert [r["question_id"] for r in extract_scores(run)] == ["q1"] + + +def test_eval_report_names_the_ask_count_apart_from_its_statistics(): + from dokimi.report.eval_report import _ask_note + assert _ask_note(0) == [] + assert _ask_note(1)[0].startswith("_1 ask question, graded by the ask rubric") + assert _ask_note(2)[0].startswith("_2 ask questions") From 0bda29128173824890fb02a7e0c6b477c0f6c7be Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 28 Nov 2026 20:55:47 -0800 Subject: [PATCH 05/40] fix(ask): ask rows stay out of every reader's statistics Review of the ask rows found readers that still pooled them: the eval judge and panel-score consoles, report eval's single-condition page, baseline save, the dashboard, the pipeline summary (via paired_summary). A failed panel ask cell lost its ask stamp and was marked grounded. Each reader now leaves ask rows out and says how many, where it prints numbers. Signed-off-by: Nikolay Petrov --- ...25_130000_napetrov_expected-outcome-ask.md | 7 ++- dokimi/dokimi/commands/baseline.py | 6 +-- dokimi/dokimi/commands/evaluate.py | 39 ++++++++------- dokimi/dokimi/dashboard/aggregator.py | 5 +- dokimi/dokimi/eval/judge.py | 6 ++- dokimi/dokimi/eval/panel.py | 7 ++- dokimi/dokimi/eval/stats.py | 5 +- .../dokimi/report/single_condition_report.py | 13 +++-- dokimi/tests/test_ask_readers.py | 47 +++++++++++++++++++ dokimi/tests/test_expected_outcome.py | 4 +- 10 files changed, 107 insertions(+), 32 deletions(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index 3fbe591e46..a25f94a348 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -10,6 +10,11 @@ SPDX-License-Identifier: Apache-2.0 by the ask rubric (clarifying question, targets the ambiguity, avoids guessing) with its own prompt hash (`ASK_JUDGE_PROMPT_SHA256`); `JUDGE_PROMPT_SHA256` is unchanged. The value is stored on answers records and on every eval row. An arm summary's headline (means, deltas, significance) covers answer rows only; ask - rows report their count and means in an `ask` block, and a run with ask rows stamps `ask_judge_prompt_sha256`. The readers that pool evaluations (`arms report`, `arms run` console, `eval report`, `report generate`, `report model-compare`, the plugin delta, the arms-to-binary bridge) leave ask rows out of their statistics; `arms report` and `eval report` say how many were left out. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, + rows report their count and means in an `ask` block, and a run with ask rows stamps `ask_judge_prompt_sha256`. + Every reader that pools evaluations leaves ask rows out of its statistics: `arms report`, the `arms run` + console, `eval report`, `report eval`, the `eval judge` and `eval panel-score` consoles, the plugin delta, the + arms-to-binary bridge, `report model-compare`, the pipeline's step-5 summary, `baseline save` and the dashboard. The readers that print a + count say how many ask rows were left out (`arms report`, `arms run`, `eval report`, `report eval`, `eval judge`, + `eval panel-score`); `report generate`, `baseline save` and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, RAGAS) refuse an `ask` record that has an answer to judge, before any judge call. See `docs/methodology.md` (questions that expect an ask). diff --git a/dokimi/dokimi/commands/baseline.py b/dokimi/dokimi/commands/baseline.py index a9e0118edd..ffb0731ffe 100644 --- a/dokimi/dokimi/commands/baseline.py +++ b/dokimi/dokimi/commands/baseline.py @@ -74,11 +74,11 @@ def _save_manifest(manifest: Dict[str, Any]) -> None: def _compute_summary(eval_data: Dict[str, Any]) -> Dict[str, Any]: """Extract key stats from an eval file.""" - from dokimi.records import BASELINE, CONTEXT, records + from dokimi.records import ASK, BASELINE, CONTEXT, records evals = records(eval_data.get("evaluations", []), source="evaluations", kind="evaluations") - # Unscored arms stay out of the means, as in the trust gate. - valid = [e for e in evals if e.delta is not None + # Unscored arms stay out of the means, as in the trust gate; ask questions are graded by their own rubric. + valid = [e for e in evals if e.expected_outcome != ASK and e.delta is not None and e.score(CONTEXT) is not None and e.score(BASELINE) is not None] if not valid: return {} diff --git a/dokimi/dokimi/commands/evaluate.py b/dokimi/dokimi/commands/evaluate.py index 34c2c3df3d..6c7bd8a079 100644 --- a/dokimi/dokimi/commands/evaluate.py +++ b/dokimi/dokimi/commands/evaluate.py @@ -90,6 +90,28 @@ def _stop_of(answers_meta) -> dict: return {"terminated": answers_meta["terminated"]} if answers_meta.get("terminated") else {} +def _print_panel_summary(results: list) -> None: + """The context arm's own quality, not a comparison. Ask questions have their own rubric: counted, not averaged.""" + from dokimi.records import ASK, CONTEXT, records + + all_rows = list(records(results, kind="evaluations")) + rows = [r for r in all_rows if r.expected_outcome != ASK] + if len(rows) != len(all_rows): + print(f"Ask questions left out (graded by the ask rubric): {len(all_rows) - len(rows)}") + valid = [r.scores[CONTEXT] for r in rows if r.score(CONTEXT) is not None] + if valid: + mean_score = sum(s.aggregate or 0 for s in valid) / len(valid) + # A question judged by one panelist has no spread, so no agreement score. + agreed = [s.agreement for s in valid if s.agreement is not None] + flagged = sum(1 for s in valid if s.raw.get("disagreement_flag", False)) + print(f"\n{'─'*50}") + print(f"Panel score (context arm): {mean_score:.1f}/100") + print("Mean agreement score: " + (f"{sum(agreed) / len(agreed):.3f} (1.0 = perfect)" + if agreed else "n/a")) + print(f"Disagreement flags: {flagged}/{len(valid)} questions") + _print_left_out(rows, valid) + + def cmd_eval_panel_score(args: argparse.Namespace) -> None: """Score answers using a multi-judge panel (parallel, role-diverse judges).""" from dokimi.eval.panel import JudgePanel, JudgeConfig, DEFAULT_PANEL, JUDGE_ROLES @@ -148,22 +170,7 @@ def cmd_eval_panel_score(args: argparse.Namespace) -> None: except OSError as exc: raise InputError(f"cannot write {output_path}: {exc.strerror or exc}") from exc - # Summary: the context arm's own quality, not a comparison. - from dokimi.records import CONTEXT, records - - rows = list(records(results, kind="evaluations")) - valid = [r.scores[CONTEXT] for r in rows if r.score(CONTEXT) is not None] - if valid: - mean_score = sum(s.aggregate or 0 for s in valid) / len(valid) - # A question judged by one panelist has no spread, so no agreement score. - agreed = [s.agreement for s in valid if s.agreement is not None] - flagged = sum(1 for s in valid if s.raw.get("disagreement_flag", False)) - print(f"\n{'─'*50}") - print(f"Panel score (context arm): {mean_score:.1f}/100") - print("Mean agreement score: " + (f"{sum(agreed) / len(agreed):.3f} (1.0 = perfect)" - if agreed else "n/a")) - print(f"Disagreement flags: {flagged}/{len(valid)} questions") - _print_left_out(rows, valid) + _print_panel_summary(results) print(f"\n✅ Saved to {output_path}") diff --git a/dokimi/dokimi/dashboard/aggregator.py b/dokimi/dokimi/dashboard/aggregator.py index d35afb6e67..68f3ee3206 100644 --- a/dokimi/dokimi/dashboard/aggregator.py +++ b/dokimi/dokimi/dashboard/aggregator.py @@ -12,7 +12,7 @@ from pathlib import Path from typing import Any, Dict, List, Mapping, Optional, Union -from dokimi.records import BASELINE, CONTEXT, RecordError, read +from dokimi.records import ASK, BASELINE, CONTEXT, RecordError, read logger = logging.getLogger(__name__) @@ -146,7 +146,8 @@ def _load_snapshot(self, path: Path) -> Optional[ProductSnapshot]: return None try: - recs = read(data, source=str(path), section="evaluations", required=False).records + recs = [r for r in read(data, source=str(path), section="evaluations", required=False).records + if r.expected_outcome != ASK] except RecordError as e: logger.warning(f"Invalid eval file, skipped: {e}") return None diff --git a/dokimi/dokimi/eval/judge.py b/dokimi/dokimi/eval/judge.py index b9bdf59159..f07b4ad2c6 100644 --- a/dokimi/dokimi/eval/judge.py +++ b/dokimi/dokimi/eval/judge.py @@ -360,7 +360,11 @@ def _process(idx: int, answer: Record) -> None: f.result() # wait for completion evaluations = [results[i] for i in range(n)] - valid = [r for r in records(evaluations, kind="evaluations") if r.delta is not None] + judged = list(records(evaluations, kind="evaluations")) + valid = [r for r in judged if r.expected_outcome != ASK and r.delta is not None] + asks = sum(1 for r in judged if r.expected_outcome == ASK) + if asks: + print(f" Ask questions left out (graded by the ask rubric): {asks}", flush=True) if valid: avg_with = sum(r.score(CONTEXT) or 0 for r in valid) / len(valid) avg_without = sum(r.score(BASELINE) or 0 for r in valid) / len(valid) diff --git a/dokimi/dokimi/eval/panel.py b/dokimi/dokimi/eval/panel.py index a901b0ebc6..5e22a2c122 100644 --- a/dokimi/dokimi/eval/panel.py +++ b/dokimi/dokimi/eval/panel.py @@ -464,7 +464,9 @@ def evaluate(self, question: str, answer: str, library_name: str, } for future in as_completed(futures): votes.append(future.result()) - return self._aggregate(votes, grounded=bool(ground_truth), expected_outcome=expected_outcome) + # The ask prompt carries no ground truth, so an ask verdict is never grounded. + grounded = bool(ground_truth) and expected_outcome != ASK + return self._aggregate(votes, grounded=grounded, expected_outcome=expected_outcome) def _aggregate(self, votes: List[JudgeVote], grounded: bool = False, expected_outcome: str = ANSWER) -> PanelVerdict: @@ -474,7 +476,8 @@ def _aggregate(self, votes: List[JudgeVote], grounded: bool = False, valid = [v for v in votes if v.aggregate is not None] if len(valid) < quorum: return PanelVerdict(votes=votes, mean_aggregate=None, std_aggregate=None, - agreement_score=None, quorum=quorum, grounded=grounded) + agreement_score=None, quorum=quorum, grounded=grounded, + expected_outcome=expected_outcome) aggs = [v.aggregate for v in valid if v.aggregate is not None] mean_agg = round(statistics.mean(aggs), 1) # One vote has no spread to measure: report none, not a perfect agreement. diff --git a/dokimi/dokimi/eval/stats.py b/dokimi/dokimi/eval/stats.py index 4f4472e8ce..386867f7e6 100644 --- a/dokimi/dokimi/eval/stats.py +++ b/dokimi/dokimi/eval/stats.py @@ -77,7 +77,7 @@ tie_widths, within, ) -from dokimi.records import BASELINE, CONTEXT, RecordLike, records +from dokimi.records import ASK, BASELINE, CONTEXT, RecordLike, records #: Checked without importing scipy, whose OpenBLAS starts a thread per core #: (~18 CPU-seconds per dokimi call on a 224-core box); :func:`_sp_stats` imports it. @@ -505,7 +505,8 @@ def paired_summary(evaluations: Iterable[RecordLike]) -> PairedSummary: degradation by comparing its two scores, not their difference. """ # https://github.com/intel/dokimi/issues/830 - recs = records(evaluations, source="evaluations", kind="evaluations") + # Ask questions are graded by their own rubric: the pairs are the answer rows. + recs = [r for r in records(evaluations, source="evaluations", kind="evaluations") if r.expected_outcome != ASK] with_s, without_s = paired_vectors(recs, CONTEXT, BASELINE) rows = [(t, c, _pair_delta(t, c)) for t, c in zip(with_s, without_s, strict=True)] deltas = [d for _, _, d in rows if d is not None] diff --git a/dokimi/dokimi/report/single_condition_report.py b/dokimi/dokimi/report/single_condition_report.py index 77dd5c1a4f..3e4f5292e9 100644 --- a/dokimi/dokimi/report/single_condition_report.py +++ b/dokimi/dokimi/report/single_condition_report.py @@ -17,12 +17,13 @@ from dokimi.atomic_write import write_bytes_in_place_or_atomic from dokimi.process_io import text_file_bytes -from dokimi.records import (BASELINE, KNOWLEDGE_INTENT, Record, held_conditions, is_knowledge_run, +from dokimi.records import (ASK, BASELINE, KNOWLEDGE_INTENT, Record, held_conditions, is_knowledge_run, is_single_condition, records) from dokimi.report.eval_report import ( _sibling_answers_path, DIFFICULTY_ORDER, _answers_by_id, + _ask_note, answers_from_items, _difficulty, detect_static_prefix, @@ -74,7 +75,8 @@ def _question_row(q: Record, cond: str) -> str: f"{fmt_question(q.question_text)} |") -def render(evals: Sequence[Record], meta: Dict[str, Any], library: str, generated: str, cond: str) -> List[str]: +def render(evals: Sequence[Record], meta: Dict[str, Any], library: str, generated: str, cond: str, + asks: int = 0) -> List[str]: """The markdown lines of the one-condition report for *evals* (the records of a single-condition run).""" scored = [q for q in evals if q.score(cond) is not None] weakest = sorted(scored, key=lambda q: q.score(cond) or 0.0)[:WEAK_SPOTS] @@ -83,6 +85,7 @@ def render(evals: Sequence[Record], meta: Dict[str, Any], library: str, generate f"_Generated: {generated}_", "", *stop_note(meta), + *_ask_note(asks), "## Run Configuration", "| | |", "|---|---|", @@ -184,7 +187,9 @@ def _declared_intent(data: Dict[str, Any]) -> Any: def write_eval_report(eval_path: str, out_path: str, qa_json_out: Optional[str] = None) -> str: """``report eval``: the one-condition page for a knowledge run, else :func:`eval_report.generate_report`.""" data = _load_eval(eval_path) - evals = records(data["evaluations"], source=eval_path, kind="evaluations") + all_evals = records(data["evaluations"], source=eval_path, kind="evaluations") + evals = [e for e in all_evals if e.expected_outcome != ASK] + asks = len(all_evals) - len(evals) held = held_conditions(evals) # A declared knowledge run keeps its page when nothing was scored (every grade unscored): its one # condition is the baseline, which the declared intent says it answered. @@ -198,7 +203,7 @@ def write_eval_report(eval_path: str, out_path: str, qa_json_out: Optional[str] meta = _report_metadata(data) library = os.path.basename(eval_path).replace(".json", "") generated = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC") - text = "\n".join(render(evals, meta, library, generated, cond)) + text = "\n".join(render(evals, meta, library, generated, cond, asks=asks)) directory = os.path.dirname(out_path) if directory: os.makedirs(directory, exist_ok=True) diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index 0ea8c33871..a2d2637846 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -73,3 +73,50 @@ def test_eval_report_names_the_ask_count_apart_from_its_statistics(): assert _ask_note(0) == [] assert _ask_note(1)[0].startswith("_1 ask question, graded by the ask rubric") assert _ask_note(2)[0].startswith("_2 ask questions") + + +def test_baseline_summary_leaves_ask_rows_out_of_the_means(): + from dokimi.commands.baseline import _compute_summary + + def row(qid, with_, without, outcome=None): + r = {"question_id": qid, "question_text": "q", "with_docs": {"aggregate": with_}, + "without_docs": {"aggregate": without}, "delta": with_ - without} + return {**r, "expected_outcome": outcome} if outcome else r + + summary = _compute_summary({"evaluations": [row("q1", 80, 60), row("k1", 10, 90, "ask")]}) + assert summary == {"n": 1, "avg_with": 80.0, "avg_without": 60.0, "avg_delta": 20.0} + + +def test_dashboard_product_means_leave_ask_rows_out(tmp_path): + from test_records_readers import _dashboard + + [p] = _dashboard(tmp_path, {"library_name": "lib", "evaluations": [ + {"id": 1, "question": "How?", "with_docs": {"aggregate": 80}, "without_docs": {"aggregate": 60}}, + {"id": 2, "question": "Which?", "expected_outcome": "ask", + "with_docs": {"aggregate": 10}, "without_docs": {"aggregate": 90}}, + ]}) + assert [q.question_id for q in p.questions] == [1] + assert (p.avg_with_docs, p.avg_without_docs, p.avg_delta) == (80.0, 60.0, 20.0) + + +def test_panel_quorum_failure_on_an_ask_cell_keeps_the_ask_stamp(): + """A failed ask cell is still an ask cell: its verdict carries the ask rubric hash, not an answer cell's.""" + from dokimi.eval.ask_outcome import ASK, ASK_JUDGE_PROMPT_SHA256 + from dokimi.eval.panel import JudgePanel, JudgeVote, _verdict_to_dict + + failed = JudgeVote(role="r", model="m", provider="p", scores={}, reasoning="", aggregate=None, error="x") + verdict = JudgePanel._aggregate(None, [failed], grounded=False, expected_outcome=ASK) + cell = _verdict_to_dict(verdict) + assert cell["expected_outcome"] == ASK + assert cell["judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 + assert cell["grounded"] is False + + +def test_paired_summary_counts_answer_pairs_only(): + from dokimi.eval.stats import paired_summary + from dokimi.records import BASELINE, CONTEXT + + summary = paired_summary([_ev("q1", {CONTEXT: 80, BASELINE: 60}), + _ev("k1", {CONTEXT: 10, BASELINE: 90}, "ask")]) + assert (summary.paired, summary.total) == (1, 1) + assert summary.delta_mean == 20.0 diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index d0c1115ff9..2d683077ab 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -24,6 +24,7 @@ ) from dokimi.eval.arm_record import question_record from dokimi.eval import arm_runner as arm_runner_module +from dokimi.eval.judge_context import JUDGE_CONTEXT_ARM from dokimi.eval.arm_runner import ArmRunner from dokimi.eval.checklist import run_checklist from dokimi.eval.cross_judge import score_measure @@ -411,7 +412,8 @@ def test_run_stamps_the_ask_rubric_hash_only_when_ask_cells_are_present(monkeypa runner = _summarizing_runner() runner.model, runner.provider, runner.harness = "m", "p", "h" runner.plugin_set = {"plugin_set": "none", "plugin_set_id": "x", "plugins": []} - runner.grounded_from_topics, runner.session_turns, runner.judge_context = False, None, None + runner.grounded_from_topics, runner.session_turns = False, None + runner.judge_context = SimpleNamespace(mode=JUDGE_CONTEXT_ARM) runner.matrix_cell = None for name in ("_run_config", "_cost_summary", "_summarize_agentic_usage"): monkeypatch.setattr(runner, name, lambda *a, **k: {}) From d8987b63d07d985aeb348ef267c6845d5e20ca07 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 28 Nov 2026 21:08:25 -0800 Subject: [PATCH 06/40] fix(ask): baseline compare and its regression gate leave ask rows out The regression gate averaged ask-rubric drops into the answer drop it gates on, so an ask question could fail a run no answer row moved. The plugin delta now warns about the ask rows it leaves out, as the docs say. Signed-off-by: Nikolay Petrov --- ...25_130000_napetrov_expected-outcome-ask.md | 3 +- dokimi/dokimi/commands/baseline.py | 9 ++++-- dokimi/dokimi/eval/plugin_delta.py | 3 ++ dokimi/tests/test_ask_readers.py | 30 +++++++++++++++++++ 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index a25f94a348..16b0da9255 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -15,6 +15,7 @@ SPDX-License-Identifier: Apache-2.0 console, `eval report`, `report eval`, the `eval judge` and `eval panel-score` consoles, the plugin delta, the arms-to-binary bridge, `report model-compare`, the pipeline's step-5 summary, `baseline save` and the dashboard. The readers that print a count say how many ask rows were left out (`arms report`, `arms run`, `eval report`, `report eval`, `eval judge`, - `eval panel-score`); `report generate`, `baseline save` and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, + `eval panel-score`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` + (its regression gate included) and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, RAGAS) refuse an `ask` record that has an answer to judge, before any judge call. See `docs/methodology.md` (questions that expect an ask). diff --git a/dokimi/dokimi/commands/baseline.py b/dokimi/dokimi/commands/baseline.py index ffb0731ffe..ae728bf5c5 100644 --- a/dokimi/dokimi/commands/baseline.py +++ b/dokimi/dokimi/commands/baseline.py @@ -352,12 +352,15 @@ def cmd_baseline_compare(args: argparse.Namespace) -> None: entry = _pick_entry(args, baselines, eval_data) baseline_data = _read_json_object(Path(entry["path"])) - from dokimi.records import records + from dokimi.records import ASK, records # Read both record lists before the model checks: a malformed file is an InputError (exit 2), not the --strict verdict. - baseline_records = records(baseline_data.get("evaluations", []), source=entry["path"], kind="evaluations") + # Ask questions are graded by their own rubric: the compare and the regression gate see the answer rows only. + baseline_records = [e for e in records(baseline_data.get("evaluations", []), source=entry["path"], kind="evaluations") + if e.expected_outcome != ASK] baseline_evals = {e.key: e for e in baseline_records} - current_evals = records(eval_data.get("evaluations", []), source=str(eval_path), kind="evaluations") + current_evals = [e for e in records(eval_data.get("evaluations", []), source=str(eval_path), kind="evaluations") + if e.expected_outcome != ASK] _report_model_checks(args, entry, baseline_data, eval_data) diff --git a/dokimi/dokimi/eval/plugin_delta.py b/dokimi/dokimi/eval/plugin_delta.py index 0e1afd4ac0..e20e9f1711 100644 --- a/dokimi/dokimi/eval/plugin_delta.py +++ b/dokimi/dokimi/eval/plugin_delta.py @@ -151,6 +151,9 @@ def _validate_judge_pair(control: Dict[str, Any], plugin: Dict[str, Any]) -> lis def _warnings(control: Dict[str, Any], plugin: Dict[str, Any]) -> list[str]: warnings: list[str] = [] + asks = sum(1 for side in (control, plugin) for r in _section(side, "evaluations") if r.expected_outcome == ASK) + if asks: + warnings.append(f"{asks} ask question(s) left out of the plugin delta: graded by the ask rubric, not paired") if control.get("plugin_set", "none") != "none": warnings.append( "baseline artifact plugin_set is not 'none'; result is plugin-set delta, " diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index a2d2637846..22cfa6ac81 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -120,3 +120,33 @@ def test_paired_summary_counts_answer_pairs_only(): _ev("k1", {CONTEXT: 10, BASELINE: 90}, "ask")]) assert (summary.paired, summary.total) == (1, 1) assert summary.delta_mean == 20.0 + + +def test_regression_gate_ignores_ask_rows(tmp_path, monkeypatch, capsys): + """An ask question's score drop must not trip the answer regression gate; no answer row moved here.""" + import json + + from dokimi.cli import build_parser + from dokimi.commands import baseline as baseline_mod + + monkeypatch.setattr(baseline_mod, "BASELINES_DIR", tmp_path / "baselines") + + def ev(rows): + return {"judge_provider": "p", "judge_model": "m", "run_metadata": {"answer_provider": "p", + "answer_model": "m"}, + "evaluations": rows} + + answer = {"question_id": "q1", "question_text": "How?", "with_docs": {"aggregate": 80.0}, + "without_docs": {"aggregate": 60.0}, "delta": 20.0} + ask_base = {"question_id": "k1", "question_text": "Which?", "expected_outcome": "ask", + "with_docs": {"aggregate": 90.0}, "without_docs": {"aggregate": 10.0}, "delta": 80.0} + ask_cur = {**ask_base, "with_docs": {"aggregate": 10.0}, "without_docs": {"aggregate": 10.0}, "delta": 0.0} + (tmp_path / "base.json").write_text(json.dumps(ev([answer, ask_base])), encoding="utf-8") + (tmp_path / "cur.json").write_text(json.dumps(ev([answer, ask_cur])), encoding="utf-8") + parser = build_parser() + save = parser.parse_args(["baseline", "save", "--from-eval", str(tmp_path / "base.json"), "--name", "b"]) + save.func(save) + args = parser.parse_args(["baseline", "compare", "--baseline", "b", "--eval", str(tmp_path / "cur.json"), + "--max-context-drop", "5"]) + args.func(args) + assert "No notable changes" in capsys.readouterr().out From 72809cd520eed179c49940d1ec2563498491ab1d Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 28 Nov 2026 21:16:55 -0800 Subject: [PATCH 07/40] fix(ask): cross-judge stored measure, panel ask seed status, plugin warning count The stored cross-judge measure is the answer-rubric measure, so ask rows are left out of it. An ask vote now carries its unsupported-seed status as an answer vote does. The plugin delta warning counts distinct questions. Signed-off-by: Nikolay Petrov --- dokimi/dokimi/eval/cross_judge.py | 4 ++-- dokimi/dokimi/eval/panel.py | 1 + dokimi/dokimi/eval/plugin_delta.py | 4 ++-- dokimi/tests/test_ask_readers.py | 12 ++++++++++++ 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/eval/cross_judge.py b/dokimi/dokimi/eval/cross_judge.py index b2965d038c..5408a2aeef 100644 --- a/dokimi/dokimi/eval/cross_judge.py +++ b/dokimi/dokimi/eval/cross_judge.py @@ -63,7 +63,7 @@ ) from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.question_text import require_question_text -from dokimi.records import Answer, Record, RecordError, RecordLike, Run, arm_answers, arm_scores +from dokimi.records import ASK, Answer, Record, RecordError, RecordLike, Run, arm_answers, arm_scores from dokimi.records import record as as_record from dokimi.records import records as as_records from dokimi.eval.stats import adjust_pvalues, mean_ci @@ -281,7 +281,7 @@ def stored_measure(data: Dict[str, Any], name: Optional[str] = None) -> Optional """ m = Measure(name=name or stored_label(data), kind="aggregate") sources = set() - rows = _unjoined(data, "evaluations") + rows = [r for r in _unjoined(data, "evaluations") if r.expected_outcome != ASK] withheld = isinstance(data, dict) and data.get("judge_context") == PROTOCOL_WITHHELD if withheld and (unverified := _unverified_withheld_arms(rows)): raise InputError(f"withheld judge_context has no proof of empty material for {', '.join(unverified)}. " diff --git a/dokimi/dokimi/eval/panel.py b/dokimi/dokimi/eval/panel.py index 5e22a2c122..2e1e84850b 100644 --- a/dokimi/dokimi/eval/panel.py +++ b/dokimi/dokimi/eval/panel.py @@ -377,6 +377,7 @@ def send(text: str, *, draw: int, cache_if: Callable[[str], bool]) -> str: role=config.role, model=config.model, provider=config.provider, scores=scores, reasoning=str(data.get("reasoning", "")), aggregate=ask_weighted_aggregate(scores), + unsupported_seed=config.unsupported_seed, ) # Hold the prompt's wrong-figure cap in Python, with the single # judge's own rule, so the two cannot disagree about what it means. diff --git a/dokimi/dokimi/eval/plugin_delta.py b/dokimi/dokimi/eval/plugin_delta.py index e20e9f1711..c0a11b9e71 100644 --- a/dokimi/dokimi/eval/plugin_delta.py +++ b/dokimi/dokimi/eval/plugin_delta.py @@ -151,9 +151,9 @@ def _validate_judge_pair(control: Dict[str, Any], plugin: Dict[str, Any]) -> lis def _warnings(control: Dict[str, Any], plugin: Dict[str, Any]) -> list[str]: warnings: list[str] = [] - asks = sum(1 for side in (control, plugin) for r in _section(side, "evaluations") if r.expected_outcome == ASK) + asks = {r.key for side in (control, plugin) for r in _section(side, "evaluations") if r.expected_outcome == ASK} if asks: - warnings.append(f"{asks} ask question(s) left out of the plugin delta: graded by the ask rubric, not paired") + warnings.append(f"{len(asks)} ask question(s) left out of the plugin delta: graded by the ask rubric, not paired") if control.get("plugin_set", "none") != "none": warnings.append( "baseline artifact plugin_set is not 'none'; result is plugin-set delta, " diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index 22cfa6ac81..a18a340ea6 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -150,3 +150,15 @@ def ev(rows): "--max-context-drop", "5"]) args.func(args) assert "No notable changes" in capsys.readouterr().out + + +def test_cross_judge_stored_measure_leaves_ask_rows_out(): + from dokimi.eval.cross_judge import stored_measure + + data = {"evaluations": [ + {"question_id": "q1", "scores": {"baseline": {"aggregate": 60.0}}}, + {"question_id": "k1", "expected_outcome": "ask", "scores": {"baseline": {"aggregate": 10.0}}}, + ]} + measure = stored_measure(data) + assert measure is not None + assert measure.scores == {("q1", "baseline"): 60.0} From 1c2b1cf32316df286c53787d00e7745dc8b60ba8 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 28 Nov 2026 21:29:57 -0800 Subject: [PATCH 08/40] fix(ask): SPDX header on test_ask_readers; questions.v2 accepts null expected_outcome The license header check (.github/.licenserc.yaml, paths **) failed on the new test file. The schema refused null while records.outcome_of reads null as answer. Signed-off-by: Nikolay Petrov --- dokimi/dokimi/schemas/questions.v2.json | 6 +++--- dokimi/tests/test_ask_readers.py | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/dokimi/dokimi/schemas/questions.v2.json b/dokimi/dokimi/schemas/questions.v2.json index ada33160f9..a14862fe70 100644 --- a/dokimi/dokimi/schemas/questions.v2.json +++ b/dokimi/dokimi/schemas/questions.v2.json @@ -193,9 +193,9 @@ "type": "string" }, "expected_outcome": { - "description": "What a correct reply does. `answer` (the default when absent) is graded by the answer rubric. `ask` marks a question with a missing detail the answer depends on: the reply should ask for it, and is graded by the ask rubric (dokimi.eval.ask_outcome). Judge paths with no ask rubric refuse an `ask` record.", - "type": "string", - "enum": ["answer", "ask"] + "description": "What a correct reply does. `answer` (the default when absent or null) is graded by the answer rubric. `ask` marks a question with a missing detail the answer depends on: the reply should ask for it, and is graded by the ask rubric (dokimi.eval.ask_outcome). Judge paths with no ask rubric refuse an `ask` record.", + "type": ["string", "null"], + "enum": ["answer", "ask", null] }, "grading": { "description": "Format-neutral reference checks from an imported eval (`eval import`): `checks` (match, exact, fuzzy, regex, choice, json, judge, unsupported), optional `threshold`, `source_format`, `native_scorer`. Scored by `eval score reference`; see dokimi.eval.reference_checks.", diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index a18a340ea6..38a2661dd7 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -1,3 +1,5 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 """Readers of an arms run's evaluations pool answer rows only; ask rows are shown apart (expected_outcome: ask).""" from dokimi.eval.arms_adapter import to_binary From d00fe7931e6433de253ee5245d94d7d62cee5b2e Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 28 Nov 2026 21:48:27 -0800 Subject: [PATCH 09/40] refactor(judge): one send and redraw helper for the answer and ask paths The duplicate-code ratchet flagged the two nested send/redrawn blocks that _judge_answer and _judge_ask each carried. They become Judge._send_judge and Judge._note_redraw; behaviour is unchanged. Signed-off-by: Nikolay Petrov --- dokimi/dokimi/eval/judge.py | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/dokimi/dokimi/eval/judge.py b/dokimi/dokimi/eval/judge.py index f07b4ad2c6..44a809d3ad 100644 --- a/dokimi/dokimi/eval/judge.py +++ b/dokimi/dokimi/eval/judge.py @@ -559,18 +559,9 @@ def parse(raw: str) -> "tuple[Dict[str, Any], float]": cap_for_wrong_figures(scores) return scores, self._compute_aggregate(scores, weights) - def send(text: str, *, draw: int, cache_if: Callable[[str], bool]) -> str: - response = self.llm.invoke(text, draw=draw, cache_if=cache_if) - self._accumulate_usage(getattr(response, "usage", None)) - return response.content if hasattr(response, "content") else str(response) - - def redrawn() -> None: - with self._usage_lock: - self._redrawn_judgements += 1 - (scores, aggregate), _ = judged_reply( - send, prompt, parse, pinned=self.temperature is not None or self.seed is not None, - draw=draw, label="Judge response", reminder=FORMAT_REMINDER, on_redraw=redrawn) + self._send_judge, prompt, parse, pinned=self.temperature is not None or self.seed is not None, + draw=draw, label="Judge response", reminder=FORMAT_REMINDER, on_redraw=self._note_redraw) # Python computes the aggregate on BOTH paths (the LLM sets aggregate=0 # per instructions). Previously only the grounded path recomputed it and @@ -585,6 +576,16 @@ def redrawn() -> None: return scores + def _send_judge(self, text: str, *, draw: int, cache_if: Callable[[str], bool]) -> str: + """One judge call for ``judged_reply``: the response text, with its usage accumulated.""" + response = self.llm.invoke(text, draw=draw, cache_if=cache_if) + self._accumulate_usage(getattr(response, "usage", None)) + return response.content if hasattr(response, "content") else str(response) + + def _note_redraw(self) -> None: + with self._usage_lock: + self._redrawn_judgements += 1 + def _judge_ask(self, library_name: str, question: str, answer: str, context: str, *, draw: int = 0) -> Dict[str, Any]: """Grade a reply to an ``expected_outcome: ask`` question with the ask rubric. @@ -605,18 +606,9 @@ def parse(raw: str) -> "tuple[Dict[str, Any], float]": self._check_scores(scores, ASK_WEIGHTS.keys()) return scores, ask_weighted_aggregate(scores) - def send(text: str, *, draw: int, cache_if: Callable[[str], bool]) -> str: - response = self.llm.invoke(text, draw=draw, cache_if=cache_if) - self._accumulate_usage(getattr(response, "usage", None)) - return response.content if hasattr(response, "content") else str(response) - - def redrawn() -> None: - with self._usage_lock: - self._redrawn_judgements += 1 - (scores, aggregate), _ = judged_reply( - send, prompt, parse, pinned=self.temperature is not None or self.seed is not None, - draw=draw, label="Judge response", reminder=FORMAT_REMINDER, on_redraw=redrawn) + self._send_judge, prompt, parse, pinned=self.temperature is not None or self.seed is not None, + draw=draw, label="Judge response", reminder=FORMAT_REMINDER, on_redraw=self._note_redraw) # Python computes the aggregate; the judge's own figure, if any, is replaced. scores["aggregate"] = aggregate scores["expected_outcome"] = ASK From 336d3f7ab86a9f7ada66eb4b366c240a125ebaaf Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:17:47 -0800 Subject: [PATCH 10/40] fix(report): retain ask scores and questions Thread: PRRT_kwDOVBg7g869euKf Signed-off-by: Nikolay Petrov --- dokimi/dokimi/report/eval_report.py | 31 +++++++-- .../dokimi/report/single_condition_report.py | 19 +++--- dokimi/dokimi/schemas/report_qa.v1.json | 4 ++ dokimi/tests/test_ask_readers.py | 63 +++++++++++++++++++ 4 files changed, 104 insertions(+), 13 deletions(-) diff --git a/dokimi/dokimi/report/eval_report.py b/dokimi/dokimi/report/eval_report.py index 4951c523ed..3f7c4c509a 100755 --- a/dokimi/dokimi/report/eval_report.py +++ b/dokimi/dokimi/report/eval_report.py @@ -19,6 +19,7 @@ import os import re from collections import Counter, defaultdict +from collections.abc import Sequence from datetime import datetime, timezone from typing import Any @@ -27,6 +28,7 @@ from dokimi.process_io import text_file_bytes # This module defines a local ``stats()`` helper, hence the ``eval_stats`` alias. from dokimi.eval import stats as eval_stats +from dokimi.eval.arm_summary import mean_in_range from dokimi.records import ASK, BASELINE, CONTEXT, Record, RecordError, record, records from dokimi.report.stop_note import stop_note, with_stop @@ -280,15 +282,32 @@ def _ask_note(count: int) -> list[str]: if not count: return [] noun = "question" if count == 1 else "questions" - return [f"_{count} ask {noun}, graded by the ask rubric, are not in the statistics below._", ""] + return [f"_{count} ask {noun}, graded by the ask rubric, appear in their own section below._", ""] + + +def _ask_section(asks: Sequence[Record], conditions: Sequence[tuple[str, str]]) -> list[str]: + if not asks: + return [] + lines = ["## Ask questions (own rubric)", "", f"Questions: {len(asks)}", "", + "| Condition | Scored | Mean |", "|---|---:|---:|"] + for condition, label in conditions: + scores = [score for row in asks if (score := row.score(condition)) is not None] + mean = f"{mean_in_range(scores):.1f}" if scores else "N/A" + lines.append(f"| {label} | {len(scores)} | {mean} |") + labels = " | ".join(label for _, label in conditions) + columns = "|".join("---:" for _ in conditions) + lines += ["", f"| QID | {labels} | Question |", f"|---|{columns}|---|"] + for row in asks: + cells = " | ".join(str(_score_cell(row, condition)) for condition, _ in conditions) + lines.append(f"| {row.question_id} | {cells} | {fmt_question(row.question_text)} |") + return [*lines, ""] def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = None): data = _load_eval(eval_path) all_evals = records(data["evaluations"], source=eval_path, kind="evaluations") - # Ask questions are graded by their own rubric: the statistics are the answer rows, the count is shown. - ask_count = sum(1 for e in all_evals if e.expected_outcome == ASK) + asks = [e for e in all_evals if e.expected_outcome == ASK] evals = [e for e in all_evals if e.expected_outcome != ASK] meta = data.get("run_metadata", {}) library = os.path.basename(eval_path).replace(".json", "") @@ -318,7 +337,7 @@ def generate_report(eval_path: str, out_path: str, qa_json_out: str | None = Non f"_Generated: {datetime.now(tz=_TZ).strftime('%Y-%m-%d %H:%M %Z') if _TZ else datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}_", "", *stop_note(data), - *_ask_note(ask_count), + *_ask_note(len(asks)), "## Run Configuration", "| | |", "|---|---|", @@ -551,6 +570,7 @@ def _val(key): "", ] + lines += _ask_section(asks, [(CONTEXT, "Context arm"), (BASELINE, "Baseline")]) report = "\n".join(lines) dir_path = os.path.dirname(out_path) @@ -569,7 +589,7 @@ def _answer_text(a: Record | None, condition: str): return answer.text if answer is not None else None qa_records = [] - for e in evals: + for e in all_evals: a = answers_by_id.get(e.key) qa_records.append({ "question_id": e.question_id, @@ -579,6 +599,7 @@ def _answer_text(a: Record | None, condition: str): "with_docs_score": e.score(CONTEXT), "without_docs_score": e.score(BASELINE), "delta": e.delta, + **({"expected_outcome": ASK} if e.expected_outcome == ASK else {}), "with_docs_answer": _answer_text(a, CONTEXT), "without_docs_answer": _answer_text(a, BASELINE), }) diff --git a/dokimi/dokimi/report/single_condition_report.py b/dokimi/dokimi/report/single_condition_report.py index 3e4f5292e9..4b0662cae0 100644 --- a/dokimi/dokimi/report/single_condition_report.py +++ b/dokimi/dokimi/report/single_condition_report.py @@ -17,13 +17,14 @@ from dokimi.atomic_write import write_bytes_in_place_or_atomic from dokimi.process_io import text_file_bytes -from dokimi.records import (ASK, BASELINE, KNOWLEDGE_INTENT, Record, held_conditions, is_knowledge_run, +from dokimi.records import (ASK, BASELINE, CONTEXT, KNOWLEDGE_INTENT, Record, held_conditions, is_knowledge_run, is_single_condition, records) from dokimi.report.eval_report import ( _sibling_answers_path, DIFFICULTY_ORDER, _answers_by_id, _ask_note, + _ask_section, answers_from_items, _difficulty, detect_static_prefix, @@ -76,7 +77,7 @@ def _question_row(q: Record, cond: str) -> str: def render(evals: Sequence[Record], meta: Dict[str, Any], library: str, generated: str, cond: str, - asks: int = 0) -> List[str]: + asks: Sequence[Record] = ()) -> List[str]: """The markdown lines of the one-condition report for *evals* (the records of a single-condition run).""" scored = [q for q in evals if q.score(cond) is not None] weakest = sorted(scored, key=lambda q: q.score(cond) or 0.0)[:WEAK_SPOTS] @@ -85,7 +86,7 @@ def render(evals: Sequence[Record], meta: Dict[str, Any], library: str, generate f"_Generated: {generated}_", "", *stop_note(meta), - *_ask_note(asks), + *_ask_note(len(asks)), "## Run Configuration", "| | |", "|---|---|", @@ -123,7 +124,8 @@ def render(evals: Sequence[Record], meta: Dict[str, Any], library: str, generate "(docs/knowledge-runs.md).", "", ] - return lines + label = {BASELINE: "Baseline", CONTEXT: "Context arm"}.get(cond, cond) + return lines + _ask_section(asks, [(cond, label)]) def _report_metadata(data: Dict[str, Any]) -> Dict[str, Any]: @@ -161,6 +163,7 @@ def _answer_text(a: Optional[Record]) -> Optional[str]: "with_docs_score": None, "without_docs_score": e.score(cond), "delta": None, + **({"expected_outcome": ASK} if e.expected_outcome == ASK else {}), "with_docs_answer": None, "without_docs_answer": _answer_text(answers_by_id.get(e.key)), } @@ -189,14 +192,14 @@ def write_eval_report(eval_path: str, out_path: str, qa_json_out: Optional[str] data = _load_eval(eval_path) all_evals = records(data["evaluations"], source=eval_path, kind="evaluations") evals = [e for e in all_evals if e.expected_outcome != ASK] - asks = len(all_evals) - len(evals) - held = held_conditions(evals) + asks = [e for e in all_evals if e.expected_outcome == ASK] + held = held_conditions(all_evals) # A declared knowledge run keeps its page when nothing was scored (every grade unscored): its one # condition is the baseline, which the declared intent says it answered. declared = _declared_intent(data) == KNOWLEDGE_INTENT if not held and declared: cond = BASELINE - elif is_single_condition(evals) and is_knowledge_run(evals, data): + elif is_single_condition(all_evals) and is_knowledge_run(all_evals, data): cond = held[0] else: return generate_report(eval_path, out_path, qa_json_out) @@ -208,7 +211,7 @@ def write_eval_report(eval_path: str, out_path: str, qa_json_out: Optional[str] if directory: os.makedirs(directory, exist_ok=True) write_bytes_in_place_or_atomic(out_path, text_file_bytes(text)) - _write_qa(eval_path, out_path, qa_json_out, evals, meta, data, cond) + _write_qa(eval_path, out_path, qa_json_out, all_evals, meta, data, cond) scored = [s for s in (q.score(cond) for q in evals) if s is not None] print(f"✅ Report written to: {out_path}") print(f" Questions: {len(evals)} ({len(scored)} scored), one condition: {cond}, " diff --git a/dokimi/dokimi/schemas/report_qa.v1.json b/dokimi/dokimi/schemas/report_qa.v1.json index c1ec3c1523..8bd69c569e 100644 --- a/dokimi/dokimi/schemas/report_qa.v1.json +++ b/dokimi/dokimi/schemas/report_qa.v1.json @@ -67,6 +67,10 @@ "integer" ] }, + "expected_outcome": { + "description": "The question's rubric. Writers stamp ask on clarifying-question rows and omit the field on ordinary answer rows.", + "examples": ["answer", "ask"] + }, "question_text": { "type": [ "string", diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index 38a2661dd7..c073a8ac5b 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -2,7 +2,13 @@ # SPDX-License-Identifier: Apache-2.0 """Readers of an arms run's evaluations pool answer rows only; ask rows are shown apart (expected_outcome: ask).""" +import json + +import pytest + from dokimi.eval.arms_adapter import to_binary +from dokimi.report.eval_report import generate_report +from dokimi.report.single_condition_report import write_eval_report from dokimi.eval.plugin_delta import _score_deltas from dokimi.report.arms_report import ask_summary_lines, render_arms_report from test_arms_adapter import _arms, _cell, _question, _scores @@ -164,3 +170,60 @@ def test_cross_judge_stored_measure_leaves_ask_rows_out(): measure = stored_measure(data) assert measure is not None assert measure.scores == {("q1", "baseline"): 60.0} + + +@pytest.mark.parametrize("knowledge", [False, True]) +def test_eval_report_preserves_ask_scores_and_answers(tmp_path, knowledge): + source = tmp_path / "eval" / "run.json" + source.parent.mkdir() + answer_file = tmp_path / "answers" / source.name + answer_file.parent.mkdir() + ask = {"question_id": "k1", "question_text": "Which version?", "expected_outcome": "ask", + "without_docs": {"aggregate": 95.0}} + answer = {"question_id": "q1", "question_text": "How?", "with_docs": {"aggregate": 70.0}, + "without_docs": {"aggregate": 60.0}, "delta": 10.0} + if not knowledge: + ask.update(with_docs={"aggregate": 25.0}, delta=-70.0) + source.write_text(json.dumps({"evaluations": [ask] if knowledge else [answer, ask]})) + answer_file.write_text(json.dumps({"answers": [ + {"question_id": "k1", "expected_outcome": "ask", "without_docs": {"answer": "What version?"}}, + ]})) + out = tmp_path / "report.md" + (write_eval_report if knowledge else generate_report)(str(source), str(out)) + text = out.read_text() + answer_section, ask_section = text.split("## Ask questions (own rubric)") + assert "Which version?" not in answer_section + assert "| Baseline | 1 | 95.0 |" in ask_section + assert "Which version?" in ask_section + if knowledge: + assert "Knowledge Report" in text + assert "Context arm" not in ask_section + else: + assert "| **All** | 1 | 70.0 | 60.0 | **+10.0** |" in answer_section + assert "| Context arm | 1 | 25.0 |" in ask_section + sidecar = json.loads(out.with_suffix(".qa.json").read_text()) + assert sidecar["count"] == (1 if knowledge else 2) + saved_ask = sidecar["records"][-1] + assert saved_ask["expected_outcome"] == "ask" + assert saved_ask["without_docs_score"] == 95.0 + assert saved_ask["without_docs_answer"] == "What version?" + if not knowledge: + assert "expected_outcome" not in sidecar["records"][0] + + +def test_ask_console_counts_and_plugin_warning(capsys): + from dokimi.commands.arms import _print_ask_block + from dokimi.commands.evaluate import _print_panel_summary + from dokimi.eval.plugin_delta import _warnings + + _print_ask_block({"arms": ["baseline"], "summary": {"ask": { + "cells": 1, "per_arm": {"baseline": {"avg_aggregate": 95.0, "n": 1, "errors": 0}}, + }}}) + assert "1 ask question" in capsys.readouterr().out + ask = _ev("k1", {"baseline": 95}, "ask") + _print_panel_summary([ask]) + assert "Ask questions left out (graded by the ask rubric): 1" in capsys.readouterr().out + control = {"evaluations": [ask]} + assert _warnings(control, control) == [ + "1 ask question(s) left out of the plugin delta: graded by the ask rubric, not paired", + ] From d3d98bf1b8febedbba4e0eb0dfd6a60319017950 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:17:47 -0800 Subject: [PATCH 11/40] fix(evaluate): name ask questions in the pipeline summary Thread: PRRT_kwDOVBg7g869euKm Signed-off-by: Nikolay Petrov --- dokimi/dokimi/orchestrator/pipeline.py | 8 ++++++-- dokimi/tests/test_pipeline_summary.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 8c0fba1c80..cdef6fb159 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -15,6 +15,7 @@ answers_method_version as answers_method_version_of) from dokimi.eval.stats import paired_summary from dokimi.mcp.factory import create_doc_source_client, resolve_library_id_for_product +from dokimi.records import ASK, outcome_of from dokimi.utils import InputError, key_bytes, read_json_input, refuse_device, same_evaluator logger = logging.getLogger(__name__) @@ -429,6 +430,9 @@ def run(self, concurrency: int = 5) -> Dict[str, Any]: # Summary stats over the complete pairs, the numbers the reports print for the same file. summary = paired_summary(evaluations) + ask_count = sum(outcome_of(row) == ASK for row in evaluations) + noun = "question" if ask_count == 1 else "questions" + ask_note = f" ({ask_count} ask {noun} left out, own rubric)" if ask_count else "" # Questions scored in one arm only (a retrieval miss is left unjudged, a judge may fail) # are in none of the averages: say how many, so the line is not read as covering all. results["steps"]["evaluation"]["paired"] = summary.paired @@ -447,9 +451,9 @@ def run(self, concurrency: int = 5) -> Dict[str, Any]: + ("delta=none (a paired difference leaves the float range)" if delta_avg is None else f"delta={delta_avg:+.1f}") + (f" (over the {summary.paired} scored in both arms; {summary.unpaired} left out)" - if summary.unpaired else "")) + if summary.unpaired else "") + ask_note) else: - print(f"✓ Evaluated {len(evaluations)} answers (summary unavailable)") + print(f"✓ Evaluated {len(evaluations)} answers (summary unavailable){ask_note}") # Step 6: Generate report logger.info("Step 6/6: Generating report...") diff --git a/dokimi/tests/test_pipeline_summary.py b/dokimi/tests/test_pipeline_summary.py index a2c38ef074..e3bc261747 100644 --- a/dokimi/tests/test_pipeline_summary.py +++ b/dokimi/tests/test_pipeline_summary.py @@ -95,3 +95,16 @@ def test_summary_does_not_say_left_out_when_every_question_is_paired(tmp_path, m printed = capsys.readouterr().out assert "Evaluated 2 answers: context=75.0, baseline=55.0, delta=+20.0" in printed assert "left out" not in printed + + +@pytest.mark.parametrize("with_answer", [True, False]) +def test_summary_says_how_many_ask_questions_it_excludes(tmp_path, monkeypatch, capsys, with_answer): + evaluations = [_evaluation("q1", 80, 60)] if with_answer else [] + evaluations.append({**_evaluation("k1", 10, 90), "expected_outcome": "ask"}) + + result = _run(tmp_path, monkeypatch, evaluations) + + assert result["steps"]["evaluation"]["paired"] == int(with_answer) + line = next(line for line in capsys.readouterr().out.splitlines() if "Evaluated" in line) + assert "1 ask question left out, own rubric" in line + assert ("delta=+20.0" if with_answer else "summary unavailable") in line From b307826e85de293bc8ed577d7048ec9792473f30 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:17:47 -0800 Subject: [PATCH 12/40] fix(judges): skip ask rows in agreement Thread: PRRT_kwDOVBg7g869euKz Signed-off-by: Nikolay Petrov --- dokimi/dokimi/commands/judge_reliability.py | 13 +++++++++++-- dokimi/dokimi/eval/cross_judge.py | 19 +++++++------------ dokimi/tests/test_cross_judge_judge_errors.py | 11 +++++++++++ 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/dokimi/dokimi/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index e23fc4f373..dd8715e719 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -309,6 +309,7 @@ def score(library, question, answer, ground_truth, context): library = args.product or (data.get("library_name") if isinstance(data, dict) else None) or "the library" report = CrossJudgeReport(baseline_arm=baseline, require_validated=args.require_validated) from dokimi.eval.judge_context import JUDGE_CONTEXT_BASELINE, SOURCE_STORED, JudgeContextStore + from dokimi.records import ASK, outcome_of from dokimi.utils import question_id # What the arms run's judge saw, when the file keeps it (judge_materials). Built @@ -346,7 +347,7 @@ def score(library, question, answer, ground_truth, context): if isinstance(r, dict) and isinstance(r.get("arms"), dict) for arm, body in r["arms"].items() if isinstance(body, dict)} for ev in data.get("evaluations") or []: - if not isinstance(ev, dict): + if not isinstance(ev, dict) or outcome_of(ev) == ASK: continue qid = ev.get("question_id") for arm, s in (ev.get("scores") or {}).items(): @@ -390,15 +391,23 @@ def score(library, question, answer, ground_truth, context): from_files += [_result_measure(p, "questions", list, coverage_measure) for p in args.checklist or []] validity = [_load_json_object(v, "summary")["summary"] for v in args.validity or []] specs = [j.strip() for j in (args.judges or "").split(",") if j.strip()] + has_answers_to_score = True if specs: _require_arms(args.answers, records, "eval judge agreement --judges") - scored_answers(records) # refuse a blank question before the probe call + jobs = scored_answers(records) # refuse a blank question before the probe call + ask_count = sum(row.expected_outcome == ASK for row in records) + if ask_count: + noun = "question" if ask_count == 1 else "questions" + print(f"Skipped {ask_count} ask {noun} in judge agreement (own rubric).", file=sys.stderr) + has_answers_to_score = bool(jobs) _check_judge_temperature([(m, p) for p, _, m in (s.partition("/") for s in specs) if m and p in JUDGE_PROVIDERS], args.judge_temperature) for spec in dict.fromkeys(specs): provider, _, model = spec.partition("/") if not model or provider not in JUDGE_PROVIDERS: raise InputError(f"--judges entry '{spec}' must be provider/model, provider in {JUDGE_PROVIDERS}") + if not has_answers_to_score: + continue warn_recorded_self_judge(data, [(model, provider)], "eval judge agreement") print(f"Scoring with {spec} ...", flush=True) judge = Judge(model=model, provider=provider, temperature=args.judge_temperature) diff --git a/dokimi/dokimi/eval/cross_judge.py b/dokimi/dokimi/eval/cross_judge.py index 5408a2aeef..0a2a46a7d4 100644 --- a/dokimi/dokimi/eval/cross_judge.py +++ b/dokimi/dokimi/eval/cross_judge.py @@ -61,7 +61,6 @@ from dokimi.eval.judge_context import ( JUDGE_CONTEXT_BASELINE, PROTOCOL_WITHHELD, SOURCE_STORED, SOURCE_WITHHELD, JudgeContextStore, ) -from dokimi.eval.ask_outcome import require_judgeable_outcome from dokimi.eval.question_text import require_question_text from dokimi.records import ASK, Answer, Record, RecordError, RecordLike, Run, arm_answers, arm_scores from dokimi.records import record as as_record @@ -249,14 +248,15 @@ def unreproducible_arms(data: Dict[str, Any]) -> List[str]: see the same thing. """ if isinstance(data, dict) and data.get("judge_context") == PROTOCOL_WITHHELD: - return _unverified_withheld_arms(_unjoined(data, "evaluations", skip_malformed=True)) + return _unverified_withheld_arms([r for r in _unjoined(data, "evaluations", skip_malformed=True) + if r.expected_outcome != ASK]) kinds = { arm: (a.raw.get("metadata") or {}).get("arm_kind") for r in _unjoined(data, "answers", skip_malformed=True) for arm, a in arm_answers(r).items() } return sorted({ arm for r in _unjoined(data, "evaluations", skip_malformed=True) for arm, s in arm_scores(r).items() - if s.raw.get("judge_context_source") == SOURCE_STORED + if r.expected_outcome != ASK and s.raw.get("judge_context_source") == SOURCE_STORED and kinds.get(arm) != "baseline" }) @@ -354,24 +354,19 @@ def scored_answers( ) -> List[Tuple[Record, str, Answer, str]]: """The (record, arm, answer, question) answers :func:`score_measure` sends to a judge. - Pure: no judge call. Raises :class:`EmptyQuestionError` for a record with an + Ask rows are outside this comparison. Pure: no judge call. Raises :class:`EmptyQuestionError` for a record with an answer to score and no question text; a record with only empty answers is skipped, not refused. """ return [ - (r, arm, a, _judged_question(r, i)) + (r, arm, a, require_question_text(r.raw, i)) for i, r in enumerate(as_records(records, source="answers", kind="answers")) + if r.expected_outcome != ASK for arm, a in arm_answers(r).items() if a.text and (arms is None or arm in arms) ] -def _judged_question(r: Record, i: int) -> str: - """The question of a record whose answer is about to be judged; refused if it has none, or expects an ask.""" - require_judgeable_outcome([r.raw], "the cross-judge score") - return require_question_text(r.raw, i) - - def score_measure( records: Sequence[RecordLike], scorer: Scorer, *, name: str, library: str, arms: Optional[Sequence[str]] = None, concurrency: int = 1, @@ -379,7 +374,7 @@ def score_measure( ground_truth: Optional[Dict[str, str]] = None, store: Optional[JudgeContextStore] = None, ) -> Measure: - """Score every answer; with ``ground_truth`` (question_id -> text), grounded. + """Score every answer-mode response; with ``ground_truth`` (question_id -> text), grounded. Grounding in the golden set's expected points narrowed the spread across judges: on the perf skill arm, Haiku, gpt-oss and Sonnet 5 spanned diff --git a/dokimi/tests/test_cross_judge_judge_errors.py b/dokimi/tests/test_cross_judge_judge_errors.py index 350944622a..24f3b31c3b 100644 --- a/dokimi/tests/test_cross_judge_judge_errors.py +++ b/dokimi/tests/test_cross_judge_judge_errors.py @@ -178,3 +178,14 @@ def test_every_measure_of_a_dead_judge_is_named(tmp_path, monkeypatch, capsys, b assert code == 1 # a dead judge is a run failure assert ("anthropic/m (aggregate) scored none" in err) is both assert "anthropic/m (grounded) scored none" in err + + +def test_agreement_skips_ask_rows_and_counts_them(tmp_path, monkeypatch, capsys): + answer, ask = _records(2) + ask["expected_outcome"] = "ask" + data = {"library_name": "L", "answers": [answer, ask]} + code, _ = _cross_judge(tmp_path, monkeypatch, {"b1", "s1"}, "--no-stored", data=data) + assert code == 0 + stderr = capsys.readouterr().err + assert "Skipped 1 ask question in judge agreement (own rubric)." in stderr + assert KEY_ERROR not in stderr From acf1fa86d3abce0a8c93b48dcc3467896e1a137d Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:17:47 -0800 Subject: [PATCH 13/40] docs(artifacts): describe ask fields in answers and arms Thread: PRRT_kwDOVBg7g869euK0 Signed-off-by: Nikolay Petrov --- dokimi/dokimi/schemas/answers.v1.json | 4 +++ dokimi/dokimi/schemas/arms.v1.json | 35 +++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/schemas/answers.v1.json b/dokimi/dokimi/schemas/answers.v1.json index 7a536d8481..aa0ce344c3 100644 --- a/dokimi/dokimi/schemas/answers.v1.json +++ b/dokimi/dokimi/schemas/answers.v1.json @@ -56,6 +56,10 @@ "integer" ] }, + "expected_outcome": { + "description": "The question's rubric. Writers stamp ask on clarifying-question rows and omit the field on ordinary answer rows.", + "examples": ["answer", "ask"] + }, "question_text": { "type": "string" }, diff --git a/dokimi/dokimi/schemas/arms.v1.json b/dokimi/dokimi/schemas/arms.v1.json index 17b461fe4c..a7dc7b5b2e 100644 --- a/dokimi/dokimi/schemas/arms.v1.json +++ b/dokimi/dokimi/schemas/arms.v1.json @@ -57,6 +57,9 @@ "null" ] }, + "ask_judge_prompt_sha256": { + "description": "The sha256: fingerprint of the rubric used for clarifying-question cells; written when summary.ask is present." + }, "judge_resolved_models": { "type": "array", "items": { @@ -109,10 +112,12 @@ }, "answers": { "type": "array", - "description": "One record per question: answers[].arms. is that arm's answer. A single-turn answer the model gave carries replayed (boolean): true when the response cache (DOKIMI_RESPONSE_CACHE) served it instead of a model call, a repeat of an earlier run's answer rather than a fresh sample. Error cells (no answer, never cached), session and agentic answers (which never go through the cache) and files written before the flag have no replayed (issue #370)." + "description": "One record per question: answers[].arms. is that arm's answer. A single-turn answer the model gave carries replayed (boolean): true when the response cache (DOKIMI_RESPONSE_CACHE) served it instead of a model call, a repeat of an earlier run's answer rather than a fresh sample. Error cells (no answer, never cached), session and agentic answers (which never go through the cache) and files written before the flag have no replayed (issue #370).", + "items": {"$ref": "#/$defs/question_outcome"} }, "evaluations": { - "type": "array" + "type": "array", + "items": {"$ref": "#/$defs/question_outcome"} }, "summary": { "type": "object", @@ -275,6 +280,22 @@ } } }, + "ask": { + "description": "Clarifying-question results. These scores use the ask rubric and have their own means.", + "properties": { + "cells": {"description": "Number of ask questions, including questions with missing scores."}, + "per_arm": { + "description": "Per-arm score coverage across the ask questions.", + "additionalProperties": { + "properties": { + "avg_aggregate": {"description": "Mean of scored ask cells, or null if none scored."}, + "n": {"description": "Number of scored ask cells used in the mean."}, + "errors": {"description": "Number of ask cells whose answer or judge raised an error."} + } + } + } + } + }, "significance_error": { "description": "Why per_arm..significance is absent from every arm: the paired tests of the arm family refused the scores (a difference or a sum of differences beyond the float range). Present only on such a refusal; an arm with too few pairs for the family leaves the others' significance in place.", "type": "string" @@ -443,6 +464,16 @@ } } }, + "$defs": { + "question_outcome": { + "properties": { + "expected_outcome": { + "description": "The question's rubric. Writers stamp ask on clarifying-question rows and omit the field on ordinary answer rows.", + "examples": ["answer", "ask"] + } + } + } + }, "allOf": [ { "if": { From dbcbc3307cce5f6f497f3d69c5bd5d76bb48f2d9 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:17:47 -0800 Subject: [PATCH 14/40] test(eval): cover a partial ask pair and original refusal index Thread: PRRT_kwDOVBg7g869euKr Thread: PRRT_kwDOVBg7g869euK4 Thread: PRR_kwDOVBg7g88AAAABbELB0Q Signed-off-by: Nikolay Petrov --- ...25_130000_napetrov_expected-outcome-ask.md | 7 ++-- dokimi/dokimi/eval/ask_outcome.py | 4 +-- dokimi/dokimi/eval/checklist.py | 2 +- dokimi/dokimi/eval/degrade.py | 2 +- dokimi/dokimi/eval/pairwise.py | 2 +- dokimi/dokimi/eval/ragas_eval.py | 4 +-- dokimi/tests/test_expected_outcome.py | 32 ++++++++++++++++--- 7 files changed, 39 insertions(+), 14 deletions(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index 16b0da9255..fd1b1df4a7 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -15,7 +15,8 @@ SPDX-License-Identifier: Apache-2.0 console, `eval report`, `report eval`, the `eval judge` and `eval panel-score` consoles, the plugin delta, the arms-to-binary bridge, `report model-compare`, the pipeline's step-5 summary, `baseline save` and the dashboard. The readers that print a count say how many ask rows were left out (`arms report`, `arms run`, `eval report`, `report eval`, `eval judge`, - `eval panel-score`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` - (its regression gate included) and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, cross-judge, degradation pairs, + `eval panel-score`, the pipeline summary, `eval judge agreement --judges`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` + (its regression gate included) and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, degradation pairs, RAGAS) refuse an `ask` record that has an answer to judge, before any judge call. See - `docs/methodology.md` (questions that expect an ask). + `docs/methodology.md` (questions that expect an ask). The eval report includes separate ask scores and + preserves ask rows in its Q&A JSON sidecar. diff --git a/dokimi/dokimi/eval/ask_outcome.py b/dokimi/dokimi/eval/ask_outcome.py index 6694be7789..3dcd82a272 100644 --- a/dokimi/dokimi/eval/ask_outcome.py +++ b/dokimi/dokimi/eval/ask_outcome.py @@ -45,13 +45,13 @@ def _has_answer_to_judge(record: Mapping[str, Any]) -> bool: return any(a.text for a in as_record(record).answers.values()) -def require_judgeable_outcome(records: Iterable[Mapping[str, Any]], path: str) -> None: +def require_judgeable_outcome(records: Iterable[Mapping[str, Any]], path: str, *, start: int = 0) -> None: """Refuse an ask record on a path that has no ask rubric, before any judge call. Only a record with an answer to judge is refused; one the path would skip anyway is not. ``path`` names the judge in the message. """ - for i, record in enumerate(records): + for i, record in enumerate(records, start=start): if outcome_of(record, i) == ASK and _has_answer_to_judge(record): qid = record.get("question_id") where = f"question {qid!r}" if qid is not None else f"record #{i}" diff --git a/dokimi/dokimi/eval/checklist.py b/dokimi/dokimi/eval/checklist.py index 73dc9d1273..265003e228 100644 --- a/dokimi/dokimi/eval/checklist.py +++ b/dokimi/dokimi/eval/checklist.py @@ -310,7 +310,7 @@ def checklist_jobs( if a.text and (arms is None or arm in arms)] # Only a record that would be judged must carry a question; the others keep what they have. if pending: - require_judgeable_outcome([rec.raw], "checklist") + require_judgeable_outcome([rec.raw], "checklist", start=i) question = require_question_text(rec.raw, i) if pending else rec.question_text if report is not None: report.questions[qid] = question diff --git a/dokimi/dokimi/eval/degrade.py b/dokimi/dokimi/eval/degrade.py index 6d8f908903..5955b2ef0a 100644 --- a/dokimi/dokimi/eval/degrade.py +++ b/dokimi/dokimi/eval/degrade.py @@ -654,7 +654,7 @@ def build_pairs( # row that can become a base is checked (not only the drawn bases), so the outcome does not # depend on the seed; a row dropped for missing judge material is never judged. for row in long_answers: - require_judgeable_outcome([row["_record"][0]], "the degradation pairs") + require_judgeable_outcome([row["_record"][0]], "the degradation pairs", start=row["_record"][1]) if not row["question_text"].strip(): require_question_text(*row["_record"]) bases = long_answers[:n_bases] diff --git a/dokimi/dokimi/eval/pairwise.py b/dokimi/dokimi/eval/pairwise.py index a852c32306..f4a2403eb8 100644 --- a/dokimi/dokimi/eval/pairwise.py +++ b/dokimi/dokimi/eval/pairwise.py @@ -276,7 +276,7 @@ def pairwise_jobs( continue for arm, a in by_arm.items(): if arm != baseline_arm and a.text and (arms is None or arm in arms): - require_judgeable_outcome([rec.raw], "pairwise") + require_judgeable_outcome([rec.raw], "pairwise", start=i) jobs.append((arm, rec.question_id, require_question_text(rec.raw, i), a.text, base)) return jobs diff --git a/dokimi/dokimi/eval/ragas_eval.py b/dokimi/dokimi/eval/ragas_eval.py index 034dcd6071..e3fd6492b0 100644 --- a/dokimi/dokimi/eval/ragas_eval.py +++ b/dokimi/dokimi/eval/ragas_eval.py @@ -150,7 +150,7 @@ def evaluate( wd = rec.answer(CONTEXT) if wd is not None and wd.text and wd.context: # Rows are all built before the first RAGAS call: refuse, do not grade against "". - require_judgeable_outcome([rec.raw], "RAGAS") + require_judgeable_outcome([rec.raw], "RAGAS", start=i) require_question_text(rec.raw, i) row: Dict[str, Any] = { "user_input": q, @@ -166,7 +166,7 @@ def evaluate( if include_without_docs and "answer_relevancy" in self._requested: wod = rec.answer(BASELINE) if wod is not None and wod.text: - require_judgeable_outcome([rec.raw], "RAGAS") + require_judgeable_outcome([rec.raw], "RAGAS", start=i) require_question_text(rec.raw, i) rows_without.append({ "user_input": q, diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 2d683077ab..99a77ff5d5 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -185,6 +185,22 @@ def test_answerer_pair_carries_the_outcome_of_its_question(): assert "expected_outcome" not in plain +def test_answerer_preserves_the_outcome_when_only_context_succeeded(): + from dokimi.eval.answerer import Answerer + + answerer = Answerer.__new__(Answerer) + answerer.mcp_client = object() + answerer._retrieve_docs = MagicMock(return_value=([{"snippet": "s"}], {})) + answerer._generate_with_docs = MagicMock(return_value={"answer": REPLY}) + answerer._generate_without_docs = MagicMock(side_effect=RuntimeError("baseline unavailable")) + [pair] = answerer.generate_answers("lib", "lib/id", [{"question": ASK_QUESTION, "id": "k1", + "expected_outcome": "ask"}]) + assert pair["expected_outcome"] == "ask" + assert pair["with_docs"]["answer"] == REPLY + assert pair["without_docs"] is None + assert pair["error"] == "baseline unavailable" + + # ── Judge: the rubric is routed on the record's outcome ────────────────── def test_judge_asks_the_ask_rubric_and_stamps_its_hash(): @@ -313,11 +329,19 @@ def test_checklist_refuses_an_ask_record_before_judging(): ask.assert_not_called() -def test_score_measure_refuses_an_ask_record_before_judging(): +def test_score_measure_only_scores_answer_questions(): scorer = MagicMock(return_value=50.0) - with pytest.raises(AskOutcomeError, match="'q1'"): - score_measure([_arms_record("q1", ASK_QUESTION, "ask")], scorer, name="j", library="lib") - scorer.assert_not_called() + measure = score_measure([_arms_record("k1", ASK_QUESTION, "ask"), + _arms_record("q1", "How do I fit?")], scorer, name="j", library="lib") + assert measure.scores == {("q1", "baseline"): 50.0, ("q1", "skill"): 50.0} + assert scorer.call_count == 2 + assert all(call.args[1] == "How do I fit?" for call in scorer.call_args_list) + + +def test_refusal_names_the_original_index_for_anonymous_ask(): + row = {"id": "legacy", "without_docs": {"answer": REPLY}, "expected_outcome": "ask"} + with pytest.raises(AskOutcomeError, match="record #1"): + require_judgeable_outcome([row], "checklist", start=1) def test_degradation_pairs_refuse_an_ask_record_before_judging(): From c0ecc74960fa64de5a027dd9160cbaae65cdbad3 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:19:38 -0800 Subject: [PATCH 15/40] docs(artifacts): keep arms row schemas open Thread: PRRT_kwDOVBg7g869euK0 Signed-off-by: Nikolay Petrov --- dokimi/dokimi/schemas/arms.v1.json | 31 ++++-------------------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/dokimi/dokimi/schemas/arms.v1.json b/dokimi/dokimi/schemas/arms.v1.json index a7dc7b5b2e..42eb16dbf5 100644 --- a/dokimi/dokimi/schemas/arms.v1.json +++ b/dokimi/dokimi/schemas/arms.v1.json @@ -112,12 +112,11 @@ }, "answers": { "type": "array", - "description": "One record per question: answers[].arms. is that arm's answer. A single-turn answer the model gave carries replayed (boolean): true when the response cache (DOKIMI_RESPONSE_CACHE) served it instead of a model call, a repeat of an earlier run's answer rather than a fresh sample. Error cells (no answer, never cached), session and agentic answers (which never go through the cache) and files written before the flag have no replayed (issue #370).", - "items": {"$ref": "#/$defs/question_outcome"} + "description": "One record per question: answers[].arms. is that arm's answer. A single-turn answer the model gave carries replayed (boolean): true when the response cache (DOKIMI_RESPONSE_CACHE) served it instead of a model call, a repeat of an earlier run's answer rather than a fresh sample. Error cells (no answer, never cached), session and agentic answers (which never go through the cache) and files written before the flag have no replayed (issue #370). Answers may carry expected_outcome: ask for a clarifying question or answer (the default when absent)." }, "evaluations": { "type": "array", - "items": {"$ref": "#/$defs/question_outcome"} + "description": "One grade record per question. Rows use expected_outcome: ask for a clarifying question or answer (the default when absent)." }, "summary": { "type": "object", @@ -281,20 +280,8 @@ } }, "ask": { - "description": "Clarifying-question results. These scores use the ask rubric and have their own means.", - "properties": { - "cells": {"description": "Number of ask questions, including questions with missing scores."}, - "per_arm": { - "description": "Per-arm score coverage across the ask questions.", - "additionalProperties": { - "properties": { - "avg_aggregate": {"description": "Mean of scored ask cells, or null if none scored."}, - "n": {"description": "Number of scored ask cells used in the mean."}, - "errors": {"description": "Number of ask cells whose answer or judge raised an error."} - } - } - } - } + "description": "Clarifying-question results. cells counts ask questions, including questions with missing scores. per_arm is keyed by arm and holds avg_aggregate (mean of scored ask cells, or null if none scored), n (number of scored cells), and errors (number of cells whose answer or judge raised an error).", + "examples": [{"cells": 2, "per_arm": {"baseline": {"avg_aggregate": 70.0, "n": 1, "errors": 1}}}] }, "significance_error": { "description": "Why per_arm..significance is absent from every arm: the paired tests of the arm family refused the scores (a difference or a sum of differences beyond the float range). Present only on such a refusal; an arm with too few pairs for the family leaves the others' significance in place.", @@ -464,16 +451,6 @@ } } }, - "$defs": { - "question_outcome": { - "properties": { - "expected_outcome": { - "description": "The question's rubric. Writers stamp ask on clarifying-question rows and omit the field on ordinary answer rows.", - "examples": ["answer", "ask"] - } - } - } - }, "allOf": [ { "if": { From 5e667da6749035f141b674b1bd29f5a0aecb3fe3 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:22:36 -0800 Subject: [PATCH 16/40] refactor(eval): keep summary and judge changes within growth limits Thread: PRRT_kwDOVBg7g869euKm Thread: PRRT_kwDOVBg7g869euKz Signed-off-by: Nikolay Petrov --- dokimi/dokimi/commands/judge_reliability.py | 45 ++++++++++++--------- dokimi/dokimi/orchestrator/pipeline.py | 8 +--- dokimi/scripts/growth_baseline.json | 2 +- 3 files changed, 29 insertions(+), 26 deletions(-) diff --git a/dokimi/dokimi/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index dd8715e719..1dc8772b31 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -282,10 +282,34 @@ def progress(cond: str, done: int, total: int) -> None: sys.exit(1) +def _agreement_judge_specs(args: argparse.Namespace, records): + """Validate judges on the CLI and report which questions are outside agreement.""" + from dokimi.eval.cross_judge import scored_answers + from dokimi.records import ASK + + specs = [j.strip() for j in (args.judges or "").split(",") if j.strip()] + if not specs: + return + _require_arms(args.answers, records, "eval judge agreement --judges") + jobs = scored_answers(records) # refuse a blank question before the probe call + ask_count = sum(row.expected_outcome == ASK for row in records) + if ask_count: + noun = "question" if ask_count == 1 else "questions" + print(f"Skipped {ask_count} ask {noun} in judge agreement (own rubric).", file=sys.stderr) + _check_judge_temperature([(m, p) for p, _, m in (s.partition("/") for s in specs) if m and p in JUDGE_PROVIDERS], + args.judge_temperature) + for spec in dict.fromkeys(specs): + provider, _, model = spec.partition("/") + if not model or provider not in JUDGE_PROVIDERS: + raise InputError(f"--judges entry '{spec}' must be provider/model, provider in {JUDGE_PROVIDERS}") + if jobs or not ask_count: + yield spec, provider, model + + def cmd_eval_cross_judge(args: argparse.Namespace) -> None: """Score the same arms under several judges and label each arm's verdict.""" from dokimi.eval.cross_judge import ( - CrossJudgeReport, coverage_measure, pairwise_measure, score_measure, scored_answers, + CrossJudgeReport, coverage_measure, pairwise_measure, score_measure, stored_measure, unreproducible_arms, ) from dokimi.eval.question_text import ground_truth_from_topics @@ -390,24 +414,7 @@ def score(library, question, answer, ground_truth, context): for p in args.pairwise or []] from_files += [_result_measure(p, "questions", list, coverage_measure) for p in args.checklist or []] validity = [_load_json_object(v, "summary")["summary"] for v in args.validity or []] - specs = [j.strip() for j in (args.judges or "").split(",") if j.strip()] - has_answers_to_score = True - if specs: - _require_arms(args.answers, records, "eval judge agreement --judges") - jobs = scored_answers(records) # refuse a blank question before the probe call - ask_count = sum(row.expected_outcome == ASK for row in records) - if ask_count: - noun = "question" if ask_count == 1 else "questions" - print(f"Skipped {ask_count} ask {noun} in judge agreement (own rubric).", file=sys.stderr) - has_answers_to_score = bool(jobs) - _check_judge_temperature([(m, p) for p, _, m in (s.partition("/") for s in specs) if m and p in JUDGE_PROVIDERS], - args.judge_temperature) - for spec in dict.fromkeys(specs): - provider, _, model = spec.partition("/") - if not model or provider not in JUDGE_PROVIDERS: - raise InputError(f"--judges entry '{spec}' must be provider/model, provider in {JUDGE_PROVIDERS}") - if not has_answers_to_score: - continue + for spec, provider, model in _agreement_judge_specs(args, records): warn_recorded_self_judge(data, [(model, provider)], "eval judge agreement") print(f"Scoring with {spec} ...", flush=True) judge = Judge(model=model, provider=provider, temperature=args.judge_temperature) diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index cdef6fb159..0e5840e820 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -15,7 +15,6 @@ answers_method_version as answers_method_version_of) from dokimi.eval.stats import paired_summary from dokimi.mcp.factory import create_doc_source_client, resolve_library_id_for_product -from dokimi.records import ASK, outcome_of from dokimi.utils import InputError, key_bytes, read_json_input, refuse_device, same_evaluator logger = logging.getLogger(__name__) @@ -430,11 +429,8 @@ def run(self, concurrency: int = 5) -> Dict[str, Any]: # Summary stats over the complete pairs, the numbers the reports print for the same file. summary = paired_summary(evaluations) - ask_count = sum(outcome_of(row) == ASK for row in evaluations) - noun = "question" if ask_count == 1 else "questions" - ask_note = f" ({ask_count} ask {noun} left out, own rubric)" if ask_count else "" - # Questions scored in one arm only (a retrieval miss is left unjudged, a judge may fail) - # are in none of the averages: say how many, so the line is not read as covering all. + ask_count = len(evaluations) - summary.total + ask_note = f" ({ask_count} ask question{'s' if ask_count != 1 else ''} left out, own rubric)" if ask_count else "" results["steps"]["evaluation"]["paired"] = summary.paired results["steps"]["evaluation"]["unpaired"] = summary.unpaired diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index 2ccd7c396e..df7e6d7b43 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -18,7 +18,7 @@ "dokimi/commands/benchmark.py::cmd_benchmark_preflight": {"complexity": 12}, "dokimi/commands/catalog.py::cmd_catalog_trigger_set": {"complexity": 14}, "dokimi/commands/evaluate.py::cmd_eval_judge_validity": {"complexity": 13}, - "dokimi/commands/judge_reliability.py::cmd_eval_cross_judge": {"complexity": 29, "rationale": "pre-existing when the gate was introduced"}, + "dokimi/commands/judge_reliability.py::cmd_eval_cross_judge": {"complexity": 27, "rationale": "pre-existing when the gate was introduced"}, "dokimi/commands/report.py::cmd_report_model_compare": {"complexity": 12}, "dokimi/commands/tools.py::cmd_tools_preference": {"complexity": 11}, "dokimi/context/trace.py::_apply": {"complexity": 15}, From c093068da35b86f07633404e93a4d3e2e05f9052 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:24:50 -0800 Subject: [PATCH 17/40] test(judges): cover agreement with only ask questions Thread: PRRT_kwDOVBg7g869euKz Signed-off-by: Nikolay Petrov --- ...125_130000_napetrov_expected-outcome-ask.md | 2 +- dokimi/docs/methodology.md | 4 ++-- dokimi/tests/test_cross_judge_judge_errors.py | 18 ++++++++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index fd1b1df4a7..54e6c2bb8c 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -17,6 +17,6 @@ SPDX-License-Identifier: Apache-2.0 count say how many ask rows were left out (`arms report`, `arms run`, `eval report`, `report eval`, `eval judge`, `eval panel-score`, the pipeline summary, `eval judge agreement --judges`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` (its regression gate included) and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, degradation pairs, - RAGAS) refuse an `ask` record that has an answer to judge, before any judge call. See + RAGAS, `eval score reference`) refuse an `ask` record that has an answer to judge, before any judge call. See `docs/methodology.md` (questions that expect an ask). The eval report includes separate ask scores and preserves ask rows in its Q&A JSON sidecar. diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index 7195f650bf..bd0ae654be 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -214,9 +214,9 @@ A question with `expected_outcome: ask` is one a good assistant answers by askin The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_PROMPT_SHA256` does not change, so answer-mode results keep their stamp. A judged ask row carries `expected_outcome: ask` and the ask rubric's hash; the rubric judges (the single judge, the panel, `arms run --judge`) route on the value. -The paths that compare answers with each other or with expected points (pairwise, checklist, cross-judge, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. +The paths that compare answers with each other or with expected points (pairwise, checklist, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. `eval judge agreement --judges` counts and skips ask rows so its stored and rescored measures cover answer rows. -**Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask questions the run has, errored ones included) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it; `arms report` and the `arms run` console print the block apart. The binary payloads (`to_binary`, which feed `answers.v1`/`eval.v1`) and the plugin delta leave ask questions out, and warn when they do. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. +**Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask questions the run has, errored ones included) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it; `arms report` and the `arms run` console print the block apart. The paired and knowledge eval reports give ask grades their own section and retain them in the Q&A sidecar. The binary payloads (`to_binary`, which feed `answers.v1`/`eval.v1`) and the plugin delta leave ask questions out, and warn when they do. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. **Panel agreement.** Every panel role gets the same ask prompt, so agreement between roles on ask rows measures sampling noise on one prompt, not independent judgement. Read it as a noise floor, not as evidence that the ask rubric is reliable. diff --git a/dokimi/tests/test_cross_judge_judge_errors.py b/dokimi/tests/test_cross_judge_judge_errors.py index 24f3b31c3b..36a382e807 100644 --- a/dokimi/tests/test_cross_judge_judge_errors.py +++ b/dokimi/tests/test_cross_judge_judge_errors.py @@ -189,3 +189,21 @@ def test_agreement_skips_ask_rows_and_counts_them(tmp_path, monkeypatch, capsys) stderr = capsys.readouterr().err assert "Skipped 1 ask question in judge agreement (own rubric)." in stderr assert KEY_ERROR not in stderr + + +def test_agreement_with_only_ask_rows_refuses_before_building_a_judge(tmp_path, monkeypatch, capsys): + from dokimi.utils import InputError + + def unexpected_judge(**kwargs): + pytest.fail("the ask-only file must not be sent to a judge") + + monkeypatch.setattr(judge_mod, "Judge", unexpected_judge) + [ask] = _records(1) + ask["expected_outcome"] = "ask" + answers = tmp_path / "run.json" + answers.write_text(json.dumps({"answers": [ask]}), encoding="utf-8") + args = build_parser().parse_args(["eval", "judge", "agreement", "--answers", str(answers), + "--judges", "anthropic/m"]) + with pytest.raises(InputError, match="nothing to compare"): + args.func(args) + assert "Skipped 1 ask question" in capsys.readouterr().err From c6704d1a1bbedfbc58c6a352d2508d791beea33a Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 09:46:37 -0800 Subject: [PATCH 18/40] fix(ragas): surface ask input refusals in the CLI Thread: PRRT_kwDOVBg7g869pSBt Signed-off-by: Nikolay Petrov --- dokimi/dokimi/commands/evaluate.py | 3 ++- dokimi/tests/test_expected_outcome.py | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/commands/evaluate.py b/dokimi/dokimi/commands/evaluate.py index b807b53432..db1674f00f 100644 --- a/dokimi/dokimi/commands/evaluate.py +++ b/dokimi/dokimi/commands/evaluate.py @@ -50,6 +50,7 @@ def _run_ragas_eval(answers, output_path, args) -> None: """Run RAGAS meta-evaluation and save results alongside answers.""" from dokimi.eval.question_text import EmptyQuestionError from dokimi.eval.ragas_eval import RagasEvaluator + from dokimi.records import AskOutcomeError ragas_model = getattr(args, "ragas_model", DEFAULT_JUDGE_MODEL) ragas_provider = getattr(args, "ragas_provider", DEFAULT_JUDGE_PROVIDER) @@ -70,7 +71,7 @@ def _run_ragas_eval(answers, output_path, args) -> None: print(result.format_summary()) print(f"✅ Saved RAGAS results to {ragas_path}") - except EmptyQuestionError: + except (AskOutcomeError, EmptyQuestionError): raise # a bad input record is a refusal, not a RAGAS failure: cli.main reports it (exit 2) except ImportError as exc: sys.exit(f"RAGAS meta-evaluation was requested but cannot run: {exc}") diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 99a77ff5d5..3f44bf0089 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -449,3 +449,30 @@ def test_run_stamps_the_ask_rubric_hash_only_when_ask_cells_are_present(monkeypa with_ask = runner.build_output("lib", [], [_judged_row("k1", "ask", 10, 90)], judge=judge) assert with_ask["ask_judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 assert with_ask["judge_prompt_sha256"] == JUDGE_PROMPT_SHA256 + + +def test_ragas_cli_refuses_ask_answers_before_grading(monkeypatch, capsys, tmp_path): + from dokimi.cli import main + from dokimi.commands import evaluate + from dokimi.eval import ragas_eval + + monkeypatch.setattr(evaluate, "_require_ragas", lambda: None) + evaluate_ragas = MagicMock() + monkeypatch.setattr(ragas_eval, "_import_ragas_runtime", lambda: (MagicMock(), evaluate_ragas)) + + def without_client(self, **kwargs): + self._requested = {"faithfulness", "answer_relevancy"} + self._metric_objects, self._ragas_llm = [], MagicMock() + + monkeypatch.setattr(ragas_eval.RagasEvaluator, "__init__", without_client) + path = tmp_path / "mixed.json" + ask = _answers_record("k1", ASK_QUESTION, "ask") + ask["with_docs"]["retrieved_docs"] = [{"snippet": "Reference"}] + path.write_text(json.dumps({"answers": [_answers_record("q1", "How?"), ask]}), encoding="utf-8") + monkeypatch.setattr("sys.argv", ["dokimi", "eval", "score", "ragas", "--answers", str(path)]) + with pytest.raises(SystemExit) as exc: + main() + assert exc.value.code == 2 + assert "question 'k1' expects an ask" in capsys.readouterr().err + assert not path.with_name("mixed_ragas.json").exists() + evaluate_ragas.assert_not_called() From f00f70e5a412d862f2f192111959e0998f0203f3 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Mon, 30 Nov 2026 10:01:39 -0800 Subject: [PATCH 19/40] fix(report): exclude legacy ask scores from model comparison Thread: PRRT_kwDOVBg7g869p3d7 Signed-off-by: Nikolay Petrov --- dokimi/dokimi/report/model_compare.py | 2 +- dokimi/tests/test_ask_readers.py | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/report/model_compare.py b/dokimi/dokimi/report/model_compare.py index b0c5c0a13e..680f839bff 100644 --- a/dokimi/dokimi/report/model_compare.py +++ b/dokimi/dokimi/report/model_compare.py @@ -496,7 +496,7 @@ def extract_scores( if not isinstance(baseline_arm, str) or not baseline_arm: return [] - for answer in _section(run_data, "answers"): + for answer in (a for a in _section(run_data, "answers") if a.expected_outcome != ASK): qid = answer.question_id arms = answer.conditions if baseline_arm not in arms or len(arms) < 2: diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index c073a8ac5b..bb28492d40 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -227,3 +227,16 @@ def test_ask_console_counts_and_plugin_warning(capsys): assert _warnings(control, control) == [ "1 ask question(s) left out of the plugin delta: graded by the ask rubric, not paired", ] + + +def test_model_compare_excludes_ask_rows_with_legacy_inline_evaluations(): + from dokimi.report.model_compare import extract_scores + + answer = {"question_id": "q1", "arms": {"baseline": {"evaluation": {"aggregate_score": 60}}, + "docs": {"evaluation": {"aggregate_score": 70}}}} + ask = {"question_id": "k1", "expected_outcome": "ask", "arms": { + "baseline": {"evaluation": {"aggregate_score": 10}}, + "docs": {"evaluation": {"aggregate_score": 90}}, + }} + rows = extract_scores({"baseline_arm": "baseline", "answers": [answer, ask]}) + assert [(row["question_id"], row["delta"]) for row in rows] == [("q1", 10)] From 1356e335c69635adaf72ddebc2ce159d931645b2 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 07:59:14 -0800 Subject: [PATCH 20/40] Detect golden question sources across both rubrics Thread: PRRT_kwDOVBg7g8698cMW Signed-off-by: Nikolay Petrov --- dokimi/dokimi/report/eval_report.py | 2 +- dokimi/tests/test_ask_readers.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/dokimi/dokimi/report/eval_report.py b/dokimi/dokimi/report/eval_report.py index 5b70a09b90..7c27ee42ef 100755 --- a/dokimi/dokimi/report/eval_report.py +++ b/dokimi/dokimi/report/eval_report.py @@ -338,7 +338,7 @@ def _report_context(eval_path: str) -> _Report: meta = data.get("run_metadata", {}) library = os.path.basename(eval_path).replace(".json", "") - static_prefix = detect_static_prefix(evals) + static_prefix = detect_static_prefix(all_evals) static_qs = [e for e in evals if _is_static(static_prefix, e)] dynamic_qs = [e for e in evals if not _is_static(static_prefix, e)] diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index bb28492d40..8c4eb7390c 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -178,7 +178,7 @@ def test_eval_report_preserves_ask_scores_and_answers(tmp_path, knowledge): source.parent.mkdir() answer_file = tmp_path / "answers" / source.name answer_file.parent.mkdir() - ask = {"question_id": "k1", "question_text": "Which version?", "expected_outcome": "ask", + ask = {"question_id": "onedal-Q001", "question_text": "Which version?", "expected_outcome": "ask", "without_docs": {"aggregate": 95.0}} answer = {"question_id": "q1", "question_text": "How?", "with_docs": {"aggregate": 70.0}, "without_docs": {"aggregate": 60.0}, "delta": 10.0} @@ -186,7 +186,7 @@ def test_eval_report_preserves_ask_scores_and_answers(tmp_path, knowledge): ask.update(with_docs={"aggregate": 25.0}, delta=-70.0) source.write_text(json.dumps({"evaluations": [ask] if knowledge else [answer, ask]})) answer_file.write_text(json.dumps({"answers": [ - {"question_id": "k1", "expected_outcome": "ask", "without_docs": {"answer": "What version?"}}, + {"question_id": "onedal-Q001", "expected_outcome": "ask", "without_docs": {"answer": "What version?"}}, ]})) out = tmp_path / "report.md" (write_eval_report if knowledge else generate_report)(str(source), str(out)) @@ -204,6 +204,7 @@ def test_eval_report_preserves_ask_scores_and_answers(tmp_path, knowledge): sidecar = json.loads(out.with_suffix(".qa.json").read_text()) assert sidecar["count"] == (1 if knowledge else 2) saved_ask = sidecar["records"][-1] + assert saved_ask["source"] == "static" assert saved_ask["expected_outcome"] == "ask" assert saved_ask["without_docs_score"] == 95.0 assert saved_ask["without_docs_answer"] == "What version?" From 8990d92b1db18c7fb8be6d2e1b9b0c36439137eb Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 07:59:30 -0800 Subject: [PATCH 21/40] Check when ask counts appear in judge and export output Thread: PRRT_kwDOVBg7g8698cMh Signed-off-by: Nikolay Petrov --- dokimi/tests/test_ask_readers.py | 6 +++++- dokimi/tests/test_expected_outcome.py | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index 8c4eb7390c..98c1f5ef4f 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -26,12 +26,16 @@ def _ask_question(qid): return {**_question(qid, baseline=_cell(kind="baseline"), docs=_cell(kind="docs")), "expected_outcome": "ask"} -def test_to_binary_leaves_ask_questions_out_of_both_payloads(): +def test_to_binary_leaves_ask_questions_out_of_both_payloads(caplog): answers, evaluation = to_binary(_arms( _question("q1", baseline=_cell(kind="baseline"), docs=_cell(kind="docs")), _ask_question("k1"), evaluations=[_scores("q1", baseline={"aggregate": 60.0}, docs={"aggregate": 70.0}), {**_scores("k1", baseline={"aggregate": 10.0}, docs={"aggregate": 90.0}), "expected_outcome": "ask"}])) + assert "1 ask question(s) left out" in caplog.text + caplog.clear() + to_binary(_arms(_question("q1", baseline=_cell(kind="baseline"), docs=_cell(kind="docs")))) + assert "ask question(s) left out" not in caplog.text assert [a["question_id"] for a in answers["answers"]] == ["q1"] assert [e["question_id"] for e in evaluation["evaluations"]] == ["q1"] diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 3f44bf0089..93ccd3f5ba 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -234,7 +234,7 @@ def invoke(self, text, draw=0, cache_if=None): return super().invoke(text, draw, cache_if) -def test_evaluate_answers_routes_each_record_and_stores_its_outcome(): +def test_evaluate_answers_routes_each_record_and_stores_its_outcome(capsys): judge = _judge(_ask_reply()) judge.llm = _RoutingLLM(None) rows = judge.evaluate_answers("lib", [_answers_record("q1", ASK_QUESTION, "ask"), @@ -245,6 +245,9 @@ def test_evaluate_answers_routes_each_record_and_stores_its_outcome(): assert by_id["q1"]["with_docs"]["judge_prompt_sha256"] == ASK_JUDGE_PROMPT_SHA256 assert by_id["q2"]["expected_outcome"] == "answer" assert "judge_prompt_sha256" not in by_id["q2"]["with_docs"] + assert "Ask questions left out (graded by the ask rubric): 1" in capsys.readouterr().out + judge.evaluate_answers("lib", [_answers_record("q2", "How do I fit?")]) + assert "Ask questions left out" not in capsys.readouterr().out def test_score_answer_takes_the_outcome(): From e99e891fb5ee7871d89f1584ca4ad4290656ce82 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 08:00:47 -0800 Subject: [PATCH 22/40] Exercise persisted ask failures and subsequent answer grading Thread: PRRT_kwDOVBg7g8698cMr Signed-off-by: Nikolay Petrov --- dokimi/tests/test_expected_outcome.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 93ccd3f5ba..4399f5c31c 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -70,7 +70,10 @@ def invoke(self, text, draw=0, cache_if=None): def _judge(reply): judge = Judge.__new__(Judge) judge.llm = _FakeLLM(reply) - judge.temperature = judge.seed = None + from dokimi.spend import Spend + + judge._spend = Spend() + judge.temperature = judge.seed = judge.unsupported_seed = None judge.prompt_template = None judge.model, judge.provider = "fake-judge", "openai" judge.run_metadata, judge.answers_method_version, judge.judge_placeholder = {}, 2, False @@ -250,6 +253,25 @@ def test_evaluate_answers_routes_each_record_and_stores_its_outcome(capsys): assert "Ask questions left out" not in capsys.readouterr().out +def test_failed_ask_pair_is_saved_and_the_next_answer_is_judged(tmp_path, monkeypatch): + judge = _judge(_ask_reply()) + judge.llm = _RoutingLLM(None) + evaluate_pair = judge._evaluate_answer_pair + + def fail_ask(library, row): + if row.expected_outcome == ASK: + raise RuntimeError("ask judge down") + return evaluate_pair(library, row) + + monkeypatch.setattr(judge, "_evaluate_answer_pair", fail_ask) + path = tmp_path / "eval.json" + judge.evaluate_answers("lib", [_answers_record("q1", ASK_QUESTION, ASK), _answers_record("q2", "How?")], + output_path=path) + ask, answer = json.loads(path.read_text())["evaluations"] + assert (ask["expected_outcome"], ask["error"]) == (ASK, "ask judge down") + assert answer["question_id"] == "q2" and answer["with_docs"]["aggregate"] is not None + + def test_score_answer_takes_the_outcome(): judge = _judge(_ask_reply()) out = judge.score_answer(library_name="lib", question=ASK_QUESTION, answer=REPLY, expected_outcome=ASK) From 2e21823d3c23e64ca2ae90d5cefaae2f22019fb1 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 08:01:30 -0800 Subject: [PATCH 23/40] Validate all agreement judges before paid scoring starts Thread: PRR_kwDOVBg7g88AAAABbT0g8A.b Signed-off-by: Nikolay Petrov --- dokimi/dokimi/commands/judge_reliability.py | 6 ++++-- dokimi/tests/test_cross_judge_judge_errors.py | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index 1dc8772b31..ca15c25e0e 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -289,7 +289,7 @@ def _agreement_judge_specs(args: argparse.Namespace, records): specs = [j.strip() for j in (args.judges or "").split(",") if j.strip()] if not specs: - return + return [] _require_arms(args.answers, records, "eval judge agreement --judges") jobs = scored_answers(records) # refuse a blank question before the probe call ask_count = sum(row.expected_outcome == ASK for row in records) @@ -298,12 +298,14 @@ def _agreement_judge_specs(args: argparse.Namespace, records): print(f"Skipped {ask_count} ask {noun} in judge agreement (own rubric).", file=sys.stderr) _check_judge_temperature([(m, p) for p, _, m in (s.partition("/") for s in specs) if m and p in JUDGE_PROVIDERS], args.judge_temperature) + validated = [] for spec in dict.fromkeys(specs): provider, _, model = spec.partition("/") if not model or provider not in JUDGE_PROVIDERS: raise InputError(f"--judges entry '{spec}' must be provider/model, provider in {JUDGE_PROVIDERS}") if jobs or not ask_count: - yield spec, provider, model + validated.append((spec, provider, model)) + return validated def cmd_eval_cross_judge(args: argparse.Namespace) -> None: diff --git a/dokimi/tests/test_cross_judge_judge_errors.py b/dokimi/tests/test_cross_judge_judge_errors.py index 36a382e807..4737e016db 100644 --- a/dokimi/tests/test_cross_judge_judge_errors.py +++ b/dokimi/tests/test_cross_judge_judge_errors.py @@ -207,3 +207,15 @@ def unexpected_judge(**kwargs): with pytest.raises(InputError, match="nothing to compare"): args.func(args) assert "Skipped 1 ask question" in capsys.readouterr().err + + +def test_agreement_validates_later_entries_before_building_the_first_judge(tmp_path, monkeypatch): + from dokimi.utils import InputError + + monkeypatch.setattr(judge_mod, "Judge", lambda **kwargs: pytest.fail("built a judge before validating entries")) + answers = tmp_path / "run.json" + answers.write_text(json.dumps({"answers": _records()}), encoding="utf-8") + args = build_parser().parse_args(["eval", "judge", "agreement", "--answers", str(answers), "--no-stored", + "--judges", "anthropic/m,nosuchprovider"]) + with pytest.raises(InputError, match="nosuchprovider"): + args.func(args) From 42dd600ee4196a92cead9ff9421e8cb8725b59ea Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 08:03:11 -0800 Subject: [PATCH 24/40] Pin the ask rubric when the answer template is customized Thread: PRR_kwDOVBg7g88AAAABbT0g8A.a Signed-off-by: Nikolay Petrov --- dokimi/tests/test_expected_outcome.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 4399f5c31c..b4b8edf669 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -208,7 +208,9 @@ def test_answerer_preserves_the_outcome_when_only_context_succeeded(): def test_judge_asks_the_ask_rubric_and_stamps_its_hash(): judge = _judge(_ask_reply()) + judge.prompt_template = "Custom answer rubric" result = judge._judge_answer("lib", ASK_QUESTION, REPLY, "(none)", expected_outcome=ASK) + assert "Custom answer rubric" not in judge.llm.prompts[0] assert "Clarifying question (0-100)" in judge.llm.prompts[0] assert "Correctness (0-100)" not in judge.llm.prompts[0] assert result["expected_outcome"] == ASK From 3909d8e8eb7baaa465e0d5bdf2de603fc8a55662 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 08:07:02 -0800 Subject: [PATCH 25/40] Preserve the answer prefix when ask questions come from another library Thread: PRRT_kwDOVBg7g8698cMW Signed-off-by: Nikolay Petrov --- dokimi/dokimi/report/eval_report.py | 7 +++++-- dokimi/tests/test_ask_readers.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/report/eval_report.py b/dokimi/dokimi/report/eval_report.py index 7c27ee42ef..46eee4f353 100755 --- a/dokimi/dokimi/report/eval_report.py +++ b/dokimi/dokimi/report/eval_report.py @@ -185,14 +185,17 @@ def fmt_question(text: str | None) -> str: def detect_static_prefix(evals): """Detect the prefix used for static/golden questions (e.g. 'onedal-Q', 'onetbb-Q').""" + ask_prefix = None for e in evals: qid = e.question_id # Static questions typically look like 'onedal-Q001', 'onetbb-Q001', etc. import re m = re.match(r"^([a-zA-Z]+-Q)\d+$", str(qid)) if m: - return m.group(1) - return None + if e.expected_outcome != ASK: + return m.group(1) + ask_prefix = ask_prefix or m.group(1) + return ask_prefix def _is_static(prefix: str | None, e: Record) -> bool: diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index 98c1f5ef4f..90870c861b 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -245,3 +245,15 @@ def test_model_compare_excludes_ask_rows_with_legacy_inline_evaluations(): }} rows = extract_scores({"baseline_arm": "baseline", "answers": [answer, ask]}) assert [(row["question_id"], row["delta"]) for row in rows] == [("q1", 10)] + + +@pytest.mark.parametrize("writer", [generate_report, write_eval_report]) +def test_ask_from_another_library_preserves_the_answer_prefix(tmp_path, writer): + source = tmp_path / "eval.json" + rows = [{"question_id": "other-Q001", "question_text": "Which?", "expected_outcome": "ask"}, + {"question_id": "onedal-Q001", "question_text": "How?"}] + source.write_text(json.dumps({"run_intent": "knowledge", "evaluations": rows})) + out = tmp_path / "report.md" + writer(str(source), str(out)) + answer = json.loads(out.with_suffix(".qa.json").read_text())["records"][1] + assert answer["source"] == "static" From 6fef134c0e3afd7db48b0a29782d41c67c822f9e Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 11:01:12 -0800 Subject: [PATCH 26/40] Address review: refuse a question-set ask in reference scoring eval score reference also reads expected_outcome from the matched question, so an unstamped answers row of an ask question is refused before grading. Thread: PRRT_kwDOVBg7g86-LOAh Signed-off-by: Nikolay Petrov --- dokimi/dokimi/eval/reference_run.py | 7 +++++-- dokimi/tests/test_expected_outcome.py | 13 +++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/eval/reference_run.py b/dokimi/dokimi/eval/reference_run.py index c4ca12bc41..25e904e943 100644 --- a/dokimi/dokimi/eval/reference_run.py +++ b/dokimi/dokimi/eval/reference_run.py @@ -22,7 +22,7 @@ from typing import Any, Mapping, Optional from dokimi.caching import is_empty_reply -from dokimi.eval.ask_outcome import require_judgeable_outcome +from dokimi.eval.ask_outcome import ASK, outcome_of, require_judgeable_outcome from dokimi.eval.reference_checks import Ask, Grade, grade, validate_grading from dokimi.records import NO_RETRIEVAL_SOURCES, Answer, Record, Run, read @@ -125,7 +125,10 @@ def score(data: Any, questions: list[Mapping[str, Any]], *, ask: Optional[Ask] = graded = [r for r in run if r.key in gradings] missing = [r.key for r in run if r.key not in gradings] # Refused before any judge call: the checklist judge has no rubric for a clarifying question. - require_judgeable_outcome([r.raw for r in graded], "eval score reference") + # An ask set on either the answers record or its question counts. + asks = {str(q.get("id")) for q in questions if outcome_of(q) == ASK} + require_judgeable_outcome([{**r.raw, "expected_outcome": ASK} if r.key in asks else r.raw for r in graded], + "eval score reference") with ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool: grades = list(pool.map(lambda r: _grade_record(r, gradings[r.key], ask), graded)) diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index b4b8edf669..3bffb5dcd0 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -417,6 +417,19 @@ def test_reference_scoring_refuses_an_ask_record_before_judging(): ask.assert_not_called() +def test_reference_scoring_refuses_a_question_set_ask_on_an_unstamped_answer(): + from dokimi.eval.reference_run import score + + ask = MagicMock(return_value="yes") + data = {"answers": [{"question_id": "q1", "question_text": ASK_QUESTION, + "without_docs": {"answer": "Sure: set workers to 4 in the config file."}}]} + questions = [{"id": "q1", "question": ASK_QUESTION, "expected_outcome": "ask", "grading": {"checks": [ + {"type": "judge", "criterion": "The reply asks which version or platform the user means"}]}}] + with pytest.raises(AskOutcomeError, match="'q1'"): + score(data, questions, ask=ask) + ask.assert_not_called() + + # ── headline stats exclude ask cells; ask cells get their own block ────── def _judged_row(qid, outcome, baseline, skill): From 177cbc33144ffa1a4e4147450c6c6868d57bbc3f Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 11:01:43 -0800 Subject: [PATCH 27/40] Address review: join keeps the evaluation's ask for an unstamped answer records.join falls back to the evaluation's expected_outcome when the answers record has none, as its docstring says for question metadata. Thread: PRRT_kwDOVBg7g86-LOAt Signed-off-by: Nikolay Petrov --- dokimi/dokimi/records.py | 4 ++-- dokimi/tests/test_expected_outcome.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/records.py b/dokimi/dokimi/records.py index aabba4a0cb..420e22b332 100644 --- a/dokimi/dokimi/records.py +++ b/dokimi/dokimi/records.py @@ -446,8 +446,8 @@ def join( diagnosis=e.diagnosis or a.diagnosis, retrieval_hit=e.retrieval_hit if e.retrieval_hit is not None else a.retrieval_hit, expected_skills=a.expected_skills if a.expected_skills is not None else e.expected_skills, - # The answers record copies its question's outcome; it is the one the question set sets. - expected_outcome=a.expected_outcome, + # The answers record copies its question's outcome; an unstamped one takes the evaluation's. + expected_outcome=a.expected_outcome if a.raw.get("expected_outcome") is not None else e.expected_outcome, raw={**e.raw, **a.raw}, )) out.extend(e for e in evs if e.key not in seen) diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 3bffb5dcd0..10446d711f 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -516,3 +516,13 @@ def without_client(self, **kwargs): assert "question 'k1' expects an ask" in capsys.readouterr().err assert not path.with_name("mixed_ragas.json").exists() evaluate_ragas.assert_not_called() + + +def test_join_takes_the_evaluations_ask_when_the_answers_record_has_no_outcome(): + """`join` falls back to the evaluation's metadata where the answers record has none.""" + from dokimi.records import join + + evaluated = {"question_id": "q1", "expected_outcome": "ask", "scores": {"baseline": {"aggregate": 90}}} + assert join([{"question_id": "q1"}], [evaluated])[0].expected_outcome == "ask" + stamped = {"question_id": "q1", "expected_outcome": "answer"} + assert join([stamped], [evaluated])[0].expected_outcome == "answer" From 9460ff7682bcb05f80ff644f5bde35a08051a82d Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 11:01:48 -0800 Subject: [PATCH 28/40] Address review: document RecordError in require_judgeable_outcome Thread: PRRT_kwDOVBg7g86-LhWV Signed-off-by: Nikolay Petrov --- dokimi/dokimi/eval/ask_outcome.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/eval/ask_outcome.py b/dokimi/dokimi/eval/ask_outcome.py index 3dcd82a272..6568e06f25 100644 --- a/dokimi/dokimi/eval/ask_outcome.py +++ b/dokimi/dokimi/eval/ask_outcome.py @@ -49,7 +49,8 @@ def require_judgeable_outcome(records: Iterable[Mapping[str, Any]], path: str, * """Refuse an ask record on a path that has no ask rubric, before any judge call. Only a record with an answer to judge is refused; one the path would skip anyway - is not. ``path`` names the judge in the message. + is not. ``path`` names the judge in the message. A record that is not a readable answers + record raises :class:`~dokimi.records.RecordError`; both errors are an ``InputError`` (exit 2). """ for i, record in enumerate(records, start=start): if outcome_of(record, i) == ASK and _has_answer_to_judge(record): From 43fbd4354b221750e0a1a5771c8ae749017cf62a Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 11:01:58 -0800 Subject: [PATCH 29/40] Address review: changelog names the question-set ask in reference scoring Thread: PRRT_kwDOVBg7g86-LOAh Signed-off-by: Nikolay Petrov --- .../20261125_130000_napetrov_expected-outcome-ask.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index 54e6c2bb8c..0cb068c6bf 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -17,6 +17,7 @@ SPDX-License-Identifier: Apache-2.0 count say how many ask rows were left out (`arms report`, `arms run`, `eval report`, `report eval`, `eval judge`, `eval panel-score`, the pipeline summary, `eval judge agreement --judges`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` (its regression gate included) and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, degradation pairs, - RAGAS, `eval score reference`) refuse an `ask` record that has an answer to judge, before any judge call. See + RAGAS, `eval score reference`, which also reads the outcome from the matched question) refuse an `ask` record that has + an answer to judge, before any judge call. See `docs/methodology.md` (questions that expect an ask). The eval report includes separate ask scores and preserves ask rows in its Q&A JSON sidecar. From 3e793147ecdb7a32d8505ff704a3248335e97a82 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:11:27 -0800 Subject: [PATCH 30/40] fix(eval): checklist refuses a question the question set marks ask eval score checklist read only the record's stamp, so an unstamped arms file scored an ask question against its expected points with exit 0. It now takes the ask from the question set too, as eval score reference does, and refuses before any judge call (exit 2). Signed-off-by: Alexander Rybkin --- dokimi/docs/methodology.md | 2 +- dokimi/dokimi/commands/judge_reliability.py | 14 ++++----- dokimi/dokimi/eval/checklist.py | 26 +++++++++++----- dokimi/tests/test_eval_output_write_errors.py | 2 +- dokimi/tests/test_expected_outcome.py | 30 +++++++++++++++++++ 5 files changed, 57 insertions(+), 17 deletions(-) diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index bd0ae654be..b9506b0d77 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -214,7 +214,7 @@ A question with `expected_outcome: ask` is one a good assistant answers by askin The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_PROMPT_SHA256` does not change, so answer-mode results keep their stamp. A judged ask row carries `expected_outcome: ask` and the ask rubric's hash; the rubric judges (the single judge, the panel, `arms run --judge`) route on the value. -The paths that compare answers with each other or with expected points (pairwise, checklist, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. `eval judge agreement --judges` counts and skips ask rows so its stored and rescored measures cover answer rows. +The paths that compare answers with each other or with expected points (pairwise, checklist, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call; checklist and `eval score reference` also take the ask from the matched question in the question set. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. `eval judge agreement --judges` counts and skips ask rows so its stored and rescored measures cover answer rows. **Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask questions the run has, errored ones included) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it; `arms report` and the `arms run` console print the block apart. The paired and knowledge eval reports give ask grades their own section and retain them in the Q&A sidecar. The binary payloads (`to_binary`, which feed `answers.v1`/`eval.v1`) and the plugin delta leave ask questions out, and warn when they do. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. diff --git a/dokimi/dokimi/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index ca15c25e0e..3442d8728e 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -71,11 +71,11 @@ def _load_answers(path: str): def _load_points(path: str): - """question_id -> required points from a questions file, or an InputError naming the file.""" - from dokimi.eval.checklist import load_points + """(question_id -> required points, ask question ids) from a questions file, or an InputError naming it.""" + from dokimi.eval.checklist import load_points_and_asks try: - return load_points(path) + return load_points_and_asks(path) except (OSError, ValueError) as exc: # ValueError covers bad JSON, bad UTF-8 and a refused set raise InputError(f"cannot read questions {path}: {exc}") from exc @@ -198,11 +198,11 @@ def cmd_eval_checklist(args: argparse.Namespace) -> None: from dokimi.eval.judge import Judge data, records = _load_answers(args.answers) - points = _load_points(args.questions) + points, asks = _load_points(args.questions) baseline = args.baseline_arm or (data.get("baseline_arm") if isinstance(data, dict) else None) or "baseline" arms = [a.strip() for a in args.arms.split(",")] if args.arms else None _require_arms(args.answers, records, "eval score checklist") - checklist_jobs(records, points, arms=arms) # refuse a blank question before the probe call + checklist_jobs(records, points, arms=arms, asks=asks) # refuse a blank question before the probe call _check_judge_temperature([(args.judge_model, args.judge_provider)], args.judge_temperature) warn_recorded_self_judge(data, [(args.judge_model, args.judge_provider)], "eval score checklist") llm = Judge(model=args.judge_model, provider=args.judge_provider, temperature=args.judge_temperature).llm @@ -213,7 +213,7 @@ def cmd_eval_checklist(args: argparse.Namespace) -> None: records, points, lambda prompt, draw=0, cache_if=None: llm.invoke(prompt, draw=draw, cache_if=cache_if).content, judge=label, - baseline_arm=baseline, arms=arms, concurrency=args.concurrency, progress=_progress(), + baseline_arm=baseline, arms=arms, concurrency=args.concurrency, progress=_progress(), asks=asks, ) if not report.verdicts: raise InputError("no question in the answers file has expected_topics in --questions") @@ -322,7 +322,7 @@ def cmd_eval_cross_judge(args: argparse.Namespace) -> None: if args.grounded: if not args.questions: raise InputError("--grounded needs --questions (their expected_topics are the ground truth)") - truth = {q: t for q, pts in _load_points(args.questions).items() + truth = {q: t for q, pts in _load_points(args.questions)[0].items() if (t := ground_truth_from_topics({"expected_topics": pts}))} def scorer_of(judge): diff --git a/dokimi/dokimi/eval/checklist.py b/dokimi/dokimi/eval/checklist.py index 265003e228..6864e9703a 100644 --- a/dokimi/dokimi/eval/checklist.py +++ b/dokimi/dokimi/eval/checklist.py @@ -32,13 +32,13 @@ import logging from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple +from typing import AbstractSet, Any, Callable, Dict, List, Optional, Sequence, Tuple from dokimi.eval.binary_stats import exact_binomial_two_sided from dokimi.eval.pairwise import standalone_verdict from dokimi.llm import Unparseable from dokimi.judged import judged_reply -from dokimi.eval.ask_outcome import require_judgeable_outcome +from dokimi.eval.ask_outcome import ASK, outcome_of, require_judgeable_outcome from dokimi.eval.question_text import require_question_text from dokimi.records import RecordLike, arm_answers, records as as_records from dokimi.eval.stats import mean_ci @@ -290,13 +290,15 @@ def checklist_jobs( *, arms: Optional[Sequence[str]] = None, report: Optional["ChecklistReport"] = None, + asks: AbstractSet[Any] = frozenset(), ) -> List[Tuple[Any, str, str, str, List[str]]]: """The (question_id, arm, question, answer, points) checks to judge. Pure apart from filling *report*'s questions and ``n_without_points``: no judge call. Raises :class:`EmptyQuestionError` for a record that would be checked and has no question text; a record without expected points is - skipped, not refused. + skipped, not refused. A question id in *asks* (an ask in the question set) is + refused like a record stamped ``expected_outcome: ask``. """ jobs: List[Tuple[Any, str, str, str, List[str]]] = [] for i, rec in enumerate(as_records(records, source="answers", kind="answers")): @@ -310,7 +312,8 @@ def checklist_jobs( if a.text and (arms is None or arm in arms)] # Only a record that would be judged must carry a question; the others keep what they have. if pending: - require_judgeable_outcome([rec.raw], "checklist", start=i) + raw = {**rec.raw, "expected_outcome": ASK} if qid in asks else rec.raw + require_judgeable_outcome([raw], "checklist", start=i) question = require_question_text(rec.raw, i) if pending else rec.question_text if report is not None: report.questions[qid] = question @@ -329,6 +332,7 @@ def run_checklist( arms: Optional[Sequence[str]] = None, concurrency: int = 1, progress: Optional[Callable[[int, int], None]] = None, + asks: AbstractSet[Any] = frozenset(), ) -> ChecklistReport: """Check every (question, arm) answer in an arms run against its points. @@ -338,7 +342,7 @@ def run_checklist( tied) and the skill effect vanished (p 0.06 -> 0.36). """ report = ChecklistReport(judge=judge, baseline_arm=baseline_arm) - jobs = checklist_jobs(records, points_by_qid, arms=arms, report=report) + jobs = checklist_jobs(records, points_by_qid, arms=arms, report=report, asks=asks) def one(job): qid, arm, question, answer, points = job @@ -354,8 +358,14 @@ def one(job): def load_points(path: str) -> Dict[str, List[str]]: """question_id -> required points, from a questions file.""" + return load_points_and_asks(path)[0] + + +def load_points_and_asks(path: str) -> Tuple[Dict[str, List[str]], frozenset]: + """question_id -> required points, and the ids of the ``expected_outcome: ask`` questions.""" from dokimi.questions.artifact import load_questions - # Only ids and points are read here, so a record without question text is no fault. - questions = load_questions(path, validate=False).questions - return {question_id(q): points_of(q) for q in questions if question_id(q) is not None} + # Only ids, points and outcomes are read here, so a record without question text is no fault. + questions = [q for q in load_questions(path, validate=False).questions if question_id(q) is not None] + return ({question_id(q): points_of(q) for q in questions}, + frozenset(question_id(q) for q in questions if outcome_of(q) == ASK)) diff --git a/dokimi/tests/test_eval_output_write_errors.py b/dokimi/tests/test_eval_output_write_errors.py index 3542b332a7..6b22d37c70 100644 --- a/dokimi/tests/test_eval_output_write_errors.py +++ b/dokimi/tests/test_eval_output_write_errors.py @@ -68,7 +68,7 @@ def _stub_judge_commands(monkeypatch): import dokimi.eval.pairwise as pairwise monkeypatch.setattr(judge_reliability, "_load_answers", lambda path: (None, [])) - monkeypatch.setattr(judge_reliability, "_load_points", lambda path: {}) + monkeypatch.setattr(judge_reliability, "_load_points", lambda path: ({}, frozenset())) monkeypatch.setattr(judge_reliability, "_require_arms", lambda *a, **k: None) monkeypatch.setattr(judge_reliability, "_check_judge_temperature", lambda *a, **k: None) monkeypatch.setattr(judge_reliability, "pairwise_judge", lambda args: (None, "label")) diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 10446d711f..7567644670 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -356,6 +356,36 @@ def test_checklist_refuses_an_ask_record_before_judging(): ask.assert_not_called() +def test_checklist_refuses_a_question_set_ask_on_an_unstamped_record(): + ask = MagicMock() + with pytest.raises(AskOutcomeError, match="'q1'"): + run_checklist([_arms_record("q1", ASK_QUESTION)], {"q1": ["fit"]}, ask, asks={"q1"}) + ask.assert_not_called() + + +def test_checklist_cli_refuses_a_question_set_ask_before_any_judge_call(tmp_path, monkeypatch, capsys): + from dokimi import cli + import dokimi.commands.judge_reliability as judge_reliability + import dokimi.eval.judge as judge_module + + answers, questions, out = tmp_path / "arms.json", tmp_path / "questions.json", tmp_path / "out.json" + answers.write_text(json.dumps({"answers": [_arms_record("q1", ASK_QUESTION)]}), encoding="utf-8") + questions.write_text(json.dumps({"questions": [{"id": "q1", "question": ASK_QUESTION, "expected_outcome": "ask", + "expected_topics": ["asks which version"]}]}), encoding="utf-8") + judge, probe = MagicMock(), MagicMock() + monkeypatch.setattr(judge_module, "Judge", judge) + monkeypatch.setattr(judge_reliability, "_check_judge_temperature", probe) + monkeypatch.setattr("sys.argv", ["dokimi", "eval", "score", "checklist", "--answers", str(answers), + "--questions", str(questions), "--out", str(out)]) + with pytest.raises(SystemExit) as exc: + cli.main() + assert exc.value.code == 2 + assert "'q1' expects an ask" in capsys.readouterr().err + probe.assert_not_called() + judge.assert_not_called() + assert not out.exists() + + def test_score_measure_only_scores_answer_questions(): scorer = MagicMock(return_value=50.0) measure = score_measure([_arms_record("k1", ASK_QUESTION, "ask"), From bc0aa3d8ccc373c1ef673842153d33f8d3aeb530 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:11:30 -0800 Subject: [PATCH 31/40] fix(eval): ask refusal names rubric judges that exist The refusal advised `eval judge`, the calibration group, which takes no answers file and fails with a usage error. It now names eval score pointwise, eval score panel and arms run --judge; a test checks that every command it names is a CLI leaf. Signed-off-by: Alexander Rybkin --- dokimi/dokimi/eval/ask_outcome.py | 2 +- dokimi/tests/test_expected_outcome.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/eval/ask_outcome.py b/dokimi/dokimi/eval/ask_outcome.py index 6568e06f25..2abe039607 100644 --- a/dokimi/dokimi/eval/ask_outcome.py +++ b/dokimi/dokimi/eval/ask_outcome.py @@ -59,7 +59,7 @@ def require_judgeable_outcome(records: Iterable[Mapping[str, Any]], path: str, * raise AskOutcomeError( f"{where} expects an ask (expected_outcome: ask); {path} grades answers against " "each other or expected points and has no rubric for a clarifying question. " - "Drop the record or judge it with the rubric judge (eval judge, arms run --judge)" + "Drop the record or judge it with a rubric judge (eval score pointwise, eval score panel, arms run --judge)" ) diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 7567644670..e3ab0fda0f 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -429,6 +429,16 @@ def test_refusal_skips_a_record_with_nothing_to_judge(): assert require_judgeable_outcome([unanswered], "pairwise") is None +def test_refusal_advises_only_commands_that_exist(): + from dokimi.cli_routes import LEAVES + + with pytest.raises(AskOutcomeError) as exc: + require_judgeable_outcome([_answers_record("q1", "x", "ask")], "pairwise") + advice = str(exc.value).rsplit("(", 1)[1].rstrip(")") + named = [tuple(w for w in item.split() if not w.startswith("--")) for item in advice.split(",")] + assert named and all(path in {leaf.path for leaf in LEAVES} for path in named), named + + def test_refusal_names_the_path(): with pytest.raises(AskOutcomeError, match="pairwise"): require_judgeable_outcome([_answers_record("q1", "x", "ask")], "pairwise") From 3c4a0d6f00ebf7d2003ca828bcf44f1cef476294 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:11:36 -0800 Subject: [PATCH 32/40] docs(changelog): ask fragment names commands that exist arms report, eval report, eval judge and eval panel-score are not CLI commands, and main's changelog reference test fails on them after the merge. Name arms run (--out-md), report eval, eval score pointwise and eval score panel instead. Signed-off-by: Alexander Rybkin --- .../20261125_130000_napetrov_expected-outcome-ask.md | 11 ++++++----- dokimi/docs/methodology.md | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index 0cb068c6bf..4884f34f86 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -11,13 +11,14 @@ SPDX-License-Identifier: Apache-2.0 (`ASK_JUDGE_PROMPT_SHA256`); `JUDGE_PROMPT_SHA256` is unchanged. The value is stored on answers records and on every eval row. An arm summary's headline (means, deltas, significance) covers answer rows only; ask rows report their count and means in an `ask` block, and a run with ask rows stamps `ask_judge_prompt_sha256`. - Every reader that pools evaluations leaves ask rows out of its statistics: `arms report`, the `arms run` - console, `eval report`, `report eval`, the `eval judge` and `eval panel-score` consoles, the plugin delta, the + Every reader that pools evaluations leaves ask rows out of its statistics: the `arms run` console and + Markdown report (`--out-md`), `report eval` (paired and knowledge pages), the `eval score pointwise` and + `eval score panel` consoles, the plugin delta, the arms-to-binary bridge, `report model-compare`, the pipeline's step-5 summary, `baseline save` and the dashboard. The readers that print a - count say how many ask rows were left out (`arms report`, `arms run`, `eval report`, `report eval`, `eval judge`, - `eval panel-score`, the pipeline summary, `eval judge agreement --judges`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` + count say how many ask rows were left out (`arms run`, `report eval`, `eval score pointwise`, + `eval score panel`, the pipeline summary, `eval judge agreement --judges`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` (its regression gate included) and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, degradation pairs, - RAGAS, `eval score reference`, which also reads the outcome from the matched question) refuse an `ask` record that has + RAGAS, `eval score reference`; checklist and reference scoring also read the outcome from the matched question) refuse an `ask` record that has an answer to judge, before any judge call. See `docs/methodology.md` (questions that expect an ask). The eval report includes separate ask scores and preserves ask rows in its Q&A JSON sidecar. diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index b9506b0d77..4b9de871a1 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -216,7 +216,7 @@ The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_P The paths that compare answers with each other or with expected points (pairwise, checklist, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call; checklist and `eval score reference` also take the ask from the matched question in the question set. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. `eval judge agreement --judges` counts and skips ask rows so its stored and rescored measures cover answer rows. -**Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask questions the run has, errored ones included) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it; `arms report` and the `arms run` console print the block apart. The paired and knowledge eval reports give ask grades their own section and retain them in the Q&A sidecar. The binary payloads (`to_binary`, which feed `answers.v1`/`eval.v1`) and the plugin delta leave ask questions out, and warn when they do. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. +**Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask questions the run has, errored ones included) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it; the `arms run` console and its Markdown report (`--out-md`) print the block apart. The paired and knowledge eval reports give ask grades their own section and retain them in the Q&A sidecar. The binary payloads (`to_binary`, which feed `answers.v1`/`eval.v1`) and the plugin delta leave ask questions out, and warn when they do. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. **Panel agreement.** Every panel role gets the same ask prompt, so agreement between roles on ask rows measures sampling noise on one prompt, not independent judgement. Read it as a noise floor, not as evidence that the ask rubric is reliable. From f3d6c6d288f8922e08f0142fa977bab8a29fa721 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:11:49 -0800 Subject: [PATCH 33/40] test(eval): ask rows change neither the trust verdict nor interactions report generate's trust gate and the arm summary's interaction contrasts drop ask rows, but no test failed when either filter was removed. Signed-off-by: Alexander Rybkin --- dokimi/tests/test_ask_readers.py | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py index 90870c861b..0af1a17980 100644 --- a/dokimi/tests/test_ask_readers.py +++ b/dokimi/tests/test_ask_readers.py @@ -257,3 +257,37 @@ def test_ask_from_another_library_preserves_the_answer_prefix(tmp_path, writer): writer(str(source), str(out)) answer = json.loads(out.with_suffix(".qa.json").read_text())["records"][1] assert answer["source"] == "static" + + +def _binary(qid, with_docs, without_docs, outcome=None): + row = {"question_id": qid, "question_text": "How?", + "with_docs": {"aggregate": with_docs}, "without_docs": {"aggregate": without_docs}} + if outcome is not None: + row["expected_outcome"] = outcome + return row + + +def test_report_generate_trust_verdict_is_the_verdict_of_the_answer_rows(): + from dokimi.report.generator import ReportGenerator + + def trust(rows): + report = ReportGenerator().generate_report({"evaluations": rows}, {"questions": []}, output_format="json") + return json.loads(report)["trust"] + + answers = [_binary(f"q{i}", 80.0, 70.0) for i in range(10)] + mixed = trust(answers + [_binary(f"k{i}", 0.0, 0.0, "ask") for i in range(10)]) + assert mixed["trusted"] is True + assert mixed == trust(answers) + + +def test_arm_summary_interactions_are_over_answer_rows_only(): + from dokimi.eval.arm_runner import ArmRunner + from dokimi.treatments import BaselineTreatment + + runner = ArmRunner([BaselineTreatment(name) for name in ("baseline", "a", "b", "a+b")]) + answers = [_ev(f"q{i}", {"baseline": 50.0 + i, "a": 60.0 + i, "b": 55.0 + i, "a+b": 70.0 + i % 3}) + for i in range(8)] + asks = [_ev(f"k{i}", {"baseline": 0.0, "a": 0.0, "b": 0.0, "a+b": 100.0}, "ask") for i in range(8)] + mixed = runner._summarize(answers + asks, "baseline") + assert mixed["interactions"] + assert mixed["interactions"] == runner._summarize(answers, "baseline")["interactions"] From 82f58befe988856ec8d769f4a6f8ec0ea2dc0be1 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 22:24:23 -0800 Subject: [PATCH 34/40] Address review: join keeps the evaluation's ask over a null answers outcome records.join merged the answers row's raw over the evaluation's, so a null expected_outcome on the answers row hid the evaluation's ask from the pairwise and checklist refusals, which read raw. Thread: PRRT_kwDOVBg7g86-bmhX Signed-off-by: Nikolay Petrov --- dokimi/dokimi/records.py | 5 +++-- dokimi/tests/test_expected_outcome.py | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/records.py b/dokimi/dokimi/records.py index 420e22b332..621ee50f83 100644 --- a/dokimi/dokimi/records.py +++ b/dokimi/dokimi/records.py @@ -446,9 +446,10 @@ def join( diagnosis=e.diagnosis or a.diagnosis, retrieval_hit=e.retrieval_hit if e.retrieval_hit is not None else a.retrieval_hit, expected_skills=a.expected_skills if a.expected_skills is not None else e.expected_skills, - # The answers record copies its question's outcome; an unstamped one takes the evaluation's. + # The answers record copies its question's outcome; an unstamped (absent or null) one takes + # the evaluation's, in raw too, since the no-ask-rubric refusals read raw. expected_outcome=a.expected_outcome if a.raw.get("expected_outcome") is not None else e.expected_outcome, - raw={**e.raw, **a.raw}, + raw={**e.raw, **{k: v for k, v in a.raw.items() if v is not None or k != "expected_outcome"}}, )) out.extend(e for e in evs if e.key not in seen) return out diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index e3ab0fda0f..6c2b777faa 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -566,3 +566,20 @@ def test_join_takes_the_evaluations_ask_when_the_answers_record_has_no_outcome() assert join([{"question_id": "q1"}], [evaluated])[0].expected_outcome == "ask" stamped = {"question_id": "q1", "expected_outcome": "answer"} assert join([stamped], [evaluated])[0].expected_outcome == "answer" + + +def test_a_null_answers_outcome_joined_to_an_ask_evaluation_is_refused_before_judging(): + """A null outcome reads as unstamped (questions.v2): the joined raw record keeps the evaluation's ask.""" + from dokimi.records import join + + answers = {**_arms_record("q1", ASK_QUESTION), "expected_outcome": None} + evaluated = {"question_id": "q1", "expected_outcome": "ask", "scores": {"baseline": {"aggregate": 90}}} + joined = join([answers], [evaluated]) + assert joined[0].raw["expected_outcome"] == "ask" + judge, ask = MagicMock(), MagicMock() + with pytest.raises(AskOutcomeError, match="'q1'"): + run_arm_pairwise(joined, judge) + judge.compare.assert_not_called() + with pytest.raises(AskOutcomeError, match="'q1'"): + run_checklist(joined, {"q1": ["fit"]}, ask) + ask.assert_not_called() From 78fae0f4b4d52bca9587b86e44c231b15872d333 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 22:25:16 -0800 Subject: [PATCH 35/40] Address review: judges validation and fragment check already fixed a: --judges validates every entry before the first judge is built in 2e21823d3 (tests/test_cross_judge_judge_errors.py). b: the changelog fragment names existing commands in 3c4a0d6f0; with main merged in 061d5653e, tests/test_docs_code_refs.py passes. Thread: PRR_kwDOVBg7g88AAAABbkM-gg: already fixed in 2e21823d3, 3c4a0d6f0 Signed-off-by: Nikolay Petrov From 866de1836f479c7906309756a642128644253233 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Tue, 1 Dec 2026 22:25:16 -0800 Subject: [PATCH 36/40] Address review: reviewer-pushed fixes verified on the merged tree a: fragment and methodology commands (3c4a0d6f0), b: checklist takes the ask from the question set (3e793147e), c: the refusal names rubric judges that exist (bc0aa3d8c), e: main merged (061d5653e). Verified: eval score pointwise/panel, arms run --judge exist; the docs-refs, ask and judge-error tests pass after the merge. d (rubric cap) is held. Thread: IC_kwDOVBg7g88AAAABtTnLEA: already fixed in 3c4a0d6f0, 3e793147e, bc0aa3d8c, 061d5653e Signed-off-by: Nikolay Petrov From 0288384be1a81f0c2015da4d49412e25ffb83136 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 03:56:10 -0700 Subject: [PATCH 37/40] fix(eval): ask rubric scores 0 for a reply that asks nothing A refusal (0/0/100) scored 40 and an answer on a stated assumption 20, above a silent guess at 0. The rule is in the prompt too, so ASK_JUDGE_PROMPT_SHA256 changes with it. Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/methodology.md | 2 ++ dokimi/dokimi/eval/ask_outcome.py | 11 +++++++++-- dokimi/tests/test_expected_outcome.py | 9 +++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index 4b9de871a1..f02524cddb 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -212,6 +212,8 @@ A question with `expected_outcome: ask` is one a good assistant answers by askin - **Targets the ambiguity** (weight 2): is the question the one that resolves the missing detail. - **Avoids guessing** (weight 2): does the reply leave the detail open, rather than pick a value and do the work on it. +The aggregate is the weighted mean of the three, except that a reply that asks nothing (clarifying question 0) scores 0: otherwise a refusal, or an answer on a stated assumption, would outscore a silent guess. The dimension scores are kept as the judge gave them. + The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_PROMPT_SHA256` does not change, so answer-mode results keep their stamp. A judged ask row carries `expected_outcome: ask` and the ask rubric's hash; the rubric judges (the single judge, the panel, `arms run --judge`) route on the value. The paths that compare answers with each other or with expected points (pairwise, checklist, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call; checklist and `eval score reference` also take the ask from the matched question in the question set. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. `eval judge agreement --judges` counts and skips ask rows so its stored and rescored measures cover answer rows. diff --git a/dokimi/dokimi/eval/ask_outcome.py b/dokimi/dokimi/eval/ask_outcome.py index 2abe039607..0f141d4e17 100644 --- a/dokimi/dokimi/eval/ask_outcome.py +++ b/dokimi/dokimi/eval/ask_outcome.py @@ -98,7 +98,7 @@ def require_judgeable_outcome(records: Iterable[Mapping[str, Any]], path: str, * **Instructions:** - Replace every N with an integer 0-100, picked from the levels above - Score each dimension independently; do not round them toward each other -- Python computes the aggregate — do NOT compute it yourself, set aggregate=0 +- Python computes the aggregate — do NOT compute it yourself, set aggregate=0 (a reply that asks nothing, clarifying_question=0, gets aggregate 0 whatever the other two scores are) - Provide brief reasoning for each score **Output format (JSON only, no other text):** @@ -120,7 +120,14 @@ def require_judgeable_outcome(records: Iterable[Mapping[str, Any]], path: str, * def ask_weighted_aggregate(scores: Mapping[str, float]) -> float: - """The ask rubric's aggregate: a weighted mean, computed in Python, never by the judge.""" + """The ask rubric's aggregate: a weighted mean, computed in Python, never by the judge. + + A reply that asks nothing (``clarifying_question`` 0) scores 0: asking is what the rubric + measures, so a refusal or a stated assumption must not outscore a silent guess. The + dimension scores are kept as the judge gave them. + """ + if float(scores["clarifying_question"]) == 0: + return 0.0 total = sum(ASK_WEIGHTS.values()) return round(sum(float(scores[d]) * w for d, w in ASK_WEIGHTS.items()) / total, 1) diff --git a/dokimi/tests/test_expected_outcome.py b/dokimi/tests/test_expected_outcome.py index 6c2b777faa..5615688c67 100644 --- a/dokimi/tests/test_expected_outcome.py +++ b/dokimi/tests/test_expected_outcome.py @@ -105,6 +105,15 @@ def _arms_record(qid, text, outcome=None): # ── the vocabulary and the rubric ──────────────────────────────────────── +def test_a_reply_that_asks_nothing_scores_zero_and_keeps_its_dimensions(): + judge = _judge(_ask_reply(clarifying_question=0, targets_ambiguity=0, avoids_guessing=100)) + result = judge._judge_answer("lib", ASK_QUESTION, "I cannot help with that request.", "(none)", + expected_outcome=ASK) + assert result["aggregate"] == 0 + assert result["avoids_guessing"] == 100 + assert "clarifying_question=0, gets aggregate 0" in judge.llm.prompts[0] + + def test_answer_rubric_hash_is_unchanged_by_the_ask_rubric(): assert JUDGE_PROMPT_SHA256 == PRE_FEATURE_JUDGE_PROMPT_SHA256 From bfd48ca2d30b27e8aa2fe57c060df33039d80fd7 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 03:56:10 -0700 Subject: [PATCH 38/40] docs(changelog): ask fragment says a reply that asks nothing scores 0 Signed-off-by: Vladislav Perevezentsev --- .../20261125_130000_napetrov_expected-outcome-ask.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index 4884f34f86..17cfc2a47b 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -8,7 +8,8 @@ SPDX-License-Identifier: Apache-2.0 - **`expected_outcome: ask`: a question that expects the assistant to ask back is judged by its own rubric.** A question record may carry `expected_outcome` (`answer`, the default, or `ask`). An `ask` record is graded by the ask rubric (clarifying question, targets the ambiguity, avoids guessing) with its own prompt hash - (`ASK_JUDGE_PROMPT_SHA256`); `JUDGE_PROMPT_SHA256` is unchanged. The value is stored on answers records + (`ASK_JUDGE_PROMPT_SHA256`); `JUDGE_PROMPT_SHA256` is unchanged. A reply that asks nothing + scores 0 on the ask rubric, so a refusal does not outscore a guess. The value is stored on answers records and on every eval row. An arm summary's headline (means, deltas, significance) covers answer rows only; ask rows report their count and means in an `ask` block, and a run with ask rows stamps `ask_judge_prompt_sha256`. Every reader that pools evaluations leaves ask rows out of its statistics: the `arms run` console and From e19e693a9b9947c60378a650a351549173f0bd69 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 2 Dec 2026 11:55:50 -0800 Subject: [PATCH 39/40] Align ask agreement tests with repeatable judge flag Signed-off-by: Nikolay Petrov --- .../20261125_130000_napetrov_expected-outcome-ask.md | 2 +- dokimi/docs/methodology.md | 2 +- dokimi/dokimi/commands/judge_reliability.py | 9 ++++----- dokimi/tests/test_cross_judge_judge_errors.py | 6 +++--- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md index 17cfc2a47b..1afcd4d9c3 100644 --- a/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -17,7 +17,7 @@ SPDX-License-Identifier: Apache-2.0 `eval score panel` consoles, the plugin delta, the arms-to-binary bridge, `report model-compare`, the pipeline's step-5 summary, `baseline save` and the dashboard. The readers that print a count say how many ask rows were left out (`arms run`, `report eval`, `eval score pointwise`, - `eval score panel`, the pipeline summary, `eval judge agreement --judges`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` + `eval score panel`, the pipeline summary, `eval judge agreement --judge`, and the plugin delta, which warns); `report generate`, `baseline save`, `baseline compare` (its regression gate included) and the dashboard leave them out silently. The paths with no ask rubric (pairwise, checklist, degradation pairs, RAGAS, `eval score reference`; checklist and reference scoring also read the outcome from the matched question) refuse an `ask` record that has an answer to judge, before any judge call. See diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index 808259ffd4..a83df62d5b 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -215,7 +215,7 @@ The aggregate is the weighted mean of the three, except that a reply that asks n The ask rubric has its own prompt identity (`ASK_JUDGE_PROMPT_SHA256`). `JUDGE_PROMPT_SHA256` does not change, so answer-mode results keep their stamp. A judged ask row carries `expected_outcome: ask` and the ask rubric's hash; the rubric judges (the single judge, the panel, `arms run --judge`) route on the value. -The paths that compare answers with each other or with expected points (pairwise, checklist, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call; checklist and `eval score reference` also take the ask from the matched question in the question set. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. `eval judge agreement --judges` counts and skips ask rows so its stored and rescored measures cover answer rows. +The paths that compare answers with each other or with expected points (pairwise, checklist, degradation pairs, which judge validity also reads, RAGAS, and `eval score reference`) have no ask rubric. They refuse an ask record that has an answer to judge, naming its question id, before any judge call; checklist and `eval score reference` also take the ask from the matched question in the question set. A record the path would skip anyway is not refused. Drop such records from those paths, or judge them with a rubric judge. `eval judge agreement --judge` counts and skips ask rows so its stored and rescored measures cover answer rows. **Reporting.** The arm headline (per-arm means, paired deltas, significance and interactions) is computed over answer rows only. Ask rows are reported apart in the arm summary's `ask` block: `cells` (how many ask questions the run has, errored ones included) and each arm's `avg_aggregate`, `n` and `errors` over them. Their means are never pooled into the headline and are not tested against it; the `arms run` console and its Markdown report (`--out-md`) print the block apart. The paired and knowledge eval reports give ask grades their own section and retain them in the Q&A sidecar. The binary payloads (`to_binary`, which feed `answers.v1`/`eval.v1`) and the plugin delta leave ask questions out, and warn when they do. A run with ask rows carries `ask_judge_prompt_sha256` next to `judge_prompt_sha256`; a run without them has neither change. diff --git a/dokimi/dokimi/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index 2829799aeb..7e9bba25ea 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -340,7 +340,7 @@ def score(library, question, answer, ground_truth, context): from dokimi.utils import question_id # What the arms run's judge saw, when the file keeps it (judge_materials). Built - # once and only for --judges: it is the store the gate checks and the judge reads. + # once and only for --judge: it is the store the gate checks and the judge reads. materials: Optional[JudgeContextStore] = ( JudgeContextStore.from_artifact(data) if args.judges and isinstance(data, dict) else None ) @@ -362,9 +362,8 @@ def score(library, question, answer, ground_truth, context): if args.pairwise or args.checklist: unrepro.update(pair_unrepro) elif materials is not None and materials.mode != JUDGE_CONTEXT_BASELINE: - # The loop below is the whole --judges gate: it compares each stored score's - # digest with what the reader serves, for the questions score_measure scores. - # score_measure only scores questions that have an answer record. + # Check stored digests only for questions that score_measure can rescore + # because they have an answer record. answered = {question_id(r) for r in data.get("answers") or [] if isinstance(r, dict) and isinstance(question_id(r), (str, int))} # The arm exempt from the check is the one whose recorded kind is baseline, as in @@ -451,7 +450,7 @@ def score(library, question, answer, ground_truth, context): def _scored_nothing_exit(unscored: Sequence[Measure]) -> None: - """Exit 1 (a run failure) when a ``--judges`` judge scored none of its answers. + """Exit 1 (a run failure) when a ``--judge`` judge scored none of its answers. That is a judge that could not run (no key, an unknown model, a dead endpoint), not a measurement, so it fails the run even without ``--strict`` and even when diff --git a/dokimi/tests/test_cross_judge_judge_errors.py b/dokimi/tests/test_cross_judge_judge_errors.py index e749d50046..1cafad9b1c 100644 --- a/dokimi/tests/test_cross_judge_judge_errors.py +++ b/dokimi/tests/test_cross_judge_judge_errors.py @@ -86,7 +86,7 @@ def test_a_measure_read_from_a_file_asked_no_judge(): def _cross_judge(tmp_path, monkeypatch, failing, *extra, data=None): - """``eval judge agreement --judges anthropic/m`` with a judge that raises on *failing* answers. + """``eval judge agreement --judge anthropic/m`` with a judge that raises on *failing* answers. Returns ``(exit code, stderr, the written JSON report)``; the code is 0 when it did not exit. """ @@ -203,7 +203,7 @@ def unexpected_judge(**kwargs): answers = tmp_path / "run.json" answers.write_text(json.dumps({"answers": [ask]}), encoding="utf-8") args = build_parser().parse_args(["eval", "judge", "agreement", "--answers", str(answers), - "--judges", "anthropic/m"]) + "--judge", "anthropic/m"]) with pytest.raises(InputError, match="nothing to compare"): args.func(args) assert "Skipped 1 ask question" in capsys.readouterr().err @@ -216,6 +216,6 @@ def test_agreement_validates_later_entries_before_building_the_first_judge(tmp_p answers = tmp_path / "run.json" answers.write_text(json.dumps({"answers": _records()}), encoding="utf-8") args = build_parser().parse_args(["eval", "judge", "agreement", "--answers", str(answers), "--no-stored", - "--judges", "anthropic/m,nosuchprovider"]) + "--judge", "anthropic/m", "--judge", "nosuchprovider"]) with pytest.raises(InputError, match="nosuchprovider"): args.func(args) From 1788b05c23f39ff2f2b33cdec6de815ce440ace6 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Wed, 2 Dec 2026 08:31:08 -0800 Subject: [PATCH 40/40] test(cli): supply an agent run fault fixture Signed-off-by: Nikolay Petrov (cherry picked from commit e249323eb321bbc70ac425c03170071d835a143c) --- dokimi/tests/cli_faults.py | 1 + 1 file changed, 1 insertion(+) diff --git a/dokimi/tests/cli_faults.py b/dokimi/tests/cli_faults.py index 8034505a28..72de4eb572 100644 --- a/dokimi/tests/cli_faults.py +++ b/dokimi/tests/cli_faults.py @@ -33,6 +33,7 @@ # Words for an argument the harness cannot guess, always given: (command, option or operand) -> argv words. FILLERS: dict[tuple[str, str], list[str]] = { + ("agent run", "--agent"): ["claude-code=openai/gpt-4o-mini"], ("explore run", "--all"): [], ("repo hits judge", "--judge"): ["openai/gpt-4o-mini"], ("tasks run", "--all"): [],