metric-contracts 0.1.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.
- metric_contracts-0.1.0/.gitignore +13 -0
- metric_contracts-0.1.0/CHANGELOG.md +13 -0
- metric_contracts-0.1.0/LICENSE +202 -0
- metric_contracts-0.1.0/PKG-INFO +207 -0
- metric_contracts-0.1.0/README.md +162 -0
- metric_contracts-0.1.0/examples/saas/seed_duckdb.py +70 -0
- metric_contracts-0.1.0/examples/saas/subscriptions.contract.yaml +144 -0
- metric_contracts-0.1.0/pyproject.toml +70 -0
- metric_contracts-0.1.0/schema/metric-contract-payload.schema.json +337 -0
- metric_contracts-0.1.0/schema/metric-contract.schema.json +572 -0
- metric_contracts-0.1.0/src/metric_contracts/__init__.py +46 -0
- metric_contracts-0.1.0/src/metric_contracts/chart.py +176 -0
- metric_contracts-0.1.0/src/metric_contracts/cli.py +252 -0
- metric_contracts-0.1.0/src/metric_contracts/decompose.py +123 -0
- metric_contracts-0.1.0/src/metric_contracts/importers/__init__.py +4 -0
- metric_contracts-0.1.0/src/metric_contracts/importers/dbt.py +117 -0
- metric_contracts-0.1.0/src/metric_contracts/importers/ossie.py +128 -0
- metric_contracts-0.1.0/src/metric_contracts/load.py +126 -0
- metric_contracts-0.1.0/src/metric_contracts/mcp_server.py +135 -0
- metric_contracts-0.1.0/src/metric_contracts/model.py +301 -0
- metric_contracts-0.1.0/src/metric_contracts/plan.py +185 -0
- metric_contracts-0.1.0/src/metric_contracts/py.typed +0 -0
- metric_contracts-0.1.0/src/metric_contracts/rules.py +42 -0
- metric_contracts-0.1.0/src/metric_contracts/schema.py +53 -0
- metric_contracts-0.1.0/src/metric_contracts/validate.py +193 -0
- metric_contracts-0.1.0/tests/__init__.py +0 -0
- metric_contracts-0.1.0/tests/conftest.py +41 -0
- metric_contracts-0.1.0/tests/test_chart.py +78 -0
- metric_contracts-0.1.0/tests/test_cli_and_mcp.py +56 -0
- metric_contracts-0.1.0/tests/test_decompose.py +59 -0
- metric_contracts-0.1.0/tests/test_interop.py +101 -0
- metric_contracts-0.1.0/tests/test_plan.py +68 -0
- metric_contracts-0.1.0/tests/test_validate.py +139 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 - 2026-11-08
|
|
4
|
+
|
|
5
|
+
- Contract schema (standalone file + Apache Ossie `custom_extensions` payload), JSON Schema 2020-12 committed under `schema/`.
|
|
6
|
+
- `validate`: rules V00-V15.
|
|
7
|
+
- `plan`: allowed/denied with reason, aggregation plan, DuckDB reference SQL (P01-P06).
|
|
8
|
+
- `chart-check`: chart meaning gate (C01-C14).
|
|
9
|
+
- `decompose-check`: driver breakdown must sum to the change (D01-D06).
|
|
10
|
+
- `import dbt`, `import ossie`, `export ossie`.
|
|
11
|
+
- MCP server: `list_metrics`, `get_contract`, `plan_query`, `check_chart`, `check_decomposition`, `list_dimensions`, `validate_contracts`.
|
|
12
|
+
- Example contracts for a fictional subscription SaaS, synthetic DuckDB data, offline before/after demo.
|
|
13
|
+
- GitHub Action `val-ye/metric-contracts@v0`.
|
|
@@ -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,207 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: metric-contracts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: One governed metric contract, many consumers: validator CLI, MCP server, chart meaning gate, decomposition check.
|
|
5
|
+
Project-URL: Homepage, https://github.com/val-ye/metric-contracts
|
|
6
|
+
Project-URL: Issues, https://github.com/val-ye/metric-contracts/issues
|
|
7
|
+
Project-URL: Schema, https://github.com/val-ye/metric-contracts/blob/main/schema/metric-contract.schema.json
|
|
8
|
+
Author: Val Ye
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: additivity,analytics-engineering,data-contracts,mcp,metrics,semantic-layer
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Database
|
|
19
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: jsonschema>=4.23
|
|
23
|
+
Requires-Dist: pydantic>=2.7
|
|
24
|
+
Requires-Dist: pyyaml>=6.0
|
|
25
|
+
Provides-Extra: all
|
|
26
|
+
Requires-Dist: anthropic>=0.40; extra == 'all'
|
|
27
|
+
Requires-Dist: duckdb>=1.3; extra == 'all'
|
|
28
|
+
Requires-Dist: mcp>=2.3; extra == 'all'
|
|
29
|
+
Provides-Extra: demo
|
|
30
|
+
Requires-Dist: duckdb>=1.3; extra == 'demo'
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: anthropic>=0.40; extra == 'dev'
|
|
33
|
+
Requires-Dist: duckdb>=1.3; extra == 'dev'
|
|
34
|
+
Requires-Dist: mcp>=2.3; extra == 'dev'
|
|
35
|
+
Requires-Dist: mypy>=1.11; extra == 'dev'
|
|
36
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
37
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
38
|
+
Requires-Dist: types-jsonschema; extra == 'dev'
|
|
39
|
+
Requires-Dist: types-pyyaml; extra == 'dev'
|
|
40
|
+
Provides-Extra: live
|
|
41
|
+
Requires-Dist: anthropic>=0.40; extra == 'live'
|
|
42
|
+
Provides-Extra: mcp
|
|
43
|
+
Requires-Dist: mcp>=2.3; extra == 'mcp'
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
|
|
46
|
+
# metric-contracts
|
|
47
|
+
|
|
48
|
+
<!-- mcp-name: io.github.val-ye/metric-contracts -->
|
|
49
|
+
|
|
50
|
+
One governed metric contract, many consumers.
|
|
51
|
+
|
|
52
|
+
A metric contract declares what a semantic layer usually leaves implicit: formula, components,
|
|
53
|
+
source, refresh cadence, as-of semantics, allowed dimensions, **additivity** (additive,
|
|
54
|
+
semi-additive with the non-additive dimension named, or non-additive), caveats, owner.
|
|
55
|
+
Four consumers enforce it:
|
|
56
|
+
|
|
57
|
+
1. **Validator CLI for CI.** A semi-additive metric must name its non-additive dimension or the
|
|
58
|
+
build fails. Allowed-dimension sets must be subsets of the declared registry. Ratios must
|
|
59
|
+
carry components. Every metric needs an owner, a refresh cadence and as-of semantics.
|
|
60
|
+
2. **MCP server.** `list_metrics`, `get_contract`, `plan_query(metric, grain, dimensions)` returns
|
|
61
|
+
allowed or denied with the reason, so an agent reads the contract before it writes SQL.
|
|
62
|
+
3. **Chart meaning gate.** Given a proposed chart, return veto or allow with the rule that fired:
|
|
63
|
+
ratios are not stacked, pie'd or summed; semi-additive at a coarse grain takes LAST; pie
|
|
64
|
+
category cap; funnels only for ordered stages; no duplicate axis values. The model proposes,
|
|
65
|
+
the rules veto.
|
|
66
|
+
4. **Decomposition check.** A driver/drag breakdown must sum back to the total change, partition
|
|
67
|
+
one dimension, and state its method for ratios. Otherwise the "insight" is rejected.
|
|
68
|
+
|
|
69
|
+
Vocabulary follows [Apache Ossie discussion #465](https://github.com/apache/ossie/discussions/465)
|
|
70
|
+
(`additivity`, `non_additive_dimensions[{field, window}]`), and the contract ships both as a
|
|
71
|
+
standalone YAML file and as an Ossie `custom_extensions` payload. Design notes and the survey of
|
|
72
|
+
what dbt, Cube, Malloy, LookML, Rill, Snowflake, Databricks and others already support are in
|
|
73
|
+
[docs/design.md](docs/design.md).
|
|
74
|
+
|
|
75
|
+
## Install in two minutes
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pip install "metric-contracts[all]" # CLI + MCP server + DuckDB demo
|
|
79
|
+
git clone https://github.com/val-ye/metric-contracts && cd metric-contracts
|
|
80
|
+
|
|
81
|
+
metric-contracts validate examples/saas # 0 errors
|
|
82
|
+
metric-contracts plan active_subscribers --grain month --dims plan -c examples/saas
|
|
83
|
+
metric-contracts plan active_subscribers --grain month --dims plan --agg sum -c examples/saas # denied, P04
|
|
84
|
+
python demo/before_after.py # the before/after agent demo, offline
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Python 3.11 or newer. The core package depends on pydantic, PyYAML and jsonschema only. The
|
|
88
|
+
`mcp`, `demo` and `live` extras add the MCP SDK, DuckDB and the Anthropic SDK.
|
|
89
|
+
|
|
90
|
+
## A contract
|
|
91
|
+
|
|
92
|
+
```yaml
|
|
93
|
+
contract_version: "0.1"
|
|
94
|
+
domain: subscriptions
|
|
95
|
+
owner: { team: analytics-engineering, contact: analytics-eng@example.com }
|
|
96
|
+
dimensions:
|
|
97
|
+
- { name: date, type: time, grains: [day, week, month] }
|
|
98
|
+
- { name: plan, type: categorical, values: [free, starter, pro, enterprise] }
|
|
99
|
+
metrics:
|
|
100
|
+
- name: active_subscribers
|
|
101
|
+
kind: measure
|
|
102
|
+
formula: count(subscription_id)
|
|
103
|
+
source: { table: fct_subscriber_snapshot_daily, grain: [date, subscription_id], time_dimension: date }
|
|
104
|
+
additivity: semi_additive
|
|
105
|
+
non_additive_dimensions:
|
|
106
|
+
- { field: date, window: last }
|
|
107
|
+
dimensions: { allowed: [date, plan, region], time_grains: [day, week, month] }
|
|
108
|
+
refresh: { cadence: daily, lands_at: "06:00Z", settling_window: P1D }
|
|
109
|
+
as_of: { semantics: snapshot, snapshot_at: end_of_day }
|
|
110
|
+
caveats:
|
|
111
|
+
- A month-end figure is the last daily snapshot, never a sum of days.
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The full example with an additive measure, a semi-additive snapshot, a non-additive ratio and a
|
|
115
|
+
distinct count is in [examples/saas](examples/saas/subscriptions.contract.yaml). The JSON Schema
|
|
116
|
+
is committed under [schema/](schema/) and regenerated from the pydantic models in CI.
|
|
117
|
+
|
|
118
|
+
## Before and after
|
|
119
|
+
|
|
120
|
+
`python demo/before_after.py` seeds a synthetic DuckDB database and asks two scripted agents the
|
|
121
|
+
same question: total active subscribers by month for Q1, split by plan. Measured output of the
|
|
122
|
+
committed seed:
|
|
123
|
+
|
|
124
|
+
- Agent A has only the table name. It writes `COUNT(subscription_id) ... GROUP BY month` over a
|
|
125
|
+
daily snapshot table and reports a total 23.3x the month-end truth.
|
|
126
|
+
- Agent B calls `plan_query` first, receives `{"date": "last", "plan": "sum"}` and a reference
|
|
127
|
+
query, and matches the month-end truth row for row.
|
|
128
|
+
- Agent B then asks to SUM across months and is denied with
|
|
129
|
+
`P04_sum_over_non_additive_dim: active_subscribers is semi-additive over date`.
|
|
130
|
+
|
|
131
|
+
`python demo/before_after.py --live` runs the same two prompts through a real model with
|
|
132
|
+
`plan_query` exposed as a tool (needs `ANTHROPIC_API_KEY` and the `live` extra) and prints the SQL
|
|
133
|
+
each one wrote.
|
|
134
|
+
|
|
135
|
+
## MCP server
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
metric-contracts serve -c examples/saas # stdio
|
|
139
|
+
metric-contracts serve -c examples/saas --http # streamable-http on 127.0.0.1:8765
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Claude Desktop / Claude Code config:
|
|
143
|
+
|
|
144
|
+
```json
|
|
145
|
+
{ "mcpServers": { "metric-contracts": { "command": "metric-contracts", "args": ["serve", "-c", "/path/to/contracts"] } } }
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Tools: `list_metrics`, `get_contract`, `plan_query`, `check_chart`, `check_decomposition`,
|
|
149
|
+
`list_dimensions`, `validate_contracts`. Resources: `contract://schema`,
|
|
150
|
+
`contract://schema/payload`, `contract://{domain}`. The server's instructions tell the agent to
|
|
151
|
+
plan before it queries and to treat a denial as an answer, not an obstacle.
|
|
152
|
+
|
|
153
|
+
## CI
|
|
154
|
+
|
|
155
|
+
```yaml
|
|
156
|
+
- uses: val-ye/metric-contracts@v0
|
|
157
|
+
with:
|
|
158
|
+
paths: contracts/
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Or `pipx run metric-contracts validate contracts/ --format github`. Exit code 1 on any error;
|
|
162
|
+
findings are emitted as GitHub annotations.
|
|
163
|
+
|
|
164
|
+
## Rules
|
|
165
|
+
|
|
166
|
+
Every rule names the contract field it reads, so a veto is explainable and testable.
|
|
167
|
+
|
|
168
|
+
| Family | Ids | What they check |
|
|
169
|
+
|---|---|---|
|
|
170
|
+
| Validate | V00-V15 | schema, semi-additive names its dimension, allowed dims in registry, grains, ratio components, distinct count non-additive, source or components, owner, refresh, as-of, dangling components, ordinal funnel dims, unique names, no TODO markers |
|
|
171
|
+
| Plan | P01-P06 | unknown metric, dimension not allowed, grain not allowed, sum over the non-additive dimension, ratio aggregated directly, distinct count rolled up |
|
|
172
|
+
| Chart | C01-C14 | ratio stacked / pie'd / summed, semi-additive at coarse grain takes the declared window, semi-additive stacked over time, distinct count summed, pie cap, pie needs additive, funnel needs ordinal stages, duplicate axis values, dimension and grain allowed, settling window unmarked, series density |
|
|
173
|
+
| Decompose | D01-D06 | sums to total within tolerance, one partition, partition allowed, ratio needs a method, semi-additive deltas are last-to-last, residual disclosed and bounded |
|
|
174
|
+
|
|
175
|
+
Full tables with the field each rule reads: [docs/design.md](docs/design.md).
|
|
176
|
+
|
|
177
|
+
## Interop
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
metric-contracts import dbt target/semantic_manifest.json --out contracts/ # stubs with TODO markers
|
|
181
|
+
metric-contracts import ossie model.yaml --out contracts/
|
|
182
|
+
metric-contracts export ossie -c contracts/ --out model.ossie.yaml # payload in custom_extensions
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The dbt importer maps `non_additive_dimension.window_choice` `max` to `last` and `min` to
|
|
186
|
+
`first`, `count_distinct` to a non-additive distinct count, ratio metrics to `components`.
|
|
187
|
+
Refresh, as-of, owner and allowed dimensions are never inferred; they come back as `TODO` and
|
|
188
|
+
`validate` fails until a human declares them.
|
|
189
|
+
|
|
190
|
+
## What this is not
|
|
191
|
+
|
|
192
|
+
metric-contracts is not a query engine, not a semantic layer, and not a replacement for dbt,
|
|
193
|
+
Cube, MetricFlow, Malloy or LookML. It does not compute metrics. It holds the declarations those
|
|
194
|
+
tools leave implicit, checks them in CI, and hands them to agents, chart builders and insight
|
|
195
|
+
generators so the rules are enforced where the mistakes happen. The reference SQL `plan` emits
|
|
196
|
+
is a DuckDB illustration of the aggregation plan, not a dialect-aware compiler.
|
|
197
|
+
|
|
198
|
+
## Development
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
uv venv && uv pip install -e ".[dev]"
|
|
202
|
+
pytest
|
|
203
|
+
ruff check src tests demo examples && mypy
|
|
204
|
+
metric-contracts schema --write schema # regenerate after a model change
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Apache-2.0. Everything in `examples/` is synthetic.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# metric-contracts
|
|
2
|
+
|
|
3
|
+
<!-- mcp-name: io.github.val-ye/metric-contracts -->
|
|
4
|
+
|
|
5
|
+
One governed metric contract, many consumers.
|
|
6
|
+
|
|
7
|
+
A metric contract declares what a semantic layer usually leaves implicit: formula, components,
|
|
8
|
+
source, refresh cadence, as-of semantics, allowed dimensions, **additivity** (additive,
|
|
9
|
+
semi-additive with the non-additive dimension named, or non-additive), caveats, owner.
|
|
10
|
+
Four consumers enforce it:
|
|
11
|
+
|
|
12
|
+
1. **Validator CLI for CI.** A semi-additive metric must name its non-additive dimension or the
|
|
13
|
+
build fails. Allowed-dimension sets must be subsets of the declared registry. Ratios must
|
|
14
|
+
carry components. Every metric needs an owner, a refresh cadence and as-of semantics.
|
|
15
|
+
2. **MCP server.** `list_metrics`, `get_contract`, `plan_query(metric, grain, dimensions)` returns
|
|
16
|
+
allowed or denied with the reason, so an agent reads the contract before it writes SQL.
|
|
17
|
+
3. **Chart meaning gate.** Given a proposed chart, return veto or allow with the rule that fired:
|
|
18
|
+
ratios are not stacked, pie'd or summed; semi-additive at a coarse grain takes LAST; pie
|
|
19
|
+
category cap; funnels only for ordered stages; no duplicate axis values. The model proposes,
|
|
20
|
+
the rules veto.
|
|
21
|
+
4. **Decomposition check.** A driver/drag breakdown must sum back to the total change, partition
|
|
22
|
+
one dimension, and state its method for ratios. Otherwise the "insight" is rejected.
|
|
23
|
+
|
|
24
|
+
Vocabulary follows [Apache Ossie discussion #465](https://github.com/apache/ossie/discussions/465)
|
|
25
|
+
(`additivity`, `non_additive_dimensions[{field, window}]`), and the contract ships both as a
|
|
26
|
+
standalone YAML file and as an Ossie `custom_extensions` payload. Design notes and the survey of
|
|
27
|
+
what dbt, Cube, Malloy, LookML, Rill, Snowflake, Databricks and others already support are in
|
|
28
|
+
[docs/design.md](docs/design.md).
|
|
29
|
+
|
|
30
|
+
## Install in two minutes
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install "metric-contracts[all]" # CLI + MCP server + DuckDB demo
|
|
34
|
+
git clone https://github.com/val-ye/metric-contracts && cd metric-contracts
|
|
35
|
+
|
|
36
|
+
metric-contracts validate examples/saas # 0 errors
|
|
37
|
+
metric-contracts plan active_subscribers --grain month --dims plan -c examples/saas
|
|
38
|
+
metric-contracts plan active_subscribers --grain month --dims plan --agg sum -c examples/saas # denied, P04
|
|
39
|
+
python demo/before_after.py # the before/after agent demo, offline
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Python 3.11 or newer. The core package depends on pydantic, PyYAML and jsonschema only. The
|
|
43
|
+
`mcp`, `demo` and `live` extras add the MCP SDK, DuckDB and the Anthropic SDK.
|
|
44
|
+
|
|
45
|
+
## A contract
|
|
46
|
+
|
|
47
|
+
```yaml
|
|
48
|
+
contract_version: "0.1"
|
|
49
|
+
domain: subscriptions
|
|
50
|
+
owner: { team: analytics-engineering, contact: analytics-eng@example.com }
|
|
51
|
+
dimensions:
|
|
52
|
+
- { name: date, type: time, grains: [day, week, month] }
|
|
53
|
+
- { name: plan, type: categorical, values: [free, starter, pro, enterprise] }
|
|
54
|
+
metrics:
|
|
55
|
+
- name: active_subscribers
|
|
56
|
+
kind: measure
|
|
57
|
+
formula: count(subscription_id)
|
|
58
|
+
source: { table: fct_subscriber_snapshot_daily, grain: [date, subscription_id], time_dimension: date }
|
|
59
|
+
additivity: semi_additive
|
|
60
|
+
non_additive_dimensions:
|
|
61
|
+
- { field: date, window: last }
|
|
62
|
+
dimensions: { allowed: [date, plan, region], time_grains: [day, week, month] }
|
|
63
|
+
refresh: { cadence: daily, lands_at: "06:00Z", settling_window: P1D }
|
|
64
|
+
as_of: { semantics: snapshot, snapshot_at: end_of_day }
|
|
65
|
+
caveats:
|
|
66
|
+
- A month-end figure is the last daily snapshot, never a sum of days.
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The full example with an additive measure, a semi-additive snapshot, a non-additive ratio and a
|
|
70
|
+
distinct count is in [examples/saas](examples/saas/subscriptions.contract.yaml). The JSON Schema
|
|
71
|
+
is committed under [schema/](schema/) and regenerated from the pydantic models in CI.
|
|
72
|
+
|
|
73
|
+
## Before and after
|
|
74
|
+
|
|
75
|
+
`python demo/before_after.py` seeds a synthetic DuckDB database and asks two scripted agents the
|
|
76
|
+
same question: total active subscribers by month for Q1, split by plan. Measured output of the
|
|
77
|
+
committed seed:
|
|
78
|
+
|
|
79
|
+
- Agent A has only the table name. It writes `COUNT(subscription_id) ... GROUP BY month` over a
|
|
80
|
+
daily snapshot table and reports a total 23.3x the month-end truth.
|
|
81
|
+
- Agent B calls `plan_query` first, receives `{"date": "last", "plan": "sum"}` and a reference
|
|
82
|
+
query, and matches the month-end truth row for row.
|
|
83
|
+
- Agent B then asks to SUM across months and is denied with
|
|
84
|
+
`P04_sum_over_non_additive_dim: active_subscribers is semi-additive over date`.
|
|
85
|
+
|
|
86
|
+
`python demo/before_after.py --live` runs the same two prompts through a real model with
|
|
87
|
+
`plan_query` exposed as a tool (needs `ANTHROPIC_API_KEY` and the `live` extra) and prints the SQL
|
|
88
|
+
each one wrote.
|
|
89
|
+
|
|
90
|
+
## MCP server
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
metric-contracts serve -c examples/saas # stdio
|
|
94
|
+
metric-contracts serve -c examples/saas --http # streamable-http on 127.0.0.1:8765
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Claude Desktop / Claude Code config:
|
|
98
|
+
|
|
99
|
+
```json
|
|
100
|
+
{ "mcpServers": { "metric-contracts": { "command": "metric-contracts", "args": ["serve", "-c", "/path/to/contracts"] } } }
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Tools: `list_metrics`, `get_contract`, `plan_query`, `check_chart`, `check_decomposition`,
|
|
104
|
+
`list_dimensions`, `validate_contracts`. Resources: `contract://schema`,
|
|
105
|
+
`contract://schema/payload`, `contract://{domain}`. The server's instructions tell the agent to
|
|
106
|
+
plan before it queries and to treat a denial as an answer, not an obstacle.
|
|
107
|
+
|
|
108
|
+
## CI
|
|
109
|
+
|
|
110
|
+
```yaml
|
|
111
|
+
- uses: val-ye/metric-contracts@v0
|
|
112
|
+
with:
|
|
113
|
+
paths: contracts/
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Or `pipx run metric-contracts validate contracts/ --format github`. Exit code 1 on any error;
|
|
117
|
+
findings are emitted as GitHub annotations.
|
|
118
|
+
|
|
119
|
+
## Rules
|
|
120
|
+
|
|
121
|
+
Every rule names the contract field it reads, so a veto is explainable and testable.
|
|
122
|
+
|
|
123
|
+
| Family | Ids | What they check |
|
|
124
|
+
|---|---|---|
|
|
125
|
+
| Validate | V00-V15 | schema, semi-additive names its dimension, allowed dims in registry, grains, ratio components, distinct count non-additive, source or components, owner, refresh, as-of, dangling components, ordinal funnel dims, unique names, no TODO markers |
|
|
126
|
+
| Plan | P01-P06 | unknown metric, dimension not allowed, grain not allowed, sum over the non-additive dimension, ratio aggregated directly, distinct count rolled up |
|
|
127
|
+
| Chart | C01-C14 | ratio stacked / pie'd / summed, semi-additive at coarse grain takes the declared window, semi-additive stacked over time, distinct count summed, pie cap, pie needs additive, funnel needs ordinal stages, duplicate axis values, dimension and grain allowed, settling window unmarked, series density |
|
|
128
|
+
| Decompose | D01-D06 | sums to total within tolerance, one partition, partition allowed, ratio needs a method, semi-additive deltas are last-to-last, residual disclosed and bounded |
|
|
129
|
+
|
|
130
|
+
Full tables with the field each rule reads: [docs/design.md](docs/design.md).
|
|
131
|
+
|
|
132
|
+
## Interop
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
metric-contracts import dbt target/semantic_manifest.json --out contracts/ # stubs with TODO markers
|
|
136
|
+
metric-contracts import ossie model.yaml --out contracts/
|
|
137
|
+
metric-contracts export ossie -c contracts/ --out model.ossie.yaml # payload in custom_extensions
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The dbt importer maps `non_additive_dimension.window_choice` `max` to `last` and `min` to
|
|
141
|
+
`first`, `count_distinct` to a non-additive distinct count, ratio metrics to `components`.
|
|
142
|
+
Refresh, as-of, owner and allowed dimensions are never inferred; they come back as `TODO` and
|
|
143
|
+
`validate` fails until a human declares them.
|
|
144
|
+
|
|
145
|
+
## What this is not
|
|
146
|
+
|
|
147
|
+
metric-contracts is not a query engine, not a semantic layer, and not a replacement for dbt,
|
|
148
|
+
Cube, MetricFlow, Malloy or LookML. It does not compute metrics. It holds the declarations those
|
|
149
|
+
tools leave implicit, checks them in CI, and hands them to agents, chart builders and insight
|
|
150
|
+
generators so the rules are enforced where the mistakes happen. The reference SQL `plan` emits
|
|
151
|
+
is a DuckDB illustration of the aggregation plan, not a dialect-aware compiler.
|
|
152
|
+
|
|
153
|
+
## Development
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
uv venv && uv pip install -e ".[dev]"
|
|
157
|
+
pytest
|
|
158
|
+
ruff check src tests demo examples && mypy
|
|
159
|
+
metric-contracts schema --write schema # regenerate after a model change
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Apache-2.0. Everything in `examples/` is synthetic.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Generate the synthetic SaaS tables the example contracts point at.
|
|
2
|
+
|
|
3
|
+
Deterministic (fixed seed). Writes examples/saas/saas.duckdb unless a path is
|
|
4
|
+
given. Nothing here comes from a real company.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import random
|
|
10
|
+
import sys
|
|
11
|
+
from datetime import date, timedelta
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import duckdb
|
|
15
|
+
|
|
16
|
+
PLANS = ["free", "starter", "pro", "enterprise"]
|
|
17
|
+
REGIONS = ["na", "emea", "apac", "latam", "anz", "mea"]
|
|
18
|
+
CHANNELS = [f"ch_{i:02d}" for i in range(1, 13)]
|
|
19
|
+
START = date(2026, 1, 1)
|
|
20
|
+
END = date(2026, 6, 30)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def seed(path: Path, seed_value: int = 7) -> None:
|
|
24
|
+
rng = random.Random(seed_value)
|
|
25
|
+
if path.exists():
|
|
26
|
+
path.unlink()
|
|
27
|
+
con = duckdb.connect(str(path))
|
|
28
|
+
con.execute("CREATE TABLE fct_subscription_events (date DATE, subscription_id INTEGER, event_type VARCHAR, plan VARCHAR, region VARCHAR, channel VARCHAR)")
|
|
29
|
+
con.execute("CREATE TABLE fct_subscriber_snapshot_daily (date DATE, subscription_id INTEGER, plan VARCHAR, region VARCHAR)")
|
|
30
|
+
con.execute("CREATE TABLE fct_trial_events (date DATE, trial_id INTEGER, plan VARCHAR, channel VARCHAR, converted BOOLEAN)")
|
|
31
|
+
con.execute("CREATE TABLE fct_account_activity (date DATE, account_id INTEGER, region VARCHAR)")
|
|
32
|
+
|
|
33
|
+
active: dict[int, tuple[str, str, str]] = {}
|
|
34
|
+
next_id = 1
|
|
35
|
+
events = []
|
|
36
|
+
snapshots = []
|
|
37
|
+
trials = []
|
|
38
|
+
activity = []
|
|
39
|
+
trial_id = 1
|
|
40
|
+
day = START
|
|
41
|
+
while day <= END:
|
|
42
|
+
starts = rng.randint(25, 45) + (10 if day.weekday() < 5 else 0)
|
|
43
|
+
for _ in range(starts):
|
|
44
|
+
sub = (rng.choice(PLANS[1:]), rng.choice(REGIONS), rng.choice(CHANNELS))
|
|
45
|
+
active[next_id] = sub
|
|
46
|
+
events.append((day, next_id, "start", *sub))
|
|
47
|
+
next_id += 1
|
|
48
|
+
for sid in list(active):
|
|
49
|
+
if rng.random() < 0.004:
|
|
50
|
+
events.append((day, sid, "cancel", *active.pop(sid)))
|
|
51
|
+
for sid, (plan, region, _) in active.items():
|
|
52
|
+
snapshots.append((day, sid, plan, region))
|
|
53
|
+
for _ in range(rng.randint(60, 90)):
|
|
54
|
+
trials.append((day, trial_id, rng.choice(PLANS[1:]), rng.choice(CHANNELS), rng.random() < 0.22))
|
|
55
|
+
trial_id += 1
|
|
56
|
+
for aid in rng.sample(range(1, 4000), rng.randint(900, 1300)):
|
|
57
|
+
activity.append((day, aid, REGIONS[aid % len(REGIONS)]))
|
|
58
|
+
day += timedelta(days=1)
|
|
59
|
+
|
|
60
|
+
con.executemany("INSERT INTO fct_subscription_events VALUES (?,?,?,?,?,?)", events)
|
|
61
|
+
con.executemany("INSERT INTO fct_subscriber_snapshot_daily VALUES (?,?,?,?)", snapshots)
|
|
62
|
+
con.executemany("INSERT INTO fct_trial_events VALUES (?,?,?,?,?)", trials)
|
|
63
|
+
con.executemany("INSERT INTO fct_account_activity VALUES (?,?,?)", activity)
|
|
64
|
+
con.close()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
out = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name("saas.duckdb")
|
|
69
|
+
seed(out)
|
|
70
|
+
print(f"wrote {out}")
|