Skip to content

fix(eval): open the benchmark DB read-only and cap every query with a budget - #142

Open
ddaihao2022 wants to merge 1 commit into
LLMSQL:mainfrom
ddaihao2022:fix-96-readonly-db-and-query-timeout
Open

ddaihao2022 wants to merge 1 commit into
LLMSQL:mainfrom
ddaihao2022:fix-96-readonly-db-and-query-timeout

Conversation

@ddaihao2022

Copy link
Copy Markdown
Contributor

Closes #96

What this fixes

Evaluation runs SQL extracted from model output against a database that is
cached under workdir_path and reused by every later run. Two things were
unguarded:

  1. Nothing stopped a destructive statement. connect_sqlite() handed out a
    regular read-write connection, so a single DROP TABLE / DELETE FROM
    candidate silently corrupts sqlite_tables.db permanently. As the issue
    notes, the only thing keeping statements read-only today is find_sql()
    requiring a leading SELECT — that is a property of the extractor, not a
    guarantee from the execution layer, and it disappears the moment the
    extractor changes.
  2. Nothing bounded a single statement. A pathological query (self-join,
    unbounded recursive CTE) hangs evaluation forever, with no way back short of
    killing the process.

Changes

1. Read-only connection (llmsql/utils/evaluation_utils.py)

uri = Path(db_path).resolve().as_uri() + "?mode=ro"
conn = sqlite3.connect(uri, uri=True)
conn.execute("PRAGMA query_only = ON")

resolve().as_uri() gives an absolute, properly escaped URI, so paths with
spaces or # don't break it. Write attempts now fail, which execute_sql
already reports as None → counted as a SQL error. Reads are unaffected.

FileNotFoundError behaviour for a missing DB is unchanged.

2. Per-statement time budget

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, which the existing except Exception turns 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
already-expired deadline and abort immediately. query_timeout <= 0 restores
the previous unbounded behaviour.

Default is DEFAULT_QUERY_TIMEOUT = 5.0 seconds, checked every
PROGRESS_HANDLER_OPS = 1000 VM instructions.

3. Wired through

evaluate_sample(..., query_timeout=...) and
evaluate(..., query_timeout=...), so callers can tune or disable it.

Tests

New tests/evaluation/test_db_safety.py — 16 cases:

  • DROP TABLE / DELETE FROM / UPDATE / INSERT / ALTER TABLE all fail
    and leave the data intact (DB is reopened independently to confirm).
  • Reads still work on the read-only connection; a missing DB still raises
    FileNotFoundError.
  • An unbounded recursive CTE is cut off within its budget, the connection stays
    usable afterwards, and evaluate_sample counts it as a SQL error.
  • 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.

Verification

  • Full suite: 197 → 213 passed, with the same 7 pre-existing failures and
    5 collection errors as on unmodified main in my environment (all caused by
    transformers not being installed here, plus one Windows-path assertion in
    tests/utils/test_inference_utils.py). No new failures.
  • Reverse check: reverting connect_sqlite() to sqlite3.connect(db_path)
    makes all 5 destructive-statement tests fail, so they really bite.
  • ruff check clean on the three touched files.

Not done / notes

  • No CLI flag was added (the issue only asks for evaluate(..., query_timeout=...)); happy to add --query-timeout to llmsql evaluate if
    you want it exposed on the command line.
  • PRAGMA query_only = ON also blocks CREATE TEMP TABLE. Nothing in llmsql/
    uses temp tables (checked), and it is the extra belt-and-braces the issue
    suggests — say the word if you'd rather rely on mode=ro alone.

… budget

Closes LLMSQL#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:<abs path>?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.
@codecov

codecov Bot commented Oct 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Security] Evaluation executes model-generated SQL on a writable DB connection without timeout

1 participant