Skip to content
Draft
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
43 changes: 40 additions & 3 deletions src/lang2sql/tools/explore_schema.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
"""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.
arg it lists tables; with one it returns full column detail and a few sample
rows, so stored formats are visible before SQL is written.
"""

from __future__ import annotations

import logging
from dataclasses import replace
from typing import TYPE_CHECKING, Any

from ..core.ports.explorer import Column, Table
from ..core.types import ToolResult, ToolSpec
from .run_sql import render_row_table

if TYPE_CHECKING:
from ..harness.context import HarnessContext

logger = logging.getLogger(__name__)

_KV_PREFIX = "enriched_desc"
# Enough rows to show value formats; long text is cut so wide tables stay small.
_SAMPLE_ROWS = 3
_SAMPLE_VALUE_CHARS = 80


def _apply_enrichment_cache(table: Table, ctx: HarnessContext) -> Table:
Expand All @@ -38,7 +46,7 @@ class ExploreSchema:
def spec(self) -> ToolSpec:
return ToolSpec(
name="explore_schema",
description="List tables and views, or describe one object's columns, primary key and foreign keys. Call before writing SQL.",
description="List tables and views, or describe one object's columns, primary key, foreign keys and a few sample rows. Call before writing SQL.",
parameters={
"type": "object",
"properties": {
Expand Down Expand Up @@ -95,4 +103,33 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult:
+ ")"
)
detail = "\n".join([f"{t.qualified} ({t.kind})", cols, *constraints])
return ToolResult(call_id="", content=detail)
try:
rows = await ctx.explorer.sample_rows(t.name, _SAMPLE_ROWS)
except Exception as exc:
logger.warning(
"explore_schema sample skipped table=%s error=%s: %s",
t.qualified,
type(exc).__name__,
exc,
)
return ToolResult(
call_id="",
content=f"{detail}\nSample rows unavailable ({type(exc).__name__}).",
)
logger.info("explore_schema sampled table=%s rows=%d", t.qualified, len(rows))
if not rows:
return ToolResult(call_id="", content=f"{detail}\nSample rows: (0 rows)")
shown = [
{
k: (
v[:_SAMPLE_VALUE_CHARS] + "…"
if isinstance(v, str) and len(v) > _SAMPLE_VALUE_CHARS
else v
)
for k, v in r.items()
}
for r in rows
]
return ToolResult(
call_id="", content=f"{detail}\nSample rows: {render_row_table(shown)}"
)
12 changes: 6 additions & 6 deletions src/lang2sql/tools/run_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,11 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult:
def _render_rows(sql: str, rows: list[dict]) -> str:
if not rows:
return f"(0 rows)\nSQL: {sql}"
return render_row_table(rows) + f"\nSQL: {sql}"


def render_row_table(rows: list[dict]) -> str:
"""Row count, observed value types and a pipe table of up to 50 rows."""
headers = list(rows[0].keys())
observed_types = {
h: sorted({type(r.get(h)).__name__ for r in rows[:50]}) for h in headers
Expand All @@ -206,9 +211,4 @@ def _render_rows(sql: str, rows: list[dict]) -> str:
for r in rows[:50]:
lines.append(" | ".join(str(r.get(h, "")) for h in headers))
suffix = f"\n… ({len(rows)} rows total)" if len(rows) > 50 else ""
return (
f"{len(rows)} row(s):\n{type_note}\n"
+ "\n".join(lines)
+ suffix
+ f"\nSQL: {sql}"
)
return f"{len(rows)} row(s):\n{type_note}\n" + "\n".join(lines) + suffix
7 changes: 7 additions & 0 deletions tests/test_codex_mcp_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ def test_result_display_keeps_numeric_and_text_distinguishable():
)
assert "numeric=float" in output and "formatted=str" in output
assert "missing=NoneType" in output
assert output == (
"1 row(s):\n"
"Observed value types (displayed rows): "
"numeric=float; formatted=str; missing=NoneType\n"
"numeric | formatted | missing\n--- | --- | ---\n0.9833 | 0.9833 | None\n"
"SQL: SELECT ..."
)


@pytest.mark.parametrize(
Expand Down
75 changes: 75 additions & 0 deletions tests/test_db_adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,78 @@ async def test_composite_keys_reach_schema_tool_without_guessing(tmp_path):
concierge.store.close()
engine.dispose()
exp._engine.dispose()


@pytest.mark.asyncio
async def test_schema_tool_shows_sample_rows_with_long_text_cut(tmp_path):
from sqlalchemy import create_engine, text

from lang2sql.core.identity import Identity
from lang2sql.tenancy.concierge import ContextConcierge
from lang2sql.tools.explore_schema import ExploreSchema

db = tmp_path / "samples.db"
engine = create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(
text("CREATE TABLE trees (tree_id INTEGER, health TEXT, note TEXT)")
)
conn.execute(text("CREATE TABLE empty_t (x INTEGER)"))
for i, health in enumerate(["Good", "Fair", "Good", "Poor"]):
conn.execute(
text("INSERT INTO trees VALUES (:i, :h, :n)"),
{"i": i, "h": health, "n": "x" * 200},
)
exp = SqlAlchemyExplorer(f"sqlite:///{db}")
concierge = ContextConcierge(explorer=exp)
try:
ctx = await concierge.build_context(Identity(user_id="test"))
result = await ExploreSchema().run({"table": "trees"}, ctx)
assert not result.is_error
assert "- health: TEXT" in result.content
assert "Sample rows: 3 row(s):" in result.content
assert "tree_id=int; health=str; note=str" in result.content
assert "0 | Good | " + "x" * 80 + "…" in result.content
assert "x" * 81 not in result.content
assert "Poor" not in result.content # only three rows are sampled
empty = await ExploreSchema().run({"table": "empty_t"}, ctx)
assert empty.content.endswith("Sample rows: (0 rows)")
finally:
concierge.store.close()
engine.dispose()
exp._engine.dispose()


@pytest.mark.asyncio
async def test_schema_tool_keeps_schema_when_sampling_fails(tmp_path, caplog):
import logging

from sqlalchemy import create_engine, text

from lang2sql.core.identity import Identity
from lang2sql.tenancy.concierge import ContextConcierge
from lang2sql.tools.explore_schema import ExploreSchema

db = tmp_path / "fail.db"
engine = create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(text("CREATE TABLE t (id INTEGER PRIMARY KEY)"))
exp = SqlAlchemyExplorer(f"sqlite:///{db}")

async def refuse(name, limit=5):
raise RuntimeError("sample denied")

exp.sample_rows = refuse
concierge = ContextConcierge(explorer=exp)
try:
ctx = await concierge.build_context(Identity(user_id="test"))
with caplog.at_level(logging.WARNING, logger="lang2sql.tools.explore_schema"):
result = await ExploreSchema().run({"table": "t"}, ctx)
assert not result.is_error
assert "PRIMARY KEY (id)" in result.content
assert result.content.endswith("Sample rows unavailable (RuntimeError).")
assert "error=RuntimeError: sample denied" in caplog.text
finally:
concierge.store.close()
engine.dispose()
exp._engine.dispose()