diff --git a/bench/accuracy/README.md b/bench/accuracy/README.md index 462d4688..f19e7c61 100644 --- a/bench/accuracy/README.md +++ b/bench/accuracy/README.md @@ -206,3 +206,12 @@ It contains question/schema/documentation and any explicitly requested prior observations; no environment variables or authentication configuration are added. Historical runs without these artifacts are not retroactively reconstructed as captured inputs. This improves auditability, not measured benchmark accuracy. + +Final SQL provenance is bound to the server's `SQL:` execution footer. If the +final answer names a submitted query that the safety gate rewrote, the exported +prediction uses the executed rewrite (for example, its actual LIMIT), not the +unbounded input. Formatting-only aliases are checked using SQLite bytecode; +changed literals are not accepted. Repeated input aliases bind to their latest +successful execution. A success-looking row header without an execution footer +is insufficient evidence. Original answer text and raw events remain available +alongside the bound `record.sql`; no reference answer determines this binding. diff --git a/bench/accuracy/codex_mcp.py b/bench/accuracy/codex_mcp.py index 8c2b61d6..0a095f9b 100644 --- a/bench/accuracy/codex_mcp.py +++ b/bench/accuracy/codex_mcp.py @@ -56,26 +56,31 @@ def executed_sql(answer, events, *, db=None, sql_timeout=30, max_rows=100000): result = block.get("text", "") if not re.match(r"(?:\d+ row\(s\):|\(0 rows\))", result): continue - # The server applies safety rewrites (e.g. LIMIT) before execution. - # Its result footer records that executed SQL, unlike input arguments. - if "\nSQL: " in result: - candidates.append(result.rsplit("\nSQL: ", 1)[1].strip()) - candidates.append(call.get("arguments", {}).get("sql", "")) - if any( - candidate.strip().removesuffix(";").rstrip() == sql.removesuffix(";").rstrip() - for candidate in candidates - ): - return sql + # Bind exports to the SQL the server actually executed, not to + # the pre-safety request (which may lack a rewritten row limit). + if "\nSQL: " not in result: + logger.warning("Missing executed SQL footer call_id=%s", call.get("id")) + continue + actual = result.rsplit("\nSQL: ", 1)[1].strip() + if actual: + candidates.append((call.get("arguments", {}).get("sql", ""), actual, call.get("id"))) + sql_key = sql.removesuffix(";").rstrip() + for submitted, actual, call_id in reversed(candidates): + if actual.removesuffix(";").rstrip() == sql_key: + return sql + if submitted.strip().removesuffix(";").rstrip() == sql_key: + logger.info("Final SQL bound to server rewrite call_id=%s", call_id) + return actual if db is not None and candidates: - # Compare SQLite bytecode, preserving literals. No result/gold-based selection. + # Formatting equivalence preserves literals. Neither result nor gold + # equivalence is used, and an input alias still binds to executed SQL. plan = query_rows(db, "EXPLAIN " + sql, sql_timeout, max_rows) - for candidate in candidates: - if ( - candidate - and query_rows(db, "EXPLAIN " + candidate, sql_timeout, max_rows) - == plan - ): + for submitted, actual, call_id in reversed(candidates): + if query_rows(db, "EXPLAIN " + actual, sql_timeout, max_rows) == plan: return sql + if submitted and query_rows(db, "EXPLAIN " + submitted, sql_timeout, max_rows) == plan: + logger.info("Final SQL alias bound to server rewrite call_id=%s", call_id) + return actual raise ValueError("Final SQL was not executed through Lang2SQL MCP") diff --git a/bench/accuracy/diagnostics/executed-sql-binding/replay-as-executed.py b/bench/accuracy/diagnostics/executed-sql-binding/replay-as-executed.py new file mode 100644 index 00000000..4b008f2d --- /dev/null +++ b/bench/accuracy/diagnostics/executed-sql-binding/replay-as-executed.py @@ -0,0 +1,24 @@ +import pathlib,json,hashlib +from bench.accuracy.codex_mcp import executed_sql +from bench.accuracy.evaluate import query_rows +root=pathlib.Path('/Users/seyoung/workspace/benchmarks');report={'purpose':'Offline replay of saved execution provenance; no model calls, no grader/old artifact mutation','runs':[]} +for name in ['codex-mcp-integrated-20261127','codex-mcp-prior-full-failures-20261127','codex-mcp-integrated-review-20261127']: + for suite in ['bird','spider']: + run=root/name/(suite+'-gpt-6.2-sol');manifest=json.loads((run/'manifest.json').read_text());cases={c['instance_id']:c for c in manifest['cases']};entry={'source':str(run),'predictions_checked':0,'changed_sql':[],'rejected':[]} + for p in sorted((run/'codex-mcp/records').glob('*.json')): + d=json.loads(p.read_text()) + if d['status']!='predicted':continue + i=d['instance_id'];events=run/'codex-mcp/events'/(i+'.jsonl');assert hashlib.sha256(events.read_bytes()).hexdigest()==d['events_sha256'] + db=root/('bird-sqlite' if suite=='bird' else 'spider2-databases')/(cases[i]['db']+'.sqlite') + raw=[json.loads(l) for l in events.read_text().splitlines() if l.startswith('{')] + entry['predictions_checked']+=1 + try:new=executed_sql(d['answer'],raw,db=db) + except ValueError as exc: + entry['rejected'].append({'id':i,'error':str(exc)});continue + if new!=d['sql']: + assert hashlib.sha256(db.read_bytes()).hexdigest()==manifest['db_sha256'][cases[i]['db']] + old_rows=query_rows(db,d['sql'],30,100000);new_rows=query_rows(db,new,30,100000) + entry['changed_sql'].append({'id':i,'old_sql':d['sql'],'bound_sql':new,'old_rows':len(old_rows),'new_rows':len(new_rows),'native_rows_identical':old_rows==new_rows,'record_sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'events_sha256':d['events_sha256']}) + report['runs'].append(entry) + print(name,suite,entry['predictions_checked'],'changed',[(x['id'],x['native_rows_identical']) for x in entry['changed_sql']],'rejected',len(entry['rejected'])) +p=pathlib.Path('bench/accuracy/diagnostics/executed-sql-binding/replay.json');p.write_text(json.dumps(report,indent=2)+'\n') diff --git a/bench/accuracy/diagnostics/executed-sql-binding/replay.json b/bench/accuracy/diagnostics/executed-sql-binding/replay.json new file mode 100644 index 00000000..d7c713d1 --- /dev/null +++ b/bench/accuracy/diagnostics/executed-sql-binding/replay.json @@ -0,0 +1,70 @@ +{ + "purpose": "Offline replay of saved execution provenance; no model calls, no grader/old artifact mutation", + "runs": [ + { + "source": "/Users/seyoung/workspace/benchmarks/codex-mcp-integrated-20261127/bird-gpt-6.2-sol", + "predictions_checked": 31, + "changed_sql": [], + "rejected": [] + }, + { + "source": "/Users/seyoung/workspace/benchmarks/codex-mcp-integrated-20261127/spider-gpt-6.2-sol", + "predictions_checked": 26, + "changed_sql": [ + { + "id": "local259", + "old_sql": "WITH role_counts AS (\n SELECT player_id,\n role,\n SUM(COUNT(*)) OVER (PARTITION BY player_id) AS total_matches_played,\n RANK() OVER (\n PARTITION BY player_id\n ORDER BY role IS NULL, COUNT(*) DESC\n ) AS role_rank\n FROM main.player_match\n GROUP BY player_id, role\n),\nappearances AS (\n SELECT player_id,\n GROUP_CONCAT(role, ', ') AS most_frequent_role,\n MAX(total_matches_played) AS total_matches_played\n FROM (\n SELECT player_id, role, total_matches_played\n FROM role_counts\n WHERE role_rank = 1\n ORDER BY player_id, role\n )\n GROUP BY player_id\n),\nbatting_by_match AS (\n SELECT b.striker AS player_id,\n b.match_id,\n SUM(s.runs_scored) AS runs_scored,\n COUNT(*) AS balls_faced\n FROM main.ball_by_ball AS b\n JOIN main.batsman_scored AS s USING (match_id, over_id, ball_id, innings_no)\n GROUP BY b.striker, b.match_id\n),\nbatting_career AS (\n SELECT player_id,\n SUM(runs_scored) AS total_runs_scored,\n MAX(runs_scored) AS highest_score,\n SUM(runs_scored >= 30) AS matches_with_30_plus,\n SUM(runs_scored >= 50) AS matches_with_50_plus,\n SUM(runs_scored >= 100) AS matches_with_100_plus,\n SUM(balls_faced) AS total_balls_faced\n FROM batting_by_match\n GROUP BY player_id\n),\ndismissals AS (\n SELECT player_out AS player_id,\n COUNT(*) AS total_dismissals\n FROM main.wicket_taken\n WHERE kind_out <> 'retired hurt'\n GROUP BY player_out\n),\nbowling_by_match AS (\n SELECT b.bowler AS player_id,\n b.match_id,\n SUM(COALESCE(s.runs_scored, 0)) AS runs_given,\n -- Count recorded deliveries for economy while ignoring the extra-runs data.\n COUNT(*) AS balls_bowled,\n COUNT(CASE WHEN w.kind_out IN (\n 'bowled', 'caught', 'caught and bowled', 'hit wicket', 'lbw', 'stumped'\n ) THEN 1 END) AS wickets_taken\n FROM main.ball_by_ball AS b\n LEFT JOIN main.batsman_scored AS s USING (match_id, over_id, ball_id, innings_no)\n LEFT JOIN main.wicket_taken AS w USING (match_id, over_id, ball_id, innings_no)\n GROUP BY b.bowler, b.match_id\n),\nbowling_career AS (\n SELECT player_id,\n wickets_taken || '-' || runs_given AS best_bowling_performance,\n SUM(wickets_taken) OVER player_matches AS total_wickets_taken,\n SUM(runs_given) OVER player_matches AS total_runs_given,\n SUM(balls_bowled) OVER player_matches AS total_balls_bowled,\n ROW_NUMBER() OVER (\n PARTITION BY player_id\n ORDER BY wickets_taken DESC, runs_given, match_id\n ) AS performance_rank\n FROM bowling_by_match\n WINDOW player_matches AS (PARTITION BY player_id)\n)\nSELECT p.player_id,\n p.player_name,\n a.most_frequent_role,\n p.batting_hand,\n p.bowling_skill,\n COALESCE(bt.total_runs_scored, 0) AS total_runs_scored,\n COALESCE(a.total_matches_played, 0) AS total_matches_played,\n COALESCE(d.total_dismissals, 0) AS total_dismissals,\n 1.0 * COALESCE(bt.total_runs_scored, 0) / NULLIF(d.total_dismissals, 0) AS batting_average,\n bt.highest_score,\n COALESCE(bt.matches_with_30_plus, 0) AS matches_with_30_plus,\n COALESCE(bt.matches_with_50_plus, 0) AS matches_with_50_plus,\n COALESCE(bt.matches_with_100_plus, 0) AS matches_with_100_plus,\n COALESCE(bt.total_balls_faced, 0) AS total_balls_faced,\n 100.0 * bt.total_runs_scored / NULLIF(bt.total_balls_faced, 0) AS strike_rate,\n COALESCE(bw.total_wickets_taken, 0) AS total_wickets_taken,\n 6.0 * bw.total_runs_given / NULLIF(bw.total_balls_bowled, 0) AS economy_rate,\n bw.best_bowling_performance\nFROM main.player AS p\nLEFT JOIN appearances AS a ON a.player_id = p.player_id\nLEFT JOIN batting_career AS bt ON bt.player_id = p.player_id\nLEFT JOIN dismissals AS d ON d.player_id = p.player_id\nLEFT JOIN bowling_career AS bw ON bw.player_id = p.player_id AND bw.performance_rank = 1\nORDER BY p.player_id", + "bound_sql": "WITH role_counts AS (\n SELECT player_id,\n role,\n SUM(COUNT(*)) OVER (PARTITION BY player_id) AS total_matches_played,\n RANK() OVER (\n PARTITION BY player_id\n ORDER BY role IS NULL, COUNT(*) DESC\n ) AS role_rank\n FROM main.player_match\n GROUP BY player_id, role\n),\nappearances AS (\n SELECT player_id,\n GROUP_CONCAT(role, ', ') AS most_frequent_role,\n MAX(total_matches_played) AS total_matches_played\n FROM (\n SELECT player_id, role, total_matches_played\n FROM role_counts\n WHERE role_rank = 1\n ORDER BY player_id, role\n )\n GROUP BY player_id\n),\nbatting_by_match AS (\n SELECT b.striker AS player_id,\n b.match_id,\n SUM(s.runs_scored) AS runs_scored,\n COUNT(*) AS balls_faced\n FROM main.ball_by_ball AS b\n JOIN main.batsman_scored AS s USING (match_id, over_id, ball_id, innings_no)\n GROUP BY b.striker, b.match_id\n),\nbatting_career AS (\n SELECT player_id,\n SUM(runs_scored) AS total_runs_scored,\n MAX(runs_scored) AS highest_score,\n SUM(runs_scored >= 30) AS matches_with_30_plus,\n SUM(runs_scored >= 50) AS matches_with_50_plus,\n SUM(runs_scored >= 100) AS matches_with_100_plus,\n SUM(balls_faced) AS total_balls_faced\n FROM batting_by_match\n GROUP BY player_id\n),\ndismissals AS (\n SELECT player_out AS player_id,\n COUNT(*) AS total_dismissals\n FROM main.wicket_taken\n WHERE kind_out <> 'retired hurt'\n GROUP BY player_out\n),\nbowling_by_match AS (\n SELECT b.bowler AS player_id,\n b.match_id,\n SUM(COALESCE(s.runs_scored, 0)) AS runs_given,\n -- Count recorded deliveries for economy while ignoring the extra-runs data.\n COUNT(*) AS balls_bowled,\n COUNT(CASE WHEN w.kind_out IN (\n 'bowled', 'caught', 'caught and bowled', 'hit wicket', 'lbw', 'stumped'\n ) THEN 1 END) AS wickets_taken\n FROM main.ball_by_ball AS b\n LEFT JOIN main.batsman_scored AS s USING (match_id, over_id, ball_id, innings_no)\n LEFT JOIN main.wicket_taken AS w USING (match_id, over_id, ball_id, innings_no)\n GROUP BY b.bowler, b.match_id\n),\nbowling_career AS (\n SELECT player_id,\n wickets_taken || '-' || runs_given AS best_bowling_performance,\n SUM(wickets_taken) OVER player_matches AS total_wickets_taken,\n SUM(runs_given) OVER player_matches AS total_runs_given,\n SUM(balls_bowled) OVER player_matches AS total_balls_bowled,\n ROW_NUMBER() OVER (\n PARTITION BY player_id\n ORDER BY wickets_taken DESC, runs_given, match_id\n ) AS performance_rank\n FROM bowling_by_match\n WINDOW player_matches AS (PARTITION BY player_id)\n)\nSELECT p.player_id,\n p.player_name,\n a.most_frequent_role,\n p.batting_hand,\n p.bowling_skill,\n COALESCE(bt.total_runs_scored, 0) AS total_runs_scored,\n COALESCE(a.total_matches_played, 0) AS total_matches_played,\n COALESCE(d.total_dismissals, 0) AS total_dismissals,\n 1.0 * COALESCE(bt.total_runs_scored, 0) / NULLIF(d.total_dismissals, 0) AS batting_average,\n bt.highest_score,\n COALESCE(bt.matches_with_30_plus, 0) AS matches_with_30_plus,\n COALESCE(bt.matches_with_50_plus, 0) AS matches_with_50_plus,\n COALESCE(bt.matches_with_100_plus, 0) AS matches_with_100_plus,\n COALESCE(bt.total_balls_faced, 0) AS total_balls_faced,\n 100.0 * bt.total_runs_scored / NULLIF(bt.total_balls_faced, 0) AS strike_rate,\n COALESCE(bw.total_wickets_taken, 0) AS total_wickets_taken,\n 6.0 * bw.total_runs_given / NULLIF(bw.total_balls_bowled, 0) AS economy_rate,\n bw.best_bowling_performance\nFROM main.player AS p\nLEFT JOIN appearances AS a ON a.player_id = p.player_id\nLEFT JOIN batting_career AS bt ON bt.player_id = p.player_id\nLEFT JOIN dismissals AS d ON d.player_id = p.player_id\nLEFT JOIN bowling_career AS bw ON bw.player_id = p.player_id AND bw.performance_rank = 1\nORDER BY p.player_id\nLIMIT 1000", + "old_rows": 468, + "new_rows": 468, + "native_rows_identical": true, + "record_sha256": "6d0878b2acb9963b3499f93e515b5722e1426d466a34f56563554a50aac0e76b", + "events_sha256": "433f709207cbc00cfddb8ac2beef95d5fcd002cfa14b8015e274e3907a851ed1" + } + ], + "rejected": [] + }, + { + "source": "/Users/seyoung/workspace/benchmarks/codex-mcp-prior-full-failures-20261127/bird-gpt-6.2-sol", + "predictions_checked": 59, + "changed_sql": [ + { + "id": "bird357", + "old_sql": "WITH female_races AS (\n SELECT DISTINCT h.race_id\n FROM main.superhero AS h\n JOIN main.gender AS g ON g.id = h.gender_id\n WHERE g.gender = 'Female'\n)\nSELECT AVG(NULLIF(h.weight_kg, 0)) AS average_weight_kg\nFROM main.superhero AS h\nJOIN main.race AS r ON r.id = h.race_id\nLEFT JOIN female_races AS f ON f.race_id = r.id\nWHERE f.race_id IS NULL;", + "bound_sql": "WITH female_races AS (\n SELECT DISTINCT h.race_id\n FROM main.superhero AS h\n JOIN main.gender AS g ON g.id = h.gender_id\n WHERE g.gender = 'Female'\n)\nSELECT AVG(NULLIF(h.weight_kg, 0)) AS average_weight_kg\nFROM main.superhero AS h\nJOIN main.race AS r ON r.id = h.race_id\nLEFT JOIN female_races AS f ON f.race_id = r.id\nWHERE f.race_id IS NULL\nLIMIT 1000", + "old_rows": 1, + "new_rows": 1, + "native_rows_identical": true, + "record_sha256": "f12bb04d3230cb4253bfaf728335f0ced4a488b8d1e98e3c8fcd54e2928d56e8", + "events_sha256": "284678d1b215e8abc38be48ab30f33416af7782d73fbb363aab52d80d261cb33" + } + ], + "rejected": [] + }, + { + "source": "/Users/seyoung/workspace/benchmarks/codex-mcp-prior-full-failures-20261127/spider-gpt-6.2-sol", + "predictions_checked": 29, + "changed_sql": [], + "rejected": [] + }, + { + "source": "/Users/seyoung/workspace/benchmarks/codex-mcp-integrated-review-20261127/bird-gpt-6.2-sol", + "predictions_checked": 4, + "changed_sql": [], + "rejected": [] + }, + { + "source": "/Users/seyoung/workspace/benchmarks/codex-mcp-integrated-review-20261127/spider-gpt-6.2-sol", + "predictions_checked": 3, + "changed_sql": [], + "rejected": [] + } + ], + "script_sha256": "aad364cd0126fac1e439db7feeb726a0b11b18d31732fcac8c929b544db46e5f", + "summary": { + "predictions_checked": 152, + "sql_text_changes": 2, + "rejected": 0, + "native_result_changes": 0 + } +} diff --git a/tests/test_codex_mcp_benchmark.py b/tests/test_codex_mcp_benchmark.py index 6c21c627..c7af091f 100644 --- a/tests/test_codex_mcp_benchmark.py +++ b/tests/test_codex_mcp_benchmark.py @@ -15,7 +15,7 @@ def event(tool="run_sql", status="completed", server="lang2sql", sql="SELECT 1") "status": status, "error": None, "arguments": {"sql": sql}, - "result": {"content": [{"type": "text", "text": "1 row(s):\n1"}]}, + "result": {"content": [{"type": "text", "text": "1 row(s):\n1\nSQL: " + sql}]}, }, } @@ -86,8 +86,8 @@ def test_server_rewritten_sql_is_execution_evidence(prefix): call = event(sql="SELECT 1") call["item"]["result"]["content"][0]["text"] = prefix + "\nSQL: SELECT 1 LIMIT 1000" assert executed_sql("```sql\nSELECT 1 LIMIT 1000\n```", [call]) == "SELECT 1 LIMIT 1000" - # Preserve the existing input-query contract, but reject invented limits. - assert executed_sql("```sql\nSELECT 1\n```", [call]) == "SELECT 1" + # A submitted alias binds to the actual rewrite, not an unexecuted unlimited query. + assert executed_sql("```sql\nSELECT 1\n```", [call]) == "SELECT 1 LIMIT 1000" for sql in ["SELECT 1 LIMIT 2000"]: with pytest.raises(ValueError): executed_sql("```sql\n" + sql + "\n```", [call]) @@ -294,3 +294,51 @@ def test_spawn_failure_has_explicit_absent_trace(tmp_path): assert record["cli_exit_code"] is None assert record["mcp_calls"] == [] assert "events_sha256" not in record + + +def test_export_binds_to_executed_rewrite_not_unbounded_request(tmp_path): + import sqlite3 + + from bench.accuracy.evaluate import query_rows + + db = tmp_path / "data.sqlite" + with sqlite3.connect(db) as conn: + conn.execute("CREATE TABLE t(x)") + conn.executemany("INSERT INTO t VALUES (?)", [(1,), (2,)]) + call = event(sql="SELECT x FROM t ORDER BY x") + call["item"]["result"]["content"][0]["text"] = "1 row(s):\nx\n1\nSQL: SELECT x FROM t ORDER BY x LIMIT 1" + sql = executed_sql("```sql\nSELECT x FROM t ORDER BY x\n```", [call], db=db) + assert query_rows(db, sql, 1, 100) == [(1,)] + assert sql.endswith("LIMIT 1") + + +def test_missing_execution_footer_is_not_execution_proof(): + call = event() + call["item"]["result"]["content"][0]["text"] = "1 row(s):\n1" + with pytest.raises(ValueError, match="not executed"): + executed_sql("```sql\nSELECT 1\n```", [call]) + + +def test_reformatted_request_binds_to_rewrite_without_accepting_other_literals(tmp_path): + import sqlite3 + + db = tmp_path / "data.sqlite" + with sqlite3.connect(db) as conn: + conn.execute("CREATE TABLE t(x)") + call = event(sql="SELECT x FROM t WHERE x > 1") + call["item"]["result"]["content"][0]["text"] = "(0 rows)\nSQL: SELECT x FROM t WHERE x > 1 LIMIT 2" + answer = "```sql\nselect x from t -- display formatting\nwhere x > 1;\n```" + assert executed_sql(answer, [call], db=db) == "SELECT x FROM t WHERE x > 1 LIMIT 2" + with pytest.raises(ValueError): + executed_sql(answer.replace("> 1", "> 2"), [call], db=db) + + +def test_repeated_request_alias_binds_to_latest_successful_execution(): + calls = [] + for limit in [2, 5]: + call = event(sql="SELECT x FROM t") + call["item"]["result"]["content"][0]["text"] = f"{limit} row(s):\nSQL: SELECT x FROM t LIMIT {limit}" + calls.append(call) + assert executed_sql("```sql\nSELECT x FROM t\n```", calls) == "SELECT x FROM t LIMIT 5" + # An earlier executed SQL is still valid when the final answer names it explicitly. + assert executed_sql("```sql\nSELECT x FROM t LIMIT 2\n```", calls) == "SELECT x FROM t LIMIT 2" diff --git a/tests/test_mcp.py b/tests/test_mcp.py index f42e81ca..3534a542 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -404,7 +404,7 @@ async def test_output_columns_contract_stdio(tmp_path, sql, expected, error, fra 'status': 'completed', 'arguments': {'sql': sql}, 'result': {'content': [{'text': result.content[0].text}]}, }}] - assert executed_sql('```sql\n' + sql + '\n```', events) == sql + assert executed_sql('```sql\n' + sql + '\n```', events) == sql + '\nLIMIT 1000' @pytest.mark.asyncio async def test_output_contract_legacy_empty_result_is_not_verified():