From e4135cd1dc14ee5a5517f8ee0e666f1153974b1e Mon Sep 17 00:00:00 2001 From: daiyu Date: Mon, 12 Oct 2026 23:52:33 +0800 Subject: [PATCH] fix(eval): open the benchmark DB read-only and cap every query with a budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #96 Evaluation runs SQL that was extracted from model output against a database that is cached under `workdir_path` and reused by every later run. Two ways that goes wrong: 1. Nothing stops a destructive statement. `connect_sqlite()` handed out a regular read-write connection, so one `DROP TABLE` / `DELETE FROM` candidate silently corrupts `sqlite_tables.db` for good — and the issue notes the extractor is the only thing keeping `find_sql()` results SELECT-only, which is not a guarantee. 2. Nothing bounds a single statement. A pathological query (self-join, unbounded recursive CTE) hangs evaluation forever with no way back short of killing the process. Changes: - `connect_sqlite()` opens `file:?mode=ro` via URI mode and turns on `PRAGMA query_only`. `Path.resolve().as_uri()` takes care of absolute paths and escaping, so paths with spaces or `#` don't break the URI. Write attempts now fail, which `execute_sql` already reports as `None`. - `execute_sql(conn, sql, query_timeout=DEFAULT_QUERY_TIMEOUT)` installs a `set_progress_handler` callback with a monotonic deadline; returning non-zero aborts the statement, and the existing `except Exception` turns that into `None`. The handler lives on the connection, so it is always removed again in a `finally` — otherwise the next statement on that connection would inherit an expired deadline. `query_timeout <= 0` restores the previous unbounded behaviour. - The budget is threaded through `evaluate_sample(..., query_timeout=...)` and `evaluate(..., query_timeout=...)`, defaulting to 5s per statement. Tests (tests/evaluation/test_db_safety.py, 16 cases): - `DROP`/`DELETE`/`UPDATE`/`INSERT`/`ALTER` all fail and leave the data intact. - An unbounded recursive CTE is cut off within its budget, the connection stays usable afterwards, and it is counted as a SQL error by `evaluate_sample`. - The progress handler is installed and removed on both success and failure, and not installed at all when the budget is disabled. - `evaluate()` forwards `query_timeout` down to `evaluate_sample`. Verified: full suite goes 197 -> 213 passed with the same 7 pre-existing failures (all `transformers`-missing or Windows-path related in this environment). Reverting the read-only connection makes all 5 destructive statement tests fail, confirming they bite. --- llmsql/evaluation/evaluate.py | 11 +- llmsql/utils/evaluation_utils.py | 86 +++++++++- tests/evaluation/test_db_safety.py | 258 +++++++++++++++++++++++++++++ 3 files changed, 348 insertions(+), 7 deletions(-) create mode 100644 tests/evaluation/test_db_safety.py diff --git a/llmsql/evaluation/evaluate.py b/llmsql/evaluation/evaluate.py index 9565fb1..1816773 100644 --- a/llmsql/evaluation/evaluate.py +++ b/llmsql/evaluation/evaluate.py @@ -20,6 +20,7 @@ ) from llmsql.loggers.logging_config import log from llmsql.utils.evaluation_utils import ( + DEFAULT_QUERY_TIMEOUT, connect_sqlite, evaluate_sample, resolve_prediction_coverage, @@ -44,6 +45,7 @@ def evaluate( model_name: str | None = None, save_leaderboard_yaml: str | None = None, run_metadata: dict[str, Any] | None = None, + query_timeout: float = DEFAULT_QUERY_TIMEOUT, ) -> dict: """ Evaluate predicted SQL queries against the LLMSQL benchmark. @@ -63,8 +65,11 @@ def evaluate( ``leaderboard/`` folder). If None, no YAML is written. run_metadata: Optional dict deep-merged into the leaderboard YAML to fill fields that cannot be detected automatically, e.g. - ``{"type": "open-source", "inference": {"backend": "vllm", + `` {"type": "open-source", "inference": {"backend": "vllm", "arguments": {"num_fewshots": 5}}}``. + query_timeout: Per-statement time budget in seconds. A prediction (or + gold query) that runs longer is aborted and counted as a SQL error + instead of hanging the run. ``<= 0`` disables the budget. Returns: dict: Metrics and mismatches, plus coverage counters ``expected``, @@ -133,7 +138,9 @@ def evaluate( 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, query_timeout=query_timeout + ) metrics["matches"] += is_match metrics["pred_none"] += m["pred_none"] diff --git a/llmsql/utils/evaluation_utils.py b/llmsql/utils/evaluation_utils.py index 04e253a..26f1575 100644 --- a/llmsql/utils/evaluation_utils.py +++ b/llmsql/utils/evaluation_utils.py @@ -2,6 +2,7 @@ from pathlib import Path import re import sqlite3 +import time from typing import Any from huggingface_hub import hf_hub_download @@ -9,8 +10,32 @@ from llmsql.loggers.logging_config import log from llmsql.utils.regex_extractor import find_sql +# Time budget for a single SQL statement, in seconds. +# +# The statements handed to `execute_sql` are extracted from model output, so a +# pathological one (a self-join, an unbounded recursive CTE) can run forever and +# hang the whole evaluation. Without a budget there is no way to get control +# back short of killing the process. +DEFAULT_QUERY_TIMEOUT = 5.0 -def execute_sql(conn: sqlite3.Connection, sql: str) -> list[tuple] | None: +# Granularity of the SQLite progress callback: the deadline is checked once +# every this many VM instructions. Small enough to catch runaway queries +# quickly, large enough not to slow normal ones down. +PROGRESS_HANDLER_OPS = 1000 + + +def _clear_progress_handler(conn: sqlite3.Connection) -> None: + """Remove any progress handler installed on `conn`.""" + clear = getattr(conn, "set_progress_handler", None) + if callable(clear): + clear(None, 0) + + +def execute_sql( + conn: sqlite3.Connection, + sql: str, + query_timeout: float = DEFAULT_QUERY_TIMEOUT, +) -> list[tuple] | None: """ Execute a SQL query on the given SQLite connection and return its results. @@ -20,6 +45,10 @@ def execute_sql(conn: sqlite3.Connection, sql: str) -> list[tuple] | None: Args: conn (sqlite3.Connection): An active SQLite database connection. sql (str): SQL query string to execute. + query_timeout (float): Time budget for this one statement, in seconds. + A statement that runs longer is aborted and reported as a failure + (``None``), which callers count as a SQL error. ``<= 0`` disables + the budget, restoring the previous unbounded behaviour. Returns: Optional[List[Tuple]]: @@ -27,13 +56,31 @@ def execute_sql(conn: sqlite3.Connection, sql: str) -> list[tuple] | None: - [(None,)] if the query executed but returned NULL values. - None if the SQL execution failed due to an exception. """ + use_timeout = query_timeout is not None and query_timeout > 0 + try: + if use_timeout: + # SQLite calls this back while the statement runs; returning a + # non-zero value aborts it with an "interrupted" error, which the + # except branch below already turns into None. + deadline = time.monotonic() + query_timeout + + def _abort_when_over_budget() -> int: + return 1 if time.monotonic() > deadline else 0 + + conn.set_progress_handler(_abort_when_over_budget, PROGRESS_HANDLER_OPS) + cur = conn.cursor() cur.execute(sql) results = cur.fetchall() return sorted(results) except Exception: return None + finally: + # The handler lives on the connection, so it has to be removed again or + # the next statement on this connection inherits an expired deadline. + if use_timeout: + _clear_progress_handler(conn) def fix_table_name(sql: str, table_id: str) -> str: @@ -171,6 +218,7 @@ def evaluate_sample( item: dict[str, int | str], questions: dict[int, dict[str, str]], conn: sqlite3.Connection, + query_timeout: float = DEFAULT_QUERY_TIMEOUT, ) -> tuple[int, dict[str, Any] | None, dict[Any, Any]]: """ Evaluate a single model prediction against the gold (ground-truth) SQL query. @@ -189,6 +237,9 @@ def evaluate_sample( questions (dict): Dictionary mapping `question_id` → question metadata: {"sql": ..., "table_id": ..., "question": ...}. conn (sqlite3.Connection): Active SQLite connection used to run queries. + query_timeout (float): Per-statement time budget in seconds; a statement + that overruns it is aborted and counted as a SQL error. ``<= 0`` + disables the budget. Returns: tuple: @@ -222,7 +273,7 @@ def evaluate_sample( ) # Execute the gold (ground-truth) SQL - gold_results = execute_sql(conn, gold_sql) + gold_results = execute_sql(conn, gold_sql, query_timeout=query_timeout) # Initialize counters for this sample pred_none = gold_none = sql_error = exact_string_match = 0 @@ -247,7 +298,7 @@ def evaluate_sample( pred_sql_fixed = fix_table_name(pred_sql, table_id) # Execute predicted SQL - pred_res = execute_sql(conn, pred_sql_fixed) + pred_res = execute_sql(conn, pred_sql_fixed, query_timeout=query_timeout) last_pred_res = pred_res # Exact string match after whitespace / trailing semicolon normalization. @@ -307,7 +358,32 @@ def download_benchmark_file(repo_id: str, filename: str, local_dir: Path) -> str def connect_sqlite(db_path: str) -> sqlite3.Connection: - """Create SQLite connection.""" + """ + Open the benchmark SQLite database read-only. + + The statements that :func:`execute_sql` runs are extracted from model + output, and the database is cached under ``workdir_path`` and reused by + every later run. A writable connection therefore means one destructive + candidate (``DROP TABLE``, ``DELETE FROM``, ...) silently corrupts the + benchmark for good. Opening with ``mode=ro`` plus ``PRAGMA query_only`` + makes those statements fail instead, which :func:`execute_sql` already + reports as a SQL error. + + Args: + db_path (str): Path to the SQLite database file. + + Returns: + sqlite3.Connection: A read-only connection. + + Raises: + FileNotFoundError: if `db_path` does not exist. + """ if not os.path.exists(db_path): raise FileNotFoundError(f"Database not found at: {db_path}") - return sqlite3.connect(db_path) + + # as_uri() needs an absolute path and takes care of escaping, so paths with + # spaces or '#' don't break the URI. + uri = Path(db_path).resolve().as_uri() + "?mode=ro" + conn = sqlite3.connect(uri, uri=True) + conn.execute("PRAGMA query_only = ON") + return conn diff --git a/tests/evaluation/test_db_safety.py b/tests/evaluation/test_db_safety.py new file mode 100644 index 0000000..40c56e8 --- /dev/null +++ b/tests/evaluation/test_db_safety.py @@ -0,0 +1,258 @@ +"""Evaluation runs model-generated SQL against a shared DB. + +The statements come out of the model output, so they must not be able to change +the database (see issue #96): one destructive candidate would otherwise corrupt +the cached ``sqlite_tables.db`` for every later run. A pathological query must +not be able to hang the run either. +""" + +import sqlite3 +import time + +import pytest + +from llmsql.evaluation.evaluate import evaluate +from llmsql.utils.evaluation_utils import ( + DEFAULT_QUERY_TIMEOUT, + connect_sqlite, + evaluate_sample, + execute_sql, +) +from llmsql.utils.regex_extractor import find_sql + +# A single statement that never terminates on its own (unbounded recursive CTE). +# It has to start with SELECT so the extractor picks it up like a real +# prediction would. +RUNAWAY_SQL = ( + "SELECT (WITH RECURSIVE c(n) AS " + "(SELECT 1 UNION ALL SELECT n+1 FROM c) SELECT count(*) FROM c)" +) + + +@pytest.fixture +def db_file(tmp_path): + """A small SQLite DB with one table, copied next to the evaluation files.""" + db_path = tmp_path / "sqlite_tables.db" + conn = sqlite3.connect(db_path) + conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)") + conn.executemany("INSERT INTO test (name) VALUES (?)", [("Alice",), ("Bob",)]) + conn.commit() + conn.close() + return str(db_path) + + +class TestReadOnlyConnection: + """connect_sqlite must not hand out a writable connection""" + + @pytest.mark.parametrize( + "statement", + [ + "DROP TABLE test", + "DELETE FROM test", + "UPDATE test SET name = 'x'", + "INSERT INTO test (name) VALUES ('Carol')", + "ALTER TABLE test ADD COLUMN extra TEXT", + ], + ) + def test_write_attempts_fail_and_leave_db_intact(self, db_file, statement): + conn = connect_sqlite(db_file) + try: + assert execute_sql(conn, statement) is None + finally: + conn.close() + + # The data has to survive: the DB is cached in workdir_path and reused + # by every later evaluation. + check = sqlite3.connect(db_file) + try: + assert check.execute("SELECT name FROM test ORDER BY id").fetchall() == [ + ("Alice",), + ("Bob",), + ] + finally: + check.close() + + def test_reads_still_work(self, db_file): + conn = connect_sqlite(db_file) + try: + assert execute_sql(conn, "SELECT name FROM test") == [ + ("Alice",), + ("Bob",), + ] + finally: + conn.close() + + def test_missing_db_still_raises(self, tmp_path): + with pytest.raises(FileNotFoundError): + connect_sqlite(str(tmp_path / "nope.db")) + + +class TestQueryTimeout: + """A runaway statement must be cut off instead of hanging the run""" + + def test_runaway_query_is_aborted_within_budget(self, db_file): + conn = connect_sqlite(db_file) + try: + start = time.monotonic() + assert execute_sql(conn, RUNAWAY_SQL, query_timeout=1.0) is None + elapsed = time.monotonic() - start + finally: + conn.close() + + # Some slack for slow CI machines, but nowhere near an unbounded run. + assert elapsed < 10.0 + + def test_connection_is_usable_after_an_abort(self, db_file): + """Aborting one statement must not poison the connection""" + conn = connect_sqlite(db_file) + try: + assert execute_sql(conn, RUNAWAY_SQL, query_timeout=0.5) is None + assert execute_sql(conn, "SELECT name FROM test") == [ + ("Alice",), + ("Bob",), + ] + finally: + conn.close() + + def test_fast_queries_are_not_affected(self, db_file): + conn = connect_sqlite(db_file) + try: + assert execute_sql(conn, "SELECT name FROM test", query_timeout=0.05) == [ + ("Alice",), + ("Bob",), + ] + finally: + conn.close() + + def test_timeout_is_counted_as_sql_error(self, db_file): + """ + An overrunning prediction is a SQL error, not a silent wrong answer + """ + questions = { + 1: { + "table_id": "test", + "sql": "SELECT name FROM test", + "question": "List names", + } + } + item = {"question_id": 1, "completion": RUNAWAY_SQL} + + conn = connect_sqlite(db_file) + try: + is_match, _, metrics = evaluate_sample( + item, questions, conn, query_timeout=1.0 + ) + finally: + conn.close() + + # The extractor yields one candidate per SELECT keyword, and every one + # of them overruns the budget, so each is counted as a SQL error. + assert is_match == 0 + assert metrics["sql_error"] == len(find_sql(RUNAWAY_SQL)) + + def test_default_budget_is_applied(self): + """The default is a real budget, not an unbounded run""" + assert DEFAULT_QUERY_TIMEOUT > 0 + + +class StubConnection: + """Records progress-handler calls instead of running SQL""" + + def __init__(self, fail=False): + self.installed = 0 + self.cleared = 0 + self.fail = fail + + def set_progress_handler(self, handler, n): + if handler is None: + self.cleared += 1 + else: + self.installed += 1 + + def cursor(self): + class _Cursor: + def __init__(self, fail): + self.fail = fail + + def execute(self, sql): + if self.fail: + raise sqlite3.OperationalError("boom") + + def fetchall(self): + return [(1,)] + + return _Cursor(self.fail) + + +class TestProgressHandlerLifecycle: + """The handler lives on the connection, so it must be installed and removed""" + + def test_installed_and_cleared_on_success(self): + conn = StubConnection() + assert execute_sql(conn, "SELECT 1", query_timeout=1.0) == [(1,)] + assert (conn.installed, conn.cleared) == (1, 1) + + def test_cleared_after_a_failed_statement(self): + conn = StubConnection(fail=True) + assert execute_sql(conn, "SELECT 1", query_timeout=1.0) is None + assert (conn.installed, conn.cleared) == (1, 1) + + def test_not_installed_when_budget_is_disabled(self): + conn = StubConnection() + assert execute_sql(conn, "SELECT 1", query_timeout=0) == [(1,)] + assert (conn.installed, conn.cleared) == (0, 0) + + +class TestEvaluatePassesTimeout: + """evaluate() has to forward the budget down to evaluate_sample""" + + def test_query_timeout_reaches_evaluate_sample(self, monkeypatch, tmp_path): + # evaluate() only needs the file to exist here: evaluate_sample is + # replaced below, so no query is ever run against it. + db_path = tmp_path / "sqlite_tables.db" + sqlite3.connect(db_path).close() + + (tmp_path / "questions.jsonl").write_text( + '{"question_id": 1, "table_id": "test", "question": "Q", ' + '"sql": "SELECT 1"}' + ) + (tmp_path / "outputs.jsonl").write_text( + '{"question_id": 1, "completion": "SELECT 1"}' + ) + + captured = {} + + def fake_evaluate_sample(item, questions, conn, **kwargs): + captured.update(kwargs) + return ( + 1, + None, + { + "pred_none": 0, + "gold_none": 0, + "sql_error": 0, + "exact_string_match": 1, + }, + ) + + monkeypatch.setattr( + "llmsql.evaluation.evaluate.evaluate_sample", fake_evaluate_sample + ) + monkeypatch.setattr( + "llmsql.evaluation.evaluate.print_summary", lambda *a, **k: None + ) + monkeypatch.setattr( + "llmsql.evaluation.evaluate.log_mismatch", lambda **k: None + ) + monkeypatch.setattr( + "llmsql.evaluation.evaluate.save_json_report", lambda path, report: None + ) + + evaluate( + outputs=str(tmp_path / "outputs.jsonl"), + workdir_path=str(tmp_path), + show_mismatches=False, + query_timeout=1.5, + ) + + assert captured["query_timeout"] == 1.5