From 75787690aa572ef0251c8a1c2b2d4679cd09ac0e Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Fri, 4 Dec 2026 21:07:30 -0800 Subject: [PATCH 1/5] refactor(pipeline): split EvaluationPipeline.run into phase helpers run() now calls one method per phase: the personas step, the question step (one method per source: --questions-from, the cached set, the golden set, generated), and the evaluation summary. The question-source resolution in __init__ moves into two helpers. The output is unchanged. The public question-set helpers (resolve_questions_from_path, compute_question_set_hash, load_questions_payload) move to orchestrator/question_sets.py, which pipeline.py imports, so the names still resolve from pipeline. This keeps pipeline.py under the 800-line growth cap. The run() complexity baseline entry is dropped. Signed-off-by: Nikolay Petrov --- ...20000_napetrov_arch-r8-7-pipeline-split.md | 3 + dokimi/dokimi/orchestrator/pipeline.py | 382 +++++++++--------- dokimi/dokimi/orchestrator/question_sets.py | 39 ++ dokimi/scripts/growth_baseline.json | 1 - 4 files changed, 239 insertions(+), 186 deletions(-) create mode 100644 dokimi/changelog.d/20261204_120000_napetrov_arch-r8-7-pipeline-split.md create mode 100644 dokimi/dokimi/orchestrator/question_sets.py diff --git a/dokimi/changelog.d/20261204_120000_napetrov_arch-r8-7-pipeline-split.md b/dokimi/changelog.d/20261204_120000_napetrov_arch-r8-7-pipeline-split.md new file mode 100644 index 000000000..5ee930bc6 --- /dev/null +++ b/dokimi/changelog.d/20261204_120000_napetrov_arch-r8-7-pipeline-split.md @@ -0,0 +1,3 @@ +### Changed + +- **The evaluation pipeline's `run` is split into phase helpers.** No output, flag or file changes. The question-set helpers `resolve_questions_from_path`, `compute_question_set_hash` and `load_questions_payload` now live in `dokimi.orchestrator.question_sets`; they are still importable from `dokimi.orchestrator.pipeline`. diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 2472c3ca2..19a78ceac 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -7,7 +7,7 @@ import logging import json import sys -from typing import Any, Callable, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple from pathlib import Path from dokimi.artifacts import save_artifact @@ -22,28 +22,12 @@ from dokimi.digest import key_bytes from dokimi.orchestrator.question_source import warn_unpinned_questions +from dokimi.orchestrator.question_sets import ( + compute_question_set_hash, load_questions_payload, resolve_questions_from_path) logger = logging.getLogger(__name__) -def resolve_questions_from_path(questions_from: Path, product_slug: str) -> Path: - """Resolve a --questions-from file or run directory for a target slug.""" - qf = Path(questions_from) - if qf.is_dir(): - qf = qf / "questions" / f"{product_slug}.json" - return qf - - -def compute_question_set_hash(questions: List[Dict[str, Any]]) -> str: - """Return 12-char SHA-256 prefix over sorted question texts + ids.""" - fingerprints = sorted( - f"{q.get('id', '')}:{q.get('question', q.get('question_text', q.get('text', '')))}" - for q in questions - ) - raw = "\n".join(fingerprints).encode("utf-8", "surrogatepass") # a `\ud800` JSON escape loads as a lone surrogate - return hashlib.sha256(raw).hexdigest()[:12] - - def _canonical(questions: List[Dict[str, Any]]) -> List[str]: """The set's records as sorted ``(id, question)`` pairs, to compare two sets by content. @@ -56,19 +40,6 @@ def _canonical(questions: List[Dict[str, Any]]) -> List[str]: default=str) for q in questions) -def load_questions_payload(path: Path, flag: Optional[str] = None) -> List[Dict[str, Any]]: - """The records of the question set at ``path``, in the questions.v2 shape. - - :func:`dokimi.questions.artifact.load_questions` reads it: v1, v2, a bare list, or a legacy - shape (logged once); a set still invalid after that raises ``ArtifactValidationError`` (a - ``ValueError``) naming the record. ``flag`` is the option ``path`` came from: a file that is - not UTF-8 or JSON then raises ``InputError`` `` : ``. ``path`` is not written. - """ - from dokimi.questions.artifact import load_questions - - return load_questions(path, flag=flag).questions - - def _read_input_set(path: Path, what: str, fix: str = "") -> List[Dict[str, Any]]: """The records at ``path``, a set the run reads by itself; a set it cannot use is an ``InputError`` (exit 2).""" try: @@ -216,10 +187,48 @@ def __init__( self.description = description self.output_dir = Path(output_dir) + self.questions_root = Path(questions_root) if questions_root else None + self._resolve_question_source(custom_questions_path, questions_from, force_regen) + + self.model = model + self.provider = provider + self.judge_model = judge_model + self.judge_provider = judge_provider + self.judge_temperature = judge_temperature + _warn_judge_placeholder(judge_placeholder) + + self.personas_count = personas_count + self.questions_per_topic = questions_per_topic + self.top_k = top_k + self.rerank_threshold = rerank_threshold + self.debug_retrieval = debug_retrieval + self.doc_source = doc_source + self.context7_id = context7_id + # Product registry for the library id (defaults to the bundled products.yaml). + self.registry = registry + self.max_tokens_per_question = max_tokens_per_question + self.force_regen = force_regen + + self._resolve_external_questions(questions_from) + + # Output paths + self.personas_path = self.output_dir / "personas" / f"{self.product_key}.json" + self.questions_path = self.output_dir / "questions" / f"{self.product_key}.json" + self.answers_path = self.output_dir / "answers" / f"{self.product_key}.json" + self.eval_path = self.output_dir / "eval" / f"{self.product_key}.json" + self.report_path = self.output_dir / "reports" / f"{self.product_key}.md" + + # Create output dirs + for path in [self.personas_path, self.questions_path, self.answers_path, self.eval_path, self.report_path]: + path.parent.mkdir(parents=True, exist_ok=True) + self.checkpoint = _open_checkpoint(checkpoint, self.answers_path) + + def _resolve_question_source(self, custom_questions_path: Optional[Path], questions_from: Optional[Path], + force_regen: bool) -> None: + """Set the custom question file, and whether a golden set pins the run (called by ``__init__``).""" # Golden question set: explicit path wins; otherwise look for the # convention name _golden.json under the caller-supplied # questions root (the question sets live outside this repository). - self.questions_root = Path(questions_root) if questions_root else None # A golden set found under the root *is* the question set: generation is # skipped, so two runs on one root answer the same questions. An explicit # custom_questions_path is still merged into generated questions. @@ -247,25 +256,8 @@ def __init__( if questions_from is None and self.questions_root is None: warn_unpinned_questions(self.output_dir / "questions" / f"{self.product_key}.json", force_regen, self.product_key) - self.model = model - self.provider = provider - self.judge_model = judge_model - self.judge_provider = judge_provider - self.judge_temperature = judge_temperature - _warn_judge_placeholder(judge_placeholder) - - self.personas_count = personas_count - self.questions_per_topic = questions_per_topic - self.top_k = top_k - self.rerank_threshold = rerank_threshold - self.debug_retrieval = debug_retrieval - self.doc_source = doc_source - self.context7_id = context7_id - # Product registry for the library id (defaults to the bundled products.yaml). - self.registry = registry - self.max_tokens_per_question = max_tokens_per_question - self.force_regen = force_regen - + def _resolve_external_questions(self, questions_from: Optional[Path]) -> None: + """Set ``external_questions_path``: the --questions-from set this run reuses, if one is given.""" # External questions source (skip generation, load from this path/dir) if questions_from is not None: # Accept either a directory (auto-find .json) or a file path. @@ -282,27 +274,15 @@ def __init__( else: self.external_questions_path = None - # Output paths - self.personas_path = self.output_dir / "personas" / f"{self.product_key}.json" - self.questions_path = self.output_dir / "questions" / f"{self.product_key}.json" - self.answers_path = self.output_dir / "answers" / f"{self.product_key}.json" - self.eval_path = self.output_dir / "eval" / f"{self.product_key}.json" - self.report_path = self.output_dir / "reports" / f"{self.product_key}.md" - - # Create output dirs - for path in [self.personas_path, self.questions_path, self.answers_path, self.eval_path, self.report_path]: - path.parent.mkdir(parents=True, exist_ok=True) - self.checkpoint = _open_checkpoint(checkpoint, self.answers_path) - def run(self, concurrency: int = 5) -> Dict[str, Any]: """ Run full pipeline. - + Returns: Summary dict with results and paths """ logger.info(f"Starting evaluation pipeline for {self.product}") - + results: Dict[str, Any] = { "product": self.product, "repo": self.repo, @@ -313,7 +293,48 @@ def run(self, concurrency: int = 5) -> Dict[str, Any]: # model call: --questions-from, the cached set, or --questions. reused = self._read_question_inputs() - # Step 1: Discover personas (cached if already exists) + personas = self._personas_step(results) + merged_questions, write_over_input = self._questions_step(personas, reused, results) + self._require_questions(merged_questions) + # Compute and record question_set_hash for reproducibility + question_set_hash = compute_question_set_hash(merged_questions) + results["question_set_hash"] = question_set_hash + self._save_questions_artifact(merged_questions, question_set_hash, write_over_input=write_over_input) + print(f" question_set_hash: {question_set_hash}") + + # Step 4: Generate answers + logger.info("Step 4/6: Generating context-arm and baseline answers...") + answers = self._generate_answers(merged_questions, concurrency=concurrency, + question_set_hash=question_set_hash) + results["steps"]["answers"] = { + "count": len(answers), + "path": str(self.answers_path) + } + print(f"✓ Generated answers for {len(answers)} questions") + + # Step 5: Evaluate answers + logger.info("Step 5/6: Evaluating answers...") + evaluations = self._evaluate_answers(answers, concurrency=concurrency, + question_set_hash=question_set_hash) + results["steps"]["evaluation"] = { + "count": len(evaluations), + "path": str(self.eval_path) + } + self._summarize_evaluations(evaluations, results) + + # Step 6: Generate report + logger.info("Step 6/6: Generating report...") + self._generate_report(evaluations, merged_questions) + results["steps"]["report"] = { + "path": str(self.report_path) + } + print(f"✓ Generated report: {self.report_path}") + + results["status"] = "success" + return results + + def _personas_step(self, results: Dict[str, Any]) -> Dict[str, Any]: + """Step 1: the personas questions are generated from (cached unless forced); none when the set is pinned or reused.""" # Skip if using golden pinned or external questions (personas not needed) if self.golden_pinned or self.external_questions_path is not None: logger.info("Step 1/6: Skipping persona discovery (using pinned or external questions)") @@ -334,121 +355,123 @@ def run(self, concurrency: int = 5) -> Dict[str, Any]: "count": len(personas.get("personas", [])), "path": str(self.personas_path) } + return personas - # Step 2+3: Generate & merge questions (external / cached / fresh) - write_over_input = False # Default: never write over input files + def _questions_step(self, personas: Dict[str, Any], reused: Optional[List[Dict[str, Any]]], + results: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], bool]: + """Steps 2-3: the merged question set, and whether a ``--questions`` file this run wrote is written over. + The external (--questions-from), cached and golden sets are reused as read; otherwise the set is generated and merged. + """ if self.external_questions_path is not None: - # Reuse question set from another run — skip generation entirely - logger.info(f"Step 2-3/6: Loading external questions from {self.external_questions_path}...") - merged_questions = reused or [] - print(f"✓ Loaded {len(merged_questions)} questions (from --questions-from, skipping generation)") - results["steps"]["questions_generated"] = { - "count": len(merged_questions), - "external_source": str(self.external_questions_path), - } - results["steps"]["questions_merged"] = { - "total": len(merged_questions), - "external_source": str(self.external_questions_path), - "path": str(self.questions_path), - } - elif (not self.force_regen) and self.questions_path.exists(): - logger.info("Step 2-3/6: Loading cached questions (skipping generation)...") - merged_questions = reused or [] - print(f"✓ Loaded {len(merged_questions)} questions (cached — skipping generation)") - # Warn if cached questions differ from the golden set - if self.golden_pinned and self.custom_questions_path is not None: - try: - golden_questions = load_questions_payload(self.custom_questions_path) - cached_hash = compute_question_set_hash(merged_questions) - golden_hash = compute_question_set_hash(golden_questions) - if cached_hash != golden_hash: - cached_count = len(merged_questions) - golden_count = len(golden_questions) - logger.warning( - f"cached question set (n={cached_count}, hash={cached_hash}) differs from " - f"golden set (n={golden_count}, hash={golden_hash}); " - f"use a fresh output directory (or --force with benchmark run) to use the golden set" - ) - except (json.JSONDecodeError, ValueError, TypeError, AttributeError, OSError) as e: + return self._external_questions(reused, results), False + if (not self.force_regen) and self.questions_path.exists(): + return self._cached_questions(reused, results), False + if self.golden_pinned: + return self._golden_questions(results), False + return self._generated_questions(personas, results) + + def _external_questions(self, reused: Optional[List[Dict[str, Any]]], results: Dict[str, Any]) -> List[Dict[str, Any]]: + """Reuse the question set of another run (--questions-from): generation is skipped entirely.""" + logger.info(f"Step 2-3/6: Loading external questions from {self.external_questions_path}...") + merged_questions = reused or [] + print(f"✓ Loaded {len(merged_questions)} questions (from --questions-from, skipping generation)") + results["steps"]["questions_generated"] = { + "count": len(merged_questions), + "external_source": str(self.external_questions_path), + } + results["steps"]["questions_merged"] = { + "total": len(merged_questions), + "external_source": str(self.external_questions_path), + "path": str(self.questions_path), + } + return merged_questions + + def _cached_questions(self, reused: Optional[List[Dict[str, Any]]], results: Dict[str, Any]) -> List[Dict[str, Any]]: + """Reuse the question set this output directory already holds: generation is skipped.""" + logger.info("Step 2-3/6: Loading cached questions (skipping generation)...") + merged_questions = reused or [] + print(f"✓ Loaded {len(merged_questions)} questions (cached — skipping generation)") + # Warn if cached questions differ from the golden set + if self.golden_pinned and self.custom_questions_path is not None: + try: + golden_questions = load_questions_payload(self.custom_questions_path) + cached_hash = compute_question_set_hash(merged_questions) + golden_hash = compute_question_set_hash(golden_questions) + if cached_hash != golden_hash: + cached_count = len(merged_questions) + golden_count = len(golden_questions) logger.warning( - f"Could not load golden set for comparison: {e}; " - f"using cached questions" + f"cached question set (n={cached_count}, hash={cached_hash}) differs from " + f"golden set (n={golden_count}, hash={golden_hash}); " + f"use a fresh output directory (or --force with benchmark run) to use the golden set" ) - results["steps"]["questions_generated"] = {"count": len(merged_questions), "cached": True} - results["steps"]["questions_merged"] = {"total": len(merged_questions), "cached": True, - "path": str(self.questions_path)} - elif self.golden_pinned: - logger.info(f"Step 2-3/6: Loading golden questions from {self.custom_questions_path}...") - # Read (and refused, if unusable) before any model call by _read_question_inputs. - merged_questions = getattr(self, "_custom_questions", None) or self._load_custom_questions() - if not merged_questions: - raise ValueError(f"Golden set is empty: {self.custom_questions_path}") - print(f"✓ Loaded {len(merged_questions)} golden questions (skipping generation)") - results["steps"]["questions_generated"] = { - "count": len(merged_questions), - "golden_source": str(self.custom_questions_path), - } - results["steps"]["questions_merged"] = { - "total": len(merged_questions), - "manual": len(merged_questions), - "golden_source": str(self.custom_questions_path), - "path": str(self.questions_path), - } - else: - logger.info("Step 2/6: Generating questions...") - generated_questions = self._generate_questions(personas) - results["steps"]["questions_generated"] = { - "count": len(generated_questions), - "path": "temp" - } - print(f"✓ Generated {len(generated_questions)} questions from personas") - - # Step 3: Merge with custom questions + deduplicate - logger.info("Step 3/6: Merging and deduplicating questions...") - read_custom = getattr(self, "_custom_questions", None) - read_snapshot = None if read_custom is None else _canonical(read_custom) - merged_questions = self._merge_questions(generated_questions) - # A --questions file that is this run's own output is written only when the - # merged set differs from what was read from it; without a read set, never. - write_over_input = read_snapshot is not None and _canonical(merged_questions) != read_snapshot - - results["steps"]["questions_merged"] = { - "total": len(merged_questions), - "generated": sum(1 for q in merged_questions if q.get("source_type") == "generated"), - "manual": sum(1 for q in merged_questions if q.get("source_type") == "manual"), - "path": str(self.questions_path) - } - print(f"✓ Merged to {len(merged_questions)} unique questions " - f"({results['steps']['questions_merged']['generated']} generated, " - f"{results['steps']['questions_merged']['manual']} manual)") + except (json.JSONDecodeError, ValueError, TypeError, AttributeError, OSError) as e: + logger.warning( + f"Could not load golden set for comparison: {e}; " + f"using cached questions" + ) + results["steps"]["questions_generated"] = {"count": len(merged_questions), "cached": True} + results["steps"]["questions_merged"] = {"total": len(merged_questions), "cached": True, + "path": str(self.questions_path)} + return merged_questions + + def _golden_questions(self, results: Dict[str, Any]) -> List[Dict[str, Any]]: + """The golden set of ``questions_root`` is the whole question set; generation is skipped.""" + logger.info(f"Step 2-3/6: Loading golden questions from {self.custom_questions_path}...") + # Read (and refused, if unusable) before any model call by _read_question_inputs. + merged_questions = getattr(self, "_custom_questions", None) or self._load_custom_questions() + if not merged_questions: + raise ValueError(f"Golden set is empty: {self.custom_questions_path}") + print(f"✓ Loaded {len(merged_questions)} golden questions (skipping generation)") + results["steps"]["questions_generated"] = { + "count": len(merged_questions), + "golden_source": str(self.custom_questions_path), + } + results["steps"]["questions_merged"] = { + "total": len(merged_questions), + "manual": len(merged_questions), + "golden_source": str(self.custom_questions_path), + "path": str(self.questions_path), + } + return merged_questions - self._require_questions(merged_questions) - # Compute and record question_set_hash for reproducibility - question_set_hash = compute_question_set_hash(merged_questions) - results["question_set_hash"] = question_set_hash - self._save_questions_artifact(merged_questions, question_set_hash, write_over_input=write_over_input) - print(f" question_set_hash: {question_set_hash}") + def _generated_questions(self, personas: Dict[str, Any], + results: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], bool]: + """Generate the questions from the personas and merge them with the custom set. - # Step 4: Generate answers - logger.info("Step 4/6: Generating context-arm and baseline answers...") - answers = self._generate_answers(merged_questions, concurrency=concurrency, - question_set_hash=question_set_hash) - results["steps"]["answers"] = { - "count": len(answers), - "path": str(self.answers_path) + Returns the merged set and whether the run's ``--questions`` input is written over (see below). + """ + logger.info("Step 2/6: Generating questions...") + generated_questions = self._generate_questions(personas) + results["steps"]["questions_generated"] = { + "count": len(generated_questions), + "path": "temp" } - print(f"✓ Generated answers for {len(answers)} questions") - - # Step 5: Evaluate answers - logger.info("Step 5/6: Evaluating answers...") - evaluations = self._evaluate_answers(answers, concurrency=concurrency, - question_set_hash=question_set_hash) - results["steps"]["evaluation"] = { - "count": len(evaluations), - "path": str(self.eval_path) + print(f"✓ Generated {len(generated_questions)} questions from personas") + + # Step 3: Merge with custom questions + deduplicate + logger.info("Step 3/6: Merging and deduplicating questions...") + read_custom = getattr(self, "_custom_questions", None) + read_snapshot = None if read_custom is None else _canonical(read_custom) + merged_questions = self._merge_questions(generated_questions) + # A --questions file that is this run's own output is written only when the + # merged set differs from what was read from it; without a read set, never. + write_over_input = read_snapshot is not None and _canonical(merged_questions) != read_snapshot + + results["steps"]["questions_merged"] = { + "total": len(merged_questions), + "generated": sum(1 for q in merged_questions if q.get("source_type") == "generated"), + "manual": sum(1 for q in merged_questions if q.get("source_type") == "manual"), + "path": str(self.questions_path) } - + print(f"✓ Merged to {len(merged_questions)} unique questions " + f"({results['steps']['questions_merged']['generated']} generated, " + f"{results['steps']['questions_merged']['manual']} manual)") + return merged_questions, write_over_input + + def _summarize_evaluations(self, evaluations: List[Dict[str, Any]], results: Dict[str, Any]) -> None: + """Step 5's summary: the paired means and delta over the complete pairs, printed and kept in ``results``.""" # Summary stats over the complete pairs, the numbers the reports print for the same file. summary = paired_summary(evaluations) ask_count = len(evaluations) - summary.total @@ -472,18 +495,7 @@ def run(self, concurrency: int = 5) -> Dict[str, Any]: if summary.unpaired else "") + ask_note) else: print(f"✓ Evaluated {len(evaluations)} answers (summary unavailable){ask_note}") - - # Step 6: Generate report - logger.info("Step 6/6: Generating report...") - self._generate_report(evaluations, merged_questions) - results["steps"]["report"] = { - "path": str(self.report_path) - } - print(f"✓ Generated report: {self.report_path}") - - results["status"] = "success" - return results - + def _discover_personas(self) -> Dict[str, Any]: """Discover personas — from GitHub repo or from a plain description.""" import os diff --git a/dokimi/dokimi/orchestrator/question_sets.py b/dokimi/dokimi/orchestrator/question_sets.py new file mode 100644 index 000000000..a9961b43e --- /dev/null +++ b/dokimi/dokimi/orchestrator/question_sets.py @@ -0,0 +1,39 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The question sets a run reads and hashes: the questions.v2 records, the set hash and the path rule.""" + +import hashlib +from pathlib import Path +from typing import Any, Dict, List, Optional + + +def resolve_questions_from_path(questions_from: Path, product_slug: str) -> Path: + """Resolve a --questions-from file or run directory for a target slug.""" + qf = Path(questions_from) + if qf.is_dir(): + qf = qf / "questions" / f"{product_slug}.json" + return qf + + +def compute_question_set_hash(questions: List[Dict[str, Any]]) -> str: + """Return 12-char SHA-256 prefix over sorted question texts + ids.""" + fingerprints = sorted( + f"{q.get('id', '')}:{q.get('question', q.get('question_text', q.get('text', '')))}" + for q in questions + ) + raw = "\n".join(fingerprints).encode("utf-8", "surrogatepass") # a `\ud800` JSON escape loads as a lone surrogate + return hashlib.sha256(raw).hexdigest()[:12] + + +def load_questions_payload(path: Path, flag: Optional[str] = None) -> List[Dict[str, Any]]: + """The records of the question set at ``path``, in the questions.v2 shape. + + :func:`dokimi.questions.artifact.load_questions` reads it: v1, v2, a bare list, or a legacy + shape (logged once); a set still invalid after that raises ``ArtifactValidationError`` (a + ``ValueError``) naming the record. ``flag`` is the option ``path`` came from: a file that is + not UTF-8 or JSON then raises ``InputError`` `` : ``. ``path`` is not written. + """ + from dokimi.questions.artifact import load_questions + + return load_questions(path, flag=flag).questions diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index e67df758f..532dc4532 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -42,7 +42,6 @@ "dokimi/novelty/probes.py::build_probe_set": {"complexity": 12}, "dokimi/novelty/probes.py::check_wording": {"complexity": 13}, "dokimi/novelty/report.py::render_novelty_markdown": {"complexity": 15}, - "dokimi/orchestrator/pipeline.py::EvaluationPipeline.run": {"complexity": 11}, "dokimi/plugins.py::create_plugin": {"complexity": 11}, "dokimi/process.py::_select_pipes": {"complexity": 13}, "dokimi/questions/validator.py::QuestionValidator.__init__": {"complexity": 11}, From 5376ea744d05b83402301383b759d2651fbdf6e2 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Fri, 4 Dec 2026 23:20:38 -0800 Subject: [PATCH 2/5] refactor(pipeline): take the run's inputs as an EvaluationSettings EvaluationPipeline.__init__ takes an EvaluationSettings dataclass with the same fields and defaults as the keyword arguments it had. The production callers (benchmark run and evaluate) pass settings=. The keyword form still works: it builds the settings, and a refusal reads the same as before. Signed-off-by: Nikolay Petrov --- dokimi/dokimi/commands/benchmark.py | 6 +- dokimi/dokimi/commands/orchestrate.py | 6 +- dokimi/dokimi/orchestrator/__init__.py | 3 +- dokimi/dokimi/orchestrator/pipeline.py | 155 ++++++------------ .../dokimi/orchestrator/pipeline_settings.py | 95 +++++++++++ dokimi/tests/test_answering_stack_p_step2.py | 3 +- .../test_benchmark_command_question_set.py | 4 +- .../tests/test_benchmark_registry_wiring.py | 3 +- dokimi/tests/test_pipeline_question_set.py | 4 +- dokimi/tests/test_pipeline_settings.py | 64 ++++++++ 10 files changed, 227 insertions(+), 116 deletions(-) create mode 100644 dokimi/dokimi/orchestrator/pipeline_settings.py create mode 100644 dokimi/tests/test_pipeline_settings.py diff --git a/dokimi/dokimi/commands/benchmark.py b/dokimi/dokimi/commands/benchmark.py index 591dc1fd4..5d58a0847 100644 --- a/dokimi/dokimi/commands/benchmark.py +++ b/dokimi/dokimi/commands/benchmark.py @@ -52,7 +52,7 @@ def _refuse_judge_sampling(args: argparse.Namespace) -> None: def _run_single_library(entry, output_dir: str, model: str, provider: str, judge_model: str, judge_provider: str = DEFAULT_JUDGE_PROVIDER, doc_source_override=None, max_tokens_per_question: int = DEFAULT_MAX_TOKENS_PER_QUESTION, force_regen: bool = False, concurrency: int = DEFAULT_CONCURRENCY, questions_from=None, questions_root=None, judge_temperature=None, judge_placeholder=False, registry=None) -> dict: """Run full evaluation pipeline for one ProductEntry. Returns result dict.""" from dokimi.commands.arms import pipeline_checkpoint - from dokimi.orchestrator import EvaluationPipeline + from dokimi.orchestrator import EvaluationPipeline, EvaluationSettings from pathlib import Path as _Path doc_source = doc_source_override or (entry.doc_sources[0] if entry.doc_sources else "context7") @@ -72,7 +72,7 @@ def _run_single_library(entry, output_dir: str, model: str, provider: str, judge context=f"benchmark:{entry.key}", ) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product=entry.name, repo=entry.repo, description=entry.description, @@ -94,7 +94,7 @@ def _run_single_library(entry, output_dir: str, model: str, provider: str, judge registry=registry, questions_root=_Path(questions_root) if questions_root else None, checkpoint=pipeline_checkpoint, # the answered questions, until the answers file is saved (#1004) - ) + )) result = pipeline.run(concurrency=concurrency) return {"library": entry.key, "name": entry.name, "status": "ok", "result": result} diff --git a/dokimi/dokimi/commands/orchestrate.py b/dokimi/dokimi/commands/orchestrate.py index 4cbcf66e7..7d5b19908 100644 --- a/dokimi/dokimi/commands/orchestrate.py +++ b/dokimi/dokimi/commands/orchestrate.py @@ -31,7 +31,7 @@ def cmd_evaluate(args: argparse.Namespace) -> None: """Run full evaluation pipeline (orchestrator).""" from dokimi.commands.arms import pipeline_checkpoint from dokimi.mcp.factory import require_local_doc_source - from dokimi.orchestrator import EvaluationPipeline + from dokimi.orchestrator import EvaluationPipeline, EvaluationSettings if not getattr(args, "repo", None) and not getattr(args, "description", None): raise InputError("either --repo or --description must be provided.") @@ -65,7 +65,7 @@ def cmd_evaluate(args: argparse.Namespace) -> None: require_local_doc_source(getattr(args, "doc_source", "context7")) # Create pipeline; it checks --questions and creates the output directories try: - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product=args.product, repo=getattr(args, "repo", None), description=getattr(args, "description", None), @@ -87,7 +87,7 @@ def cmd_evaluate(args: argparse.Namespace) -> None: doc_source=getattr(args, "doc_source", "context7"), context7_id=getattr(args, "context7_id", None), checkpoint=pipeline_checkpoint, # the answered questions, until the answers file is saved (#1004) - ) + )) except OSError as exc: # a missing --questions file, an unusable --out-dir raise InputError(str(exc)) from exc diff --git a/dokimi/dokimi/orchestrator/__init__.py b/dokimi/dokimi/orchestrator/__init__.py index 6556a867b..aff240299 100644 --- a/dokimi/dokimi/orchestrator/__init__.py +++ b/dokimi/dokimi/orchestrator/__init__.py @@ -4,5 +4,6 @@ """Pipeline orchestration module.""" from .pipeline import EvaluationPipeline +from .pipeline_settings import EvaluationSettings -__all__ = ["EvaluationPipeline"] +__all__ = ["EvaluationPipeline", "EvaluationSettings"] diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 19a78ceac..304c5b765 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -7,20 +7,20 @@ import logging import json import sys +from dataclasses import fields from typing import Any, Callable, Dict, List, Optional, Tuple from pathlib import Path from dokimi.artifacts import save_artifact from dokimi.atomic_write import write_bytes_in_place_or_atomic from dokimi.process_io import text_file_bytes -from dokimi.defaults import (DEFAULT_ANSWER_MODEL, DEFAULT_ANSWER_PROVIDER, DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER, - DEFAULT_RETRIEVAL_TOP_K) from dokimi.eval.stats import paired_summary from dokimi.mcp.factory import create_doc_source_client, require_local_doc_source, resolve_library_id_for_product from dokimi.orchestrator.arm_answering import Checkpoint, PipelineArms from dokimi.files import InputError, read_json_input, refuse_device from dokimi.digest import key_bytes +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.orchestrator.question_source import warn_unpinned_questions from dokimi.orchestrator.question_sets import ( compute_question_set_hash, load_questions_payload, resolve_questions_from_path) @@ -98,118 +98,67 @@ class EvaluationPipeline: 6. Generate report """ - def __init__( - self, - product: str, - output_dir: Path, - repo: Optional[str] = None, - description: Optional[str] = None, - custom_questions_path: Optional[Path] = None, - model: str = DEFAULT_ANSWER_MODEL, - provider: str = DEFAULT_ANSWER_PROVIDER, - judge_model: str = DEFAULT_JUDGE_MODEL, - judge_provider: str = DEFAULT_JUDGE_PROVIDER, - judge_temperature: Optional[float] = None, - personas_count: int = 5, - questions_per_topic: int = 2, - top_k: int = DEFAULT_RETRIEVAL_TOP_K, - rerank_threshold: float = 0.3, - debug_retrieval: bool = False, - doc_source: str = "context7", - context7_id: Optional[str] = None, - max_tokens_per_question: int = 4000, - force_regen: bool = False, - questions_from: Optional[Path] = None, - product_key: Optional[str] = None, - questions_root: Optional[Path] = None, - registry: Optional[Any] = None, - judge_placeholder: bool = False, - checkpoint: Optional[Callable[[Path], Checkpoint]] = None, - ): + def __init__(self, *args: Any, settings: Optional[EvaluationSettings] = None, **kwargs: Any): """ Initialize pipeline. - Args: - product: Product name (e.g., "oneDNN") - output_dir: Base directory for outputs - repo: GitHub repo (e.g., "oneapi-src/oneDNN"). Optional — when - omitted, ``description`` must be provided so the LLM can - generate personas without GitHub data. - description: Plain-text description of the product. Used as the - sole signal for persona generation when ``repo`` is not given. - Also useful to supplement GitHub data. - custom_questions_path: Optional path to manual questions JSON - model: LLM model for generation/answering - provider: Provider for generation/answering - judge_model: LLM model for evaluation - judge_provider: Provider for evaluation - judge_temperature: Optional judge sampling temperature; unset leaves - the provider default - personas_count: Target number of personas - questions_per_topic: Questions per topic per persona - top_k: Docs to retrieve before reranking - rerank_threshold: Min relevance score - debug_retrieval: Include retrieval metadata - doc_source: Documentation source descriptor — 'context7' (default), - 'local:', or 'url:' - context7_id: Explicit Context7 library ID (e.g., 'intel/mkl-dnn'). - Overrides the auto-resolved ID when doc_source is 'context7'. - questions_from: Reuse an existing question set (file, or a run - directory holding questions/.json). - product_key: Registry key used for output file names and golden - question-set lookup (defaults to ``product``). - questions_root: Directory holding golden question sets named - ``_golden.json``, for example a checkout of the - evaluation-content repository. When given and the file is - present it is the run's whole question set and generation is - skipped; when it is absent a warning is logged and questions are - generated. Without this argument (and without - ``custom_questions_path``) the run has no golden set. - registry: ProductRegistry used to find the declared context7_id - (default: the bundled products.yaml) - judge_placeholder: No effect, warned: since method version 4 the - context arm answers a question with no document found with the - plain prompt, and that answer is judged (#228 step 4c) - checkpoint: Makes the file the answered questions are kept in until - the answers file is saved, from the answers path - (``commands.arms.pipeline_checkpoint``); none by default + Takes the run's inputs as an :class:`EvaluationSettings` (``settings=``), or as + the same fields given as keyword arguments, which build one. The fields are + described on :class:`EvaluationSettings`. The fields may also be given + positionally, in field order, as the keyword signature always allowed. """ - if not repo and not description: + if args: + names = [f.name for f in fields(EvaluationSettings)] + if len(args) > len(names): + raise TypeError(f"EvaluationPipeline.__init__() takes from 3 to {len(names) + 1} positional " + f"arguments but {len(args) + 1} were given") + for name, value in zip(names, args, strict=False): + if name in kwargs: + raise TypeError(f"EvaluationPipeline.__init__() got multiple values for argument '{name}'") + kwargs[name] = value + if settings is None: + try: + settings = EvaluationSettings(**kwargs) + except TypeError as exc: # the refusal the keyword signature gave before, under this class's name + raise TypeError(str(exc).replace("EvaluationSettings.__init__()", "EvaluationPipeline.__init__()", 1)) from None + elif kwargs: + raise TypeError("EvaluationPipeline() takes settings or keyword arguments, not both") + if not settings.repo and not settings.description: raise ValueError( "Either 'repo' or 'description' must be provided. " "Supply 'repo' for GitHub-based persona discovery, or " "'description' for products without a public repository." ) - self.product = product - self.product_key = product_key or product - self.repo = repo - self.description = description - self.output_dir = Path(output_dir) - - self.questions_root = Path(questions_root) if questions_root else None - self._resolve_question_source(custom_questions_path, questions_from, force_regen) - - self.model = model - self.provider = provider - self.judge_model = judge_model - self.judge_provider = judge_provider - self.judge_temperature = judge_temperature - _warn_judge_placeholder(judge_placeholder) - - self.personas_count = personas_count - self.questions_per_topic = questions_per_topic - self.top_k = top_k - self.rerank_threshold = rerank_threshold - self.debug_retrieval = debug_retrieval - self.doc_source = doc_source - self.context7_id = context7_id + self.product = settings.product + self.product_key = settings.product_key or settings.product + self.repo = settings.repo + self.description = settings.description + self.output_dir = Path(settings.output_dir) + + self.questions_root = Path(settings.questions_root) if settings.questions_root else None + self._resolve_question_source(settings.custom_questions_path, settings.questions_from, settings.force_regen) + + self.model = settings.model + self.provider = settings.provider + self.judge_model = settings.judge_model + self.judge_provider = settings.judge_provider + self.judge_temperature = settings.judge_temperature + _warn_judge_placeholder(settings.judge_placeholder) + + self.personas_count = settings.personas_count + self.questions_per_topic = settings.questions_per_topic + self.top_k = settings.top_k + self.rerank_threshold = settings.rerank_threshold + self.debug_retrieval = settings.debug_retrieval + self.doc_source = settings.doc_source + self.context7_id = settings.context7_id # Product registry for the library id (defaults to the bundled products.yaml). - self.registry = registry - self.max_tokens_per_question = max_tokens_per_question - self.force_regen = force_regen + self.registry = settings.registry + self.max_tokens_per_question = settings.max_tokens_per_question + self.force_regen = settings.force_regen - self._resolve_external_questions(questions_from) + self._resolve_external_questions(settings.questions_from) # Output paths self.personas_path = self.output_dir / "personas" / f"{self.product_key}.json" @@ -221,7 +170,7 @@ def __init__( # Create output dirs for path in [self.personas_path, self.questions_path, self.answers_path, self.eval_path, self.report_path]: path.parent.mkdir(parents=True, exist_ok=True) - self.checkpoint = _open_checkpoint(checkpoint, self.answers_path) + self.checkpoint = _open_checkpoint(settings.checkpoint, self.answers_path) def _resolve_question_source(self, custom_questions_path: Optional[Path], questions_from: Optional[Path], force_regen: bool) -> None: diff --git a/dokimi/dokimi/orchestrator/pipeline_settings.py b/dokimi/dokimi/orchestrator/pipeline_settings.py new file mode 100644 index 000000000..8e04b7486 --- /dev/null +++ b/dokimi/dokimi/orchestrator/pipeline_settings.py @@ -0,0 +1,95 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Settings for one run of :class:`~dokimi.orchestrator.pipeline.EvaluationPipeline`.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Optional + +from dokimi.defaults import (DEFAULT_ANSWER_MODEL, DEFAULT_ANSWER_PROVIDER, DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER, + DEFAULT_RETRIEVAL_TOP_K) +from dokimi.orchestrator.arm_answering import Checkpoint + + +@dataclass(frozen=True) +class EvaluationSettings: + """ + The inputs of one pipeline run. ``EvaluationPipeline(settings=...)`` takes this + object; ``EvaluationPipeline(**fields)`` builds it from the same fields. + + Fields: + product: Product name (e.g., "oneDNN") + output_dir: Base directory for outputs + repo: GitHub repo (e.g., "oneapi-src/oneDNN"). Optional — when + omitted, ``description`` must be provided so the LLM can + generate personas without GitHub data. + description: Plain-text description of the product. Used as the + sole signal for persona generation when ``repo`` is not given. + Also useful to supplement GitHub data. + custom_questions_path: Optional path to manual questions JSON + model: LLM model for generation/answering + provider: Provider for generation/answering + judge_model: LLM model for evaluation + judge_provider: Provider for evaluation + judge_temperature: Optional judge sampling temperature; unset leaves + the provider default + personas_count: Target number of personas + questions_per_topic: Questions per topic per persona + top_k: Docs to retrieve before reranking + rerank_threshold: Min relevance score + debug_retrieval: Include retrieval metadata + doc_source: Documentation source descriptor — 'context7' (default), + 'local:', or 'url:' + context7_id: Explicit Context7 library ID (e.g., 'intel/mkl-dnn'). + Overrides the auto-resolved ID when doc_source is 'context7'. + max_tokens_per_question: Output token budget per question + force_regen: Regenerate the question set even when a cached one exists + questions_from: Reuse an existing question set (file, or a run + directory holding questions/.json). + product_key: Registry key used for output file names and golden + question-set lookup (defaults to ``product``). + questions_root: Directory holding golden question sets named + ``_golden.json``, for example a checkout of the + evaluation-content repository. When given and the file is + present it is the run's whole question set and generation is + skipped; when it is absent a warning is logged and questions are + generated. Without this argument (and without + ``custom_questions_path``) the run has no golden set. + registry: ProductRegistry used to find the declared context7_id + (default: the bundled products.yaml) + judge_placeholder: No effect, warned: since method version 4 the + context arm answers a question with no document found with the + plain prompt, and that answer is judged (#228 step 4c) + checkpoint: Makes the file the answered questions are kept in until + the answers file is saved, from the answers path + (``commands.arms.pipeline_checkpoint``); none by default + """ + + product: str + output_dir: Path + repo: Optional[str] = None + description: Optional[str] = None + custom_questions_path: Optional[Path] = None + model: str = DEFAULT_ANSWER_MODEL + provider: str = DEFAULT_ANSWER_PROVIDER + judge_model: str = DEFAULT_JUDGE_MODEL + judge_provider: str = DEFAULT_JUDGE_PROVIDER + judge_temperature: Optional[float] = None + personas_count: int = 5 + questions_per_topic: int = 2 + top_k: int = DEFAULT_RETRIEVAL_TOP_K + rerank_threshold: float = 0.3 + debug_retrieval: bool = False + doc_source: str = "context7" + context7_id: Optional[str] = None + max_tokens_per_question: int = 4000 + force_regen: bool = False + questions_from: Optional[Path] = None + product_key: Optional[str] = None + questions_root: Optional[Path] = None + registry: Optional[Any] = None + judge_placeholder: bool = False + checkpoint: Optional[Callable[[Path], Checkpoint]] = None diff --git a/dokimi/tests/test_answering_stack_p_step2.py b/dokimi/tests/test_answering_stack_p_step2.py index f9a53ae63..5b8a836e4 100644 --- a/dokimi/tests/test_answering_stack_p_step2.py +++ b/dokimi/tests/test_answering_stack_p_step2.py @@ -26,7 +26,8 @@ class _FakePipeline: built: list = [] - def __init__(self, **kwargs): + def __init__(self, settings): + kwargs = vars(settings) _FakePipeline.built.append(kwargs) self.answers_path = kwargs["output_dir"] / "answers" / f"{kwargs['product_key']}.json" diff --git a/dokimi/tests/test_benchmark_command_question_set.py b/dokimi/tests/test_benchmark_command_question_set.py index d96892ecd..9d6fea90e 100644 --- a/dokimi/tests/test_benchmark_command_question_set.py +++ b/dokimi/tests/test_benchmark_command_question_set.py @@ -161,8 +161,8 @@ def test_questions_root_reaches_the_pipeline(monkeypatch, tmp_path): seen: dict[str, object] = {} class FakePipeline: - def __init__(self, **kwargs): - seen.update(kwargs) + def __init__(self, settings): + seen.update(vars(settings)) def run(self, concurrency=5): return {} diff --git a/dokimi/tests/test_benchmark_registry_wiring.py b/dokimi/tests/test_benchmark_registry_wiring.py index 3ce13f3fa..05b324455 100644 --- a/dokimi/tests/test_benchmark_registry_wiring.py +++ b/dokimi/tests/test_benchmark_registry_wiring.py @@ -48,7 +48,8 @@ class _Spy: built: list = [] - def __init__(self, **kwargs): + def __init__(self, settings): + kwargs = vars(settings) # every field is also a keyword: EvaluationPipeline(**kwargs) takes them back self.kwargs = kwargs _Spy.built.append(kwargs) diff --git a/dokimi/tests/test_pipeline_question_set.py b/dokimi/tests/test_pipeline_question_set.py index 8166a6c17..57f063f2f 100644 --- a/dokimi/tests/test_pipeline_question_set.py +++ b/dokimi/tests/test_pipeline_question_set.py @@ -228,8 +228,8 @@ def test_evaluate_command_forwards_questions_root(tmp_path, monkeypatch): seen: dict[str, object] = {} class FakePipeline: - def __init__(self, **kwargs): - seen.update(kwargs) + def __init__(self, settings): + seen.update(vars(settings)) def run(self, concurrency=5): return { diff --git a/dokimi/tests/test_pipeline_settings.py b/dokimi/tests/test_pipeline_settings.py new file mode 100644 index 000000000..3c172963e --- /dev/null +++ b/dokimi/tests/test_pipeline_settings.py @@ -0,0 +1,64 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""EvaluationPipeline takes its inputs as an EvaluationSettings, or as the same fields as keywords.""" + +from dataclasses import fields +from pathlib import Path + +import pytest + +from dokimi.orchestrator import EvaluationPipeline, EvaluationSettings + + +def _attrs(pipe): + return {k: v for k, v in sorted(vars(pipe).items()) if not callable(v)} + + +def test_settings_and_keywords_build_the_same_pipeline(tmp_path): + kwargs = dict(product="oneTBB", output_dir=tmp_path / "run", description="d", model="m", top_k=7) + by_keywords = EvaluationPipeline(**kwargs) + by_settings = EvaluationPipeline(settings=EvaluationSettings(**kwargs)) + assert _attrs(by_settings) == _attrs(by_keywords) + + +def test_positional_arguments_fill_the_fields_in_order(tmp_path): + by_position = EvaluationPipeline("oneTBB", tmp_path / "run", "oneapi-src/oneTBB", description=None) + by_keyword = EvaluationPipeline(product="oneTBB", output_dir=tmp_path / "run", repo="oneapi-src/oneTBB", + description=None) + assert _attrs(by_position) == _attrs(by_keyword) + + +def test_a_positional_argument_repeated_as_a_keyword_is_refused(tmp_path): + with pytest.raises(TypeError) as exc: + EvaluationPipeline("oneTBB", tmp_path, product="x", description="d") + assert str(exc.value) == "EvaluationPipeline.__init__() got multiple values for argument 'product'" + + +def test_the_settings_fields_are_the_constructor_keywords(): + names = {f.name for f in fields(EvaluationSettings)} + assert {"product", "output_dir", "questions_root", "checkpoint", "judge_placeholder"} <= names + assert "settings" not in names + + +def test_settings_and_keywords_together_are_refused(tmp_path): + settings = EvaluationSettings(product="oneTBB", output_dir=tmp_path, description="d") + with pytest.raises(TypeError, match="takes settings or keyword arguments, not both"): + EvaluationPipeline(settings=settings, model="m") + + +def test_an_unknown_keyword_is_refused_under_the_pipeline_name(tmp_path): + with pytest.raises(TypeError) as exc: + EvaluationPipeline(product="oneTBB", output_dir=tmp_path, description="d", bogus=1) + assert str(exc.value) == "EvaluationPipeline.__init__() got an unexpected keyword argument 'bogus'" + + +def test_a_missing_required_field_is_refused_under_the_pipeline_name(tmp_path): + with pytest.raises(TypeError) as exc: + EvaluationPipeline(output_dir=tmp_path, description="d") + assert str(exc.value) == "EvaluationPipeline.__init__() missing 1 required positional argument: 'product'" + + +def test_the_settings_are_not_stored_on_the_pipeline(tmp_path): + pipe = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=Path(tmp_path), description="d")) + assert not any(isinstance(v, EvaluationSettings) for v in vars(pipe).values()) From 4394b4a1fa9a1d2cd8ad2c97a74b0baaad1a08c1 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 22:19:40 -0800 Subject: [PATCH 3/5] docs(pipeline): clarify retrieval token budget Thread: PRRT_kwDOVBg7g87AQkCS Signed-off-by: Nikolay Petrov --- .../20261205_221923_nikolay.a.petrov_pipeline-settings.md | 8 ++++++++ dokimi/dokimi/orchestrator/pipeline_settings.py | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md diff --git a/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md b/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md new file mode 100644 index 000000000..8325e54c2 --- /dev/null +++ b/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md @@ -0,0 +1,8 @@ + + +### Added + +- **`EvaluationPipeline` accepts an `EvaluationSettings` object.** Python callers can pass the same run settings as one object with `EvaluationPipeline(settings=...)`. Existing positional and keyword arguments still work. diff --git a/dokimi/dokimi/orchestrator/pipeline_settings.py b/dokimi/dokimi/orchestrator/pipeline_settings.py index 8e04b7486..fdee207ce 100644 --- a/dokimi/dokimi/orchestrator/pipeline_settings.py +++ b/dokimi/dokimi/orchestrator/pipeline_settings.py @@ -45,7 +45,7 @@ class EvaluationSettings: 'local:', or 'url:' context7_id: Explicit Context7 library ID (e.g., 'intel/mkl-dnn'). Overrides the auto-resolved ID when doc_source is 'context7'. - max_tokens_per_question: Output token budget per question + max_tokens_per_question: Token budget for documentation retrieved per question force_regen: Regenerate the question set even when a cached one exists questions_from: Reuse an existing question set (file, or a run directory holding questions/.json). From 5d11fb1614c3ad8de267d02a067b34e5871604af Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 22:22:37 -0800 Subject: [PATCH 4/5] fix(pipeline): preserve argument error order Signed-off-by: Nikolay Petrov --- dokimi/dokimi/orchestrator/pipeline.py | 16 +++------------- dokimi/tests/test_pipeline_settings.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 304c5b765..c48754fc0 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -7,7 +7,6 @@ import logging import json import sys -from dataclasses import fields from typing import Any, Callable, Dict, List, Optional, Tuple from pathlib import Path @@ -107,21 +106,12 @@ def __init__(self, *args: Any, settings: Optional[EvaluationSettings] = None, ** described on :class:`EvaluationSettings`. The fields may also be given positionally, in field order, as the keyword signature always allowed. """ - if args: - names = [f.name for f in fields(EvaluationSettings)] - if len(args) > len(names): - raise TypeError(f"EvaluationPipeline.__init__() takes from 3 to {len(names) + 1} positional " - f"arguments but {len(args) + 1} were given") - for name, value in zip(names, args, strict=False): - if name in kwargs: - raise TypeError(f"EvaluationPipeline.__init__() got multiple values for argument '{name}'") - kwargs[name] = value if settings is None: try: - settings = EvaluationSettings(**kwargs) - except TypeError as exc: # the refusal the keyword signature gave before, under this class's name + settings = EvaluationSettings(*args, **kwargs) + except TypeError as exc: # preserve the original parameter binding error under the pipeline name raise TypeError(str(exc).replace("EvaluationSettings.__init__()", "EvaluationPipeline.__init__()", 1)) from None - elif kwargs: + elif args or kwargs: raise TypeError("EvaluationPipeline() takes settings or keyword arguments, not both") if not settings.repo and not settings.description: raise ValueError( diff --git a/dokimi/tests/test_pipeline_settings.py b/dokimi/tests/test_pipeline_settings.py index 3c172963e..d1bb7ebd7 100644 --- a/dokimi/tests/test_pipeline_settings.py +++ b/dokimi/tests/test_pipeline_settings.py @@ -35,6 +35,16 @@ def test_a_positional_argument_repeated_as_a_keyword_is_refused(tmp_path): assert str(exc.value) == "EvaluationPipeline.__init__() got multiple values for argument 'product'" +@pytest.mark.parametrize(("kwargs", "message"), [ + ({"product": "other"}, "got multiple values for argument 'product'"), + ({"bogus": True}, "got an unexpected keyword argument 'bogus'"), +]) +def test_constructor_reports_bad_keywords_before_excess_positional_arguments(kwargs, message): + with pytest.raises(TypeError) as exc: + EvaluationPipeline(*([None] * 26), **kwargs) + assert str(exc.value) == f"EvaluationPipeline.__init__() {message}" + + def test_the_settings_fields_are_the_constructor_keywords(): names = {f.name for f in fields(EvaluationSettings)} assert {"product", "output_dir", "questions_root", "checkpoint", "judge_placeholder"} <= names From 2580ee49597b8c0d9ce632dc14a41fcde77dfb77 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 23:51:11 -0800 Subject: [PATCH 5/5] refactor(pipeline): EvaluationPipeline takes settings= only The constructor was (*args, settings=None, **kwargs), so mypy could not check the fields of a call. It is now __init__(self, settings: EvaluationSettings). A non-EvaluationSettings value raises TypeError. Every caller moves to settings=EvaluationSettings(...): the production callers were already there; the tests (about 60 sites) and the methodology doc example move too. The keyword and positional forms are refused by the signature. A changed fragment records the API change. Stacked on #1648. Signed-off-by: Nikolay Petrov --- ...1923_nikolay.a.petrov_pipeline-settings.md | 8 -- ...0_napetrov_arch-r15-3-pipeline-settings.md | 3 + dokimi/docs/methodology.md | 2 +- dokimi/dokimi/orchestrator/pipeline.py | 19 +-- .../dokimi/orchestrator/pipeline_settings.py | 2 +- dokimi/scripts/growth_baseline.json | 2 +- dokimi/tests/answering_stack_parity.py | 5 +- .../test_benchmark_command_question_set.py | 7 +- .../tests/test_benchmark_registry_wiring.py | 7 +- dokimi/tests/test_evaluate_cli_inputs.py | 13 +- dokimi/tests/test_input_devices.py | 5 +- .../tests/test_lone_surrogate_cache_keys.py | 5 +- dokimi/tests/test_lone_surrogate_digests.py | 5 +- .../tests/test_missing_doc_source_refused.py | 9 +- dokimi/tests/test_paired_summary_overflow.py | 3 +- dokimi/tests/test_pipeline_arm_runner.py | 5 +- .../tests/test_pipeline_empty_question_set.py | 5 +- .../tests/test_pipeline_independence_flag.py | 5 +- dokimi/tests/test_pipeline_library_id.py | 9 +- dokimi/tests/test_pipeline_question_set.py | 127 +++++++++--------- dokimi/tests/test_pipeline_settings.py | 78 +++++------ dokimi/tests/test_pipeline_summary.py | 3 +- dokimi/tests/test_questions_artifact.py | 5 +- dokimi/tests/test_report_writers_surrogate.py | 3 +- dokimi/tests/test_run_wide_stop.py | 5 +- dokimi/tests/test_writers_save_artifact.py | 5 +- 26 files changed, 175 insertions(+), 170 deletions(-) delete mode 100644 dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md create mode 100644 dokimi/changelog.d/20261206_100000_napetrov_arch-r15-3-pipeline-settings.md diff --git a/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md b/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md deleted file mode 100644 index 8325e54c2..000000000 --- a/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md +++ /dev/null @@ -1,8 +0,0 @@ - - -### Added - -- **`EvaluationPipeline` accepts an `EvaluationSettings` object.** Python callers can pass the same run settings as one object with `EvaluationPipeline(settings=...)`. Existing positional and keyword arguments still work. diff --git a/dokimi/changelog.d/20261206_100000_napetrov_arch-r15-3-pipeline-settings.md b/dokimi/changelog.d/20261206_100000_napetrov_arch-r15-3-pipeline-settings.md new file mode 100644 index 000000000..94780db42 --- /dev/null +++ b/dokimi/changelog.d/20261206_100000_napetrov_arch-r15-3-pipeline-settings.md @@ -0,0 +1,3 @@ +### Changed + +- **`EvaluationPipeline` takes the run's inputs only as `settings=EvaluationSettings(...)`.** The Python API no longer accepts the fields as keyword or positional arguments: `EvaluationPipeline(product="lib", output_dir=out, description="d")` now raises `TypeError`, and the same run is `EvaluationPipeline(settings=EvaluationSettings(product="lib", output_dir=out, description="d"))`. The `EvaluationSettings` fields, their defaults and the refusal for a run with neither `repo` nor `description` are unchanged; the CLI (`evaluate`, `benchmark run`, `orchestrate`) is unchanged. Scripts that build the pipeline directly move their arguments into `EvaluationSettings(...)`. diff --git a/dokimi/docs/methodology.md b/dokimi/docs/methodology.md index 85e335232..798b8e871 100644 --- a/dokimi/docs/methodology.md +++ b/dokimi/docs/methodology.md @@ -124,7 +124,7 @@ Every writer (`eval questions generate`, `eval questions refine`, the `evaluate` | `metadata` as a list | `{"items": [...]}` (v2 declares `metadata` an object; the list is kept, not dropped) | | `null` in a key v1 does not declare and v2 types (`model`, `total_questions`, `persona_id`, `source_type`, `topics`, ...) | key dropped, without a notice. A `null` inside a typed value (`"topics": [null]`) is not dropped and is refused | -A set that needed any of these, or that is not valid under the version it declares (e.g. a set stamped `questions.v1` whose records use `question`, which `eval questions refine` wrote before v2), is logged once: `read in legacy questions format (...); using it as questions.v2`. Reading these shapes is meant to be retired later; fix the file by hand to stop the notice (`question` for `text` or `question_text`, an `id` on each record, `metadata` as an object, and `schema_version` set to `questions.v2` or removed). No command rewrites a set unchanged: `eval questions refine` is not a re-save, it normalizes fields, drops trivial and duplicate questions and changes the `question_set_hash`, so do not use it on a curated set. A set that is still not valid v2 after reading (a record with an empty question, a field of the wrong type) fails before any model call, with each failing record and the fix named. The run then writes its own v2 copy to `/questions/.json` with the `question_set_hash`. A `--questions` file that is not UTF-8 or not JSON (an empty file included) stops `evaluate` at start-up, before any output directory exists, with `Error: --questions : ` and exit 2, when the run will read it; a re-run that reuses the cached `/questions/.json` never reads it, so a file that is empty, not JSON or not UTF-8 does not stop it (a missing path or a directory still does). `evaluate` has no `--questions-from`; through the Python API (`EvaluationPipeline(questions_from=)`) an unparseable file raises `InputError` with the message `--questions-from : `, while `benchmark run` and `benchmark preflight` keep their own `questions source invalid` message. A `--questions-from` file is never written. A `--questions` file is written only through the Python API (`EvaluationPipeline(custom_questions_path=/questions/.json, force_regen=True)`), when the merge added a record to it; that file keeps each record's `source_type`, while any other custom or golden set is tagged `manual`. The cached file is the run's own and is rewritten as v2. No CLI command can reach this path: `evaluate` takes `--questions` but not `--force`, and `benchmark run` and `benchmark batch` take `--force` but not `--questions`. For sets already valid as v1 or v2, ids and `question_set_hash` do not change on the way through. `data export --kind questions` exports any of these in the v2 shape and records the source version (or `legacy`) in the dataset card. +A set that needed any of these, or that is not valid under the version it declares (e.g. a set stamped `questions.v1` whose records use `question`, which `eval questions refine` wrote before v2), is logged once: `read in legacy questions format (...); using it as questions.v2`. Reading these shapes is meant to be retired later; fix the file by hand to stop the notice (`question` for `text` or `question_text`, an `id` on each record, `metadata` as an object, and `schema_version` set to `questions.v2` or removed). No command rewrites a set unchanged: `eval questions refine` is not a re-save, it normalizes fields, drops trivial and duplicate questions and changes the `question_set_hash`, so do not use it on a curated set. A set that is still not valid v2 after reading (a record with an empty question, a field of the wrong type) fails before any model call, with each failing record and the fix named. The run then writes its own v2 copy to `/questions/.json` with the `question_set_hash`. A `--questions` file that is not UTF-8 or not JSON (an empty file included) stops `evaluate` at start-up, before any output directory exists, with `Error: --questions : ` and exit 2, when the run will read it; a re-run that reuses the cached `/questions/.json` never reads it, so a file that is empty, not JSON or not UTF-8 does not stop it (a missing path or a directory still does). `evaluate` has no `--questions-from`; through the Python API (`EvaluationPipeline(settings=EvaluationSettings(questions_from=))`) an unparseable file raises `InputError` with the message `--questions-from : `, while `benchmark run` and `benchmark preflight` keep their own `questions source invalid` message. A `--questions-from` file is never written. A `--questions` file is written only through the Python API (`EvaluationPipeline(settings=EvaluationSettings(custom_questions_path=/questions/.json, force_regen=True))`), when the merge added a record to it; that file keeps each record's `source_type`, while any other custom or golden set is tagged `manual`. The cached file is the run's own and is rewritten as v2. No CLI command can reach this path: `evaluate` takes `--questions` but not `--force`, and `benchmark run` and `benchmark batch` take `--force` but not `--questions`. For sets already valid as v1 or v2, ids and `question_set_hash` do not change on the way through. `data export --kind questions` exports any of these in the v2 shape and records the source version (or `legacy`) in the dataset card. `expected_topics` carries two different kinds of content depending on the source, and evaluation treats them differently. Persona-generated sets store short keyword labels ("version check", "import test"). Curated golden sets store verified answer statements, often with citations in `metadata` (`must_cite`, `github_issue`, `verified_by`). Only the latter are usable as judge ground truth — see [Grounded Judging](#grounded-judging). diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index c48754fc0..9c5531be2 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -97,22 +97,15 @@ class EvaluationPipeline: 6. Generate report """ - def __init__(self, *args: Any, settings: Optional[EvaluationSettings] = None, **kwargs: Any): + def __init__(self, settings: EvaluationSettings): """ - Initialize pipeline. + Initialize pipeline from the run's inputs. - Takes the run's inputs as an :class:`EvaluationSettings` (``settings=``), or as - the same fields given as keyword arguments, which build one. The fields are - described on :class:`EvaluationSettings`. The fields may also be given - positionally, in field order, as the keyword signature always allowed. + The fields are described on :class:`EvaluationSettings`. """ - if settings is None: - try: - settings = EvaluationSettings(*args, **kwargs) - except TypeError as exc: # preserve the original parameter binding error under the pipeline name - raise TypeError(str(exc).replace("EvaluationSettings.__init__()", "EvaluationPipeline.__init__()", 1)) from None - elif args or kwargs: - raise TypeError("EvaluationPipeline() takes settings or keyword arguments, not both") + if not isinstance(settings, EvaluationSettings): + raise TypeError(f"EvaluationPipeline.__init__() settings must be an EvaluationSettings, " + f"not {type(settings).__name__}") if not settings.repo and not settings.description: raise ValueError( "Either 'repo' or 'description' must be provided. " diff --git a/dokimi/dokimi/orchestrator/pipeline_settings.py b/dokimi/dokimi/orchestrator/pipeline_settings.py index fdee207ce..2ffaf6845 100644 --- a/dokimi/dokimi/orchestrator/pipeline_settings.py +++ b/dokimi/dokimi/orchestrator/pipeline_settings.py @@ -18,7 +18,7 @@ class EvaluationSettings: """ The inputs of one pipeline run. ``EvaluationPipeline(settings=...)`` takes this - object; ``EvaluationPipeline(**fields)`` builds it from the same fields. + object. Fields: product: Product name (e.g., "oneDNN") diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index 868f5aecb..55806fc0f 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -8,7 +8,7 @@ "tests/test_container_agent.py": {"lines": 1233, "rationale": "pre-existing when the gate was introduced"}, "tests/test_judge_reliability.py": {"lines": 1680, "rationale": "grew on main in #73 (judge-validity --context stored), 1505 -> 1695, before the ratchet landed; split it in its own PR"}, "tests/test_judge_validity.py": {"lines": 2233, "rationale": "grew on main in #73 (judge-validity --context stored), 1423 -> 2235, before the ratchet landed; split it in its own PR"}, - "tests/test_pipeline_question_set.py": {"lines": 1223}, + "tests/test_pipeline_question_set.py": {"lines": 1220}, "tests/test_repo_environment.py": {"lines": 1271, "rationale": "grew on main in #147 before the ratchet landed; +2 for the instructions assert of two crash tests (#103 review); split it in its own PR"} }, "functions": { diff --git a/dokimi/tests/answering_stack_parity.py b/dokimi/tests/answering_stack_parity.py index d7acefb5d..801a2813a 100644 --- a/dokimi/tests/answering_stack_parity.py +++ b/dokimi/tests/answering_stack_parity.py @@ -26,6 +26,7 @@ from typing import Any, Dict, List, Optional, Sequence, Tuple from dokimi import llm +from dokimi.orchestrator.pipeline_settings import EvaluationSettings PRODUCT = "fixture-lib" PRODUCT_KEY = "fixture-lib" @@ -271,7 +272,7 @@ def run_stack_p( answer_with_canned_reply(provider_calls) judge_inputs = install_judge_spy(monkeypatch) - pipe = pipeline_mod.EvaluationPipeline( + pipe = pipeline_mod.EvaluationPipeline(settings=EvaluationSettings( product=PRODUCT, output_dir=tmp_path, description=DESCRIPTION, @@ -285,7 +286,7 @@ def run_stack_p( product_key=PRODUCT_KEY, registry=registry, judge_placeholder=judge_placeholder, - ) + )) qs = QUESTIONS if questions is None else questions mark = len(provider_calls.calls) arms = pipe._generate_answers(qs, concurrency=1) diff --git a/dokimi/tests/test_benchmark_command_question_set.py b/dokimi/tests/test_benchmark_command_question_set.py index 9d6fea90e..3ffea085e 100644 --- a/dokimi/tests/test_benchmark_command_question_set.py +++ b/dokimi/tests/test_benchmark_command_question_set.py @@ -17,6 +17,7 @@ from dokimi.cli import build_parser from dokimi.commands import benchmark from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.registry import ProductEntry from tests.cli_refusal import refusal @@ -157,7 +158,7 @@ def fake_run_single_library(entry, **kwargs): def test_questions_root_reaches_the_pipeline(monkeypatch, tmp_path): - """--questions-root ends up as EvaluationPipeline(questions_root=...).""" + """--questions-root ends up as EvaluationSettings(questions_root=...).""" seen: dict[str, object] = {} class FakePipeline: @@ -622,10 +623,10 @@ def test_bare_run_with_cached_questions_says_it_reuses_them(tmp_path, caplog, fo (out / "questions" / "demo.json").write_text(json.dumps({"questions": [{"id": "old", "question": "Q?"}]}), encoding="utf-8") with caplog.at_level(logging.INFO): - EvaluationPipeline( + EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=out, description="A demo product", force_regen=force_regen, - ) + )) assert ("questions will be generated" not in caplog.text) is reused assert ("reusing the questions cached" in caplog.text) is reused diff --git a/dokimi/tests/test_benchmark_registry_wiring.py b/dokimi/tests/test_benchmark_registry_wiring.py index 05b324455..9890a4c07 100644 --- a/dokimi/tests/test_benchmark_registry_wiring.py +++ b/dokimi/tests/test_benchmark_registry_wiring.py @@ -12,6 +12,7 @@ from dokimi import orchestrator from dokimi.commands import benchmark from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from tests.test_answering_stack_parity import _subparser @pytest.fixture(autouse=True) @@ -49,7 +50,7 @@ class _Spy: built: list = [] def __init__(self, settings): - kwargs = vars(settings) # every field is also a keyword: EvaluationPipeline(**kwargs) takes them back + kwargs = vars(settings) # the fields go back into the settings: EvaluationSettings(**kwargs) self.kwargs = kwargs _Spy.built.append(kwargs) @@ -78,7 +79,7 @@ def test_a_custom_entry_without_an_id_is_not_looked_up_in_the_bundled_registry(s _run(tmp_path, library) (kwargs,) = spy.built - real = EvaluationPipeline(**kwargs) + real = EvaluationPipeline(settings=EvaluationSettings(**kwargs)) with pytest.raises(ValueError, match="declares no 'context7_id'"): real._library_id(_DeclaredIdClient()) @@ -113,7 +114,7 @@ def test_an_mcp_source_id_wins_over_the_entry_id(spy, tmp_path): benchmark.cmd_benchmark_run(args) (kwargs,) = spy.built - real = EvaluationPipeline(**kwargs) + real = EvaluationPipeline(settings=EvaluationSettings(**kwargs)) assert real._library_id(_DeclaredIdClient()) == "org/declared" assert real._library_id(_SourceIdClient()) == "my/override" diff --git a/dokimi/tests/test_evaluate_cli_inputs.py b/dokimi/tests/test_evaluate_cli_inputs.py index fd8d427b1..520c1aa0b 100644 --- a/dokimi/tests/test_evaluate_cli_inputs.py +++ b/dokimi/tests/test_evaluate_cli_inputs.py @@ -21,6 +21,7 @@ from dokimi.cli import build_parser from dokimi.orchestrator.pipeline import EvaluationPipeline, load_questions_payload +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.files import InputError @@ -81,8 +82,8 @@ def test_an_unparseable_custom_questions_file_exits_2_before_any_output_director def _pipeline(tmp_path, bad, out="out", **kw): - return EvaluationPipeline(product="Demo", product_key="demo", output_dir=tmp_path / out, - description="A demo product", custom_questions_path=bad, **kw) + return EvaluationPipeline(settings=EvaluationSettings(product="Demo", product_key="demo", output_dir=tmp_path / out, + description="A demo product", custom_questions_path=bad, **kw)) def test_a_custom_questions_file_the_run_never_reads_does_not_stop_it(tmp_path): @@ -123,8 +124,8 @@ def test_an_unparseable_questions_from_file_names_the_flag(tmp_path): source.write_text("not json", encoding="utf-8") with pytest.raises(InputError, match=rf"^--questions-from {re.escape(str(source))}: "): - EvaluationPipeline(product="Demo", product_key="demo", output_dir=tmp_path / "out", - description="A demo product", questions_from=source) + EvaluationPipeline(settings=EvaluationSettings(product="Demo", product_key="demo", output_dir=tmp_path / "out", + description="A demo product", questions_from=source)) assert not (tmp_path / "out").exists() @@ -139,8 +140,8 @@ def test_a_named_pipe_as_custom_questions_or_questions_from_is_not_read_up_front os.mkfifo(fifo) pipeline._check_custom_questions(fifo) - EvaluationPipeline(product="Demo", product_key="demo", output_dir=tmp_path / "out", - description="A demo product", questions_from=fifo) + EvaluationPipeline(settings=EvaluationSettings(product="Demo", product_key="demo", output_dir=tmp_path / "out", + description="A demo product", questions_from=fifo)) assert read == [] diff --git a/dokimi/tests/test_input_devices.py b/dokimi/tests/test_input_devices.py index 200322e8d..63e1e9290 100644 --- a/dokimi/tests/test_input_devices.py +++ b/dokimi/tests/test_input_devices.py @@ -21,6 +21,7 @@ from dokimi.commands import benchmark from dokimi.commands.inputs import read_text_or_exit from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.registry import ProductEntry from dokimi.files import InputError, read_json_input, refuse_device @@ -122,12 +123,12 @@ def test_arms_questions_loader_refuses_a_device_with_its_flag_name(): def test_the_pipeline_refuses_a_device_as_questions_from(tmp_path): with pytest.raises(InputError, match=r"^--questions-from /dev/null: not a file$"): - EvaluationPipeline(product="Demo", output_dir=tmp_path / "out", description="d", questions_from=DEVICE) + EvaluationPipeline(settings=EvaluationSettings(product="Demo", output_dir=tmp_path / "out", description="d", questions_from=DEVICE)) def test_the_custom_set_loader_refuses_a_device_set_after_construction(tmp_path): """The Python API can point ``custom_questions_path`` at a device after the constructor's check.""" - pipeline = EvaluationPipeline(product="Demo", output_dir=tmp_path / "out", description="d") + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="Demo", output_dir=tmp_path / "out", description="d")) pipeline.custom_questions_path = Path(DEVICE) with pytest.raises(InputError, match=r"^--questions /dev/null: not a file$"): pipeline._load_custom_questions() diff --git a/dokimi/tests/test_lone_surrogate_cache_keys.py b/dokimi/tests/test_lone_surrogate_cache_keys.py index e18cc1df7..f2dec6f23 100644 --- a/dokimi/tests/test_lone_surrogate_cache_keys.py +++ b/dokimi/tests/test_lone_surrogate_cache_keys.py @@ -276,6 +276,7 @@ def _topics_dir(monkeypatch, doc_source: str) -> Path: """The cache directory the question step hands the topics extractor for ``doc_source``.""" import dokimi.questions as questions from dokimi.orchestrator.pipeline import EvaluationPipeline + from dokimi.orchestrator.pipeline_settings import EvaluationSettings seen = {} @@ -288,8 +289,8 @@ def extract_topics(self, **kwargs): monkeypatch.setattr("dokimi.orchestrator.pipeline.create_doc_source_client", lambda source: object()) monkeypatch.setattr(questions, "RagasSeedExtractor", _Extractor) - pipeline = EvaluationPipeline(product="P", description="d", output_dir=Path("run"), doc_source=doc_source, - context7_id="org/x") + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="P", description="d", output_dir=Path("run"), doc_source=doc_source, + context7_id="org/x")) with pytest.raises(_Stop): pipeline._generate_questions({}) return seen["dir"] diff --git a/dokimi/tests/test_lone_surrogate_digests.py b/dokimi/tests/test_lone_surrogate_digests.py index 5f72443f6..0d5d0ad21 100644 --- a/dokimi/tests/test_lone_surrogate_digests.py +++ b/dokimi/tests/test_lone_surrogate_digests.py @@ -298,6 +298,7 @@ def _topics_cache_dir(tmp_path, monkeypatch, doc_source: str) -> Path: """The ``cache_dir`` the pipeline's question step hands the topic extractor for ``doc_source``.""" import dokimi.questions as questions from dokimi.orchestrator.pipeline import EvaluationPipeline + from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.registry import ProductRegistry seen = {} @@ -320,8 +321,8 @@ class _Client: registry_path = tmp_path / "products.yaml" registry_path.write_text("products:\n my_lib:\n name: My Lib\n description: d\n context7_id: org/lib\n", encoding="utf-8") - pipeline = EvaluationPipeline(product="My Lib", description="d", product_key="my_lib", output_dir=tmp_path / "run", - registry=ProductRegistry(path=registry_path), doc_source=doc_source) + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="My Lib", description="d", product_key="my_lib", output_dir=tmp_path / "run", + registry=ProductRegistry(path=registry_path), doc_source=doc_source)) with pytest.raises(_StopHere): pipeline._generate_questions({}) return seen["cache_dir"] diff --git a/dokimi/tests/test_missing_doc_source_refused.py b/dokimi/tests/test_missing_doc_source_refused.py index 778620d78..8ca214f42 100644 --- a/dokimi/tests/test_missing_doc_source_refused.py +++ b/dokimi/tests/test_missing_doc_source_refused.py @@ -24,6 +24,7 @@ from dokimi.treatments import create_treatment from dokimi.treatments.arms import DocTreatment, MCPAgentTreatment from dokimi.files import InputError +from dokimi.orchestrator.pipeline_settings import EvaluationSettings PREFIXES = ["local", "okf"] @@ -124,8 +125,8 @@ def test_evaluate_refuses_a_missing_doc_source_that_the_output_directory_would_c def test_pipeline_run_refuses_a_missing_doc_source_before_any_step(tmp_path, monkeypatch): monkeypatch.setattr(pipeline_mod.EvaluationPipeline, "_read_question_inputs", _unreached("the first step")) missing = tmp_path / "nope" - pipeline = pipeline_mod.EvaluationPipeline(product="Lib", description="d", output_dir=tmp_path / "run", - doc_source=f"local:{missing}") + pipeline = pipeline_mod.EvaluationPipeline(settings=EvaluationSettings(product="Lib", description="d", output_dir=tmp_path / "run", + doc_source=f"local:{missing}")) with pytest.raises(InputError, match=re.escape(f"doc source path does not exist: local:{missing}")): pipeline.run(concurrency=1) @@ -173,8 +174,8 @@ def first_step(self): monkeypatch.setattr(pipeline_mod.EvaluationPipeline, "_read_question_inputs", first_step) docs = tmp_path / "docs" docs.mkdir() - pipeline = pipeline_mod.EvaluationPipeline(product="Lib", description="d", output_dir=tmp_path / "run", - doc_source=f"local:{docs}") + pipeline = pipeline_mod.EvaluationPipeline(settings=EvaluationSettings(product="Lib", description="d", output_dir=tmp_path / "run", + doc_source=f"local:{docs}")) with pytest.raises(Reached): pipeline.run(concurrency=1) diff --git a/dokimi/tests/test_paired_summary_overflow.py b/dokimi/tests/test_paired_summary_overflow.py index b359e5bd3..9dd7ada78 100644 --- a/dokimi/tests/test_paired_summary_overflow.py +++ b/dokimi/tests/test_paired_summary_overflow.py @@ -16,6 +16,7 @@ from dokimi.eval import stats from dokimi.gate.trust_gate import evaluate_trust from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.report.eval_report import generate_report from dokimi.report.generator import ReportGenerator @@ -65,7 +66,7 @@ def _run_pipeline(tmp_path, monkeypatch, evaluations): (output_dir / "personas" / "oneTBB.json").write_text(json.dumps({"personas": []}), encoding="utf-8") questions = [{"id": e["question_id"], "question": e["question_text"], "source_type": "manual"} for e in evaluations] (output_dir / "questions" / "oneTBB.json").write_text(json.dumps({"questions": questions}), encoding="utf-8") - pipeline = EvaluationPipeline(product="oneTBB", output_dir=output_dir, description="Threading Building Blocks") + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=output_dir, description="Threading Building Blocks")) return pipeline.run(concurrency=1) diff --git a/dokimi/tests/test_pipeline_arm_runner.py b/dokimi/tests/test_pipeline_arm_runner.py index f1b590348..ecbfbb859 100644 --- a/dokimi/tests/test_pipeline_arm_runner.py +++ b/dokimi/tests/test_pipeline_arm_runner.py @@ -19,6 +19,7 @@ from dokimi.eval import arm_runner as arm_runner_mod from dokimi.eval.arms_adapter import to_binary from dokimi.orchestrator import pipeline as pipeline_mod +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.records import load from tests.answering_stack_parity import ( JUDGE_MODEL, JUDGE_PROVIDER, PRODUCT, QUESTIONS, run_stack_a, run_stack_p, @@ -49,8 +50,8 @@ def _sources(monkeypatch) -> None: def _pipeline(monkeypatch, tmp_path, **kwargs): _sources(monkeypatch) - return pipeline_mod.EvaluationPipeline(product="lib", output_dir=tmp_path, description="d", model="m", - provider="openai", **kwargs) + return pipeline_mod.EvaluationPipeline(settings=EvaluationSettings(product="lib", output_dir=tmp_path, description="d", model="m", + provider="openai", **kwargs)) def _answers_until(monkeypatch, crash_on_call: int) -> list: diff --git a/dokimi/tests/test_pipeline_empty_question_set.py b/dokimi/tests/test_pipeline_empty_question_set.py index f420cd1cd..e1ac0c94d 100644 --- a/dokimi/tests/test_pipeline_empty_question_set.py +++ b/dokimi/tests/test_pipeline_empty_question_set.py @@ -13,6 +13,7 @@ from dokimi.cli import build_parser from dokimi.commands import benchmark from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.registry import ProductEntry from tests.cli_refusal import refusal @@ -43,13 +44,13 @@ def no_answers(self, questions, concurrency=5, question_set_hash=None): monkeypatch.setattr(EvaluationPipeline, "_generate_questions", no_questions) monkeypatch.setattr(EvaluationPipeline, "_generate_answers", no_answers) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_from=questions_from, - ) + )) with pytest.raises(ValueError, match="No questions to answer"): pipeline.run(concurrency=1) diff --git a/dokimi/tests/test_pipeline_independence_flag.py b/dokimi/tests/test_pipeline_independence_flag.py index e71a8061d..76002f632 100644 --- a/dokimi/tests/test_pipeline_independence_flag.py +++ b/dokimi/tests/test_pipeline_independence_flag.py @@ -10,6 +10,7 @@ import pytest from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings @pytest.mark.parametrize("provider, model, judge_provider, judge_model, expected", [ @@ -34,9 +35,9 @@ def score_answer(self, **kwargs): monkeypatch.setattr("dokimi.eval.arm_runner.llm_call_with_usage", lambda **kw: ("an answer", usage)) monkeypatch.setattr("dokimi.orchestrator.pipeline.create_doc_source_client", lambda source: EmptyDocClient()) monkeypatch.setattr("dokimi.eval.Judge", FakeJudge) - pipeline = EvaluationPipeline(product="oneTBB", output_dir=tmp_path, description="d", model=model, + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=tmp_path, description="d", model=model, provider=provider, - judge_model=judge_model, judge_provider=judge_provider) + judge_model=judge_model, judge_provider=judge_provider)) pipeline._evaluate_answers(pipeline._generate_answers(QUESTIONS, concurrency=1)) diff --git a/dokimi/tests/test_pipeline_library_id.py b/dokimi/tests/test_pipeline_library_id.py index 5f0271c17..e39966d90 100644 --- a/dokimi/tests/test_pipeline_library_id.py +++ b/dokimi/tests/test_pipeline_library_id.py @@ -6,6 +6,7 @@ import pytest from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.registry import ProductRegistry REGISTRY = """\ @@ -39,9 +40,9 @@ def registry(tmp_path): def _pipeline(tmp_path, registry, **kwargs): - return EvaluationPipeline( + return EvaluationPipeline(settings=EvaluationSettings( product="My Lib", description="d", product_key="my_lib", output_dir=tmp_path / "run", registry=registry, **kwargs - ) + )) def test_an_explicit_id_wins_over_the_registry_entry(tmp_path, registry): @@ -86,9 +87,9 @@ def test_the_registry_key_not_the_display_name_finds_the_declared_id(tmp_path, r def test_an_unregistered_product_asks_the_client_for_its_key(tmp_path, registry): """A key that is not in the registry goes to the client, by its key and not its display name.""" client = _RecordingClient() - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="Other Lib", description="d", product_key="other_lib", output_dir=tmp_path / "run", registry=registry - ) + )) library_id = pipeline._library_id(client) diff --git a/dokimi/tests/test_pipeline_question_set.py b/dokimi/tests/test_pipeline_question_set.py index 57f063f2f..d68430482 100644 --- a/dokimi/tests/test_pipeline_question_set.py +++ b/dokimi/tests/test_pipeline_question_set.py @@ -11,11 +11,8 @@ import pytest -from dokimi.orchestrator.pipeline import ( - EvaluationPipeline, - compute_question_set_hash, - load_questions_payload, -) +from dokimi.orchestrator.pipeline import EvaluationPipeline, compute_question_set_hash, load_questions_payload +from dokimi.orchestrator.pipeline_settings import EvaluationSettings def _write_json(path: Path, data: object) -> None: @@ -68,11 +65,11 @@ def test_cached_questions_skip_generation_and_get_question_set_id(tmp_path, monk _write_json(output_dir / "personas" / "oneTBB.json", {"personas": []}) _write_json(output_dir / "questions" / "oneTBB.json", {"questions": questions}) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=output_dir, description="Threading Building Blocks", - ) + )) result = pipeline.run(concurrency=1) expected_hash = compute_question_set_hash(questions) @@ -96,12 +93,12 @@ def test_questions_from_directory_is_reused_and_normalized(tmp_path, monkeypatch _write_json(output_dir / "personas" / "oneTBB.json", {"personas": []}) source_bytes = (source_dir / "questions" / "oneTBB.json").read_bytes() - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=output_dir, description="Threading Building Blocks", questions_from=source_dir, - ) + )) result = pipeline.run(concurrency=1) # The id is stamped on this run's copy; the source set is read, never written. @@ -127,13 +124,13 @@ def test_questions_from_directory_uses_product_key_when_provided(tmp_path, monke _write_json(source_dir / "questions" / "onetbb.json", questions) _write_json(output_dir / "personas" / "onetbb.json", {"personas": []}) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", product_key="onetbb", output_dir=output_dir, description="Threading Building Blocks", questions_from=source_dir, - ) + )) result = pipeline.run(concurrency=1) saved = json.loads((output_dir / "questions" / "onetbb.json").read_text()) @@ -150,13 +147,13 @@ def test_auto_golden_discovery_uses_product_key(tmp_path): # A set named after the display name must not be picked up instead. _write_json(questions_root / "demoproduct_golden.json", {"questions": []}) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=tmp_path / "out", description="A demo product", questions_root=questions_root, - ) + )) assert pipeline.custom_questions_path is not None assert pipeline.custom_questions_path.name == "demo_golden.json" @@ -168,13 +165,13 @@ def test_missing_golden_set_under_questions_root_warns(tmp_path, caplog): questions_root.mkdir() with caplog.at_level(logging.WARNING): - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=tmp_path / "out", description="A demo product", questions_root=questions_root, - ) + )) assert pipeline.custom_questions_path is None assert "has no golden set for demo" in caplog.text @@ -188,12 +185,12 @@ def test_no_questions_root_means_no_golden_set(tmp_path, caplog): incomparable, so it must say so and name the flag. """ with caplog.at_level(logging.WARNING): - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=tmp_path / "out", description="A demo product", - ) + )) assert pipeline.custom_questions_path is None assert pipeline.questions_root is None @@ -209,14 +206,14 @@ def test_custom_questions_path_wins_over_questions_root(tmp_path): explicit = tmp_path / "explicit.json" _write_json(explicit, {"questions": []}) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=tmp_path / "out", description="A demo product", custom_questions_path=explicit, questions_root=questions_root, - ) + )) assert pipeline.custom_questions_path == explicit @@ -283,12 +280,12 @@ def test_questions_from_wins_over_cache(tmp_path, monkeypatch): _write_json(output_dir / "personas" / "oneTBB.json", {"personas": []}) _write_json(output_dir / "questions" / "oneTBB.json", cached_questions) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=output_dir, description="Threading Building Blocks", questions_from=external_dir, - ) + )) pipeline.run(concurrency=1) # Verify external set was used, not cache @@ -318,12 +315,12 @@ def test_relative_questions_from_path_not_confused_with_output(tmp_path, monkeyp os.chdir(tmp_path) (tmp_path / "sub").mkdir() # The same directory, spelled two ways: only a resolved comparison sees one path - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=Path("shared"), description="Threading Building Blocks", questions_from=Path("sub/../shared"), - ) + )) pipeline.run(concurrency=1) # External input files (--questions-from) are never written, even if they're the output path @@ -380,13 +377,13 @@ def generate_report(self, evaluations, questions): monkeypatch.setattr(EvaluationPipeline, "_evaluate_answers", evaluate_answers) monkeypatch.setattr(EvaluationPipeline, "_generate_report", generate_report) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", custom_questions_path=custom_file, force_regen=True, - ) + )) pipeline.run(concurrency=1) # The merged set (g1 + c1) should be saved with question_set_id @@ -452,13 +449,13 @@ def generate_report(self, evaluations, questions): monkeypatch.setattr(EvaluationPipeline, "_generate_report", generate_report) # Run 1: force_regen with custom input at same path - pipeline1 = EvaluationPipeline( + pipeline1 = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", custom_questions_path=custom_file, force_regen=True, - ) + )) pipeline1.run(concurrency=1) saved1 = json.loads(custom_file.read_text()) @@ -466,13 +463,13 @@ def generate_report(self, evaluations, questions): assert {q.get("source_type") for q in saved1["questions"]} == {"generated", "manual"} # Run 2: force_regen again; g1 should still be "generated", not downgraded to "manual" - pipeline2 = EvaluationPipeline( + pipeline2 = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", custom_questions_path=custom_file, force_regen=True, - ) + )) pipeline2.run(concurrency=1) saved2 = json.loads(custom_file.read_text()) @@ -529,13 +526,13 @@ def generate_report(self, evaluations, questions): monkeypatch.setattr(EvaluationPipeline, "_evaluate_answers", evaluate_answers) monkeypatch.setattr(EvaluationPipeline, "_generate_report", generate_report) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", custom_questions_path=custom_file, force_regen=True, - ) + )) pipeline.run(concurrency=1) # Input file must not be rewritten (no generated questions to merge) @@ -555,11 +552,11 @@ def stub_generate(self, personas): monkeypatch.setattr(EvaluationPipeline, "_discover_personas", stub_discover) monkeypatch.setattr(EvaluationPipeline, "_generate_questions", stub_generate) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", - ) + )) # Should raise ArtifactValidationError before generating answers with pytest.raises(Exception, match="should be non-empty"): @@ -578,12 +575,12 @@ def test_cached_resume_with_custom_input_at_same_path_leaves_input_unchanged(tmp _write_json(tmp_path / "personas" / "oneTBB.json", {"personas": []}) # Use the cache file as custom_questions_path (same location) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", custom_questions_path=cache_file, - ) + )) pipeline.run(concurrency=1) # The input file must not be rewritten (same bytes) @@ -641,13 +638,13 @@ def generate_report(self, evaluations, questions): monkeypatch.setattr(EvaluationPipeline, "_evaluate_answers", evaluate_answers) monkeypatch.setattr(EvaluationPipeline, "_generate_report", generate_report) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", custom_questions_path=custom_file, force_regen=True, - ) + )) pipeline.run(concurrency=1) # Input file must not be rewritten (no generated questions to merge) @@ -664,13 +661,13 @@ def _stub_regen_steps(monkeypatch: pytest.MonkeyPatch, generated: list[dict]) -> def _own_output_pipeline(tmp_path: Path) -> EvaluationPipeline: - return EvaluationPipeline( + return EvaluationPipeline(settings=EvaluationSettings( product="oneTBB", output_dir=tmp_path, description="Threading Building Blocks", custom_questions_path=tmp_path / "questions" / "oneTBB.json", force_regen=True, - ) + )) def test_a_stubbed_merge_that_returns_the_custom_set_does_not_write_it(tmp_path, monkeypatch): @@ -710,9 +707,9 @@ def test_a_custom_set_elsewhere_is_still_tagged_manual(tmp_path, monkeypatch): _write_json(custom_file, [{"id": "c1", "question": "Custom?", "source_type": "generated"}]) _stub_regen_steps(monkeypatch, []) - pipeline = EvaluationPipeline(product="oneTBB", output_dir=tmp_path / "run", + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=tmp_path / "run", description="Threading Building Blocks", - custom_questions_path=custom_file, force_regen=True) + custom_questions_path=custom_file, force_regen=True)) pipeline.run(concurrency=1) saved = json.loads((tmp_path / "run" / "questions" / "oneTBB.json").read_text()) @@ -772,13 +769,13 @@ def generate_answers(self, questions, concurrency=5, question_set_hash=None): for run in ("run_a", "run_b"): output_dir = tmp_path / run _write_json(output_dir / "personas" / "demo.json", {"personas": []}) - EvaluationPipeline( + EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_root=questions_root, - ).run(concurrency=1) + )).run(concurrency=1) assert answered == [["g1", "g2"], ["g1", "g2"]] @@ -790,13 +787,13 @@ def test_empty_golden_set_fails_the_run_and_writes_no_cache(tmp_path, monkeypatc output_dir = tmp_path / "out" _write_json(output_dir / "personas" / "demo.json", {"personas": []}) _stub_expensive_steps(monkeypatch) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_root=questions_root, - ) + )) with pytest.raises(ValueError, match="Golden set is empty"): pipeline.run(concurrency=1) @@ -823,14 +820,14 @@ def generate_answers(self, questions, concurrency=5, question_set_hash=None): monkeypatch.setattr(EvaluationPipeline, "_generate_report", lambda self, e, q: "report") for force_regen in (False, True): - EvaluationPipeline( + EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_root=questions_root, force_regen=force_regen, - ).run(concurrency=1) + )).run(concurrency=1) assert answered == [["old"], ["g1"]] @@ -841,13 +838,13 @@ def test_questions_from_does_not_warn_that_questions_are_generated(tmp_path, cap _write_json(source_dir / "questions" / "demo.json", [{"id": "q1", "question": "Q?"}]) with caplog.at_level(logging.WARNING): - EvaluationPipeline( + EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=tmp_path / "out", description="A demo product", questions_from=source_dir, - ) + )) assert "questions will be generated" not in caplog.text @@ -870,13 +867,13 @@ def test_cached_questions_differing_from_golden_warns(tmp_path, monkeypatch, cap ]) with caplog.at_level(logging.WARNING): - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_root=questions_root, - ) + )) pipeline.run(concurrency=1) assert "cached question set" in caplog.text @@ -900,13 +897,13 @@ def track_discover_personas(self): monkeypatch.setattr(EvaluationPipeline, "_discover_personas", track_discover_personas) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_root=questions_root, - ) + )) result = pipeline.run(concurrency=1) assert not discover_personas_called, "persona discovery should not have been called" @@ -922,8 +919,8 @@ def test_a_pinned_run_records_its_golden_source_and_question_path(tmp_path, monk golden = questions_root / "demo_golden.json" _write_json(golden, [{"id": "g1", "question": "Q1?"}, {"id": "g2", "question": "Q2?"}]) - pipeline = EvaluationPipeline(product="DemoProduct", product_key="demo", output_dir=tmp_path / "out", - description="A demo product", questions_root=questions_root) + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="DemoProduct", product_key="demo", output_dir=tmp_path / "out", + description="A demo product", questions_root=questions_root)) steps = pipeline.run(concurrency=1)["steps"] assert steps["questions_generated"] == {"count": 2, "golden_source": str(golden)} @@ -947,13 +944,13 @@ def track_discover_personas(self): monkeypatch.setattr(EvaluationPipeline, "_discover_personas", track_discover_personas) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_from=source_dir, - ) + )) result = pipeline.run(concurrency=1) assert not discover_personas_called, "persona discovery should not have been called" @@ -969,14 +966,14 @@ def test_questions_from_with_root_ignores_root(tmp_path, caplog): _write_json(questions_root / "demo_golden.json", [{"id": "g1", "question": "Golden?"}]) with caplog.at_level(logging.WARNING): - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", questions_from=source_dir, questions_root=questions_root, - ) + )) # golden_pinned should be False and external_questions_path should be set assert pipeline.golden_pinned is False @@ -1018,14 +1015,14 @@ def generate_report(self, evaluations, questions): monkeypatch.setattr(EvaluationPipeline, "_evaluate_answers", evaluate_answers) monkeypatch.setattr(EvaluationPipeline, "_generate_report", generate_report) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=output_dir, description="A demo product", custom_questions_path=custom_q, questions_root=questions_root, - ) + )) # custom_questions_path is set, but golden_pinned stays False (explicit custom != auto-golden) assert pipeline.custom_questions_path == custom_q @@ -1052,10 +1049,10 @@ def _golden_run(tmp_path, golden, cached, *, raw=False, custom=False): if cached is not None: _write_json(out / "questions" / "demo.json", cached) kwargs = {"custom_questions_path": root / "demo_golden.json"} if custom else {"questions_root": root} - return EvaluationPipeline( + return EvaluationPipeline(settings=EvaluationSettings( product="DemoProduct", product_key="demo", output_dir=out, description="A demo product", **kwargs, - ).run(concurrency=1) + )).run(concurrency=1) @pytest.mark.parametrize("golden,raw", [(["just a string"], False), ('{"questions": [', True)]) @@ -1213,10 +1210,10 @@ def test_a_relative_own_output_path_keeps_source_types(tmp_path, monkeypatch): old = os.getcwd() try: os.chdir(tmp_path) - EvaluationPipeline(product="oneTBB", output_dir=Path("."), + EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=Path("."), description="Threading Building Blocks", custom_questions_path=Path("sub/../questions/oneTBB.json"), - force_regen=True).run(concurrency=1) + force_regen=True)).run(concurrency=1) finally: os.chdir(old) by_id = {q["id"]: q for q in json.loads(custom_file.read_text())["questions"]} diff --git a/dokimi/tests/test_pipeline_settings.py b/dokimi/tests/test_pipeline_settings.py index d1bb7ebd7..8f533742c 100644 --- a/dokimi/tests/test_pipeline_settings.py +++ b/dokimi/tests/test_pipeline_settings.py @@ -1,8 +1,9 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""EvaluationPipeline takes its inputs as an EvaluationSettings, or as the same fields as keywords.""" +"""EvaluationPipeline takes its inputs as an EvaluationSettings, passed as settings=.""" +import inspect from dataclasses import fields from pathlib import Path @@ -15,58 +16,59 @@ def _attrs(pipe): return {k: v for k, v in sorted(vars(pipe).items()) if not callable(v)} -def test_settings_and_keywords_build_the_same_pipeline(tmp_path): - kwargs = dict(product="oneTBB", output_dir=tmp_path / "run", description="d", model="m", top_k=7) - by_keywords = EvaluationPipeline(**kwargs) - by_settings = EvaluationPipeline(settings=EvaluationSettings(**kwargs)) - assert _attrs(by_settings) == _attrs(by_keywords) +def test_the_constructor_takes_settings_and_nothing_else(): + params = list(inspect.signature(EvaluationPipeline.__init__).parameters.values()) + assert [p.name for p in params] == ["self", "settings"] + assert params[1].annotation in (EvaluationSettings, "EvaluationSettings") -def test_positional_arguments_fill_the_fields_in_order(tmp_path): - by_position = EvaluationPipeline("oneTBB", tmp_path / "run", "oneapi-src/oneTBB", description=None) - by_keyword = EvaluationPipeline(product="oneTBB", output_dir=tmp_path / "run", repo="oneapi-src/oneTBB", - description=None) - assert _attrs(by_position) == _attrs(by_keyword) +def test_settings_build_the_pipeline(tmp_path): + pipe = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=tmp_path / "run", + repo="oneapi-src/oneTBB", description=None, top_k=7)) + assert pipe.product == "oneTBB" + assert pipe.repo == "oneapi-src/oneTBB" + assert pipe.output_dir == tmp_path / "run" -def test_a_positional_argument_repeated_as_a_keyword_is_refused(tmp_path): - with pytest.raises(TypeError) as exc: - EvaluationPipeline("oneTBB", tmp_path, product="x", description="d") - assert str(exc.value) == "EvaluationPipeline.__init__() got multiple values for argument 'product'" - - -@pytest.mark.parametrize(("kwargs", "message"), [ - ({"product": "other"}, "got multiple values for argument 'product'"), - ({"bogus": True}, "got an unexpected keyword argument 'bogus'"), -]) -def test_constructor_reports_bad_keywords_before_excess_positional_arguments(kwargs, message): - with pytest.raises(TypeError) as exc: - EvaluationPipeline(*([None] * 26), **kwargs) - assert str(exc.value) == f"EvaluationPipeline.__init__() {message}" +def test_the_product_key_defaults_to_the_product(tmp_path): + pipe = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=tmp_path, description="d")) + assert pipe.product_key == "oneTBB" -def test_the_settings_fields_are_the_constructor_keywords(): +def test_the_settings_fields_are_the_settings_keywords(): names = {f.name for f in fields(EvaluationSettings)} assert {"product", "output_dir", "questions_root", "checkpoint", "judge_placeholder"} <= names - assert "settings" not in names -def test_settings_and_keywords_together_are_refused(tmp_path): - settings = EvaluationSettings(product="oneTBB", output_dir=tmp_path, description="d") - with pytest.raises(TypeError, match="takes settings or keyword arguments, not both"): - EvaluationPipeline(settings=settings, model="m") +def test_keyword_fields_are_refused(tmp_path): + with pytest.raises(TypeError, match="unexpected keyword argument 'product'"): + EvaluationPipeline(product="oneTBB", output_dir=tmp_path, description="d") -def test_an_unknown_keyword_is_refused_under_the_pipeline_name(tmp_path): - with pytest.raises(TypeError) as exc: - EvaluationPipeline(product="oneTBB", output_dir=tmp_path, description="d", bogus=1) - assert str(exc.value) == "EvaluationPipeline.__init__() got an unexpected keyword argument 'bogus'" +def test_positional_fields_are_refused(tmp_path): + with pytest.raises(TypeError, match="positional argument"): + EvaluationPipeline("oneTBB", tmp_path, "oneapi-src/oneTBB", None) -def test_a_missing_required_field_is_refused_under_the_pipeline_name(tmp_path): +def test_settings_is_required(): + with pytest.raises(TypeError, match="missing 1 required positional argument: 'settings'"): + EvaluationPipeline() + + +@pytest.mark.parametrize(("value", "type_name"), [ + ({"product": "oneTBB", "output_dir": "run", "description": "d"}, "dict"), + (None, "NoneType"), +]) +def test_settings_that_is_not_an_evaluation_settings_is_refused(value, type_name): with pytest.raises(TypeError) as exc: - EvaluationPipeline(output_dir=tmp_path, description="d") - assert str(exc.value) == "EvaluationPipeline.__init__() missing 1 required positional argument: 'product'" + EvaluationPipeline(settings=value) + assert str(exc.value) == (f"EvaluationPipeline.__init__() settings must be an EvaluationSettings, " + f"not {type_name}") + + +def test_a_run_with_neither_repo_nor_description_is_refused(tmp_path): + with pytest.raises(ValueError, match="Either 'repo' or 'description' must be provided"): + EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=Path(tmp_path))) def test_the_settings_are_not_stored_on_the_pipeline(tmp_path): diff --git a/dokimi/tests/test_pipeline_summary.py b/dokimi/tests/test_pipeline_summary.py index e3bc26174..44b8c9f1f 100644 --- a/dokimi/tests/test_pipeline_summary.py +++ b/dokimi/tests/test_pipeline_summary.py @@ -10,6 +10,7 @@ import pytest from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings def _evaluation(qid, with_score, without_score): @@ -35,7 +36,7 @@ def _run(tmp_path, monkeypatch: pytest.MonkeyPatch, evaluations): questions = [{"id": e["question_id"], "question": e["question_text"], "source_type": "manual"} for e in evaluations] (output_dir / "questions" / "oneTBB.json").write_text(json.dumps({"questions": questions}), encoding="utf-8") - pipeline = EvaluationPipeline(product="oneTBB", output_dir=output_dir, description="Threading Building Blocks") + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=output_dir, description="Threading Building Blocks")) return pipeline.run(concurrency=1) diff --git a/dokimi/tests/test_questions_artifact.py b/dokimi/tests/test_questions_artifact.py index b1dbc7cf2..024a0d901 100644 --- a/dokimi/tests/test_questions_artifact.py +++ b/dokimi/tests/test_questions_artifact.py @@ -443,6 +443,7 @@ def test_a_list_metadata_is_kept_under_items(): def _pipeline(tmp_path, monkeypatch, **kwargs): """A pipeline whose model calls fail the test; answers and judging are stubbed.""" from dokimi.orchestrator.pipeline import EvaluationPipeline + from dokimi.orchestrator.pipeline_settings import EvaluationSettings def no_model_call(*a, **kw): raise AssertionError("a model call was made") @@ -454,8 +455,8 @@ def no_model_call(*a, **kw): [{"question_id": q["id"]} for q in questions]) monkeypatch.setattr(EvaluationPipeline, "_evaluate_answers", lambda self, *a, **kw: []) monkeypatch.setattr(EvaluationPipeline, "_generate_report", lambda self, *a, **kw: "report") - return EvaluationPipeline(product="oneTBB", output_dir=tmp_path / "run", - description="Threading Building Blocks", **kwargs) + return EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=tmp_path / "run", + description="Threading Building Blocks", **kwargs)) def _personas(tmp_path): diff --git a/dokimi/tests/test_report_writers_surrogate.py b/dokimi/tests/test_report_writers_surrogate.py index a0cf7cbab..0c2475c1a 100644 --- a/dokimi/tests/test_report_writers_surrogate.py +++ b/dokimi/tests/test_report_writers_surrogate.py @@ -12,6 +12,7 @@ from dokimi.cli import build_parser from dokimi.orchestrator.pipeline import EvaluationPipeline +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.report.markdown_report import write_compare_report, write_run_report NAMES = pytest.mark.parametrize( @@ -100,7 +101,7 @@ def test_model_compare_writes_the_run_id(tmp_path, name, written): @NAMES def test_pipeline_report_step_writes_the_question_text(tmp_path, name, written): output_dir = tmp_path / "run" - pipeline = EvaluationPipeline(product="oneTBB", output_dir=output_dir, description="Threading Building Blocks") + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=output_dir, description="Threading Building Blocks")) text = f"Q {name}" pipeline.eval_path.write_text( json.dumps({"evaluations": [{**_EVALUATION, "question_text": text}]}), encoding="utf-8") diff --git a/dokimi/tests/test_run_wide_stop.py b/dokimi/tests/test_run_wide_stop.py index 3637811f6..508430db2 100644 --- a/dokimi/tests/test_run_wide_stop.py +++ b/dokimi/tests/test_run_wide_stop.py @@ -22,6 +22,7 @@ from dokimi.eval.arm_runner import ArmRunner from dokimi.treatments import BaselineTreatment from tests.test_answers_command import _args, _stub_generate +from dokimi.orchestrator.pipeline_settings import EvaluationSettings QUESTIONS = [{"id": "q1", "question": "How do I parallelize a loop?"}, {"id": "q2", "question": "How do I sum an array in parallel?"}] @@ -199,8 +200,8 @@ def test_a_stopped_answers_run_is_not_judged_or_reported_as_whole(monkeypatch, t calls = _usage_stop(monkeypatch, arm_runner_module, stop_on_call=3) # q1's two arms, then q2's first monkeypatch.setattr(pipeline_mod, "create_doc_source_client", lambda source: EmptyDocClient()) - pipe = pipeline_mod.EvaluationPipeline(product="lib", output_dir=tmp_path, description="d", model="m", - provider="claude-cli") + pipe = pipeline_mod.EvaluationPipeline(settings=EvaluationSettings(product="lib", output_dir=tmp_path, description="d", model="m", + provider="claude-cli")) with pytest.raises(RuntimeError, match="stopped after 2 of 2 questions: usage limit exceeded"): pipe._generate_answers(QUESTIONS, concurrency=1) diff --git a/dokimi/tests/test_writers_save_artifact.py b/dokimi/tests/test_writers_save_artifact.py index 3352e2c57..bde595bb1 100644 --- a/dokimi/tests/test_writers_save_artifact.py +++ b/dokimi/tests/test_writers_save_artifact.py @@ -126,10 +126,11 @@ def test_a_persona_the_model_gives_other_types_is_saved_with_the_schemas_types( def test_an_evaluate_run_goes_on_past_a_persona_the_model_gives_other_types(tmp_path, persona_reply): """The pipeline's personas step saves the same way, so the run is not stopped by the schema.""" from dokimi.orchestrator.pipeline import EvaluationPipeline + from dokimi.orchestrator.pipeline_settings import EvaluationSettings persona_reply["personas"] = [{**PERSONA, "id": 7}] - pipeline = EvaluationPipeline(product="lib", description="A library", product_key="lib", - output_dir=tmp_path / "run") + pipeline = EvaluationPipeline(settings=EvaluationSettings(product="lib", description="A library", product_key="lib", + output_dir=tmp_path / "run")) assert pipeline._discover_personas()["personas"][0]["id"] == "7" assert _saved(tmp_path / "run" / "personas" / "lib.json", "personas")["personas"][0]["id"] == "7"