Repository navigation
Expand file tree
/
Copy pathtest_mcp.py
More file actions
751 lines (675 loc) · 28.5 KB
/
Copy pathtest_mcp.py
File metadata and controls
751 lines (675 loc) · 28.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
"""Exercise the actual stdio protocol against the tool-only composition."""
import json
import os
import sqlite3
import sys
from contextlib import asynccontextmanager
import pytest
pytest.importorskip("mcp")
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from lang2sql.core.identity import Identity
from lang2sql.tenancy.tool_runtime import ExternalAgentLLM, build_tool_context
@asynccontextmanager
async def connected(db, store, *, team="finance", extra=()):
env = dict(os.environ)
env["LANG2SQL_DB_URL"] = f"sqlite:///{db}"
env.pop("LANG2SQL_DB_SCHEMA", None)
parameters = StdioServerParameters(
command=sys.executable,
args=[
"-m",
"lang2sql.frontends.mcp.server",
"--user-id",
"analyst",
"--org-id",
"demo",
"--team-id",
team,
"--store",
str(store),
*extra,
],
env=env,
)
async with (
stdio_client(parameters) as (reader, writer),
ClientSession(reader, writer) as client,
):
await client.initialize()
yield client
async def checked_sql(client, sql):
saved = await client.call_tool(
"term_custom",
{"term": "order_total", "definition": "SUM(orders.amount)", "layer": "team"},
)
assert not saved.isError
check = await client.call_tool("resolve_business_terms", {"terms": ["order_total"]})
token = json.loads(check.content[0].text)["definition_check_id"]
return await client.call_tool("run_sql", {"sql": sql, "definition_check_id": token})
def fixture_db(tmp_path):
db = tmp_path / "data.db"
with sqlite3.connect(db) as conn:
conn.execute("CREATE TABLE orders (amount INTEGER)")
conn.executemany("INSERT INTO orders VALUES (?)", [(10,), (20,)])
return db
@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} == {
"context_candidates",
"calendar_interval_sql",
"fixed_decimal_sql",
"integer_ratio_sql",
"run_sql",
"explore_schema",
"term_custom",
"remember",
"recall_memory",
"save_column_notes",
"resolve_business_terms",
}
schema = await client.call_tool("explore_schema", {})
assert not schema.isError and "orders" in schema.content[0].text
assert "paid_orders [view]" in schema.content[0].text
view = await client.call_tool("explore_schema", {"table": "paid_orders"})
assert not view.isError
assert "paid_orders (view)\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 checked_sql(client, "SELECT SUM(amount) AS total FROM orders")
assert not result.isError and "30" in result.content[0].text
blocked = await checked_sql(client, "DROP TABLE orders")
assert blocked.isError and "BLOCKED" in blocked.content[0].text
malformed = await client.call_tool("run_sql", {"sql": 123})
assert malformed.isError
spoof = await client.call_tool("term_custom", {"list": True, "is_admin": True})
assert spoof.isError
unknown = await client.call_tool("org_setup", {})
assert unknown.isError
await client.call_tool("remember", {"text": "Refunds are excluded."})
recalled = await client.call_tool("recall_memory", {"query": "refund"})
assert "Refunds are excluded." in recalled.content[0].text
with sqlite3.connect(db) as conn:
assert conn.execute("SELECT SUM(amount) FROM orders").fetchone() == (30,)
with sqlite3.connect(tmp_path / "metadata.db") as conn:
assert (
conn.execute(
"SELECT count(*) FROM audit WHERE action='run_sql'"
).fetchone()[0]
== 1
)
@pytest.mark.asyncio
async def test_metadata_persists_and_team_scope_is_preserved(tmp_path):
db = fixture_db(tmp_path)
store = tmp_path / "metadata.db"
async with connected(db, store) as client:
saved = await client.call_tool(
"term_custom",
{"term": "net_revenue", "definition": "Exclude refunds", "layer": "team"},
)
assert not saved.isError
denied = await client.call_tool(
"term_custom",
{"term": "net_revenue", "definition": "Not allowed", "layer": "org"},
)
assert denied.isError
await client.call_tool("remember", {"text": "Persistent note"})
async with connected(db, store) as client:
terms = await client.call_tool("term_custom", {"list": True})
assert "Exclude refunds" in terms.content[0].text
notes = await client.call_tool("recall_memory", {"query": "note"})
assert "Persistent note" in notes.content[0].text
async with connected(db, store, team="sales") as client:
terms = await client.call_tool("term_custom", {"list": True})
assert "Exclude refunds" not in terms.content[0].text
def test_no_connection_does_not_silently_use_stub(monkeypatch):
for key in [
"LANG2SQL_DB_URL",
"CLOUDFLARE_D1_ACCOUNT_ID",
"CLOUDFLARE_D1_DATABASE_ID",
]:
monkeypatch.delenv(key, raising=False)
with pytest.raises(ValueError, match="LANG2SQL_DB_URL"):
build_tool_context(Identity(user_id="test"))
@pytest.mark.asyncio
async def test_internal_llm_is_disabled():
with pytest.raises(RuntimeError, match="internal LLM"):
await ExternalAgentLLM().complete([])
@pytest.mark.asyncio
async def test_missing_definition_never_reaches_database(tmp_path):
db = fixture_db(tmp_path)
store = tmp_path / "metadata.db"
async with connected(db, store) as client:
direct = await client.call_tool("run_sql", {"sql": "SELECT * FROM orders"})
assert direct.isError
check = await client.call_tool(
"resolve_business_terms", {"terms": ["loyal_customer"]}
)
assert check.isError and "DEFINITION_REQUIRED" in check.content[0].text
assert "context_candidates" in check.content[0].text
assert "operator must approve" in check.content[0].text
assert "term_custom" not in check.content[0].text
guessed = await client.call_tool(
"run_sql",
{"sql": "SELECT * FROM orders", "definition_check_id": "fabricated"},
)
assert guessed.isError and "NOT executed" in guessed.content[0].text
empty = await client.call_tool("resolve_business_terms", {"terms": []})
assert (
not empty.isError
) # No lookup needed for an explicitly specified literal query.
with sqlite3.connect(store) as conn:
assert (
conn.execute(
"SELECT count(*) FROM audit WHERE action LIKE 'run_sql%'"
).fetchone()[0]
== 0
)
@pytest.mark.asyncio
async def test_check_scope_inferred_mutation_and_single_use(tmp_path):
db = fixture_db(tmp_path)
store = tmp_path / "metadata.db"
async with connected(db, store) as client:
async def save(definition, inferred=False):
result = await client.call_tool(
"term_custom",
{
"term": "revenue",
"definition": definition,
"layer": "team",
"inferred": inferred,
},
)
assert not result.isError
async def resolve():
return await client.call_tool(
"resolve_business_terms", {"terms": ["revenue"]}
)
async def execute(token):
return await client.call_tool(
"run_sql",
{"sql": "SELECT SUM(amount) FROM orders", "definition_check_id": token},
)
await save("SUM(amount)", True)
assert (await resolve()).isError
await save("SUM(amount)")
token = json.loads((await resolve()).content[0].text)["definition_check_id"]
await save("SUM(amount) - 5")
assert (await execute(token)).isError
await save("SUM(amount)")
token = json.loads((await resolve()).content[0].text)["definition_check_id"]
result = await execute(token)
assert not result.isError and "30" in result.content[0].text
assert (await execute(token)).isError
token = json.loads((await resolve()).content[0].text)["definition_check_id"]
assert (
await client.call_tool(
"resolve_business_terms", {"terms": ["revenue", "missing"]}
)
).isError
assert (await execute(token)).isError
async with connected(db, store) as client:
assert (
await client.call_tool(
"run_sql",
{"sql": "SELECT * FROM orders", "definition_check_id": token},
)
).isError
assert not (
await client.call_tool("resolve_business_terms", {"terms": ["revenue"]})
).isError
async with connected(db, store, team="sales") as client:
assert (
await client.call_tool("resolve_business_terms", {"terms": ["revenue"]})
).isError
@pytest.mark.asyncio
async def test_memory_survives_stdio_restart_and_isolates_team(tmp_path):
db = fixture_db(tmp_path)
store = tmp_path / "metadata.db"
async with connected(db, store, team="sales") as client:
result = await client.call_tool(
"remember", {"text": "October cutoff is October 31"}
)
assert not result.isError
async with connected(db, store, team="sales") as client:
result = await client.call_tool("recall_memory", {"query": "cutoff"})
assert "October cutoff is October 31" in result.content[0].text
async with connected(db, store, team="finance", extra=()) as client:
result = await client.call_tool("recall_memory", {"query": "cutoff"})
assert "No remembered notes" in result.content[0].text
@pytest.mark.asyncio
async def test_literal_query_without_catalog_still_requires_single_use_receipt(
tmp_path,
):
db = fixture_db(tmp_path)
async with connected(db, tmp_path / "metadata.db") as client:
check = await client.call_tool("resolve_business_terms", {"terms": []})
assert not check.isError
token = json.loads(check.content[0].text)["definition_check_id"]
args = {"sql": "SELECT COUNT(*) AS n FROM orders", "definition_check_id": token}
result = await client.call_tool("run_sql", args)
assert not result.isError and "2" in result.content[0].text
assert (await client.call_tool("run_sql", args)).isError
missing = await client.call_tool(
"resolve_business_terms", {"terms": ["undefined_net_revenue"]}
)
assert missing.isError and "DEFINITION_REQUIRED" in missing.content[0].text
@pytest.mark.asyncio
async def test_missing_definitions_are_reported_together_and_revoke_receipt(tmp_path):
async with connected(fixture_db(tmp_path), tmp_path / "metadata.db") as client:
await client.call_tool(
"term_custom",
{"term": "known", "definition": "SUM(orders.amount)", "layer": "team"},
)
check = await client.call_tool("resolve_business_terms", {"terms": ["known"]})
token = json.loads(check.content[0].text)["definition_check_id"]
check = await client.call_tool(
"resolve_business_terms", {"terms": ["missing_a", "known", "missing_b"]}
)
assert check.isError
message = check.content[0].text
assert '["missing_a", "missing_b"]' in message
assert '"known"' not in message
rejected = await client.call_tool(
"run_sql",
{"sql": "SELECT COUNT(*) FROM orders", "definition_check_id": token},
)
assert rejected.isError
@pytest.mark.asyncio
@pytest.mark.parametrize("limit", [-1, 0])
async def test_invalid_fetch_limit_rejected_before_database_access(tmp_path, limit):
from unittest.mock import AsyncMock
from lang2sql.tools.run_sql import RunSQL
explorer = AsyncMock()
ctx = build_tool_context(
Identity(user_id="analyst", guild_id="demo"),
store_path=":memory:",
explorer=explorer,
)
try:
result = await RunSQL().run({"sql": "SELECT 1", "limit": limit}, ctx)
assert result.is_error
assert "positive maximum row count" in result.content
explorer.execute.assert_not_called()
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
@pytest.mark.asyncio
@pytest.mark.parametrize(
"sql, expected, error, fragment",
[
("SELECT amount FROM orders", ["amount"], False, "Output columns validated"),
("SELECT amount FROM orders", ["amount", "growth"], True, "missing"),
("SELECT amount, 1 AS extra FROM orders", ["amount"], True, "unexpected"),
(
"SELECT amount FROM orders WHERE 0",
["amount"],
False,
"Output columns validated",
),
("SELECT amount FROM orders WHERE 0", ["growth"], True, "missing"),
("SELECT amount, 1 AS extra FROM orders", ["extra", "amount"], True, "order"),
],
)
async def test_output_columns_contract_stdio(tmp_path, sql, expected, error, fragment):
async with connected(fixture_db(tmp_path), tmp_path / "metadata.db") as client:
check = await client.call_tool("resolve_business_terms", {"terms": []})
token = json.loads(check.content[0].text)["definition_check_id"]
result = await client.call_tool(
"run_sql",
{
"sql": sql,
"definition_check_id": token,
"expected_columns": expected,
},
)
assert result.isError == error
assert fragment in result.content[0].text
if error:
assert "Output column contract failed" in result.content[0].text
@pytest.mark.asyncio
async def test_output_contract_legacy_empty_result_is_not_verified():
from lang2sql.tools.run_sql import RunSQL
class LegacyExplorer:
async def execute(self, sql, limit):
return []
ctx = build_tool_context(Identity(user_id="analyst"), explorer=LegacyExplorer())
try:
result = await RunSQL().run(
{"sql": "SELECT 1 AS n", "expected_columns": ["n"]}, ctx
)
assert result.is_error and "metadata unavailable" in result.content
assert any(
e.action == "run_sql_contract_failed"
for e in await ctx.store.query("analyst")
)
unchecked = await RunSQL().run({"sql": "SELECT 1 AS n"}, ctx)
assert not unchecked.is_error
finally:
ctx.store.close()
@pytest.mark.asyncio
@pytest.mark.parametrize("expected", [None, [], ["n", "n"], [""], [1], "n", [{}]])
async def test_invalid_output_contract_never_executes(expected):
from lang2sql.tools.run_sql import RunSQL
class NeverExecute:
async def execute(self, sql, limit):
pytest.fail("Invalid contract reached database")
ctx = build_tool_context(Identity(user_id="analyst"), explorer=NeverExecute())
try:
result = await RunSQL().run(
{"sql": "SELECT 1 AS n", "expected_columns": expected}, ctx
)
assert result.is_error and "NOT executed" in result.content
finally:
ctx.store.close()
@pytest.mark.asyncio
async def test_calendar_compiler_through_stdio_and_sql_guard(tmp_path):
from lang2sql.tools.calendar_interval_sql import CALENDAR_CTES
async with connected(fixture_db(tmp_path), tmp_path / "meta.db") as client:
compiled = await client.call_tool(
"calendar_interval_sql", {"dialect": "sqlite"}
)
assert not compiled.isError
assert CALENDAR_CTES in compiled.content[0].text
check = await client.call_tool("resolve_business_terms", {"terms": []})
token = json.loads(check.content[0].text)["definition_check_id"]
sql = (
"WITH calendar_input(row_id, start_date, end_date) AS "
"(VALUES (1, '2020-02-29', '2021-02-28')), "
+ CALENDAR_CTES
+ " SELECT years, months, days FROM calendar_interval"
)
result = await client.call_tool(
"run_sql", {"sql": sql, "definition_check_id": token}
)
assert not result.isError
assert "1 | 0 | 0" in result.content[0].text
denied = await client.call_tool("run_sql", {"sql": sql})
assert denied.isError
@pytest.mark.asyncio
async def test_fixed_decimal_compiler_stdio_execution(tmp_path):
from lang2sql.tools.fixed_decimal_sql import fixed_decimal_ctes
async with connected(fixture_db(tmp_path), tmp_path / "meta.db") as client:
compiled = await client.call_tool(
"fixed_decimal_sql",
{
"dialect": "sqlite",
"input_scale": 1,
"output_scale": 1,
"aggregate": "avg",
},
)
assert not compiled.isError
ctes = fixed_decimal_ctes(1, 1, "avg")
assert ctes in compiled.content[0].text
check = await client.call_tool("resolve_business_terms", {"terms": []})
token = json.loads(check.content[0].text)["definition_check_id"]
sql = (
"WITH decimal_input(group_id, scaled_value) AS (VALUES ('a', 11), ('a', 12)), "
+ ctes
+ " SELECT status, rounded_value FROM decimal_result"
)
result = await client.call_tool(
"run_sql", {"sql": sql, "definition_check_id": token}
)
assert not result.isError
assert "ok | 1.2" in result.content[0].text
@pytest.mark.asyncio
@pytest.mark.parametrize(
"sql, expected, limit, error, fragment",
[
("SELECT SUM(amount) AS value FROM orders", 1, 1000, False, "1 row(s):"),
(
"SELECT amount AS value FROM orders LIMIT -1",
1,
1000,
True,
"expected=1; observed=2",
),
("SELECT amount AS value FROM orders WHERE 0", 0, 1000, False, "(0 rows)"),
(
"SELECT amount AS value FROM orders LIMIT -1",
1,
1,
True,
"observed=at least 2",
),
("SELECT amount AS value FROM orders LIMIT -1", 2, 2, False, "2 row(s):"),
(
"WITH RECURSIVE n(value) AS (SELECT 1 UNION ALL SELECT value+1 FROM n WHERE value<60) SELECT value FROM n LIMIT -1",
60,
100,
False,
"displayed_rows=50",
),
(
"WITH RECURSIVE n(value) AS (SELECT 1 UNION ALL SELECT value+1 FROM n WHERE value<60) SELECT value FROM n LIMIT -1",
50,
50,
True,
"observed=at least 51",
),
],
)
async def test_output_cardinality_stdio(
tmp_path, sql, expected, limit, error, fragment
):
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",
{
"definition_check_id": json.loads(check.content[0].text)[
"definition_check_id"
],
"sql": sql,
"expected_columns": ["value"],
"expected_rows": expected,
"limit": limit,
},
)
text = result.content[0].text
assert result.isError == error
assert fragment in text
if error:
assert text.startswith("Output row count contract failed:")
else:
assert "Output columns validated" in text
assert "Output row count validated (executed SQL only)." in text
@pytest.mark.asyncio
@pytest.mark.parametrize(
"args",
[
{"expected_rows": None},
{"expected_rows": True},
{"expected_rows": False},
{"expected_rows": -1},
{"expected_rows": 1.0},
{"expected_rows": "1"},
{"expected_rows": []},
{"expected_rows": 2, "limit": 1},
],
)
async def test_invalid_cardinality_never_executes(args):
from lang2sql.tools.run_sql import RunSQL
class NeverExecute:
async def execute(self, sql, limit):
pytest.fail("Invalid cardinality contract reached database")
ctx = build_tool_context(Identity(user_id="analyst"), explorer=NeverExecute())
try:
result = await RunSQL().run({"sql": "SELECT 1 AS n", **args}, ctx)
assert result.is_error and "NOT executed" in result.content
finally:
ctx.store.close()
@pytest.mark.asyncio
async def test_cardinality_failure_is_audited_without_changing_sql():
from lang2sql.tools.run_sql import RunSQL
class TwoRows:
async def execute(self, sql, limit):
assert sql == "SELECT 1 AS n UNION ALL SELECT 2 AS n LIMIT -1"
return [{"n": 1}, {"n": 2}]
ctx = build_tool_context(Identity(user_id="analyst"), explorer=TwoRows())
try:
result = await RunSQL().run(
{
"sql": "SELECT 1 AS n UNION ALL SELECT 2 AS n LIMIT -1",
"expected_rows": 1,
},
ctx,
)
assert result.is_error
assert (
"2 row(s):" in result.content
) # No truncation to the declared one-row target.
events = await ctx.store.query("analyst")
assert any(
e.action == "run_sql_contract_failed"
and "expected=1" in e.detail["contract_error"]
for e in events
)
finally:
ctx.store.close()
@pytest.mark.asyncio
async def test_integer_ratio_compiler_executes_via_stdio(tmp_path):
from lang2sql.tools.integer_ratio_sql import integer_ratio_ctes
async with connected(fixture_db(tmp_path), tmp_path / "metadata.db") as client:
compiled = await client.call_tool(
"integer_ratio_sql", {"dialect": "sqlite", "multiplier": 100}
)
assert not compiled.isError
ctes = integer_ratio_ctes(100)
assert ctes in compiled.content[0].text
check = await client.call_tool("resolve_business_terms", {"terms": []})
result = await client.call_tool(
"run_sql",
{
"definition_check_id": json.loads(check.content[0].text)[
"definition_check_id"
],
"sql": "WITH ratio_input AS (SELECT 1 AS group_id, 1.0 AS numerator, 3.0 AS denominator), "
+ ctes
+ " SELECT status, ratio_value FROM ratio_result",
},
)
assert not result.isError
assert "ok | 33.333333333333336" in result.content[0].text
@pytest.mark.asyncio
async def test_column_notes_need_admin_and_show_in_schema(tmp_path):
db = fixture_db(tmp_path)
store = tmp_path / "metadata.db"
notes = {"table": "orders", "notes": {"AMOUNT": "주문 금액(원)"}}
async with connected(db, store) as client:
denied = await client.call_tool("save_column_notes", notes)
assert denied.isError and "admin" in denied.content[0].text
async with connected(db, store, extra=["--admin"]) as client:
unknown = await client.call_tool(
"save_column_notes", {"table": "orders", "notes": {"nope": "x"}}
)
assert unknown.isError and "nope" in unknown.content[0].text
saved = await client.call_tool("save_column_notes", notes)
assert not saved.isError, saved.content[0].text
async with connected(db, store) as client: # a later, non-admin session
schema = await client.call_tool("explore_schema", {"table": "orders"})
assert "amount: INTEGER — 주문 금액(원)" in schema.content[0].text
@pytest.mark.asyncio
async def test_writes_depend_on_operator_flag(tmp_path):
db = fixture_db(tmp_path)
store = tmp_path / "metadata.db"
async with connected(db, store) as client:
blocked = await checked_sql(client, "CREATE TABLE notes (id INTEGER)")
assert blocked.isError and "BLOCKED by whitelist" in blocked.content[0].text
async with connected(db, store, extra=["--allow-write"]) as client:
for sql in (
"CREATE TABLE notes (id INTEGER, body TEXT)",
"INSERT INTO notes VALUES (1, 'a')",
"UPDATE notes SET body = 'b' WHERE id = 1",
):
result = await checked_sql(client, sql)
assert not result.isError, result.content[0].text
read = await checked_sql(client, "SELECT body FROM notes")
assert "b" in read.content[0].text
deleted = await checked_sql(client, "DELETE FROM notes")
assert "rows_affected" in deleted.content[0].text
with sqlite3.connect(db) as conn: # committed, visible to another connection
assert conn.execute("SELECT COUNT(*) FROM notes").fetchone() == (0,)