Skip to content
Merged
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
606 changes: 584 additions & 22 deletions src/lang2sql/adapters/db/sqlalchemy_explorer.py

Large diffs are not rendered by default.

467 changes: 401 additions & 66 deletions src/lang2sql/adapters/storage/sqlite_store.py

Large diffs are not rendered by default.

118 changes: 116 additions & 2 deletions src/lang2sql/core/ports/explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,86 @@
from __future__ import annotations

from dataclasses import dataclass, field
import inspect
from typing import Protocol, runtime_checkable


class DataAccessError(RuntimeError):
"""Requested data is unavailable to this DB identity; do not probe alternatives."""


class QueryRows(list[dict]):
"""List-compatible result with ordered column labels, including empty results."""

def __init__(self, rows, *, columns):
super().__init__(rows)
self.columns = tuple(columns)


class QueryTimedOutError(TimeoutError):
"""The adapter stopped a statement after its verified deadline."""


class QueryTimeoutUnsupportedError(RuntimeError):
"""The adapter cannot prove statement cancellation for this dialect."""


class QueryCancelledError(RuntimeError):
"""Internal worker signal after a caller cancellation interrupted SQL."""


def accepts_statement_timeout(explorer: object) -> bool:
"""Fail closed for legacy adapters that predate the timeout contract."""

execute = getattr(explorer, "execute", None)
if execute is None:
return False
try:
signature = inspect.signature(execute)
except (TypeError, ValueError):
return False
parameter = signature.parameters.get("timeout_seconds")
if parameter is not None and parameter.kind in {
inspect.Parameter.KEYWORD_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
}:
return True
return any(
item.kind == inspect.Parameter.VAR_KEYWORD
for item in signature.parameters.values()
)


def accepts_bound_parameters(explorer: object) -> bool:
"""Return whether the adapter explicitly accepts separated bind values."""

execute = getattr(explorer, "execute", None)
if execute is None:
return False
try:
signature = inspect.signature(execute)
except (TypeError, ValueError):
return False
parameter = signature.parameters.get("parameters")
if parameter is not None and parameter.kind in {
inspect.Parameter.KEYWORD_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
}:
return True
return any(
item.kind == inspect.Parameter.VAR_KEYWORD
for item in signature.parameters.values()
)


def close_explorer(explorer: object) -> None:
"""Release an adapter resource when it exposes a synchronous close seam."""

close = getattr(explorer, "close", None)
if callable(close):
close()


@dataclass
class Column:
name: str
Expand All @@ -19,12 +96,23 @@ class Column:
description: str = "" # may be auto-enriched (v1.5 metadata layer)


@dataclass
class ForeignKey:
columns: list[str]
referred_table: str
referred_columns: list[str]
referred_schema: str = ""


@dataclass
class Table:
name: str
schema: str = "public"
columns: list[Column] = field(default_factory=list)
description: str = ""
kind: str = "table"
primary_key: list[str] = field(default_factory=list)
foreign_keys: list[ForeignKey] = field(default_factory=list)

@property
def qualified(self) -> str:
Expand All @@ -33,7 +121,11 @@ def qualified(self) -> str:

@runtime_checkable
class ExplorerPort(Protocol):
"""Introspect a connected database, read-only."""
"""Introspect a connected database, read-only.

Adapters may expose a non-I/O ``dialect`` string (e.g. ``oracle``) for
prompt and row-limit syntax. Legacy implementations default to LIMIT SQL.
"""

async def list_tables(self) -> list[Table]:
"""Tables visible to the connection (columns may be unpopulated)."""
Expand All @@ -47,8 +139,30 @@ async def sample_rows(self, name: str, limit: int = 5) -> list[dict]:
"""A few rows to give the model a feel for the data."""
...

async def execute(self, sql: str, limit: int = 1000) -> list[dict]:
async def execute(
self,
sql: str,
limit: int = 1000,
*,
timeout_seconds: float = 30.0,
parameters: dict[str, object] | None = None,
) -> list[dict]:
"""Run a read-only query (already cleared by the safety pipeline) and
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]: ...
2 changes: 1 addition & 1 deletion src/lang2sql/core/ports/safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class SafetyDecision:
class SafetyContext:
"""Knobs a layer reads (timeout, row cap). Grows over versions."""

timeout_seconds: int = 30
timeout_seconds: float = 30.0
row_limit: int = 1000
extras: dict = field(default_factory=dict)

Expand Down
5 changes: 5 additions & 0 deletions src/lang2sql/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ class ToolResult:
is_error: bool = False
tables_with_columns: tuple[str, ...] = ()

stop_turn: bool = False


@dataclass
class Message:
Expand All @@ -58,6 +60,9 @@ class Message:
tool_calls: list[ToolCall] = field(default_factory=list)
tool_call_id: str | None = None
name: str | None = None
# Frontends may persist one sanitized clarification for exactly the next
# user turn. It is provider-visible but removed by the next compression.
transient: bool = False


@dataclass
Expand Down
17 changes: 15 additions & 2 deletions src/lang2sql/harness/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
class Session:
identity: Identity
transcript: list[Message] = field(default_factory=list)
source_id: str = ""
connection_generation: int = 0

def add(self, message: Message) -> None:
self.transcript.append(message)
Expand All @@ -27,17 +29,28 @@ def history(self) -> list[Message]:
def reset(self) -> None:
self.transcript.clear()

def compress(self) -> None:
def discard_transient(self) -> bool:
"""Consume frontend-only one-turn context on any real user message."""

original = len(self.transcript)
self.transcript = [
message for message in self.transcript if not message.transient
]
return len(self.transcript) != original

def compress(self, *, preserve_tool_content: bool = True) -> None:
"""Remove tool call/result messages to prevent context pollution across turns."""
from ..core.types import Role

cleaned: list[Message] = []
for msg in self.transcript:
if msg.transient:
continue
if msg.role == Role.TOOL:
continue
if msg.role == Role.ASSISTANT and msg.tool_calls:
if (
msg.content
preserve_tool_content and msg.content
): # skip if no text content — empty assistant messages confuse OpenAI
cleaned.append(Message(role=Role.ASSISTANT, content=msg.content))
else:
Expand Down
8 changes: 7 additions & 1 deletion src/lang2sql/semantic/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Semantic federation layer (★④) — type definitions."""
"""Semantic federation plus the small first-connect query kernel."""

from __future__ import annotations

Expand All @@ -10,6 +10,8 @@
SemanticEntry,
SemanticKind,
)
from .catalog import Aggregate, SemanticCatalog
from .service import QueryOutcome, SemanticService

__all__ = [
"SemanticEntry",
Expand All @@ -18,4 +20,8 @@
"Dimension",
"Relationship",
"Rule",
"Aggregate",
"SemanticCatalog",
"SemanticService",
"QueryOutcome",
]
Loading
Loading