Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/docs/evaluation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,20 @@ The function returns a dictionary with the following keys:
- timestamp – Evaluation timestamp
- input_mode – How results were provided ("jsonl_path" or "dict_list")

How a Prediction Is Scored
--------------------------

The evaluator extracts up to 10 SQL candidates from each model completion and
executes them in turn. A sample counts as correct when **any** candidate returns
the same result as the gold query, so a model that emits several queries is
scored on its best one. Candidates that fail to execute count toward
``sql_errors``.

Candidates are taken from the end of the completion. When a model reasons in
prose before answering, its final query is the answer, so trailing candidates
win over leading ones. A Markdown block tagged ``sql`` wins over any query found
in the surrounding prose.

Report Saving
-------------

Expand Down
119 changes: 99 additions & 20 deletions llmsql/utils/regex_extractor.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,116 @@
import re

_FENCE = "```"

# A fenced block tagged as SQL, e.g. ```sql\nSELECT 1\n```
_FENCED_SQL = re.compile(r"```[ \t]*sql[ \t]*\r?\n(.*?)```", re.IGNORECASE | re.DOTALL)

# Every occurrence of the SELECT keyword starts a candidate query
_SELECT = re.compile(r"(?i)(SELECT)")

# Characters that open a quoted run: a string literal, a quoted identifier
# or a backtick-quoted identifier.
_QUOTES = "'\"" + "`"


def _skip_quoted(text: str, index: int) -> int:
"""Return the index just past the quoted run that opens at ``index``.

SQL escapes a quote inside a literal by doubling it, so ``'it''s'`` is a
single literal rather than two adjacent ones.
"""
quote = text[index]
position = index + 1
while position < len(text):
if text[position] == quote:
if text.startswith(quote * 2, position):
position += 2
continue
return position + 1
position += 1
return len(text)


def _query_end(text: str, start: int) -> int:
"""Return the index just past the query that starts at ``start``.

A query ends at a semicolon, at a run of at least four newlines, at a
markdown fence, or at the end of the text. Semicolons inside a quoted
literal or a quoted identifier do not end the query, so
``WHERE b = 'x;y';`` is no longer cut down to ``WHERE b = 'x``.
"""
index = start
newlines = 0
while index < len(text):
# A fence is checked before quotes: ``` is a markdown marker, not the
# start of a backtick-quoted identifier.
if text.startswith(_FENCE, index):
return index
char = text[index]
if char in _QUOTES:
index = _skip_quoted(text, index)
newlines = 0
continue
if char == ";":
return index
if char == "\n":
newlines += 1
if newlines >= 4:
return index - (newlines - 1)
elif char != "\r":
newlines = 0
index += 1
return len(text)


def _fenced_sql_blocks(model_output: str) -> list[str]:
"""Return the contents of every ````sql`` fenced block, in order."""
blocks: list[str] = []
for match in _FENCED_SQL.finditer(model_output):
query = match.group(1).strip()
# The scanner drops the terminating ";", so fenced queries match it.
if query.endswith(";"):
query = query[:-1].strip()
if query and "select" in query.lower() and query not in blocks:
blocks.append(query)
return blocks


def _scan_selects(model_output: str) -> list[str]:
"""Return one candidate query per SELECT keyword occurrence."""
results: list[str] = []
for match in _SELECT.finditer(model_output):
start_pos = match.start(1) # Start of SELECT word
query = model_output[start_pos : _query_end(model_output, start_pos)].strip()
if query and query not in results:
results.append(query)
return results


def find_sql(model_output: str, limit: int = 10) -> list[str]:
"""Function to extract SQL queries from the model's response

A fenced ````sql`` block is the clearest statement of intent, so its
contents win over any SELECT found in the surrounding prose. Without a
fence, every SELECT keyword starts a candidate.

The last ``limit`` candidates are returned, not the first ones: a model
that reasons out loud before answering starts its prose with words like
"select", and those prose candidates used to fill every slot and push the
real query out of the list.

Args:
model_output (str): Model's response as string
limit (int, optional): The number of SQL queries to return. Defaults to 10.

Returns:
List[str]: SQL queries from input.
"""
results = []

# Find all SELECT keywords that could start a query
for match in re.finditer(r"(?i)(SELECT)", model_output, re.IGNORECASE):
start_pos = match.start(1) # Start of SELECT word

