dimctx 0.2.0__tar.gz → 0.3.1__tar.gz

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.
Files changed (25) hide show
  1. {dimctx-0.2.0/src/dimctx.egg-info → dimctx-0.3.1}/PKG-INFO +18 -5
  2. {dimctx-0.2.0 → dimctx-0.3.1}/README.md +17 -4
  3. {dimctx-0.2.0 → dimctx-0.3.1}/pyproject.toml +1 -1
  4. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/core/canon.py +44 -23
  5. dimctx-0.3.1/src/dimctx/core/detector.py +261 -0
  6. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/server.py +21 -2
  7. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/tools.py +102 -17
  8. {dimctx-0.2.0 → dimctx-0.3.1/src/dimctx.egg-info}/PKG-INFO +18 -5
  9. dimctx-0.3.1/tests/test_dimctx.py +378 -0
  10. dimctx-0.2.0/src/dimctx/core/detector.py +0 -174
  11. dimctx-0.2.0/tests/test_dimctx.py +0 -198
  12. {dimctx-0.2.0 → dimctx-0.3.1}/LICENSE +0 -0
  13. {dimctx-0.2.0 → dimctx-0.3.1}/NOTICE +0 -0
  14. {dimctx-0.2.0 → dimctx-0.3.1}/setup.cfg +0 -0
  15. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/__init__.py +0 -0
  16. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/core/__init__.py +0 -0
  17. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/core/complexity.py +0 -0
  18. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/core/matrix.py +0 -0
  19. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/core/profiler.py +0 -0
  20. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx/models.py +0 -0
  21. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx.egg-info/SOURCES.txt +0 -0
  22. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx.egg-info/dependency_links.txt +0 -0
  23. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx.egg-info/entry_points.txt +0 -0
  24. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx.egg-info/requires.txt +0 -0
  25. {dimctx-0.2.0 → dimctx-0.3.1}/src/dimctx.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dimctx
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: dimctx = dimensional modeling context provider — MCP server giving AI coding assistants Kimball modeling judgement, bus-matrix truth, and SQL complexity checks.
5
5
  Author: wagic
6
6
  License: AGPL-3.0-or-later
@@ -35,18 +35,29 @@ AI 写 SQL/DDL 时会瞎编建模决策:分不清事实和维度、猜不准
35
35
 
36
36
  | 工具 | 作用 |
37
37
  |---|---|
38
- | `analyze_table` | 判定表角色(fact/dimension)、粒度键、SCD 建议、总线矩阵格值 |
39
- | `search_canon` | 检索**你自备**的建模语料(本地 markdown) |
38
+ | `analyze_table` | 判定表角色(fact/dimension)、粒度键、SCD 建议(按原典 Type 2 三列签名)、总线矩阵格值;事实表用了可更新键模型时附类型债检查(见下);判为事实表却戴 `dim_` 前缀时给出 `naming_misalignment` |
39
+ | `search_canon` | 检索**你自备**的建模语料(本地 markdown,可配多个目录) |
40
40
  | `bus_matrix` | 总线矩阵查询(单表格值 / 单维度实现 / 全库概览) |
41
41
  | `measure_sql` | 度量下游取数复杂度(CASE WHEN / JOIN 深度 / 子查询 / 聚合嵌套) |
42
42
  | `check_conformed_facts` | **一致性事实检查**:同名度量在多张事实表出现时,定义/单位/过滤/时间口径必须完全一致;不兼容则按原典须改名 |
43
43
 
44
+ `analyze_table` 遇到「事实表 + 可更新键模型(Doris `UNIQUE` / `PRIMARY KEY`)」时多给一项 `upsert_check`。
45
+ 原典:三型事实表里只有累积快照的行应被更新,判据是每个关键里程碑有一个日期外键——所以只看**键外的业务时间列**:
46
+
47
+ | verdict | 含义 |
48
+ |---|---|
49
+ | `accumulating_snapshot` | 有起止里程碑对 → 行随流程改写属合法更新 |
50
+ | `periodic_snapshot` | 业务时间列全在键内 → 按键重写通常只是幂等重算 |
51
+ | `type_debt_risk` | 其余 → 若行是事务粒度事件,同键重写会无声明地抹掉历史(同时写入 `signals`) |
52
+ | `out_of_scope` | 贴源 / 汇总 / 维度 / 系统表(按图谱 `layer` 关键字或表名前缀)→ 不作类型判定 |
53
+
44
54
  ## 三步接入
