From 9274ff1f7fca3834701e1927f8c412407216f0b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EC=A0=9C=ED=98=95?= <184927314+jhpark324@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:07:50 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=97=AC=EB=9F=AC=20=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=B8=94=EC=9D=98=20=EC=BB=AC=EB=9F=BC=20=EC=A0=95=EB=B3=B4=20?= =?UTF-8?q?=EC=9D=BC=EA=B4=84=20=EC=A1=B0=ED=9A=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lang2sql/adapters/db/d1_explorer.py | 2 + .../adapters/db/sqlalchemy_explorer.py | 15 ++- src/lang2sql/harness/context.py | 3 +- src/lang2sql/harness/loop.py | 4 + src/lang2sql/harness/system_prompt.py | 6 +- src/lang2sql/tools/explore_schema.py | 116 ++++++++++++++---- tests/test_db_adapters.py | 13 ++ tests/test_harness_loop.py | 41 ++++++- tests/test_integration.py | 99 +++++++++++++++ tests/test_mcp.py | 14 +++ 10 files changed, 287 insertions(+), 26 deletions(-) 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/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..63a1dd7e 100644 --- a/src/lang2sql/harness/loop.py +++ b/src/lang2sql/harness/loop.py @@ -8,6 +8,8 @@ from __future__ import annotations +from dataclasses import replace + from ..core.types import Message, Role from .context import HarnessContext from .system_prompt import build_system_prompt @@ -17,6 +19,8 @@ async def agent_loop(ctx: HarnessContext, user_text: str) -> str: """Run one user turn to completion; return the final assistant text.""" 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() diff --git a/src/lang2sql/harness/system_prompt.py b/src/lang2sql/harness/system_prompt.py index b5474f43..a535a61d 100644 --- a/src/lang2sql/harness/system_prompt.py +++ b/src/lang2sql/harness/system_prompt.py @@ -19,6 +19,8 @@ - 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. + For multiple tables, select names from Known tables and request their columns + together with the tables argument. - Prefer definitions from the semantic layer below over your own assumptions. - Answer concisely. Show only the final successful SQL you ran, not intermediate attempts. @@ -32,7 +34,9 @@ async def build_system_prompt(ctx: HarnessContext) -> str: parts: list[str] = [_BASE] 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( diff --git a/src/lang2sql/tools/explore_schema.py b/src/lang2sql/tools/explore_schema.py index 01e46e5e..158037d4 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,117 @@ 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] = [] + 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)) + 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) + + 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)" - ) - return ToolResult(call_id="", content=f"{t.qualified}\n{cols}") + 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)) 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..c7e74e72 100644 --- a/tests/test_harness_loop.py +++ b/tests/test_harness_loop.py @@ -9,13 +9,15 @@ import asyncio +from lang2sql.adapters.db.postgres_explorer import PostgresExplorer from lang2sql.adapters.llm.fake import FakeLLM from lang2sql.core.identity import Identity -from lang2sql.core.types import Role +from lang2sql.core.types import Completion, Role, ToolCall 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.tools.explore_schema import ExploreSchema from lang2sql.tools.ping import Ping @@ -50,6 +52,43 @@ 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()] diff --git a/tests/test_integration.py b/tests/test_integration.py index ca5dcd1d..2fcdcf6b 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,98 @@ 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 not single.is_error + assert batch.is_error + 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 "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.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 + + 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"} )