# Look for end of query constraints from this position:
# semicolumn, block of at least 4 newlines, markdown code fence or just end of string.
remaining = model_output[start_pos:]
query_match = re.search(
r"(?s)SELECT\b.*?(?=(?:;|\n{4,}|```|$))",
remaining,
re.IGNORECASE,
)

if query_match:
query = query_match.group(0).strip()
if query and query not in results:
results.append(query)
if limit <= 0:
return []

return results[:limit]
results = _fenced_sql_blocks(model_output) or _scan_selects(model_output)
return results[-limit:]


if __name__ == "__main__":
Expand Down
90 changes: 90 additions & 0 deletions tests/utils/test_regex_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,93 @@ def test_limit_zero(self) -> None:
output = "SELECT * FROM users"
result = find_sql(output, limit=0)
assert result == []


class TestFindSQLQuotedTerminators:
"""A ';' only ends a query when it is outside quotes."""

def test_semicolon_inside_string_literal(self) -> None:
"""Regression test: a ';' in a literal must not truncate the query."""
output = """SELECT a FROM "Table" WHERE b = 'x;y';"""
result = find_sql(output)
assert result == ["""SELECT a FROM "Table" WHERE b = 'x;y'"""]

def test_semicolon_inside_doubled_quote_escape(self) -> None:
"""'' is an escaped quote, so the ';' after it is still inside the literal."""
output = "SELECT a FROM t WHERE b = 'it''s; here';"
result = find_sql(output)
assert result == ["SELECT a FROM t WHERE b = 'it''s; here'"]

def test_semicolon_inside_quoted_identifier(self) -> None:
output = 'SELECT "we;ird" FROM t;'
result = find_sql(output)
assert result == ['SELECT "we;ird" FROM t']

def test_semicolon_inside_backtick_identifier(self) -> None:
output = "SELECT `we;ird` FROM t;"
result = find_sql(output)
assert result == ["SELECT `we;ird` FROM t"]

def test_semicolon_after_the_literal_still_terminates(self) -> None:
"""The terminating ';' must still work once the literal is closed."""
output = "SELECT a FROM t WHERE b = 'x'; SELECT c FROM t;"
result = find_sql(output)
assert len(result) == 2
assert result[0] == "SELECT a FROM t WHERE b = 'x'"


class TestFindSQLCandidateOrder:
"""The final answer is at the end of the output, not the start."""

_QUERY = 'SELECT "a" FROM "t" WHERE "b" = 1'

def _reasoning_then_query(self, sentences: int = 12) -> str:
prose = "\n".join(
f"I need to select the right column for question {i}."
for i in range(sentences)
)
return f"{prose}\n{self._QUERY};"

def test_query_after_reasoning_prose_is_kept(self) -> None:
"""
Regression test: prose that starts with 'select' used to fill every
slot, so the real query at the end was never evaluated.
"""
result = find_sql(self._reasoning_then_query())
assert self._QUERY in result

def test_last_candidates_survive_the_limit(self) -> None:
result = find_sql(self._reasoning_then_query(), limit=1)
assert result == [self._QUERY]

def test_first_candidates_are_the_prose(self) -> None:
"""The prose candidates are still extracted, just no longer preferred."""
result = find_sql(self._reasoning_then_query())
assert len(result) == 10
assert result[-1] == self._QUERY


class TestFindSQLFencedBlocks:
"""A ```sql block is the clearest statement of intent."""

def test_sql_fence_is_preferred_over_prose(self) -> None:
output = (
"I need to select the right column first.\n"
"```sql\nSELECT a FROM t;\n```\n"
)
result = find_sql(output)
assert result == ["SELECT a FROM t"]

def test_last_sql_fence_wins(self) -> None:
output = "```sql\nSELECT 1;\n```\nsome prose\n```sql\nSELECT 2;\n```\n"
result = find_sql(output, limit=1)
assert result == ["SELECT 2"]

def test_untagged_fence_falls_back_to_scanning(self) -> None:
"""A bare ``` block is not a sql fence, so scanning still applies."""
output = "```\nSELECT * FROM data\n```"
assert find_sql(output) == ["SELECT * FROM data"]

def test_empty_sql_fence_falls_back_to_scanning(self) -> None:
output = "```sql\n\n```\nSELECT a FROM t;"
assert find_sql(output) == ["SELECT a FROM t"]
Loading