dimctx 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dimctx/__init__.py +0 -0
- dimctx/core/__init__.py +0 -0
- dimctx/core/canon.py +117 -0
- dimctx/core/complexity.py +145 -0
- dimctx/core/detector.py +174 -0
- dimctx/core/matrix.py +123 -0
- dimctx/core/profiler.py +81 -0
- dimctx/models.py +57 -0
- dimctx/server.py +103 -0
- dimctx/tools.py +163 -0
- dimctx-0.1.0.dist-info/METADATA +73 -0
- dimctx-0.1.0.dist-info/RECORD +17 -0
- dimctx-0.1.0.dist-info/WHEEL +5 -0
- dimctx-0.1.0.dist-info/entry_points.txt +2 -0
- dimctx-0.1.0.dist-info/licenses/LICENSE +661 -0
- dimctx-0.1.0.dist-info/licenses/NOTICE +31 -0
- dimctx-0.1.0.dist-info/top_level.txt +1 -0
dimctx/__init__.py
ADDED
|
File without changes
|
dimctx/core/__init__.py
ADDED
|
File without changes
|
dimctx/core/canon.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
"""canon——原典检索(BM25,零依赖)。
|
|
3
|
+
|
|
4
|
+
语料边界(03 号决策):
|
|
5
|
+
- 正文永不随包;用户用环境变量 DIMCTX_CANON_DIR 指向自备 markdown 目录;
|
|
6
|
+
- 索引(标题/URL/日期/导读句)可随包——导读句由**我们自己写**,不用原文摘句。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import unicodedata
|
|
13
|
+
from collections import Counter
|
|
14
|
+
from typing import Dict, List, Optional
|
|
15
|
+
|
|
16
|
+
_TOKEN_RE = re.compile(r"[A-Za-z][A-Za-z0-9_'-]+|[\u4e00-\u9fff]{2,}")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def tokenize(text: str) -> List[str]:
|
|
20
|
+
"""英文词 + 中文二元组(零依赖中文近似分词)。"""
|
|
21
|
+
out: List[str] = []
|
|
22
|
+
for m in _TOKEN_RE.finditer(unicodedata.normalize("NFKC", text).lower()):
|
|
23
|
+
s = m.group(0)
|
|
24
|
+
if "\u4e00" <= s[0] <= "\u9fff":
|
|
25
|
+
out.extend(s[i:i + 2] for i in range(len(s) - 1))
|
|
26
|
+
else:
|
|
27
|
+
out.append(s)
|
|
28
|
+
return out
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class BM25:
|
|
32
|
+
def __init__(self, docs: List[Dict], k1: float = 1.5, b: float = 0.75):
|
|
33
|
+
self.docs = docs
|
|
34
|
+
self.k1, self.b = k1, b
|
|
35
|
+
self.df: Counter = Counter()
|
|
36
|
+
self.tf: List[Counter] = []
|
|
37
|
+
self.lens: List[int] = []
|
|
38
|
+
for d in docs:
|
|
39
|
+
toks = tokenize(d["text"])
|
|
40
|
+
tf = Counter(toks)
|
|
41
|
+
self.tf.append(tf)
|
|
42
|
+
self.lens.append(len(toks))
|
|
43
|
+
for t in tf:
|
|
44
|
+
self.df[t] += 1
|
|
45
|
+
self.N = len(docs)
|
|
46
|
+
self.avgdl = (sum(self.lens) / self.N) if self.N else 0.0
|
|
47
|
+
|
|
48
|
+
def search(self, query: str, limit: int = 5) -> List[Dict]:
|
|
49
|
+
q = tokenize(query)
|
|
50
|
+
if not q or not self.N:
|
|
51
|
+
return []
|
|
52
|
+
scored = []
|
|
53
|
+
for i in range(self.N):
|
|
54
|
+
s = 0.0
|
|
55
|
+
dl = self.lens[i] or 1
|
|
56
|
+
for t in q:
|
|
57
|
+
f = self.tf[i].get(t)
|
|
58
|
+
if not f:
|
|
59
|
+
continue
|
|
60
|
+
idf = math.log(1 + (self.N - self.df[t] + 0.5) / (self.df[t] + 0.5))
|
|
61
|
+
s += idf * (f * (self.k1 + 1)) / (f + self.k1 * (1 - self.b + self.b * dl / self.avgdl))
|
|
62
|
+
if s > 0:
|
|
63
|
+
scored.append((s, i))
|
|
64
|
+
scored.sort(reverse=True)
|
|
65
|
+
out = []
|
|
66
|
+
for s, i in scored[:limit]:
|
|
67
|
+
d = self.docs[i]
|
|
68
|
+
out.append({"title": d["title"], "url": d.get("url", ""), "date": d.get("date", ""),
|
|
69
|
+
"source": d.get("source", "canon"), "score": round(s, 3),
|
|
70
|
+
"snippet": _snippet(d["text"], q)})
|
|
71
|
+
return out
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _snippet(text: str, q: List[str], width: int = 160) -> str:
|
|
75
|
+
"""命中窗口片段(本地返回给调用方,不上传——03 号第 2 层边界)。"""
|
|
76
|
+
low = text.lower()
|
|
77
|
+
best, best_pos = 0, 0
|
|
78
|
+
for t in q[:6]:
|
|
79
|
+
pos = low.find(t)
|
|
80
|
+
if pos >= 0:
|
|
81
|
+
score = sum(1 for x in q if x in low[max(0, pos - 80):pos + 80])
|
|
82
|
+
if score > best:
|
|
83
|
+
best, best_pos = score, pos
|
|
84
|
+
start = max(0, best_pos - 40)
|
|
85
|
+
return text[start:start + width].replace("\n", " ").strip()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def load_corpus(canon_dir: str, analysis_dir: Optional[str] = None) -> List[Dict]:
|
|
89
|
+
"""从用户自备目录加载 markdown。canon_dir 为空/不存在 → 返回空(不报错,服务照常)。"""
|
|
90
|
+
docs: List[Dict] = []
|
|
91
|
+
for src, d in (("canon", canon_dir), ("analysis", analysis_dir)):
|
|
92
|
+
if not d or not os.path.isdir(d):
|
|
93
|
+
continue
|
|
94
|
+
for fn in sorted(os.listdir(d)):
|
|
95
|
+
if not fn.endswith(".md"):
|
|
96
|
+
continue
|
|
97
|
+
p = os.path.join(d, fn)
|
|
98
|
+
try:
|
|
99
|
+
text = open(p, encoding="utf-8").read()
|
|
100
|
+
except OSError:
|
|
101
|
+
continue
|
|
102
|
+
fm = {}
|
|
103
|
+
if text.startswith("---"):
|
|
104
|
+
parts = text.split("---", 2)
|
|
105
|
+
if len(parts) >= 3:
|
|
106
|
+
for line in parts[1].splitlines():
|
|
107
|
+
if ":" in line:
|
|
108
|
+
k, v = line.split(":", 1)
|
|
109
|
+
fm[k.strip()] = v.strip()
|
|
110
|
+
text = parts[2]
|
|
111
|
+
docs.append({"title": fm.get("title", fn[:-3]), "url": fm.get("url", ""),
|
|
112
|
+
"date": fm.get("date", ""), "source": src, "text": text})
|
|
113
|
+
return docs
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def build_index(canon_dir: str, analysis_dir: Optional[str] = None) -> BM25:
|
|
117
|
+
return BM25(load_corpus(canon_dir, analysis_dir))
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""measure_downstream_complexity——mdop 消费侧下游取数复杂度度量器(Kimball 判据工具化)。
|
|
3
|
+
|
|
4
|
+
理论锚:内训讲者「下游取数复杂度」判据(音频 [62:53-63:58])——模型合格 ⇔ 下游只剩
|
|
5
|
+
SELECT…FROM…WHERE;CASE WHEN 口径 / 关联计算 / 多级聚合 = 口径外置债。
|
|
6
|
+
|
|
7
|
+
四指标(每条消费 SQL / 按表聚合双口径):
|
|
8
|
+
1. case_when :CASE WHEN 计数(口径分支外置)
|
|
9
|
+
2. join_depth :JOIN 个数(关联计算外置;1=正常星型,≥2 开始值得审视)
|
|
10
|
+
3. subq_depth :嵌套 SELECT 最大深度(FROM (SELECT…) 套层)
|
|
11
|
+
4. agg_nest :聚合套聚合(外层聚合参数内含聚合,如 SUM(SUM(x)) 或聚合+再关联形态)
|
|
12
|
+
|
|
13
|
+
解析策略:MyBatis XML 动态片段(<if>/<foreach>/<choose>)平铺拼合后做词法分析——
|
|
14
|
+
指标是计数型非语义型,词法法零依赖且稳定(不引 sqlglot,保证独立可跑)。
|
|
15
|
+
|
|
16
|
+
用法:
|
|
17
|
+
python3 scripts/measure_downstream_complexity.py [--json out.json]
|
|
18
|
+
退出码恒 0(度量工具,超标不是异常是产物)。
|
|
19
|
+
|
|
20
|
+
Python 3.9+,零第三方依赖。对三仓只读。
|
|
21
|
+
"""
|
|
22
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import sys
|
|
29
|
+
from collections import defaultdict
|
|
30
|
+
from typing import Dict, List, Optional, Tuple
|
|
31
|
+
import xml.etree.ElementTree as ET
|
|
32
|
+
|
|
33
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
34
|
+
ROOT = os.path.abspath(os.path.join(HERE, ".."))
|
|
35
|
+
|
|
36
|
+
WAREHOUSES = [
|
|
37
|
+
("admin", os.path.join(ROOT, "modules/mdop-cell-admin/mdop-cell-admin/src/main/resources/mappers")),
|
|
38
|
+
("process", os.path.join(ROOT, "modules/mdop-cell-process/mdop-process/src/main/resources/mappers")),
|
|
39
|
+
]
|
|
40
|
+
# web 仓经对抗审查坐实零表引用(T08 疑点2),不扫。
|
|
41
|
+
|
|
42
|
+
DT_RE = re.compile(r"\b((?:mdop_)?dt_[a-z0-9_]+)\b", re.I)
|
|
43
|
+
CASE_RE = re.compile(r"\bcase\s+when\b", re.I)
|
|
44
|
+
JOIN_RE = re.compile(r"\b(?:left\s+|right\s+|inner\s+|full\s+|cross\s+|left\s+semi\s+|left\s+anti\s+)?join\b", re.I)
|
|
45
|
+
AGG_RE = re.compile(r"\b(sum|avg|count|min|max|count_distinct|any_value)\s*\(", re.I)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def flatten_xml(node: ET.Element, buf: List[str], sql_frags: Dict[str, ET.Element],
|
|
49
|
+
_visiting: Optional[set] = None) -> None:
|
|
50
|
+
"""平铺 MyBatis 动态节点:文本顺序拼接;<include refid> 递归展开同文件 <sql> 片段(判例:ParamDataMapper
|
|
51
|
+
六个 main*Query 片段含 dt_ 表、42 处 include 复用——不展开则 JOIN 深度与表引用双漏)。"""
|
|
52
|
+
if node.tag == "include":
|
|
53
|
+
ref = node.attrib.get("refid")
|
|
54
|
+
frag = sql_frags.get(ref) if ref else None
|
|
55
|
+
if frag is not None:
|
|
56
|
+
visiting = _visiting or set()
|
|
57
|
+
if ref in visiting:
|
|
58
|
+
return # 防环
|
|
59
|
+
visiting.add(ref)
|
|
60
|
+
flatten_xml(frag, buf, sql_frags, visiting)
|
|
61
|
+
if node.tail:
|
|
62
|
+
buf.append(node.tail)
|
|
63
|
+
return
|
|
64
|
+
if node.text:
|
|
65
|
+
buf.append(node.text)
|
|
66
|
+
for child in node:
|
|
67
|
+
flatten_xml(child, buf, sql_frags, _visiting)
|
|
68
|
+
if child.tail:
|
|
69
|
+
buf.append(child.tail)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def strip_dynamic_noise(sql: str) -> str:
|
|
73
|
+
"""去绑定符号噪声(#{}/ ${} / <!-- --> / CDATA 残留),保留词法结构。"""
|
|
74
|
+
sql = re.sub(r"--[^\n]*", " ", sql)
|
|
75
|
+
sql = re.sub(r"/\*.*?\*/", " ", sql, flags=re.S)
|
|
76
|
+
sql = re.sub(r"[#\$]\{[^}]*\}", " ? ", sql)
|
|
77
|
+
return sql
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def max_select_depth(sql: str) -> int:
|
|
81
|
+
"""嵌套 SELECT 最大深度:括号栈内每遇 SELECT 计一层(FROM (SELECT ...)形态)。"""
|
|
82
|
+
depth = best = 0
|
|
83
|
+
for i, ch in enumerate(sql):
|
|
84
|
+
if ch == "(":
|
|
85
|
+
# 该括号内直接以 SELECT 开头(容忍空白)才算一层子查询
|
|
86
|
+
m = re.match(r"\s*select\b", sql[i + 1:i + 12], re.I)
|
|
87
|
+
if m:
|
|
88
|
+
depth += 1
|
|
89
|
+
best = max(best, depth)
|
|
90
|
+
elif ch == ")":
|
|
91
|
+
if depth > 0:
|
|
92
|
+
depth -= 1
|
|
93
|
+
return best
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def agg_nesting_count(sql: str) -> int:
|
|
97
|
+
"""聚合套聚合:外层聚合的参数区内再出现聚合函数。"""
|
|
98
|
+
count = 0
|
|
99
|
+
for m in AGG_RE.finditer(sql):
|
|
100
|
+
open_idx = m.end() - 1
|
|
101
|
+
depth = 0
|
|
102
|
+
j = open_idx
|
|
103
|
+
while j < len(sql):
|
|
104
|
+
if sql[j] == "(":
|
|
105
|
+
depth += 1
|
|
106
|
+
elif sql[j] == ")":
|
|
107
|
+
depth -= 1
|
|
108
|
+
if depth == 0:
|
|
109
|
+
break
|
|
110
|
+
j += 1
|
|
111
|
+
inner = sql[open_idx + 1:j]
|
|
112
|
+
if AGG_RE.search(inner):
|
|
113
|
+
count += 1
|
|
114
|
+
return count
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def analyze_statement(sql: str) -> Dict[str, int]:
|
|
118
|
+
sql = strip_dynamic_noise(sql)
|
|
119
|
+
return {
|
|
120
|
+
"case_when": len(CASE_RE.findall(sql)),
|
|
121
|
+
"join_depth": len(JOIN_RE.findall(sql)),
|
|
122
|
+
"subq_depth": max_select_depth(sql),
|
|
123
|
+
"agg_nest": agg_nesting_count(sql),
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def iter_statements(mapper_dir: str):
|
|
128
|
+
for dirpath, _dirs, files in os.walk(mapper_dir):
|
|
129
|
+
for fn in files:
|
|
130
|
+
if not fn.endswith(".xml"):
|
|
131
|
+
continue
|
|
132
|
+
path = os.path.join(dirpath, fn)
|
|
133
|
+
try:
|
|
134
|
+
tree = ET.parse(path)
|
|
135
|
+
except ET.ParseError:
|
|
136
|
+
continue # 含 DTD/实体引用的 MyBatis 头可能解析失败,跳过并计数
|
|
137
|
+
root = tree.getroot()
|
|
138
|
+
sql_frags = {s.attrib.get("id"): s for s in root.iter("sql") if s.attrib.get("id")}
|
|
139
|
+
for tag in ("select", "insert", "update", "delete"):
|
|
140
|
+
for st in root.iter(tag):
|
|
141
|
+
buf: List[str] = []
|
|
142
|
+
flatten_xml(st, buf, sql_frags)
|
|
143
|
+
yield path, fn, tag, st.attrib.get("id", "?"), "".join(buf)
|
|
144
|
+
|
|
145
|
+
|
dimctx/core/detector.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""detector——C13 M1/M2:五探测器(D1-D5,盲测纪律:只看列特征,不看 layer/keys)。
|
|
3
|
+
|
|
4
|
+
D1 事实/维度划分(评分制) D2 粒度候选键(业务标识启发)
|
|
5
|
+
D3 SCD 类型 D4 总线矩阵一致性
|
|
6
|
+
D5 命名对齐
|
|
7
|
+
"""
|
|
8
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
from . import profiler
|
|
14
|
+
|
|
15
|
+
AUDIT_TIME = re.compile(r"^(create_time|update_time|etl_time|created_at|updated_at|sync_time)$", re.I)
|
|
16
|
+
# origin/source=U06 合并键判例(工厂维度三套表示合并 → origin_system 是合并维度业务键)
|
|
17
|
+
GRAIN_HINT = re.compile(r"(material|product|station|process|factory|workshop|line|group|base|supplier|vendor|param|equipment|origin|source)", re.I)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def business_time_cols(p: Dict[str, Any]) -> List[str]:
|
|
21
|
+
"""业务时间列(排除审计列)——事实表的强信号(U12 时间片判例)。"""
|
|
22
|
+
return [c for c in p.get("time_cols", []) if not AUDIT_TIME.match(c)]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def classify_role(p: Dict[str, Any]) -> Dict[str, Any]:
|
|
26
|
+
"""D1:事实/维度划分(评分制)。返回 {role, fact_score, dim_score, signals}。"""
|
|
27
|
+
signals: List[str] = []
|
|
28
|
+
bt = business_time_cols(p)
|
|
29
|
+
measures = p.get("measure_cols", [])
|
|
30
|
+
batches = p.get("batch_cols", [])
|
|
31
|
+
|
|
32
|
+
dim_score = 0.0
|
|
33
|
+
fact_score = 0.0
|
|
34
|
+
if p["desc_ratio"] >= 0.12:
|
|
35
|
+
dim_score += 2.0
|
|
36
|
+
signals.append(f"desc_ratio={p['desc_ratio']}")
|
|
37
|
+
if not measures:
|
|
38
|
+
dim_score += 1.5
|
|
39
|
+
signals.append("无度量列")
|
|
40
|
+
if not bt:
|
|
41
|
+
dim_score += 1.5
|
|
42
|
+
signals.append("无业务时间列")
|
|
43
|
+
if p["n_cols"] <= 25:
|
|
44
|
+
dim_score += 0.5
|
|
45
|
+
|
|
46
|
+
if measures:
|
|
47
|
+
fact_score += min(len(measures), 3) * 0.8
|
|
48
|
+
signals.append(f"度量列{len(measures)}个")
|
|
49
|
+
if bt:
|
|
50
|
+
fact_score += 2.0
|
|
51
|
+
signals.append(f"业务时间{bt[:2]}")
|
|
52
|
+
if batches:
|
|
53
|
+
fact_score += 1.5
|
|
54
|
+
signals.append(f"批次列{batches[:2]}")
|
|
55
|
+
if p["numeric_ratio"] >= 0.25:
|
|
56
|
+
fact_score += 0.5
|
|
57
|
+
if p["n_cols"] > 25:
|
|
58
|
+
fact_score += 0.5
|
|
59
|
+
|
|
60
|
+
role = "fact" if fact_score > dim_score else "dimension"
|
|
61
|
+
return {"role": role, "fact_score": round(fact_score, 2), "dim_score": round(dim_score, 2),
|
|
62
|
+
"signals": signals}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# D2 前导键列前缀(M1-r7):业务键列族 *_code/*_no/*_id + time/batch + 枚举 flag(type/role/...)。
|
|
66
|
+
# 不读 keys 真值——只用 DDL 列声明序:建模表惯把主键/业务键列排在列定义最前。
|
|
67
|
+
_GRAIN_SEM = {"code", "batch", "time", "flag"}
|
|
68
|
+
_GRAIN_HINT = re.compile(r"(category|role|type|key|system|side|status|source|file|_no)", re.I)
|
|
69
|
+
# 纯物理/审计列:前导段遇到即跳过(create_time 可能是业务事件时间,不在此列)
|
|
70
|
+
_NON_GRAIN = re.compile(r"^(id|update_time|updated_time|etl_time|etl_date|sync_time|sync_version)$", re.I)
|
|
71
|
+
_GRAIN_CAP = 5
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _leading_grain(p: Dict[str, Any]) -> List[str]:
|
|
75
|
+
"""从 DDL 列声明序前导段抽业务键列(复合 UK 的 *_no 序号列族一并捕获)。"""
|
|
76
|
+
order = p.get("columns_order", [])
|
|
77
|
+
if not order:
|
|
78
|
+
return []
|
|
79
|
+
sem: Dict[str, str] = {}
|
|
80
|
+
for bucket, cols in p.get("semantic", {}).items():
|
|
81
|
+
for c in cols:
|
|
82
|
+
sem[c] = bucket
|
|
83
|
+
grain: List[str] = []
|
|
84
|
+
for c in order:
|
|
85
|
+
if _NON_GRAIN.match(c):
|
|
86
|
+
continue
|
|
87
|
+
s = sem.get(c, "other")
|
|
88
|
+
if s in _GRAIN_SEM or (s == "other" and _GRAIN_HINT.search(c)):
|
|
89
|
+
grain.append(c)
|
|
90
|
+
else:
|
|
91
|
+
break
|
|
92
|
+
if len(grain) >= _GRAIN_CAP:
|
|
93
|
+
break
|
|
94
|
+
return grain
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def guess_grain(p: Dict[str, Any], role: Optional[str] = None) -> List[str]:
|
|
98
|
+
"""D2:粒度候选键(前导键列前缀优先,按角色分化兜底;不看 keys 真值)。
|
|
99
|
+
|
|
100
|
+
前导段存在键列时即以其为粒度——图谱建模表惯把主键列置于列定义最前,
|
|
101
|
+
覆盖复合 UK(dt_iqc_incoming 5 列 *_no 序号族)。无前导键列时才回落角色规则。
|
|
102
|
+
"""
|
|
103
|
+
lead = _leading_grain(p)
|
|
104
|
+
if lead:
|
|
105
|
+
return lead
|
|
106
|
+
if role is None:
|
|
107
|
+
role = classify_role(p)["role"]
|
|
108
|
+
if role == "dimension":
|
|
109
|
+
# 维度粒度=业务键(与真值清洗口径对称:代理键 id 非粒度声明)——
|
|
110
|
+
# mapping 类取 code 对(source/output_param_code 族),枚举类取 code/type/role 列
|
|
111
|
+
cand = [c for c in p.get("code_cols", []) if not AUDIT_TIME.match(c)]
|
|
112
|
+
# hint 命中优先 + 收窄到 ≤3(M1-r3 判例:多猜列拉低 IoU——维度业务键取最小组合倾向)
|
|
113
|
+
hinted = [c for c in cand if GRAIN_HINT.search(c)]
|
|
114
|
+
plain = [c for c in cand if not GRAIN_HINT.search(c)]
|
|
115
|
+
flagged = [c for c in p.get("flag_cols", [])
|
|
116
|
+
if re.search(r"(type|role|category|key|system|side)", c, re.I)]
|
|
117
|
+
guess = (hinted + plain + flagged)[:4]
|
|
118
|
+
if guess:
|
|
119
|
+
return sorted(set(guess))
|
|
120
|
+
return ["id"] if "id" in {c.lower() for c in _all_cols(p)} else []
|
|
121
|
+
grain: List[str] = []
|
|
122
|
+
bt = business_time_cols(p)
|
|
123
|
+
if bt:
|
|
124
|
+
grain.append(bt[0]) # 业务时间窗通常是粒度一部分(U12 时间片)
|
|
125
|
+
grain.extend(p.get("batch_cols", [])[:2])
|
|
126
|
+
for c in p.get("code_cols", []):
|
|
127
|
+
if GRAIN_HINT.search(c) and c not in grain and len(grain) < 5:
|
|
128
|
+
grain.append(c)
|
|
129
|
+
return grain
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _all_cols(p: Dict[str, Any]) -> List[str]:
|
|
133
|
+
"""画像内全部列名(semantic 各桶并集)。"""
|
|
134
|
+
out: List[str] = []
|
|
135
|
+
for cols in p.get("semantic", {}).values():
|
|
136
|
+
out.extend(cols)
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def detect_scd(p: Dict[str, Any], columns: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
|
|
141
|
+
"""D3:SCD 类型建议(变更列探测)。"""
|
|
142
|
+
cols = {c.lower() for c in columns}
|
|
143
|
+
has_update = bool({"update_time", "updated_at"} & cols)
|
|
144
|
+
has_history = any(re.search(r"(_v\d+|_prev|_old|_history)", c, re.I) for c in columns)
|
|
145
|
+
if has_history:
|
|
146
|
+
scd, why = "SCD2", "存在历史版本列(_v2/_prev/_history 族)"
|
|
147
|
+
elif has_update and p["desc_ratio"] >= 0.08:
|
|
148
|
+
scd, why = "SCD1", "有 update 时间且描述列丰富(属性就地覆盖形态)"
|
|
149
|
+
else:
|
|
150
|
+
scd, why = "未判定", "变更列特征不足,人工定"
|
|
151
|
+
return {"scd": scd, "why": why}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def check_bus_matrix(entries: List[Dict[str, Any]], table_edges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
155
|
+
"""D4:总线矩阵一致性——维度被多事实复用检查(需血缘边,供 reviewer 阶段)。"""
|
|
156
|
+
edge_pairs = {(e.get("from"), e.get("to")) for e in table_edges}
|
|
157
|
+
findings = []
|
|
158
|
+
dims = [e["table"] for e in entries if e.get("role") == "dimension"]
|
|
159
|
+
for d in dims:
|
|
160
|
+
linked = {t for (f, t) in edge_pairs if f == d}
|
|
161
|
+
if len(linked) >= 2:
|
|
162
|
+
findings.append({"dim": d, "shared_by": sorted(linked)[:5],
|
|
163
|
+
"note": "跨事实复用维度(总线矩阵合格位)"})
|
|
164
|
+
return findings
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def naming_alignment(table: str, role: str) -> Optional[str]:
|
|
168
|
+
"""D5:命名对齐建议(U06 三套表示教训规则化)。"""
|
|
169
|
+
prefix = table.split("_")[0]
|
|
170
|
+
if role == "dimension" and prefix not in ("dim", "dwd"):
|
|
171
|
+
return f"维度表前缀 {prefix}_ ≠ dim_(U06 教训:统一前缀防三套表示)"
|
|
172
|
+
if role == "fact" and prefix in ("dim",):
|
|
173
|
+
return f"事实表前缀 dim_ 与角色矛盾"
|
|
174
|
+
return None
|
dimctx/core/matrix.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
"""matrix——总线矩阵查询核(从 scripts/gen_bus_matrix.py 迁移并纯函数化)。
|
|
3
|
+
|
|
4
|
+
四档符号(12 号正典):✓ 列直接存在 / ○ 仅代理列或异值域 / ⊕ 设计有落地未建列 / 空 无。
|
|
5
|
+
三档择优(2026-11-26 修 bug 判例):精确 base > 后缀匹配 > 最短子串。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from typing import Dict, List, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
DIM_WORDS = ("station", "factory", "base", "process", "material", "supplier",
|
|
14
|
+
"equipment", "line", "workshop", "customer", "product", "batch",
|
|
15
|
+
"work_order")
|
|
16
|
+
TIME_ANCHOR_RE = re.compile(r"^ptime$|_(date|time)$", re.I)
|
|
17
|
+
ENG_COLS = {"created_by", "updated_by", "created_time", "updated_time", "etl_time",
|
|
18
|
+
"ptime", "batch_log_id", "id"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def load_atlas(path: str) -> Optional[Dict]:
|
|
22
|
+
if not path or not os.path.exists(path):
|
|
23
|
+
return None
|
|
24
|
+
with open(path, encoding="utf-8") as f:
|
|
25
|
+
return json.load(f)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def pick_column(bases: Dict[str, Tuple[str, str]], dc: str) -> Optional[Tuple[str, str]]:
|
|
29
|
+
"""三档择优:精确 > 后缀 > 最短子串。返回 (type, column)。"""
|
|
30
|
+
if dc in bases:
|
|
31
|
+
return bases[dc]
|
|
32
|
+
suff = [(b, v) for b, v in bases.items() if b.endswith(dc)]
|
|
33
|
+
if suff:
|
|
34
|
+
return min(suff, key=lambda kv: len(kv[0]))[1]
|
|
35
|
+
subs = [(b, v) for b, v in bases.items() if dc in b]
|
|
36
|
+
if subs:
|
|
37
|
+
return min(subs, key=lambda kv: len(kv[0]))[1]
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def dt_rows(atlas: Dict) -> List[str]:
|
|
42
|
+
"""DT 结果层表(排除 shadow/bak/temp 变体)。"""
|
|
43
|
+
return sorted(n for n, i in atlas["tables"].items()
|
|
44
|
+
if re.match(r"^(mdop_)?dt_", n) and "DT 结果" in (i.get("layer") or "")
|
|
45
|
+
and not re.search(r"shadow|_bak$|_temp$|_new$|_v2$|_xm4$|_uk$|_dup$", n))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def build_grid(atlas: Dict) -> Tuple[List[str], List[str], Dict[str, Dict]]:
|
|
49
|
+
"""返回 (行表, 列概念, grid[表][概念] = (type, column) | None)。"""
|
|
50
|
+
tables = atlas["tables"]
|
|
51
|
+
rows = dt_rows(atlas)
|
|
52
|
+
dim_cols, has_time = [], {}
|
|
53
|
+
for n in rows:
|
|
54
|
+
cols = tables[n].get("columns") or {}
|
|
55
|
+
has_time[n] = any(TIME_ANCHOR_RE.search(c) for c in cols)
|
|
56
|
+
for c in cols:
|
|
57
|
+
if c.lower() in ENG_COLS:
|
|
58
|
+
continue
|
|
59
|
+
base = re.sub(r"_?(id|code|name|key)$", "", c.lower())
|
|
60
|
+
if base in ENG_COLS:
|
|
61
|
+
continue
|
|
62
|
+
for w in DIM_WORDS:
|
|
63
|
+
if w in base and len(base) <= 24:
|
|
64
|
+
dim_cols.append(w)
|
|
65
|
+
break
|
|
66
|
+
dim_cols = sorted(set(dim_cols))
|
|
67
|
+
dim_cols.insert(0, "时间锚")
|
|
68
|
+
grid = {}
|
|
69
|
+
for n in rows:
|
|
70
|
+
cols = tables[n].get("columns") or {}
|
|
71
|
+
bases = {}
|
|
72
|
+
for c, meta in cols.items():
|
|
73
|
+
base = re.sub(r"_?(id|code|name|key)$", "", c.lower())
|
|
74
|
+
bases.setdefault(base, (meta.get("type", "?"), c))
|
|
75
|
+
grid[n] = {}
|
|
76
|
+
for dc in dim_cols:
|
|
77
|
+
if dc == "时间锚":
|
|
78
|
+
grid[n][dc] = ("(存在性)", "时间列") if has_time.get(n) else None
|
|
79
|
+
else:
|
|
80
|
+
grid[n][dc] = pick_column(bases, dc)
|
|
81
|
+
return rows, dim_cols, grid
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def table_view(atlas: Dict, table: str) -> Optional[Dict]:
|
|
85
|
+
"""单表矩阵视图:全部格值 + evidence 列名/类型。"""
|
|
86
|
+
rows, dim_cols, grid = build_grid(atlas)
|
|
87
|
+
if table not in grid:
|
|
88
|
+
return None
|
|
89
|
+
cells = []
|
|
90
|
+
for dc in dim_cols:
|
|
91
|
+
v = grid[table][dc]
|
|
92
|
+
cells.append({"dim": dc, "cell": "✓" if v else "空",
|
|
93
|
+
"column": v[1] if v else "", "type": v[0] if v else ""})
|
|
94
|
+
return {"table": table, "cells": cells, "hits": sum(1 for c in cells if c["cell"] == "✓")}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def dimension_view(atlas: Dict, dim: str) -> Dict:
|
|
98
|
+
"""单维度概念视图:全部实现表 + 类型一致性。"""
|
|
99
|
+
rows, dim_cols, grid = build_grid(atlas)
|
|
100
|
+
impls, type_map = [], {}
|
|
101
|
+
for r in rows:
|
|
102
|
+
v = grid[r].get(dim)
|
|
103
|
+
if v:
|
|
104
|
+
impls.append({"table": r, "column": v[1], "type": v[0]})
|
|
105
|
+
type_map.setdefault(v[0], []).append(r)
|
|
106
|
+
consistent = len(type_map) <= 1
|
|
107
|
+
return {"dim": dim, "implementations": impls,
|
|
108
|
+
"type_groups": {t: ts for t, ts in type_map.items()},
|
|
109
|
+
"consistent": consistent}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def overview(atlas: Dict) -> Dict:
|
|
113
|
+
rows, dim_cols, grid = build_grid(atlas)
|
|
114
|
+
hits = sum(1 for r in rows for dc in dim_cols if grid[r][dc])
|
|
115
|
+
inconsistent = []
|
|
116
|
+
for dc in dim_cols:
|
|
117
|
+
if dc == "时间锚":
|
|
118
|
+
continue
|
|
119
|
+
v = dimension_view(atlas, dc)
|
|
120
|
+
if not v["consistent"]:
|
|
121
|
+
inconsistent.append({"dim": dc, "type_groups": v["type_groups"]})
|
|
122
|
+
return {"rows": len(rows), "cols": len(dim_cols), "cells_hit": hits,
|
|
123
|
+
"inconsistent_dims": inconsistent}
|
dimctx/core/profiler.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""profiler——C13 M0:表画像(列名语义分类)。
|
|
3
|
+
|
|
4
|
+
为 D1-D5 探测器提供统一的列语义视图。刻意**不读** layer/keys 字段——
|
|
5
|
+
那是 evalset 真值源,探测器只能看列名/类型/DDL 特征(盲测纪律,01 文档 §三)。
|
|
6
|
+
"""
|
|
7
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
from typing import Any, Dict, List, Optional
|
|
13
|
+
|
|
14
|
+
# 列语义词表(94 契约扫描+U06 三套表示判例的经验词表,可随研读线增补)
|
|
15
|
+
_PATTERNS = [
|
|
16
|
+
("time", re.compile(r"^(ptime|.*_time|.*_at|.*date|.*_dt)$", re.I)),
|
|
17
|
+
("batch", re.compile(r"^(.*batch.*|.*lot_no|.*批.*|inspection_lot_no)$", re.I)),
|
|
18
|
+
("measure", re.compile(r"^.*(qty|quantity|value|amount|count|cnt|num|数量|金额|值)$", re.I)),
|
|
19
|
+
("desc", re.compile(r"^.*(name|desc|remark|comment|说明|名称|备注)$", re.I)),
|
|
20
|
+
("flag", re.compile(r"^(is_.+|has_.+|.*_flag|.*status|.*_type|.*result)$", re.I)),
|
|
21
|
+
# system 入 code(M1-r5 判例:origin_system=来源系统标识,U06 合并维度业务键)
|
|
22
|
+
("code", re.compile(r"^.*(code|_id|_no|key|编码|编号|system)$", re.I)),
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
NUMERIC_TYPES = ("int", "decimal", "double", "float", "bigint", "tinyint", "smallint", "largeint")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def classify_column(name: str, col_type: str = "") -> str:
|
|
29
|
+
"""列名→语义类别;无匹配返回 'other'。type 用于消歧(如 *_value 若为 varchar 多为文本)。"""
|
|
30
|
+
n = (name or "").strip()
|
|
31
|
+
for sem, pat in _PATTERNS:
|
|
32
|
+
if pat.match(n):
|
|
33
|
+
# 消歧:measure 语义但类型非数值 → 降为 code(如 param_value 若是 varchar 存编码)
|
|
34
|
+
if sem == "measure" and col_type and not col_type.lower().startswith(NUMERIC_TYPES):
|
|
35
|
+
return "code"
|
|
36
|
+
return sem
|
|
37
|
+
return "other"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def profile_table(name: str, columns: Dict[str, Dict[str, Any]],
|
|
41
|
+
partition: Optional[str] = None) -> Dict[str, Any]:
|
|
42
|
+
"""单表画像。columns={列名: {type, comment}}(图谱 tables[].columns 形态)。"""
|
|
43
|
+
sem_counts: Dict[str, List[str]] = {}
|
|
44
|
+
numeric_cols: List[str] = []
|
|
45
|
+
for col, meta in columns.items():
|
|
46
|
+
sem = classify_column(col, (meta or {}).get("type", ""))
|
|
47
|
+
sem_counts.setdefault(sem, []).append(col)
|
|
48
|
+
if ((meta or {}).get("type", "") or "").lower().startswith(NUMERIC_TYPES):
|
|
49
|
+
numeric_cols.append(col)
|
|
50
|
+
n = max(len(columns), 1)
|
|
51
|
+
return {
|
|
52
|
+
"table": name,
|
|
53
|
+
"n_cols": len(columns),
|
|
54
|
+
"semantic": {k: v for k, v in sem_counts.items()},
|
|
55
|
+
"measure_cols": sem_counts.get("measure", []),
|
|
56
|
+
"time_cols": sem_counts.get("time", []),
|
|
57
|
+
"batch_cols": sem_counts.get("batch", []),
|
|
58
|
+
"code_cols": sem_counts.get("code", []),
|
|
59
|
+
"desc_cols": sem_counts.get("desc", []),
|
|
60
|
+
"flag_cols": sem_counts.get("flag", []),
|
|
61
|
+
"numeric_ratio": round(len(numeric_cols) / n, 3),
|
|
62
|
+
"desc_ratio": round(len(sem_counts.get("desc", [])) / n, 3),
|
|
63
|
+
"measure_ratio": round(len(sem_counts.get("measure", [])) / n, 3),
|
|
64
|
+
# 列声明序(DDL 特征,非 keys 真值)——D2 前导键列前缀识别用(M1-r7)
|
|
65
|
+
"columns_order": list(columns.keys()),
|
|
66
|
+
"partition": partition or "",
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def load_atlas(path: str) -> Dict[str, Any]:
|
|
71
|
+
with open(path, encoding="utf-8") as f:
|
|
72
|
+
return json.load(f)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def profile_atlas(atlas_path: str) -> List[Dict[str, Any]]:
|
|
76
|
+
"""全图谱画像(不含未注册表)。"""
|
|
77
|
+
doc = load_atlas(atlas_path)
|
|
78
|
+
out = []
|
|
79
|
+
for name, t in doc.get("tables", {}).items():
|
|
80
|
+
out.append(profile_table(name, t.get("columns", {}), t.get("partition", "")))
|
|
81
|
+
return out
|