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 000000000..1afcd4d9c --- /dev/null +++ b/dokimi/changelog.d/20261125_130000_napetrov_expected-outcome-ask.md @@ -0,0 +1,25 @@ + + +### 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. 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 + 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 run`, `report eval`, `eval score pointwise`, + `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 + `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 46d95d164..a83df62d5 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -104,6 +104,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. @@ -201,6 +203,24 @@ 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 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 --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. + +**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/commands/arms.py b/dokimi/dokimi/commands/arms.py index 0d816d2f1..e31698532 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -16,6 +16,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, read_json_input from dokimi.write_probe import can_write @@ -75,6 +76,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 @@ -120,6 +127,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/commands/baseline.py b/dokimi/dokimi/commands/baseline.py index a9e0118ed..ae728bf5c 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 {} @@ -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/commands/evaluate.py b/dokimi/dokimi/commands/evaluate.py index c7748ba7f..04e07af4c 100644 --- a/dokimi/dokimi/commands/evaluate.py +++ b/dokimi/dokimi/commands/evaluate.py @@ -51,6 +51,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) @@ -71,7 +72,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}") @@ -91,6 +92,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 @@ -149,22 +172,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/commands/judge_reliability.py b/dokimi/dokimi/commands/judge_reliability.py index 8048e3510..7e9bba25e 100644 --- a/dokimi/dokimi/commands/judge_reliability.py +++ b/dokimi/dokimi/commands/judge_reliability.py @@ -72,11 +72,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 @@ -199,11 +199,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 @@ -214,7 +214,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") @@ -283,10 +283,36 @@ 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 raw in (args.judges or []) for j in raw.split(",") if j.strip()] + if not specs: + return [] + _require_arms(args.answers, records, "eval judge agreement --judge") + 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) + validated = [] + for spec in dict.fromkeys(specs): + provider, _, model = spec.partition("/") + if not model or provider not in JUDGE_PROVIDERS: + raise InputError(f"--judge entry '{spec}' must be provider/model, provider in {JUDGE_PROVIDERS}") + if jobs or not ask_count: + validated.append((spec, provider, model)) + return validated + + 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 @@ -297,7 +323,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): @@ -310,10 +336,11 @@ 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 - # 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 ) @@ -335,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 @@ -347,7 +373,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,16 +416,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 raw in (args.judges or []) for j in raw.split(",") if j.strip()] - if specs: - _require_arms(args.answers, records, "eval judge agreement --judge") - scored_answers(records) # refuse a blank question before the probe call - _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"--judge entry '{spec}' must be provider/model, provider in {JUDGE_PROVIDERS}") + 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) @@ -433,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/dokimi/dashboard/aggregator.py b/dokimi/dokimi/dashboard/aggregator.py index d35afb6e6..68f3ee320 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/answerer.py b/dokimi/dokimi/eval/answerer.py index 0e72b66f3..2bb992249 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 e674131c4..b41e93d47 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 8b6b36329..a039f4a4d 100644 --- a/dokimi/dokimi/eval/arm_runner.py +++ b/dokimi/dokimi/eval/arm_runner.py @@ -26,10 +26,11 @@ 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 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 @@ -734,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") @@ -758,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 @@ -777,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 4c04ca051..8c4d23b6d 100644 --- a/dokimi/dokimi/eval/arm_summary.py +++ b/dokimi/dokimi/eval/arm_summary.py @@ -21,7 +21,9 @@ from dokimi.measure import as_float 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 @@ -384,3 +386,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/dokimi/eval/arms_adapter.py b/dokimi/dokimi/eval/arms_adapter.py index a5cb135c7..ef1f2e60b 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/ask_outcome.py b/dokimi/dokimi/eval/ask_outcome.py new file mode 100644 index 000000000..0f141d4e1 --- /dev/null +++ b/dokimi/dokimi/eval/ask_outcome.py @@ -0,0 +1,142 @@ +# 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, *, 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. 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): + 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 a rubric judge (eval score pointwise, eval score panel, 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 (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):** +{ + "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. + + 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) + + +_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 63aaa561f..6864e9703 100644 --- a/dokimi/dokimi/eval/checklist.py +++ b/dokimi/dokimi/eval/checklist.py @@ -32,12 +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 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 @@ -289,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")): @@ -308,6 +311,9 @@ 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: + 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 @@ -326,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. @@ -335,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 @@ -351,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/dokimi/eval/cross_judge.py b/dokimi/dokimi/eval/cross_judge.py index c1afb3ef1..0a2a46a7d 100644 --- a/dokimi/dokimi/eval/cross_judge.py +++ b/dokimi/dokimi/eval/cross_judge.py @@ -62,7 +62,7 @@ JUDGE_CONTEXT_BASELINE, PROTOCOL_WITHHELD, SOURCE_STORED, SOURCE_WITHHELD, JudgeContextStore, ) 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 @@ -248,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" }) @@ -280,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)}. " @@ -353,13 +354,14 @@ 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, 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) ] @@ -372,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/dokimi/eval/degrade.py b/dokimi/dokimi/eval/degrade.py index a445334cd..5955b2ef0 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", 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/judge.py b/dokimi/dokimi/eval/judge.py index 2ee2ec495..44a809d3a 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, @@ -355,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) @@ -377,6 +386,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 +401,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 +413,7 @@ def _evaluate_answer_pair( answer=baseline_answer.text, context="(No documentation provided)", ground_truth=ground_truth, + expected_outcome=outcome, ) # Calculate delta @@ -418,6 +430,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 +508,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: @@ -536,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 @@ -562,6 +576,45 @@ 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. + + 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) + + (scores, aggregate), _ = judged_reply( + 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 + scores["judge_prompt_sha256"] = ASK_JUDGE_PROMPT_SHA256 + return scores + def score_answer( self, library_name: str, @@ -570,6 +623,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 +633,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 5f84ca817..f4a2403eb 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 @@ -275,6 +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", 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/panel.py b/dokimi/dokimi/eval/panel.py index eda971ffa..2e1e84850 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,13 @@ 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), + 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. capped: Dict[str, Any] = {"correctness": scores["correctness"], @@ -392,6 +408,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 +426,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,49 +445,59 @@ 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)) + # 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) -> 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 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. 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 +505,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 +522,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 +537,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 +593,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/plugin_delta.py b/dokimi/dokimi/eval/plugin_delta.py index 69f084a50..c0a11b9e7 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): @@ -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 = {r.key for side in (control, plugin) for r in _section(side, "evaluations") if r.expected_outcome == ASK} + if asks: + 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, " @@ -214,8 +217,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/eval/ragas_eval.py b/dokimi/dokimi/eval/ragas_eval.py index 0364647e8..e3fd6492b 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", start=i) 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", start=i) require_question_text(rec.raw, i) rows_without.append({ "user_input": q, diff --git a/dokimi/dokimi/eval/reference_run.py b/dokimi/dokimi/eval/reference_run.py index c03ab3d2e..25e904e94 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 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 @@ -123,6 +124,11 @@ 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. + # 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/dokimi/eval/stats.py b/dokimi/dokimi/eval/stats.py index 4f4472e8c..386867f7e 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/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 76c0885c7..64e7d60bd 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -426,8 +426,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) - # 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 @@ -444,9 +444,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/dokimi/records.py b/dokimi/dokimi/records.py index 70f4a0695..621ee50f8 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,7 +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, - raw={**e.raw, **a.raw}, + # 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, **{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 @@ -614,6 +654,13 @@ 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: + 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/report/arms_report.py b/dokimi/dokimi/report/arms_report.py index 3277ae632..e6819419c 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 6f7cf9b7e..46eee4f35 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 dataclasses import dataclass from datetime import datetime, timezone from typing import Any @@ -28,7 +29,8 @@ 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.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 try: @@ -183,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: @@ -282,11 +287,38 @@ 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, 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, ""] + + @dataclass(frozen=True) class _Report: """What the sections of one eval report read, computed once by :func:`_report_context`.""" data: dict + all_evals: list[Record] + asks: list[Record] evals: list[Record] meta: Any library: str @@ -303,11 +335,13 @@ class _Report: def _report_context(eval_path: str) -> _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") + 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", "") - 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)] @@ -324,7 +358,7 @@ def _report_context(eval_path: str) -> _Report: if has_scores(e) and e.delta is not None and not math.isnan(e.delta) ] return _Report( - data=data, evals=evals, meta=meta, library=library, static_prefix=static_prefix, + data=data, all_evals=all_evals, asks=asks, evals=evals, meta=meta, library=library, static_prefix=static_prefix, static_qs=static_qs, dynamic_qs=dynamic_qs, all_stats=all_stats, static_stats=static_stats, dyn_stats=dyn_stats, diff_groups=diff_groups, valid_all=valid_all, @@ -352,6 +386,7 @@ def _header_section(r: _Report) -> list[str]: 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(r.data), + *_ask_note(len(r.asks)), "## Run Configuration", "| | |", "|---|---|", @@ -599,6 +634,7 @@ def _report_lines(r: _Report) -> list[str]: lines += _qa_static_section(r) lines += _qa_dynamic_section(r) lines += _recommendations_section(r) + lines += _ask_section(r.asks, [(CONTEXT, "Context arm"), (BASELINE, "Baseline")]) return lines @@ -610,7 +646,7 @@ def _answer_text(a: Record | None, condition: str): def _qa_records(r: _Report, answers_by_id: dict[str, Record]) -> list[dict]: """The Q&A sidecar's one row per question: its text, scores and both arms' answers.""" qa_records = [] - for e in r.evals: + for e in r.all_evals: a = answers_by_id.get(e.key) qa_records.append({ "question_id": e.question_id, @@ -620,6 +656,7 @@ def _qa_records(r: _Report, answers_by_id: dict[str, Record]) -> list[dict]: "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/generator.py b/dokimi/dokimi/report/generator.py index af41181f8..f847cb8a1 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 c7b6a0622..496a9b102 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.eval.arm_summary import pooled_spend_fields @@ -442,7 +442,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 @@ -491,7 +491,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/dokimi/report/single_condition_report.py b/dokimi/dokimi/report/single_condition_report.py index 77dd5c1a4..4b0662cae 100644 --- a/dokimi/dokimi/report/single_condition_report.py +++ b/dokimi/dokimi/report/single_condition_report.py @@ -17,12 +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 (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, @@ -74,7 +76,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: 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] @@ -83,6 +86,7 @@ def render(evals: Sequence[Record], meta: Dict[str, Any], library: str, generate f"_Generated: {generated}_", "", *stop_note(meta), + *_ask_note(len(asks)), "## Run Configuration", "| | |", "|---|---|", @@ -120,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]: @@ -158,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)), } @@ -184,26 +190,28 @@ 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") - held = held_conditions(evals) + all_evals = records(data["evaluations"], source=eval_path, kind="evaluations") + evals = [e for e in all_evals if e.expected_outcome != ASK] + 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) 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) 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/answers.v1.json b/dokimi/dokimi/schemas/answers.v1.json index 7a536d848..aa0ce344c 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 17b461fe4..42eb16dbf 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,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)." + "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" + "type": "array", + "description": "One grade record per question. Rows use expected_outcome: ask for a clarifying question or answer (the default when absent)." }, "summary": { "type": "object", @@ -275,6 +279,10 @@ } } }, + "ask": { + "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.", "type": "string" diff --git a/dokimi/dokimi/schemas/eval.v1.json b/dokimi/dokimi/schemas/eval.v1.json index 376639c78..5ad239f64 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 8d61732d0..0a861d166 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 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.", "type": "object", diff --git a/dokimi/dokimi/schemas/report_qa.v1.json b/dokimi/dokimi/schemas/report_qa.v1.json index c1ec3c152..8bd69c569 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/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index 91843c532..90fa11c35 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -17,7 +17,7 @@ "dokimi/commands/benchmark.py::cmd_benchmark_preflight": {"complexity": 12}, "dokimi/commands/catalog.py::cmd_catalog_trigger_set": {"complexity": 11}, "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}, diff --git a/dokimi/tests/cli_faults.py b/dokimi/tests/cli_faults.py index 8034505a2..72de4eb57 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"): [], diff --git a/dokimi/tests/test_ask_readers.py b/dokimi/tests/test_ask_readers.py new file mode 100644 index 000000000..0af1a1798 --- /dev/null +++ b/dokimi/tests/test_ask_readers.py @@ -0,0 +1,293 @@ +# 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).""" + +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 + + +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(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"] + + +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") + + +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 + + +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 + + +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} + + +@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": "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} + 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": "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)) + 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["source"] == "static" + 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", + ] + + +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)] + + +@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" + + +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"] diff --git a/dokimi/tests/test_cross_judge_judge_errors.py b/dokimi/tests/test_cross_judge_judge_errors.py index cbcf6eebd..1cafad9b1 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. """ @@ -178,3 +178,44 @@ 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 + + +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), + "--judge", "anthropic/m"]) + 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", + "--judge", "anthropic/m", "--judge", "nosuchprovider"]) + with pytest.raises(InputError, match="nosuchprovider"): + args.func(args) diff --git a/dokimi/tests/test_eval_output_write_errors.py b/dokimi/tests/test_eval_output_write_errors.py index 78e9e26a8..426db4638 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 new file mode 100644 index 000000000..5615688c6 --- /dev/null +++ b/dokimi/tests/test_expected_outcome.py @@ -0,0 +1,594 @@ +# 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 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 +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) + 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 + 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_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 + + +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 + + +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(): + 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 + 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(capsys): + 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"] + 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_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) + 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_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"), + _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(): + 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_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") + + +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() + + +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): + 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 = 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: {}) + 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 + + +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() + + +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" + + +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() diff --git a/dokimi/tests/test_pipeline_summary.py b/dokimi/tests/test_pipeline_summary.py index a2c38ef07..e3bc26174 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 diff --git a/dokimi/tests/test_record_readers.py b/dokimi/tests/test_record_readers.py index 969262997..bf5fde052 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,