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
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"transport": "actual MCP stdio",
"configured_execution_timeout_seconds": 30,
"elapsed_seconds": 30.00790879095439,
"error": "TimeoutError: SQLite query exceeded execution deadline (30s)",
"same_server_next_query_succeeded": true,
"model_calls": 0,
"prompt_changes": false,
"scope": "SQLite VM execution; connection/lock waits and blocking UDF calls are not covered"
}
55 changes: 53 additions & 2 deletions src/lang2sql/adapters/db/sqlalchemy_explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,52 @@

import asyncio
import logging
import math
import time
from collections import Counter
from contextlib import contextmanager
from typing import Any

from ...core.ports.explorer import Column, DataAccessError, ForeignKey, Table

logger = logging.getLogger(__name__)

_ORACLE_ACCESS_ERRORS = frozenset({942, 1031})
_SQLITE_PROGRESS_OPCODES = 1000


@contextmanager
def _sqlite_deadline(conn, timeout_seconds):
"""Bound SQLite VM execution and remove the handler before returning to the pool.

This does not bound connection acquisition, lock waits, or blocking user
functions that do not yield to the SQLite VM.
"""
if timeout_seconds is None:
yield
return
if not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
raise ValueError("SQL deadline must be a finite positive number")
from sqlalchemy.exc import DBAPIError

raw = conn.connection.driver_connection
deadline = time.monotonic() + timeout_seconds
expired = False

def check_deadline():
nonlocal expired
expired = time.monotonic() >= deadline
return int(expired)

raw.set_progress_handler(check_deadline, _SQLITE_PROGRESS_OPCODES)
try:
yield
except DBAPIError as exc:
if expired:
raise TimeoutError(f"SQLite query exceeded execution deadline ({timeout_seconds}s)") from exc
raise
finally:
raw.set_progress_handler(None, 0)


class SqlAlchemyExplorer:
Expand Down Expand Up @@ -76,6 +114,19 @@ def _sample_rows_sync(self, name: str, limit: int) -> list[dict]:
async def execute(self, sql: str, limit: int = 1000) -> list[dict]:
return await asyncio.to_thread(self._execute_sync, sql, int(limit))

@property
def supports_query_timeout(self) -> bool:
return self.dialect == "sqlite"

@property
def query_timeout_scope(self) -> str:
return "sqlite_vm" if self.supports_query_timeout else "unsupported"

async def execute_with_timeout(self, sql: str, limit: int, timeout_seconds: float) -> list[dict]:
if not self.supports_query_timeout:
raise NotImplementedError("Native query deadlines are currently supported for SQLite only")
return await asyncio.to_thread(self._execute_sync, sql, int(limit), timeout_seconds)

# --- sync workers ----------------------------------------------------

def _list_tables_sync(self) -> list[Table]:
Expand Down Expand Up @@ -152,11 +203,11 @@ def _describe_table_sync(self, name: str) -> Table:
foreign_keys=foreign_keys,
)

def _execute_sync(self, sql: str, limit: int) -> list[dict]:
def _execute_sync(self, sql: str, limit: int, timeout_seconds=None) -> list[dict]:
from sqlalchemy import text
from sqlalchemy.exc import DBAPIError