45
55
 
46
56
  ```bash
47
57
  # 1) 配置(可选,缺省也能跑:只是语料检索为空)
48
58
  export DIMCTX_ATLAS=/path/to/atlas.json # 工程表图谱(可选)
49
- export DIMCTX_CANON_DIR=/path/to/markdown # 你自备的建模语料(可选)
59
+ export DIMCTX_CANON_DIR=/path/to/markdown # 你自备的建模语料(可选;多个目录用 os.pathsep 分隔:macOS/Linux ':',Windows ';')
60
+ export DIMCTX_ANALYSIS_DIR=/path/to/notes # 你自己的分析笔记(可选;同样可多目录,结果以 source 字段区分)
50
61
 
51
62
  # 2) 在 IDE 的 MCP 配置里加一条
52
63
  # VS Code (mcp.json) / Cursor (.cursor/mcp.json) / Continue (config.yaml)
@@ -65,7 +76,9 @@ export DIMCTX_CANON_DIR=/path/to/markdown # 你自备的建模语料(可选
65
76
  ## 开发
66
77
 
67
78
  ```bash
68
- uv run --with pytest --with pydantic python -m pytest tests/ -q # 19 passed
79
+ uv run --with pytest --with pydantic python -m pytest tests/ -q # 26 passed, 15 skipped(图谱相关用例跳过)
80
+ # 有工程表图谱时可全跑:
81
+ DIMCTX_TEST_ATLAS=/path/to/atlas.json uv run --with pytest --with pydantic python -m pytest tests/ -q # 41 passed
69
82
  ```
70
83
 
71
84
  ## 许可
@@ -14,18 +14,29 @@ AI 写 SQL/DDL 时会瞎编建模决策:分不清事实和维度、猜不准
14
14
 
15
15
  | 工具 | 作用 |
16
16
  |---|---|
17
- | `analyze_table` | 判定表角色(fact/dimension)、粒度键、SCD 建议、总线矩阵格值 |
18
- | `search_canon` | 检索**你自备**的建模语料(本地 markdown) |
17
+ | `analyze_table` | 判定表角色(fact/dimension)、粒度键、SCD 建议(按原典 Type 2 三列签名)、总线矩阵格值;事实表用了可更新键模型时附类型债检查(见下);判为事实表却戴 `dim_` 前缀时给出 `naming_misalignment` |
18
+ | `search_canon` | 检索**你自备**的建模语料(本地 markdown,可配多个目录) |
19
19
  | `bus_matrix` | 总线矩阵查询(单表格值 / 单维度实现 / 全库概览) |
20
20
  | `measure_sql` | 度量下游取数复杂度(CASE WHEN / JOIN 深度 / 子查询 / 聚合嵌套) |
21
21
  | `check_conformed_facts` | **一致性事实检查**:同名度量在多张事实表出现时,定义/单位/过滤/时间口径必须完全一致;不兼容则按原典须改名 |
22
22
 
23
+ `analyze_table` 遇到「事实表 + 可更新键模型(Doris `UNIQUE` / `PRIMARY KEY`)」时多给一项 `upsert_check`。
24
+ 原典:三型事实表里只有累积快照的行应被更新,判据是每个关键里程碑有一个日期外键——所以只看**键外的业务时间列**:
25
+
26
+ | verdict | 含义 |
27
+ |---|---|
28
+ | `accumulating_snapshot` | 有起止里程碑对 → 行随流程改写属合法更新 |
29
+ | `periodic_snapshot` | 业务时间列全在键内 → 按键重写通常只是幂等重算 |
30
+ | `type_debt_risk` | 其余 → 若行是事务粒度事件,同键重写会无声明地抹掉历史(同时写入 `signals`) |
31
+ | `out_of_scope` | 贴源 / 汇总 / 维度 / 系统表(按图谱 `layer` 关键字或表名前缀)→ 不作类型判定 |
32
+
23
33
  ## 三步接入
24
34
 
25
35
  ```bash
26
36
  # 1) 配置(可选,缺省也能跑:只是语料检索为空)
