From c6a2799c2425d58056cf1444972b52df4f13101b Mon Sep 17 00:00:00 2001 From: daiyu Date: Sun, 11 Oct 2026 23:55:12 +0800 Subject: [PATCH] fix(eval): don't drop a random-named report file in the CWD MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #128 `evaluate()` called `save_json_report()` unconditionally. When `save_report` was None it generated `evaluation_results_.json`, so every call from a notebook, a test or a loop left a new file behind in the working directory — and the report embeds every mismatch with the full model output, so a full run can be tens of MB. The repo even had a session fixture that sweeps `evaluation_results*` out of the CWD after the test session. Changes: * `evaluate()` writes the file only when `save_report` is given. The report dict was already returned to the caller, so nothing is lost for API users. * `llmsql evaluate` still produces a report by default (a one-shot CLI run should leave one behind), but at a deterministic path derived from `--outputs`: `.eval.json`. Re-running on the same predictions overwrites the previous report instead of piling up new ones. * The SQLite connection now goes through `contextlib.closing()` around the evaluation loop. It used to be closed only by a bare `conn.close()` at the end of the function, so any exception raised by `evaluate_sample()` leaked it. * Dropped the now-unused `uuid` import and updated `evaluation/README.md`, which documented the old default filename. Tests: * `test_no_report_file_is_written_when_save_report_is_none` replaces the old `test_saves_report_with_auto_filename`, which asserted the exact behaviour the issue asks us to remove. * `test_report_is_written_to_the_given_path` keeps the `save_report=` path covered. * Two CLI tests pin the default `.eval.json` name and check that an explicit `--save-report` is passed through untouched. --- llmsql/_cli/evaluate.py | 10 +++- llmsql/evaluation/README.md | 5 +- llmsql/evaluation/evaluate.py | 47 +++++++++--------- tests/cli/test_cli.py | 50 +++++++++++++++++++- tests/evaluation/test_evaluator_stability.py | 29 +++++++++--- 5 files changed, 107 insertions(+), 34 deletions(-) diff --git a/llmsql/_cli/evaluate.py b/llmsql/_cli/evaluate.py index f28b823..5a1a228 100644 --- a/llmsql/_cli/evaluate.py +++ b/llmsql/_cli/evaluate.py @@ -108,11 +108,19 @@ def _execute(args: argparse.Namespace) -> None: if not isinstance(run_metadata, dict): raise ValueError("--run-metadata file must contain a mapping") + save_report = args.save_report + if save_report is None: + # evaluate() 本身不再默认落盘,但 CLI 一行命令跑完总得留下报告。 + # 这里用与 --outputs 对应的确定性文件名,而不是随机名, + # 重跑同一份预测会覆盖旧报告而不是堆一地文件。 + save_report = f"{args.outputs}.eval.json" + log.info("No --save-report given; writing report to %s", save_report) + evaluate( outputs=args.outputs, version=args.version, workdir_path=args.workdir_path, - save_report=args.save_report, + save_report=save_report, show_mismatches=args.show_mismatches, max_mismatches=args.max_mismatches, model_name=args.model_name, diff --git a/llmsql/evaluation/README.md b/llmsql/evaluation/README.md index 2f51da9..ad0627c 100644 --- a/llmsql/evaluation/README.md +++ b/llmsql/evaluation/README.md @@ -57,7 +57,7 @@ evaluate( | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `outputs` | **Required**. Either a path to a JSONL file or a list of dicts with predictions. | | `workdir_path` | Directory used to cache downloaded benchmark files. If omitted, a temporary directory is created automatically. | -| `save_report` | Optional path to save detailed JSON report. Defaults to `evaluation_results_{uuid}.json`. | +| `save_report` | Optional path to save a detailed JSON report. Default: `None` (no file written — the report is returned as a dict). | | `show_mismatches` | Print mismatches while evaluating. Default: `True`. | | `max_mismatches` | Maximum number of mismatches to print. Default: `5`. | | `model_name` | Name of the evaluated model (e.g. `Qwen/Qwen3-0.6B`). Stored in the JSON report and the leaderboard YAML. Default: `None`. | @@ -106,7 +106,8 @@ Total: 100 | Matches: 82 | Pred None: 5 | Gold None: 3 | SQL Errors: 2 **Report Saving** -* By default, the report is saved as `evaluation_results_{uuid}.json` in the current directory. +* No file is written unless you pass `save_report`; `evaluate()` always returns the report as a dict. +* The CLI (`llmsql evaluate`) still writes a report by default, to `outputs.eval.json` next to `--outputs` (override with `--save-report`). * Includes timestamp and input mode (JSONL path or dict list). * You can override the save path via the `save_report` argument. diff --git a/llmsql/evaluation/evaluate.py b/llmsql/evaluation/evaluate.py index 9565fb1..fe4c7b5 100644 --- a/llmsql/evaluation/evaluate.py +++ b/llmsql/evaluation/evaluate.py @@ -8,9 +8,9 @@ See the documentation for full usage details. """ +from contextlib import closing from datetime import datetime, timezone from typing import Any -import uuid from rich.progress import track @@ -53,7 +53,8 @@ def evaluate( outputs: Either a JSONL file path or a list of dicts. workdir_path: Directory to store downloaded benchmark files. If omitted, a temporary directory is created automatically. - save_report: Optional manual save path. If None → auto-generated. + save_report: Optional manual save path. If None → no report file is + written (the report dict is still returned). show_mismatches: Print mismatches while evaluating. max_mismatches: Max mismatches to print. model_name: Name of the evaluated model (e.g. ``Qwen/Qwen3-0.6B``). @@ -116,9 +117,6 @@ def evaluate( f"accuracy is computed over {coverage['answered']} answer(s) only." ) - # --- Connect to DB --- - conn = connect_sqlite(db_path) - # --- Evaluation loop --- metrics = { "total": 0, @@ -130,21 +128,25 @@ def evaluate( } mismatches: list[dict] = [] - for item in track(outputs_list, description="Evaluating"): - metrics["total"] += 1 + # --- Connect to DB --- + # closing() 保证 evaluate_sample 抛异常时连接也会被关掉:原来只有函数末尾 + # 一句 conn.close(),中途报错就把连接漏在那儿。 + with closing(connect_sqlite(db_path)) as conn: + for item in track(outputs_list, description="Evaluating"): + metrics["total"] += 1 - is_match, mismatch_info, m = evaluate_sample(item, questions, conn) + is_match, mismatch_info, m = evaluate_sample(item, questions, conn) - metrics["matches"] += is_match - metrics["pred_none"] += m["pred_none"] - metrics["gold_none"] += m["gold_none"] - metrics["sql_errors"] += m["sql_error"] - metrics["exact_string_matches"] += m["exact_string_match"] + metrics["matches"] += is_match + metrics["pred_none"] += m["pred_none"] + metrics["gold_none"] += m["gold_none"] + metrics["sql_errors"] += m["sql_error"] + metrics["exact_string_matches"] += m["exact_string_match"] - if mismatch_info: - mismatches.append(mismatch_info) - if show_mismatches and len(mismatches) <= max_mismatches: - log_mismatch(**mismatch_info) + if mismatch_info: + mismatches.append(mismatch_info) + if show_mismatches and len(mismatches) <= max_mismatches: + log_mismatch(**mismatch_info) print_summary( metrics["total"], @@ -179,11 +181,11 @@ def evaluate( "input_mode": input_mode, } - # --- Auto-generate report filename (if not provided) --- - if save_report is None: - save_report = f"evaluation_results_{uuid.uuid4()}.json" - - save_json_report(save_report, report) + # 只有显式传入路径才落盘。以前 None 会生成一个随机名的文件写在当前目录, + # 每次 notebook / 测试 / 循环调用都会多留一个可能几十 MB 的报告; + # 报告字典本来就会作为返回值交回调用方,CLI 侧自己会补一个确定性的路径。 + if save_report is not None: + save_json_report(save_report, report) if save_leaderboard_yaml is not None: # The leaderboard ranks models on the whole benchmark: unanswered @@ -198,5 +200,4 @@ def evaluate( ) write_leaderboard_yaml(save_leaderboard_yaml, record) - conn.close() return report diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 7dc1ad1..a6db75c 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -261,4 +261,52 @@ async def test_evaluate_command_called(monkeypatch): call_kwargs = mock_evaluate.call_args.kwargs assert call_kwargs["outputs"] == "dummy_file.jsonl" assert call_kwargs["show_mismatches"] is True - assert call_kwargs["max_mismatches"] == 10 \ No newline at end of file + assert call_kwargs["max_mismatches"] == 10 + + +@pytest.mark.asyncio +async def test_evaluate_default_report_path_is_deterministic(monkeypatch): + """ + CLI 没传 --save-report 时仍然要出报告,但文件名要可预测。 + + evaluate() 本身不再默认落盘,CLI 这里补一个由 --outputs 推导出来的 + 确定性路径,重跑同一份预测会覆盖旧报告,而不是每次多一个随机文件。 + """ + mock_evaluate = MagicMock(return_value={}) + monkeypatch.setattr("llmsql._cli.evaluate.evaluate", mock_evaluate) + + monkeypatch.setattr( + sys, "argv", ["llmsql", "evaluate", "--outputs", "dummy_file.jsonl"] + ) + + cli = ParserCLI() + args = cli.parse_args() + cli.execute(args) + + assert mock_evaluate.call_args.kwargs["save_report"] == "dummy_file.jsonl.eval.json" + + +@pytest.mark.asyncio +async def test_evaluate_explicit_report_path_is_preserved(monkeypatch): + """显式传了 --save-report 时用调用方给的路径,不覆盖成默认名""" + mock_evaluate = MagicMock(return_value={}) + monkeypatch.setattr("llmsql._cli.evaluate.evaluate", mock_evaluate) + + monkeypatch.setattr( + sys, + "argv", + [ + "llmsql", + "evaluate", + "--outputs", + "dummy_file.jsonl", + "--save-report", + "custom/report.json", + ], + ) + + cli = ParserCLI() + args = cli.parse_args() + cli.execute(args) + + assert mock_evaluate.call_args.kwargs["save_report"] == "custom/report.json" \ No newline at end of file diff --git a/tests/evaluation/test_evaluator_stability.py b/tests/evaluation/test_evaluator_stability.py index 321b115..c7d7d76 100644 --- a/tests/evaluation/test_evaluator_stability.py +++ b/tests/evaluation/test_evaluator_stability.py @@ -236,7 +236,12 @@ def test_download_occurs_if_files_missing(mock_utils, mocker): assert dl.call_count == 2 # questions + sqlite -def test_saves_report_with_auto_filename(mock_utils, mocker): +def test_no_report_file_is_written_when_save_report_is_none(mock_utils, mocker): + """save_report=None 时不能再往当前目录丢一个随机名的报告文件 + + 报告字典本来就会作为返回值交回调用方,没必要每次调用都落盘一份 + (里面带全部 mismatch 的模型输出,完整跑一次能到几十 MB)。 + """ save = mocker.patch("llmsql.evaluation.evaluate.save_json_report") report = evaluate( @@ -245,15 +250,25 @@ def test_saves_report_with_auto_filename(mock_utils, mocker): save_report=None, ) - # automatic UUID-based filename - args, kwargs = save.call_args - auto_filename = args[0] - assert auto_filename.startswith("evaluation_results_") - assert auto_filename.endswith(".json") - + save.assert_not_called() assert report["total"] == 1 +def test_report_is_written_to_the_given_path(mock_utils, mocker, tmp_path): + """显式给了 save_report 时才落盘,且写到指定的路径""" + save = mocker.patch("llmsql.evaluation.evaluate.save_json_report") + report_path = tmp_path / "report.json" + + evaluate( + [{"question_id": 1, "completion": "SELECT 1"}], + workdir_path=str(mock_utils), + save_report=str(report_path), + ) + + args, kwargs = save.call_args + assert args[0] == str(report_path) + + def test_mismatch_handling(mock_utils, mocker): """Test branch where a mismatch is returned.""" mocker.patch(