mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-23 09:52:02 +00:00
合入集成分支 feat/data-catalog(d897981,含 F2a 的证据面板、时间线和服务端修复):自动合并,没有冲突;catalog_profile._relation_finding 两边的改动(F2b 的 previous_status、F2a 的 cardinality_checked 写在关系上)互不重叠
This commit is contained in:
+41
-6
@@ -3,28 +3,63 @@
|
||||
model = FakeModel({"visits": {"label": "入园记录", "kind": "fact"}}, fail={"orders"})
|
||||
await catalog.draft_with_model(model, source, ["visits"])
|
||||
|
||||
- 结构化输出(with_structured_output)返回自己;ainvoke 从提示词里认出这一批有哪些表(「表 <表名>」),
|
||||
- 结构化输出(with_structured_output(...).ainvoke)从提示词里认出这一批有哪些表(「表 <表名>」),
|
||||
返回 {"tables": [{"table": 表名, **replies[表名]}, …]};
|
||||
- 直接 ainvoke 是纯文本那条路:同样的内容写成一段正文(AIMessage),前面带一句话;
|
||||
- fail 里的表所在的那一批抛异常,用来验证「一批失败只影响这一批」;
|
||||
- calls 记下每次收到的提示词全文,用来核对交给模型的内容(只有结构,没有数据)。
|
||||
- calls 记下每次收到的提示词全文,用来核对交给模型的内容(只有结构,没有数据);modes 记下每次走的是
|
||||
structured 还是 text。
|
||||
|
||||
structured、text 模拟实测见过的几种回复(两条路各自设):
|
||||
|
||||
- "tables":正常,{"tables": [...]};
|
||||
- "hollow":退化的空壳,表名对上了、一个字段都没有:{"tables": [{"table": 表名}, …]};
|
||||
- "single":只给第一张表的对象,没有 tables 外壳:{"table": 表名, …};
|
||||
- "error":这条路用不了(网关不支持工具调用之类),一调就抛异常。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
class FakeModel:
|
||||
def __init__(self, replies: dict[str, dict], fail: set[str] = frozenset()) -> None:
|
||||
def __init__(self, replies: dict[str, dict], fail: set[str] = frozenset(), *,
|
||||
structured: str = "tables", text: str = "tables") -> None:
|
||||
self.replies, self.fail, self.calls = replies, set(fail), []
|
||||
self.structured, self.text = structured, text
|
||||
self.modes: list[str] = []
|
||||
|
||||
def with_structured_output(self, schema: Any, **_: Any) -> "FakeModel":
|
||||
def with_structured_output(self, schema: Any, **_: Any) -> "_Structured":
|
||||
assert schema["title"]
|
||||
return self
|
||||
return _Structured(self)
|
||||
|
||||
async def ainvoke(self, messages: list[Any]) -> dict:
|
||||
async def ainvoke(self, messages: list[Any]) -> Any:
|
||||
from langchain_core.messages import AIMessage
|
||||
|
||||
reply = self._reply(messages, "text")
|
||||
return AIMessage(content="草稿如下:" + json.dumps(reply, ensure_ascii=False))
|
||||
|
||||
def _reply(self, messages: list[Any], mode: str) -> dict:
|
||||
text = "\n".join(str(getattr(m, "content", m)) for m in messages)
|
||||
self.calls.append(text)
|
||||
self.modes.append(mode)
|
||||
names = [t for t in self.replies if f"表 {t}\n" in text or f"表 {t}(" in text]
|
||||
if any(t in self.fail for t in names):
|
||||
raise RuntimeError("网关超时")
|
||||
shape = self.structured if mode == "structured" else self.text
|
||||
if shape == "error":
|
||||
raise NotImplementedError("这条路用不了")
|
||||
if shape == "hollow":
|
||||
return {"tables": [{"table": t} for t in names]}
|
||||
if shape == "single":
|
||||
return {"table": names[0], **self.replies[names[0]]} if names else {}
|
||||
return {"tables": [{"table": t, **self.replies[t]} for t in names]}
|
||||
|
||||
|
||||
class _Structured:
|
||||
def __init__(self, owner: FakeModel) -> None:
|
||||
self.owner = owner
|
||||
|
||||
async def ainvoke(self, messages: list[Any]) -> dict:
|
||||
return self.owner._reply(messages, "structured")
|
||||
|
||||
@@ -162,6 +162,9 @@ async def test_draft_defaults_to_top_tables_and_model_via_settings(client, sourc
|
||||
body = r.json()
|
||||
assert len(body["tables"]) == 20 and body["tables"][0]["table_name"] == "visits"
|
||||
assert body["model_used"] is True and body["model"] == "fake-model"
|
||||
# 每张表模型给了几项可用内容:模型给了内容的表是正数;回复里没有的表记 model_error,没有这个数
|
||||
assert body["tables"][0]["model_items"] == 2 and body["tables"][0]["model_error"] is None
|
||||
assert all(t["model_items"] is None and t["model_error"] for t in body["tables"][1:])
|
||||
detail = (await client.get(f"{_base(source_id)}/visits")).json()
|
||||
assert detail["notes"]["label"]["source"] == "llm" and detail["usage"] == 7
|
||||
|
||||
|
||||
@@ -263,6 +263,41 @@ async def test_model_without_structured_output_falls_back_to_text():
|
||||
assert got["visits"].notes == {"label": make_item("入园记录", "llm")}
|
||||
|
||||
|
||||
# ---- 实测见过的几种退化回复(A2):一项都没写进去时不能说「没有变化」
|
||||
|
||||
|
||||
async def test_model_single_table_object_without_wrapper_is_recognized():
|
||||
"""纯文本兜底时只回了单个表对象,没有 tables 外壳:照样认出来。"""
|
||||
model = FakeModel({"visits": {"label": "入园记录"}}, structured="error", text="single")
|
||||
got = await catalog.draft_with_model(model, _source(_scenic_tables()), ["visits"])
|
||||
assert got["visits"].notes == {"label": make_item("入园记录", "llm")}
|
||||
|
||||
|
||||
async def test_hollow_structured_output_retries_with_text():
|
||||
"""结构化输出只给了 {"tables":[{"table":"visits"}]} 这样的空壳:改走纯文本再问一次,用纯文本给的内容。"""
|
||||
model = FakeModel({"visits": {"label": "入园记录", "kind": "fact"}}, structured="hollow", text="tables")
|
||||
got = await catalog.draft_with_model(model, _source(_scenic_tables()), ["visits"])
|
||||
assert model.modes == ["structured", "text"]
|
||||
assert got["visits"].notes == {"label": make_item("入园记录", "llm"), "kind": make_item("fact", "llm")}
|
||||
|
||||
|
||||
async def test_hollow_structured_then_single_text_object():
|
||||
model = FakeModel({"visits": {"label": "入园记录"}}, structured="hollow", text="single")
|
||||
got = await catalog.draft_with_model(model, _source(_scenic_tables()), ["visits"])
|
||||
assert got["visits"].notes == {"label": make_item("入园记录", "llm")}
|
||||
|
||||
|
||||
async def test_table_with_no_usable_content_is_a_model_error():
|
||||
"""表名对上了、一个字段都没有(两条路都是空壳):这张表记模型失败,不算起草成功。"""
|
||||
model = FakeModel({"visits": {"label": "入园记录"}}, structured="hollow", text="hollow")
|
||||
got = await catalog.draft_with_model(model, _source(_scenic_tables()), ["visits"])
|
||||
assert got["visits"] == catalog.MODEL_EMPTY_REASON
|
||||
# 给了字段、但没有一项合规(列名对不上、取值不在范围里)同样算没有可用内容
|
||||
junk = FakeModel({"visits": {"kind": "planet", "columns": [{"name": "ghost", "label": "不存在的列"}]}})
|
||||
got = await catalog.draft_with_model(junk, _source(_scenic_tables()), ["visits"])
|
||||
assert got["visits"] == catalog.MODEL_EMPTY_REASON
|
||||
|
||||
|
||||
async def test_model_draft_respects_system_notes_of_imported_tables():
|
||||
"""导入表格:表说明已经写了粒度、列说明写了单位,模型起草的粒度和单位不进目录,免得重复或矛盾。"""
|
||||
src = _source({"日报": _table(_col("日期", "TEXT", comment="格式 YYYY-MM-DD"), _col("客流"), pk=(),
|
||||
@@ -383,6 +418,30 @@ async def test_draft_catalog_model_failure_on_one_table(monkeypatch):
|
||||
assert by["channels"].model_error is None and by["channels"].added == 1
|
||||
|
||||
|
||||
async def test_draft_catalog_empty_model_reply_is_not_no_change():
|
||||
"""模型一项可用内容都没给:这张表记 model_error,没有 model_items,界面据此不说「没有变化」。
|
||||
模型给了内容、只是和现有目录一致:没有 model_error,model_items 是模型给的项数。"""
|
||||
row = await _db_source(_scenic_tables())
|
||||
hollow = FakeModel({"visits": {"label": "入园记录"}}, structured="hollow", text="hollow")
|
||||
async with SessionLocal() as session:
|
||||
report = await catalog.draft_catalog(session, row, tables=["visits"], use_model=True, model=hollow)
|
||||
result = report.tables[0]
|
||||
assert result.model_error == catalog.MODEL_EMPTY_REASON and result.model_items is None
|
||||
assert (result.added, result.updated, result.removed) == (0, 0, 0)
|
||||
|
||||
model = FakeModel({"visits": {"label": "入园记录", "kind": "fact"}})
|
||||
async with SessionLocal() as session:
|
||||
first = await catalog.draft_catalog(session, row, tables=["visits"], use_model=True, model=model)
|
||||
again = await catalog.draft_catalog(session, row, tables=["visits"], use_model=True, model=model)
|
||||
assert first.tables[0].model_items == 2 and first.tables[0].added == 2
|
||||
assert again.tables[0].model_error is None and again.tables[0].model_items == 2
|
||||
assert (again.tables[0].added, again.tables[0].updated, again.tables[0].removed) == (0, 0, 0)
|
||||
# 不用模型时没有这个数
|
||||
async with SessionLocal() as session:
|
||||
plain = await catalog.draft_catalog(session, row, tables=["visits"], use_model=False)
|
||||
assert plain.tables[0].model_items is None
|
||||
|
||||
|
||||
async def test_draft_catalog_defaults_to_most_used_tables(monkeypatch):
|
||||
tables = {f"t{i:02d}": _table(_col("id"), fks=[]) for i in range(25)}
|
||||
row = await _db_source(tables)
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import sqlite3
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -194,9 +195,15 @@ async def test_profile_verifies_name_relations_and_proposes_codes_and_business_d
|
||||
assert (rel["source"], rel["status"]) == ("profile", "verified")
|
||||
assert rel["coverage"] == 1.0 and rel["cardinality"] == "many_to_one"
|
||||
assert "数据剖析" in rel["note"] and "抽样" in rel["note"]
|
||||
# 子表一侧数过 COUNT 和 COUNT(DISTINCT)、确有重复:基数是用数据核实的(A6,一对多关联的检查据此给 error)
|
||||
assert rel["cardinality_checked"] is True
|
||||
# A7:说明里不写日期,时间看这一项的 updated_at(界面按本地时间显示)
|
||||
assert rel["note"].startswith("数据剖析:") and not re.search(r"\d{4}-\d{2}-\d{2}", rel["note"])
|
||||
assert rel["updated_at"]
|
||||
# 外键约束来的关系不动:外键是外键,剖析是剖析
|
||||
park = _relation(notes, "park_id")
|
||||
assert (park["source"], park["status"], park["coverage"]) == ("fk", "verified", None)
|
||||
assert "cardinality_checked" not in park # 外键的基数是按表结构推的,没用数据核对
|
||||
|
||||
# 状态列:码值候选,值有了、含义留空,推断
|
||||
codes = notes["columns"]["status"]["codes"]
|
||||
@@ -265,6 +272,8 @@ async def test_confirmed_relation_only_gets_coverage_and_cardinality(client, mak
|
||||
rel = _relation((await _notes(client, sid, "visits"))["notes"], "gate_id")
|
||||
assert (rel["source"], rel["status"]) == ("name", "confirmed")
|
||||
assert rel["coverage"] == 1.0 and rel["cardinality"] == "many_to_one"
|
||||
# 人定的基数不改;原来就有基数(命名推断记的多对一),剖析也不给它记「用数据核实过」
|
||||
assert "cardinality_checked" not in rel
|
||||
finding = next(f for f in _table(r.json(), "visits")["findings"] if f.get("columns") == ["gate_id"])
|
||||
assert finding["status"] == "confirmed" and finding["confirmed"] is True
|
||||
|
||||
@@ -381,9 +390,10 @@ async def test_large_tables_get_no_full_scans(client, make_source, scenic_db, sp
|
||||
assert not any("MIN(" in s for s in on_visits)
|
||||
assert "too_large" in _reasons(visits)
|
||||
assert any("太大" in s["detail"] or "上限" in s["detail"] for s in visits["skipped"] if s["reason"] == "too_large")
|
||||
# 父表有主键,覆盖率又够:照样有确证;子表一侧没核对唯一,按多对一记
|
||||
# 父表有主键,覆盖率又够:照样有确证;子表一侧没核对唯一,按多对一记,不算用数据核实过基数
|
||||
rel = _relation((await _notes(client, sid, "visits"))["notes"], "gate_id")
|
||||
assert rel["status"] == "verified" and rel["cardinality"] == "many_to_one"
|
||||
assert not rel.get("cardinality_checked")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 接口
|
||||
@@ -426,6 +436,69 @@ async def test_default_tables_are_used_tables_with_relation_candidates(client, m
|
||||
assert "parks" not in names and "channels" not in names # 没有待核实关系的表不选
|
||||
|
||||
|
||||
async def _candidates(sid: str) -> tuple[list[str], set[str]]:
|
||||
"""默认挑表的候选(目录里有要核对的关系的表,按表结构顺序)和其中还有待核实(推断)关系的那些。"""
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(DataSource, sid)
|
||||
entries = await catalog.read_catalog(session, sid)
|
||||
order = list((row.schema_cache or {}).get("tables") or {})
|
||||
rels = {name: catalog_profile._relation_candidates(entries[name].notes) for name in order if name in entries}
|
||||
names = [name for name in order if rels.get(name)]
|
||||
return names, {name for name in names if any(r["status"] == "proposed" for r in rels[name])}
|
||||
|
||||
|
||||
async def test_default_pick_skips_empty_tables_and_prefers_pending_relations(client, make_source, tmp_path,
|
||||
monkeypatch):
|
||||
"""B1:表都没被运行查询过(使用次数都是 0)时,以前按表结构顺序取前几张,结果大半是空表(景区库里排在前面的
|
||||
候选表正好多数没有数据)。现在跳过行数估计为 0 的表(记在 empty_tables 里),并且先挑还有待核实关系的表,
|
||||
不把刚核实过的再剖析一遍。默认张数调成 3,好在一个小库上看出先后。"""
|
||||
monkeypatch.setattr(catalog_profile, "PROFILE_DEFAULT_TABLES", 3)
|
||||
path = scenic.build(tmp_path / "b1.db")
|
||||
db = sqlite3.connect(path)
|
||||
try:
|
||||
tables = [r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY rowid")]
|
||||
empty = {t for t in tables if db.execute(f'SELECT COUNT(*) FROM "{t}"').fetchone()[0] == 0}
|
||||
finally:
|
||||
db.close()
|
||||
sid = await make_source(str(path), options=_on(), draft=tables)
|
||||
names, pending = await _candidates(sid)
|
||||
full = [name for name in names if name not in empty]
|
||||
# 前提:按表结构顺序的前 3 张候选里有空表(以前就会挑中它们),有数据、还待核实的候选不止 6 张
|
||||
assert set(names[:3]) & empty
|
||||
assert len([name for name in full if name in pending]) >= 6
|
||||
|
||||
first = (await client.post(_url(sid), json={}, headers=ACTOR)).json()
|
||||
picked = [t["table_name"] for t in first["tables"]]
|
||||
assert len(picked) == 3 and not set(picked) & empty, picked
|
||||
assert first["empty_tables"] and set(first["empty_tables"]) <= empty
|
||||
assert all(t["queries"] > 0 for t in first["tables"])
|
||||
assert first["queries_used"] >= sum(t["queries"] for t in first["tables"]) + len(first["empty_tables"])
|
||||
|
||||
# 第二次:先挑还有待核实关系的表;第一次核实过的(关系都升为有确证了)排到后面,这次挑不到
|
||||
names, pending = await _candidates(sid)
|
||||
assert not set(picked) & pending # 第一次挑的三张,关系都核实了
|
||||
second = (await client.post(_url(sid), json={}, headers=ACTOR)).json()
|
||||
again = [t["table_name"] for t in second["tables"]]
|
||||
assert len(again) == 3 and all(name in pending for name in again), (again, pending)
|
||||
assert not set(again) & set(picked) and not set(again) & empty
|
||||
|
||||
|
||||
async def test_profile_note_when_every_candidate_is_empty(client, make_source, tmp_path):
|
||||
path = scenic.build(tmp_path / "b1-empty.db")
|
||||
sid = await make_source(str(path), options=_on(), draft=[])
|
||||
names, _ = await _candidates(sid)
|
||||
db = sqlite3.connect(path)
|
||||
try:
|
||||
for name in names:
|
||||
db.execute(f'DELETE FROM "{name}"')
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
body = (await client.post(_url(sid), json={}, headers=ACTOR)).json()
|
||||
assert body["tables"] == [] and set(body["empty_tables"]) == set(names)
|
||||
assert "空表" in body["note"]
|
||||
|
||||
|
||||
async def test_unknown_table_and_missing_source(client, make_source, scenic_db):
|
||||
sid = await make_source(scenic_db, options=_on(), draft=["visits"])
|
||||
r = await client.post(_url(sid), json={"tables": ["nope"]}, headers=ACTOR)
|
||||
|
||||
@@ -146,7 +146,12 @@ def test_frozen_catalog_strips_rejected_and_keeps_versions():
|
||||
assert set(frozen) == {"visits"} # 表结构里没有的、全被驳回的都不冻结
|
||||
assert frozen["visits"]["version"] == 4
|
||||
assert "dedup" not in frozen["visits"]["notes"]
|
||||
assert len(frozen["visits"]["notes"]["relations"]) == 2
|
||||
# 两条没被驳回的关系原样冻结;驳回的那条只留编号和状态(重建检查器时不被按外键、命名推回来)
|
||||
relations = frozen["visits"]["notes"]["relations"]
|
||||
assert len([r for r in relations if r.get("status") != "rejected"]) == 2
|
||||
assert [r for r in relations if r.get("status") == "rejected"] == [
|
||||
{"id": r["id"], "status": "rejected"} for r in VISITS["relations"] if r.get("status") == "rejected"]
|
||||
assert len(catalog.visible_notes(frozen["visits"]["notes"])["relations"]) == 2
|
||||
assert catalog.frozen_catalog({}, ["visits"]) == {}
|
||||
|
||||
|
||||
|
||||
@@ -137,6 +137,8 @@ async def test_confirming_a_profiled_relation_by_patch_keeps_the_fanout_check(cl
|
||||
rel = _relation(detail["notes"], "gate_id")
|
||||
assert (rel["source"], rel["status"], rel["cardinality"], rel["coverage"]) == (
|
||||
"profile", "verified", "many_to_one", 1.0)
|
||||
# 子表一侧数过、确有重复:基数用数据核实过,一对多确有其事 → error(A6)
|
||||
assert rel["cardinality_checked"] is True
|
||||
assert ("fanout_sum", "error", "gates", "id") in await _found(sid, sql)
|
||||
|
||||
changes = [{"path": "relations.new", "value": {"columns": ["gate_id"], "to_table": "gates", "to_columns": ["id"]},
|
||||
@@ -149,6 +151,21 @@ async def test_confirming_a_profiled_relation_by_patch_keeps_the_fanout_check(cl
|
||||
assert ("fanout_sum", "error", "gates", "id") in await _found(sid, sql)
|
||||
|
||||
|
||||
async def test_profiled_relation_without_child_check_only_warns(client, make_source, scenic_db):
|
||||
"""A6:子表超过整表统计上限、没核对子表一侧唯不唯一的关系,剖析照样记有确证、按多对一记,但基数不算用数据
|
||||
核实过:扇出检查只给 warning(「可能重复计算」),不给 error、不让出具降档。"""
|
||||
sql = "SELECT COUNT(g.id) AS n FROM gates g JOIN visits v ON v.gate_id = g.id"
|
||||
sid = await make_source(scenic_db, options=_on(max_scan_rows=100), draft=["visits", "gates"])
|
||||
r = await client.post(_url(sid), json={"tables": ["visits"]})
|
||||
assert r.status_code == 200, r.text
|
||||
rel = _relation((await _notes(client, sid, "visits"))["notes"], "gate_id")
|
||||
assert (rel["source"], rel["status"], rel["cardinality"]) == ("profile", "verified", "many_to_one")
|
||||
assert not rel.get("cardinality_checked")
|
||||
found = await _found(sid, sql)
|
||||
assert ("fanout_sum", "warning", "gates", "id") in found
|
||||
assert ("fanout_sum", "error", "gates", "id") not in found
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# A2:去掉推断或外键来的关系即驳回
|
||||
# ==========================================================================
|
||||
@@ -193,6 +210,19 @@ def test_human_edit_rejects_a_removed_human_relation_that_structure_would_bring_
|
||||
assert catalog.apply_human_edit({"relations": [park]}, {"relations": []}, table="visits", at=AT) == {}
|
||||
|
||||
|
||||
def test_human_edit_cannot_forge_a_data_checked_cardinality():
|
||||
"""A6:「基数用数据核实过」只能由数据剖析写。人工改了关系(记成人工确认),提交里带的 cardinality_checked 不作数;
|
||||
值没动的关系保留剖析原来写的。"""
|
||||
gate = {**_rel(["gate_id"], "gates", ["id"], "profile", "verified"), "coverage": 1.0, "cardinality_checked": True}
|
||||
park = _rel(["park_id"], "parks", ["id"], "name")
|
||||
forged = {**park, "cardinality": "one_to_many", "cardinality_checked": True}
|
||||
out = catalog.apply_human_edit({"relations": [gate, park]}, {"relations": [gate, forged]}, table="visits", at=AT)
|
||||
by_id = {r["id"]: r for r in out["relations"]}
|
||||
assert by_id[gate["id"]]["cardinality_checked"] is True
|
||||
assert (by_id[park["id"]]["source"], by_id[park["id"]]["status"]) == ("human", "confirmed")
|
||||
assert "cardinality_checked" not in by_id[park["id"]]
|
||||
|
||||
|
||||
async def test_removed_or_rejected_relations_stay_out_of_checks_graph_and_redraft(client, make_source, scenic_db):
|
||||
sid = await make_source(scenic_db, draft=["visits"])
|
||||
detail = await _notes(client, sid, "visits")
|
||||
@@ -377,7 +407,9 @@ async def test_rerun_on_another_day_with_same_data_keeps_the_version(client, mak
|
||||
third = _table((await client.post(_url(sid), json={"tables": ["visits"]})).json(), "visits")
|
||||
assert third["version"] == second["version"] + 1 and third["updated"] >= 1
|
||||
codes = (await _notes(client, sid, "visits"))["notes"]["columns"]["status"]["codes"]
|
||||
assert set(codes["value"]) == {"0", "1", "2"} and "2026-10-03" in codes["note"]
|
||||
assert set(codes["value"]) == {"0", "1", "2"} and codes["updated_at"] == DAY3
|
||||
# A7:说明里不写日期(以前写的是 UTC 日期,和界面上的本地时间对不上),时间以这一项的 updated_at 为准
|
||||
assert codes["note"].startswith("数据剖析:") and "2026-10-03" not in codes["note"]
|
||||
|
||||
|
||||
def test_merge_ignores_a_profile_note_that_only_changed_its_date():
|
||||
@@ -394,6 +426,24 @@ def test_merge_ignores_a_profile_note_that_only_changed_its_date():
|
||||
assert stats.updated == 1 and "2026-10-02" in merged["columns"]["status"]["codes"]["note"]
|
||||
|
||||
|
||||
def test_profile_notes_without_date_stay_compatible_with_dated_ones():
|
||||
"""A7:剖析写的说明不再带日期(「数据剖析:…」)。升级前写的「数据剖析(2026-10-01):…」照样认得是剖析写的;
|
||||
结论一样、只是新的不带日期,不算变化——升级后第一次重新剖析不能因此给每张表升一个版本。"""
|
||||
dated = "数据剖析(2026-10-01):统计全表,1500 行非空值共 2 个取值。"
|
||||
plain = "数据剖析:统计全表,1500 行非空值共 2 个取值。"
|
||||
assert catalog.is_profile_note(dated) and catalog.is_profile_note(plain)
|
||||
assert not catalog.is_profile_note("人工备注:数据剖析(2026-10-01)") and not catalog.is_profile_note(None)
|
||||
assert catalog.same_profile_note(dated, plain) and catalog.same_profile_note(plain, dated)
|
||||
assert catalog.same_profile_note("数据剖析(2026-10-02):统计全表,1500 行非空值共 2 个取值。", dated)
|
||||
assert not catalog.same_profile_note(dated, "数据剖析:统计全表,1600 行非空值共 2 个取值。")
|
||||
assert not catalog.same_profile_note(plain, "统计全表,1500 行非空值共 2 个取值。")
|
||||
old = {"columns": {"status": {"codes": catalog.make_item({"1": "", "0": ""}, "profile", "proposed", note=dated,
|
||||
at=DAY1)}}}
|
||||
new = {"columns": {"status": {"codes": catalog.make_item({"1": "", "0": ""}, "profile", "proposed", note=plain)}}}
|
||||
merged, stats = catalog.merge_notes(old, new, covered={"profile"}, at=DAY2)
|
||||
assert merged == old and stats == catalog.MergeStats()
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# B3:公式在人工编辑、模型起草两条路径上也拦下
|
||||
# ==========================================================================
|
||||
|
||||
@@ -116,6 +116,9 @@ async def test_read_catalog_lists_all_tables_of_a_source():
|
||||
({"formula": _label("sum(amount)")}, "formula"), # 目录不放公式
|
||||
({"relations": [{"id": "r1", "columns": ["a"], "to_table": "t", "to_columns": [],
|
||||
"source": "fk", "status": "verified"}]}, "关联关系 r1"),
|
||||
# 基数是否用数据核实过(数据剖析写):只能是 true / false
|
||||
({"relations": [{"id": "r1", "columns": ["a"], "to_table": "t", "to_columns": ["id"], "cardinality": "many_to_one",
|
||||
"source": "profile", "status": "verified", "cardinality_checked": "yes"}]}, "关联关系 r1"),
|
||||
])
|
||||
def test_validate_rejects_malformed_notes(notes, fragment):
|
||||
problems = catalog.validate_notes(notes)
|
||||
@@ -134,7 +137,10 @@ def test_validate_accepts_full_example():
|
||||
"codes": _label({"1": "有效"}, "comment", "proposed")}},
|
||||
"relations": [{"id": catalog.relation_id("visits", ["store_id"], "stores", ["id"]), "columns": ["store_id"],
|
||||
"to_table": "stores", "to_columns": ["id"], "cardinality": "many_to_one", "coverage": None,
|
||||
"source": "fk", "status": "verified"}],
|
||||
"source": "fk", "status": "verified"},
|
||||
{"id": catalog.relation_id("visits", ["gate_id"], "gates", ["id"]), "columns": ["gate_id"],
|
||||
"to_table": "gates", "to_columns": ["id"], "cardinality": "many_to_one", "coverage": 1.0,
|
||||
"source": "profile", "status": "verified", "cardinality_checked": True}],
|
||||
}
|
||||
assert catalog.validate_notes(notes) == []
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""证据面板的查询步骤:合并查询的输入带上检查结果,查询步骤说明用的是哪一版数据目录。
|
||||
|
||||
- 合并查询的列追不到逐格来历时,证据面板只有合并步骤、没有输入步骤:输入查询的 SQL 检查结果以前在这里看不到,
|
||||
指标却因为它标了「存疑」。现在合并步骤的每个输入带上 checks(不带给模型的那句)。
|
||||
- 表结构快照里冻结了数据目录(随查询冻结的那一版),以前没有任何读取方。查询步骤带上表结构快照 id 和这条查询
|
||||
用到的表的目录版本,面板上写「数据目录:入园记录 第 3 版」。
|
||||
- 冻结时保留被驳回关系的编号(只放编号和状态):拿冻结的那份重建检查器,按外键现推的关系不会把驳回的推回来。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.api import evidence as api
|
||||
from app.core import artifact_store
|
||||
from app.data import catalog, sqlcheck
|
||||
from app.engine.merge_query import MERGE_SOURCE, MergeInput, execute
|
||||
|
||||
FANOUT = {"code": "fanout_sum", "level": "error", "message": "「订单」关联「订单明细」是一对多,求和会重复计算。先汇总再关联",
|
||||
"for_model": "orders 关联 order_items 后对 total_amount 求和会重复计算", "table": "orders"}
|
||||
NOTICE = {"code": "missing_valid_filter", "level": "warning", "message": "没有筛掉作废订单", "for_model": "加 status = 1",
|
||||
"table": "orders"}
|
||||
|
||||
|
||||
async def put(obj, kind="query_snapshot") -> str:
|
||||
return await artifact_store.put_json(obj, kind=kind)
|
||||
|
||||
|
||||
def _sealed(queries: dict[str, dict]) -> api._Sealed:
|
||||
seal = {"sealed": True, "ok": True, "manifest_seq": 9, "legacy": False}
|
||||
return api._Sealed(run_id="run-x", graph={}, seal=seal, events=[], queries=queries)
|
||||
|
||||
|
||||
async def test_merge_inputs_carry_their_sql_checks():
|
||||
sales = {"columns": ["日期", "销售额"], "rows": [["2026-05-01", 10]], "row_count": 1, "truncated": False,
|
||||
"sql": "SELECT 日期, SUM(o.total_amount) FROM orders o JOIN order_items i ON i.order_id = o.id",
|
||||
"source": "shop", "checks": [FANOUT, NOTICE]}
|
||||
visits = {"columns": ["日期", "到店"], "rows": [["2026-05-01", 3]], "row_count": 1, "truncated": False,
|
||||
"sql": "SELECT 日期, 到店 FROM 到店", "source": "foot"}
|
||||
sid, vid = await put(sales), await put(visits)
|
||||
outcome = execute([MergeInput(alias="s", node_id="q_sales", artifact=sid, snapshot=sales),
|
||||
MergeInput(alias="v", node_id="q_visits", artifact=vid, snapshot=visits)],
|
||||
'SELECT s."日期", s."销售额" * 1.0 / v."到店" AS 店均 FROM s JOIN v ON s."日期" = v."日期"')
|
||||
mid = await put(outcome.snapshot())
|
||||
doc = {"catalog": {"Q1": {"kind": "query", "artifact": sid}, "Q2": {"kind": "query", "artifact": vid},
|
||||
"Q3": {"kind": "query", "artifact": mid, "source": MERGE_SOURCE}}}
|
||||
sealed = _sealed({sid: {"node_id": "q_sales"}, vid: {"node_id": "q_visits"}, mid: {"node_id": "merge"}})
|
||||
# 算出来的列追不到逐格来历:只有合并步骤,输入的检查结果要在合并步骤里看得到
|
||||
[step] = await api._query_steps(mid, [(0, "店均")], doc, sealed, api._Masks())
|
||||
s_in, v_in = step["merge"]["inputs"]
|
||||
assert [c["code"] for c in s_in["checks"]] == ["fanout_sum", "missing_valid_filter"]
|
||||
assert all("for_model" not in c for c in s_in["checks"])
|
||||
assert s_in["checks"][0]["level"] == "error" and s_in["checks"][0]["table"] == "orders"
|
||||
assert "checks" not in v_in
|
||||
|
||||
|
||||
def _schema_cache() -> dict:
|
||||
return {"schema": "main", "tables": {
|
||||
"visits": {"qualified": "main.visits", "primary_key": ["id"],
|
||||
"columns": [{"name": "id", "type": "INTEGER"}, {"name": "member_id", "type": "INTEGER"},
|
||||
{"name": "fee", "type": "REAL"}],
|
||||
"foreign_keys": [{"columns": ["member_id"], "to_table": "members", "to_columns": ["id"]}]},
|
||||
"members": {"qualified": "main.members", "primary_key": ["id"],
|
||||
"columns": [{"name": "id", "type": "INTEGER"}], "foreign_keys": []}}}
|
||||
|
||||
|
||||
def _fk_relation(cache: dict) -> dict:
|
||||
[rel] = [r for r in catalog.fk_relations(cache, "visits") or [] if r["to_table"] == "members"]
|
||||
return rel
|
||||
|
||||
|
||||
async def test_the_query_step_names_the_catalog_version_it_was_checked_against():
|
||||
cache = _schema_cache()
|
||||
notes = {"label": catalog.make_item("入园记录", "human")}
|
||||
frozen = catalog.frozen_catalog({"visits": catalog.CatalogEntry("visits", notes, 3)}, cache["tables"])
|
||||
schema_id = await put({"source": "scenic", **cache, "catalog": frozen}, kind="schema_snapshot")
|
||||
query = {"columns": ["n"], "rows": [[4]], "row_count": 1, "truncated": False, "source": "scenic",
|
||||
"sql": "SELECT COUNT(*) AS n FROM visits v JOIN members m ON m.id = v.member_id",
|
||||
"schema_artifact": schema_id}
|
||||
qid = await put(query)
|
||||
doc = {"catalog": {"Q1": {"kind": "query", "artifact": qid}}}
|
||||
step = await api._query_step(qid, [(0, "n")], doc, _sealed({qid: {"node_id": "fetch"}}), api._Masks())
|
||||
assert step["schema_artifact"] == schema_id
|
||||
# 只列这条查询用到、而且有目录的表:members 没有目录,不列
|
||||
assert step["catalog"] == [{"table": "visits", "label": "入园记录", "version": 3}]
|
||||
|
||||
|
||||
async def test_a_query_without_a_frozen_catalog_says_nothing_extra():
|
||||
"""没对照过目录的查询(老快照、没有目录的源):步骤的形状和以前一字不差(期 4 的金样逐字比对)。"""
|
||||
schema_id = await put({"source": "scenic", **_schema_cache()}, kind="schema_snapshot")
|
||||
for extra in ({}, {"schema_artifact": schema_id}):
|
||||
query = {"columns": ["n"], "rows": [[4]], "row_count": 1, "truncated": False, "source": "scenic",
|
||||
"sql": "SELECT COUNT(*) AS n FROM visits", **extra}
|
||||
qid = await put(query)
|
||||
doc = {"catalog": {"Q1": {"kind": "query", "artifact": qid}}}
|
||||
step = await api._query_step(qid, [(0, "n")], doc, _sealed({qid: {"node_id": "fetch"}}), api._Masks())
|
||||
assert "catalog" not in step and "schema_artifact" not in step
|
||||
|
||||
|
||||
def test_frozen_catalog_keeps_rejected_relation_ids_without_their_content():
|
||||
cache = _schema_cache()
|
||||
rel = {**_fk_relation(cache), "status": "rejected", "note": "这条外键是历史遗留,不能拿来关联"}
|
||||
notes = {"label": catalog.make_item("入园记录", "human"), "relations": [rel]}
|
||||
frozen = catalog.frozen_catalog({"visits": catalog.CatalogEntry("visits", notes, 2)}, cache["tables"])
|
||||
assert frozen["visits"]["notes"]["relations"] == [{"id": rel["id"], "status": "rejected"}]
|
||||
assert catalog.visible_notes(frozen["visits"]["notes"]) == {"label": notes["label"]}
|
||||
|
||||
# 拿冻结的那份重建检查器:驳回过的外键关系不会按表结构又推回来
|
||||
checker = sqlcheck.frozen_checker({"source": "scenic", **cache, "catalog": frozen}, kind="sqlite")
|
||||
assert checker is not None and checker.edges_between("visits", "members") == []
|
||||
live = sqlcheck.SqlChecker(kind="sqlite", schema_cache=cache, notes={"visits": notes})
|
||||
assert live.edges_between("visits", "members") == [] # 和当时库里那份一致
|
||||
|
||||
# 只有驳回关系的表也要冻结:不然编号丢了,重建时又推回来
|
||||
only = catalog.frozen_catalog({"visits": catalog.CatalogEntry("visits", {"relations": [rel]}, 1)}, cache["tables"])
|
||||
assert only == {"visits": {"version": 1, "notes": {"relations": [{"id": rel["id"], "status": "rejected"}]}}}
|
||||
|
||||
|
||||
def test_a_snapshot_without_a_catalog_rebuilds_no_checker():
|
||||
assert sqlcheck.frozen_checker({"source": "scenic", **_schema_cache()}, kind="sqlite") is None
|
||||
assert sqlcheck.frozen_checker(None, kind="sqlite") is None
|
||||
@@ -462,6 +462,12 @@ async def test_warnings_reach_the_output_and_the_events(monkeypatch, sources):
|
||||
logs = [e for e in await events(row.id, "log", "merge") if e.get("level") == "warn"]
|
||||
assert sorted(e["code"] for e in logs) == ["merge_key_type", "merge_rows_grew"]
|
||||
assert all(e["message"] for e in logs)
|
||||
# 结构化字段随日志带上:运行时间线读字段,不从中文里解析
|
||||
key = next(e for e in logs if e["code"] == "merge_key_type")
|
||||
assert key["keys"] == ["s.门店", "v.门店"] and key["detail"].startswith("s.门店 是文本") and "v.门店 是数值" in key["detail"]
|
||||
grew = next(e for e in logs if e["code"] == "merge_rows_grew")
|
||||
assert grew["rows"] == done["rows"] and grew["input"] in ("s", "v") and isinstance(grew["input_rows"], int)
|
||||
assert grew["rows"] > grew["input_rows"] and "有重复的键" in grew["duplicates"]
|
||||
|
||||
|
||||
async def test_rerunning_the_node_on_the_same_inputs_gives_the_same_snapshot(monkeypatch, sources):
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""写作指引:[[see:]] 只放句末;涉及码值时写含义、不写码值本身(R2 走查的 A4、B4)。
|
||||
|
||||
- A4:报告正文出现「以 为依据看」这样的断句。[[see:]] 渲染后不显示,写作者把它写进了句子中间
|
||||
(「以 [[see:Q1]] 为依据看,……」)。指引写明只放句末;组装文档时能稳妥认出的写法(「以 [[see:…]] 为」
|
||||
「根据 [[see:…]]」之类)报出来,交回写作者重写;重写不好也不判失败——数字和出处都没问题,只是句子不通。
|
||||
- B4:报告核对把码值 1、0、9 当成没有出处的数字,每次运行都强制重写一轮。数字核对不放宽(不可回退的约定),
|
||||
指引里写明:涉及码值时写它的含义(「作废记录」),不写码值本身。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.copilot import NODE_REFERENCE as COPILOT_PROMPT
|
||||
from app.engine.evidence import SEE_AND_CODE_RULES, build_catalog, compose_doc
|
||||
from app.engine.nodes.report import REWRITE_ONLY
|
||||
from tests.test_report_node import ( # noqa: F401 - 夹具按名字引入
|
||||
CLEAN,
|
||||
engine_up,
|
||||
events,
|
||||
finish,
|
||||
script,
|
||||
weekly,
|
||||
)
|
||||
|
||||
|
||||
def test_the_writer_is_told_to_put_see_at_the_end_and_write_code_meanings():
|
||||
assert "[[see:…]]" in SEE_AND_CODE_RULES and "句末" in SEE_AND_CODE_RULES
|
||||
assert "以 [[see:Q1]] 为依据" in SEE_AND_CODE_RULES # 点名不要这样写
|
||||
assert "码值" in SEE_AND_CODE_RULES and "含义" in SEE_AND_CODE_RULES and "作废记录" in SEE_AND_CODE_RULES
|
||||
|
||||
|
||||
def test_the_copilot_tells_report_instructions_the_same():
|
||||
"""助手写报告节点的指引(copilot 的系统提示)同样说清:see 只放句末,码值写含义。"""
|
||||
assert "只能放在句末" in COPILOT_PROMPT and "以 [[see:" not in COPILOT_PROMPT.replace("不要写「以 [[see:", "")
|
||||
assert "码值" in COPILOT_PROMPT and "含义" in COPILOT_PROMPT
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalog():
|
||||
card = {"kind": "metric_set", "caliber": "周报口径", "caliber_version": "v1",
|
||||
"metrics": [{"id": "gmv", "name": "销售额", "value": 45678.5, "unit": "元", "format": "thousands"}]}
|
||||
return build_catalog(nodes={"card": card}, ledger=[{"kind": "metric_set", "node_id": "card", "artifact": "c" * 64}])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"以 [[see:m:gmv]] 为依据看,本周销售额 [[m:gmv]] 偏高。",
|
||||
"以[[see:m:gmv]]为依据,本周销售额 [[m:gmv]] 偏高。",
|
||||
"根据 [[see:m:gmv]],本周销售额 [[m:gmv]] 偏高。",
|
||||
"本周销售额 [[m:gmv]] 偏高,详见 [[see:m:gmv]]。",
|
||||
"基于 [[see:m:gmv]] 的结果,本周销售额 [[m:gmv]] 偏高。",
|
||||
])
|
||||
def test_see_used_as_part_of_the_sentence_is_flagged(catalog, text):
|
||||
doc = compose_doc(text, catalog)
|
||||
[v] = [v for v in doc["violations"] if v["code"] == "inline_see"]
|
||||
assert "[[see:" in v["text"] and "句末" in v["for_model"]
|
||||
assert "断句" in v["message"] and "[[see:" not in doc["markdown"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"本周销售额 [[m:gmv]] 偏高。[[see:m:gmv]]",
|
||||
"本周销售额 [[m:gmv]] 偏高 [[see:m:gmv]]。",
|
||||
"本周销售额 [[m:gmv]] 偏高 [[see:m:gmv]],所以 [[see:m:gmv]] 下周要关注。", # 「所以」不是介词
|
||||
"这是结论的依据 [[see:m:gmv]]。",
|
||||
"可以 [[see:m:gmv]]。",
|
||||
])
|
||||
def test_see_at_the_end_of_a_clause_is_fine(catalog, text):
|
||||
doc = compose_doc(text, catalog)
|
||||
assert not [v for v in doc["violations"] if v["code"] == "inline_see"], doc["violations"]
|
||||
|
||||
|
||||
INLINE = "## 本周概览\n\n以 [[see:m:gmv]] 为依据看,本周([[i:week]])销售额 [[m:gmv]],环比 [[m:wow]];订单 [[m:orders]]。"
|
||||
|
||||
|
||||
async def test_inline_see_is_sent_back_for_one_rewrite(engine_up, monkeypatch):
|
||||
seen = script(monkeypatch, INLINE, CLEAN)
|
||||
row = await finish(weekly({"on_violation": "fail"}))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(seen) == 2, "句中的依据应当交回重写一次"
|
||||
assert "只能挂在句末" in str(seen[1][-1].content)
|
||||
|
||||
|
||||
async def test_inline_see_that_survives_the_rewrite_does_not_fail_the_node(engine_up, monkeypatch):
|
||||
"""数字、出处都对得上,只是句子不通:重写还这样也不判失败,留在核对结果里。"""
|
||||
assert "inline_see" in REWRITE_ONLY
|
||||
seen = script(monkeypatch, INLINE)
|
||||
row = await finish(weekly({"on_violation": "fail"}))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(seen) == 2
|
||||
[checked] = [e.data for e in await events(row.id, "report.checked")]
|
||||
assert checked["failed"] is False and [v["code"] for v in checked["violations"]] == ["inline_see"]
|
||||
@@ -0,0 +1,200 @@
|
||||
"""报告直接引用没通过 SQL 检查的查询时,出具同样降档;同一条查询的问题只记一次。
|
||||
|
||||
以前缺口只从口径卡的指标来:报告绕过口径卡、直接写 [[v:Q1.r0.gmv]] 引用一条一对多关联后求和的查询,
|
||||
数字回指得上快照,出具照样盖「完整出具」的章;写作目录也只给指标标「存疑」,写作者不知道这条查询本身有问题。
|
||||
另一头,同一条查询算出三个指标时,运行时间线和降档原因里同一句话各重复三遍。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import app.engine.issuance as issuance_mod
|
||||
from app.core import artifact_store
|
||||
from app.engine.issuance import sql_check_gaps
|
||||
from app.engine.merge_query import MERGE_SOURCE as ENGINE_MERGE_SOURCE
|
||||
from app.engine.runner import run_manager
|
||||
from app.engine.sql_problems import MERGE_SOURCE, query_problems, reason_text
|
||||
from tests.test_runtime_sqlcheck import ( # noqa: F401 - 夹具按名字引入
|
||||
CLEAN_SQL,
|
||||
FANOUT_SQL,
|
||||
GMV,
|
||||
GMV2,
|
||||
REASON,
|
||||
Writer,
|
||||
_drop_created_sources,
|
||||
chain,
|
||||
engine_up,
|
||||
events,
|
||||
node,
|
||||
scenic_source,
|
||||
wait,
|
||||
)
|
||||
|
||||
PROBLEM = "「订单」关联「订单明细」是一对多,对「订单」的「订单金额」求和会重复计算"
|
||||
|
||||
|
||||
def test_the_merge_source_literal_matches_the_engine():
|
||||
assert MERGE_SOURCE == ENGINE_MERGE_SOURCE
|
||||
assert reason_text([PROBLEM]) == REASON
|
||||
|
||||
|
||||
def direct(source: str, sql: str, text: str) -> dict:
|
||||
"""报告不经口径卡,直接引用查询结果里的格。"""
|
||||
return chain([
|
||||
node("start", "input"),
|
||||
node("fetch", "tool", tool=f"db_query__{source}", args={"sql": sql}),
|
||||
node("write", "report", instructions="写订单周报"),
|
||||
node("out", "output", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}],
|
||||
contract={"report_from": "write"}),
|
||||
])
|
||||
|
||||
|
||||
async def test_a_cell_cited_from_a_failing_query_degrades_the_issuance(scenic_source, engine_up, monkeypatch):
|
||||
writer = Writer(monkeypatch, text="本周订单金额 [[v:Q1.r0.gmv]]。")
|
||||
run = await run_manager.start(graph=direct(scenic_source, FANOUT_SQL, ""), input_payload={})
|
||||
row = await wait(run.id)
|
||||
assert row.status == "succeeded", row.error
|
||||
issuance = row.output["_issuance"]
|
||||
assert issuance["tier"] == "degraded", issuance
|
||||
[gap] = [g for g in issuance["gaps"] if "SQL 检查" in g]
|
||||
assert gap.startswith("查询「fetch」(Q1)未通过 SQL 检查") and PROBLEM in gap
|
||||
assert "受影响的引用:Q1 第 1 行「gmv」" in gap
|
||||
# 写作目录里,这条查询本身就标着「存疑」:写作者引用它的格时知道要交代
|
||||
prompt = writer.prompts[0]
|
||||
q1 = prompt[prompt.index("- Q1:"):]
|
||||
assert "这次查询未通过 SQL 检查" in q1.split("\n例:")[0] and PROBLEM in q1
|
||||
|
||||
|
||||
async def test_the_same_report_on_a_clean_query_issues_formally(scenic_source, engine_up, monkeypatch):
|
||||
writer = Writer(monkeypatch, text="本周订单金额 [[v:Q1.r0.gmv]]。")
|
||||
run = await run_manager.start(graph=direct(scenic_source, CLEAN_SQL, ""), input_payload={})
|
||||
row = await wait(run.id)
|
||||
assert row.status == "succeeded", row.error
|
||||
assert row.output["_issuance"]["tier"] == "formal", row.output["_issuance"]
|
||||
assert "未通过 SQL 检查" not in writer.prompts[0]
|
||||
|
||||
|
||||
def three(source: str, sql: str) -> dict:
|
||||
"""同一条查询算出两个指标,报告又直接引用了它的一格、拿它当依据。"""
|
||||
return chain([
|
||||
node("start", "input"),
|
||||
node("fetch", "tool", tool=f"db_query__{source}", args={"sql": sql}),
|
||||
node("parse", "transform", mode="json", template="{{ nodes.fetch }}", assign_to="res"),
|
||||
node("card", "metrics", caliber="订单口径", caliber_version="v1", metrics=[GMV, GMV2]),
|
||||
node("write", "report", instructions="写订单周报"),
|
||||
node("out", "output", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}],
|
||||
contract={"report_from": "write", "metrics_from": ["card"], "required": ["gmv"]}),
|
||||
])
|
||||
|
||||
|
||||
async def test_one_failing_query_is_one_gap_and_one_timeline_row(scenic_source, engine_up, monkeypatch):
|
||||
Writer(monkeypatch, text="本周订单金额 [[m:gmv]],查询结果 [[v:Q1.r0.gmv]]。[[see:Q1]]")
|
||||
run = await run_manager.start(graph=three(scenic_source, FANOUT_SQL), input_payload={})
|
||||
row = await wait(run.id)
|
||||
assert row.status == "succeeded", row.error
|
||||
issuance = row.output["_issuance"]
|
||||
assert issuance["tier"] == "degraded"
|
||||
[gap] = [g for g in issuance["gaps"] if "SQL 检查" in g]
|
||||
assert gap.count(PROBLEM) == 1
|
||||
assert "指标「订单金额」" in gap and "指标「订单金额(整形后)」" in gap and "Q1 第 1 行「gmv」" in gap
|
||||
# 出具声明和事件另带结构化的 sql_checks:报告页在显眼处说明降档原因,不从缺口的中文里认(B5)
|
||||
[found] = issuance["sql_checks"]
|
||||
assert found == {"query": "查询「fetch」(Q1)", "node_id": "fetch", "problems": [PROBLEM],
|
||||
"refs": ["指标「订单金额」", "指标「订单金额(整形后)」", "Q1 第 1 行「gmv」"], "gap": gap}, found
|
||||
[declared] = [e.data for e in await events(row.id, "issuance")]
|
||||
assert declared["sql_checks"] == issuance["sql_checks"]
|
||||
|
||||
# 运行时间线:同一条查询的问题一行,列出受影响的指标;带着结构化字段,界面不用解析中文
|
||||
[log] = [e.data for e in await events(row.id, "log", "card") if e.data.get("code") == "metric_sql_check"]
|
||||
assert log["metrics"] == ["gmv", "gmv2"] and log["metric_names"] == ["订单金额", "订单金额(整形后)"]
|
||||
assert log["message"] == f"指标「订单金额」「订单金额(整形后)」{REASON}"
|
||||
assert log["reason"] == REASON and log["problems"] == [PROBLEM]
|
||||
assert log["source_node"] == "fetch" and log["source_field"] == "args.sql"
|
||||
[check] = log["checks"]
|
||||
assert check["code"] == "fanout_sum" and check["level"] == "error" and "for_model" not in check
|
||||
[query_end] = [e.data for e in await events(row.id, "tool.end", "fetch")]
|
||||
assert log["query_artifact"] == query_end["query_artifact"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 合并查询:问题记在出问题的那条源查询上,经几条路径找到都只算一次
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
FANOUT = {"code": "fanout_sum", "level": "error", "message": f"{PROBLEM}。改法:先汇总再关联"}
|
||||
|
||||
|
||||
def _snap(checks=None, **extra):
|
||||
snap = {"columns": ["日期", "门店", "销售额"], "rows": [["2026-05-01", "S01", 10]], "truncated": False, **extra}
|
||||
return {**snap, "checks": checks} if checks else snap
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def snapshots(monkeypatch):
|
||||
store = {
|
||||
"sales": _snap([FANOUT]),
|
||||
"visits": _snap(),
|
||||
"merged": _snap(source=MERGE_SOURCE, inputs=[{"alias": "s", "node_id": "q_sales", "artifact": "sales"},
|
||||
{"alias": "v", "node_id": "q_visits", "artifact": "visits"}]),
|
||||
}
|
||||
monkeypatch.setattr(artifact_store, "load", lambda artifact: store.get(artifact))
|
||||
return store
|
||||
|
||||
|
||||
def test_problems_are_recorded_on_the_input_that_failed(snapshots):
|
||||
[problem] = query_problems("merged")
|
||||
assert problem.artifact == "sales" and problem.node_id == "q_sales" and problem.problems == [PROBLEM]
|
||||
|
||||
|
||||
def test_metrics_and_cells_through_a_merge_share_one_gap(snapshots):
|
||||
metrics = [{"id": "gmv", "name": "销售额", "sql_check_failed": True, "sql_check_reason": REASON,
|
||||
"sql_check_sources": [{"artifact": "merged", "codes": ["fanout_sum"]}]},
|
||||
{"id": "avg", "name": "店均销售额", "sql_check_failed": True, "sql_check_reason": REASON,
|
||||
"sql_check_sources": [{"artifact": "merged", "codes": ["fanout_sum"]}]}]
|
||||
labels = {"sales": "查询「取销售」(Q1)"}
|
||||
gaps = sql_check_gaps(metrics, {"merged": ["Q2 第 1 行「销售额」"], "sales": ["Q1(结论依据)"]},
|
||||
label=lambda artifact, node: labels.get(artifact))
|
||||
assert gaps == [f"查询「取销售」(Q1)未通过 SQL 检查({PROBLEM}),结果不可靠;"
|
||||
"受影响的引用:指标「销售额」、指标「店均销售额」、Q2 第 1 行「销售额」、Q1(结论依据)"]
|
||||
|
||||
|
||||
def test_a_flagged_metric_whose_snapshot_is_gone_still_counts(monkeypatch):
|
||||
"""快照读不出来(被清理、被改过)时退回口径卡记下的那句:缺口不能因为读不到快照就消失。"""
|
||||
monkeypatch.setattr(issuance_mod, "query_problems", lambda artifact, **_: [])
|
||||
metrics = [{"id": "gmv", "name": "订单金额", "sql_check_failed": True, "sql_check_reason": REASON,
|
||||
"sql_check_sources": [{"artifact": "gone", "codes": ["fanout_sum"]}]}]
|
||||
assert sql_check_gaps(metrics) == [f"指标「订单金额」{REASON}"]
|
||||
assert sql_check_gaps([{"id": "n", "name": "订单数", "value": 2}]) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 运行时间线:tool.end 单独带上这次查询的 SQL 检查结果
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_tool_end_carries_the_sql_checks_of_the_query(scenic_source, engine_up, monkeypatch):
|
||||
"""preview 只是结果的前 2000 个字符,checks 排在 rows 后面,通常被截掉:界面看不到这条查询的检查结果。"""
|
||||
Writer(monkeypatch, text="本周订单金额 [[v:Q1.r0.gmv]]。")
|
||||
run = await run_manager.start(graph=direct(scenic_source, FANOUT_SQL, ""), input_payload={})
|
||||
row = await wait(run.id)
|
||||
[end] = [e.data for e in await events(row.id, "tool.end", "fetch")]
|
||||
[check] = end["checks"]
|
||||
assert check["code"] == "fanout_sum" and check["level"] == "error" and check["table"] == "orders"
|
||||
assert PROBLEM in check["message"] and "for_model" not in check
|
||||
|
||||
clean = await run_manager.start(graph=direct(scenic_source, CLEAN_SQL, ""), input_payload={})
|
||||
row = await wait(clean.id)
|
||||
[end] = [e.data for e in await events(row.id, "tool.end", "fetch")]
|
||||
assert "checks" not in end
|
||||
|
||||
|
||||
def test_agent_and_team_tool_events_read_checks_the_same_way():
|
||||
"""Agent 节点和协作团队里的查库调用交回的是 JSON 文本:同一个读法,取不到就不加。"""
|
||||
import json
|
||||
|
||||
from app.engine.sql_problems import event_checks
|
||||
|
||||
text = json.dumps({"rows": [[1]], "checks": [{**FANOUT, "for_model": "改写"}]}, ensure_ascii=False)
|
||||
assert event_checks(text) == [{k: v for k, v in FANOUT.items()}]
|
||||
assert event_checks({"rows": [], "checks": [FANOUT]}) == [FANOUT]
|
||||
assert event_checks("查询失败:no such table") == [] and event_checks(None) == []
|
||||
assert event_checks('{"rows": [], "checks": "坏的"}') == []
|
||||
@@ -150,6 +150,7 @@ async def test_a_failing_or_slow_check_never_breaks_the_query(scenic_source, mon
|
||||
|
||||
|
||||
def test_sql_check_failures_become_readable_gaps():
|
||||
# 没记来源快照(或快照读不出来)时退回口径卡那句;按查询归并的写法见 test_report_sqlcheck_cells
|
||||
metrics = [{"id": "gmv", "name": "订单金额", "value": 1, "sql_check_failed": True, "sql_check_reason": REASON},
|
||||
{"id": "n", "name": "订单数", "value": 2}]
|
||||
assert sql_check_gaps(metrics) == [f"指标「订单金额」{REASON}"]
|
||||
@@ -246,11 +247,13 @@ async def test_a_fanout_behind_a_contract_metric_degrades_the_issuance(scenic_so
|
||||
"codes": ["fanout_sum"]}]
|
||||
assert "(存疑:所依据的查询未通过 SQL 检查)" in card["text"]
|
||||
warns = [e.data for e in await events(row.id, "log", "card") if e.data.get("code") == "metric_sql_check"]
|
||||
assert [w["message"] for w in warns] == [f"指标「订单金额」{REASON}", f"指标「订单金额(整形后)」{REASON}"]
|
||||
# 同一条查询算出的两个指标:时间线上一行,降档原因里一句(按查询归并,列出受影响的指标)
|
||||
assert [w["message"] for w in warns] == [f"指标「订单金额」「订单金额(整形后)」{REASON}"]
|
||||
|
||||
issuance = row.output["_issuance"]
|
||||
assert issuance["tier"] == "degraded", issuance
|
||||
assert f"指标「订单金额」{REASON}" in issuance["gaps"]
|
||||
assert [g for g in issuance["gaps"] if "SQL 检查" in g] == [
|
||||
f"查询「fetch」(Q1){REASON.removeprefix('所依据的查询')};受影响的引用:指标「订单金额」、指标「订单金额(整形后)」"]
|
||||
# 写作目录提醒写作者:这个数存疑,引用时要说明
|
||||
assert "所依据的查询未通过 SQL 检查,结果存疑" in writer.prompts[0]
|
||||
|
||||
|
||||
@@ -113,10 +113,19 @@ async def test_fanout_count_of_the_one_side_key(cache):
|
||||
|
||||
|
||||
async def test_fanout_through_two_hops_with_an_inferred_foreign_key(cache):
|
||||
"""支付记录没写目录:订单 → 支付记录的关系按外键现推(verified),明细经订单连支付记录,明细的金额照样重复。"""
|
||||
"""支付记录没写目录:订单 → 支付记录的关系按外键现推(verified),明细经订单连支付记录,明细的金额可能重复。
|
||||
这条一对多只是按外键推的(没用数据核对过子表一侧),所以是 warning(A6)。"""
|
||||
sql = ("SELECT SUM(i.amount) FROM order_items i JOIN orders o ON o.id = i.order_id "
|
||||
"JOIN payments p ON p.order_id = o.id WHERE o.status = 1")
|
||||
[check] = [c for c in run(cache, sql) if c.code == "fanout_sum"]
|
||||
assert (check.level, check.table, check.column) == ("warning", "order_items", "amount")
|
||||
assert "可能重复计算" in check.message and "「订单」关联「payments」" in check.message
|
||||
# 人工确认了支付记录 → 订单这条关系(基数是人定的):一对多确有其事,error,说清明细怎么随之重复
|
||||
notes = scenic_notes.notes()
|
||||
notes["payments"] = {"relations": [scenic_notes._rel("payments", ["order_id"], "orders", ["id"], "many_to_one",
|
||||
"confirmed")]}
|
||||
checker = SqlChecker(kind="sqlite", schema_cache=cache, notes=notes, source_name="scenic")
|
||||
[check] = [c for c in checker.check(sql) if c.code == "fanout_sum"]
|
||||
assert (check.level, check.table, check.column) == ("error", "order_items", "amount")
|
||||
assert "「订单」关联「payments」是一对多,「订单明细」的每一行会随之重复" in check.message
|
||||
assert "去掉与「payments」的关联" in check.message
|
||||
@@ -156,7 +165,9 @@ async def test_fanout_sum_negative(cache, sql):
|
||||
|
||||
async def test_fanout_level_follows_the_status_of_its_basis(cache):
|
||||
sql = FANOUT[0]
|
||||
assert ("fanout_sum", "error", "orders", "total_amount") in found(cache, sql, "verified")
|
||||
assert ("fanout_sum", "error", "orders", "total_amount") in found(cache, sql, "confirmed")
|
||||
# 外键 + verified:一对多只是按表结构推的,降为 warning(A6,见下一个测试)
|
||||
assert ("fanout_sum", "warning", "orders", "total_amount") in found(cache, sql, "verified")
|
||||
assert ("fanout_sum", "info", "orders", "total_amount") in found(cache, sql, "proposed")
|
||||
# 关系确认了、度量类型只是推断:依据里有推断就降为 info
|
||||
assert ("fanout_sum", "info", "orders", "total_amount") in found(
|
||||
@@ -169,6 +180,37 @@ async def test_fanout_level_follows_the_status_of_its_basis(cache):
|
||||
assert "fanout_sum" not in codes(cache, sql, override={("orders", "columns.total_amount.measure"): "rejected"})
|
||||
|
||||
|
||||
def _checked(table_notes: dict, rid: str, *, source: str = "profile") -> dict:
|
||||
"""把一条关系记成「剖析用数据核实过基数」(cardinality_checked),不改入参。"""
|
||||
import copy
|
||||
|
||||
out = copy.deepcopy(table_notes)
|
||||
rel = next(r for r in out["relations"] if r["id"] == rid)
|
||||
rel.update(source=source, status="verified", cardinality_checked=True)
|
||||
return out
|
||||
|
||||
|
||||
async def test_fanout_error_only_when_one_to_many_is_established(cache):
|
||||
"""A6:error 只给「一对多确有其事」——剖析在数据上核实过子表一侧的键不唯一,或者人工确认过基数。
|
||||
只凭外键结构推出的一对多(子表一侧可能每个键恰好一行)降为 warning,说法是「可能重复计算」。"""
|
||||
sql = FANOUT[0]
|
||||
# 外键 + verified:基数是按表结构推的,没用数据核对过 → warning,不说「会重复计算」
|
||||
[fk] = [c for c in run(cache, sql, "verified") if c.code == "fanout_sum"]
|
||||
assert (fk.level, fk.table, fk.column) == ("warning", "orders", "total_amount")
|
||||
assert "可能重复计算" in fk.message and "会重复计算" not in fk.message
|
||||
assert "确认关联表" in fk.message and "每个键只有一行" in fk.message and "先汇总再关联" in fk.message
|
||||
assert "必然" not in fk.message and "必然" not in fk.for_model
|
||||
# 剖析核实过(关系上记 cardinality_checked)→ error
|
||||
profiled = scenic_notes.notes("verified")
|
||||
profiled["order_items"] = _checked(profiled["order_items"], ORDER_ITEMS_TO_ORDERS)
|
||||
checker = SqlChecker(kind="sqlite", schema_cache=cache, notes=profiled, source_name="scenic")
|
||||
[hit] = [c for c in checker.check(sql) if c.code == "fanout_sum"]
|
||||
assert hit.level == "error" and "会重复计算" in hit.message
|
||||
# 人工确认过基数(关系是 confirmed)→ error
|
||||
assert ("fanout_sum", "error", "orders", "total_amount") in found(
|
||||
cache, sql, "verified", override={("order_items", f"relations.{ORDER_ITEMS_TO_ORDERS}"): "confirmed"})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# stock_summed:存量跨时间求和
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user