27
37
  export DIMCTX_ATLAS=/path/to/atlas.json # 工程表图谱(可选)
28
- export DIMCTX_CANON_DIR=/path/to/markdown # 你自备的建模语料(可选)
38
+ export DIMCTX_CANON_DIR=/path/to/markdown # 你自备的建模语料(可选;多个目录用 os.pathsep 分隔:macOS/Linux ':',Windows ';')
39
+ export DIMCTX_ANALYSIS_DIR=/path/to/notes # 你自己的分析笔记(可选;同样可多目录,结果以 source 字段区分)
29
40
 
30
41
  # 2) 在 IDE 的 MCP 配置里加一条
31
42
  # VS Code (mcp.json) / Cursor (.cursor/mcp.json) / Continue (config.yaml)
@@ -44,7 +55,9 @@ export DIMCTX_CANON_DIR=/path/to/markdown # 你自备的建模语料(可选
44
55
  ## 开发
45
56
 
46
57
  ```bash
47
- uv run --with pytest --with pydantic python -m pytest tests/ -q # 19 passed
58
+ uv run --with pytest --with pydantic python -m pytest tests/ -q # 26 passed, 15 skipped(图谱相关用例跳过)
59
+ # 有工程表图谱时可全跑:
60
+ DIMCTX_TEST_ATLAS=/path/to/atlas.json uv run --with pytest --with pydantic python -m pytest tests/ -q # 41 passed
48
61
  ```
49
62
 
50
63
  ## 许可
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "dimctx"
7
- version = "0.2.0"
7
+ version = "0.3.1"
8
8
  description = "dimctx = dimensional modeling context provider — MCP server giving AI coding assistants Kimball modeling judgement, bus-matrix truth, and SQL complexity checks."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -85,31 +85,52 @@ def _snippet(text: str, q: List[str], width: int = 160) -> str:
85
85
  return text[start:start + width].replace("\n", " ").strip()
86
86
 
87
87
 
88
+ def split_dirs(spec: Optional[str]) -> List[str]:
89
+ """把环境变量的目录说明拆成目录列表。
90
+
91
+ 多个目录用 os.pathsep 分隔(macOS/Linux 为 ':',Windows 为 ';'),顺序即加载顺序;
92
+ 空项与不存在的目录静默忽略——语料是可选配置,配错不应让服务起不来。
93
+ """
94
+ return [d for d in (x.strip() for x in (spec or "").split(os.pathsep)) if d and os.path.isdir(d)]
95
+
96
+
97
+ def _unquote(v: str) -> str:
98
+ """frontmatter 值两侧成对的一层引号去掉(title: 'Foo: bar' 是 YAML 的常见写法)。"""
99
+ return v[1:-1].strip() if len(v) >= 2 and v[0] == v[-1] and v[0] in "'\"" else v
100
+
101
+
88
102
  def load_corpus(canon_dir: str, analysis_dir: Optional[str] = None) -> List[Dict]:
89
- """从用户自备目录加载 markdown。canon_dir 为空/不存在 → 返回空(不报错,服务照常)。"""
103
+ """从用户自备目录加载 markdown(每个目录只读一层、只认 .md)。
104
+
105
+ canon_dir / analysis_dir 均可含多个目录(见 split_dirs);为空或全不存在 → 返回空(不报错,服务照常)。
106
+ """
90
107
  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})
108
+ seen = set()
109
+ for src, spec in (("canon", canon_dir), ("analysis", analysis_dir)):
110
+ for d in split_dirs(spec):
111
+ for fn in sorted(os.listdir(d)):
112
+ if not fn.endswith(".md"):
113
+ continue
114
+ p = os.path.join(d, fn)
115
+ real = os.path.realpath(p)
116
+ if real in seen: # 经软链/重复配置到达的同一文件只收一次,免得在 BM25 里加倍
117
+ continue
118
+ try:
119
+ text = open(p, encoding="utf-8").read()
120
+ except OSError:
121
+ continue
122
+ seen.add(real)
123
+ fm = {}
124
+ if text.startswith("---"):
125
+ parts = text.split("---", 2)
126
+ if len(parts) >= 3:
127
+ for line in parts[1].splitlines():
128
+ if ":" in line:
129
+ k, v = line.split(":", 1)
130
+ fm[k.strip()] = _unquote(v.strip())
131
+ text = parts[2]
132
+ docs.append({"title": fm.get("title", fn[:-3]), "url": fm.get("url", ""),
133
+ "date": fm.get("date", ""), "source": src, "text": text})
113
134
  return docs
