diff --git a/src/lang2sql/adapters/db/d1_explorer.py b/src/lang2sql/adapters/db/d1_explorer.py index a719e9be..b35fd3cf 100644 --- a/src/lang2sql/adapters/db/d1_explorer.py +++ b/src/lang2sql/adapters/db/d1_explorer.py @@ -60,6 +60,8 @@ async def list_tables(self) -> list[Table]: async def describe_table(self, name: str) -> Table: rows = await self._query(f"PRAGMA table_info({_ident(name)})") + if not rows: + raise KeyError(f"unknown table: {name}") cols = [ Column( name=r["name"], type=r["type"] or "", nullable=not bool(r["notnull"]) diff --git a/src/lang2sql/adapters/db/sqlalchemy_explorer.py b/src/lang2sql/adapters/db/sqlalchemy_explorer.py index 11fd3cd8..c4c7ef6a 100644 --- a/src/lang2sql/adapters/db/sqlalchemy_explorer.py +++ b/src/lang2sql/adapters/db/sqlalchemy_explorer.py @@ -71,8 +71,19 @@ def _list_tables_sync(self) -> list[Table]: def _describe_table_sync(self, name: str) -> Table: from sqlalchemy import inspect + from sqlalchemy.exc import NoSuchTableError insp = inspect(self._get_engine()) + schema = self._schema + table_name = name.removeprefix(f"{schema}.") if schema else name + try: + columns = insp.get_columns(table_name, schema=schema) + except NoSuchTableError: + if table_name == name: + raise + # An identifier can also literally start with the schema prefix. + table_name = name + columns = insp.get_columns(table_name, schema=schema) cols = [ Column( name=c["name"], @@ -80,9 +91,9 @@ def _describe_table_sync(self, name: str) -> Table: nullable=bool(c.get("nullable", True)), description=c.get("comment") or "", ) - for c in insp.get_columns(name, schema=self._schema) + for c in columns ] - return Table(name=name, schema=self._schema or "", columns=cols) + return Table(name=table_name, schema=schema or "", columns=cols) def _execute_sync(self, sql: str, limit: int) -> list[dict]: from sqlalchemy import text diff --git a/src/lang2sql/adapters/llm/openai_.py b/src/lang2sql/adapters/llm/openai_.py index e604efe5..a3557786 100644 --- a/src/lang2sql/adapters/llm/openai_.py +++ b/src/lang2sql/adapters/llm/openai_.py @@ -46,6 +46,23 @@ async def complete( self, messages: Sequence[Message], tools: Sequence[ToolSpec] = (), + ) -> Completion: + return await self._complete(messages, tools) + + async def complete_with_required_tool( + self, + messages: Sequence[Message], + tools: Sequence[ToolSpec], + tool_name: str, + ) -> Completion: + return await self._complete(messages, tools, required_tool=tool_name) + + async def _complete( + self, + messages: Sequence[Message], + tools: Sequence[ToolSpec], + *, + required_tool: str | None = None, ) -> Completion: if not self._api_key: raise RuntimeError("OPENAI_API_KEY not set") @@ -56,6 +73,11 @@ async def complete( } if tools: payload["tools"] = [_encode_tool(t) for t in tools] + if required_tool is not None: + payload["tool_choice"] = { + "type": "function", + "function": {"name": required_tool}, + } raw = await asyncio.to_thread(self._post, payload) return _decode_completion(raw) diff --git a/src/lang2sql/core/ports/llm.py b/src/lang2sql/core/ports/llm.py index 66238807..6c415a61 100644 --- a/src/lang2sql/core/ports/llm.py +++ b/src/lang2sql/core/ports/llm.py @@ -23,3 +23,15 @@ async def complete( ) -> Completion: """Run one completion. May return tool calls, a final answer, or both.""" ... + + +@runtime_checkable +class RequiredToolLLMPort(LLMPort, Protocol): + """An LLM adapter that can require a specific tool on one request.""" + + async def complete_with_required_tool( + self, + messages: Sequence[Message], + tools: Sequence[ToolSpec], + tool_name: str, + ) -> Completion: ... diff --git a/src/lang2sql/core/types.py b/src/lang2sql/core/types.py index 4637585d..ef26d8a2 100644 --- a/src/lang2sql/core/types.py +++ b/src/lang2sql/core/types.py @@ -36,11 +36,12 @@ class ToolCall: @dataclass class ToolResult: - """Outcome of running a :class:`ToolCall`, fed back to the model.""" + """Tool response text and the tables whose columns appear in that text.""" call_id: str content: str is_error: bool = False + tables_with_columns: tuple[str, ...] = () @dataclass diff --git a/src/lang2sql/frontends/cli/tools.py b/src/lang2sql/frontends/cli/tools.py index cadfa9c4..f780e4c3 100644 --- a/src/lang2sql/frontends/cli/tools.py +++ b/src/lang2sql/frontends/cli/tools.py @@ -26,7 +26,13 @@ async def execute(ctx, calls): call_id = uuid.uuid4().hex logger.info("cli_tool_start tool=%s call_id=%s", call["name"], call_id) result = await ctx.tools.dispatch(call["name"], call["arguments"], ctx, call_id) - results.append(asdict(result)) + results.append( + { + "call_id": result.call_id, + "content": result.content, + "is_error": result.is_error, + } + ) if result.is_error: logger.warning("cli_tool_failed tool=%s call_id=%s", call["name"], call_id) break diff --git a/src/lang2sql/harness/context.py b/src/lang2sql/harness/context.py index a9fdb8c2..2214045f 100644 --- a/src/lang2sql/harness/context.py +++ b/src/lang2sql/harness/context.py @@ -16,7 +16,7 @@ if TYPE_CHECKING: from ..adapters.storage.sqlite_store import SqliteStore from ..core.ports.audit import AuditPort -from ..core.ports.explorer import ExplorerPort +from ..core.ports.explorer import ExplorerPort, Table from ..core.ports.llm import LLMPort from ..core.ports.safety import SafetyPipelinePort from .session import Session @@ -35,3 +35,4 @@ class HarnessContext: store: SqliteStore | None = None okf_bundle_dir: str | None = None max_turns: int = 8 + known_tables: list[Table] | None = None diff --git a/src/lang2sql/harness/loop.py b/src/lang2sql/harness/loop.py index 4a8e59a0..eb5341fd 100644 --- a/src/lang2sql/harness/loop.py +++ b/src/lang2sql/harness/loop.py @@ -8,34 +8,162 @@ from __future__ import annotations -from ..core.types import Message, Role +from dataclasses import replace +from typing import Callable + +from ..core.ports.llm import RequiredToolLLMPort +from ..core.types import Message, Role, ToolResult, ToolSpec from .context import HarnessContext +from .sql_candidate import is_database_query, sql_from_answer from .system_prompt import build_system_prompt +_SCHEMA_TOOL = "explore_schema" +_SQL_WITHHELD = ( + "SQL withheld because no table columns were provided to the model. " + "Use column information from explore_schema before rewriting the query." +) +_NEEDS_SCHEMA = ( + "Call explore_schema with a non-empty tables list to obtain the missing columns." +) +_REWRITE_SQL = ( + "A previous SQL query was withheld. Use the columns in the schema results to " + "rewrite the query before running it or returning it as the final answer." +) + + +def _recovery_specs(specs: list[ToolSpec], schema: ToolSpec) -> list[ToolSpec]: + tables_parameter = schema.parameters["properties"]["tables"] + schema_for_recovery = replace( + schema, + description="Return the columns for one or more relevant tables.", + parameters={ + "type": "object", + "properties": { + "tables": { + **tables_parameter, + "description": "Names of tables needed to rewrite the query.", + } + }, + "required": ["tables"], + "additionalProperties": False, + }, + ) + return [schema_for_recovery if spec is schema else spec for spec in specs] + -async def agent_loop(ctx: HarnessContext, user_text: str) -> str: - """Run one user turn to completion; return the final assistant text.""" +async def agent_loop( + ctx: HarnessContext, + user_text: str, + *, + extract_final_sql: Callable[[str], str] | None = None, +) -> str: + """Run one user turn. + + Evaluators can supply their final SQL parser to apply the same output + contract before scoring. The parser raises ValueError for other answers. + """ ctx.session.add(Message(role=Role.USER, content=user_text)) + if ctx.explorer is not None: + ctx = replace(ctx, known_tables=await ctx.explorer.list_tables()) system = await build_system_prompt(ctx) specs = ctx.tools.specs() + schema_spec = next((spec for spec in specs if spec.name == _SCHEMA_TOOL), None) + tables_with_columns = system.tables_with_columns + sql_withheld = False + deferred_answer: tuple[int, Message] | None = None + failure: str | None = None for _ in range(ctx.max_turns): - messages = [Message(role=Role.SYSTEM, content=system), *ctx.session.history()] - completion = await ctx.llm.complete(messages, specs) + # Every tool call in this response was authored with the same context. + model_has_columns = bool(tables_with_columns) + needs_recovery = sql_withheld and not model_has_columns + prompt = system.content + if sql_withheld: + prompt += "\n\n" + ( + f"{_SQL_WITHHELD} {_NEEDS_SCHEMA}" if needs_recovery else _REWRITE_SQL + ) + history = ctx.session.history() + if deferred_answer is not None: + # Keep the rejected draft available to the model for schema selection. + index, draft = deferred_answer + history.insert(index, draft) + messages = [Message(role=Role.SYSTEM, content=prompt), *history] + + try: + if needs_recovery: + if schema_spec is None or ctx.explorer is None: + failure = "schema lookup is unavailable" + break + if not isinstance(ctx.llm, RequiredToolLLMPort): + failure = "the model adapter cannot require schema lookup" + break + completion = await ctx.llm.complete_with_required_tool( + messages, _recovery_specs(specs, schema_spec), _SCHEMA_TOOL + ) + else: + completion = await ctx.llm.complete(messages, specs) + except Exception as exc: + if not sql_withheld: + raise + step = "schema lookup" if needs_recovery else "SQL rewrite" + failure = f"model request failed during {step}: {type(exc).__name__}" + break assistant = Message( role=Role.ASSISTANT, - content=completion.content, + content="" if needs_recovery else completion.content, tool_calls=completion.tool_calls, ) - ctx.session.add(assistant) - if not completion.tool_calls: + if needs_recovery: + continue + if not model_has_columns and is_database_query( + sql_from_answer(completion.content, extract_final_sql) + ): + sql_withheld = True + deferred_answer = (len(history), assistant) + continue + if sql_withheld and ( + completion.finish_reason == "length" + or not completion.content.strip() + or ( + extract_final_sql is not None + and sql_from_answer(completion.content, extract_final_sql) is None + ) + ): + continue + ctx.session.add(assistant) return completion.content + ctx.session.add(assistant) for call in completion.tool_calls: - result = await ctx.tools.dispatch(call.name, call.arguments, ctx, call.id) + if needs_recovery and ( + call.name != _SCHEMA_TOOL + or not isinstance(call.arguments, dict) + or call.arguments.keys() != {"tables"} + ): + result = ToolResult( + call_id=call.id, content=_NEEDS_SCHEMA, is_error=True + ) + elif ( + not model_has_columns + and call.name == "run_sql" + and ctx.explorer is not None + and isinstance(call.arguments, dict) + and is_database_query(call.arguments.get("sql")) + ): + sql_withheld = True + # Keep the candidate in the tool call, outside the persisted reply. + assistant.content = "" + result = ToolResult( + call_id=call.id, content=_SQL_WITHHELD, is_error=True + ) + else: + result = await ctx.tools.dispatch( + call.name, call.arguments, ctx, call.id + ) + tables_with_columns.update(result.tables_with_columns) ctx.session.add( Message( role=Role.TOOL, @@ -45,4 +173,14 @@ async def agent_loop(ctx: HarnessContext, user_text: str) -> str: ) ) - return "(reached max turns without a final answer)" + if not sql_withheld: + return "(reached max turns without a final answer)" + if failure is None: + failure = ( + "reached max turns before receiving a rewritten final answer" + if tables_with_columns + else "no table columns obtained before reaching max turns" + ) + answer = f"(SQL withheld: {failure})" + ctx.session.add(Message(role=Role.ASSISTANT, content=answer)) + return answer diff --git a/src/lang2sql/harness/sql_candidate.py b/src/lang2sql/harness/sql_candidate.py new file mode 100644 index 00000000..f5526b62 --- /dev/null +++ b/src/lang2sql/harness/sql_candidate.py @@ -0,0 +1,86 @@ +"""Identify SQL submissions at the harness boundary.""" + +from __future__ import annotations + +import re +from typing import Callable + +_SQL_FENCE = re.compile(r"```sql[ \t]*\r?\n(.*?)```", re.IGNORECASE | re.DOTALL) +_SQL_LABEL = re.compile( + r"^(?:\*\*)?(?:final\s+sql|최종\s*sql|sql)(?:\*\*)?\s*:(?:\*\*)?\s*", + re.IGNORECASE, +) +_SENTENCE_END = re.compile(r"(?:[!?。!?]|(? bool: + """Recognize a table source in a read query without resolving SQL names.""" + if not isinstance(sql, str): + return False + + def mask(match: re.Match[str]) -> str: + token = match[0] + if token.startswith(("--", "/*", "'")): + return " " + return " identifier " + + bare = _COMMENTS_AND_QUOTES.sub(mask, sql).strip() + if not _READ_QUERY.match(bare): + return False + + # SQL expressions such as EXTRACT(... FROM ...) share the FROM keyword. + # A FROM clause belongs to a SELECT at the same parenthesis depth. + depth = 0 + select_depths: set[int] = set() + for token in _QUERY_TOKENS.finditer(bare): + word = token[0].upper() + if word == "(": + depth += 1 + elif word == ")": + select_depths.discard(depth) + depth -= 1 + elif word == "SELECT": + select_depths.add(depth) + elif ( + word == "FROM" + and depth in select_depths + and _TABLE_SOURCE.match(bare, token.end()) + ): + return True + return False + + +def sql_from_answer( + answer: str, extract_final_sql: Callable[[str], str] | None +) -> str | None: + """Extract a candidate from a standalone, optionally labeled SQL answer.""" + if extract_final_sql is not None: + try: + return extract_final_sql(answer) + except ValueError: + return None + + answer = _SQL_LABEL.sub("", answer.strip(), count=1) + if block := _SQL_FENCE.fullmatch(answer): + return block[1].strip() if "```" not in block[1] else None + if "```" in answer or _SENTENCE_END.search(answer): + return None + return answer diff --git a/src/lang2sql/harness/system_prompt.py b/src/lang2sql/harness/system_prompt.py index b5474f43..800c9b6d 100644 --- a/src/lang2sql/harness/system_prompt.py +++ b/src/lang2sql/harness/system_prompt.py @@ -9,6 +9,7 @@ from __future__ import annotations import json +from dataclasses import dataclass from .context import HarnessContext @@ -18,7 +19,9 @@ Rules: - Only ever read data. Never modify the database. - When you need data, call the run_sql tool with a single SELECT/WITH query. -- Discover schema with explore_schema before guessing table or column names. +- Before writing a database query, use explore_schema(tables=[...]) for + relevant tables whose columns are missing from your context. Choose table + names from Known tables. A list of table names does not provide columns. - Prefer definitions from the semantic layer below over your own assumptions. - Answer concisely. Show only the final successful SQL you ran, not intermediate attempts. @@ -28,11 +31,20 @@ """ -async def build_system_prompt(ctx: HarnessContext) -> str: +@dataclass +class SystemPrompt: + content: str + tables_with_columns: set[str] + + +async def build_system_prompt(ctx: HarnessContext) -> SystemPrompt: parts: list[str] = [_BASE] + tables_with_columns: set[str] = set() if ctx.explorer is not None: - tables = await ctx.explorer.list_tables() + tables = ctx.known_tables + if tables is None: + tables = await ctx.explorer.list_tables() if tables: scope = ctx.identity.kv_scope if ctx.store else None has_enrichment = bool( @@ -43,7 +55,7 @@ async def build_system_prompt(ctx: HarnessContext) -> str: schema_lines: list[str] = [] for tbl in tables: try: - described = await ctx.explorer.describe_table(tbl.name) + described = await ctx.explorer.describe_table(tbl.qualified) except Exception: schema_lines.append(f"- {tbl.qualified}") continue @@ -58,6 +70,8 @@ async def build_system_prompt(ctx: HarnessContext) -> str: ) col_lines.append(f" - {col.name}{': ' + desc if desc else ''}") schema_lines.append(f"- {tbl.qualified}\n" + "\n".join(col_lines)) + if col_lines: + tables_with_columns.add(tbl.qualified) parts.append( "## Known tables (with column descriptions)\n" + "\n".join(schema_lines) @@ -88,4 +102,4 @@ async def build_system_prompt(ctx: HarnessContext) -> str: if semfed_section: parts.append(semfed_section) - return "\n\n".join(parts) + return SystemPrompt("\n\n".join(parts), tables_with_columns) diff --git a/src/lang2sql/tools/explore_schema.py b/src/lang2sql/tools/explore_schema.py index 01e46e5e..3a8041bd 100644 --- a/src/lang2sql/tools/explore_schema.py +++ b/src/lang2sql/tools/explore_schema.py @@ -1,7 +1,7 @@ """explore_schema — let the agent discover tables/columns before writing SQL. -Read-only introspection through the :class:`ExplorerPort`. With no ``table`` -arg it lists tables; with one it returns full column detail. +Read-only introspection through the :class:`ExplorerPort`. List available +tables, or describe the columns of one or more selected tables. """ from __future__ import annotations @@ -9,7 +9,7 @@ from dataclasses import replace from typing import TYPE_CHECKING, Any -from ..core.ports.explorer import Column, Table +from ..core.ports.explorer import Column, ExplorerPort, Table from ..core.types import ToolResult, ToolSpec if TYPE_CHECKING: @@ -33,43 +33,129 @@ def _apply_enrichment_cache(table: Table, ctx: "HarnessContext") -> Table: return replace(table, columns=enriched_cols) +def _format_columns(table: Table, ctx: "HarnessContext") -> str: + table = _apply_enrichment_cache(table, ctx) + cols = ( + "\n".join( + f"- {c.name}: {c.type}{'' if c.nullable else ' NOT NULL'}" + f"{(' — ' + c.description) if c.description else ''}" + for c in table.columns + ) + or "(no columns)" + ) + return f"{table.qualified}\n{cols}" + + +async def _list_tables(explorer: ExplorerPort, ctx: "HarnessContext") -> list[Table]: + if ctx.known_tables is not None: + return ctx.known_tables + return await explorer.list_tables() + + +async def _describe_tables( + names: list[str], explorer: ExplorerPort, ctx: "HarnessContext" +) -> ToolResult: + catalog = await _list_tables(explorer, ctx) + qualified_names = {table.qualified: table for table in catalog} + bare_names: dict[str, Table | None] = {} + for candidate in catalog: + bare_names[candidate.name] = ( + candidate if candidate.name not in bare_names else None + ) + + sections: list[str] = [] + tables_with_columns: list[str] = [] + seen: set[str] = set() + has_error = False + for name in dict.fromkeys(name.strip() for name in names): + table = qualified_names.get(name) or bare_names.get(name) + if table is None and name in bare_names: + sections.append(f"{name}: ambiguous table. Include its schema name.") + has_error = True + continue + + if name in seen or (table is not None and table.qualified in seen): + continue + try: + described = await explorer.describe_table(name) + if described.qualified not in seen: + sections.append(_format_columns(described, ctx)) + if described.columns: + tables_with_columns.append(described.qualified) + seen.update((name, described.qualified)) + except Exception as exc: + sections.append(f"{name}: {type(exc).__name__}: {exc}") + has_error = True + return ToolResult( + call_id="", + content="\n\n".join(sections), + is_error=has_error, + tables_with_columns=tuple(tables_with_columns), + ) + + class ExploreSchema: @property def spec(self) -> ToolSpec: return ToolSpec( name="explore_schema", - description="List tables, or describe one table's columns. Call before writing SQL.", + description=( + "List tables or describe their columns before writing SQL. " + "Request multiple relevant tables together with 'tables'." + ), parameters={ "type": "object", "properties": { "table": { "type": "string", - "description": "table name to describe; omit to list all tables", + "description": "one table name; use either 'table' or 'tables'", + }, + "tables": { + "type": "array", + "items": {"type": "string", "minLength": 1}, + "minItems": 1, + "description": ( + "names of relevant tables; omit both arguments to list tables" + ), }, }, }, ) async def run(self, args: dict[str, Any], ctx: "HarnessContext") -> ToolResult: - if ctx.explorer is None: + explorer = ctx.explorer + if explorer is None: return ToolResult( call_id="", content="no DB connected (use /connect)", is_error=True ) + if "tables" in args: + if "table" in args: + return ToolResult( + call_id="", content="Use either 'table' or 'tables'.", is_error=True + ) + names = args["tables"] + if ( + not isinstance(names, list) + or not names + or any(not isinstance(name, str) or not name.strip() for name in names) + ): + return ToolResult( + call_id="", + content="'tables' must be a non-empty list of table names.", + is_error=True, + ) + return await _describe_tables(names, explorer, ctx) + table = (args.get("table") or "").strip() if not table: - tables = await ctx.explorer.list_tables() - names = "\n".join(f"- {t.qualified}" for t in tables) or "(no tables)" - return ToolResult(call_id="", content="Tables:\n" + names) - - t = await ctx.explorer.describe_table(table) - t = _apply_enrichment_cache(t, ctx) - cols = ( - "\n".join( - f"- {c.name}: {c.type}{'' if c.nullable else ' NOT NULL'}" - f"{(' — ' + c.description) if c.description else ''}" - for c in t.columns - ) - or "(no columns)" + tables = await _list_tables(explorer, ctx) + listed = "\n".join(f"- {t.qualified}" for t in tables) or "(no tables)" + return ToolResult(call_id="", content="Tables:\n" + listed) + + described = await explorer.describe_table(table) + return ToolResult( + call_id="", + content=_format_columns(described, ctx), + tables_with_columns=(described.qualified,) if described.columns else (), ) - return ToolResult(call_id="", content=f"{t.qualified}\n{cols}") diff --git a/tests/test_adapters.py b/tests/test_adapters.py index 4fa48d79..80c2373d 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -1,8 +1,4 @@ -"""Adapter tests — SqliteStore round trips, OpenAILLM offline behaviour, stub. - -No network: OpenAI is only checked for construction + the no-key RuntimeError. -Async port methods are driven with ``asyncio.run``. -""" +"""Offline tests for SqliteStore, OpenAILLM, and the PostgreSQL stub.""" from __future__ import annotations @@ -15,7 +11,7 @@ from lang2sql.core.identity import Identity from lang2sql.core.ports.audit import AuditEvent from lang2sql.core.ports.explorer import ExplorerPort -from lang2sql.core.types import Message, Role, ToolCall +from lang2sql.core.types import Message, Role, ToolCall, ToolSpec from lang2sql.harness.session import Session @@ -150,3 +146,31 @@ def test_openai_complete_without_key_raises() -> None: finally: if saved is not None: os.environ["OPENAI_API_KEY"] = saved + + +def test_openai_requires_a_tool_on_one_request(monkeypatch) -> None: + requests = [] + + def post(payload): + requests.append(payload) + return {"choices": [{"message": {"content": "ok"}}]} + + llm = OpenAILLM(api_key="test") + monkeypatch.setattr(llm, "_post", post) + messages = [Message(role=Role.USER, content="Show order amounts")] + tools = [ToolSpec(name="explore_schema", description="Show table columns")] + + async def complete(): + await llm.complete(messages, tools) + await llm.complete_with_required_tool(messages, tools, "explore_schema") + await llm.complete(messages) + + asyncio.run(complete()) + ordinary, forced, auxiliary = requests + assert "tool_choice" not in ordinary + assert ordinary["tools"] == forced["tools"] + assert forced["tool_choice"] == { + "type": "function", + "function": {"name": "explore_schema"}, + } + assert "tool_choice" not in auxiliary and "tools" not in auxiliary diff --git a/tests/test_db_adapters.py b/tests/test_db_adapters.py index ab09f300..82bb24bf 100644 --- a/tests/test_db_adapters.py +++ b/tests/test_db_adapters.py @@ -95,6 +95,19 @@ def test_sqlalchemy_explorer_introspect_and_execute(tmp_path): assert len(sample) == 1 +def test_sqlalchemy_explorer_describes_names_in_its_configured_schema(tmp_path): + db = tmp_path / "demo.db" + _seed_sqlite(str(db)) + exp = SqlAlchemyExplorer(f"sqlite:///{db}", schema="main") + + qualified = asyncio.run(exp.describe_table("main.users")) + bare = asyncio.run(exp.describe_table("users")) + + assert qualified == bare + assert qualified.qualified == "main.users" + assert [column.name for column in qualified.columns] == ["id", "email"] + + # --- D1 explorer with mocked HTTP transport -------------------------------- diff --git a/tests/test_harness_loop.py b/tests/test_harness_loop.py index 5272d04f..d9ecd75e 100644 --- a/tests/test_harness_loop.py +++ b/tests/test_harness_loop.py @@ -1,21 +1,27 @@ -"""Week-1 smoke test: the agent loop completes a full tool cycle. - -Locks in the walking-skeleton contract — user turn → tool call → tool result → -final answer — so later refactors of loop/registry/context don't silently break -the dispatch path. -""" +"""Agent loop and natural-language frontend regression tests.""" from __future__ import annotations import asyncio +import json +import re + +import pytest +from lang2sql.adapters.db.postgres_explorer import PostgresExplorer from lang2sql.adapters.llm.fake import FakeLLM +from lang2sql.adapters.llm.openai_ import OpenAILLM from lang2sql.core.identity import Identity -from lang2sql.core.types import Role +from lang2sql.core.ports.explorer import Table +from lang2sql.core.types import Completion, Role, ToolCall +from lang2sql.frontends.cli import app +from lang2sql.frontends.discord.commands import CommandHandlers from lang2sql.harness.context import HarnessContext from lang2sql.harness.loop import agent_loop from lang2sql.harness.session import Session from lang2sql.harness.tool_registry import ToolRegistry +from lang2sql.tenancy.concierge import ContextConcierge +from lang2sql.tools.explore_schema import ExploreSchema from lang2sql.tools.ping import Ping @@ -50,7 +56,444 @@ def test_tool_call_id_is_stamped(): assert tool_msgs and tool_msgs[0].tool_call_id +def test_schema_batch_uses_the_catalog_from_the_system_prompt(): + class CountingExplorer(PostgresExplorer): + catalog_reads = 0 + + async def list_tables(self): + self.catalog_reads += 1 + return await super().list_tables() + + class SchemaLLM: + async def complete(self, messages, tools=()): + if messages[-1].role == Role.TOOL: + assert "- amount: numeric" in messages[-1].content + assert "- email: text" in messages[-1].content + return Completion(content="Found both tables.") + assert "## Known tables\npublic.orders, public.users" in messages[0].content + return Completion( + tool_calls=[ + ToolCall( + id="schema", + name="explore_schema", + arguments={"tables": ["public.orders", "public.users"]}, + ) + ] + ) + + ctx = _ctx() + explorer = CountingExplorer("postgresql://ignored") + ctx.explorer = explorer + ctx.llm = SchemaLLM() + ctx.tools = ToolRegistry([ExploreSchema()]) + + assert asyncio.run(agent_loop(ctx, "Show the schema for orders and users.")) == ( + "Found both tables." + ) + assert explorer.catalog_reads == 1 + + def test_scope_chain_orders_narrow_to_wide(): ident = Identity(user_id="u", guild_id="g", channel_id="c", thread_id="t") levels = [s.level.value for s in ident.scope_chain()] assert levels == ["thread", "team", "org", "builtin"] + + +class RecordingExplorer(PostgresExplorer): + def __init__(self): + super().__init__("postgresql://ignored") + self.described = [] + self.executed = [] + + async def describe_table(self, name): + self.described.append(name) + return await super().describe_table(name) + + async def execute(self, sql, limit=1000): + self.executed.append(sql) + return await super().execute(sql, limit) + + +class ScriptedOpenAI(OpenAILLM): + """Record the actual API payload without sending requests.""" + + def __init__(self, *replies): + super().__init__(api_key="test") + self.requests = [] + self.replies = replies + + def _post(self, payload): + self.requests.append(payload) + assert len(self.requests) <= len(self.replies), "Unexpected model request" + content, calls = self.replies[len(self.requests) - 1] + return { + "choices": [ + { + "message": { + "content": content, + "tool_calls": [ + { + "id": call_id, + "function": { + "name": name, + "arguments": json.dumps(args), + }, + } + for call_id, name, args in calls + ], + } + } + ] + } + + +def _calls(*calls): + return "", calls + + +def _answer(text): + return text, () + + +_FORCED = {"type": "function", "function": {"name": "explore_schema"}} +_SQL = "SELECT amount FROM orders" +_STALE_SQL = "SELECT guessed_amount FROM orders" +_EXECUTE = ("sql", "run_sql", {"sql": _STALE_SQL}) +_SCHEMA = ("columns", "explore_schema", {"tables": ["public.orders"]}) + + +def _context_for(llm, *, max_turns=8): + concierge = ContextConcierge( + llm=llm, explorer=RecordingExplorer(), max_turns=max_turns + ) + return asyncio.run(concierge.build_context(Identity(user_id="analyst"))) + + +def _choices(llm): + return [request.get("tool_choice") for request in llm.requests] + + +def _tool_results(request): + return { + message["tool_call_id"]: message["content"] + for message in request["messages"] + if message["role"] == "tool" + } + + +def test_run_sql_waits_for_columns_before_executing(): + llm = ScriptedOpenAI( + _calls(_EXECUTE), + _calls(_SCHEMA), + _calls(("rewritten", "run_sql", {"sql": _SQL})), + _answer("Order totals are available."), + ) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Show order amounts")) == ( + "Order totals are available." + ) + assert _choices(llm) == [None, _FORCED, None, None] + assert "SQL withheld" in _tool_results(llm.requests[1])["sql"] + assert "- amount: numeric" in _tool_results(llm.requests[2])["columns"] + assert len(ctx.explorer.executed) == 1 + assert _SQL in ctx.explorer.executed[0] + assert "guessed_amount" not in ctx.explorer.executed[0] + + +@pytest.mark.parametrize( + "output", ["{sql}", "```sql\n{sql}\n```", "**최종 SQL:**\n```sql\n{sql}\n```"] +) +def test_final_sql_is_withheld_until_the_model_has_columns(output): + draft = output.format(sql=_STALE_SQL) + revised = output.format(sql=_SQL) + llm = ScriptedOpenAI( + _answer(draft), + _calls(_SCHEMA), + _answer(revised), + ) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Write the order amounts query")) == revised + assert _choices(llm) == [None, _FORCED, None] + assert llm.requests[1]["messages"][-1] == {"role": "assistant", "content": draft} + assert not any(_STALE_SQL in message.content for message in ctx.session.history()) + schema = [ + tool["function"]["parameters"] + for request in llm.requests + for tool in request["tools"] + if tool["function"]["name"] == "explore_schema" + ] + original, recovery, restored = schema + assert "required" not in original and "table" in original["properties"] + assert recovery["required"] == ["tables"] + assert recovery["properties"]["tables"]["minItems"] == 1 + assert "table" not in recovery["properties"] + assert original == restored + + +def test_evaluator_uses_its_sql_output_contract(): + def extract_sql(answer): + blocks = re.findall(r"```sql\s*(.*?)```", answer, re.I | re.S) + if len(blocks) != 1: + raise ValueError("Expected one SQL block") + return blocks[0].strip() + + initial = f"Final query:\n```sql\n{_STALE_SQL}\n```" + revised = f"Final query:\n```sql\n{_SQL}\n```" + llm = ScriptedOpenAI( + _answer(initial), + _calls(_SCHEMA), + _answer("The orders table is available."), + _answer(revised), + ) + ctx = _context_for(llm) + + assert ( + asyncio.run(agent_loop(ctx, "Write SQL", extract_final_sql=extract_sql)) + == revised + ) + assert _choices(llm) == [None, _FORCED, None, None] + assert not any( + message.content == "The orders table is available." + for message in ctx.session.history() + ) + + +@pytest.mark.parametrize("schema_first", [True, False]) +def test_schema_and_sql_in_the_same_response_use_the_same_model_context(schema_first): + batch = [_SCHEMA, _EXECUTE] if schema_first else [_EXECUTE, _SCHEMA] + llm = ScriptedOpenAI((_STALE_SQL, batch), _answer(_SQL)) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL + assert _choices(llm) == [None, None] + assert ctx.explorer.executed == [] + results = _tool_results(llm.requests[1]) + assert list(results) == [call[0] for call in batch] + assert "- amount: numeric" in results["columns"] + assert "SQL withheld" in results["sql"] + ctx.session.compress() + assert [message.content for message in ctx.session.history()] == [ + "Show order amounts", + _SQL, + ] + + +def test_recovery_rejects_list_only_legacy_and_empty_calls_and_uses_partial_success(): + llm = ScriptedOpenAI( + _calls(("list", "explore_schema", {})), + _answer(_STALE_SQL), + _calls(("recovery-list", "explore_schema", {})), + _calls(("legacy", "explore_schema", {"table": "orders"})), + _calls(("empty", "explore_schema", {"tables": []})), + _calls(("failed", "explore_schema", {"tables": ["missing"]})), + _calls(("partial", "explore_schema", {"tables": ["missing", "public.orders"]})), + _answer(_SQL), + ) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL + assert _choices(llm) == [None, None, *([_FORCED] * 5), None] + list_result, draft = llm.requests[2]["messages"][-2:] + assert list_result["tool_call_id"] == "list" + assert draft == {"role": "assistant", "content": _STALE_SQL} + results = _tool_results(llm.requests[-1]) + assert results["list"] == "Tables:\n- public.orders\n- public.users" + assert all( + "non-empty" in results[key] for key in ("recovery-list", "legacy", "empty") + ) + assert "unknown table: missing" in results["failed"] + assert "unknown table: missing" in results["partial"] + assert "- amount: numeric" in results["partial"] + assert ctx.explorer.described == ["missing", "missing", "public.orders"] + + +@pytest.mark.parametrize( + ("tables", "reason"), + [ + (["missing"], "no table columns obtained"), + (["orders"], "rewritten final answer"), + ], +) +def test_recovery_respects_existing_turn_budget(tables, reason): + llm = ScriptedOpenAI( + _answer(_STALE_SQL), _calls(("retry", "explore_schema", {"tables": tables})) + ) + ctx = _context_for(llm, max_turns=2) + answer = asyncio.run(agent_loop(ctx, "Show order amounts")) + + assert reason in answer + assert _STALE_SQL not in answer + assert _choices(llm) == [None, _FORCED] + assert ctx.session.history()[-1].content == answer + + +def test_legacy_adapter_returns_reason_when_required_tool_choice_is_unavailable(): + class LegacyLLM: + async def complete(self, messages, tools=()): + assert messages[-1].role == Role.USER + return Completion(content=_STALE_SQL) + + ctx = _context_for(LegacyLLM()) + answer = asyncio.run(agent_loop(ctx, "Show order amounts")) + + assert "model adapter cannot require schema lookup" in answer + assert ctx.session.history()[-1].content == answer + + +@pytest.mark.parametrize( + "sql", + [ + "SELECT (SELECT amount FROM orders)", + "/* order totals */ WITH amounts AS NOT MATERIALIZED " + '(SELECT amount FROM "orders") SELECT * FROM amounts', + ], +) +def test_nested_table_sources_trigger_recovery(sql): + llm = ScriptedOpenAI( + _calls(("draft", "run_sql", {"sql": sql})), _calls(_SCHEMA), _answer(_SQL) + ) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL + assert _choices(llm) == [None, _FORCED, None] + assert ctx.explorer.executed == [] + + +def test_schema_response_without_columns_requires_recovery(): + class EmptyTableExplorer(RecordingExplorer): + async def describe_table(self, name): + if name == "empty": + return Table(name="empty") + return await super().describe_table(name) + + llm = ScriptedOpenAI( + _calls(("empty", "explore_schema", {"table": "empty"})), + _answer(_STALE_SQL), + _calls(_SCHEMA), + _answer(_SQL), + ) + ctx = _context_for(llm) + ctx.explorer = EmptyTableExplorer() + + assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL + assert "(no columns)" in _tool_results(llm.requests[1])["empty"] + assert _choices(llm) == [None, None, _FORCED, None] + + +def test_prompt_with_actual_columns_allows_sql_on_the_first_call(): + llm = ScriptedOpenAI(_calls(("sql", "run_sql", {"sql": _SQL})), _answer(_SQL)) + ctx = _context_for(llm) + ctx.store.kv_set(ctx.identity.kv_scope, "schema_relationships", '["orders"]') + + assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL + assert _choices(llm) == [None, None] + assert "- amount" in llm.requests[0]["messages"][0]["content"] + assert len(ctx.explorer.executed) == 1 + + +def test_column_results_are_scoped_to_the_current_user_turn(): + llm = ScriptedOpenAI( + _calls(_SCHEMA), + _answer(_SQL), + _answer(_STALE_SQL), + _calls(("next-turn-columns", "explore_schema", {"tables": ["orders"]})), + _answer(_SQL), + ) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL + assert asyncio.run(agent_loop(ctx, "Show order amounts again")) == _SQL + assert _choices(llm) == [None, None, None, _FORCED, None] + + +@pytest.mark.parametrize( + "answer", + [ + "Hello. How can I help?", + "Which definition of revenue should I use?", + f"For example, you can write:\n```sql\n{_SQL}\n```", + "Select a date from the list.", + "SELECT 'FROM orders' AS example", + "SELECT EXTRACT(YEAR FROM CURRENT_DATE)", + "SELECT 42 IS DISTINCT FROM 7", + "SELECT * FROM (SELECT 42 AS amount)", + ], +) +def test_general_answers_remain_automatic(answer): + llm = ScriptedOpenAI(_answer(answer)) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Help me understand my options")) == answer + assert _choices(llm) == [None] + + +def test_run_sql_allows_queries_without_table_sources(): + sql = "SELECT EXTRACT(YEAR FROM CURRENT_DATE)" + llm = ScriptedOpenAI( + _calls(("current-year", "run_sql", {"sql": sql})), _answer("Current year.") + ) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Read the current year")) == "Current year." + assert _choices(llm) == [None, None] + assert len(ctx.explorer.executed) == 1 + assert sql in ctx.explorer.executed[0] + + +def test_term_custom_and_enrich_keep_their_existing_calls(): + llm = ScriptedOpenAI( + _calls( + ( + "term", + "term_custom", + { + "term": "net revenue", + "definition": "Exclude refunds", + "layer": "user", + }, + ), + ("enrich", "enrich_schema", {}), + ), + _answer('{"columns": {"orders.amount": "Order total"}, "relationships": []}'), + _answer("Saved the definition."), + ) + ctx = _context_for(llm) + + assert asyncio.run(agent_loop(ctx, "Save net revenue and enrich the schema.")) == ( + "Saved the definition." + ) + assert _choices(llm) == [None, None, None] + assert "tools" not in llm.requests[1] + assert "Exclude refunds" in _tool_results(llm.requests[2])["term"] + assert "orders.amount: Order total" in _tool_results(llm.requests[2])["enrich"] + + +def test_cli_and_discord_natural_language_use_schema_recovery(monkeypatch, capsys): + cli_model = ScriptedOpenAI(_answer(_STALE_SQL), _calls(_SCHEMA), _answer(_SQL)) + cli_concierge = ContextConcierge(llm=cli_model, explorer=RecordingExplorer()) + monkeypatch.setattr(app, "ContextConcierge", lambda: cli_concierge) + assert app.main(["Show", "order", "amounts"]) == 0 + assert capsys.readouterr().out == f"{_SQL}\n" + assert _choices(cli_model) == [None, _FORCED, None] + assert cli_model.requests[0]["messages"][-1]["content"] == "Show order amounts" + + discord_model = ScriptedOpenAI(_answer(_STALE_SQL), _calls(_SCHEMA), _answer(_SQL)) + concierge = ContextConcierge(llm=discord_model, explorer=RecordingExplorer()) + identity = Identity(user_id="tester", guild_id="shop", channel_id="analytics") + + async def run_discord(): + response = await CommandHandlers(concierge).query( + identity, "Show order amounts" + ) + session = await concierge.store.load(identity.session_key()) + return response, session + + response, session = asyncio.run(run_discord()) + assert response.text == _SQL + assert _choices(discord_model) == [None, _FORCED, None] + assert [message.content for message in session.history()] == [ + "Show order amounts", + _SQL, + ] diff --git a/tests/test_integration.py b/tests/test_integration.py index ca5dcd1d..3ce8bc5e 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -9,8 +9,15 @@ from __future__ import annotations import asyncio +import sqlite3 +from contextlib import closing +import pytest + +from lang2sql.adapters.db.d1_explorer import D1Explorer +from lang2sql.adapters.db.postgres_explorer import PostgresExplorer from lang2sql.core.identity import Identity +from lang2sql.core.ports.explorer import Column, Table from lang2sql.core.ports.safety import SafetyContext, Verdict from lang2sql.tenancy.concierge import ContextConcierge from lang2sql.tools.run_sql import RunSQL @@ -58,6 +65,104 @@ def test_run_sql_tolerates_bad_limit(): assert not res.is_error # malformed limit must not crash the tool +def test_explore_schema_batch_preserves_column_details_and_partial_results(): + _, ctx = _ctx() + + async def explore(args): + return await ctx.tools.dispatch("explore_schema", args, ctx, "schema") + + listed = asyncio.run(explore({})) + single = asyncio.run(explore({"table": "orders"})) + batch = asyncio.run( + explore({"tables": ["public.orders", "missing", "orders", " users "]}) + ) + assert listed.content == "Tables:\n- public.orders\n- public.users" + assert listed.tables_with_columns == () + assert not single.is_error + assert single.tables_with_columns == ("public.orders",) + assert batch.is_error + assert batch.tables_with_columns == ("public.orders", "public.users") + assert batch.content.startswith(single.content + "\n\n") + assert batch.content.count("public.orders\n") == 1 + assert "missing: KeyError: 'unknown table: missing'" in batch.content + assert "public.users\n" in batch.content + + +def test_explore_schema_d1_batch_reports_missing_table_and_preserves_columns(): + _, ctx = _ctx() + with closing(sqlite3.connect(":memory:", check_same_thread=False)) as conn: + conn.execute("CREATE TABLE orders (amount INTEGER NOT NULL)") + conn.row_factory = sqlite3.Row + + def transport(sql, params): + rows = [dict(row) for row in conn.execute(sql, params)] + return {"success": True, "result": [{"results": rows}]} + + ctx.explorer = D1Explorer("acct", "db", transport=transport) + result = asyncio.run( + ctx.tools.dispatch( + "explore_schema", {"tables": ["missing", "orders"]}, ctx, "schema" + ) + ) + + assert result.is_error + assert result.tables_with_columns == ("orders",) + assert "missing: KeyError: 'unknown table: missing'" in result.content + assert "orders\n- amount: INTEGER NOT NULL" in result.content + + +def test_explore_schema_batch_preserves_qualified_names_and_rejects_ambiguity(): + class MultiSchemaExplorer(PostgresExplorer): + tables = { + "sales.orders": Table("orders", "sales", [Column("sold_at", "date")]), + "archive.orders": Table( + "orders", "archive", [Column("archived_at", "date")] + ), + } + + async def list_tables(self): + return list(self.tables.values()) + + async def describe_table(self, name): + return self.tables["sales.orders" if name == "orders" else name] + + _, ctx = _ctx() + ctx.explorer = MultiSchemaExplorer("postgresql://ignored") + + result = asyncio.run( + ctx.tools.dispatch( + "explore_schema", + {"tables": ["sales.orders", "orders", "archive.orders"]}, + ctx, + "schema", + ) + ) + + assert result.is_error + assert result.tables_with_columns == ("sales.orders", "archive.orders") + assert result.content.split("\n\n") == [ + "sales.orders\n- sold_at: date", + "orders: ambiguous table. Include its schema name.", + "archive.orders\n- archived_at: date", + ] + + +@pytest.mark.parametrize( + "args", + [ + {"tables": []}, + {"tables": "orders"}, + {"tables": ["orders", " "]}, + {"tables": ["orders"], "table": "users"}, + ], +) +def test_explore_schema_rejects_invalid_batch_input(args): + _, ctx = _ctx() + result = asyncio.run(ctx.tools.dispatch("explore_schema", args, ctx, "schema")) + assert result.is_error + assert result.tables_with_columns == () + + def test_term_custom_is_scope_local(): from lang2sql.tools.semantic_federation import _render_effective diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 4819e412..0454f324 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -55,6 +55,9 @@ def fixture_db(tmp_path): @pytest.mark.asyncio async def test_stdio_schema_sql_memory_and_errors(tmp_path): db = fixture_db(tmp_path) + with sqlite3.connect(db) as conn: + conn.execute("CREATE TABLE customers (email TEXT NOT NULL)") + conn.execute("CREATE VIEW paid_orders AS SELECT amount FROM orders") async with connected(db, tmp_path / "metadata.db") as client: tools = (await client.list_tools()).tools assert {t.name for t in tools} == { @@ -66,6 +69,17 @@ async def test_stdio_schema_sql_memory_and_errors(tmp_path): } schema = await client.call_tool("explore_schema", {}) assert not schema.isError and "orders" in schema.content[0].text + assert "paid_orders" not in schema.content[0].text + view = await client.call_tool("explore_schema", {"table": "paid_orders"}) + assert not view.isError + assert "paid_orders\n- amount: INTEGER" in view.content[0].text + columns = await client.call_tool( + "explore_schema", {"tables": ["ORDERS", "customers", "paid_orders"]} + ) + assert not columns.isError + assert "ORDERS\n- amount: INTEGER" in columns.content[0].text + assert "customers\n- email: TEXT NOT NULL" in columns.content[0].text + assert view.content[0].text in columns.content[0].text result = await client.call_tool( "run_sql", {"sql": "SELECT SUM(amount) AS total FROM orders"} ) diff --git a/tests/test_tools_cli.py b/tests/test_tools_cli.py index 02a780c7..d334b0df 100644 --- a/tests/test_tools_cli.py +++ b/tests/test_tools_cli.py @@ -44,9 +44,23 @@ def test_catalog_and_real_sql(tmp_path): assert status == 0 assert "run_sql" in {tool["name"] for tool in result["tools"]} status, result = invoke( - tmp_path, "call", "run_sql", "--args", '{"sql":"SELECT 42 AS answer"}' + tmp_path, + "call", + "run_sql", + "--args", + '{"sql":"SELECT COUNT(*) AS answer FROM orders"}', ) - assert status == 0 and "42" in result["content"] + assert status == 0 and "answer\n---\n0" in result["content"] + + +def test_explore_schema_preserves_its_public_result_shape(tmp_path): + status, result = invoke( + tmp_path, "call", "explore_schema", "--args", '{"tables":["orders"]}' + ) + assert status == 0 + assert set(result) == {"call_id", "content", "is_error"} + assert not result["is_error"] + assert result["content"] == "orders\n- amount: INTEGER" @pytest.mark.parametrize(