fineprint 0.8.0__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.
@@ -0,0 +1,19 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.egg-info/
5
+ dist/
6
+ node_modules/
7
+ dashboard/dist/
8
+ *.duckdb
9
+ *.duckdb.wal
10
+ warehouse/dbt_project/target/
11
+ warehouse/dbt_project/dbt_packages/
12
+ warehouse/dbt_project/logs/
13
+ logs/
14
+ .metriclens/
15
+ warehouse/dbt_project/.metriclens/
16
+ .env
17
+ *.log
18
+ .DS_Store
19
+ .user.yml
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.5
2
+ Name: fineprint
3
+ Version: 0.8.0
4
+ Summary: The fine print of your metrics: deterministic column-level lineage x LLM reading over dbt artifacts, cross-validated, evidence-bound caliber cards
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: data-governance,dbt,lineage,metrics,semantic-layer,sqlglot
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Database
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: pyyaml>=6.0
17
+ Requires-Dist: requests>=2.28
18
+ Requires-Dist: sqlglot<32,>=30
19
+ Provides-Extra: demo
20
+ Requires-Dist: dbt-duckdb; extra == 'demo'
21
+ Requires-Dist: duckdb; extra == 'demo'
22
+ Requires-Dist: faker; extra == 'demo'
23
+ Requires-Dist: fastapi; extra == 'demo'
24
+ Requires-Dist: numpy; extra == 'demo'
25
+ Requires-Dist: pandas; extra == 'demo'
26
+ Requires-Dist: uvicorn[standard]; extra == 'demo'
27
+ Provides-Extra: dev
28
+ Requires-Dist: httpx; extra == 'dev'
29
+ Requires-Dist: pytest; extra == 'dev'
30
+ Requires-Dist: ruff; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # fineprint
34
+
35
+ **The fine print of your metrics.** 从 dbt 项目的编译产物(manifest / catalog /
36
+ compiled SQL)逆向合成每个指标的完整技术口径——零数据库连接。
37
+
38
+ Reverse-engineers the full technical caliber of every metric from your dbt
39
+ artifacts (manifest / catalog / compiled SQL) — zero database connection.
40
+
41
+ - **字段级血缘图 column-level lineage**:跨模型、进 CTE/子查询/UNION/PIVOT,
42
+ 条件与聚合语义一并入图。
43
+ - **口径卡 caliber cards**:确定性公式组合器(发布权威)× LLM 解读(解释与
44
+ 叙述)双通道互证,每个事实带机器证据;组合器不可证时 LLM 兜底并标注原因。
45
+ 在 5 个公开真实项目(34,499 列)上组合器覆盖 99.7%,残余全部具名。
46
+ - **口径漂移检测 caliber drift**:图快照逐语义点比对,SQL 改动落到受影响
47
+ 指标与条件粒度。
48
+
49
+ ```bash
50
+ pip install fineprint
51
+
52
+ metriclens init --project <dbt 项目目录> # 生成 metriclens.yml 模板
53
+ metriclens graph --project DIR # 建血缘图(需先 dbt compile + docs generate)
54
+ metriclens synth --project DIR # 合成口径卡(需配置 LLM 端点)
55
+ metriclens drift --project DIR # 漂移检测
56
+ ```
57
+
58
+ `fineprint` 与 `metriclens` 两个命令等价;import 名为 `metriclens`。
59
+ LLM 端点经环境变量或项目根 `.env` 配置(`METRICLENS_LLM_BASE` /
60
+ `METRICLENS_LLM_KEY` / `METRICLENS_LLM_MODEL`),兼容 OpenAI 风格 API。
61
+
62
+ 无 catalog 也能跑(列 schema 由 yml 声明 + 编译 SQL 拓扑推断补全);能执行
63
+ `dbt docs generate` 时仍建议补上,实测列集更可靠。
64
+
65
+ License: Apache-2.0
@@ -0,0 +1,33 @@
1
+ # fineprint
2
+
3
+ **The fine print of your metrics.** 从 dbt 项目的编译产物(manifest / catalog /
4
+ compiled SQL)逆向合成每个指标的完整技术口径——零数据库连接。
5
+
6
+ Reverse-engineers the full technical caliber of every metric from your dbt
7
+ artifacts (manifest / catalog / compiled SQL) — zero database connection.
8
+
9
+ - **字段级血缘图 column-level lineage**:跨模型、进 CTE/子查询/UNION/PIVOT,
10
+ 条件与聚合语义一并入图。
11
+ - **口径卡 caliber cards**:确定性公式组合器(发布权威)× LLM 解读(解释与
12
+ 叙述)双通道互证,每个事实带机器证据;组合器不可证时 LLM 兜底并标注原因。
13
+ 在 5 个公开真实项目(34,499 列)上组合器覆盖 99.7%,残余全部具名。
14
+ - **口径漂移检测 caliber drift**:图快照逐语义点比对,SQL 改动落到受影响
15
+ 指标与条件粒度。
16
+
17
+ ```bash
18
+ pip install fineprint
19
+
20
+ metriclens init --project <dbt 项目目录> # 生成 metriclens.yml 模板
21
+ metriclens graph --project DIR # 建血缘图(需先 dbt compile + docs generate)
22
+ metriclens synth --project DIR # 合成口径卡(需配置 LLM 端点)
23
+ metriclens drift --project DIR # 漂移检测
24
+ ```
25
+
26
+ `fineprint` 与 `metriclens` 两个命令等价;import 名为 `metriclens`。
27
+ LLM 端点经环境变量或项目根 `.env` 配置(`METRICLENS_LLM_BASE` /
28
+ `METRICLENS_LLM_KEY` / `METRICLENS_LLM_MODEL`),兼容 OpenAI 风格 API。
29
+
30
+ 无 catalog 也能跑(列 schema 由 yml 声明 + 编译 SQL 拓扑推断补全);能执行
31
+ `dbt docs generate` 时仍建议补上,实测列集更可靠。
32
+
33
+ License: Apache-2.0
@@ -0,0 +1,10 @@
1
+ """MetricLens — metric caliber synthesis for dbt projects.
2
+
3
+ Reverse-engineers the business & technical definition ("caliber") of every
4
+ dashboard metric from your existing multi-layer SQL: deterministic column-level
5
+ lineage × LLM per-model reading, cross-validated, evidence-bound, and published
6
+ as consumer-facing caliber cards.
7
+
8
+ Distributed on PyPI as ``fineprint`` — the fine print of your metrics.
9
+ """
10
+ __version__ = "0.8.0"
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env python3
2
+ """metriclens 命令行入口。
3
+
4
+ metriclens init --project <dbt 项目目录> 生成 metriclens.yml 模板
5
+ metriclens graph --project DIR 构建字段级血缘图(需先 dbt compile + docs generate)
6
+ metriclens trace --project DIR model.column S/F/E 三元组回溯
7
+ metriclens synth --project DIR [--only KEY] 双通道口径合成,整批原子发布
8
+ metriclens drift --project DIR [--strict] 口径快照对比,漂移事件入日志
9
+ metriclens govern --project DIR 指纹扫描 + B 档 LLM 仲裁 → 治理报告
10
+ metriclens report --project DIR [-o FILE] 口径卡导出为自包含 HTML
11
+ """
12
+ import argparse
13
+ import sys
14
+ from pathlib import Path
15
+
16
+
17
+ def _project(args):
18
+ from metriclens.project import DbtProject
19
+ return DbtProject(args.project, target_dir=getattr(args, "target_path", None))
20
+
21
+
22
+ def _cfg(args):
23
+ from metriclens.config import MLConfig
24
+ return MLConfig.load(Path(args.project))
25
+
26
+
27
+ def _graph(project):
28
+ from metriclens.trace import load_graph
29
+ p = project.graph_path()
30
+ if not p.exists():
31
+ print(f"血缘图不存在({p});请先执行 metriclens graph", file=sys.stderr)
32
+ sys.exit(1)
33
+ return load_graph(p)
34
+
35
+
36
+ def cmd_init(args):
37
+ from metriclens.config import EXAMPLE
38
+ f = Path(args.project) / "metriclens.yml"
39
+ if f.exists() and not args.force:
40
+ print(f"{f} 已存在(--force 覆盖)")
41
+ return
42
+ f.write_text(EXAMPLE)
43
+ print(f"已生成 {f}\n下一步:填入 metrics(model.column),设置 LLM 环境变量(见 README),然后 metriclens graph")
44
+
45
+
46
+ def cmd_graph(args):
47
+ from metriclens.lineage import build_graph, save_graph
48
+ project = _project(args)
49
+ if project.catalog_missing:
50
+ print("⚠ 未找到 catalog.json,进入无 catalog 模式:列 schema 由 yml 声明 + "
51
+ "编译 SQL 拓扑推断补全;能执行 dbt docs generate 时仍建议补上(实测列集更强)",
52
+ file=sys.stderr)
53
+ graph = build_graph(project)
54
+ ncols = sum(len(m["columns"]) for m in graph["models"].values())
55
+ nconds = sum(len(m["conditions"]) for m in graph["models"].values())
56
+ nsem = sum(len(m["semantics"]) for m in graph["models"].values())
57
+ errs = [(n, c) for n, m in graph["models"].items() for c, d in m["columns"].items() if d.get("error")]
58
+ errs += [(n, f"<model: {m['error'][:60]}>") for n, m in graph["models"].items() if m.get("error")]
59
+ if errs and not args.allow_partial:
60
+ # 校验不过不落盘:失败运行不得覆盖上一次可用的图(trace/synth 仍读旧图)
61
+ print(f"column lineage errors ({len(errs)}):", errs[:8], file=sys.stderr)
62
+ print("图未写出,旧图保持不变;确认可接受后用 --allow-partial 强制写出", file=sys.stderr)
63
+ sys.exit(1)
64
+ save_graph(project, graph)
65
+ print(f"graph: {len(graph['models'])} models, {ncols} columns, {nconds} conditions, "
66
+ f"{nsem} semantic points → {project.graph_path()} (dialect={graph['meta']['dialect']})")
67
+ if errs:
68
+ print(f"column lineage errors ({len(errs)}, --allow-partial):", errs[:8], file=sys.stderr)
69
+
70
+
71
+ def cmd_trace(args):
72
+ from metriclens.trace import render, trace
73
+ project = _project(args)
74
+ graph = _graph(project)
75
+ model, col = args.target.rsplit(".", 1)
76
+ print(render(trace(graph, model, col)))
77
+
78
+
79
+ def cmd_synth(args):
80
+ from metriclens.llm import load_dotenv
81
+ from metriclens.synth import run_all
82
+ project = _project(args)
83
+ load_dotenv(project.project_dir)
84
+ cfg = _cfg(args)
85
+ sys.exit(run_all(project, cfg, _graph(project), only=args.only))
86
+
87
+
88
+ def cmd_drift(args):
89
+ from metriclens.drift import print_events, run_check
90
+ project = _project(args)
91
+ cfg = _cfg(args)
92
+ events = run_check(project, cfg, _graph(project), save=not args.dry_run,
93
+ block_high=args.strict)
94
+ print_events(events)
95
+ if args.strict and any(e["severity"] == "high" for e in events):
96
+ sys.exit(1)
97
+
98
+
99
+ def cmd_govern(args):
100
+ try:
101
+ from metriclens.arbitrate import build_report, print_report
102
+ except ImportError:
103
+ print("此发行版未包含治理组件(重复建设扫描与仲裁);其余命令不受影响。",
104
+ file=sys.stderr)
105
+ return 3
106
+ from metriclens.llm import load_dotenv
107
+ project = _project(args)
108
+ load_dotenv(project.project_dir)
109
+ cfg = _cfg(args)
110
+ print_report(build_report(project, cfg, _graph(project)))
111
+
112
+
113
+ def cmd_report(args):
114
+ from metriclens.report import export_html
115
+ project = _project(args)
116
+ out = Path(args.output) if args.output else project.workspace / "caliber_report.html"
117
+ n = export_html(project, out)
118
+ print(f"报告已导出: {out}({n} 张口径卡)")
119
+
120
+
121
+ def main(argv=None):
122
+ ap = argparse.ArgumentParser(prog="metriclens", description=__doc__,
123
+ formatter_class=argparse.RawDescriptionHelpFormatter)
124
+ sub = ap.add_subparsers(dest="cmd", required=True)
125
+
126
+ def common(p):
127
+ p.add_argument("--project", default=".", help="dbt 项目根目录(默认当前目录)")
128
+ p.add_argument("--target-path", dest="target_path",
129
+ help="dbt target 目录(默认: DBT_TARGET_PATH → dbt_project.yml 的 target-path → target)")
130
+ return p
131
+
132
+ p = common(sub.add_parser("init", help="生成 metriclens.yml 模板"))
133
+ p.add_argument("--force", action="store_true")
134
+ p.set_defaults(fn=cmd_init)
135
+ p = common(sub.add_parser("graph", help="构建字段级血缘图"))
136
+ p.add_argument("--allow-partial", action="store_true", help="存在解析失败的列时仍以 0 退出")
137
+ p.set_defaults(fn=cmd_graph)
138
+ p = common(sub.add_parser("trace", help="回溯 S/F/E 三元组"))
139
+ p.add_argument("target", help="model.column")
140
+ p.set_defaults(fn=cmd_trace)
141
+ p = common(sub.add_parser("synth", help="双通道口径合成(LLM)"))
142
+ p.add_argument("--only", help="只重跑一个指标 key(从 active 批次补齐其余)")
143
+ p.set_defaults(fn=cmd_synth)
144
+ p = common(sub.add_parser("drift", help="口径漂移检测"))
145
+ p.add_argument("--strict", action="store_true", help="high 级漂移非零退出")
146
+ p.add_argument("--dry-run", action="store_true", help="只对比不落盘")
147
+ p.set_defaults(fn=cmd_drift)
148
+ common(sub.add_parser("govern", help="指纹扫描 + LLM 仲裁 → 治理报告")).set_defaults(fn=cmd_govern)
149
+ p = common(sub.add_parser("report", help="口径卡导出 HTML"))
150
+ p.add_argument("-o", "--output", help="输出文件(默认 .metriclens/caliber_report.html)")
151
+ p.set_defaults(fn=cmd_report)
152
+
153
+ args = ap.parse_args(argv)
154
+ args.fn(args)
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env python3
2
+ """metriclens.yml 配置:指标清单、语言、业务词典、治理参数。
3
+
4
+ 放在 dbt 项目根目录。密钥永不进配置文件——LLM 凭据只走环境变量(见 llm.py)。
5
+ """
6
+ import re
7
+ import unicodedata
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+
11
+ import yaml
12
+
13
+ # key 直接用作批次目录内的文件名:限定字符集,杜绝路径分隔符与 ../ 逃逸
14
+ KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$")
15
+ # target 两段 model.column;短名跨包歧义时用三段 package.model.column 消歧
16
+ TARGET_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$")
17
+ RESERVED_KEYS = {"index", "active_run"}
18
+
19
+
20
+ def _internal_packages_of(raw: dict) -> tuple:
21
+ v = raw.get("internal_packages")
22
+ if v is None:
23
+ return ()
24
+ if not isinstance(v, list) or not all(isinstance(x, str) and x for x in v):
25
+ raise ValueError(f"internal_packages 须为字符串列表(dbt 包名),实得 {v!r}")
26
+ return tuple(v)
27
+
28
+
29
+ def read_internal_packages(project_dir) -> tuple:
30
+ """metriclens.yml 顶层 internal_packages:按一方代码解析的额外 dbt 包名单。
31
+
32
+ 独立于 MLConfig.load 的轻量读取器——`metriclens graph` 不要求完整配置
33
+ (可以没有 metrics),但第三方包的数据源边界判定必须在建图时就生效。"""
34
+ f = Path(project_dir) / "metriclens.yml"
35
+ if not f.exists():
36
+ return ()
37
+ raw = yaml.safe_load(f.read_text()) or {}
38
+ return _internal_packages_of(raw) if isinstance(raw, dict) else ()
39
+
40
+ EXAMPLE = """\
41
+ # MetricLens 配置(放在 dbt 项目根目录)
42
+ language: zh # 口径卡语言: zh | en
43
+ metrics: # 要合成口径卡的看板指标(model.column)
44
+ - key: revenue
45
+ title: 营收
46
+ target: fct_orders_daily.revenue
47
+ # - key: refund_rate
48
+ # title: 退款率
49
+ # target: mart_refunds.refund_rate
50
+ # extra_targets: [mart_refunds.channel] # 可选:合并回溯的关联列
51
+ # query_filter: "channel = 'live'" # 可选:取数时的查询层过滤说明
52
+ lexicon: {} # 可选:业务词典(术语 → 解释),供业务口径生成引用
53
+ # internal_packages: [shared_models] # 可选:按一方代码解析的 dbt 包;
54
+ # 其余第三方包(Fivetran/dbt_utils 等)的模型一律按数据源边界
55
+ # 处理——不解析其 SQL 与口径,血缘在其物化表处截止
56
+ governance:
57
+ scan_layers: [] # 指纹重复扫描的分层白名单;空 = 全部模型
58
+ base_suffixes: [_total, _14d, _1d, _7d, _30d] # 判定"同基名"时剥离的后缀
59
+ skip_columns: [] # 扫描跳过的列名
60
+ skip_suffixes: [_id, _date, _time, _key]
61
+ max_llm_pairs: 40 # B 档 LLM 仲裁的候选上限(超出截断并提示,控制成本)
62
+ """
63
+
64
+
65
+ @dataclass
66
+ class MetricDef:
67
+ key: str
68
+ title: str
69
+ target: str
70
+ extra_targets: list = field(default_factory=list)
71
+ query_filter: str | None = None
72
+
73
+
74
+ @dataclass
75
+ class MLConfig:
76
+ language: str = "zh"
77
+ metrics: list = field(default_factory=list)
78
+ lexicon: dict = field(default_factory=dict)
79
+ internal_packages: tuple = ()
80
+ scan_layers: list = field(default_factory=list)
81
+ base_suffixes: list = field(default_factory=lambda: ["_total", "_14d", "_1d", "_7d", "_30d"])
82
+ skip_columns: list = field(default_factory=list)
83
+ skip_suffixes: list = field(default_factory=lambda: ["_id", "_date", "_time", "_key"])
84
+ max_llm_pairs: int = 40
85
+ path: Path | None = None
86
+
87
+ @classmethod
88
+ def load(cls, project_dir: Path) -> "MLConfig":
89
+ f = Path(project_dir) / "metriclens.yml"
90
+ if not f.exists():
91
+ raise FileNotFoundError(
92
+ f"未找到 {f}\n请先执行 metriclens init 生成配置,或手工创建(模板见 README)")
93
+ raw = yaml.safe_load(f.read_text()) or {}
94
+ if not isinstance(raw, dict):
95
+ raise ValueError(f"{f} 顶层须为映射(language/metrics/…),实得 {type(raw).__name__}")
96
+ gov = raw.get("governance") or {}
97
+ if not isinstance(gov, dict):
98
+ raise ValueError(f"governance 须为映射,实得 {type(gov).__name__}")
99
+ metrics, seen_keys = [], set()
100
+ for m in raw.get("metrics") or []:
101
+ if not isinstance(m, dict) or not m.get("key") or not m.get("target"):
102
+ raise ValueError(f"metrics 条目缺少 key/target: {m}")
103
+ key = str(m["key"])
104
+ if not KEY_RE.match(key):
105
+ raise ValueError(f"metric key 非法: {key!r}(须匹配 {KEY_RE.pattern},不得含路径分隔符)")
106
+ if key.lower() in RESERVED_KEYS:
107
+ raise ValueError(f"metric key 为保留名: {key!r}(保留: {sorted(RESERVED_KEYS)})")
108
+ # 大小写不敏感文件系统(macOS/Windows 默认)上 GMV.json 与 gmv.json 同文件,
109
+ # NFC + casefold 判重杜绝跨平台互相覆盖
110
+ folded = unicodedata.normalize("NFC", key).casefold()
111
+ if folded in seen_keys:
112
+ raise ValueError(f"metric key 重复: {key!r}(大小写不敏感文件系统上同批发布会互相覆盖)")
113
+ seen_keys.add(folded)
114
+ targets = [m["target"], *(m.get("extra_targets") or [])]
115
+ for tgt in targets:
116
+ if not isinstance(tgt, str) or not TARGET_RE.match(tgt):
117
+ raise ValueError(f"metric {key!r} 的 target/extra_targets 须为 'model.column'"
118
+ f"(或跨包重名时 'package.model.column'),实得 {tgt!r}")
119
+ qf = m.get("query_filter")
120
+ if qf is not None and not isinstance(qf, str):
121
+ raise ValueError(f"metric {key!r} 的 query_filter 须为字符串,实得 {type(qf).__name__}")
122
+ metrics.append(MetricDef(
123
+ key=key, title=m.get("title", key), target=m["target"],
124
+ extra_targets=list(m.get("extra_targets") or []), query_filter=qf))
125
+ if not metrics:
126
+ raise ValueError(f"{f} 的 metrics 为空:至少配置一个 model.column 目标")
127
+
128
+ def _strlist(field_name: str, v, default: list) -> list:
129
+ v = v if v is not None else default
130
+ if not isinstance(v, list) or not all(isinstance(x, str) for x in v):
131
+ raise ValueError(f"governance.{field_name} 须为字符串列表,实得 {v!r}")
132
+ return v
133
+
134
+ pairs = gov.get("max_llm_pairs", cls().max_llm_pairs)
135
+ if not isinstance(pairs, int) or isinstance(pairs, bool) or pairs < 0:
136
+ raise ValueError(f"governance.max_llm_pairs 须为非负整数,实得 {pairs!r}")
137
+ lex = raw.get("lexicon") or {}
138
+ if not isinstance(lex, dict):
139
+ raise ValueError(f"lexicon 须为映射(术语 → 解释),实得 {type(lex).__name__}")
140
+ cfg = cls(
141
+ language=raw.get("language", "zh"), metrics=metrics,
142
+ lexicon=lex,
143
+ internal_packages=_internal_packages_of(raw),
144
+ scan_layers=_strlist("scan_layers", gov.get("scan_layers"), []),
145
+ base_suffixes=_strlist("base_suffixes", gov.get("base_suffixes"), cls().base_suffixes),
146
+ skip_columns=_strlist("skip_columns", gov.get("skip_columns"), []),
147
+ skip_suffixes=_strlist("skip_suffixes", gov.get("skip_suffixes"), cls().skip_suffixes),
148
+ max_llm_pairs=pairs,
149
+ path=f)
150
+ if cfg.language not in ("zh", "en"):
151
+ raise ValueError(f"language 须为 zh|en,实得 {cfg.language!r}")
152
+ return cfg
153
+
154
+ def metric(self, key: str) -> MetricDef | None:
155
+ return next((m for m in self.metrics if m.key == key), None)