From 3c7635a8da10fcd71707cdaf2e7f725c6b565535 Mon Sep 17 00:00:00 2001 From: daiyu Date: Sat, 10 Oct 2026 00:07:09 +0800 Subject: [PATCH] fix(eval): score coverage against the benchmark instead of the predictions file evaluate() computed accuracy as matches / len(outputs), so a crashed run, --limit or a filtered file produced a full-looking accuracy with no warning, and duplicate question_ids were counted twice. - New pure helper resolve_prediction_coverage() deduplicates predictions (keeping the first per question_id) and returns expected / answered / missing / duplicates. Unknown ids now raise ValueError naming the id instead of a bare KeyError from questions[qid]. - New normalize_question_id() accepts int-like strings (123), which other tools commonly produce; anything else fails with the offending value. - The two asserts in evaluate_sample are replaced with explicit errors: they disappear entirely under python -O, letting malformed input through. - coverage lands both in print_summary (Coverage / Missing / Duplicate rows plus Accuracy over Benchmark) and in the JSON report; evaluate() logs a warning whenever coverage is below 100%. - New accuracy_over_benchmark field counts unanswered questions as wrong. Note: replacing the asserts changes what two existing tests in tests/utils/test_evaluation_utils.py assert on, so those assertions are updated (string ids are now a valid input, not an error case). Closes #124 --- llmsql/evaluation/evaluate.py | 35 +++++++- llmsql/utils/evaluation_utils.py | 117 +++++++++++++++++++++--- llmsql/utils/rich_utils.py | 43 ++++++++- tests/utils/test_evaluation_utils.py | 130 +++++++++++++++++++++++++-- 4 files changed, 306 insertions(+), 19 deletions(-) diff --git a/llmsql/evaluation/evaluate.py b/llmsql/evaluation/evaluate.py index d67eb9f..4f90bb8 100644 --- a/llmsql/evaluation/evaluate.py +++ b/llmsql/evaluation/evaluate.py @@ -18,9 +18,11 @@ DEFAULT_LLMSQL_VERSION, get_repo_id, ) +from llmsql.loggers.logging_config import log from llmsql.utils.evaluation_utils import ( connect_sqlite, evaluate_sample, + resolve_prediction_coverage, ) from llmsql.utils.inference_utils import _maybe_download, resolve_workdir_path from llmsql.utils.leaderboard_utils import ( @@ -65,7 +67,14 @@ def evaluate( "arguments": {"num_fewshots": 5}}}``. Returns: - dict: Metrics and mismatches. + dict: Metrics and mismatches, plus coverage counters ``expected``, + ``answered``, ``missing`` and ``duplicates``. ``accuracy`` is + computed over the predictions, ``accuracy_over_benchmark`` counts + unanswered questions as wrong. + + Raises: + ValueError: if a prediction references a ``question_id`` that is not + part of the benchmark. """ # Determine input type @@ -90,6 +99,23 @@ def evaluate( "outputs must be file path or list of dicts in format {'question_id': int, 'completion': str}" ) + # --- Drop duplicates / measure coverage against the benchmark --- + # Scoring the predictions file directly made partial runs (crash, --limit, + # filtered file) look like full results, and counted duplicate ids twice. + outputs_list, coverage = resolve_prediction_coverage(outputs_list, questions) + + if coverage["duplicates"]: + log.warning( + f"{coverage['duplicates']} duplicate question_id(s) in the predictions " + f"file; keeping only the first prediction for each." + ) + if coverage["missing"]: + log.warning( + f"Coverage {coverage['answered']}/{coverage['expected']} question(s): " + f"{coverage['missing']} benchmark question(s) have no prediction, so " + f"accuracy is computed over {coverage['answered']} answer(s) only." + ) + # --- Connect to DB --- conn = connect_sqlite(db_path) @@ -127,6 +153,7 @@ def evaluate( metrics["gold_none"], metrics["sql_errors"], metrics["exact_string_matches"], + coverage, ) # --- Build report structure --- @@ -135,7 +162,13 @@ def evaluate( "model_name": model_name, "version": version, **metrics, + **coverage, "accuracy": accuracy, + # Missing answers count as wrong, so a partial run cannot silently + # report a full-looking accuracy. + "accuracy_over_benchmark": ( + metrics["matches"] / coverage["expected"] if coverage["expected"] else 0.0 + ), "exact_string_match_accuracy": ( metrics["exact_string_matches"] / metrics["total"] if metrics["total"] diff --git a/llmsql/utils/evaluation_utils.py b/llmsql/utils/evaluation_utils.py index 94ec7a8..04e253a 100644 --- a/llmsql/utils/evaluation_utils.py +++ b/llmsql/utils/evaluation_utils.py @@ -79,6 +79,94 @@ def normalize_sql(sql: str) -> str: return re.sub(r"\s+", " ", sql.strip().rstrip(";").strip()) +def normalize_question_id(value: Any) -> int: + """ + Coerce a ``question_id`` coming from a predictions file into an ``int``. + + Other tools commonly serialise ids as strings (``"123"``), so an int-like + string is accepted and converted. Anything else fails with a message that + names the offending value. + + Args: + value: raw ``question_id`` value from a prediction entry. + + Returns: + The id as ``int``. + + Raises: + TypeError: if the value is neither an int nor a string. + ValueError: if the value is a string that does not parse as an int. + """ + if isinstance(value, int): + return value + + if isinstance(value, str): + text = value.strip() + try: + return int(text) + except ValueError: + raise ValueError( + f"question_id must be an int or an int-like string, got {value!r}." + ) from None + + raise TypeError( + f"question_id must be an int or an int-like string, got {type(value).__name__}." + ) + + +def resolve_prediction_coverage( + outputs_list: list[dict[str, Any]], + questions: dict[int, dict[str, str]], +) -> tuple[list[dict[str, Any]], dict[str, int]]: + """ + Deduplicate predictions and measure how much of the benchmark they cover. + + ``evaluate()`` used to score whatever rows happened to be in the predictions + file, so a crashed run (or ``--limit``) produced a full-looking accuracy + with no hint that most questions were never answered. Duplicate ids were + also counted twice. + + Args: + outputs_list: predictions as loaded from a JSONL file or passed by the caller. + questions: benchmark questions keyed by ``question_id``. + + Returns: + A tuple ``(unique_outputs, coverage)`` where ``coverage`` holds + ``expected`` (benchmark size), ``answered`` (unique matching ids), + ``missing`` (benchmark questions with no prediction) and ``duplicates``. + + Raises: + ValueError: if a prediction references an id that is not in the benchmark. + """ + expected = len(questions) + seen: set[int] = set() + unique: list[dict[str, Any]] = [] + duplicates = 0 + + for item in outputs_list: + qid = normalize_question_id(item["question_id"]) + + if qid not in questions: + raise ValueError( + f"question_id {qid} from the predictions file is not part of the " + f"benchmark ({expected} questions loaded)." + ) + + if qid in seen: + duplicates += 1 + continue + + seen.add(qid) + unique.append(item) + + return unique, { + "expected": expected, + "answered": len(seen), + "missing": expected - len(seen), + "duplicates": duplicates, + } + + def evaluate_sample( item: dict[str, int | str], questions: dict[int, dict[str, str]], @@ -115,11 +203,17 @@ def evaluate_sample( "sql_error": int } """ - # Extract question metadata - qid = item["question_id"] - assert isinstance( - qid, int - ), "question_id in the outputs file needs to be of type int." + # Extract question metadata. + # These used to be plain asserts: ``python -O`` strips asserts entirely, so + # malformed input silently slipped through instead of being reported. + qid = normalize_question_id(item["question_id"]) + + if qid not in questions: + raise ValueError( + f"question_id {qid} from the predictions file is not part of the " + f"benchmark ({len(questions)} questions loaded)." + ) + q_info = questions[qid] table_id, gold_sql, question_text = ( q_info["table_id"], @@ -142,10 +236,13 @@ def evaluate_sample( last_pred_res = None # store last prediction results for mismatch logging # Loop over all SQL queries extracted from the model output - assert isinstance( - item["completion"], str - ), f"Completion filed in outputs file must be of type string: {item['completion']}. Type: {type(item['completion'])}" - for pred_sql in find_sql(item["completion"]): + completion = item["completion"] + if not isinstance(completion, str): + raise TypeError( + f"completion must be of type str, got {type(completion).__name__}: " + f"{completion!r}" + ) + for pred_sql in find_sql(completion): # Replace placeholder table names with the actual one pred_sql_fixed = fix_table_name(pred_sql, table_id) @@ -179,7 +276,7 @@ def evaluate_sample( "question_id": qid, "question": question_text, "gold_sql": gold_sql, - "model_output": item["completion"], + "model_output": completion, "gold_results": gold_results, "prediction_results": last_pred_res, } diff --git a/llmsql/utils/rich_utils.py b/llmsql/utils/rich_utils.py index 3fc41bf..ae2275c 100644 --- a/llmsql/utils/rich_utils.py +++ b/llmsql/utils/rich_utils.py @@ -37,20 +37,57 @@ def print_summary( gold_none: int, sql_errors: int, exact_string_matches: int, + coverage: dict[str, int] | None = None, ) -> None: - """Pretty-print summary with Rich.""" + """ + Pretty-print summary with Rich. + + Args: + total, matches, pred_none, gold_none, sql_errors, exact_string_matches: + per-prediction counters. + coverage: optional ``{"expected", "answered", "missing", "duplicates"}`` + mapping as returned by + :func:`~llmsql.utils.evaluation_utils.resolve_prediction_coverage`. + When given, answered/missing coverage and accuracy over the whole + benchmark are added to the table. + """ table = Table(title="[green]Evaluation Summary[/green]", show_lines=True) table.add_column("Metric", style="bold green") table.add_column("Value", style="bold yellow") table.add_row("Total Samples", str(total)) - table.add_row("Correct Results", f"{matches} ({matches / total:.2%})") + + if coverage: + expected = coverage["expected"] + answered = coverage["answered"] + coverage_text = ( + f"{answered}/{expected} ({answered / expected:.2%})" if expected else "n/a" + ) + table.add_row("Coverage", coverage_text) + + if coverage["missing"]: + table.add_row("Missing Predictions", str(coverage["missing"])) + if coverage["duplicates"]: + table.add_row("Duplicate Predictions", str(coverage["duplicates"])) + + table.add_row( + "Correct Results", + f"{matches} ({matches / total:.2%})" if total else "n/a", + ) table.add_row( "Exact String Match", - f"{exact_string_matches} ({exact_string_matches / total:.2%})", + f"{exact_string_matches} ({exact_string_matches / total:.2%})" + if total + else "n/a", ) table.add_row("Prediction None", f"{pred_none}/{total}") table.add_row("Ground Truth None", f"{gold_none}/{total}") table.add_row("SQL Errors", str(sql_errors)) + if coverage and coverage["expected"]: + table.add_row( + "Accuracy over Benchmark", + f"{matches} ({matches / coverage['expected']:.2%})", + ) + console.print(table) diff --git a/tests/utils/test_evaluation_utils.py b/tests/utils/test_evaluation_utils.py index ee8004d..c815cfa 100644 --- a/tests/utils/test_evaluation_utils.py +++ b/tests/utils/test_evaluation_utils.py @@ -8,7 +8,9 @@ evaluate_sample, execute_sql, fix_table_name, + normalize_question_id, normalize_sql, + resolve_prediction_coverage, ) @@ -279,22 +281,42 @@ def test_multiple_predictions_none_match(self, eval_db, questions_dict) -> None: ) assert is_match == 0 + def test_int_like_string_question_id_is_accepted( + self, eval_db, questions_dict + ) -> None: + """Other tools serialise ids as strings; int-like strings must work.""" + item = { + "question_id": "1", # int-like string instead of int + "completion": "SELECT name FROM Table WHERE id = 1", + } + is_match, _, _ = evaluate_sample(item, questions_dict, eval_db) + assert is_match == 1 + def test_invalid_question_id_type(self, eval_db, questions_dict) -> None: - """Test assertion when question_id is not int.""" + """A non-int-like question_id is reported by name, not by a bare assert.""" + item = { + "question_id": "not-an-id", + "completion": "SELECT 1", + } + with pytest.raises(ValueError, match="not-an-id"): + evaluate_sample(item, questions_dict, eval_db) + + def test_unknown_question_id_is_reported(self, eval_db, questions_dict) -> None: + """An id outside the benchmark raises ValueError instead of KeyError.""" item = { - "question_id": "1", # String instead of int + "question_id": 99999, "completion": "SELECT 1", } - with pytest.raises(AssertionError): + with pytest.raises(ValueError, match="99999"): evaluate_sample(item, questions_dict, eval_db) def test_invalid_completion_type(self, eval_db, questions_dict) -> None: - """Test assertion when completion is not string.""" + """Test error when completion is not string.""" item = { "question_id": 1, "completion": ["SELECT 1"], # List instead of string } - with pytest.raises(AssertionError): + with pytest.raises(TypeError, match="completion"): evaluate_sample(item, questions_dict, eval_db) def test_metrics_counters(self, eval_db, questions_dict) -> None: @@ -398,3 +420,101 @@ def test_null_results_metrics(self, eval_db) -> None: assert metrics["pred_none"] == 1 assert metrics["sql_error"] == 0 assert metrics["exact_string_match"] == 1 + + +class TestNormalizeQuestionId: + """question_id coercion""" + + def test_int_passes_through(self): + assert normalize_question_id(42) == 42 + + def test_int_like_string_is_accepted(self): + assert normalize_question_id("42") == 42 + assert normalize_question_id(" 42 ") == 42 + + def test_non_int_string_is_rejected(self): + with pytest.raises(ValueError): + normalize_question_id("forty-two") + + def test_unsupported_type_is_rejected(self): + with pytest.raises(TypeError): + normalize_question_id(None) + with pytest.raises(TypeError): + normalize_question_id([1]) + + +class TestResolvePredictionCoverage: + """Coverage accounting for partial / duplicated / malformed predictions""" + + @staticmethod + def _questions(*ids): + return { + qid: {"table_id": qid, "sql": "SELECT 1", "question": "q"} for qid in ids + } + + @staticmethod + def _item(qid): + return {"question_id": qid, "completion": "SELECT 1"} + + def test_full_coverage(self): + questions = self._questions(1, 2, 3) + outputs = [self._item(1), self._item(2), self._item(3)] + + unique, coverage = resolve_prediction_coverage(outputs, questions) + + assert len(unique) == 3 + assert coverage == { + "expected": 3, + "answered": 3, + "missing": 0, + "duplicates": 0, + } + + def test_partial_run_is_reported_as_missing(self): + """Regression: 1 of 3 answered used to yield a full-looking accuracy.""" + questions = self._questions(1, 2, 3) + + unique, coverage = resolve_prediction_coverage([self._item(1)], questions) + + assert len(unique) == 1 + assert coverage["expected"] == 3 + assert coverage["answered"] == 1 + assert coverage["missing"] == 2 + + def test_duplicates_keep_first_prediction(self): + questions = self._questions(1, 2) + outputs = [self._item(1), self._item(1), self._item(2), self._item(1)] + + unique, coverage = resolve_prediction_coverage(outputs, questions) + + assert [item["question_id"] for item in unique] == [1, 2] + assert coverage["duplicates"] == 2 + + def test_string_ids_are_matched_against_the_benchmark(self): + questions = self._questions(1, 2) + + unique, coverage = resolve_prediction_coverage( + [self._item("1"), self._item("2")], questions + ) + + assert [item["question_id"] for item in unique] == ["1", "2"] + assert coverage["missing"] == 0 + + def test_unknown_id_raises_with_the_id_in_the_message(self): + questions = self._questions(1) + + with pytest.raises(ValueError, match="999"): + resolve_prediction_coverage([self._item(999)], questions) + + def test_empty_predictions(self): + questions = self._questions(1, 2) + + unique, coverage = resolve_prediction_coverage([], questions) + + assert unique == [] + assert coverage == { + "expected": 2, + "answered": 0, + "missing": 2, + "duplicates": 0, + }