diff --git a/llmsql/_cli/inference.py b/llmsql/_cli/inference.py index 919ced4..c9f3321 100644 --- a/llmsql/_cli/inference.py +++ b/llmsql/_cli/inference.py @@ -187,6 +187,16 @@ def add_common_benchmark_args(parser: argparse.ArgumentParser) -> None: parser.add_argument("--batch-size", type=int, default=8) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--limit", type=parse_limit) + parser.add_argument( + "--resume", + action=argparse.BooleanOptionalAction, + default=False, + help=( + "Keep the completions already present in --output-file and " + "only generate the missing questions (use --no-resume to " + "always start from an empty file, which is the default)." + ), + ) # ========================= # COMMON GENERATION ARGS @@ -350,6 +360,7 @@ def _execute_transformers(args: argparse.Namespace) -> None: batch_size=args.batch_size, limit=args.limit, seed=args.seed, + resume=args.resume, ) @staticmethod @@ -374,6 +385,7 @@ def _execute_vllm(args: argparse.Namespace) -> None: num_fewshots=args.num_fewshots, batch_size=args.batch_size, seed=args.seed, + resume=args.resume, ) @staticmethod @@ -395,4 +407,5 @@ def _execute_api(args: argparse.Namespace) -> None: limit=args.limit, num_fewshots=args.num_fewshots, seed=args.seed, + resume=args.resume, ) diff --git a/llmsql/inference/inference_api.py b/llmsql/inference/inference_api.py index 7746cb7..0caa041 100644 --- a/llmsql/inference/inference_api.py +++ b/llmsql/inference/inference_api.py @@ -18,21 +18,17 @@ import nest_asyncio from tqdm.asyncio import tqdm -from llmsql.config.config import ( - DEFAULT_LLMSQL_VERSION, - get_repo_id, -) +from llmsql.config.config import DEFAULT_LLMSQL_VERSION from llmsql.loggers.logging_config import log from llmsql.utils.inference_utils import ( - _maybe_download, _setup_seed, - resolve_workdir_path, + prepare_benchmark, + prepare_output_file, + skip_completed, ) from llmsql.utils.utils import ( build_all_requests, choose_prompt_builder, - load_jsonl, - overwrite_jsonl, save_jsonl_lines, ) @@ -180,6 +176,7 @@ def inference_api( limit: int | float | None = None, num_fewshots: int = 5, seed: int = 42, + resume: bool = False, ) -> list[dict[str, str]]: """Run SQL generation using an OpenAI-compatible Chat Completions API. @@ -205,6 +202,9 @@ def inference_api( limit: Limit the number of questions to evaluate. If an integer, evaluates the first N samples. If a float between 0.0 and 1.0, evaluates the first X*100% of samples. If None, evaluates all samples (default). + resume: If True and `output_file` already exists, keep the completions it + contains and only generate the missing questions. If False + (default), the file is truncated first. Returns: List of dicts containing `question_id` and generated `completion`. @@ -213,28 +213,11 @@ def inference_api( api_kwargs = api_kwargs or {} request_headers = request_headers or {} - workdir = resolve_workdir_path(workdir_path) - - repo_id = get_repo_id(version) - questions_path = _maybe_download(repo_id, "questions.jsonl", workdir) - tables_path = _maybe_download(repo_id, "tables.jsonl", workdir) - - questions = load_jsonl(questions_path) - tables_list = load_jsonl(tables_path) - tables = {t["table_id"]: t for t in tables_list} - - if limit is not None: - if isinstance(limit, float): - if not (0.0 < limit <= 1.0): - raise ValueError( - f"When a float, `limit` must be between 0.0 and 1.0, got {limit}." - ) - limit = max(1, int(len(questions) * limit)) - if not isinstance(limit, int) or limit < 1: - raise ValueError( - f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}." - ) - questions = questions[:limit] + run = prepare_benchmark( + version=version, + workdir_path=workdir_path, + limit=limit, + ) key = api_key or os.environ.get("OPENAI_API_KEY") headers: dict[str, str] = { @@ -246,7 +229,9 @@ def inference_api( prompt_builder = choose_prompt_builder(num_fewshots) - overwrite_jsonl(output_file) + questions = skip_completed( + run.questions, prepare_output_file(output_file, resume=resume) + ) coro = _inference_api_async( model_name, @@ -257,7 +242,7 @@ def inference_api( requests_per_minute=requests_per_minute, api_kwargs=api_kwargs, questions=questions, - tables=tables, + tables=run.tables, prompt_builder=prompt_builder, output_file=output_file, ) diff --git a/llmsql/inference/inference_function.py b/llmsql/inference/inference_function.py index 64c34f3..2d114c7 100644 --- a/llmsql/inference/inference_function.py +++ b/llmsql/inference/inference_function.py @@ -18,18 +18,17 @@ import nest_asyncio from tqdm.asyncio import tqdm -from llmsql.config.config import DEFAULT_LLMSQL_VERSION, get_repo_id +from llmsql.config.config import DEFAULT_LLMSQL_VERSION from llmsql.loggers.logging_config import log from llmsql.utils.inference_utils import ( - _maybe_download, _setup_seed, - resolve_workdir_path, + prepare_benchmark, + prepare_output_file, + skip_completed, ) from llmsql.utils.utils import ( build_all_requests, choose_prompt_builder, - load_jsonl, - overwrite_jsonl, save_jsonl_lines, ) @@ -186,6 +185,7 @@ def inference_function( limit: int | float | None = None, num_fewshots: int = 5, seed: int = 42, + resume: bool = False, ) -> list[dict[str, str]]: """Run SQL generation using a user-provided async callable. @@ -259,6 +259,10 @@ def inference_function( samples (default). num_fewshots: Number of few-shot examples (0, 1, or 5). seed: Random seed for reproducibility. + resume: If ``True`` and ``output_file`` already exists, keep the + completions it contains and only generate the missing questions. + If ``False`` (default), ``output_file`` is truncated first — the + historical behaviour. Returns: List of dicts containing ``question_id`` and generated ``completion``, @@ -288,32 +292,18 @@ def inference_function( ) function_kwargs = function_kwargs or {} - workdir = resolve_workdir_path(workdir_path) - repo_id = get_repo_id(version) - questions_path = _maybe_download(repo_id, "questions.jsonl", workdir) - tables_path = _maybe_download(repo_id, "tables.jsonl", workdir) - - questions = load_jsonl(questions_path) - tables_list = load_jsonl(tables_path) - tables = {t["table_id"]: t for t in tables_list} - - if limit is not None: - if isinstance(limit, float): - if not (0.0 < limit <= 1.0): - raise ValueError( - f"When a float, `limit` must be between 0.0 and 1.0, got {limit}." - ) - limit = max(1, int(len(questions) * limit)) - if not isinstance(limit, int) or limit < 1: - raise ValueError( - f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}." - ) - questions = questions[:limit] + run = prepare_benchmark( + version=version, + workdir_path=workdir_path, + limit=limit, + ) prompt_builder = choose_prompt_builder(num_fewshots) - overwrite_jsonl(output_file) + questions = skip_completed( + run.questions, prepare_output_file(output_file, resume=resume) + ) coro = _inference_function_async( inference_callable=inference_function, @@ -322,7 +312,7 @@ def inference_function( raise_on_error=raise_on_error, function_kwargs=function_kwargs, questions=questions, - tables=tables, + tables=run.tables, prompt_builder=prompt_builder, output_file=output_file, ) diff --git a/llmsql/inference/inference_transformers.py b/llmsql/inference/inference_transformers.py index 3bcb381..bf96405 100644 --- a/llmsql/inference/inference_transformers.py +++ b/llmsql/inference/inference_transformers.py @@ -44,20 +44,16 @@ from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer -from llmsql.config.config import ( - DEFAULT_LLMSQL_VERSION, - get_repo_id, -) +from llmsql.config.config import DEFAULT_LLMSQL_VERSION from llmsql.loggers.logging_config import log from llmsql.utils.inference_utils import ( - _maybe_download, _setup_seed, - resolve_workdir_path, + prepare_benchmark, + prepare_output_file, + skip_completed, ) from llmsql.utils.utils import ( choose_prompt_builder, - load_jsonl, - overwrite_jsonl, save_jsonl_lines, ) @@ -120,6 +116,7 @@ def inference_transformers( batch_size: int = 8, limit: int | float | None = None, seed: int = 42, + resume: bool = False, ) -> list[dict[str, str]]: """ Inference a causal model (Transformers) on the LLMSQL benchmark. @@ -169,6 +166,9 @@ def inference_transformers( limit: Limit the number of questions to evaluate. If an integer, evaluates the first N samples. If a float between 0.0 and 1.0, evaluates the first X*100% of samples. If None, evaluates all samples (default). + resume: If True and `output_file` already exists, keep the completions it + contains and only generate the missing questions. If False + (default), the file is truncated first. Returns: List of generated SQL results with metadata. @@ -254,32 +254,11 @@ def inference_transformers( model.eval() # --- Load necessary files --- - workdir = resolve_workdir_path(workdir_path) - repo_id = get_repo_id(version) - - questions_path = _maybe_download(repo_id, "questions.jsonl", workdir) - tables_path = _maybe_download(repo_id, "tables.jsonl", workdir) - - questions = load_jsonl(questions_path) - tables_list = load_jsonl(tables_path) - tables = {t["table_id"]: t for t in tables_list} - - # --- Apply limit --- - if limit is not None: - if isinstance(limit, float): - if not (0.0 < limit <= 1.0): - raise ValueError( - f"When a float, `limit` must be between 0.0 and 1.0, got {limit}." - ) - limit = max(1, int(len(questions) * limit)) - if not isinstance(limit, int) or limit < 1: - raise ValueError( - f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}." - ) - log.info( - f"Limiting evaluation to first {limit} questions out of {len(questions)}" - ) - questions = questions[:limit] + run = prepare_benchmark( + version=version, + workdir_path=workdir_path, + limit=limit, + ) # --- Chat template setup --- use_chat_template = chat_template or getattr(tokenizer, "chat_template", None) @@ -287,7 +266,9 @@ def inference_transformers( log.info("Using chat template for prompt formatting.") # --- Output setup --- - overwrite_jsonl(output_file) + questions = skip_completed( + run.questions, prepare_output_file(output_file, resume=resume) + ) log.info(f"Writing results to {output_file}") prompt_builder = choose_prompt_builder(num_fewshots) @@ -302,7 +283,7 @@ def inference_transformers( prompts = [] for q in batch: - tbl = tables[q["table_id"]] + tbl = run.tables[q["table_id"]] example_row = tbl["rows"][0] if tbl["rows"] else [] text = prompt_builder( q["question"], tbl["header"], tbl["types"], example_row diff --git a/llmsql/inference/inference_vllm.py b/llmsql/inference/inference_vllm.py index 53b4ebf..e87b7cc 100644 --- a/llmsql/inference/inference_vllm.py +++ b/llmsql/inference/inference_vllm.py @@ -47,21 +47,17 @@ from vllm import LLM, SamplingParams from vllm.lora.request import LoRARequest -from llmsql.config.config import ( - DEFAULT_LLMSQL_VERSION, - get_repo_id, -) +from llmsql.config.config import DEFAULT_LLMSQL_VERSION from llmsql.loggers.logging_config import log from llmsql.utils.inference_utils import ( - _maybe_download, _setup_seed, - resolve_workdir_path, + prepare_benchmark, + prepare_output_file, + skip_completed, ) from llmsql.utils.utils import ( build_all_requests, choose_prompt_builder, - load_jsonl, - overwrite_jsonl, save_jsonl_lines, ) @@ -92,6 +88,7 @@ def inference_vllm( num_fewshots: int = 5, batch_size: int = 8, seed: int = 42, + resume: bool = False, ) -> list[dict[str, str]]: """ Run SQL generation using vLLM. @@ -137,6 +134,9 @@ def inference_vllm( limit: Limit the number of questions to evaluate. If an integer, evaluates the first N samples. If a float between 0.0 and 1.0, evaluates the first X*100% of samples. If None, evaluates all samples (default). + resume: If True and `output_file` already exists, keep the completions it + contains and only generate the missing questions. If False + (default), the file is truncated first. @@ -153,32 +153,11 @@ def inference_vllm( # --- load input data --- log.info("Preparing questions and tables...") - workdir = resolve_workdir_path(workdir_path) - repo_id = get_repo_id(version) - - questions_path = _maybe_download(repo_id, "questions.jsonl", workdir) - tables_path = _maybe_download(repo_id, "tables.jsonl", workdir) - - questions = load_jsonl(questions_path) - tables_list = load_jsonl(tables_path) - tables = {t["table_id"]: t for t in tables_list} - - # --- Apply limit --- - if limit is not None: - if isinstance(limit, float): - if not (0.0 < limit <= 1.0): - raise ValueError( - f"When a float, `limit` must be between 0.0 and 1.0, got {limit}." - ) - limit = max(1, int(len(questions) * limit)) - if not isinstance(limit, int) or limit < 1: - raise ValueError( - f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}." - ) - log.info( - f"Limiting evaluation to first {limit} questions out of {len(questions)}" - ) - questions = questions[:limit] + run = prepare_benchmark( + version=version, + workdir_path=workdir_path, + limit=limit, + ) # --- Validate LoRA usage --- enable_lora = llm_kwargs.get("enable_lora", False) @@ -220,7 +199,9 @@ def inference_vllm( use_chat_template = getattr(tokenizer, "chat_template", None) # type: ignore # --- prepare output file --- - overwrite_jsonl(output_file) + questions = skip_completed( + run.questions, prepare_output_file(output_file, resume=resume) + ) log.info(f"Output will be written to {output_file}") # --- prompt builder and sampling params --- @@ -239,7 +220,7 @@ def inference_vllm( # --- build all requests --- prompts = build_all_requests( questions, - tables, + run.tables, prompt_builder, tokenizer=tokenizer if use_chat_template else None, use_chat_template=bool(use_chat_template), diff --git a/llmsql/utils/inference_utils.py b/llmsql/utils/inference_utils.py index 72c5880..c34e3e2 100644 --- a/llmsql/utils/inference_utils.py +++ b/llmsql/utils/inference_utils.py @@ -1,12 +1,17 @@ +from dataclasses import dataclass +import json from pathlib import Path import random import tempfile +from typing import Any from huggingface_hub import hf_hub_download import numpy as np import torch +from llmsql.config.config import get_repo_id from llmsql.loggers.logging_config import log +from llmsql.utils.utils import load_jsonl, overwrite_jsonl def resolve_workdir_path(workdir_path: str | Path | None) -> Path: @@ -72,3 +77,135 @@ def _maybe_download( log.info(f"Downloaded {filename} to: {local_path}") return local_path # type: ignore + + +@dataclass(frozen=True) +class BenchmarkRun: + """ + 一份已经取好、limit 也应用过的基准数据 + + Attributes: + questions: 题目列表 + tables: ``table_id -> table`` 映射 + """ + + questions: list[dict[str, Any]] + tables: dict[str, Any] + + +def prepare_benchmark( + *, + version: str, + workdir_path: str | Path | None = None, + limit: int | float | None = None, +) -> BenchmarkRun: + """ + 取基准数据并应用 limit,四个推理后端共用 + + 这段逻辑原先在 ``inference_transformers`` / ``inference_vllm`` / + ``inference_api`` / ``inference_function`` 里各抄了一份,任何修复都得改 + 四遍。 + + Args: + version: 基准版本 + workdir_path: 下载目录,``None`` 时用临时目录 + limit: 题目数量上限(正整数)或比例(0 到 1 之间的浮点) + + Returns: + :class:`BenchmarkRun` + + Raises: + ValueError: ``limit`` 不是正整数也不是 (0, 1] 之间的浮点时抛出 + """ + workdir = resolve_workdir_path(workdir_path) + + repo_id = get_repo_id(version) + questions_path = _maybe_download(repo_id, "questions.jsonl", workdir) + tables_path = _maybe_download(repo_id, "tables.jsonl", workdir) + + questions: list[dict[str, Any]] = load_jsonl(questions_path) + tables_list = load_jsonl(tables_path) + tables: dict[str, Any] = {t["table_id"]: t for t in tables_list} + + if limit is not None: + if isinstance(limit, float): + if not (0.0 < limit <= 1.0): + raise ValueError( + f"When a float, `limit` must be between 0.0 and 1.0, got {limit}." + ) + limit = max(1, int(len(questions) * limit)) + if not isinstance(limit, int) or limit < 1: + raise ValueError( + f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}." + ) + log.info( + f"Limiting evaluation to first {limit} questions out of {len(questions)}" + ) + questions = questions[:limit] + + return BenchmarkRun(questions=questions, tables=tables) + + +def _question_id(question: dict[str, Any]) -> str: + """题目的 ID:基准里写作 ``question_id``,个别写法用 ``id``""" + return str(question.get("question_id", question.get("id", ""))) + + +def _completed_question_ids(output_file: str) -> set[str]: + """ + 读输出文件里已经写完的 question_id + + 上次运行是被杀掉的话,最后一行可能只落了一半,``json.loads`` 会抛错。 + 这种残缺行直接跳过(对应题目重跑一次),不能让续跑流程整个崩掉。 + """ + path = Path(output_file) + if not path.exists(): + return set() + + done: set[str] = set() + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(row, dict): + qid = row.get("question_id", row.get("id")) + if qid is not None: + done.add(str(qid)) + + return done + + +def prepare_output_file(output_file: str, resume: bool = False) -> set[str]: + """ + 准备输出文件,返回已经完成的 question_id 集合 + + ``resume=False``(默认)时清空文件,与旧行为一致;``resume=True`` 且文件里 + 已经有结果时保留原文件,让调用方用 :func:`skip_completed` 跳过这批题目。 + + Args: + output_file: 输出文件路径 + resume: 保留输出文件里已有的结果 + """ + if resume: + done = _completed_question_ids(output_file) + if done: + log.info( + f"Resuming {output_file}: {len(done)} question(s) already answered." + ) + return done + + overwrite_jsonl(output_file) + return set() + + +def skip_completed( + questions: list[dict[str, Any]], done: set[str] +) -> list[dict[str, Any]]: + """去掉 ``done`` 里已经出现过的题目""" + if not done: + return questions + return [q for q in questions if _question_id(q) not in done] diff --git a/tests/inference/test_inference_resume.py b/tests/inference/test_inference_resume.py new file mode 100644 index 0000000..e3e999f --- /dev/null +++ b/tests/inference/test_inference_resume.py @@ -0,0 +1,209 @@ +"""Tests for resuming an interrupted inference run (issue #122).""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from llmsql.inference.inference_function import inference_function +from llmsql.utils.inference_utils import ( + prepare_benchmark, + prepare_output_file, + skip_completed, +) + + +class _Crash(BaseException): + """Stands in for Ctrl-C / a killed process.""" + + +def _write_jsonl(path: Path, rows: list[dict]) -> None: + path.write_text("\n".join(json.dumps(r) for r in rows) + "\n") + + +def _make_fixtures(tmp_path: Path, n_questions: int = 5) -> Path: + """Populate tmp_path with the benchmark files so no download happens.""" + questions = [ + {"question_id": f"q{i}", "question": f"Q{i}?", "table_id": "t1"} + for i in range(n_questions) + ] + tables = [{"table_id": "t1", "header": ["col"], "types": ["text"], "rows": [["x"]]}] + _write_jsonl(tmp_path / "questions.jsonl", questions) + _write_jsonl(tmp_path / "tables.jsonl", tables) + return tmp_path / "out.jsonl" + + +def _read_ids(path: Path) -> list[str]: + return [ + json.loads(line)["question_id"] + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def test_interrupted_run_then_resume_has_one_line_per_question(tmp_path): + """ + Regression test for #122: an interrupted run followed by ``resume=True`` + must end up with exactly one line per question. + + With the old unconditional ``overwrite_jsonl`` the retry starts from an + empty file and re-generates the questions that were already answered, so + those ids appear twice. + """ + out = _make_fixtures(tmp_path) + calls = {"n": 0} + + async def crashing(prompt, **kwargs): + calls["n"] += 1 + if calls["n"] > 2: + raise _Crash + return "SELECT 1" + + with pytest.raises(_Crash): + inference_function( + inference_function=crashing, + max_concurrency=1, + output_file=str(out), + workdir_path=str(tmp_path), + ) + + assert len(_read_ids(out)) == 2, "the interrupted run should keep its progress" + + async def finishing(prompt, **kwargs): + return "SELECT 2" + + results = inference_function( + inference_function=finishing, + max_concurrency=1, + resume=True, + output_file=str(out), + workdir_path=str(tmp_path), + ) + + assert len(results) == 3, "only the missing questions should be generated" + assert sorted(_read_ids(out)) == ["q0", "q1", "q2", "q3", "q4"] + + +def test_resume_skips_already_answered_questions(tmp_path): + """``resume=True`` only generates the questions missing from the file.""" + out = _make_fixtures(tmp_path) + _write_jsonl( + out, + [ + {"question_id": "q0", "completion": "SELECT 0"}, + {"question_id": "q2", "completion": "SELECT 2"}, + ], + ) + + seen: list[str] = [] + + async def fake(prompt, **kwargs): + seen.append(kwargs["question"]["question_id"]) + return "SELECT 1" + + inference_function( + inference_function=fake, + max_concurrency=1, + resume=True, + output_file=str(out), + workdir_path=str(tmp_path), + ) + + assert sorted(seen) == ["q1", "q3", "q4"] + assert sorted(_read_ids(out)) == ["q0", "q1", "q2", "q3", "q4"] + + +def test_without_resume_the_output_file_is_still_overwritten(tmp_path): + """The default (``resume=False``) keeps overwriting, as before.""" + out = _make_fixtures(tmp_path) + _write_jsonl(out, [{"question_id": "stale", "completion": "OLD"}] * 3) + + async def fake(prompt, **kwargs): + return "SELECT 1" + + results = inference_function( + inference_function=fake, + max_concurrency=1, + output_file=str(out), + workdir_path=str(tmp_path), + ) + + assert len(results) == 5 + assert sorted(_read_ids(out)) == ["q0", "q1", "q2", "q3", "q4"] + + +def test_prepare_output_file_keeps_completions_when_resuming(tmp_path): + """``resume=True`` returns the ids already in the file and leaves it alone.""" + out = tmp_path / "out.jsonl" + _write_jsonl(out, [{"question_id": "q0", "completion": "SELECT 0"}]) + + done = prepare_output_file(str(out), resume=True) + + assert done == {"q0"} + assert _read_ids(out) == ["q0"] + + +def test_prepare_output_file_truncates_without_resume(tmp_path): + out = tmp_path / "out.jsonl" + _write_jsonl(out, [{"question_id": "q0", "completion": "OLD"}]) + + done = prepare_output_file(str(out), resume=False) + + assert done == set() + assert out.read_text(encoding="utf-8") == "" + + +def test_resume_ignores_truncated_last_line(tmp_path): + """A half-written final line must not break resume (it is just skipped).""" + out = tmp_path / "out.jsonl" + out.write_text( + '{"question_id": "q0", "completion": "SELECT 0"}\n{"question_id": "q1", "com', + encoding="utf-8", + ) + + done = prepare_output_file(str(out), resume=True) + + assert done == {"q0"} + + +def test_resume_on_missing_file_starts_fresh(tmp_path): + out = tmp_path / "does_not_exist.jsonl" + + done = prepare_output_file(str(out), resume=True) + + assert done == set() + assert out.exists() + + +def test_skip_completed_keeps_order_and_unknown_questions(): + questions = [{"question_id": f"q{i}"} for i in range(4)] + + assert skip_completed(questions, set()) == questions + assert skip_completed(questions, {"q1", "q3"}) == [ + {"question_id": "q0"}, + {"question_id": "q2"}, + ] + assert skip_completed(questions, {"other"}) == questions + + +def test_prepare_benchmark_applies_limit(tmp_path): + _make_fixtures(tmp_path, n_questions=10) + + run = prepare_benchmark(version="2.0", workdir_path=str(tmp_path), limit=3) + + assert [q["question_id"] for q in run.questions] == ["q0", "q1", "q2"] + assert set(run.tables) == {"t1"} + + run = prepare_benchmark(version="2.0", workdir_path=str(tmp_path), limit=0.5) + + assert len(run.questions) == 5 + + +@pytest.mark.parametrize("limit", [0, -1, 1.5, 0.0]) +def test_prepare_benchmark_rejects_bad_limit(tmp_path, limit): + _make_fixtures(tmp_path) + + with pytest.raises(ValueError): + prepare_benchmark(version="2.0", workdir_path=str(tmp_path), limit=limit)