合入完整性修复 F3:Agent 查库的模板也记目录版本并提醒「可能涉及」,只探查了部分表时清单、目录页和助手上下文都说明,升级入口接上 SQL 检查,截断判定和工具节点遍历各收成一处

This commit is contained in:
ThearchyHelios
2026-10-04 01:28:59 +08:00
24 changed files with 1032 additions and 222 deletions
+37
View File
@@ -183,3 +183,40 @@ def test_graph_sql_tables_uses_the_evidence_rules():
))
tables = {"shop": {"orders": {}, "order_items": {}, "customers": {}}, "other": {"orders": {}}}
assert graph_sql_tables(spec, tables) == {"shop": {"orders", "order_items", "customers"}, "other": {"orders"}}
def test_assistant_seeds_read_tool_nodes_the_same_way():
"""助手给全字段的「现有工作流用到的表」和发布记录、SQL 检查认的是同一种节点(sqlcheck.tool_query)。
画布上把调用工具节点换成别的类型,配置里的 tool、args 还留着:那已经不是一条会执行的查询,不能当成用到的表。
"""
from app.api.copilot_context import graph_tables
shop = SimpleNamespace(name="shop", schema_cache={"tables": {
"orders": {"qualified": "orders"}, "customers": {"qualified": "customers"}, "stores": {"qualified": "stores"}}})
graph = _graph(
_query("q1", "shop", "SELECT * FROM customers c JOIN orders o ON o.customer_id = c.id"),
# 换成了 Agent 的节点:残留的写死查询不算
_node("ask", "agent", tool="db_query__shop", args={"sql": "SELECT * FROM stores"}, tools=["db_query__shop"]),
# GraphSpec 的写法(config 在节点上)照样认
{"id": "q2", "type": "tool", "config": {"tool": "db_query__shop", "args": {"sql": "SELECT * FROM stores"}}},
_query("q3", "shop", " "),
)
assert graph_tables(graph, [shop]) == {"shop": ["customers", "orders", "stores"]}
graph["nodes"] = [n for n in graph["nodes"] if n["id"] != "q2"]
assert graph_tables(graph, [shop]) == {"shop": ["customers", "orders"]}
def test_recorded_versions_reads_both_shapes():
"""发布记录两种写法:现在的 {direct, possible},和可能涉及上线之前只记直接引用的 {源名: {表名: 版本}}。
源名可以就叫 direct / possible,靠第二层是不是版本号分开。"""
from app.data.catalog_impact import recorded_versions
now = {"direct": {"shop": {"orders": 2}}, "possible": {"shop": {"customers": 1}, "crm": {}}}
assert recorded_versions(now) == now
assert recorded_versions({"direct": {}, "possible": {}}) == {"direct": {}, "possible": {}}
assert recorded_versions({"shop": {"orders": 2}}) == {"direct": {"shop": {"orders": 2}}, "possible": {}}
# 旧写法里一个叫 direct 的源
assert recorded_versions({"direct": {"orders": 2}}) == {"direct": {"direct": {"orders": 2}}, "possible": {}}
assert recorded_versions({}) == {"direct": {}, "possible": {}}
assert recorded_versions(None) is None and recorded_versions("x") is None and recorded_versions({"shop": 3}) is None
+156 -15
View File
@@ -1,10 +1,14 @@
"""发布时记下目录版本,正式运行时提示目录的变化(阶段 4A)。
- 发布(把某一版立为正式版本)时,记下这个模板 SQL 用到的每张表的目录版本 {源名: {表名: 版本}},存在
workflow_versions.catalog_versions;还没有目录的表记 0(之后补了目录也算变化)。
- 从这一版发起正式运行时和当前的目录版本比:有变化发一条 catalog.drift 事件(列出表和前后版本),**不拦运行**;
目录没变不发。
- 发布(把某一版立为正式版本)时,记下这个模板用到的表的目录版本,存在 workflow_versions.catalog_versions,
分两组:{"direct": {源名: {表名: 版本}}, "possible": {源名: {表名: 版本}}}。
- direct:调用工具节点写死的 SQL 用到的表;还没有目录的表记 0(之后补了目录也算变化)。
- possible:Agent 节点、协作成员绑定了某个源的查询工具——SQL 运行时才写,发布时记下这个源里所有有目录的表
(直接引用的不重复记)。之后新建了目录的表同样算变化。
- 从这一版发起正式运行时和当前的目录版本比:有变化发一条 catalog.drift 事件(列出表、前后版本、属于哪一组),
**不拦运行**;目录没变不发。
- 版本详情给出发布时的目录版本,以及哪些表在那之后变了。
- 没有记录的老版本不提醒;只有直接引用那一种写法({源名: {表名: 版本}})的记录照旧按直接引用比,不提醒可能涉及。
"""
from __future__ import annotations
@@ -81,18 +85,52 @@ def node(nid, ntype, **config):
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
def _chain(*nodes) -> dict:
return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]}
def daily(source: str) -> dict:
nodes = [
return _chain(
node("start", "input"),
node("fetch", "tool", tool=f"db_query__{source}", args={"sql": SQL}),
node("out", "output", fields=[{"name": "结果", "value": "{{ nodes.fetch }}"}]),
]
return {"nodes": nodes, "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]}
)
async def _publish(client, source) -> str:
def agent_only(source: str) -> dict:
"""SQL 只写在 Agent 里:图上没有一条写死的查询。"""
return _chain(
node("start", "input"),
node("ask", "agent", prompt="查一下昨天各景区的入园人数", tools=[f"db_query__{source}"]),
node("out", "output", fields=[{"name": "结果", "value": "{{ nodes.ask.text }}"}]),
)
def team(source: str) -> dict:
"""协作成员里有一个绑定了查询工具。"""
return _chain(
node("start", "input"),
node("crew", "supervisor", agents=[
{"name": "取数员", "prompt": "查入园人数", "tools": [f"db_query__{source}"]},
{"name": "撰稿人", "prompt": "写一句总结", "tools": []},
]),
node("out", "output", fields=[{"name": "结果", "value": "{{ nodes.crew.text }}"}]),
)
def mixed(source: str) -> dict:
"""写死的查询用到入园记录和景区,Agent 还绑着同一个源。"""
return _chain(
node("start", "input"),
node("fetch", "tool", tool=f"db_query__{source}", args={"sql": SQL}),
node("ask", "agent", prompt="再看看别的表", tools=[f"db_query__{source}"]),
node("out", "output", fields=[{"name": "结果", "value": "{{ nodes.ask.text }}"}]),
)
async def _publish(client, source, graph: dict | None = None) -> str:
wf = (await client.post("/api/workflows", json={"name": f"入园日报-{uuid.uuid4().hex[:6]}",
"graph": daily(source.name)})).json()["id"]
"graph": graph or daily(source.name)})).json()["id"]
source.made.append(wf)
body = (await client.post(f"/api/workflows/{wf}/publish", json={"level": "published"})).json()
assert body["ok"] is True, body
@@ -106,12 +144,13 @@ async def _events(run_id: str, kind: str) -> list[dict]:
return [e.data for e in rows]
async def _settle(run_id: str) -> Run:
async def _settle(run_id: str, *, sealed: bool = True) -> Run:
"""等运行结束。sealed=False 时不等封存:Agent 没有可用的模型,跑到它那一步就失败,只看开头的事件。"""
for _ in range(400):
await asyncio.sleep(0.05)
async with SessionLocal() as session:
row = await session.get(Run, run_id)
if row.status in ("succeeded", "failed") and row.manifest_seq is not None:
if row.status in ("succeeded", "failed") and (row.manifest_seq is not None or not sealed):
return row
raise AssertionError(f"run {run_id} 没跑完:{row.status}")
@@ -125,15 +164,35 @@ async def _edit_visits(source_id: str) -> int:
return saved.version
async def _recorded(wf: str) -> dict | None:
async with SessionLocal() as session:
return (await session.execute(select(WorkflowVersion.catalog_versions).where(
WorkflowVersion.workflow_id == wf, WorkflowVersion.version == 1))).scalar_one()
async def _catalogued(source_id: str) -> dict[str, int]:
"""这个源现在所有有目录的表:{表名: 版本}。"""
async with SessionLocal() as session:
return {t: e.version for t, e in (await catalog.read_catalog(session, source_id)).items()}
async def _formal(client, wf: str, *, sealed: bool = True) -> str:
r = await client.post("/api/runs", json={"workflow_id": wf, "run_class": "formal"})
assert r.status_code == 201, r.text # 不拦
run_id = r.json()["id"]
await _settle(run_id, sealed=sealed)
return run_id
async def test_publish_records_catalog_versions(client, source):
wf = await _publish(client, source)
async with SessionLocal() as session:
snap = (await session.execute(select(WorkflowVersion).where(
WorkflowVersion.workflow_id == wf, WorkflowVersion.version == 1))).scalar_one()
# 入园记录有目录(第 1 版);景区表还没有目录,记 0
assert snap.catalog_versions == {source.name: {"parks": 0, "visits": 1}}
# 入园记录有目录(第 1 版);景区表还没有目录,记 0。没有 Agent 查库,可能涉及的一组是空的
assert snap.catalog_versions == {"direct": {source.name: {"parks": 0, "visits": 1}}, "possible": {}}
detail = (await client.get(f"/api/workflows/{wf}/versions/1")).json()
assert detail["catalog_versions"] == {source.name: {"parks": 0, "visits": 1}}
assert detail["catalog_versions"] == {"direct": {source.name: {"parks": 0, "visits": 1}}, "possible": {}}
assert detail["catalog_changes"] == []
@@ -149,7 +208,7 @@ async def test_formal_run_warns_on_catalog_change_but_runs(client, source):
assert drift["count"] == 1 and drift["version"] == 1
[table] = drift["tables"]
assert table == {"source": source.name, "source_id": source.id, "table": "visits", "label": "入园记录",
"published": 1, "current": now}
"published": 1, "current": now, "impact": "direct"}
# 版本详情也写明哪些表在发布之后变了
detail = (await client.get(f"/api/workflows/{wf}/versions/1")).json()
assert [(c["table"], c["published"], c["current"]) for c in detail["catalog_changes"]] == [("visits", 1, now)]
@@ -167,6 +226,88 @@ async def test_catalog_added_after_publish_counts_as_change(client, source):
assert [(t["table"], t["published"], t["current"], t["label"]) for t in drift["tables"]] == [("parks", 0, 1, "景区")]
# --------------------------------------------------------------------------
# SQL 只写在 Agent 里:可能涉及的表
# --------------------------------------------------------------------------
async def test_agent_only_template_records_every_catalogued_table_as_possible(client, source):
"""影响面把绑定了查询工具的 Agent 算作「可能涉及」,发布记录得是同一个说法:记下这个源所有有目录的表。"""
wf = await _publish(client, source, agent_only(source.name))
recorded = await _recorded(wf)
assert recorded == {"direct": {}, "possible": {source.name: await _catalogued(source.id)}}
assert "visits" in recorded["possible"][source.name] and "parks" not in recorded["possible"][source.name]
detail = (await client.get(f"/api/workflows/{wf}/versions/1")).json()
assert detail["catalog_versions"] == recorded and detail["catalog_changes"] == []
async def test_agent_only_template_warns_after_a_catalog_change(client, source):
wf = await _publish(client, source, agent_only(source.name))
now = await _edit_visits(source.id)
run_id = await _formal(client, wf, sealed=False)
[drift] = await _events(run_id, "catalog.drift")
assert drift["count"] == 1
assert drift["tables"] == [{"source": source.name, "source_id": source.id, "table": "visits", "label": "入园记录",
"published": 1, "current": now, "impact": "possible"}]
detail = (await client.get(f"/api/workflows/{wf}/versions/1")).json()
assert [(c["table"], c["impact"]) for c in detail["catalog_changes"]] == [("visits", "possible")]
async def test_catalog_created_after_publish_counts_for_possible_tables(client, source):
"""发布时没有目录的表不逐张记 0(一个库几百张表),之后有人给它建了目录同样算变化。"""
wf = await _publish(client, source, agent_only(source.name))
async with SessionLocal() as session:
await catalog.write_entry(session, source.id, "parks", {"label": catalog.make_item("景区", "human")},
if_version=0, actor="王敏")
run_id = await _formal(client, wf, sealed=False)
[drift] = await _events(run_id, "catalog.drift")
assert [(t["table"], t["published"], t["current"], t["impact"]) for t in drift["tables"]] == [
("parks", 0, 1, "possible")]
async def test_team_members_with_the_query_tool_count_as_possible(client, source):
wf = await _publish(client, source, team(source.name))
assert await _recorded(wf) == {"direct": {}, "possible": {source.name: await _catalogued(source.id)}}
async def test_direct_tables_are_not_repeated_as_possible(client, source):
"""同一个源既有写死的查询、又有 Agent:写死的 SQL 用到的表按直接引用记,可能涉及里不再记一遍。"""
wf = await _publish(client, source, mixed(source.name))
recorded = await _recorded(wf)
assert recorded["direct"] == {source.name: {"parks": 0, "visits": 1}}
rest = {t: v for t, v in (await _catalogued(source.id)).items() if t not in ("parks", "visits")}
assert recorded["possible"] == {source.name: rest} and rest
now = await _edit_visits(source.id)
async with SessionLocal() as session:
await catalog.write_entry(session, source.id, "parks", {"label": catalog.make_item("景区", "human")},
if_version=0, actor="王敏")
run_id = await _formal(client, wf, sealed=False)
[drift] = await _events(run_id, "catalog.drift")
# 两张都是直接引用:parks 新建了目录也不会再按可能涉及报一遍
assert [(t["table"], t["published"], t["current"], t["impact"]) for t in drift["tables"]] == [
("parks", 0, 1, "direct"), ("visits", 1, now, "direct")]
async def test_direct_only_records_from_before_still_warn_as_direct(client, source):
"""可能涉及上线之前发布的版本只记了直接引用({源名: {表名: 版本}}):照旧按直接引用比,不补可能涉及。"""
wf = await _publish(client, source, mixed(source.name))
async with SessionLocal() as session:
snap = (await session.execute(select(WorkflowVersion).where(
WorkflowVersion.workflow_id == wf, WorkflowVersion.version == 1))).scalar_one()
snap.catalog_versions = {source.name: {"parks": 0, "visits": 1}}
await session.commit()
detail = (await client.get(f"/api/workflows/{wf}/versions/1")).json()
assert detail["catalog_versions"] == {"direct": {source.name: {"parks": 0, "visits": 1}}, "possible": {}}
now = await _edit_visits(source.id)
async with SessionLocal() as session:
await catalog.write_entry(session, source.id, "gates", {"label": catalog.make_item("闸机", "human")},
if_version=0, actor="王敏")
run_id = await _formal(client, wf, sealed=False)
[drift] = await _events(run_id, "catalog.drift")
assert [(t["table"], t["impact"]) for t in drift["tables"]] == [("visits", "direct")]
assert drift["tables"][0]["current"] == now
async def test_no_change_no_warning(client, source):
wf = await _publish(client, source)
r = await client.post("/api/runs", json={"workflow_id": wf, "run_class": "formal"})
@@ -0,0 +1,116 @@
"""没探查到的表要说出来(数据目录完整性审查 F3 / B4)。
探查结构每个数据源最多取 200 张表(introspect._MAX_TABLES)。多出来的表不在表结构缓存里:目录页列不出,助手也
看不到字段。以前这件事哪儿都没说——目录清单只给探查到的 200 行,助手上下文里的「共几张表」是探查到的张数,
提示词里也不提。这组守的是:
- 目录清单接口返回 schema_truncated、schema_total(数据库里一共几张),界面据此说明「只探查了前 200 张」
- 助手上下文的 total 是表结构缓存里的真实总数;context 操作里带上 explored(探查到几张)
- 提示词里写明还有几张没探查到,遇到不认识的表名先查结构
- 没截断的库照旧,不多说一句
合成库:205 张空表,测试里临时建,用完连同数据源一起删掉。
"""
from __future__ import annotations
import sqlite3
import uuid
import pytest
from httpx import ASGITransport, AsyncClient
from app.db.base import SessionLocal
from app.db.models import DataSource
from app.main import app
from tests.fixtures.sources import drop_source
WIDE = 205
def _build(path, count: int) -> str:
db = sqlite3.connect(path)
for i in range(count):
db.execute(f"CREATE TABLE t{i:03d} (id INTEGER PRIMARY KEY, amount INTEGER)")
db.commit()
db.close()
return str(path)
@pytest.fixture
async def client():
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
async def _source(client, path: str) -> tuple[str, str]:
name = f"wide_{uuid.uuid4().hex[:8]}"
r = await client.post("/api/datasources", json={"name": name, "kind": "sqlite", "database": path,
"readonly": True})
assert r.status_code in (200, 201), r.text
sid = r.json()["id"]
r = await client.post(f"/api/datasources/{sid}/introspect")
assert r.status_code == 200, r.text
return sid, name
@pytest.fixture
async def wide(client, tmp_path):
sid, name = await _source(client, _build(tmp_path / "wide.db", WIDE))
yield sid, name
await drop_source(sid)
@pytest.fixture
async def narrow(client, tmp_path):
sid, name = await _source(client, _build(tmp_path / "narrow.db", 3))
yield sid, name
await drop_source(sid)
async def _row(sid: str) -> DataSource:
async with SessionLocal() as session:
row = await session.get(DataSource, sid)
session.expunge(row)
return row
async def test_catalog_list_says_how_many_tables_were_not_introspected(client, wide):
sid, _ = wide
body = (await client.get(f"/api/datasources/{sid}/catalog")).json()
assert len(body["tables"]) == 200
assert body["schema_truncated"] is True and body["schema_total"] == WIDE
async def test_catalog_list_of_a_complete_schema(client, narrow):
sid, _ = narrow
body = (await client.get(f"/api/datasources/{sid}/catalog")).json()
assert len(body["tables"]) == 3
assert body["schema_truncated"] is False and body["schema_total"] == 3
async def test_assistant_context_counts_the_real_total(wide):
from app.api import copilot_context
sid, name = wide
plan = await copilot_context.plan_context([await _row(sid)])
ctx = plan.fallback("测试")
(row,) = ctx.op()["sources"]
assert row["total"] == WIDE and row["explored"] == 200
text = ctx.section()
assert f"共 {WIDE} 张表" in text and "只探查了 200 张" in text and f"还有 {WIDE - 200} 张没有探查到" in text
# 遇到不认识的表名先查结构,别猜
assert f"db_schema__{name}" in text and "information_schema" in text
# 挑表的请求里也写明只列了探查到的
pick = plan._pick_messages("各表的金额")[1][1]
assert f"共 {WIDE} 张表,只探查了 200 张" in pick
async def test_assistant_context_of_a_complete_schema_says_nothing_extra(narrow):
from app.api import copilot_context
sid, _ = narrow
plan = await copilot_context.plan_context([await _row(sid)])
ctx = await plan.resolve(None, need="x")
(row,) = ctx.op()["sources"]
assert row["total"] == 3 and "explored" not in row
assert "没有探查到" not in ctx.section()
+51
View File
@@ -241,3 +241,54 @@ async def test_clean_sql_costs_no_extra_call(scenic_source, monkeypatch):
final = events[-1]
assert final["autorun"] is True
assert not [i for i in final["issues"] if i.get("code") in ("fanout_sum", "missing_valid_filter")]
# --------------------------------------------------------------------------
# 一键升级的语义层(assist_upgrade):自查和最终判断同样带 SQL 检查器,和发布门禁一个口径
# --------------------------------------------------------------------------
def _upgrade_graph(source: str) -> dict:
"""查库 → 沙箱代码算比率 → 口径卡读代码的产出 → 报告撰写 → 出口。查库的 SQL 本身没问题。"""
def n(nid, ntype, x, **config):
return {"id": nid, "type": ntype, "position": {"x": x, "y": 80}, "data": {"label": nid, "config": config}}
nodes = [
n("start", "input", 0),
n("fetch", "tool", 280, tool=f"db_query__{source}", args={"sql": CLEAN_SQL}),
n("calc", "code", 560, language="python", assign_to="calc", code="import json\nprint(json.dumps({'ratio': 3 / 4}))"),
n("card", "metrics", 840, metrics=[{"id": "ratio", "name": "客单价", "expression": "vars.calc.ratio"}]),
n("write", "report", 1120, instructions="写一句话"),
n("out", "output", 1400, fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]),
]
return {"nodes": nodes, "edges": [{"id": f"e{i}", "source": a["id"], "target": b["id"]}
for i, (a, b) in enumerate(zip(nodes, nodes[1:]))]}
async def test_upgrade_assist_checks_sql_like_the_publish_gate(scenic_source, monkeypatch):
"""助手改写口径卡时顺手把查询改成了一对多关联后求和:受管级别的发布门禁会挡,升级的自查也得交回去改,
改不好就作废——以前自查和最终判断都没带 SQL 检查器,这样的改写会被采纳,交出去的图发布时才被拦。"""
import app.api.copilot as copilot
from app.db.base import SessionLocal
first = [{"op": "plan", "summary": "把纯算术的代码挪进口径卡"},
{"op": "update_node", "id": "card", "config": {"metrics": [
{"id": "ratio", "name": "客单价", "expression": "cell(nodes.fetch, 0, 'gmv') / 4"}]}},
{"op": "update_node", "id": "fetch", "config": {"args": {"sql": FANOUT_SQL}}},
{"op": "done", "explanation": "客单价改由口径卡直接算"}]
fix = [{"op": "update_node", "id": "fetch", "config": {"args": {"sql": FANOUT_SQL + " "}}},
{"op": "done", "explanation": "改了"}]
model = _Scripted(first, fix)
async def _model(*_a, **_k):
return model, "mock-fast"
monkeypatch.setattr(copilot, "get_chat_model", _model)
async with SessionLocal() as session:
out = await copilot.assist_upgrade(session, _upgrade_graph(scenic_source), level="governed")
# 自查把一对多求和交回模型,带着给模型的改法
assert len(model.calls) >= 2 and "上线前自查" in model.calls[1]
assert "orders 关联 order_items 是一对多" in model.calls[1]
# 改不好:整个作废,原因写的是这条 SQL 检查
assert out["accepted"] is False and out["ok"] is False
assert "一对多" in (out["reason"] or ""), out["reason"]
+33
View File
@@ -225,6 +225,39 @@ def test_byte_limit_matches_the_query_layer():
assert out.truncated is True and 0 < len(out.rows) < 16
def test_row_collector_is_the_one_cutoff_rule():
"""截断判定只有一份(data.engine.RowCollector):到了行数或字节上限之后确实还有下一行才算截断,恰好取满不算;
第一行总是收下(单行就超过字节上限也得交回点什么)。"""
from app.data.engine import RowCollector
full = RowCollector(QueryLimits(max_rows=2))
assert full.take([1]) and full.take([2])
assert full.rows == [[1], [2]] and full.truncated is False # 恰好取满、后面没有了
assert full.take([3]) is False # 取满之后还有一行:截断,这一行不收
assert full.rows == [[1], [2]] and full.truncated is True
tiny = RowCollector(QueryLimits(max_bytes=5))
assert tiny.take(["一行就超过字节上限"]) is True and tiny.take(["下一行"]) is False
assert len(tiny.rows) == 1 and tiny.truncated is True
def test_merge_reads_through_the_query_layer_cutoff(monkeypatch):
"""合并查询调用查询层的判定,不另写一遍:两边的口径不会再各改各的。"""
import app.engine.merge_query as merge_query
from app.data.engine import RowCollector
made: list[RowCollector] = []
class Spy(RowCollector):
def __init__(self, limits):
super().__init__(limits)
made.append(self)
monkeypatch.setattr(merge_query, "RowCollector", Spy)
out = execute([sales(), visits()], "SELECT * FROM s CROSS JOIN v", limits=QueryLimits(max_rows=5))
assert len(made) == 1 and made[0].truncated is True and len(out.rows) == len(made[0].rows) == 5
def test_runaway_query_is_stopped():
endless = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT count(*) FROM c"
with pytest.raises(MergeError, match="秒"):