mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-25 22:22:20 +00:00
合入集成分支 feat/data-catalog(d897981,含 F2a 的证据面板、时间线和服务端修复):自动合并,没有冲突;catalog_profile._relation_finding 两边的改动(F2b 的 previous_status、F2a 的 cardinality_checked 写在关系上)互不重叠
This commit is contained in:
@@ -227,7 +227,11 @@ async def put_catalog_table(source_id: str, table: str, payload: CatalogPutIn,
|
||||
async def draft_catalog(source_id: str, payload: CatalogDraftIn,
|
||||
x_actor: str | None = Header(default=None),
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""同步起草。返回每张表新增、更新、删除了几项;模型用不了或某张表的模型起草失败,照实写在结果里。"""
|
||||
"""同步起草。返回每张表新增、更新、删除了几项;模型用不了或某张表的模型起草失败,照实写在结果里。
|
||||
|
||||
model_items:模型给了这张表几项可用内容(没用模型、模型这部分失败时为 null)。界面据此区分「模型给了内容、
|
||||
只是和现有目录一致」(model_items > 0、三个数都是 0)和「模型没给内容」(model_error 有值)。
|
||||
"""
|
||||
_, source = await _resolved(session, source_id)
|
||||
cache = source.schema_cache or {}
|
||||
if not cache.get("tables"):
|
||||
@@ -235,7 +239,8 @@ async def draft_catalog(source_id: str, payload: CatalogDraftIn,
|
||||
report = await catalog.draft_catalog(session, source, tables=payload.tables or None,
|
||||
use_model=payload.use_model, actor=actor_of(x_actor))
|
||||
rows = [{"table_name": r.table, "added": r.added, "updated": r.updated, "removed": r.removed,
|
||||
"version": r.version, "error": r.error, "model_error": r.model_error} for r in report.tables]
|
||||
"version": r.version, "error": r.error, "model_error": r.model_error, "model_items": r.model_items}
|
||||
for r in report.tables]
|
||||
return {
|
||||
"tables": rows,
|
||||
"total": {k: sum(r[k] for r in rows) for k in ("added", "updated", "removed")},
|
||||
@@ -287,7 +292,10 @@ async def profile_catalog_tables(source_id: str, payload: CatalogProfileIn,
|
||||
raise HTTPException(409, str(e)) from e
|
||||
rows = [_profile_table_out(t) for t in report.tables]
|
||||
note = None
|
||||
if not rows:
|
||||
if not rows and report.empty_tables:
|
||||
note = (f"有待核对关联关系的 {len(report.empty_tables)} 张表都是空表,没有可以核实的数据。"
|
||||
"请在数据有了之后再剖析,或指定要剖析的表")
|
||||
elif not rows:
|
||||
note = "目录里还没有待核实的关联关系,请先起草数据目录,或指定要剖析的表"
|
||||
return {
|
||||
"profiled_at": report.profiled_at,
|
||||
@@ -297,6 +305,8 @@ async def profile_catalog_tables(source_id: str, payload: CatalogProfileIn,
|
||||
"stopped": report.stopped,
|
||||
"tables": rows,
|
||||
"total": {k: sum(r[k] for r in rows) for k in ("added", "updated", "removed")},
|
||||
# 不指定表时挑表途中确知是空表、跳过了的表(指定了表时总是空列表)
|
||||
"empty_tables": report.empty_tables,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
@@ -219,7 +219,10 @@ NODE_REFERENCE = """\
|
||||
查过的数据源里真实存在的名字,表结构、查询、结果列里都没有的会被标成「可能是编造的名字」(受管模板的正式出具因此降档)
|
||||
- [[q:K1|逐字引文]]:知识库检索的原话,必须和命中片段里的字逐字一致(空白不计,至少 4 个字),改一个字就算
|
||||
没有出处;只是拿检索当依据时写 [[see:K1]]。要引原话,在 report 前面接 retrieve 节点
|
||||
- 句末的 [[see:m:指标id,Q1,K1]]:这句结论的依据,不显示
|
||||
- 句末的 [[see:m:指标id,Q1,K1]]:这句结论的依据,不显示,所以只能放在句末;instructions 里不要写「以 [[see:…]] 为依据」
|
||||
「根据 [[see:…]]」这样把它当成句子成分的示例,模型照着写会留下「以 为依据」这样的断句
|
||||
- 涉及码值(状态、类型这类用数字编码的取值)时,instructions 里让模型写它的含义(「作废记录」),不要写码值本身:
|
||||
码值是没有出处的数字,会被数字核对打回重写
|
||||
metrics_from 不写就取所有上游口径卡;on_violation 不写时探索运行是 flag(标出来、照常产出),正式运行是 fail;
|
||||
numbers 默认 strict(裸数字算违规)。claims 是结论句策略:off(默认,不管)/ require_citation(每句结论都要
|
||||
挂引用,没挂的计入缺口、出具降档)/ judge(在 require_citation 之外,再请另一个模型按每句挂的依据判断支不支持:
|
||||
|
||||
@@ -983,7 +983,8 @@ async def _query_step(artifact: str, cells: list[tuple[Any, Any]], doc: dict[str
|
||||
# 查询时从驱动的原始值记下的列类型(老快照没有):文本列里的 "2026" 按文本显示,不当数
|
||||
column_types=snap.get("column_types") if isinstance(snap.get("column_types"), dict) else {},
|
||||
**({"provenance": True} if hint and snap.get("data_version") and not merged else {}),
|
||||
**({"checks": checks} if (checks := _query_checks(snap)) else {}))
|
||||
**({"checks": checks} if (checks := _query_checks(snap)) else {}),
|
||||
**_catalog_of(snap))
|
||||
if len(index) > MAX_WINDOW_ROWS:
|
||||
index, step["window_truncated"] = index[:MAX_WINDOW_ROWS], True
|
||||
step["row_index"] = index
|
||||
@@ -993,6 +994,38 @@ async def _query_step(artifact: str, cells: list[tuple[Any, Any]], doc: dict[str
|
||||
return step
|
||||
|
||||
|
||||
def _catalog_of(snap: dict[str, Any]) -> dict[str, Any]:
|
||||
"""{schema_artifact, catalog}:这条查询当时冻结的表结构快照,以及它用到的表在快照里冻结的目录版本。
|
||||
|
||||
数据源查询工具每次查询都把当时的表结构和数据目录冻结进表结构快照(tools/datasource._store_schema),SQL 检查
|
||||
对照的就是这一版。面板上写「数据目录:入园记录 第 3 版」:事后目录改了、升了版本,看得出这次查询按的是哪一版。
|
||||
catalog 只列 SQL 用到、而且冻结了目录的表:[{table, label?, version}]。这条查询没对照过目录(合并查询、老快照、
|
||||
没探查过结构或没有目录的源、表结构快照读不出来)时两个键都不加:步骤的形状和以前一字不差(期 4 的金样逐字比对)。
|
||||
"""
|
||||
schema_id = snap.get("schema_artifact")
|
||||
if not isinstance(schema_id, str) or not schema_id:
|
||||
return {}
|
||||
try:
|
||||
schema = load(schema_id)
|
||||
except Exception: # noqa: BLE001 - 读不出来:不编版本
|
||||
return {}
|
||||
frozen = schema.get("catalog") if isinstance(schema, dict) else None
|
||||
if not isinstance(frozen, dict) or not frozen:
|
||||
return {}
|
||||
from app.data.catalog import resolve_table_name
|
||||
|
||||
listed: list[dict[str, Any]] = []
|
||||
for name in sql_tables(str(snap.get("sql") or "")):
|
||||
key = resolve_table_name(schema, name)
|
||||
entry = frozen.get(key) if key else None
|
||||
if not isinstance(entry, dict) or any(t["table"] == key for t in listed):
|
||||
continue
|
||||
label = ((entry.get("notes") or {}).get("label") or {}).get("value")
|
||||
listed.append({"table": key, **({"label": label} if isinstance(label, str) and label else {}),
|
||||
"version": entry.get("version")})
|
||||
return {"schema_artifact": schema_id, "catalog": listed} if listed else {}
|
||||
|
||||
|
||||
#: 查询步骤里每条 SQL 检查结果交给界面的字段(data/sqlcheck.SqlCheck.as_dict 去掉 for_model)
|
||||
_CHECK_FIELDS = ("code", "level", "message", "table", "column", "relation_id", "sql_excerpt")
|
||||
|
||||
@@ -1052,7 +1085,10 @@ def _merge_view(snap: dict[str, Any], cells: list[tuple[Any, Any]], catalog: dic
|
||||
inputs.append({"alias": item.get("alias"), "node_id": item.get("node_id"),
|
||||
"label": labels.get(str(item.get("node_id"))), "query": _query_alias(catalog, art),
|
||||
"rows": item.get("rows"), "source": item.get("source"), "artifact": art or None,
|
||||
"sealed": sealed.trusted and art in sealed.queries})
|
||||
"sealed": sealed.trusted and art in sealed.queries,
|
||||
# 输入查询的 SQL 检查结果:被引用的格追不到逐格来历时没有输入步骤,指标却因为它标了「存疑」,
|
||||
# 问题得在合并步骤里看得到。没查出问题、快照读不出来的输入不加这个键
|
||||
**({"checks": checks} if (checks := _input_checks(art)) else {})})
|
||||
traced = []
|
||||
for row, column in dict.fromkeys((r, c) for r, c in cells if isinstance(r, int) and c):
|
||||
hit = trace_cell(snap, row, column)
|
||||
@@ -1067,6 +1103,17 @@ def _merge_view(snap: dict[str, Any], cells: list[tuple[Any, Any]], catalog: dic
|
||||
return {"sql": snap.get("sql"), "inputs": inputs, "warnings": warnings, "traced": traced}
|
||||
|
||||
|
||||
def _input_checks(artifact: str) -> list[dict[str, Any]]:
|
||||
"""合并查询某个输入的 SQL 检查结果(_query_checks 的形状)。读不出来的快照返回空列表:快照的问题输入步骤另有说法。"""
|
||||
if not artifact:
|
||||
return []
|
||||
try:
|
||||
snap = load(artifact)
|
||||
except Exception: # noqa: BLE001 - 被改过、读不出来:这里不报
|
||||
return []
|
||||
return _query_checks(snap) if isinstance(snap, dict) else []
|
||||
|
||||
|
||||
async def _merge_masks(snap: dict[str, Any], masks: _Masks) -> tuple[set[str], list[str]]:
|
||||
"""合并结果要遮的列(小写)和已经不在的数据源:
|
||||
|
||||
|
||||
+103
-34
@@ -18,7 +18,11 @@ notes 结构(每个「项」都是 {value, source, status},可选 note、upd
|
||||
"codes": 项(dict[码值, 含义];含义可为空串,表示待填写;项上可带 complete: true,
|
||||
表示已列出全部取值)}},
|
||||
"relations": [{"id", "columns", "to_table", "to_columns", "cardinality", "coverage",
|
||||
"source", "status", "note"?}]}
|
||||
"source", "status", "note"?, "cardinality_checked"?}]}
|
||||
|
||||
关系上的 cardinality_checked: true 只由数据剖析写:基数是用数据核实的(子表一侧数过 COUNT 和 COUNT(DISTINCT),
|
||||
或者有主键、唯一约束)。外键约束、命名推断给的基数是按表结构推的,子表一侧可能每个键恰好一行;SQL 检查只在
|
||||
基数用数据核实过、或者人工确认过时,才把一对多关联后的重复计算报成错误(data/sqlcheck.py)。
|
||||
|
||||
来源(source):comment 数据库注释、fk 外键约束、name 命名推断、profile 数据剖析(data/catalog_profile.py)、
|
||||
llm 模型起草、human 人工填写。状态(status):proposed 推断(命名推断、模型起草、数据库注释)、verified 有确证
|
||||
@@ -40,7 +44,7 @@ import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Mapping
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
@@ -88,7 +92,7 @@ _ITEM_KEYS = frozenset({"value", "source", "status", "note", "updated_at"})
|
||||
#: 没截断地看完了全表取值时才有;没有它的码值表只是「已知的一部分」,SQL 检查不能拿它判断某个值「不在码值表里」
|
||||
_CODES_ITEM_KEYS = _ITEM_KEYS | {"complete"}
|
||||
_RELATION_KEYS = frozenset({"id", "columns", "to_table", "to_columns", "cardinality", "coverage", "source",
|
||||
"status", "note", "updated_at"})
|
||||
"status", "note", "updated_at", "cardinality_checked"})
|
||||
_BUSINESS_DATE_KEYS = frozenset({"column", "rule", "timezone"})
|
||||
#: 文本项的长度上限。目录是给模型和人读的短说明,长篇大论放口径卡或知识库
|
||||
_TEXT_MAX = 500
|
||||
@@ -293,6 +297,8 @@ def _relation_problems(rel: Any, seen: set[str]) -> list[str]:
|
||||
problems.append(f"{where}的状态「{rel.get('status')}」不在可选值内")
|
||||
if "note" in rel and not isinstance(rel["note"], str):
|
||||
problems.append(f"{where}的备注应为文字")
|
||||
if "cardinality_checked" in rel and not isinstance(rel["cardinality_checked"], bool):
|
||||
problems.append(f"{where}的「基数已用数据核实」应为是或否")
|
||||
if "updated_at" in rel and not isinstance(rel["updated_at"], str):
|
||||
problems.append(f"{where}的修改时间应为文字")
|
||||
return problems
|
||||
@@ -512,22 +518,35 @@ def _core(item: Mapping[str, Any]) -> dict[str, Any]:
|
||||
return {k: v for k, v in item.items() if k != "updated_at"}
|
||||
|
||||
|
||||
#: 数据剖析写的备注都以「数据剖析(日期):」开头(data/catalog_profile.py 的 NOTE_PREFIX 就是它)
|
||||
PROFILE_NOTE_PREFIX = "数据剖析("
|
||||
_PROFILE_NOTE_DAY = re.compile(r"^数据剖析(\d{4}-\d{2}-\d{2})")
|
||||
#: 数据剖析写的备注都以「数据剖析:」开头(data/catalog_profile.py 的 NOTE_PREFIX 就是它)。说明里不写日期:以前写的是
|
||||
#: UTC 日期,和界面上按本地时间显示的修改时间对不上;什么时候剖析的,看这一项的 updated_at
|
||||
PROFILE_NOTE_PREFIX = "数据剖析:"
|
||||
#: 升级前的剖析备注带着当天的 UTC 日期:「数据剖析(2026-10-01):」。旧数据里还有,照样认
|
||||
_PROFILE_NOTE_DAY = re.compile(r"^数据剖析(\d{4}-\d{2}-\d{2})(?=:)")
|
||||
|
||||
|
||||
def is_profile_note(note: Any) -> bool:
|
||||
"""这段备注是不是数据剖析写的(新写法「数据剖析:」,或者升级前带日期的「数据剖析(日期):」)。"""
|
||||
return isinstance(note, str) and (note.startswith(PROFILE_NOTE_PREFIX) or bool(_PROFILE_NOTE_DAY.match(note)))
|
||||
|
||||
|
||||
def _undated(note: str) -> str:
|
||||
"""剖析备注去掉升级前写的日期:「数据剖析(2026-10-01):…」→「数据剖析:…」。别的备注原样返回。"""
|
||||
return _PROFILE_NOTE_DAY.sub("数据剖析", note, count=1)
|
||||
|
||||
|
||||
def same_profile_note(a: Any, b: Any) -> bool:
|
||||
"""两段备注是否相同;数据剖析写的备注只有开头的日期不同,也算相同。
|
||||
"""两段备注是否相同;数据剖析写的备注只差开头的日期(升级前每次都写当天的日期),或者一段带日期、一段是不带
|
||||
日期的新写法,也算相同。
|
||||
|
||||
剖析每次都把当天的日期写进备注。隔天重跑、数据没变,结论一字不差、只有日期变了:要是这也算「变了」,目录就
|
||||
升一个版本,发布时记下的目录版本对不上,之后每次正式运行都提醒「目录有变化」。
|
||||
隔天重跑、数据没变,结论一字不差、只有日期变了:要是这也算「变了」,目录就升一个版本,发布时记下的目录版本
|
||||
对不上,之后每次正式运行都提醒「目录有变化」。升级后第一次重新剖析也是一样:结论没变,只是新写法不带日期。
|
||||
"""
|
||||
if a == b:
|
||||
return True
|
||||
if not (isinstance(a, str) and isinstance(b, str) and _PROFILE_NOTE_DAY.match(a) and _PROFILE_NOTE_DAY.match(b)):
|
||||
if not (is_profile_note(a) and is_profile_note(b)):
|
||||
return False
|
||||
return _PROFILE_NOTE_DAY.sub("", a, count=1) == _PROFILE_NOTE_DAY.sub("", b, count=1)
|
||||
return _undated(a) == _undated(b)
|
||||
|
||||
|
||||
def _same_core(a: Mapping[str, Any], b: Mapping[str, Any]) -> bool:
|
||||
@@ -742,7 +761,8 @@ def apply_human_edit(existing: Mapping[str, Any] | None, submitted: Mapping[str,
|
||||
for key, item in new.items():
|
||||
prev = old.get(key)
|
||||
if prev is None or _edit_value(key, item) != _edit_value(key, prev):
|
||||
fresh = {k: v for k, v in item.items() if k != "updated_at"}
|
||||
# 「基数已用数据核实」只由数据剖析写:人工改过的关系记成人工确认,提交里带的这个标记不作数
|
||||
fresh = {k: v for k, v in item.items() if k not in ("updated_at", "cardinality_checked")}
|
||||
fresh.update(source="human", status="confirmed", updated_at=at)
|
||||
out[key] = fresh
|
||||
continue
|
||||
@@ -1576,8 +1596,16 @@ def _batches(names: list[str], tables: Mapping[str, Any]) -> list[list[str]]:
|
||||
return out
|
||||
|
||||
|
||||
#: 模型给了这张表、但一项可用内容都没有(只有表名的空壳,或者给的值全不合规):这张表记模型失败,不算起草成功。
|
||||
#: 不然界面只看到「新增 0 项」,会说成「没有变化」
|
||||
MODEL_EMPTY_REASON = "模型没有给出这张表的可用内容"
|
||||
|
||||
|
||||
def _model_tables(raw: Any) -> list[dict[str, Any]] | None:
|
||||
"""模型的回复 → 每张表一项的列表。结构化输出给的对象、正文里的 JSON 都认;对不上格式返回 None。"""
|
||||
"""模型的回复 → 每张表一项的列表。结构化输出给的对象、正文里的 JSON 都认;对不上格式返回 None。
|
||||
|
||||
实测模型有时不带 tables 外壳、只回单个表对象({"table": "x", "label": …}),也认成一张表。
|
||||
"""
|
||||
if hasattr(raw, "model_dump"):
|
||||
raw = raw.model_dump()
|
||||
if isinstance(raw, str):
|
||||
@@ -1591,31 +1619,43 @@ def _model_tables(raw: Any) -> list[dict[str, Any]] | None:
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get("tables")
|
||||
raw = [raw] if "tables" not in raw and raw.get("table") else raw.get("tables")
|
||||
if not isinstance(raw, list):
|
||||
return None
|
||||
return [t for t in raw if isinstance(t, dict)]
|
||||
|
||||
|
||||
async def _ask_model(model: Any, messages: list[Any]) -> list[dict[str, Any]]:
|
||||
"""问一批。先走结构化输出;模型不支持、调用报错、或给回来的不是约定的结构,再退回纯文本、从正文里取 JSON。
|
||||
async def _ask_model(model: Any, messages: list[Any],
|
||||
usable: Callable[[list[dict[str, Any]]], bool] | None = None) -> list[dict[str, Any]]:
|
||||
"""问一批。先走结构化输出;模型不支持、调用报错、给回来的不是约定的结构,或者 usable 说它不够用(实测见过
|
||||
结构化输出只给 {"tables":[{"table":"x"}]} 这样的空壳),再退回纯文本、从正文里取 JSON。
|
||||
|
||||
结构化输出报错也退回(同 judge._ask):有的网关不支持工具调用,一调就报错,纯文本却能用。代价是真的
|
||||
网络故障会多试一次,两次加起来仍受 MODEL_TIMEOUT_S 约束。
|
||||
|
||||
两条路都拿到了东西时,结构化的在前、纯文本的在后一起交回(同一张表各有一份,调用方挑能用的那份);纯文本那次
|
||||
失败了就只交回结构化的那份(调用方据此给空壳的表记失败)。
|
||||
"""
|
||||
try:
|
||||
parsed = _model_tables(await model.with_structured_output(CATALOG_DRAFT_PROMPT_SCHEMA).ainvoke(messages))
|
||||
except Exception: # noqa: BLE001 - 退回纯文本
|
||||
parsed = None
|
||||
if parsed is not None:
|
||||
if parsed is not None and (usable is None or usable(parsed)):
|
||||
return parsed
|
||||
from app.engine.state import message_text
|
||||
|
||||
reply = await model.ainvoke(messages)
|
||||
parsed = _model_tables(message_text(reply))
|
||||
if parsed is None:
|
||||
try:
|
||||
reply = await model.ainvoke(messages)
|
||||
except Exception: # noqa: BLE001 - 结构化那份还在:交回它,空壳的表由调用方记失败
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
raise
|
||||
text = _model_tables(message_text(reply))
|
||||
if text is None:
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
raise ValueError("模型的回复不是约定的格式")
|
||||
return parsed
|
||||
return [*(parsed or []), *text]
|
||||
|
||||
|
||||
def _clean_text(value: Any, limit: int = _TEXT_MAX) -> str | None:
|
||||
@@ -1695,9 +1735,22 @@ async def draft_with_model(model: Any, source: Any, tables: list[str], *,
|
||||
existing=(existing or {}).get(n)) for n in batch)
|
||||
messages = [SystemMessage(content=CATALOG_DRAFT_SYSTEM),
|
||||
HumanMessage(content=CATALOG_DRAFT_PROMPT.format(n=len(batch), tables=described))]
|
||||
def drafted(entries: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
"""这批里每张表能用的那份:同一张表给了几份(结构化、纯文本各一份)时取第一份有可用内容的。"""
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for entry in entries:
|
||||
name = str(entry.get("table"))
|
||||
if name in batch and name not in out:
|
||||
notes = _from_model(entry, all_tables[name], system=system)
|
||||
if notes:
|
||||
out[name] = notes
|
||||
return out
|
||||
|
||||
try:
|
||||
async with gate:
|
||||
got = await asyncio.wait_for(_ask_model(model, messages), timeout=MODEL_TIMEOUT_S)
|
||||
got = await asyncio.wait_for(
|
||||
_ask_model(model, messages, usable=lambda entries: len(drafted(entries)) == len(batch)),
|
||||
timeout=MODEL_TIMEOUT_S)
|
||||
except asyncio.TimeoutError:
|
||||
for n in batch:
|
||||
results[n] = f"模型起草超时:{MODEL_TIMEOUT_S} 秒内没有收到回复"
|
||||
@@ -1708,14 +1761,13 @@ async def draft_with_model(model: Any, source: Any, tables: list[str], *,
|
||||
for n in batch:
|
||||
results[n] = f"模型起草失败:{first_line(e) or describe_exception(e)}"
|
||||
return
|
||||
by_name = {str(t.get("table")): t for t in got}
|
||||
named = {str(t.get("table")) for t in got}
|
||||
usable = drafted(got)
|
||||
for n in batch:
|
||||
entry = by_name.get(n)
|
||||
if entry is None:
|
||||
results[n] = "模型的回复里没有这张表"
|
||||
continue
|
||||
results[n] = TableDraft(notes=_from_model(entry, all_tables[n], system=system),
|
||||
covered=frozenset({"llm"}))
|
||||
if n in usable:
|
||||
results[n] = TableDraft(notes=usable[n], covered=frozenset({"llm"}))
|
||||
else:
|
||||
results[n] = MODEL_EMPTY_REASON if n in named else "模型的回复里没有这张表"
|
||||
|
||||
await asyncio.gather(*(run(b) for b in _batches(names, all_tables)))
|
||||
return {n: results[n] for n in names if n in results}
|
||||
@@ -1737,6 +1789,9 @@ class TableDraftResult:
|
||||
version: int = 0
|
||||
error: str | None = None
|
||||
model_error: str | None = None
|
||||
#: 模型给了这张表几项可用内容(并入目录之前,按项数)。没用模型、模型这部分失败时为 None。
|
||||
#: 大于 0 而新增、更新、删除都是 0,才是「模型给了内容、只是和现有目录一致」
|
||||
model_items: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -1800,6 +1855,8 @@ async def draft_catalog(session: AsyncSession, source: Any, *, tables: list[str]
|
||||
modeled = llm.get(table)
|
||||
if isinstance(modeled, str):
|
||||
result.model_error = modeled
|
||||
elif isinstance(modeled, TableDraft):
|
||||
result.model_items = len(_slots(modeled.notes))
|
||||
for _attempt in range(3):
|
||||
entry = await read_entry(session, source.id, table)
|
||||
version = entry.version if entry else 0
|
||||
@@ -1991,7 +2048,8 @@ _FLIP = {"many_to_one": "one_to_many", "one_to_many": "many_to_one", "one_to_one
|
||||
class JoinEdge:
|
||||
"""关系图里的一条有向边:从 from_table 的 from_columns 连到 to_table 的 to_columns。
|
||||
|
||||
每条关系在图里有正反两条边;cardinality 是从 from_table 看过去的基数。
|
||||
每条关系在图里有正反两条边;cardinality 是从 from_table 看过去的基数。cardinality_checked:基数是数据剖析
|
||||
用数据核实的(关系上的同名字段),不是按表结构推的。
|
||||
"""
|
||||
|
||||
from_table: str
|
||||
@@ -2002,10 +2060,11 @@ class JoinEdge:
|
||||
cardinality: str | None
|
||||
source: str
|
||||
status: str
|
||||
cardinality_checked: bool = False
|
||||
|
||||
def reversed(self) -> "JoinEdge":
|
||||
return JoinEdge(self.to_table, self.to_columns, self.from_table, self.from_columns, self.relation_id,
|
||||
_FLIP.get(self.cardinality or ""), self.source, self.status)
|
||||
_FLIP.get(self.cardinality or ""), self.source, self.status, self.cardinality_checked)
|
||||
|
||||
def condition(self) -> str:
|
||||
"""连接条件:visits.id = channel_visits.visit_id(多列用 AND 连接)。"""
|
||||
@@ -2049,7 +2108,7 @@ def relation_graph(notes_by_table: Mapping[str, Mapping[str, Any]], *,
|
||||
continue
|
||||
edge = JoinEdge(table, tuple(rel.get("columns") or ()), str(rel.get("to_table")),
|
||||
tuple(rel.get("to_columns") or ()), rid, rel.get("cardinality"), str(rel.get("source")),
|
||||
str(rel.get("status")))
|
||||
str(rel.get("status")), rel.get("cardinality_checked") is True)
|
||||
graph.setdefault(edge.from_table, []).append(edge)
|
||||
graph.setdefault(edge.to_table, []).append(edge.reversed())
|
||||
return graph
|
||||
@@ -2163,6 +2222,10 @@ def frozen_catalog(entries: Mapping[str, CatalogEntry], tables: Iterable[str]) -
|
||||
只收表结构快照里有的表(tables);去掉驳回项以后什么都不剩的表不收。一张也没有时返回空 dict,
|
||||
调用方据此不加这个键:没有目录的源,快照内容和以前一字不差。目录不变(版本和内容都不变)则返回值
|
||||
不变,快照哈希也就不变。
|
||||
|
||||
被驳回的关系留下编号和状态({"id", "status": "rejected"},不放内容):拿冻结的这份重建 SQL 检查器
|
||||
(sqlcheck.frozen_checker)时,关系图(relation_graph)认得这些编号,按外键、命名现推的关系不会把驳回的推回来。
|
||||
只有驳回关系的表也因此要冻结。visible_notes 照样把它们去掉,给人看、给模型看的内容不变。
|
||||
"""
|
||||
wanted = set(tables)
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
@@ -2170,6 +2233,10 @@ def frozen_catalog(entries: Mapping[str, CatalogEntry], tables: Iterable[str]) -
|
||||
if name not in wanted:
|
||||
continue
|
||||
notes = visible_notes(entries[name].notes)
|
||||
rejected = [{"id": str(item["id"]), "status": "rejected"} for key, item in _slots(entries[name].notes).items()
|
||||
if key[0] == "r" and item.get("status") == "rejected"]
|
||||
if rejected:
|
||||
notes = {**notes, "relations": [*(notes.get("relations") or []), *rejected]}
|
||||
if notes:
|
||||
out[name] = {"version": entries[name].version, "notes": notes}
|
||||
return out
|
||||
@@ -2180,11 +2247,13 @@ __all__ = [
|
||||
"CATALOG_DRAFT_SYSTEM", "COLUMN_FIELDS", "COLUMN_FIELD_LABEL", "COLUMN_MEASURES", "CatalogConflict",
|
||||
"CatalogEntry", "CatalogInvalid", "CatalogModelUnavailable", "CatalogPathError", "DRAFT_DEFAULT_TABLES",
|
||||
"DraftReport", "INFERRED_MARK", "ITEM_SOURCES", "ITEM_STATUSES", "JoinEdge", "KIND_LABEL", "MEASURE_LABEL",
|
||||
"MergeStats", "NEW_RELATION_PATH", "PATCH_MAX_CHANGES", "PROFILE_NOTE_PREFIX", "PROFILE_VERIFY_COVERAGE",
|
||||
"MODEL_EMPTY_REASON", "MergeStats", "NEW_RELATION_PATH", "PATCH_MAX_CHANGES", "PROFILE_NOTE_PREFIX",
|
||||
"PROFILE_VERIFY_COVERAGE",
|
||||
"PatchChange", "PatchPlan", "QUERY_SNAPSHOT_KIND", "REVIEW_ACTIONS", "TABLE_FIELDS", "TABLE_FIELD_LABEL",
|
||||
"TABLE_KINDS", "TableDraft", "TableDraftResult", "UI_KIND_LABEL", "UI_MEASURE_LABEL", "apply_human_edit",
|
||||
"apply_patch", "codes_complete", "describe_slot", "draft_catalog", "draft_structure", "draft_with_model",
|
||||
"fk_relations", "frozen_catalog", "infer_name_relations", "initial_status", "is_date_column", "join_paths",
|
||||
"fk_relations", "frozen_catalog", "infer_name_relations", "initial_status", "is_date_column", "is_profile_note",
|
||||
"join_paths",
|
||||
"make_item", "merge_notes", "name_words", "now_iso", "parse_path", "plan_patch", "profile_relation_holds",
|
||||
"query_snapshot_meta", "read_catalog", "read_entry", "relation_graph", "relation_id", "render_table_index",
|
||||
"render_table_notes", "resolve_draft_model", "resolve_table_name", "review_entry", "review_item", "same_notes",
|
||||
|
||||
@@ -440,12 +440,14 @@ async def estimate_size(run: _Runner, dialect: SqlDialect, meta: dict[str, Any],
|
||||
# 一次剖析:上下文、结果
|
||||
# ==========================================================================
|
||||
|
||||
#: 不指定表时剖析几张:按使用次数取目录里有待核实关系的表
|
||||
#: 不指定表时剖析几张:目录里有要核对的关系的表,还有待核实(推断)关系的在前,再按使用次数;确知是空表的跳过
|
||||
PROFILE_DEFAULT_TABLES = 10
|
||||
#: 不指定表时,为跳过空表最多先估几张候选表的行数;估行数的查询最多用掉查询次数上限的一半,免得都花在挑表上
|
||||
PROFILE_PROBE_TABLES = 30
|
||||
#: IN 列表每批最多几个值:Oracle 的 IN 列表不能超过 1000 项(ORA-01795),各家统一按它分批
|
||||
IN_CHUNK = 1000
|
||||
#: 剖析写的备注都以它开头:人工确认过的关系,只覆盖剖析自己写的备注,不碰人写的。开头接着剖析的日期,
|
||||
#: 比较「结论变没变」时日期不算(catalog.same_profile_note)
|
||||
#: 剖析写的备注都以它开头(「数据剖析:」):人工确认过的关系,只覆盖剖析自己写的备注,不碰人写的(认的时候连
|
||||
#: 升级前带日期的「数据剖析(日期):」一起认,catalog.is_profile_note)。不写日期,时间看这一项的 updated_at
|
||||
NOTE_PREFIX = catalog.PROFILE_NOTE_PREFIX
|
||||
#: 整次剖析停下的原因 → 剩下没查的项的说明
|
||||
_STOP_DETAIL = {
|
||||
@@ -512,6 +514,8 @@ class ProfileReport:
|
||||
tables: list[TableProfile] = field(default_factory=list)
|
||||
queries_used: int = 0
|
||||
stopped: str | None = None
|
||||
#: 不指定表时,挑表途中估过行数、确知是空表而跳过的表(表结构顺序)。估行数的查询算在 queries_used 里
|
||||
empty_tables: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -526,6 +530,9 @@ class _RelationOutcome:
|
||||
sample: int
|
||||
matched: int
|
||||
note: str
|
||||
#: 基数是用数据核实的:子表一侧是否唯一有了定论(主键、唯一约束,或数过 COUNT 和 COUNT(DISTINCT))。
|
||||
#: 子表太大、没数成的按多对一记,但不算核实——SQL 检查据此不把一对多关联后的重复计算报成错误
|
||||
cardinality_checked: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -572,8 +579,6 @@ class _Context:
|
||||
tables: dict[str, Any]
|
||||
#: 遮罩的列(小写)。遮罩按列名生效、不分大小写、不分表,和证据面板的比法一致
|
||||
masked: set[str]
|
||||
#: 写进备注的剖析日期(UTC)
|
||||
day: str
|
||||
sizes: dict[str, TableSize] = field(default_factory=dict)
|
||||
|
||||
async def size(self, table: str, result: TableProfile) -> TableSize:
|
||||
@@ -663,10 +668,11 @@ async def _unique(cx: _Context, table: str, meta: dict[str, Any], column: str,
|
||||
return total == distinct, "count"
|
||||
|
||||
|
||||
def _relation_note(day: str, *, sample: int, matched: int, coverage: float, scan_cap: int | None,
|
||||
def _relation_note(*, sample: int, matched: int, coverage: float, scan_cap: int | None,
|
||||
skipped_values: int, parent: tuple[bool | None, str], child: tuple[bool | None, str] | None,
|
||||
holds: bool) -> str:
|
||||
"""关系的剖析备注:日期、抽样规模、覆盖率、父键和子键唯一的依据。人据此判断这条结论有多可靠。"""
|
||||
"""关系的剖析备注:抽样规模、覆盖率、父键和子键唯一的依据。人据此判断这条结论有多可靠。
|
||||
不写日期:什么时候剖析的看这一项的 updated_at(界面按本地时间显示)。"""
|
||||
parts: list[str] = []
|
||||
low = coverage < catalog.PROFILE_VERIFY_COVERAGE
|
||||
if low:
|
||||
@@ -698,7 +704,7 @@ def _relation_note(day: str, *, sample: int, matched: int, coverage: float, scan
|
||||
parts.append("未能核对子表一侧是否唯一,按多对一记")
|
||||
if not holds and not low:
|
||||
parts.append("暂不升为有确证")
|
||||
return f"{NOTE_PREFIX}{day}):" + ";".join(parts) + "。"
|
||||
return NOTE_PREFIX + ";".join(parts) + "。"
|
||||
|
||||
|
||||
async def _check_relation(cx: _Context, table: str, rel: dict[str, Any], out: _TableOutcome,
|
||||
@@ -749,12 +755,13 @@ async def _check_relation(cx: _Context, table: str, rel: dict[str, Any], out: _T
|
||||
if child_unique is not None:
|
||||
cardinality = "one_to_one" if child_unique[0] is True else "many_to_one"
|
||||
holds = coverage >= catalog.PROFILE_VERIFY_COVERAGE and cardinality is not None
|
||||
note = _relation_note(cx.day, sample=len(literals), matched=matched, coverage=coverage, scan_cap=scan_cap,
|
||||
note = _relation_note(sample=len(literals), matched=matched, coverage=coverage, scan_cap=scan_cap,
|
||||
skipped_values=len(values) - len(literals), parent=parent_unique, child=child_unique,
|
||||
holds=holds)
|
||||
checked = child_unique is not None and child_unique[0] is not None
|
||||
out.relations.append(_RelationOutcome(rid=str(rel["id"]), target=_relation_target(rel), coverage=coverage,
|
||||
cardinality=cardinality, holds=holds, sample=len(literals),
|
||||
matched=matched, note=note))
|
||||
matched=matched, note=note, cardinality_checked=checked))
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
@@ -869,7 +876,7 @@ async def _check_codes(cx: _Context, table: str, column: str, out: _TableOutcome
|
||||
rows = sum(n for _, n in values)
|
||||
scope = f"按前 {scan_cap} 行统计" if scan_cap else "统计全表"
|
||||
spread = "、".join(f"{k}({_share(n, rows)})" for k, n in values)
|
||||
note = f"{NOTE_PREFIX}{cx.day}):{scope},{rows} 行非空值共 {len(values)} 个取值:{spread}。"
|
||||
note = f"{NOTE_PREFIX}{scope},{rows} 行非空值共 {len(values)} 个取值:{spread}。"
|
||||
out.codes.append(_CodesOutcome(column=column, values=values, rows=rows, note=note, complete=scan_cap is None))
|
||||
|
||||
|
||||
@@ -899,7 +906,7 @@ async def _check_dates(cx: _Context, table: str, columns: list[str], total: int,
|
||||
if not result.date_ranges:
|
||||
raise _Skip("no_data", f"{table}.{columns[0]} 没有可识别的日期值")
|
||||
found = result.date_ranges[0]
|
||||
note = (f"{NOTE_PREFIX}{cx.day}):表里只有这一个日期类列,取值从 {str(found['min'])[:19]} 到 "
|
||||
note = (f"{NOTE_PREFIX}表里只有这一个日期类列,取值从 {str(found['min'])[:19]} 到 "
|
||||
f"{str(found['max'])[:19]},可作为业务日期的参考。")
|
||||
out.business_date = _DateOutcome(column=found["column"], low=found["min"], high=found["max"], note=note)
|
||||
|
||||
@@ -956,9 +963,11 @@ def _patch_confirmed(rel: dict[str, Any], o: _RelationOutcome, at: str) -> bool:
|
||||
changed = True
|
||||
if rel.get("cardinality") is None and o.cardinality is not None:
|
||||
rel["cardinality"] = o.cardinality
|
||||
if o.cardinality_checked:
|
||||
rel["cardinality_checked"] = True
|
||||
changed = True
|
||||
note = rel.get("note")
|
||||
if (not note or str(note).startswith(NOTE_PREFIX)) and not catalog.same_profile_note(note, o.note):
|
||||
if (not note or catalog.is_profile_note(note)) and not catalog.same_profile_note(note, o.note):
|
||||
rel["note"] = o.note
|
||||
changed = True
|
||||
if changed:
|
||||
@@ -995,7 +1004,9 @@ def _apply(existing: dict[str, Any] | None, out: _TableOutcome, *,
|
||||
status = "verified" if o.holds else "proposed"
|
||||
relations.append({"id": o.rid, "columns": list(rel["columns"]), "to_table": rel["to_table"],
|
||||
"to_columns": list(rel["to_columns"]), "cardinality": o.cardinality,
|
||||
"coverage": o.coverage, "source": "profile", "status": status, "note": o.note})
|
||||
"coverage": o.coverage, "source": "profile", "status": status, "note": o.note,
|
||||
# 只在基数用数据核实过时有这个键:没核实的关系和以前一字不差
|
||||
**({"cardinality_checked": True} if o.cardinality_checked else {})})
|
||||
findings.append(_relation_finding(o, rel, status=status, confirmed=False))
|
||||
for rid in out.keep_relations:
|
||||
rel = current.get(rid)
|
||||
@@ -1152,7 +1163,44 @@ async def _pick_tables(session: AsyncSession, source: Any, tables: list[str] | N
|
||||
candidates = [name for name, meta in all_tables.items()
|
||||
if not (meta or {}).get("is_view") and name in entries
|
||||
and _relation_candidates(entries[name].notes)]
|
||||
return sorted(candidates, key=lambda n: (-usage.get(n, 0), order[n]))[:PROFILE_DEFAULT_TABLES]
|
||||
# 还有待核实(推断)关系的表排在前面:剖析就是来核实它们的;关系都核实过、人工确认过的再剖析只是补覆盖率。
|
||||
# 同样待核实的按使用次数,再按表结构顺序。返回全部候选,空表由 _skip_empty 估过行数再跳过
|
||||
return sorted(candidates, key=lambda n: (not _pending(entries[n].notes), -usage.get(n, 0), order[n]))
|
||||
|
||||
|
||||
def _pending(notes: dict[str, Any] | None) -> bool:
|
||||
"""这张表还有没有待核实的关系:要核对的关系里有还是推断(proposed)的。"""
|
||||
return any(r.get("status") == "proposed" for r in _relation_candidates(notes))
|
||||
|
||||
|
||||
async def _skip_empty(cx: _Context, candidates: list[str], report: ProfileReport) -> list[TableProfile]:
|
||||
"""不指定表时:按顺序估候选表的行数,确知是空表的跳过(记进 report.empty_tables),凑够 PROFILE_DEFAULT_TABLES
|
||||
张为止。以前不估,所有表使用次数都是 0 时按表结构顺序取前 10 张,结果大半是空表、一条关系都核实不了。
|
||||
|
||||
估行数的查询算进这张表的查询数,行数留在 cx.sizes 里,剖析时不再查。最多估 PROFILE_PROBE_TABLES 张、最多用掉
|
||||
查询次数上限的一半;超过了、或者整次剖析已经停下,剩下的候选不估、照顺序排上(真是空表的,剖析时各项检查会
|
||||
记下「空表,无法剖析」)。
|
||||
"""
|
||||
picked: list[TableProfile] = []
|
||||
probed = 0
|
||||
for name in candidates:
|
||||
if len(picked) >= PROFILE_DEFAULT_TABLES:
|
||||
break
|
||||
result = TableProfile(table=name)
|
||||
if (cx.run.stopped is None and probed < PROFILE_PROBE_TABLES
|
||||
and cx.run.used < cx.settings.max_queries // 2):
|
||||
probed += 1
|
||||
before = cx.run.used
|
||||
try:
|
||||
size = await cx.size(name, result)
|
||||
except _Stop:
|
||||
size = None
|
||||
result.queries = cx.run.used - before
|
||||
if size is not None and size.rows == 0:
|
||||
report.empty_tables.append(name)
|
||||
continue
|
||||
picked.append(result)
|
||||
return picked
|
||||
|
||||
|
||||
async def profile_catalog(session: AsyncSession, row: Any, source: Any, *, tables: list[str] | None = None,
|
||||
@@ -1194,11 +1242,12 @@ async def _profile(session: AsyncSession, row: Any, source: Any, tables: list[st
|
||||
run = _Runner(source, settings, dialect)
|
||||
cx = _Context(source=source, settings=settings, dialect=dialect, run=run,
|
||||
tables=(getattr(source, "schema_cache", None) or {}).get("tables") or {},
|
||||
masked={c.lower() for c in data_engine.masked_columns(getattr(row, "options", None))},
|
||||
day=at[:10])
|
||||
masked={c.lower() for c in data_engine.masked_columns(getattr(row, "options", None))})
|
||||
entries = await catalog.read_catalog(session, source.id)
|
||||
for table in await _pick_tables(session, source, tables, entries, report):
|
||||
result = TableProfile(table=table)
|
||||
picked = await _pick_tables(session, source, tables, entries, report)
|
||||
results = [TableProfile(table=t) for t in picked] if tables else await _skip_empty(cx, picked, report)
|
||||
for result in results:
|
||||
table = result.table
|
||||
report.tables.append(result)
|
||||
if run.stopped:
|
||||
detail = _STOP_DETAIL[run.stopped].format(max_queries=settings.max_queries,
|
||||
@@ -1208,7 +1257,7 @@ async def _profile(session: AsyncSession, row: Any, source: Any, tables: list[st
|
||||
before = run.used
|
||||
entry = entries.get(table)
|
||||
out = await _profile_table(cx, table, entry.notes if entry else {}, result)
|
||||
result.queries = run.used - before
|
||||
result.queries += run.used - before
|
||||
await _write(session, source.id, table, out, result, at=at, actor=actor)
|
||||
report.queries_used = run.used
|
||||
report.stopped = run.stopped
|
||||
@@ -1218,6 +1267,6 @@ async def _profile(session: AsyncSession, row: Any, source: Any, tables: list[st
|
||||
|
||||
|
||||
__all__ = ["CODES_MAX", "IN_CHUNK", "MAX_CODE_LEN", "MAX_LITERAL_LEN", "NOTE_PREFIX", "PROFILE_DEFAULT_TABLES",
|
||||
"PROFILE_OPTION", "ProfileBusy", "ProfileDisabled", "ProfileReport", "ProfileSettings", "ProfileSkip",
|
||||
"SqlDialect", "TableProfile", "TableSize", "ensure_enabled", "estimate_size", "profile_catalog",
|
||||
"profile_settings", "profile_settings_problem", "sql_literal"]
|
||||
"PROFILE_OPTION", "PROFILE_PROBE_TABLES", "ProfileBusy", "ProfileDisabled", "ProfileReport",
|
||||
"ProfileSettings", "ProfileSkip", "SqlDialect", "TableProfile", "TableSize", "ensure_enabled",
|
||||
"estimate_size", "profile_catalog", "profile_settings", "profile_settings_problem", "sql_literal"]
|
||||
|
||||
@@ -16,7 +16,10 @@
|
||||
- wrong_date_column:表定义了业务日期,查询却按这张表的另一个时间列分组或筛选。
|
||||
|
||||
**级别看依据。** 依据全是 confirmed / verified(人工确认、外键约束、数据剖析)时,fanout_sum、stock_summed 是 error,
|
||||
其余是 warning;依据里有 proposed(命名推断、模型起草)就一律降为 info。join_unconfirmed 反过来看:对上推断的关系是
|
||||
其余是 warning;依据里有 proposed(命名推断、模型起草)就一律降为 info。fanout_sum 另有一道门槛:error 只给「一对多
|
||||
确有其事」的——那条一对多的关系人工确认过,或者数据剖析在数据上核实过子表一侧的键不唯一(关系上的
|
||||
cardinality_checked)。只凭外键约束推出的一对多降为 warning、说「可能重复计算」:外键只保证父键唯一,子表一侧完全
|
||||
可能每个键恰好一行,照「会重复计算」报错就是误报,还会让出具降档。join_unconfirmed 反过来看:对上推断的关系是
|
||||
info,什么都对不上是 warning,对上有确证的关系不报。rejected 的项一律视而不见(catalog.visible_notes),被驳回的关系
|
||||
既不算「对上了」,也不拿来判断基数。
|
||||
|
||||
@@ -50,7 +53,8 @@ CHECK_CODES = ("fanout_sum", "stock_summed", "join_unconfirmed", "ratio_aggregat
|
||||
"unknown_code", "wrong_date_column")
|
||||
#: 结果的级别,从重到轻
|
||||
LEVELS = ("error", "warning", "info")
|
||||
#: 依据有确证时报 error 的规则:它们算出来的数必然是错的。其余规则只是「很可能不对」
|
||||
#: 依据有确证时报 error 的规则:照这样写,算出来的数很可能是错的。其余规则只是「可能不对」。
|
||||
#: fanout_sum 另要那条一对多的基数人工确认过、或用数据核实过(_ScopeCheck.fanout)
|
||||
_ERROR_CODES = frozenset({"fanout_sum", "stock_summed"})
|
||||
_STRONG = frozenset({"confirmed", "verified"})
|
||||
_STATUS_RANK = {"confirmed": 3, "verified": 2, "proposed": 1}
|
||||
@@ -221,6 +225,25 @@ def check_sql(sql: Any, *, kind: str | None, schema_cache: Mapping[str, Any] | N
|
||||
return SqlChecker(kind=kind, schema_cache=schema_cache, notes=notes, source_name=source_name).check(sql)
|
||||
|
||||
|
||||
def frozen_checker(schema_snapshot: Any, *, kind: str | None) -> SqlChecker | None:
|
||||
"""按表结构快照里冻结的那一版目录重建检查器:事后核对一次运行当时的 SQL 检查用。快照里没冻结目录返回 None。
|
||||
|
||||
数据源查询工具每次查询都把当时的表结构和目录冻结进表结构快照(tools/datasource._store_schema,
|
||||
catalog.frozen_catalog)。冻结的目录去掉了驳回项,只留被驳回关系的编号和状态,关系图据此不把它们按外键推回来。
|
||||
快照里没有数据源类型,方言由调用方给(数据源的 kind)。
|
||||
"""
|
||||
if not isinstance(schema_snapshot, Mapping):
|
||||
return None
|
||||
frozen = schema_snapshot.get("catalog")
|
||||
tables = schema_snapshot.get("tables")
|
||||
if not isinstance(frozen, Mapping) or not frozen or not isinstance(tables, Mapping):
|
||||
return None
|
||||
notes = {str(name): entry.get("notes") for name, entry in frozen.items()
|
||||
if isinstance(entry, Mapping) and isinstance(entry.get("notes"), Mapping)}
|
||||
cache = {"tables": tables, **({"schema": schema_snapshot["schema"]} if schema_snapshot.get("schema") else {})}
|
||||
return SqlChecker(kind=kind, schema_cache=cache, notes=notes, source_name=schema_snapshot.get("source"))
|
||||
|
||||
|
||||
def _fold(found: list[SqlCheck]) -> list[SqlCheck]:
|
||||
"""同一件事只报一次(规则、表、列、关系相同的留最重的那条),重的在前,最多 MAX_CHECKS 条。"""
|
||||
kept: dict[tuple[Any, ...], SqlCheck] = {}
|
||||
@@ -681,6 +704,12 @@ class _ScopeCheck:
|
||||
[status] + [e.status for e in path], counting=isinstance(node, exp.Count)))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _one_to_many_established(edge: catalog.JoinEdge) -> bool:
|
||||
"""这条一对多是不是确有其事:人工确认过(基数是人定的),或者数据剖析在数据上核实过子表一侧的键不唯一
|
||||
(cardinality_checked)。外键约束、命名推断给的基数只是按表结构推的:子表一侧可能每个键恰好一行。"""
|
||||
return edge.status == "confirmed" or edge.cardinality_checked
|
||||
|
||||
def _fanout_basis(self, table: _Table, columns: list[str], *, counting: bool) -> tuple[str, str] | None:
|
||||
"""参数里能说明「这是一张表自己的数」的那一列和它的依据:求和看度量类型(流量、存量),
|
||||
计数另外认标识列和业务主键(数订单数却数成了明细行数)。"""
|
||||
@@ -698,6 +727,18 @@ class _ScopeCheck:
|
||||
path: list[catalog.JoinEdge], statuses: list[str], *, counting: bool) -> SqlCheck:
|
||||
what = "计数" if counting else "求和"
|
||||
excerpt = self.excerpt(node)
|
||||
level = _level("fanout_sum", statuses)
|
||||
if not self._one_to_many_established(path[-1]):
|
||||
# 只凭表结构推出的一对多:不说「会重复计算」,最多是提醒;下一步先确认是不是真的一对多
|
||||
return SqlCheck(
|
||||
code="fanout_sum", level="warning" if level == "error" else level, table=table.name, column=column,
|
||||
relation_id=path[-1].relation_id, sql_excerpt=excerpt,
|
||||
message=(f"按表结构,「{via.label()}」关联「{many.label()}」是一对多,"
|
||||
f"对「{table.label()}」的「{table.column_label(column)}」{what}可能重复计算。"
|
||||
f"请确认关联表「{many.label()}」里每个键只有一行,或先汇总再关联"),
|
||||
for_model=(f"按表结构,{via.name} 关联 {many.name} 是一对多(这个基数没用数据核对过),"
|
||||
f"{excerpt or what} 可能把 {table.name}.{column} 重复计算。确认 {many.name} 里每个关联键"
|
||||
f"只有一行;不确定就先在子查询里把 {many.name} 汇总成每条 {via.name} 一行再关联"))
|
||||
if via.alias == table.alias:
|
||||
head = f"「{table.label()}」关联「{many.label()}」是一对多,"
|
||||
model_head = f"{table.name} 关联 {many.name} 是一对多(一行 {table.name} 对多行 {many.name}),"
|
||||
@@ -721,7 +762,7 @@ class _ScopeCheck:
|
||||
model_fix = (f"先在子查询里把 {many.name} 按关联列汇总成每条 {via.name} 一行再关联;用不到 {many.name} 的列"
|
||||
f"就去掉这个关联")
|
||||
return SqlCheck(
|
||||
code="fanout_sum", level=_level("fanout_sum", statuses), table=table.name, column=column,
|
||||
code="fanout_sum", level=level, table=table.name, column=column,
|
||||
relation_id=path[-1].relation_id, sql_excerpt=excerpt,
|
||||
message=f"{head}对「{table.label()}」的「{table.column_label(column)}」{what}会重复计算。{fix}",
|
||||
for_model=f"{model_head}{excerpt or what} 会把 {table.name}.{column} 重复计算。{model_fix}")
|
||||
|
||||
@@ -2631,7 +2631,8 @@ def compose_doc(
|
||||
"markdown": markdown, "source": source, "catalog": kept, "blocks": out_blocks,
|
||||
}
|
||||
checked = verify_doc(doc, catalog, allow_numbers=allow_numbers, cells_allowed=cells_allowed, loader=snaps)
|
||||
doc["stats"], doc["violations"] = checked["stats"], checked["violations"]
|
||||
# 句中的 [[see:]] 只在组装时查(交回写作者重写):出口复核看的是数字和出处,句子通不通不影响出具
|
||||
doc["stats"], doc["violations"] = checked["stats"], checked["violations"] + inline_see(source)
|
||||
return doc
|
||||
|
||||
|
||||
@@ -2999,6 +3000,38 @@ MARKER_RULES = """写作规则(系统会逐字核对):
|
||||
4. 日期、ISO 周(2026-W37)、「前 3 名」「第 2 季度」这类序号可以直接写。
|
||||
5. 目录里没有的指标不要编造引用;标着「没有值」的指标不要写进报告。"""
|
||||
|
||||
#: 跟在写作规则后面的两条(R2 走查 A4、B4):写作规则本身保持一期那份,这两条另起一段
|
||||
#: - [[see:]] 渲染后不显示:写进句子中间(「以 [[see:Q1]] 为依据看」)会留下「以 为依据看」这样的断句;
|
||||
#: - 码值(status = 9 里的 9)是没有出处的数字,会被数字核对打回重写:写它的含义,不写码值本身。
|
||||
SEE_AND_CODE_RULES = (
|
||||
"另外两条:\n"
|
||||
"- [[see:…]] 渲染后不显示,只能挂在句末(句号前后都行)。不要把它写进句子当成分:「以 [[see:Q1]] 为依据看,……」"
|
||||
"「根据 [[see:Q1]],……」渲染后会变成「以 为依据看」「根据 ,」这样的断句。先说结论,句末再写 [[see:Q1]]。\n"
|
||||
"- 涉及码值(状态、类型这类用数字编码的取值)时,写它的含义,比如「作废记录」「有效记录」,不要写码值本身"
|
||||
"(「状态为 9」「类型 1」):码值是没有出处的数字,系统会当成裸数字打回重写。"
|
||||
)
|
||||
|
||||
#: 句中的 [[see:]]:前面是介词、后面接着句子的写法(「以 [[see:Q1]] 为依据」「根据 [[see:Q1]],」「详见 [[see:Q1]]」)。
|
||||
#: 只认这几种拿得准的:「以」前面是「所、可、加……」的是另一个词(所以、可以),不算;「依据 [[see:…]]。」可能是
|
||||
#: 「这是结论的依据」,不算。认出来就交回写作者重写(report.REWRITE_ONLY:重写不好也不判失败)
|
||||
_SEE_MARK = r"\[\[" + _MARKER_GUARD + r"[ \t]*see[ \t]*:[^\[\]\n]*?\]\]"
|
||||
_INLINE_SEE = re.compile(
|
||||
r"(?<![所可加予得难足用是何之])以[ \t\u3000]*" + _SEE_MARK + r"[ \t\u3000]*为"
|
||||
r"|(?:根据|按照|基于|参见|详见)[ \t\u3000]*" + _SEE_MARK
|
||||
)
|
||||
INLINE_SEE_MESSAGE = _Reason(
|
||||
"依据标记写在了句子中间:依据不显示,正文会留下「以 为依据」这样的断句",
|
||||
"依据标记 [[see:…]] 写在了句子中间。它渲染后不显示,只能挂在句末:把这一句改成先说结论、句末再写 [[see:…]],"
|
||||
"不要写「以 [[see:Q1]] 为依据」「根据 [[see:Q1]]」「详见 [[see:Q1]]」",
|
||||
)
|
||||
|
||||
|
||||
def inline_see(source: str) -> list[dict[str, Any]]:
|
||||
"""原文里写在句子中间的 [[see:]](_INLINE_SEE),每处一条违规 inline_see。text 是那一截原文,没有 span:
|
||||
标记渲染后不在正文里,定位不到片段。"""
|
||||
return [_violation("inline_see", INLINE_SEE_MESSAGE, text=m.group(0)) for m in _INLINE_SEE.finditer(source or "")]
|
||||
|
||||
|
||||
#: 引用查询结果的写法。只跟着目录里的查询出现(catalog_prompt):写作规则本身保持一期那份,升级前
|
||||
#: 发起的运行跑到报告节点时提示一字不差;只有口径卡的目录也不该教写作者去引用不存在的 Q1
|
||||
CELL_RULES = (
|
||||
@@ -3044,6 +3077,23 @@ _PROMPT_HITS = 8
|
||||
_PROMPT_HIT_CHARS = 300
|
||||
|
||||
|
||||
def _sql_check_note(artifact: Any, snaps: _Snapshots) -> str | None:
|
||||
"""这次查询(合并查询则是它的输入)没通过 SQL 检查时,写作目录里跟在它后面的那句提醒;没问题返回 None。
|
||||
|
||||
口径卡的指标早就标「存疑」了,直接引用查询格子的写作者却看不到:报告照样把一对多关联后求和的数写成定论。
|
||||
出具契约会按缺口降档(issuance.sql_check_gaps),这里先让写作者知道、引用时如实交代。
|
||||
"""
|
||||
from app.engine.sql_problems import query_problems
|
||||
|
||||
found = query_problems(artifact, loader=snaps.loader)
|
||||
if not found:
|
||||
return None
|
||||
problems = list(dict.fromkeys(text for p in found for text in p.problems))
|
||||
who = "这次查询" if all(p.artifact == artifact for p in found) else "这次合并的输入查询"
|
||||
return (f" ({who}未通过 SQL 检查:{';'.join(problems[:3]) or '有错误级的问题'}。其中的数存疑:"
|
||||
"引用时须如实说明,不要当作确定的结论)")
|
||||
|
||||
|
||||
def _query_prompt(entry: dict[str, Any], snaps: _Snapshots, cells_allowed: bool) -> list[str]:
|
||||
"""一次查询在写作目录里的样子:编号、来源、列,以及能引用的行(行号 + 渲染后的值)。
|
||||
|
||||
@@ -3058,6 +3108,8 @@ def _query_prompt(entry: dict[str, Any], snaps: _Snapshots, cells_allowed: bool)
|
||||
if snapshot.get("truncated") is True:
|
||||
lines.append(" (查询结果已截断:只取回了前面一部分行,库里还有更多。单格可以引用;"
|
||||
"不要把取回的行数当成总数,也不要据此写合计、全部之类的结论)")
|
||||
if note := _sql_check_note(entry.get("artifact"), snaps):
|
||||
lines.append(note)
|
||||
if not cells_allowed:
|
||||
return lines
|
||||
columns = [str(c) for c in snapshot.get("columns") or []][:_PROMPT_COLS]
|
||||
|
||||
@@ -4,6 +4,8 @@ import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.engine.sql_problems import problem_clause, query_problems
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 出具校验:叙述里的每个数字必须能回指到指标集
|
||||
#
|
||||
@@ -462,15 +464,67 @@ def incomplete_gaps(metrics: list[dict[str, Any]]) -> list[str]:
|
||||
for m in metrics if isinstance(m, dict) and m.get("incomplete")]
|
||||
|
||||
|
||||
def sql_check_gaps(metrics: list[dict[str, Any]]) -> list[str]:
|
||||
"""契约收来的指标里来源查询没通过 SQL 检查的(口径卡标了 sql_check_failed:取数的那条 SQL 对照数据目录查出
|
||||
error 级问题,比如一对多关联之后对「一」那一侧求和),每个一句缺口。
|
||||
def sql_check_gaps(metrics: list[dict[str, Any]], cited: dict[str, list[str]] | None = None, *,
|
||||
label: Callable[[str, str | None], str | None] | None = None) -> list[str]:
|
||||
"""sql_check_findings 的那几句缺口(见下)。"""
|
||||
return [f["text"] for f in sql_check_findings(metrics, cited, label=label)]
|
||||
|
||||
和 incomplete_gaps 同一个道理:数字照样回指得上口径卡,口径卡照样复算一致,但算它的那条查询本身就把数算错了
|
||||
(重复计算、存量跨期加总),盖完整出具的章等于替一个错数作保。原因用口径卡记下的那句,写明是哪条检查。
|
||||
|
||||
def sql_check_findings(metrics: list[dict[str, Any]], cited: dict[str, list[str]] | None = None, *,
|
||||
label: Callable[[str, str | None], str | None] | None = None) -> list[dict[str, Any]]:
|
||||
"""没通过 SQL 检查(error 级:一对多关联后重复计算、存量跨期加总)的查询,每条一句缺口。
|
||||
|
||||
两处来历:契约收来的指标(口径卡标了 sql_check_failed,sql_check_sources 记着取数的查询快照),以及报告直接
|
||||
引用的查询(cited:{查询快照 id: [引用的写法…]},单元格、表格、[[see:]] 依据)。数字照样回指得上,口径卡照样
|
||||
复算一致,但算它的那条查询本身就把数算错了,盖完整出具的章等于替一个错数作保。
|
||||
|
||||
按出问题的那条查询归并(合并查询顺着输入找到源查询):同一条查询算出三个指标、报告又引用了它的格,也只记一句,
|
||||
句子里列出受影响的引用。label(快照 id, 节点 id) 给出「查询「取数」(Q1)」这样的称呼,给不出就写「所依据的查询」。
|
||||
指标标了 sql_check_failed、快照却读不出来(被清理、被改过)的,退回口径卡记下的那句:缺口不能因为读不到快照就消失。
|
||||
|
||||
每条一个 dict:text(缺口那句)、query(称呼)、artifact、node_id、problems、refs。出具声明里另存一份
|
||||
sql_checks:报告页据此在显眼处说「因为 SQL 检查没通过而降档」,不用从缺口的中文里认。
|
||||
"""
|
||||
return [f"指标「{m.get('name') or m.get('id')}」{m.get('sql_check_reason') or '所依据的查询未通过 SQL 检查'}"
|
||||
for m in metrics if isinstance(m, dict) and m.get("sql_check_failed")]
|
||||
groups: dict[str, dict[str, Any]] = {}
|
||||
fallback: list[dict[str, Any]] = []
|
||||
|
||||
def add(artifact: Any, ref: str) -> bool:
|
||||
found = query_problems(artifact) if isinstance(artifact, str) and artifact else []
|
||||
for problem in found:
|
||||
group = groups.setdefault(problem.artifact, {"problem": problem, "refs": []})
|
||||
if group["problem"].node_id is None and problem.node_id:
|
||||
group["problem"].node_id = problem.node_id
|
||||
if ref not in group["refs"]:
|
||||
group["refs"].append(ref)
|
||||
return bool(found)
|
||||
|
||||
for m in metrics:
|
||||
if not (isinstance(m, dict) and m.get("sql_check_failed")):
|
||||
continue
|
||||
name = f"指标「{m.get('name') or m.get('id')}」"
|
||||
hits = [add(src.get("artifact"), name) for src in m.get("sql_check_sources") or [] if isinstance(src, dict)]
|
||||
if not any(hits):
|
||||
fallback.append({"text": f"{name}{m.get('sql_check_reason') or '所依据的查询未通过 SQL 检查'}",
|
||||
"query": None, "artifact": None, "node_id": None, "problems": [], "refs": [name]})
|
||||
for artifact, refs in (cited or {}).items():
|
||||
for ref in refs:
|
||||
add(artifact, ref)
|
||||
|
||||
out = []
|
||||
for artifact, group in groups.items():
|
||||
problem = group["problem"]
|
||||
named = label(artifact, problem.node_id) if label else None
|
||||
who = named or "所依据的查询"
|
||||
refs = group["refs"]
|
||||
listed = "、".join(refs[:_SQL_REFS]) + (f"等 {len(refs)} 处" if len(refs) > _SQL_REFS else "")
|
||||
out.append({"text": f"{who}{problem_clause(problem.problems)};受影响的引用:{listed}", "query": named,
|
||||
"artifact": artifact, "node_id": problem.node_id, "problems": problem.problems,
|
||||
"refs": refs[:_SQL_REFS * 2]})
|
||||
return out + fallback
|
||||
|
||||
|
||||
#: 一句 SQL 检查缺口里最多列出几处受影响的引用(计数照实)
|
||||
_SQL_REFS = 8
|
||||
|
||||
|
||||
def _claims_effect(
|
||||
|
||||
@@ -834,7 +834,8 @@ def _warnings(stmt: str, inputs: list[MergeInput], tables: dict[str, list[str]],
|
||||
else:
|
||||
tail = ("SQLite 比较时会做隐式转换:文本形式的编号(如 '001'、'01')都会等于数值 1,也可能完全匹配不上。"
|
||||
"请在源查询中统一类型,或在合并 SQL 中用 CAST 明确转换")
|
||||
out.append({"code": "key_type_mismatch", "keys": [f"{a}.{ac}", f"{b}.{bc}"],
|
||||
# keys、detail 是给界面读的结构化字段(运行时间线的标题、副标题),不让它从 message 里解析中文
|
||||
out.append({"code": "key_type_mismatch", "keys": [f"{a}.{ac}", f"{b}.{bc}"], "detail": f"{left},{right}",
|
||||
"message": f"合并键类型不一致:{left},{right}。{tail}"})
|
||||
largest = max(inputs, key=lambda inp: len(inp.snapshot["rows"]))
|
||||
biggest = len(largest.snapshot["rows"])
|
||||
@@ -846,12 +847,13 @@ def _warnings(stmt: str, inputs: list[MergeInput], tables: dict[str, list[str]],
|
||||
keys[alias].append(col)
|
||||
dups = [_duplicates(alias, snaps[alias], cols) for alias, cols in keys.items()]
|
||||
detail = ";".join(d for d in dups if d)
|
||||
out.append({"code": "rows_grew", "message": (
|
||||
out.append({"code": "rows_grew", "rows": len(rows), "input": largest.alias, "input_rows": biggest,
|
||||
**({"duplicates": detail} if detail else {}), "message": (
|
||||
f"合并结果有 {len(rows)} 行,多于行数最多的输入「{largest.alias}」({biggest} 行):合并键可能不唯一,"
|
||||
"同一行被重复匹配。" + (f"{detail}。" if detail else "")
|
||||
+ "请检查合并条件是否覆盖了全部键(例如同时按日期和门店),或先在源库里聚合到相同粒度")})
|
||||
if truncated:
|
||||
out.append({"code": "result_truncated", "message": (
|
||||
out.append({"code": "result_truncated", "rows": len(rows), "max_rows": limits.max_rows, "message": (
|
||||
f"合并结果超过上限({limits.max_rows} 行或约 {max(1, limits.max_bytes // 1_000_000)} MB),只保留了前 "
|
||||
f"{len(rows)} 行,下游拿到的不是完整结果。请在合并 SQL 中聚合或加条件缩小范围")})
|
||||
return out
|
||||
|
||||
@@ -147,7 +147,7 @@ def _apply_contract(
|
||||
) -> dict[str, Any]:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.engine.issuance import decide_tier, incomplete_gaps, sql_check_gaps, trace_numbers
|
||||
from app.engine.issuance import decide_tier, incomplete_gaps, sql_check_findings, trace_numbers
|
||||
|
||||
nodes = state.get("nodes") or {}
|
||||
# 写了 report_from 就是引用模式:按报告文档逐段复核,不再按数值回指叙述
|
||||
@@ -188,8 +188,9 @@ def _apply_contract(
|
||||
gaps.append(f"指标来源未解析:{'、'.join(unresolved[:5])}")
|
||||
# 拿截断的查询结果整组算出来的指标:数回指得上,但算的只是取回的那一截,不能完整出具
|
||||
gaps.extend(incomplete_gaps(metrics))
|
||||
# 来源查询没通过 SQL 检查(error 级:重复计算、存量跨期加总)的指标:口径卡复算得一致,算的却是错数
|
||||
gaps.extend(sql_check_gaps(metrics))
|
||||
# 来源查询没通过 SQL 检查(error 级:重复计算、存量跨期加总):口径卡复算得一致,算的却是错数。
|
||||
# 报告直接引用的查询要等引用核对之后才知道,缺口放在这个位置,下面一起算
|
||||
sql_at = len(gaps)
|
||||
|
||||
# 引用模式下,缺输入记成空值的指标(口径卡 on_missing=null)就是缺:报告里引用不了它,
|
||||
# 也不能因为 id 在清单里就算「齐了」。旧模式照旧只看 id,行为不变
|
||||
@@ -222,13 +223,37 @@ def _apply_contract(
|
||||
)
|
||||
unmatched = trace.unmatched if trace else []
|
||||
|
||||
# 同一条查询算出几个指标、报告又引用了它的格,只记一句(按出问题的那条查询归并,列出受影响的引用)
|
||||
titles = {n.id: n.title for n in ctx.run.spec.nodes}
|
||||
aliases: dict[str, str] = cited.get("aliases") or {}
|
||||
|
||||
def query_label(artifact: str, node_id: str | None) -> str:
|
||||
from app.engine.sql_problems import node_of
|
||||
|
||||
title = titles.get(node_id or node_of(artifact, state.get("evidence")) or "")
|
||||
alias = aliases.get(artifact)
|
||||
if title and alias:
|
||||
return f"查询「{title}」({alias})"
|
||||
return f"查询「{title}」" if title else (f"查询 {alias}" if alias else "")
|
||||
|
||||
findings = sql_check_findings(metrics, cited.get("queries"), label=query_label)
|
||||
gaps[sql_at:sql_at] = [f["text"] for f in findings]
|
||||
# 出具声明另存一份结构化的:报告页在显眼处说「因为 SQL 检查没通过而降档」,不从缺口的中文里认。没有就不加这个键
|
||||
from app.engine.sql_problems import node_of
|
||||
|
||||
for f in findings:
|
||||
if not f.get("node_id") and f.get("artifact"):
|
||||
f["node_id"] = node_of(f["artifact"], state.get("evidence"))
|
||||
# gap 是 gaps 里对应的那一句:界面单列这几条时,据它不在「其余缺口」里重复
|
||||
sql_checks = [{**{k: f[k] for k in ("query", "node_id", "problems", "refs") if f.get(k)}, "gap": f["text"]}
|
||||
for f in findings]
|
||||
|
||||
# 声明了 metrics_from 却一个指标都没收到,同样是"没查成"
|
||||
if sources and not metrics:
|
||||
gaps.append("指标集为空,叙述中的数字无法追溯")
|
||||
|
||||
# 上游有协作团队用完轮数、按降档交付的:叙述里的话不是调度者认可的结论,
|
||||
# 数字全都对得上也不能盖「完整出具」
|
||||
titles = {n.id: n.title for n in ctx.run.spec.nodes}
|
||||
for node_id, payload in nodes.items():
|
||||
if isinstance(payload, dict) and payload.get("exhausted"):
|
||||
gaps.append(f"协作团队「{titles.get(node_id, node_id)}」用完 {payload.get('rounds', '?')} "
|
||||
@@ -250,7 +275,7 @@ def _apply_contract(
|
||||
return _declare_citations(tier, cited, calibers=calibers, metrics=metrics, gaps=gaps,
|
||||
missing_required=missing_required, missing_expected=missing_expected,
|
||||
report_from=str(report_from), declared_at=datetime.now(timezone.utc),
|
||||
ctx=ctx)
|
||||
ctx=ctx, sql_checks=sql_checks)
|
||||
|
||||
# 逐个数字的出处。以前只有一个计数,界面标不出「这个数来自哪个指标」
|
||||
matched = [
|
||||
@@ -269,6 +294,7 @@ def _apply_contract(
|
||||
# 校验没跑全的原因照实印出来——读的人要能分辨"查过都对"和"根本没查"
|
||||
"gaps": gaps,
|
||||
"declared_at": datetime.now(timezone.utc).isoformat(),
|
||||
**({"sql_checks": sql_checks} if sql_checks else {}),
|
||||
}
|
||||
ctx.emit(
|
||||
EventType.ISSUANCE,
|
||||
@@ -283,6 +309,7 @@ def _apply_contract(
|
||||
metrics_checked=len(metrics),
|
||||
matched_numbers=len(trace.matched) if trace else 0,
|
||||
matched=matched,
|
||||
**({"sql_checks": sql_checks} if sql_checks else {}),
|
||||
)
|
||||
return issuance
|
||||
|
||||
@@ -318,7 +345,7 @@ def _check_citations(
|
||||
|
||||
out: dict[str, Any] = {"matched": [], "unmatched": [], "unresolved": [], "gaps": [],
|
||||
"doc_artifact": None, "stats": None, "claims_policy": None, "uncited": None,
|
||||
"unsupported": None, "claims": None, "entities": None}
|
||||
"unsupported": None, "claims": None, "entities": None, "queries": {}, "aliases": {}}
|
||||
gaps = out["gaps"]
|
||||
spec = ctx.run.spec
|
||||
node = spec.node_map().get(report_from)
|
||||
@@ -384,6 +411,8 @@ def _check_citations(
|
||||
out["entities"] = {"unknown": unknown[:_LISTED], "unverified": unverified[:_LISTED],
|
||||
"counted": governed and bool(unknown)}
|
||||
|
||||
out["queries"], out["aliases"] = _cited_queries(doc, catalog)
|
||||
|
||||
# 老前端要用的逐个数字出处,从复核通过的数字片段拼出来
|
||||
for _, unit in iter_units(doc):
|
||||
for seg in unit.get("segments") or []:
|
||||
@@ -524,10 +553,50 @@ def _claims(out: dict[str, Any], contract: dict[str, Any], payload: dict[str, An
|
||||
}
|
||||
|
||||
|
||||
def _cited_queries(doc: dict[str, Any], catalog: dict[str, Any]) -> tuple[dict[str, list[str]], dict[str, str]]:
|
||||
"""报告直接引用的查询:({查询快照 id: [引用的写法…]}, {目录里每个查询的快照 id: 编号})。
|
||||
|
||||
单元格([[v:Q1.r0.gmv]],[[table:]] 展开后也是一格一格的引用)按查询数:一格写「Q1 第 1 行「gmv」」,
|
||||
几格写「Q1 的 3 格」;只拿它当依据([[see:Q1]])的写「Q1(结论依据)」。出具契约据此判这些查询有没有通过
|
||||
SQL 检查(issuance.sql_check_gaps)。
|
||||
"""
|
||||
from app.engine.evidence import iter_units
|
||||
|
||||
cells: dict[str, list[tuple[Any, Any]]] = {}
|
||||
support: list[str] = []
|
||||
for _, unit in iter_units(doc):
|
||||
for seg in unit.get("segments") or []:
|
||||
cite = seg.get("cite") or {}
|
||||
if cite.get("kind") == "cell" and cite.get("status") == "resolved" and cite.get("alias"):
|
||||
loc = cite.get("locator") or {}
|
||||
cells.setdefault(str(cite["alias"]), [])
|
||||
if (loc.get("row"), loc.get("column")) not in cells[str(cite["alias"])]:
|
||||
cells[str(cite["alias"])].append((loc.get("row"), loc.get("column")))
|
||||
for cite in unit.get("see") or []:
|
||||
alias = str((cite or {}).get("alias") or "")
|
||||
if (catalog.get(alias) or {}).get("kind") == "query" and alias not in support:
|
||||
support.append(alias)
|
||||
queries: dict[str, list[str]] = {}
|
||||
# 目录里全部查询的编号:合并查询的输入没被直接引用,缺口里也要写得出它是 Q 几
|
||||
aliases = {str(e["artifact"]): str(e["alias"]) for e in catalog.values()
|
||||
if isinstance(e, dict) and e.get("kind") == "query" and e.get("artifact") and e.get("alias")}
|
||||
for alias in [*cells, *(a for a in support if a not in cells)]:
|
||||
artifact = (catalog.get(alias) or {}).get("artifact")
|
||||
if not isinstance(artifact, str) or not artifact:
|
||||
continue
|
||||
hit = cells.get(alias) or []
|
||||
if len(hit) == 1 and isinstance(hit[0][0], int):
|
||||
ref = f"{alias} 第 {hit[0][0] + 1} 行「{hit[0][1]}」"
|
||||
else:
|
||||
ref = f"{alias} 的 {len(hit)} 格" if hit else f"{alias}(结论依据)"
|
||||
queries.setdefault(artifact, []).append(ref)
|
||||
return queries, aliases
|
||||
|
||||
|
||||
def _declare_citations(
|
||||
tier: str, cited: dict[str, Any], *, calibers: list[dict[str, str]], metrics: list[dict[str, Any]],
|
||||
gaps: list[str], missing_required: list[str], missing_expected: list[str], report_from: str,
|
||||
declared_at: Any, ctx: NodeContext,
|
||||
declared_at: Any, ctx: NodeContext, sql_checks: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""引用模式的 _issuance。旧字段一个不少(老前端照常显示),另加 mode、report、unresolved。"""
|
||||
report = {"node_id": report_from, "doc_artifact": cited["doc_artifact"]}
|
||||
@@ -549,6 +618,8 @@ def _declare_citations(
|
||||
# 结论句策略和可疑实体:只在用上时才有这两个键,升级前的运行和没用上的契约形状不变
|
||||
**({"claims": cited["claims"]} if cited.get("claims") else {}),
|
||||
**({"entities": cited["entities"]} if cited.get("entities") else {}),
|
||||
# 没通过 SQL 检查的查询(结构化):报告页据此在显眼处说明降档原因。没有就不加这个键
|
||||
**({"sql_checks": sql_checks} if sql_checks else {}),
|
||||
}
|
||||
entities = cited.get("entities")
|
||||
ctx.emit(
|
||||
@@ -562,6 +633,7 @@ def _declare_citations(
|
||||
unresolved=len(cited["unresolved"]),
|
||||
calibers=calibers,
|
||||
gaps=gaps,
|
||||
**({"sql_checks": sql_checks} if sql_checks else {}),
|
||||
metrics_checked=len(metrics),
|
||||
matched_numbers=len(cited["matched"]),
|
||||
matched=cited["matched"][:50],
|
||||
|
||||
@@ -47,6 +47,7 @@ from app.providers.factory import (
|
||||
bind_tools_safely,
|
||||
get_chat_model,
|
||||
)
|
||||
from app.engine.sql_problems import event_checks
|
||||
from app.tools.datasource import QUERY_PREFIX, run_versions
|
||||
from app.tools.registry import (
|
||||
ToolArgsError,
|
||||
@@ -518,6 +519,8 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
**({"query_artifact": query["artifact"]} if query else {}),
|
||||
# 查询当时数据源的表结构快照:和查询快照一样落在封存范围内,证据接口从这里认它
|
||||
**({"schema_artifact": query["schema_artifact"]} if query and query.get("schema_artifact") else {}),
|
||||
# 这次查询的 SQL 检查结果单独带上:preview 截到前 2000 个字符,checks 通常在截掉的那段里
|
||||
**({"checks": checks} if ok and name.startswith(QUERY_PREFIX) and (checks := event_checks(content)) else {}),
|
||||
**extra,
|
||||
)
|
||||
outcome: dict[str, Any] = {"content": content, "ok": ok, "duration_ms": elapsed}
|
||||
|
||||
@@ -108,8 +108,10 @@ async def run_merge(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
preview_rows=outcome.rows[:PREVIEW_ROWS], duration_ms=elapsed, query_artifact=artifact,
|
||||
lineage=outcome.lineage is not None)
|
||||
for warning in outcome.warnings:
|
||||
# 结构化字段(keys、detail、rows、input、input_rows、duplicates、max_rows)随日志带上:界面读字段,不解析中文
|
||||
fields = {k: v for k, v in warning.items() if k not in ("code", "message")}
|
||||
ctx.emit(EventType.LOG, level="warn", message=warning["message"],
|
||||
code=LOG_CODES.get(warning["code"], "merge_warning"))
|
||||
code=LOG_CODES.get(warning["code"], "merge_warning"), **fields)
|
||||
|
||||
output: dict[str, Any] = {
|
||||
"artifact": artifact, "columns": outcome.columns, "rows": outcome.rows, "row_count": len(outcome.rows),
|
||||
|
||||
@@ -33,7 +33,7 @@ from app.engine.expressions import (
|
||||
substitute,
|
||||
)
|
||||
from app.engine.labels import field_label
|
||||
from app.engine.merge_query import MERGE_SOURCE
|
||||
from app.engine.sql_problems import CHECK_FIELDS, QueryProblem, merge_problems, node_of, query_problems, reason_text
|
||||
from app.engine.state import GraphState, template_context
|
||||
|
||||
|
||||
@@ -75,8 +75,11 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
|
||||
metrics: list[dict[str, Any]] = []
|
||||
errors: list[str] = []
|
||||
#: 查询快照工件 id → 它的 error 级检查结果。一张卡里多个指标常常取自同一次查询,快照只读一次
|
||||
checked: dict[str, list[dict[str, Any]]] = {}
|
||||
#: 查询快照工件 id → 它(含合并查询的输入)没通过 SQL 检查的那几条查询。一张卡里多个指标常常取自同一次查询,
|
||||
#: 快照只读一次
|
||||
checked: dict[str, list[QueryProblem]] = {}
|
||||
#: 指标 id → 它没通过 SQL 检查的那几条来源查询。运行日志按查询归并(_emit_sql_check_logs)
|
||||
failed_by: dict[str, list[QueryProblem]] = {}
|
||||
for definition in definitions:
|
||||
metric_id = str(definition.get("id") or "").strip()
|
||||
expr = str(definition.get("expression") or "").strip()
|
||||
@@ -138,7 +141,8 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
if failed := _failed_queries(inputs, list(use.sources.values()), paths, tctx, checked):
|
||||
sql_check = {"sql_check_failed": True, "sql_check_reason": _sql_check_reason(failed),
|
||||
"sql_check_sources": [{"artifact": artifact, "codes": list(dict.fromkeys(
|
||||
str(c.get("code")) for c in found))} for artifact, found in failed]}
|
||||
code for p in found for code in p.codes))} for artifact, found in failed]}
|
||||
failed_by[metric_id] = [p for _, found in failed for p in found]
|
||||
metrics.append(
|
||||
{
|
||||
"id": metric_id,
|
||||
@@ -177,11 +181,11 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
]
|
||||
for m in metrics:
|
||||
if m.get("incomplete"):
|
||||
ctx.emit(EventType.LOG, level="warn", code="metric_incomplete", metric=m["id"],
|
||||
# 结构化字段(metric_name、reason、rows)给界面读,不让它从 message 里解析中文
|
||||
ctx.emit(EventType.LOG, level="warn", code="metric_incomplete", metric=m["id"], metric_name=m["name"],
|
||||
reason=m["incomplete_reason"], rows=[s.get("rows") for s in m.get("truncated_sources") or []],
|
||||
message=f"指标「{m['name']}」{m['incomplete_reason']}")
|
||||
if m.get("sql_check_failed"):
|
||||
ctx.emit(EventType.LOG, level="warn", code="metric_sql_check", metric=m["id"],
|
||||
message=f"指标「{m['name']}」{m['sql_check_reason']}")
|
||||
_emit_sql_check_logs(metrics, failed_by, state, ctx)
|
||||
card = {
|
||||
"kind": "metric_set",
|
||||
"caliber": caliber,
|
||||
@@ -354,9 +358,10 @@ _LAST_STEP = re.compile(r"(?:\.[^.\[\]]+|\[[^\[\]]*\])$")
|
||||
|
||||
|
||||
def _failed_queries(inputs: list[dict[str, Any]], truncated: list[dict[str, Any]], paths: list[str],
|
||||
tctx: dict[str, Any], checked: dict[str, list[dict[str, Any]]],
|
||||
) -> list[tuple[str, list[dict[str, Any]]]]:
|
||||
"""这个指标用到的查询里,SQL 检查有 error 的:[(查询快照工件 id, error 级检查结果)]。
|
||||
tctx: dict[str, Any], checked: dict[str, list[QueryProblem]],
|
||||
) -> list[tuple[str, list[QueryProblem]]]:
|
||||
"""这个指标用到的查询里,SQL 检查有 error 的:[(查询快照工件 id, 没通过检查的查询)]。合并查询的快照对应它出问题的
|
||||
那几个输入(sql_problems.query_problems)。
|
||||
|
||||
用到了哪些查询,三处来历合起来认:输入的出处(cell() 取的格、Agent 经 cite_fields 交来的字段都带着快照 id)、
|
||||
截断跟踪记下的整组、取值链上的查询结果本身(数据整形解析过的 vars.res.rows[0][0],往上找到 vars.res 那份
|
||||
@@ -368,7 +373,7 @@ def _failed_queries(inputs: list[dict[str, Any]], truncated: list[dict[str, Any]
|
||||
out = []
|
||||
for artifact in dict.fromkeys(a for a in artifacts if isinstance(a, str) and a):
|
||||
if artifact not in checked:
|
||||
checked[artifact] = _error_checks(artifact)
|
||||
checked[artifact] = query_problems(artifact)
|
||||
if checked[artifact]:
|
||||
out.append((artifact, checked[artifact]))
|
||||
return out
|
||||
@@ -394,41 +399,49 @@ def _result_artifact(path: str, tctx: dict[str, Any]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _error_checks(artifact: str, _seen: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
"""这份查询快照对照数据目录查出的 error 级问题。
|
||||
|
||||
合并查询的快照没有自己的 checks(它在内存 SQLite 上执行,不对照数据目录),但记着 inputs:顺着往下找。
|
||||
不然源库那条查询一对多关联后重复计算了,经过一次合并,指标就看不出来、照样完整出具。
|
||||
"""
|
||||
seen = _seen if _seen is not None else set()
|
||||
if artifact in seen:
|
||||
return []
|
||||
seen.add(artifact)
|
||||
try:
|
||||
snapshot = artifact_store.load(artifact)
|
||||
except Exception: # noqa: BLE001 - 快照读不出来、被改过:这里不报,证据层另有说法
|
||||
return []
|
||||
if not isinstance(snapshot, dict):
|
||||
return []
|
||||
checks = snapshot.get("checks")
|
||||
found = [c for c in checks if isinstance(c, dict) and c.get("level") == "error"] if isinstance(checks, list) else []
|
||||
inputs = snapshot.get("inputs") if snapshot.get("source") == MERGE_SOURCE else None
|
||||
for entry in inputs if isinstance(inputs, list) else []:
|
||||
if isinstance(entry, dict) and isinstance(entry.get("artifact"), str):
|
||||
found += _error_checks(entry["artifact"], seen)
|
||||
return found
|
||||
def _error_checks(artifact: str) -> list[dict[str, Any]]:
|
||||
"""这份查询快照对照数据目录查出的 error 级问题(合并查询顺着 inputs 往下找,见 sql_problems.query_problems)。"""
|
||||
return [c for p in query_problems(artifact) for c in p.checks]
|
||||
|
||||
|
||||
def _sql_check_reason(failed: list[tuple[str, list[dict[str, Any]]]]) -> str:
|
||||
def _sql_check_reason(failed: list[tuple[str, list[QueryProblem]]]) -> str:
|
||||
"""「所依据的查询未通过 SQL 检查(「订单」关联「订单明细」是一对多,对「订单」的「订单金额」求和会重复计算),
|
||||
结果不可靠」:出具声明、运行日志、证据面板都用这句。只摘问题那半句,改法留在查询步骤里看。"""
|
||||
problems = list(dict.fromkeys(str(c.get("message") or "").split("。")[0] for _, found in failed for c in found))
|
||||
problems = [p for p in problems if p]
|
||||
if not problems:
|
||||
return "所依据的查询未通过 SQL 检查,结果不可靠"
|
||||
if len(problems) == 1:
|
||||
return f"所依据的查询未通过 SQL 检查({problems[0]}),结果不可靠"
|
||||
return f"所依据的查询有 {len(problems)} 处未通过 SQL 检查({problems[0]}等),结果不可靠"
|
||||
return reason_text(list(dict.fromkeys(text for _, found in failed for p in found for text in p.problems)))
|
||||
|
||||
|
||||
def _emit_sql_check_logs(metrics: list[dict[str, Any]], failed_by: dict[str, list[QueryProblem]],
|
||||
state: GraphState, ctx: NodeContext) -> None:
|
||||
"""没通过 SQL 检查的来源查询,一条一行运行日志(metric_sql_check),列出受它影响的指标。
|
||||
|
||||
以前一个指标一行:同一条查询算出三个指标,时间线上同一句话重复三遍。现在按出问题的那条查询归并。
|
||||
结构化字段给界面读,不让它从 message 里解析中文:metrics / metric_names(受影响的指标)、reason、problems、
|
||||
checks(不带 for_model)、query_artifact(出问题的查询快照)、source_node(跑这条查询的节点)、
|
||||
source_field(要改的那一栏:调用工具节点写死的 SQL 在 args.sql;Agent 自己写的 SQL 没有可定位的栏,不给)。
|
||||
界面据 source_node / source_field 把「打开设置」落到来源查询节点的 SQL 上,而不是口径卡。
|
||||
"""
|
||||
names = {m["id"]: m["name"] for m in metrics}
|
||||
groups: dict[str, tuple[QueryProblem, list[str]]] = {}
|
||||
for metric_id, found in failed_by.items():
|
||||
for problem in merge_problems(found):
|
||||
held = groups.setdefault(problem.artifact, (problem, []))
|
||||
if metric_id not in held[1]:
|
||||
held[1].append(metric_id)
|
||||
nodes = ctx.run.spec.node_map()
|
||||
for artifact, (problem, ids) in groups.items():
|
||||
source = problem.node_id or node_of(artifact, state.get("evidence"))
|
||||
producer = nodes.get(source) if source else None
|
||||
sql_in_args = producer is not None and str(producer.type) == "tool" \
|
||||
and isinstance((producer.config.get("args") or {}), dict) and "sql" in (producer.config.get("args") or {})
|
||||
reason = reason_text(problem.problems)
|
||||
ctx.emit(EventType.LOG, level="warn", code="metric_sql_check",
|
||||
metric=ids[0], metrics=ids, metric_names=[names.get(i, i) for i in ids],
|
||||
reason=reason, problems=problem.problems,
|
||||
checks=[{k: c[k] for k in CHECK_FIELDS if k in c} for c in problem.checks],
|
||||
query_artifact=artifact,
|
||||
**({"source_node": source} if source else {}),
|
||||
**({"source_field": "args.sql"} if sql_in_args else {}),
|
||||
message="指标" + "".join(f"「{names.get(i, i)}」" for i in ids) + reason)
|
||||
|
||||
|
||||
def _truncated_field(path: str, state: GraphState, ctx: NodeContext) -> dict[str, Any] | None:
|
||||
|
||||
@@ -27,7 +27,8 @@ from app.engine.toolcalls import (
|
||||
)
|
||||
from app.providers import catalog
|
||||
from app.providers.factory import ModelSpec, bind_tools_safely, get_chat_model
|
||||
from app.tools.datasource import run_versions
|
||||
from app.engine.sql_problems import event_checks
|
||||
from app.tools.datasource import QUERY_PREFIX, run_versions
|
||||
from app.tools.registry import (
|
||||
ToolArgsError,
|
||||
ToolContext,
|
||||
@@ -419,9 +420,12 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
except Exception as e: # noqa: BLE001
|
||||
content = f"工具失败:{describe_exception(e)}"
|
||||
failure = {"error": content, "detail": raw_detail(e)}
|
||||
# 查库的 SQL 检查结果单独带上:preview 截到前 1500 个字符,checks 通常在截掉的那段里
|
||||
checks = event_checks(content) if not failure and tname.startswith(QUERY_PREFIX) else []
|
||||
ctx.emit(EventType.TOOL_ERROR if failure else EventType.TOOL_END, tool=tname,
|
||||
agent=name, call_id=cid, preview=content[:1500],
|
||||
duration_ms=int((time.perf_counter() - started) * 1000), **failure)
|
||||
duration_ms=int((time.perf_counter() - started) * 1000), **failure,
|
||||
**({"checks": checks} if checks else {}))
|
||||
calls.append({"tool": tname, "args": targs, "result": content[:2000]})
|
||||
messages.append(ToolMessage(content=content, tool_call_id=cid))
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ from app.engine.evidence import (
|
||||
CLAIMS_RULE,
|
||||
ENTITY_KINDS,
|
||||
MARKER_RULES,
|
||||
SEE_AND_CODE_RULES,
|
||||
StreamRenderer,
|
||||
build_catalog,
|
||||
catalog_prompt,
|
||||
@@ -80,6 +81,8 @@ CLAIMS = CLAIMS_VALUES
|
||||
#: 只标注、不让写作者重写也不判失败的违规:可疑实体(受管的正式出具按缺口降档)、表结构快照不全时
|
||||
#: 核对不了的名字(出口只标注)
|
||||
SOFT = frozenset({"unknown_entity", "unverified_entity"})
|
||||
#: 交回写作者重写、重写不好也不判失败的违规:句中的 [[see:]](渲染后留下断句,数字和出处都没问题)
|
||||
REWRITE_ONLY = frozenset({"inline_see"})
|
||||
#: 重写一次就是多一次整篇的模型调用,写不对的模型多给几次也大多写不对
|
||||
MAX_REPAIRS = 3
|
||||
|
||||
@@ -304,6 +307,11 @@ def _blocking(violations: list[dict[str, Any]], numbers: str) -> list[dict[str,
|
||||
and not (numbers == "off" and v.get("code") == "uncited_number")]
|
||||
|
||||
|
||||
def _fatal(blocking: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""要判失败的违规:重写之后还在的、不属于 REWRITE_ONLY 的。"""
|
||||
return [v for v in blocking if v.get("code") not in REWRITE_ONLY]
|
||||
|
||||
|
||||
def _violation_key(violation: dict[str, Any]) -> tuple[str, str]:
|
||||
"""认一处违规:(code, 点名的字)。点名的字按 text、ref、message 的顺序取第一个有的。"""
|
||||
named = violation.get("text") or violation.get("ref") or violation.get("message") or ""
|
||||
@@ -348,7 +356,7 @@ def _messages(ctx: NodeContext, state: GraphState, catalog: dict[str, Any], cell
|
||||
system = ctx.render_str(ctx.cfg("system", ""), state)
|
||||
instructions = ctx.render_str(ctx.cfg("instructions", ""), state).strip() \
|
||||
or "根据下面的证据写一份简洁的报告,先总后分。"
|
||||
rules = MARKER_RULES
|
||||
rules = f"{MARKER_RULES}\n{SEE_AND_CODE_RULES}"
|
||||
if claims in ("require_citation", CLAIMS_JUDGE):
|
||||
# 裁判只看写作者挂的依据:要判,就更得每句都挂上
|
||||
rules = f"{rules}\n{CLAIMS_RULE}" + (f"\n{judging.JUDGE_RULE}" if claims == CLAIMS_JUDGE else "")
|
||||
@@ -451,7 +459,7 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 探索运行默认按需裁判:点开哪句才判哪句,节点里不花这笔钱
|
||||
judgement = judging.on_demand(doc, on_unsupported=judge_cfg["on_unsupported"],
|
||||
rewrite_once=judge_cfg["rewrite_once"], writer_model=model_id)
|
||||
elif not (blocking and on_violation == "fail"):
|
||||
elif not (_fatal(blocking) and on_violation == "fail"):
|
||||
# 反正要判失败的报告不值得再花钱判(节点紧接着就报错)
|
||||
doc, response, blocking, judgement, usages = await _judge_inline(
|
||||
ctx, doc, catalog, judge_cfg, model_id=model_id, messages=[*messages, response],
|
||||
@@ -461,10 +469,11 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
doc_artifact = await _store(doc, ctx)
|
||||
ctx.emit(EventType.REPORT_CHECKED, doc_artifact=doc_artifact, ok=not doc["violations"],
|
||||
stats=doc["stats"], violations=doc["violations"][:20], repairs=repairs,
|
||||
on_violation=on_violation, failed=bool(blocking) and on_violation == "fail",
|
||||
on_violation=on_violation, failed=bool(_fatal(blocking)) and on_violation == "fail",
|
||||
**({"claims": claims} if evidence_on else {}),
|
||||
**({"judge": judgement} if judgement is not None else {}))
|
||||
if blocking and on_violation == "fail":
|
||||
if (fatal := _fatal(blocking)) and on_violation == "fail":
|
||||
blocking = fatal
|
||||
head = ";".join(v["message"] for v in blocking[:5])
|
||||
more = f";…另有 {len(blocking) - 5} 处" if len(blocking) > 5 else ""
|
||||
raise NodeError(
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.engine.state import GraphState
|
||||
from app.engine.toolcalls import ToolTimeout, limit_fields, limit_of, run_bounded
|
||||
from app.sandbox.base import SandboxLimits
|
||||
from app.sandbox.manager import sandbox_manager
|
||||
from app.engine.sql_problems import event_checks
|
||||
from app.tools.datasource import DATA_UNAVAILABLE, QUERY_PREFIX, SCHEMA_PREFIX, run_versions
|
||||
from app.tools.registry import (
|
||||
ToolArgsError,
|
||||
@@ -184,10 +185,12 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 只认数据源工具交回的查询:别的工具(MCP、自定义)拼出同样形状的 JSON,里面的工件 id 不是我们落的
|
||||
query = query_entry_fields(result) if evidence_on and name.startswith(QUERY_PREFIX) else None
|
||||
schema = query.get("schema_artifact") if query else None
|
||||
# 这次查询的 SQL 检查结果单独带上:preview 只有前 2000 个字符,checks 排在 rows 后面,通常被截掉
|
||||
checks = event_checks(result) if name.startswith(QUERY_PREFIX) else []
|
||||
ctx.emit(EventType.TOOL_END, tool=name, duration_ms=elapsed,
|
||||
preview=json.dumps(result, ensure_ascii=False, default=str)[:2000],
|
||||
artifact=snapshot_id, **({"query_artifact": query["artifact"]} if query else {}),
|
||||
**({"schema_artifact": schema} if schema else {}))
|
||||
**({"schema_artifact": schema} if schema else {}), **({"checks": checks} if checks else {}))
|
||||
|
||||
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
|
||||
if evidence_on:
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""查询快照上的 SQL 检查问题:口径卡、出具契约、写作目录、运行日志共用一套读法。
|
||||
|
||||
数据源查询工具执行后对照数据目录检查 SQL,结果存在查询快照的 checks 里(data/sqlcheck.py)。error 级的
|
||||
(一对多关联后重复计算、存量跨期加总)意味着这条查询算出来的数不可靠:
|
||||
|
||||
- 口径卡用它算出的指标标「存疑」(nodes/metrics.py);
|
||||
- 报告直接引用它的格、或拿它当依据,出具同样降档(nodes/io.py);
|
||||
- 写作目录里提醒写作者(engine/evidence.catalog_prompt)。
|
||||
|
||||
合并查询在内存 SQLite 上执行,不对照数据目录,它的快照没有自己的 checks,但记着 inputs:顺着往下找,问题记在
|
||||
出问题的那条源查询上。几个指标、几处引用出自同一条查询时,问题只算一次(problems_by_query 按快照 id 归并)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.core import artifact_store
|
||||
|
||||
#: 合并查询快照的 source(engine/merge_query.MERGE_SOURCE)。这里写死同一个字面量,免得为一个常量引入执行器
|
||||
MERGE_SOURCE = "合并查询"
|
||||
#: 一条链最多追几层合并:画布上不会无限嵌套,这只是防御坏快照
|
||||
_MAX_DEPTH = 8
|
||||
|
||||
|
||||
@dataclass
|
||||
class QueryProblem:
|
||||
"""一条没通过 SQL 检查的查询快照。
|
||||
|
||||
artifact 是出问题的那条查询快照(合并查询的话是它的某个输入);node_id 是跑这条查询的节点,合并快照的 inputs
|
||||
里记着,直接查询的由调用方按证据台账补(node_of);checks 是 error 级的检查结果(快照里的原样)。
|
||||
"""
|
||||
|
||||
artifact: str
|
||||
node_id: str | None
|
||||
checks: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def problems(self) -> list[str]:
|
||||
"""每条检查的问题那半句(message 的第一句),去重。改法留在证据面板的查询步骤里看。"""
|
||||
out = [str(c.get("message") or "").split("。")[0] for c in self.checks]
|
||||
return list(dict.fromkeys(p for p in out if p))
|
||||
|
||||
@property
|
||||
def codes(self) -> list[str]:
|
||||
return list(dict.fromkeys(str(c.get("code")) for c in self.checks if c.get("code")))
|
||||
|
||||
|
||||
def _load(artifact: str, loader: Callable[[str], Any] | None) -> Any:
|
||||
try:
|
||||
return (loader or artifact_store.load)(artifact)
|
||||
except Exception: # noqa: BLE001 - 快照读不出来、被改过:这里不报,证据层另有说法
|
||||
return None
|
||||
|
||||
|
||||
def query_problems(artifact: Any, *, loader: Callable[[str], Any] | None = None,
|
||||
_seen: set[str] | None = None, _node: str | None = None, _depth: int = 0) -> list[QueryProblem]:
|
||||
"""这份查询快照(或合并快照的各个输入)里有 error 级 SQL 检查的那几条查询,一条一个 QueryProblem。
|
||||
|
||||
读不出来的快照、没有问题的快照都不出现。自引用、成环的坏快照不会卡死。
|
||||
"""
|
||||
if not isinstance(artifact, str) or not artifact or _depth > _MAX_DEPTH:
|
||||
return []
|
||||
seen = _seen if _seen is not None else set()
|
||||
if artifact in seen:
|
||||
return []
|
||||
seen.add(artifact)
|
||||
snapshot = _load(artifact, loader)
|
||||
if not isinstance(snapshot, dict):
|
||||
return []
|
||||
out: list[QueryProblem] = []
|
||||
checks = snapshot.get("checks")
|
||||
errors = [c for c in checks if isinstance(c, dict) and c.get("level") == "error"] if isinstance(checks, list) else []
|
||||
if errors:
|
||||
out.append(QueryProblem(artifact, _node, errors))
|
||||
inputs = snapshot.get("inputs") if snapshot.get("source") == MERGE_SOURCE else None
|
||||
for entry in inputs if isinstance(inputs, list) else []:
|
||||
if isinstance(entry, dict) and isinstance(entry.get("artifact"), str):
|
||||
node = entry.get("node_id") if isinstance(entry.get("node_id"), str) else None
|
||||
out += query_problems(entry["artifact"], loader=loader, _seen=seen, _node=node, _depth=_depth + 1)
|
||||
return out
|
||||
|
||||
|
||||
def error_checks(artifact: Any, *, loader: Callable[[str], Any] | None = None) -> list[dict[str, Any]]:
|
||||
"""这份查询快照(含合并查询的输入)对照数据目录查出的全部 error 级检查结果,摊平成一个列表。"""
|
||||
return [c for p in query_problems(artifact, loader=loader) for c in p.checks]
|
||||
|
||||
|
||||
#: 运行事件、证据接口交给界面的检查字段(data/sqlcheck.SqlCheck.as_dict 去掉给模型的那句 for_model)
|
||||
CHECK_FIELDS = ("code", "level", "message", "table", "column", "relation_id", "sql_excerpt")
|
||||
|
||||
|
||||
def event_checks(result: Any) -> list[dict[str, Any]]:
|
||||
"""数据源查询工具交回的结果(dict 或 JSON 文本)里的 SQL 检查结果,只留给人看的字段;没有就是空列表。
|
||||
|
||||
tool.end 的 preview 只是结果的前 2000 个字符,checks 排在 rows 后面,通常被截掉。事件里单独带一份,
|
||||
运行时间线才看得到这条查询的检查结果。调用方只对数据源查询工具(db_query__)问这里。
|
||||
"""
|
||||
if isinstance(result, str):
|
||||
text = result.lstrip()
|
||||
if not text.startswith("{") or '"checks"' not in text:
|
||||
return []
|
||||
try:
|
||||
result = json.loads(text)
|
||||
except ValueError:
|
||||
return []
|
||||
checks = result.get("checks") if isinstance(result, dict) else None
|
||||
if not isinstance(checks, list):
|
||||
return []
|
||||
return [{k: c[k] for k in CHECK_FIELDS if k in c} for c in checks if isinstance(c, dict) and c.get("code")]
|
||||
|
||||
|
||||
def node_of(artifact: str, ledger: Iterable[Any] | None) -> str | None:
|
||||
"""证据台账里交回这份查询快照的节点。台账里没有(老运行、Agent 没交台账)返回 None。"""
|
||||
for entry in ledger or []:
|
||||
if isinstance(entry, dict) and entry.get("kind") == "query" and entry.get("artifact") == artifact:
|
||||
node = entry.get("node_id")
|
||||
return node if isinstance(node, str) and node else None
|
||||
return None
|
||||
|
||||
|
||||
def problem_clause(problems: list[str]) -> str:
|
||||
"""「未通过 SQL 检查(…),结果不可靠」:前面接上是哪条查询(「所依据的查询」「查询「取数」(Q1)」)。"""
|
||||
problems = [p for p in problems if p]
|
||||
if not problems:
|
||||
return "未通过 SQL 检查,结果不可靠"
|
||||
if len(problems) == 1:
|
||||
return f"未通过 SQL 检查({problems[0]}),结果不可靠"
|
||||
return f"有 {len(problems)} 处未通过 SQL 检查({problems[0]}等),结果不可靠"
|
||||
|
||||
|
||||
def reason_text(problems: list[str]) -> str:
|
||||
"""「所依据的查询未通过 SQL 检查(…),结果不可靠」:口径卡、出具声明、运行日志、证据面板都用这句。"""
|
||||
return "所依据的查询" + problem_clause(problems)
|
||||
|
||||
|
||||
def merge_problems(found: Iterable[QueryProblem]) -> list[QueryProblem]:
|
||||
"""按快照 id 归并:同一条查询经几条路径(直接引用、合并查询的输入)找到,只算一次。保持先后顺序。"""
|
||||
out: dict[str, QueryProblem] = {}
|
||||
for p in found:
|
||||
if p.artifact not in out:
|
||||
out[p.artifact] = QueryProblem(p.artifact, p.node_id, list(p.checks))
|
||||
elif out[p.artifact].node_id is None and p.node_id:
|
||||
out[p.artifact].node_id = p.node_id
|
||||
return list(out.values())
|
||||
|
||||
|
||||
__all__ = ["CHECK_FIELDS", "MERGE_SOURCE", "QueryProblem", "error_checks", "event_checks", "merge_problems", "node_of", "problem_clause", "query_problems",
|
||||
"reason_text"]
|
||||
Reference in New Issue
Block a user