Repository navigation
Expand file tree
/
Copy pathtest_harness_loop.py
More file actions
586 lines (479 loc) · 20 KB
/
Copy pathtest_harness_loop.py
File metadata and controls
586 lines (479 loc) · 20 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
"""Agent loop and natural-language frontend regression tests."""
from __future__ import annotations
import asyncio
import json
import re
import pytest
from lang2sql.adapters.db.postgres_explorer import PostgresExplorer
from lang2sql.adapters.llm.fake import FakeLLM
from lang2sql.adapters.llm.openai_ import OpenAILLM
from lang2sql.core.identity import Identity
from lang2sql.core.ports.explorer import Table
from lang2sql.core.types import Completion, Role, ToolCall
from lang2sql.frontends.cli import app
from lang2sql.frontends.discord.commands import CommandHandlers
from lang2sql.harness.context import HarnessContext
from lang2sql.harness.loop import agent_loop
from lang2sql.harness.session import Session
from lang2sql.harness.tool_registry import ToolRegistry
from lang2sql.tenancy.concierge import ContextConcierge
from lang2sql.tools.explore_schema import ExploreSchema
from lang2sql.tools.ping import Ping
from lang2sql.tools.ask_user import AskUser
def _ctx() -> HarnessContext:
identity = Identity(user_id="tester")
return HarnessContext(
identity=identity,
llm=FakeLLM(),
tools=ToolRegistry([Ping()]),
session=Session(identity=identity),
)
def test_loop_runs_tool_then_answers():
ctx = _ctx()
answer = asyncio.run(agent_loop(ctx, "hello"))
assert "pong" in answer # tool ran and its result reached the final answer
def test_transcript_shape():
ctx = _ctx()
asyncio.run(agent_loop(ctx, "hello"))
roles = [m.role for m in ctx.session.history()]
# user → assistant(tool_call) → tool → assistant(final)
assert roles == [Role.USER, Role.ASSISTANT, Role.TOOL, Role.ASSISTANT]
def test_tool_call_id_is_stamped():
ctx = _ctx()
asyncio.run(agent_loop(ctx, "hello"))
tool_msgs = [m for m in ctx.session.history() if m.role == Role.TOOL]
assert tool_msgs and tool_msgs[0].tool_call_id
def test_schema_batch_uses_the_catalog_from_the_system_prompt():
class CountingExplorer(PostgresExplorer):
catalog_reads = 0
async def list_tables(self):
self.catalog_reads += 1
return await super().list_tables()
class SchemaLLM:
async def complete(self, messages, tools=()):
if messages[-1].role == Role.TOOL:
assert "- amount: numeric" in messages[-1].content
assert "- email: text" in messages[-1].content
return Completion(content="Found both tables.")
assert "## Known tables\npublic.orders, public.users" in messages[0].content
return Completion(
tool_calls=[
ToolCall(
id="schema",
name="explore_schema",
arguments={"tables": ["public.orders", "public.users"]},
)
]
)
ctx = _ctx()
explorer = CountingExplorer("postgresql://ignored")
ctx.explorer = explorer
ctx.llm = SchemaLLM()
ctx.tools = ToolRegistry([ExploreSchema()])
assert asyncio.run(agent_loop(ctx, "Show the schema for orders and users.")) == (
"Found both tables."
)
assert explorer.catalog_reads == 1
class _AskThenActLLM:
def __init__(self, *, sibling: bool = False) -> None:
self.calls = 0
self.sibling = sibling
async def complete(self, messages, tools=()):
self.calls += 1
if self.calls == 1:
calls = [
ToolCall(
id="ask-1",
name="ask_user",
arguments={"question": "Which amount?"},
)
]
if self.sibling:
calls.append(ToolCall(id="ping-1", name="ping", arguments={}))
return Completion(tool_calls=calls)
return Completion(tool_calls=[ToolCall(id="ping-2", name="ping", arguments={})])
def _ask_ctx(llm: _AskThenActLLM) -> HarnessContext:
identity = Identity(user_id="tester")
return HarnessContext(
identity=identity,
llm=llm,
tools=ToolRegistry([AskUser(), Ping()]),
session=Session(identity=identity),
)
def test_ask_user_suspends_until_the_next_real_user_turn():
llm = _AskThenActLLM()
ctx = _ask_ctx(llm)
answer = asyncio.run(agent_loop(ctx, "ambiguous request"))
assert answer == "❓ Awaiting user: Which amount?"
assert llm.calls == 1
assert [message.role for message in ctx.session.history()] == [
Role.USER,
Role.ASSISTANT,
Role.TOOL,
]
def test_ask_user_with_a_sibling_blocks_every_tool_without_dispatch():
llm = _AskThenActLLM(sibling=True)
ctx = _ask_ctx(llm)
answer = asyncio.run(agent_loop(ctx, "ambiguous request"))
assert answer.startswith("BLOCKED (ask_user_must_be_single_call)")
assert llm.calls == 1
tool_messages = [
message for message in ctx.session.history() if message.role == Role.TOOL
]
assert [message.name for message in tool_messages] == ["ask_user", "ping"]
assert all(message.content == answer for message in tool_messages)
def test_scope_chain_orders_narrow_to_wide():
ident = Identity(user_id="u", guild_id="g", channel_id="c", thread_id="t")
levels = [s.level.value for s in ident.scope_chain()]
assert levels == ["thread", "team", "org", "builtin"]
class RecordingExplorer(PostgresExplorer):
def __init__(self):
super().__init__("postgresql://ignored")
self.described = []
self.executed = []
async def describe_table(self, name):
self.described.append(name)
return await super().describe_table(name)
async def execute(self, sql, limit=1000):
self.executed.append(sql)
return [{"amount": 10}]
class ScriptedOpenAI(OpenAILLM):
"""Record the actual API payload without sending requests."""
def __init__(self, *replies):
super().__init__(api_key="test")
self.requests = []
self.replies = replies
def _post(self, payload):
self.requests.append(payload)
assert len(self.requests) <= len(self.replies), "Unexpected model request"
content, calls = self.replies[len(self.requests) - 1]
return {
"choices": [
{
"message": {
"content": content,
"tool_calls": [
{
"id": call_id,
"function": {
"name": name,
"arguments": json.dumps(args),
},
}
for call_id, name, args in calls
],
}
}
]
}
def _calls(*calls):
return "", calls
def _answer(text):
return text, ()
_FORCED = {"type": "function", "function": {"name": "explore_schema"}}
_SQL = "SELECT amount FROM orders"
_STALE_SQL = "SELECT guessed_amount FROM orders"
_EXECUTE = ("sql", "run_sql", {"sql": _STALE_SQL})
_SCHEMA = ("columns", "explore_schema", {"tables": ["public.orders"]})
def _context_for(llm, *, max_turns=8):
concierge = ContextConcierge(
llm=llm, explorer=RecordingExplorer(), max_turns=max_turns
)
return asyncio.run(concierge.build_context(Identity(user_id="analyst")))
def _choices(llm):
return [request.get("tool_choice") for request in llm.requests]
def _tool_results(request):
return {
message["tool_call_id"]: message["content"]
for message in request["messages"]
if message["role"] == "tool"
}
def test_run_sql_waits_for_columns_before_executing():
llm = ScriptedOpenAI(
_calls(_EXECUTE),
_calls(_SCHEMA),
_calls(("rewritten", "run_sql", {"sql": _SQL})),
_answer("Order totals are available."),
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Show order amounts")) == (
"Order totals are available."
)
assert _choices(llm) == [None, _FORCED, None, None]
assert "SQL withheld" in _tool_results(llm.requests[1])["sql"]
assert "- amount: numeric" in _tool_results(llm.requests[2])["columns"]
assert len(ctx.explorer.executed) == 1
assert _SQL in ctx.explorer.executed[0]
assert "guessed_amount" not in ctx.explorer.executed[0]
@pytest.mark.parametrize(
"output", ["{sql}", "```sql\n{sql}\n```", "**최종 SQL:**\n```sql\n{sql}\n```"]
)
def test_final_sql_is_withheld_until_the_model_has_columns(output):
draft = output.format(sql=_STALE_SQL)
revised = output.format(sql=_SQL)
llm = ScriptedOpenAI(
_answer(draft),
_calls(_SCHEMA),
_answer(revised),
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Write the order amounts query")) == revised
assert _choices(llm) == [None, _FORCED, None]
assert llm.requests[1]["messages"][-1] == {"role": "assistant", "content": draft}
assert not any(_STALE_SQL in message.content for message in ctx.session.history())
schema = [
tool["function"]["parameters"]
for request in llm.requests
for tool in request["tools"]
if tool["function"]["name"] == "explore_schema"
]
original, recovery, restored = schema
assert "required" not in original and "table" in original["properties"]
assert recovery["required"] == ["tables"]
assert recovery["properties"]["tables"]["minItems"] == 1
assert "table" not in recovery["properties"]
assert original == restored
def test_evaluator_uses_its_sql_output_contract():
def extract_sql(answer):
blocks = re.findall(r"```sql\s*(.*?)```", answer, re.I | re.S)
if len(blocks) != 1:
raise ValueError("Expected one SQL block")
return blocks[0].strip()
initial = f"Final query:\n```sql\n{_STALE_SQL}\n```"
revised = f"Final query:\n```sql\n{_SQL}\n```"
llm = ScriptedOpenAI(
_answer(initial),
_calls(_SCHEMA),
_answer("The orders table is available."),
_answer(revised),
)
ctx = _context_for(llm)
assert (
asyncio.run(agent_loop(ctx, "Write SQL", extract_final_sql=extract_sql))
== revised
)
assert _choices(llm) == [None, _FORCED, None, None]
assert not any(
message.content == "The orders table is available."
for message in ctx.session.history()
)
@pytest.mark.parametrize("schema_first", [True, False])
def test_schema_and_sql_in_the_same_response_use_the_same_model_context(schema_first):
batch = [_SCHEMA, _EXECUTE] if schema_first else [_EXECUTE, _SCHEMA]
llm = ScriptedOpenAI((_STALE_SQL, batch), _answer(_SQL))
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL
assert _choices(llm) == [None, None]
assert ctx.explorer.executed == []
results = _tool_results(llm.requests[1])
assert list(results) == [call[0] for call in batch]
assert "- amount: numeric" in results["columns"]
assert "SQL withheld" in results["sql"]
ctx.session.compress()
assert [message.content for message in ctx.session.history()] == [
"Show order amounts",
_SQL,
]
def test_recovery_rejects_list_only_legacy_and_empty_calls_and_uses_partial_success():
llm = ScriptedOpenAI(
_calls(("list", "explore_schema", {})),
_answer(_STALE_SQL),
_calls(("recovery-list", "explore_schema", {})),
_calls(("legacy", "explore_schema", {"table": "orders"})),
_calls(("empty", "explore_schema", {"tables": []})),
_calls(("failed", "explore_schema", {"tables": ["missing"]})),
_calls(("partial", "explore_schema", {"tables": ["missing", "public.orders"]})),
_answer(_SQL),
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL
assert _choices(llm) == [None, None, *([_FORCED] * 5), None]
list_result, draft = llm.requests[2]["messages"][-2:]
assert list_result["tool_call_id"] == "list"
assert draft == {"role": "assistant", "content": _STALE_SQL}
results = _tool_results(llm.requests[-1])
assert results["list"] == "Tables:\n- public.orders\n- public.users"
assert all(
"non-empty" in results[key] for key in ("recovery-list", "legacy", "empty")
)
assert "unknown table: missing" in results["failed"]
assert "unknown table: missing" in results["partial"]
assert "- amount: numeric" in results["partial"]
assert ctx.explorer.described == ["missing", "missing", "public.orders"]
@pytest.mark.parametrize(
("tables", "reason"),
[
(["missing"], "no table columns obtained"),
(["orders"], "rewritten final answer"),
],
)
def test_recovery_respects_existing_turn_budget(tables, reason):
llm = ScriptedOpenAI(
_answer(_STALE_SQL), _calls(("retry", "explore_schema", {"tables": tables}))
)
ctx = _context_for(llm, max_turns=2)
answer = asyncio.run(agent_loop(ctx, "Show order amounts"))
assert reason in answer
assert _STALE_SQL not in answer
assert _choices(llm) == [None, _FORCED]
assert ctx.session.history()[-1].content == answer
def test_legacy_adapter_returns_reason_when_required_tool_choice_is_unavailable():
class LegacyLLM:
async def complete(self, messages, tools=()):
assert messages[-1].role == Role.USER
return Completion(content=_STALE_SQL)
ctx = _context_for(LegacyLLM())
answer = asyncio.run(agent_loop(ctx, "Show order amounts"))
assert "model adapter cannot require schema lookup" in answer
assert ctx.session.history()[-1].content == answer
@pytest.mark.parametrize(
"sql",
[
"SELECT (SELECT amount FROM orders)",
"/* order totals */ WITH amounts AS NOT MATERIALIZED "
'(SELECT amount FROM "orders") SELECT * FROM amounts',
],
)
def test_nested_table_sources_trigger_recovery(sql):
llm = ScriptedOpenAI(
_calls(("draft", "run_sql", {"sql": sql})), _calls(_SCHEMA), _answer(_SQL)
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL
assert _choices(llm) == [None, _FORCED, None]
assert ctx.explorer.executed == []
def test_schema_response_without_columns_requires_recovery():
class EmptyTableExplorer(RecordingExplorer):
async def describe_table(self, name):
if name == "empty":
return Table(name="empty")
return await super().describe_table(name)
llm = ScriptedOpenAI(
_calls(("empty", "explore_schema", {"table": "empty"})),
_answer(_STALE_SQL),
_calls(_SCHEMA),
_answer(_SQL),
)
ctx = _context_for(llm)
ctx.explorer = EmptyTableExplorer()
assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL
assert "(no columns)" in _tool_results(llm.requests[1])["empty"]
assert _choices(llm) == [None, None, _FORCED, None]
def test_prompt_with_actual_columns_allows_sql_on_the_first_call():
llm = ScriptedOpenAI(_calls(("sql", "run_sql", {"sql": _SQL})), _answer(_SQL))
ctx = _context_for(llm)
ctx.store.kv_set(ctx.identity.kv_scope, "schema_relationships", '["orders"]')
assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL
assert _choices(llm) == [None, None]
assert "- amount" in llm.requests[0]["messages"][0]["content"]
assert len(ctx.explorer.executed) == 1
def test_prompt_guides_the_next_model_call_after_run_sql():
question = "Show order amounts."
answer = "Here are the order amounts."
llm = ScriptedOpenAI(
_calls(_SCHEMA),
_calls(("sql", "run_sql", {"sql": _SQL})),
_answer(answer),
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, question)) == answer
_, _, after_sql = llm.requests
system, user, *_ = after_sql["messages"]
assert "compare the original question, the executed SQL" in system["content"]
assert "distinguishing a zero aggregate from no returned rows" in system["content"]
assert "correct it and run the query again" in system["content"]
assert user == {"role": "user", "content": question}
result = _tool_results(after_sql)["sql"]
assert "row(s):" in result
assert f"SQL: {ctx.explorer.executed[0]}" in result
def test_column_results_are_scoped_to_the_current_user_turn():
llm = ScriptedOpenAI(
_calls(_SCHEMA),
_answer(_SQL),
_answer(_STALE_SQL),
_calls(("next-turn-columns", "explore_schema", {"tables": ["orders"]})),
_answer(_SQL),
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Show order amounts")) == _SQL
assert asyncio.run(agent_loop(ctx, "Show order amounts again")) == _SQL
assert _choices(llm) == [None, None, None, _FORCED, None]
@pytest.mark.parametrize(
"answer",
[
"Hello. How can I help?",
"Which definition of revenue should I use?",
f"For example, you can write:\n```sql\n{_SQL}\n```",
"Select a date from the list.",
"SELECT 'FROM orders' AS example",
"SELECT EXTRACT(YEAR FROM CURRENT_DATE)",
"SELECT 42 IS DISTINCT FROM 7",
"SELECT * FROM (SELECT 42 AS amount)",
],
)
def test_general_answers_remain_automatic(answer):
llm = ScriptedOpenAI(_answer(answer))
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Help me understand my options")) == answer
assert _choices(llm) == [None]
def test_run_sql_allows_queries_without_table_sources():
sql = "SELECT EXTRACT(YEAR FROM CURRENT_DATE)"
llm = ScriptedOpenAI(
_calls(("current-year", "run_sql", {"sql": sql})), _answer("Current year.")
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Read the current year")) == "Current year."
assert _choices(llm) == [None, None]
assert len(ctx.explorer.executed) == 1
assert sql in ctx.explorer.executed[0]
def test_term_custom_and_enrich_keep_their_existing_calls():
llm = ScriptedOpenAI(
_calls(
(
"term",
"term_custom",
{
"term": "net revenue",
"definition": "Exclude refunds",
"layer": "user",
},
),
("enrich", "enrich_schema", {}),
),
_answer('{"columns": {"orders.amount": "Order total"}, "relationships": []}'),
_answer("Saved the definition."),
)
ctx = _context_for(llm)
assert asyncio.run(agent_loop(ctx, "Save net revenue and enrich the schema.")) == (
"Saved the definition."
)
assert _choices(llm) == [None, None, None]
assert "tools" not in llm.requests[1]
assert "Exclude refunds" in _tool_results(llm.requests[2])["term"]
assert "orders.amount: Order total" in _tool_results(llm.requests[2])["enrich"]
def test_cli_and_discord_natural_language_use_schema_recovery(monkeypatch, capsys):
cli_model = ScriptedOpenAI(_answer(_STALE_SQL), _calls(_SCHEMA), _answer(_SQL))
cli_concierge = ContextConcierge(llm=cli_model, explorer=RecordingExplorer())
monkeypatch.setattr(app, "ContextConcierge", lambda: cli_concierge)
assert app.main(["Show", "order", "amounts"]) == 0
assert capsys.readouterr().out == f"{_SQL}\n"
assert _choices(cli_model) == [None, _FORCED, None]
assert cli_model.requests[0]["messages"][-1]["content"] == "Show order amounts"
discord_model = ScriptedOpenAI(_answer(_STALE_SQL), _calls(_SCHEMA), _answer(_SQL))
concierge = ContextConcierge(llm=discord_model, explorer=RecordingExplorer())
identity = Identity(
user_id="tester", guild_id="shop", channel_id="analytics", is_admin=True
)
async def run_discord():
response = await CommandHandlers(concierge).query(
identity, "Show order amounts"
)
session = await concierge.store.load(identity.session_key())
return response, session
response, session = asyncio.run(run_discord())
assert response.text == _SQL
assert _choices(discord_model) == [None, _FORCED, None]
assert [message.content for message in session.history()] == [
"Show order amounts",
_SQL,
]