Repository navigation
Expand file tree
/
Copy pathtest_integration.py
More file actions
207 lines (167 loc) · 6.94 KB
/
Copy pathtest_integration.py
File metadata and controls
207 lines (167 loc) · 6.94 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
"""Week-2 integration: the ContextConcierge wires a working agent.
Exercises the assembled stack (tools + safety + scope resolver + explorer stub
+ sqlite) without network, using the offline FakeLLM. Locks in that the six V1
tools are registered and that run_sql/define_metric behave through the live
HarnessContext.
"""
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
from lang2sql.tools.semantic_federation import SemanticFederationTool
def _ctx():
concierge = ContextConcierge()
ident = Identity(user_id="u1", guild_id="g1", channel_id="c-mkt")
return ident, asyncio.run(concierge.build_context(ident))
def test_v1_tools_registered():
_, ctx = _ctx()
names = {s.name for s in ctx.tools.specs()}
assert names == {
"calendar_interval_sql",
"fixed_decimal_sql",
"integer_ratio_sql",
"run_sql",
"explore_schema",
"enrich_schema",
"term_custom",
"org_setup",
"ask_user",
"remember",
"ingest_doc",
"confirm_ingest",
}
def test_run_sql_metadata_stub_fails_closed_without_statement_timeout():
_, ctx = _ctx()
res = asyncio.run(RunSQL().run({"sql": "SELECT * FROM orders", "limit": 10}, ctx))
assert res.is_error
assert "query_timeout_unsupported" in res.content
def test_run_sql_blocks_ddl():
_, ctx = _ctx()
res = asyncio.run(RunSQL().run({"sql": "DROP TABLE users"}, ctx))
assert res.is_error and "BLOCKED" in res.content
def test_run_sql_tolerates_bad_limit():
_, ctx = _ctx()
res = asyncio.run(RunSQL().run({"sql": "SELECT 1", "limit": "demo"}, ctx))
# A malformed limit still cannot crash the tool, but the metadata-only
# adapter must fail closed before execution because it cannot cancel SQL.
assert res.is_error
assert "query_timeout_unsupported" in res.content
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 listed.tables_with_columns == ()
assert not single.is_error
assert single.tables_with_columns == ("public.orders",)
assert batch.is_error
assert batch.tables_with_columns == ("public.orders", "public.users")
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 result.tables_with_columns == ("orders",)
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.tables_with_columns == ("sales.orders", "archive.orders")
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
assert result.tables_with_columns == ()
def test_term_custom_is_scope_local():
from lang2sql.tools.semantic_federation import _render_effective
ident, ctx = _ctx()
asyncio.run(
SemanticFederationTool().run(
{"term": "active_user", "definition": "30d login", "layer": "team"}, ctx
)
)
rendered = _render_effective(
ctx.store, ident.kv_scope, ident.effective_channel_id, ident.user_id
)
assert "active_user" in rendered
# a different channel does not see this channel-level definition
other_rendered = _render_effective(ctx.store, ident.kv_scope, "c-fin", "u1")
assert "active_user" not in other_rendered
def test_term_custom_emits_audit_event():
concierge = ContextConcierge()
ident = Identity(user_id="u1", guild_id="g1", channel_id="c-mkt", is_admin=True)
ctx = asyncio.run(concierge.build_context(ident))
asyncio.run(
SemanticFederationTool().run(
{"term": "revenue", "definition": "gross revenue", "layer": "org"}, ctx
)
)
events = asyncio.run(ctx.audit.query(ident.user_id))
assert any(
e.action == "term_custom" and e.detail.get("term") == "revenue" for e in events
)
def test_safety_pipeline_on_context():
_, ctx = _ctx()
assert ctx.safety.evaluate("SELECT 1", SafetyContext()).verdict == Verdict.PASS