合入集成分支 feat/data-catalog(d897981,含 F2a 的证据面板、时间线和服务端修复):自动合并,没有冲突;catalog_profile._relation_finding 两边的改动(F2b 的 previous_status、F2a 的 cardinality_checked 写在关系上)互不重叠

This commit is contained in:
ThearchyHelios
2026-10-04 02:46:01 +08:00
45 changed files with 2007 additions and 278 deletions
+103 -34
View File
@@ -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",
+72 -23
View File
@@ -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"]
+44 -3
View File
@@ -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}")