with self._get_engine().connect() as conn:
with self._get_engine().connect() as conn, _sqlite_deadline(conn, timeout_seconds):
try:
result = conn.execute(text(sql))
except DBAPIError as exc:
Expand Down
15 changes: 15 additions & 0 deletions src/lang2sql/core/ports/explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,18 @@ async def execute(self, sql: str, limit: int = 1000) -> list[dict]:
return up to ``limit`` rows. The ``run_sql`` tool calls this only after
a PASS verdict; the adapter must never see un-gated SQL."""
...


@runtime_checkable
class QueryTimeoutExplorerPort(Protocol):
"""Optional native execution-timeout capability; legacy explorers remain valid."""

@property
def supports_query_timeout(self) -> bool: ...

@property
def query_timeout_scope(self) -> str: ...

async def execute_with_timeout(
self, sql: str, limit: int, timeout_seconds: float
) -> list[dict]: ...
32 changes: 22 additions & 10 deletions src/lang2sql/tools/run_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from typing import TYPE_CHECKING, Any

from ..core.ports.audit import AuditEvent
from ..core.ports.explorer import DataAccessError
from ..core.ports.explorer import DataAccessError, QueryTimeoutExplorerPort
from ..core.ports.safety import SafetyContext, Verdict
from ..core.types import Role, ToolResult, ToolSpec
from .bound_metric import query_metric
Expand Down Expand Up @@ -143,13 +143,11 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult:
is_error=True,
)

decision = ctx.safety.evaluate(
sql,
SafetyContext(
row_limit=limit,
extras={"dialect": getattr(ctx.explorer, "dialect", "")},
),
safety_context = SafetyContext(
row_limit=limit,
extras={"dialect": getattr(ctx.explorer, "dialect", "")},
)
decision = ctx.safety.evaluate(sql, safety_context)
if decision.verdict == Verdict.BLOCK:
return ToolResult(
call_id="",
Expand All @@ -162,11 +160,21 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult:
)

scope = ctx.identity.session_key()
timeout_enforced = (
isinstance(ctx.explorer, QueryTimeoutExplorerPort)
and ctx.explorer.supports_query_timeout
)
logger.info("run_sql started scope=%s actor=%s", scope, ctx.identity.user_id)
try:
# One lookahead row distinguishes an exact-size result from a
# result truncated by the adapter fetch budget. SQL safety is unchanged.
rows = await ctx.explorer.execute(decision.sql, limit + 1)
if timeout_enforced:
rows = await ctx.explorer.execute_with_timeout(
decision.sql, limit + 1, safety_context.timeout_seconds
)
else:
logger.warning("native query timeout unsupported scope=%s", scope)
rows = await ctx.explorer.execute(decision.sql, limit + 1)
except Exception as exc:
logger.warning(
"run_sql failed scope=%s error=%s: %s", scope, type(exc).__name__, exc
Expand Down Expand Up @@ -205,16 +213,20 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult:
return ToolResult(call_id="", content=_render_rows(
decision.sql, rows, fetch_truncated=fetch_truncated,
sql_rewritten=decision.sql != sql,
query_timeout_enforced=timeout_enforced,
query_timeout_scope=ctx.explorer.query_timeout_scope if timeout_enforced else "unsupported",
))


def _render_rows(sql: str, rows: list[dict], *, fetch_truncated=False, sql_rewritten=False) -> str:
def _render_rows(sql: str, rows: list[dict], *, fetch_truncated=False, sql_rewritten=False, query_timeout_enforced=False, query_timeout_scope="unsupported") -> str:
coverage = (
f"Result coverage: fetched_rows={len(rows)}; "
f"displayed_rows={min(len(rows), _DISPLAY_ROW_LIMIT)}; "
f"fetch_truncated={str(fetch_truncated).lower()}; "
f"display_truncated={str(len(rows) > _DISPLAY_ROW_LIMIT).lower()}; "
f"sql_rewritten={str(sql_rewritten).lower()}. "
f"sql_rewritten={str(sql_rewritten).lower()}; "
f"query_timeout_enforced={str(query_timeout_enforced).lower()}; "
f"query_timeout_scope={query_timeout_scope}. "
"Counts refer to the executed SQL, not the source table size."
)
if not rows:
Expand Down
61 changes: 61 additions & 0 deletions tests/test_db_adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,67 @@ def test_sqlalchemy_explorer_introspect_and_execute(tmp_path):
assert len(sample) == 1


def test_run_sql_enforces_safety_deadline_and_reuses_connection(tmp_path):
from lang2sql.core.identity import Identity
from lang2sql.safety.pipeline import SafetyPipeline
from lang2sql.tenancy.tool_runtime import build_tool_context
from lang2sql.tools.run_sql import RunSQL

class ShortDeadline:
def evaluate(self, sql, context):
context.timeout_seconds = 0.01
return SafetyPipeline().evaluate(sql, context)

explorer = SqlAlchemyExplorer(f"sqlite:///{tmp_path / 'timeout.db'}")
ctx = build_tool_context(Identity(user_id="test"), store_path=":memory:", explorer=explorer)
ctx.safety = ShortDeadline()
query = "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<2000000) SELECT SUM(x) AS total FROM n"
try:
with pytest.raises(TimeoutError, match="deadline"):
asyncio.run(RunSQL().run({"sql": query}, ctx))
# The timed-out progress handler must not leak into the pooled connection.
assert asyncio.run(explorer.execute(query.replace("2000000", "20000"))) == [{"total": 200010000}]
result = asyncio.run(RunSQL().run({"sql": "SELECT 42 AS value"}, ctx))
assert not result.is_error and "42" in result.content
assert "query_timeout_enforced=true" in result.content
assert "query_timeout_scope=sqlite_vm" in result.content
finally:
ctx.store.close()
explorer._get_engine().dispose()


def test_sqlite_deadline_covers_fetch_and_preserves_other_errors(tmp_path):
from sqlalchemy.exc import OperationalError

explorer = SqlAlchemyExplorer(f"sqlite:///{tmp_path / 'fetch.db'}")
query = "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<2000000) SELECT x FROM n"
try:
assert asyncio.run(explorer.execute_with_timeout(query, 1, 0.01)) == [{"x": 1}]
with pytest.raises(TimeoutError, match="deadline"):
asyncio.run(explorer.execute_with_timeout(query, 2000000, 0.01))
with pytest.raises(OperationalError, match="syntax"):
asyncio.run(explorer.execute_with_timeout("SELECT FROM", 1, 1))
assert asyncio.run(explorer.execute(query.replace("2000000", "20000"), 20000))[-1] == {"x": 20000}
finally:
explorer._get_engine().dispose()


def test_legacy_explorer_reports_timeout_not_enforced():
from lang2sql.adapters.db.postgres_explorer import PostgresExplorer
from lang2sql.core.identity import Identity
from lang2sql.tenancy.tool_runtime import build_tool_context
from lang2sql.tools.run_sql import RunSQL

ctx = build_tool_context(Identity(user_id="test"), store_path=":memory:", explorer=PostgresExplorer("stub"))
try:
result = asyncio.run(RunSQL().run({"sql": "SELECT 1"}, ctx))
assert not result.is_error
assert "query_timeout_enforced=false" in result.content
assert "query_timeout_scope=unsupported" in result.content
finally:
ctx.store.close()


# --- D1 explorer with mocked HTTP transport --------------------------------


Expand Down