From 8d19a7fc7d5d8adba750ad7f8938193faeeedb06 Mon Sep 17 00:00:00 2001 From: seyeong Date: Fri, 27 Nov 2026 03:46:15 +0900 Subject: [PATCH] Prevent silent SQL result truncation and duplicate column loss --- .../replay.json | 9 +++ .../adapters/db/sqlalchemy_explorer.py | 7 +++ src/lang2sql/tools/run_sql.py | 34 +++++++---- tests/test_mcp.py | 56 +++++++++++++++++++ 4 files changed, 96 insertions(+), 10 deletions(-) create mode 100644 bench/accuracy/mcp-review-results/deterministic-result-completeness/replay.json diff --git a/bench/accuracy/mcp-review-results/deterministic-result-completeness/replay.json b/bench/accuracy/mcp-review-results/deterministic-result-completeness/replay.json new file mode 100644 index 00000000..ae7a8feb --- /dev/null +++ b/bench/accuracy/mcp-review-results/deterministic-result-completeness/replay.json @@ -0,0 +1,9 @@ +{ + "case": "local003", + "sql_sha256": "71ecb08eae99776dd13365312ee0e37877075c854b7d32b992fa5e0a4069f181", + "transport": "actual MCP stdio, read-only original benchmark database", + "model_calls": 0, + "changed_prompt": false, + "coverage": "Result coverage: fetched_rows=1000; displayed_rows=50; fetch_truncated=true; display_truncated=true; sql_rewritten=false. Counts refer to the executed SQL, not the source table size.", + "score_claim": null +} diff --git a/src/lang2sql/adapters/db/sqlalchemy_explorer.py b/src/lang2sql/adapters/db/sqlalchemy_explorer.py index aebff3d7..cd00edee 100644 --- a/src/lang2sql/adapters/db/sqlalchemy_explorer.py +++ b/src/lang2sql/adapters/db/sqlalchemy_explorer.py @@ -14,6 +14,7 @@ import asyncio import logging +from collections import Counter from typing import Any from ...core.ports.explorer import Column, DataAccessError, ForeignKey, Table @@ -174,5 +175,11 @@ def _execute_sync(self, sql: str, limit: int) -> list[dict]: raise if not result.returns_rows: return [] + duplicates = [name for name, count in Counter(result.keys()).items() if count > 1] + if duplicates: + raise ValueError( + "Duplicate result columns would discard values; use unique column aliases: " + + ", ".join(duplicates) + ) rows = result.mappings().fetchmany(limit) return [dict(r) for r in rows] diff --git a/src/lang2sql/tools/run_sql.py b/src/lang2sql/tools/run_sql.py index 0af773a6..3647e728 100644 --- a/src/lang2sql/tools/run_sql.py +++ b/src/lang2sql/tools/run_sql.py @@ -23,6 +23,7 @@ from ..harness.context import HarnessContext logger = logging.getLogger(__name__) +_DISPLAY_ROW_LIMIT = 50 class RunSQL: @@ -163,7 +164,9 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult: scope = ctx.identity.session_key() logger.info("run_sql started scope=%s actor=%s", scope, ctx.identity.user_id) try: - rows = await ctx.explorer.execute(decision.sql, limit) + # 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) except Exception as exc: logger.warning( "run_sql failed scope=%s error=%s: %s", scope, type(exc).__name__, exc @@ -185,7 +188,9 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult: content="요청한 데이터에 접근할 수 없습니다. 현재 DB 계정에 조회 권한이 없거나 테이블이 존재하지 않습니다. DB 관리자에게 확인해 주세요.", ) raise - logger.info("run_sql completed scope=%s rows=%d", scope, len(rows)) + fetch_truncated = len(rows) > limit + rows = rows[:limit] + logger.info("run_sql completed scope=%s rows=%d fetch_truncated=%s", scope, len(rows), fetch_truncated) if ctx.audit is not None: await ctx.audit.record( @@ -197,26 +202,35 @@ async def run(self, args: dict[str, Any], ctx: HarnessContext) -> ToolResult: ) ) - return ToolResult(call_id="", content=_render_rows(decision.sql, rows)) + return ToolResult(call_id="", content=_render_rows( + decision.sql, rows, fetch_truncated=fetch_truncated, + sql_rewritten=decision.sql != sql, + )) -def _render_rows(sql: str, rows: list[dict]) -> str: +def _render_rows(sql: str, rows: list[dict], *, fetch_truncated=False, sql_rewritten=False) -> 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()}. " + "Counts refer to the executed SQL, not the source table size." + ) if not rows: - return f"(0 rows)\nSQL: {sql}" + return f"(0 rows)\n{coverage}\nSQL: {sql}" headers = list(rows[0].keys()) observed_types = { - h: sorted({type(r.get(h)).__name__ for r in rows[:50]}) for h in headers + h: sorted({type(r.get(h)).__name__ for r in rows[:_DISPLAY_ROW_LIMIT]}) for h in headers } type_note = "Observed value types (displayed rows): " + "; ".join( f"{h}={','.join(kinds)}" for h, kinds in observed_types.items() ) lines = [" | ".join(headers), " | ".join("---" for _ in headers)] - for r in rows[:50]: + for r in rows[:_DISPLAY_ROW_LIMIT]: 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" + f"{len(rows)} row(s):\n{coverage}\n{type_note}\n" + "\n".join(lines) - + suffix + f"\nSQL: {sql}" ) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 5233300a..e5a88618 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -316,3 +316,59 @@ async def test_invalid_fetch_limit_rejected_before_database_access(tmp_path, lim assert RunSQL().spec.parameters["properties"]["limit"]["minimum"] == 1 finally: ctx.store.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("count,limit,truncated", [(3, 2, True), (2, 2, False), (1, 2, False), (0, 2, False), (65, 100, False)]) +async def test_sql_result_reports_fetch_and_display_coverage(tmp_path, count, limit, truncated): + db = fixture_db(tmp_path) + with sqlite3.connect(db) as conn: + conn.execute("DELETE FROM orders") + conn.executemany("INSERT INTO orders VALUES (?)", [(n,) for n in range(count)]) + async with connected(db, tmp_path / "metadata.db") as client: + check = await client.call_tool("resolve_business_terms", {"terms": []}) + result = await client.call_tool("run_sql", { + "sql": "SELECT amount FROM orders ORDER BY amount LIMIT -1", + "limit": limit, + "definition_check_id": json.loads(check.content[0].text)["definition_check_id"], + }) + assert not result.isError + text = result.content[0].text + assert f"fetch_truncated={str(truncated).lower()}" in text + assert f"fetched_rows={min(count, limit)}" in text + assert f"displayed_rows={min(count, limit, 50)}" in text + assert f"display_truncated={str(min(count, limit) > 50).lower()}" in text + assert "rows total" not in text + assert "SQL: SELECT amount FROM orders ORDER BY amount LIMIT -1" in text + if truncated: + assert f"\n{limit}\n" not in text # The lookahead row is not exposed. + + +@pytest.mark.asyncio +async def test_lookahead_does_not_increase_safety_sql_limit(tmp_path): + async with connected(fixture_db(tmp_path), tmp_path / "metadata.db") as client: + check = await client.call_tool("resolve_business_terms", {"terms": []}) + result = await client.call_tool("run_sql", { + "sql": "SELECT amount FROM orders ORDER BY amount", + "limit": 1, + "definition_check_id": json.loads(check.content[0].text)["definition_check_id"], + }) + assert not result.isError + text = result.content[0].text + assert "fetched_rows=1" in text and "sql_rewritten=true" in text + assert "fetch_truncated=false" in text + assert text.endswith("SQL: SELECT amount FROM orders ORDER BY amount\nLIMIT 1") + assert "\n20\n" not in text + + +@pytest.mark.asyncio +async def test_duplicate_result_columns_are_not_silently_overwritten(tmp_path): + async with connected(fixture_db(tmp_path), tmp_path / "metadata.db") as client: + for suffix in ("", " WHERE 0"): + result = await checked_sql(client, "SELECT amount AS value, amount + 1 AS value FROM orders" + suffix) + assert result.isError + assert "unique column aliases" in result.content[0].text + result = await checked_sql(client, "SELECT amount AS original, amount + 1 AS incremented FROM orders") + assert not result.isError + assert "original | incremented" in result.content[0].text + assert "10 | 11" in result.content[0].text