114
135
 
115
136
 
@@ -0,0 +1,261 @@
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
+ # D3:SCD 类型——按原典 Type 2 三列签名判定(2026-11-28 改;旧判据「列名含 _v2/_prev/_old/_history」
141
+ # 是命名习惯而非原典签名,已废弃)。原典(Kimball Dimensional Modeling Techniques, Type 2: Add New Row):
142
+ # 1) row effective date 2) row expiration date 3) current row indicator
143
+ _SCD2_EFFECTIVE = re.compile(r"effective|valid_from|validity_start|valid_start|(^|_)(start|begin)(_|$)", re.I)
144
+ _SCD2_EXPIRE = re.compile(r"expir|valid_to|valid_until|validity_end|valid_end|(^|_)(end|until|thru)(_|$)", re.I)
145
+ _SCD2_CURRENT = re.compile(
146
+ r"^(is_)?current(_(row|flag|ind|indicator|record|version|yn))?(_flag|_ind|_indicator)?$"
147
+ r"|^current_yn$|^row_current(_flag|_ind)?$"
148
+ r"|^(is_)?(latest|active)(_row)?(_flag|_ind|_indicator)?$", re.I)
149
+ _TEMPORAL_TYPE = re.compile(r"^(date|datetime|timestamp|time)", re.I)
150
+
151
+
152
+ def _is_temporal(name: str, meta: Dict[str, Any], time_cols: set) -> bool:
153
+ """列名像时间(画像词表)或类型是日期时间——生效/失效列只在这里面找,免得 start_station 之类混入。"""
154
+ return name in time_cols or bool(_TEMPORAL_TYPE.match((meta or {}).get("type", "") or ""))
155
+
156
+
157
+ def detect_scd(p: Dict[str, Any], columns: Dict[str, Dict[str, Any]],
158
+ role: Optional[str] = None) -> Dict[str, Any]:
159
+ """D3:SCD 类型判定(只对维度表;按原典 Type 2 三列签名)。
160
+
161
+ role="fact" 时判「不适用」——SCD 是维度概念;事实表的行改写属累积快照(合法)或类型债
162
+ (见 upsert_risk),拿生效/失效列去套会把累积快照的里程碑误判成 SCD2。
163
+ """
164
+ if role == "fact":
165
+ return {"scd": "不适用", "why": "SCD 是维度概念;事实表的行改写请看 upsert_check(累积快照/周期快照/类型债)"}
166
+ time_cols = set(p.get("time_cols", []))
167
+ cols = list(columns)
168
+ temporal = [c for c in cols if _is_temporal(c, columns.get(c) or {}, time_cols)]
169
+ eff = [c for c in temporal if _SCD2_EFFECTIVE.search(c)]
170
+ exp = [c for c in temporal if _SCD2_EXPIRE.search(c)]
171
+ cur = [c for c in cols if _SCD2_CURRENT.match(c)]
172
+ if eff and exp:
173
+ got = f"生效 {eff[0]}、失效 {exp[0]}"
174
+ got += f"、当前行标志 {cur[0]}" if cur else "(无当前行标志列,当前行可由失效日期推断)"
175
+ return {"scd": "SCD2", "why": f"命中原典 Type 2 签名:{got}",
176
+ "columns": {"effective": eff, "expiration": exp, "current": cur}}
177
+ if cur:
178
+ return {"scd": "未判定", "why": f"只有当前行标志列 {cur[0]},缺生效/失效日期——Type 2 须三列齐备"}
179
+ lower = {c.lower() for c in cols}
180
+ if {"update_time", "updated_at"} & lower and p["desc_ratio"] >= 0.08:
181
+ return {"scd": "SCD1", "why": "有 update 时间且描述列丰富(属性就地覆盖形态)"}
182
+ return {"scd": "未判定", "why": "变更列特征不足,人工定"}
183
+
184
+
185
+ # 事实表的可更新键模型检查(2026-11-28)。原典(Kimball Dimensional Modeling Techniques):
186
+ # "the accumulating fact table row is revisited and updated. This consistent updating… is unique among
187
+ # the three types of fact tables";累积快照的判据是 "a date foreign key for each critical milestone"。
188
+ _UPDATABLE_MODELS = {"UNIQUE", "PRIMARY"} # Doris UNIQUE / PRIMARY KEY:同键重写
189
+ _AUDITISH = re.compile(r"^(create|created|update|updated|modify|modified|insert|load|etl|sync|write)"
190
+ r"_(time|date|at|ts)$|^ptime$", re.I)
191
+ _MILE_START = re.compile(r"(^|_)(start|begin)(_|$)", re.I)
192
+ _MILE_END = re.compile(r"(^|_)(end|finish|close|closed|complete|completion)(_|$)", re.I)
193
+ # 类型规则只约束「原子业务事实表」:贴源(ODS)/ 汇总(DWS·ADS)/ 维度 / 系统与元数据表按键重写是常态。
194
+ # 先看图谱 layer 关键字,再看表名前缀(DDL 模式没有 layer)。
195
+ _OUT_OF_SCOPE_LAYER = re.compile(
196
+ r"ods|贴源|stg|staging|raw|flink|sink|cdc|元数据|metadata|dws|汇总|聚合|agg|ads|dim|维表|未分层|unlayered", re.I)
197
+ _OUT_OF_SCOPE_NAME = re.compile(
198
+ r"^(ods|stg|staging|raw|dws|ads|agg|dm|dim|etl|meta|tmp|temp|lineage|alert|ingestion|worker|sys|system)_", re.I)
199
+
200
+
201
+ def upsert_risk(p: Dict[str, Any], model: Optional[str], keys: Optional[List[str]],
202
+ partition: Optional[str], name: str = "", layer: str = "") -> Optional[Dict[str, Any]]:
203
+ """事实表用了可更新键模型(Doris UNIQUE / PRIMARY KEY)时,判断行改写站不站得住。
204
+
205
+ 唯一依据是「键外的业务时间列」(排除审计列 / 分区列 / 键列),返回四态之一:
206
+ accumulating_snapshot 有起止里程碑对 → 行随流程改写属原典允许的更新
207
+ periodic_snapshot 业务时间列全在键内 → 按键重写通常只是幂等重算
208
+ type_debt_risk 其余 → 若行是事务粒度事件,同键重写会无声明地抹掉历史
209
+ out_of_scope 贴源 / 汇总 / 维度 / 系统表(按 layer 或命名)→ 不作类型判定
210
+ 键模型未知或不可更新(DUPLICATE / AGGREGATE)→ None,调用方不输出该项。
211
+ """
212
+ if (model or "").upper() not in _UPDATABLE_MODELS:
213
+ return None
214
+ hit = _OUT_OF_SCOPE_LAYER.search(layer or "") or _OUT_OF_SCOPE_NAME.match(name or "")
215
+ if hit:
216
+ return {"verdict": "out_of_scope", "key_model": model, "matched": hit.group(0),
217
+ "note": f"三型规则只约束原子业务事实表;按分层/命名({hit.group(0)})该表属贴源、汇总、维度或系统表,"
218
+ "按键重写是常态,不作类型债判定。"}
219
+ keyset = {k.lower() for k in (keys or [])}
220
+ m = re.search(r"\(\s*`?(\w+)`?\s*\)", partition or "")
221
+ pcol = m.group(1).lower() if m else ""
222
+ bt = [c for c in business_time_cols(p)
223
+ if c.lower() not in keyset and c.lower() != pcol and not _AUDITISH.match(c)]
224
+ starts = [c for c in bt if _MILE_START.search(c)]
225
+ ends = [c for c in bt if _MILE_END.search(c)]
226
+ base = {"key_model": model, "business_time_cols": bt, "milestones": {"start": starts, "end": ends}}
227
+ if starts and ends:
228
+ return {**base, "verdict": "accumulating_snapshot",
229
+ "note": f"有起止里程碑对({starts[0]} / {ends[0]}):疑似累积快照,行随流程改写属原典允许的更新。"}
230
+ if not bt and any(profiler.classify_column(k) == "time" for k in keyset):
231
+ return {**base, "verdict": "periodic_snapshot",
232
+ "note": "业务时间列全在键内:形态是周期快照,按键重写通常只是幂等重算(周期闭合后不应再改写)。"}
233
+ return {**base, "verdict": "type_debt_risk",
234
+ "note": "可更新键模型,但键外没有起止里程碑对:若这些行是事务粒度事件,同键重写会无声明地抹掉历史"
235
+ "(原典:三型事实表里只有累积快照的行应被更新);若是流程在途的快照,应补齐里程碑日期外键。"}
236
+
237
+
238
+ def check_bus_matrix(entries: List[Dict[str, Any]], table_edges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
239
+ """D4:总线矩阵一致性——维度被多事实复用检查(需血缘边,供 reviewer 阶段)。"""
240
+ edge_pairs = {(e.get("from"), e.get("to")) for e in table_edges}
241
+ findings = []
242
+ dims = [e["table"] for e in entries if e.get("role") == "dimension"]
243
+ for d in dims:
244
+ linked = {t for (f, t) in edge_pairs if f == d}
245
+ if len(linked) >= 2:
246
+ findings.append({"dim": d, "shared_by": sorted(linked)[:5],
247
+ "note": "跨事实复用维度(总线矩阵合格位)"})
248
+ return findings
249
+
250
+
251
+ def naming_alignment(table: str, role: str) -> Optional[str]:
252
+ """D5:前缀与角色矛盾——只报证据最强的一种:判为事实表却戴着 dim_ 前缀。
253
+
254
+ 「维度表却没有 dim_ 前缀」不报:命名约定各异(customers、date_dim 都合法),报了全是噪声。
255
+ 命中时的含义:维度层里混进了一张事实(治理场景「事实表被设计成了维表」)——
256
+ 实例:一张每批次一行、带三类时间各自最早/最晚共六个时间列与 update_count 的表,其实是批次时间快照。
257
+ """
258
+ if role == "fact" and table.split("_")[0] == "dim":
259
+ return (f"角色判为事实表,但表名前缀是 dim_——维度层里混入了事实;"
260
+ "核对其粒度:若一行对应一个流程实例并带里程碑时间,它是累积快照,应移出维度层")
261
+ return None
@@ -21,12 +21,26 @@ def _mcp_available() -> bool:
21
21
  return False
22
22
 
23
23
 
24
+ def _version() -> str:
25
+ """包版本,用于 MCP 握手里的 serverInfo.version。
26
+
27
+ 取自已安装的包元数据;源码目录直跑而未安装时取不到,返回空串(不影响任何功能)。
28
+ """
29
+ try:
30
+ from importlib.metadata import version
31
+ return version("dimctx")
32
+ except Exception:
33
+ return ""
34
+
35
+
24
36
  def _make_server():
25
37
  """同时支持 mcp 1.x(FastMCP)与 2.x(MCPServer)。
26
38
 
27
39
  判例(2026-11-27 实测):mcp 2.x 把 FastMCP 改名 MCPServer,且 1.x 的
28
40
  `mcp.server.fastmcp` 在 2.x 会**故意抛 ModuleNotFoundError** 并提示迁移——
29
41
  故必须按版本探测而不是 try/except ImportError 兜底(后者会被该异常击穿)。
42
+ 版本号(2026-11-28 实测 mcp 1.30 / 2.3):2.x 的 MCPServer 收 version= 参数;
43
+ 1.x 的 FastMCP 不收(TypeError),须写在其低层 Server 的 version 属性上。
30
44
  """
31
45
  major = 1
32
46
  try:
@@ -38,11 +52,16 @@ def _make_server():
38
52
  major = 2
39
53
  except Exception:
40
54
  major = 1
55
+ ver = _version()
41
56
  if major >= 2:
42
57
  from mcp.server.mcpserver import MCPServer
43
- return MCPServer("dimctx")
58
+ return MCPServer("dimctx", version=ver)
44
59
  from mcp.server.fastmcp import FastMCP
45
- return FastMCP("dimctx")
60
+ srv = FastMCP("dimctx")
61
+ low = getattr(srv, "_mcp_server", None)
62
+ if ver and low is not None:
63
+ low.version = ver
64
+ return srv
46
65
 
47
66
 
48
67
  def build_server():