semlayer 0.3.0b1__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 (74) hide show
  1. semlayer-0.3.0b1/LICENSE +201 -0
  2. semlayer-0.3.0b1/PKG-INFO +80 -0
  3. semlayer-0.3.0b1/README.md +56 -0
  4. semlayer-0.3.0b1/pyproject.toml +94 -0
  5. semlayer-0.3.0b1/setup.cfg +4 -0
  6. semlayer-0.3.0b1/src/semlayer/__init__.py +5 -0
  7. semlayer-0.3.0b1/src/semlayer/benchmark.py +115 -0
  8. semlayer-0.3.0b1/src/semlayer/cli.py +246 -0
  9. semlayer-0.3.0b1/src/semlayer/compile.py +352 -0
  10. semlayer-0.3.0b1/src/semlayer/connectors/__init__.py +1 -0
  11. semlayer-0.3.0b1/src/semlayer/connectors/bigquery.py +66 -0
  12. semlayer-0.3.0b1/src/semlayer/connectors/snowflake.py +82 -0
  13. semlayer-0.3.0b1/src/semlayer/context.py +400 -0
  14. semlayer-0.3.0b1/src/semlayer/cq/__init__.py +1 -0
  15. semlayer-0.3.0b1/src/semlayer/cq/answer.py +226 -0
  16. semlayer-0.3.0b1/src/semlayer/cq/generate.py +83 -0
  17. semlayer-0.3.0b1/src/semlayer/describe/__init__.py +2 -0
  18. semlayer-0.3.0b1/src/semlayer/describe/run.py +157 -0
  19. semlayer-0.3.0b1/src/semlayer/drift.py +309 -0
  20. semlayer-0.3.0b1/src/semlayer/enrich/__init__.py +2 -0
  21. semlayer-0.3.0b1/src/semlayer/enrich/run.py +671 -0
  22. semlayer-0.3.0b1/src/semlayer/errors.py +33 -0
  23. semlayer-0.3.0b1/src/semlayer/export/__init__.py +1 -0
  24. semlayer-0.3.0b1/src/semlayer/export/dbt.py +130 -0
  25. semlayer-0.3.0b1/src/semlayer/init_cmd.py +60 -0
  26. semlayer-0.3.0b1/src/semlayer/link/__init__.py +2 -0
  27. semlayer-0.3.0b1/src/semlayer/link/candidates.py +214 -0
  28. semlayer-0.3.0b1/src/semlayer/link/run.py +255 -0
  29. semlayer-0.3.0b1/src/semlayer/link/table_type.py +71 -0
  30. semlayer-0.3.0b1/src/semlayer/link/validate_llm.py +62 -0
  31. semlayer-0.3.0b1/src/semlayer/llm/__init__.py +1 -0
  32. semlayer-0.3.0b1/src/semlayer/llm/provider.py +161 -0
  33. semlayer-0.3.0b1/src/semlayer/mcp_server.py +198 -0
  34. semlayer-0.3.0b1/src/semlayer/ontology/__init__.py +2 -0
  35. semlayer-0.3.0b1/src/semlayer/ontology/base.py +105 -0
  36. semlayer-0.3.0b1/src/semlayer/pipeline.py +85 -0
  37. semlayer-0.3.0b1/src/semlayer/profile/__init__.py +2 -0
  38. semlayer-0.3.0b1/src/semlayer/profile/llm_typing.py +110 -0
  39. semlayer-0.3.0b1/src/semlayer/profile/run.py +192 -0
  40. semlayer-0.3.0b1/src/semlayer/profile/stats.py +155 -0
  41. semlayer-0.3.0b1/src/semlayer/profile/typing_rules.py +239 -0
  42. semlayer-0.3.0b1/src/semlayer/review.py +133 -0
  43. semlayer-0.3.0b1/src/semlayer/scoring.py +108 -0
  44. semlayer-0.3.0b1/src/semlayer/source.py +110 -0
  45. semlayer-0.3.0b1/src/semlayer/spec/cq-suite.schema.json +58 -0
  46. semlayer-0.3.0b1/src/semlayer/spec/semantic-layer.schema.json +550 -0
  47. semlayer-0.3.0b1/src/semlayer/telemetry.py +49 -0
  48. semlayer-0.3.0b1/src/semlayer/validate.py +275 -0
  49. semlayer-0.3.0b1/src/semlayer.egg-info/PKG-INFO +80 -0
  50. semlayer-0.3.0b1/src/semlayer.egg-info/SOURCES.txt +72 -0
  51. semlayer-0.3.0b1/src/semlayer.egg-info/dependency_links.txt +1 -0
  52. semlayer-0.3.0b1/src/semlayer.egg-info/entry_points.txt +2 -0
  53. semlayer-0.3.0b1/src/semlayer.egg-info/requires.txt +16 -0
  54. semlayer-0.3.0b1/src/semlayer.egg-info/top_level.txt +1 -0
  55. semlayer-0.3.0b1/tests/test_adversarial_small.py +225 -0
  56. semlayer-0.3.0b1/tests/test_adversarial_structural.py +340 -0
  57. semlayer-0.3.0b1/tests/test_bigquery_live.py +72 -0
  58. semlayer-0.3.0b1/tests/test_cli_extras.py +48 -0
  59. semlayer-0.3.0b1/tests/test_compile.py +257 -0
  60. semlayer-0.3.0b1/tests/test_context.py +248 -0
  61. semlayer-0.3.0b1/tests/test_cq_harness.py +118 -0
  62. semlayer-0.3.0b1/tests/test_cqs.py +97 -0
  63. semlayer-0.3.0b1/tests/test_describe.py +116 -0
  64. semlayer-0.3.0b1/tests/test_drift.py +139 -0
  65. semlayer-0.3.0b1/tests/test_enrich.py +135 -0
  66. semlayer-0.3.0b1/tests/test_fan_trap.py +91 -0
  67. semlayer-0.3.0b1/tests/test_fiscal.py +135 -0
  68. semlayer-0.3.0b1/tests/test_link.py +91 -0
  69. semlayer-0.3.0b1/tests/test_messy_mart.py +176 -0
  70. semlayer-0.3.0b1/tests/test_profile.py +120 -0
  71. semlayer-0.3.0b1/tests/test_review_mcp.py +162 -0
  72. semlayer-0.3.0b1/tests/test_snowflake_live.py +83 -0
  73. semlayer-0.3.0b1/tests/test_spec.py +123 -0
  74. semlayer-0.3.0b1/tests/test_tpcds_gold.py +142 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: semlayer
3
+ Version: 0.3.0b1
4
+ Summary: Open semantic layer format and inference engine for data warehouses
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: pyyaml>=6.0
10
+ Requires-Dist: jsonschema>=4.20
11
+ Requires-Dist: duckdb>=1.5
12
+ Requires-Dist: anthropic>=0.40
13
+ Requires-Dist: mcp>=1.0
14
+ Provides-Extra: warehouses
15
+ Requires-Dist: snowflake-connector-python>=3.12; extra == "warehouses"
16
+ Requires-Dist: google-cloud-bigquery>=3.25; extra == "warehouses"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8.0; extra == "dev"
19
+ Requires-Dist: python-dotenv>=1.0; extra == "dev"
20
+ Requires-Dist: ruff>=0.15; extra == "dev"
21
+ Requires-Dist: mypy>=2.0; extra == "dev"
22
+ Requires-Dist: pip-audit>=2.10; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # semlayer
26
+
27
+ **The open-source semantic layer that infers itself — skip the quarter of hand-writing dbt YAML.**
28
+
29
+ Point it at your warehouse. It profiles every column, discovers the foreign keys nobody declared, decodes the status columns, finds the business rules hiding in your aggregate tables, and writes the whole thing down as an open, portable semantic layer — with **confidence, provenance, and lifecycle on every single claim** — ready for any AI agent to consume over MCP.
30
+
31
+ ```bash
32
+ pip install -e ".[warehouses]"
33
+ semlayer init snowflake # generates the minimal-grant setup script
34
+ semlayer infer snowflake -o layer.yaml \
35
+ --context ./docs/ --context ./etl-repo/CLAUDE.md # optional: your wikis/dictionaries as priors
36
+ semlayer review layer.yaml # accept/reject what the engine inferred
37
+ semlayer mcp layer.yaml # serve it to Claude, Cursor, or any MCP client
38
+ semlayer drift layer.yaml snowflake # catch schema changes (cron- and CI-friendly)
39
+ ```
40
+
41
+ ## Why
42
+
43
+ AI agents fail on real warehouses: frontier models solved just **21.3%** of Spider 2.0's enterprise-warehouse tasks at publication (vs ~91% on the earlier academic Spider 1.0) — and even today's best agentic scaffolds only reach ~30%. The fix is a semantic layer — but every existing tool (dbt, LookML, Cube, Snowflake semantic views) makes humans write it by hand, and it goes stale the day someone runs an `ALTER TABLE`.
44
+
45
+ On our messy-warehouse benchmark (cryptic names, zero declared constraints, hidden business rules), an agent using the inferred layer answers **53% of business questions correctly vs 34% from the raw schema (+54% relative)** — and the errors it fixes are the *silent* kind: raw-schema "total revenue" happily sums cancelled orders. [Full benchmark, including where we DON'T help →](docs/benchmark.md)
46
+
47
+ ## What gets inferred
48
+
49
+ | | Examples from the test suite |
50
+ |---|---|
51
+ | **Semantic types + roles** | `sts_cd` → status code; `tot_amt` → monetary measure with sum/avg aggregations; PII flagged recall-first |
52
+ | **Keys & joins** | 104/104 undeclared FKs on TPC-DS-style naming, F1 = 1.0 on our messy fixture — with **zero** of the seeded false-FK traps accepted (statistics alone never auto-include; naming + LLM must corroborate) |
53
+ | **Enum decodes** | `C=Completed, X=Cancelled` — joined from the decode dimension the engine itself discovered |
54
+ | **Business rules** | "these aggregate tables reconcile only when `sts_cd <> 'X'`" — found by hypothesis-testing, scoped to revenue metrics, never to counts |
55
+ | **Metrics, routing, deprecation** | revenue/count metrics with contract-legal filters; "use `ord_hdr`, avoid `ord_hdr_legacy` (superseded)" |
56
+ | **Descriptions** | every table + column, LLM-written from evidence via join-graph context propagation, judged 0.82–0.89 correct+useful by an independent model |
57
+ | **Your docs as priors** | `--context` ingests data dictionaries, wiki exports, CLAUDE.md files — and *tells you where they're wrong*: doc-vs-data contradictions go to review, never silent override ([guide](docs/context-priors.md)) |
58
+
59
+ Everything lands with `confidence`, `provenance` (which signals produced it), and `lifecycle` (`inferred → reviewed → certified`, plus `deprecated`/`orphaned`), governed by a [normative consumer contract](spec/SPEC.md) that makes silent misuse — summing across a fan-out, joining SCD2 at current-row, filtering on guessed decodes — *non-conforming*, not merely unwise.
60
+
61
+ ## Cost & privacy
62
+
63
+ - **~$0.70 per 100 tables** end-to-end on the cheap model tier, with your own API key ([measured cost model](docs/cost-model.md)). LLM calls are escalation-only; ~80% of columns resolve from statistics alone.
64
+ - **`--no-llm`**: fully deterministic mode, zero API calls, still useful (0.81 typing accuracy on the messy fixture) — for orgs where LLM access needs procurement.
65
+ - **`--no-sample-egress`**: cell values never leave for the LLM; measured cost ≈ 1 point of accuracy.
66
+ - **Read-only, minimal-grant**: `semlayer init` generates the grant script; the nightly test suite proves the reader persona cannot write.
67
+ - **Telemetry**: anonymous command counts spooled *locally only* — nothing leaves your machine in this release; opt out with `SEMLAYER_TELEMETRY=off`. ([details](SECURITY.md))
68
+
69
+ ## Honest scope (v0.1 beta)
70
+
71
+ - **Best on messy warehouses.** On clean, well-named schemas our benchmark shows raw DDL is already sufficient — we publish that negative result rather than hide it. If your warehouse is tidy TPC-DS, you may not need us.
72
+ - Warehouses: **Snowflake, BigQuery, DuckDB** (+ Iceberg on S3 via the [DuckDB bridge](docs/iceberg-bridge.md)). Exporter: **dbt** (losses reported, never silent). LLM: Anthropic API (Bedrock/Vertex routing is next).
73
+ - Not included: hosted service, ontology enrichment (it failed our own ablation gate — [receipts](docs/ablation-m5.md)), LookML/RDF exporters.
74
+ - The eval harness ships in this repo — fixtures, gold layers, competency questions, benchmark runner. **Run our numbers yourself**: `python fixtures/build.py && pytest tests/ -q`.
75
+
76
+ ## Layout
77
+
78
+ [`spec/`](spec/) format schema + consumer contract · [`src/semlayer/`](src/semlayer/) the engine · [`fixtures/`](fixtures/) 9 eval warehouses + golds + CQ suites · [`docs/`](docs/) benchmark, cost model, spike reports · [`ARCHITECTURE.md`](ARCHITECTURE.md) how it works
79
+
80
+ License: Apache-2.0.
@@ -0,0 +1,56 @@
1
+ # semlayer
2
+
3
+ **The open-source semantic layer that infers itself — skip the quarter of hand-writing dbt YAML.**
4
+
5
+ Point it at your warehouse. It profiles every column, discovers the foreign keys nobody declared, decodes the status columns, finds the business rules hiding in your aggregate tables, and writes the whole thing down as an open, portable semantic layer — with **confidence, provenance, and lifecycle on every single claim** — ready for any AI agent to consume over MCP.
6
+
7
+ ```bash
8
+ pip install -e ".[warehouses]"
9
+ semlayer init snowflake # generates the minimal-grant setup script
10
+ semlayer infer snowflake -o layer.yaml \
11
+ --context ./docs/ --context ./etl-repo/CLAUDE.md # optional: your wikis/dictionaries as priors
12
+ semlayer review layer.yaml # accept/reject what the engine inferred
13
+ semlayer mcp layer.yaml # serve it to Claude, Cursor, or any MCP client
14
+ semlayer drift layer.yaml snowflake # catch schema changes (cron- and CI-friendly)
15
+ ```
16
+
17
+ ## Why
18
+
19
+ AI agents fail on real warehouses: frontier models solved just **21.3%** of Spider 2.0's enterprise-warehouse tasks at publication (vs ~91% on the earlier academic Spider 1.0) — and even today's best agentic scaffolds only reach ~30%. The fix is a semantic layer — but every existing tool (dbt, LookML, Cube, Snowflake semantic views) makes humans write it by hand, and it goes stale the day someone runs an `ALTER TABLE`.
20
+
21
+ On our messy-warehouse benchmark (cryptic names, zero declared constraints, hidden business rules), an agent using the inferred layer answers **53% of business questions correctly vs 34% from the raw schema (+54% relative)** — and the errors it fixes are the *silent* kind: raw-schema "total revenue" happily sums cancelled orders. [Full benchmark, including where we DON'T help →](docs/benchmark.md)
22
+
23
+ ## What gets inferred
24
+
25
+ | | Examples from the test suite |
26
+ |---|---|
27
+ | **Semantic types + roles** | `sts_cd` → status code; `tot_amt` → monetary measure with sum/avg aggregations; PII flagged recall-first |
28
+ | **Keys & joins** | 104/104 undeclared FKs on TPC-DS-style naming, F1 = 1.0 on our messy fixture — with **zero** of the seeded false-FK traps accepted (statistics alone never auto-include; naming + LLM must corroborate) |
29
+ | **Enum decodes** | `C=Completed, X=Cancelled` — joined from the decode dimension the engine itself discovered |
30
+ | **Business rules** | "these aggregate tables reconcile only when `sts_cd <> 'X'`" — found by hypothesis-testing, scoped to revenue metrics, never to counts |
31
+ | **Metrics, routing, deprecation** | revenue/count metrics with contract-legal filters; "use `ord_hdr`, avoid `ord_hdr_legacy` (superseded)" |
32
+ | **Descriptions** | every table + column, LLM-written from evidence via join-graph context propagation, judged 0.82–0.89 correct+useful by an independent model |
33
+ | **Your docs as priors** | `--context` ingests data dictionaries, wiki exports, CLAUDE.md files — and *tells you where they're wrong*: doc-vs-data contradictions go to review, never silent override ([guide](docs/context-priors.md)) |
34
+
35
+ Everything lands with `confidence`, `provenance` (which signals produced it), and `lifecycle` (`inferred → reviewed → certified`, plus `deprecated`/`orphaned`), governed by a [normative consumer contract](spec/SPEC.md) that makes silent misuse — summing across a fan-out, joining SCD2 at current-row, filtering on guessed decodes — *non-conforming*, not merely unwise.
36
+
37
+ ## Cost & privacy
38
+
39
+ - **~$0.70 per 100 tables** end-to-end on the cheap model tier, with your own API key ([measured cost model](docs/cost-model.md)). LLM calls are escalation-only; ~80% of columns resolve from statistics alone.
40
+ - **`--no-llm`**: fully deterministic mode, zero API calls, still useful (0.81 typing accuracy on the messy fixture) — for orgs where LLM access needs procurement.
41
+ - **`--no-sample-egress`**: cell values never leave for the LLM; measured cost ≈ 1 point of accuracy.
42
+ - **Read-only, minimal-grant**: `semlayer init` generates the grant script; the nightly test suite proves the reader persona cannot write.
43
+ - **Telemetry**: anonymous command counts spooled *locally only* — nothing leaves your machine in this release; opt out with `SEMLAYER_TELEMETRY=off`. ([details](SECURITY.md))
44
+
45
+ ## Honest scope (v0.1 beta)
46
+
47
+ - **Best on messy warehouses.** On clean, well-named schemas our benchmark shows raw DDL is already sufficient — we publish that negative result rather than hide it. If your warehouse is tidy TPC-DS, you may not need us.
48
+ - Warehouses: **Snowflake, BigQuery, DuckDB** (+ Iceberg on S3 via the [DuckDB bridge](docs/iceberg-bridge.md)). Exporter: **dbt** (losses reported, never silent). LLM: Anthropic API (Bedrock/Vertex routing is next).
49
+ - Not included: hosted service, ontology enrichment (it failed our own ablation gate — [receipts](docs/ablation-m5.md)), LookML/RDF exporters.
50
+ - The eval harness ships in this repo — fixtures, gold layers, competency questions, benchmark runner. **Run our numbers yourself**: `python fixtures/build.py && pytest tests/ -q`.
51
+
52
+ ## Layout
53
+
54
+ [`spec/`](spec/) format schema + consumer contract · [`src/semlayer/`](src/semlayer/) the engine · [`fixtures/`](fixtures/) 9 eval warehouses + golds + CQ suites · [`docs/`](docs/) benchmark, cost model, spike reports · [`ARCHITECTURE.md`](ARCHITECTURE.md) how it works
55
+
56
+ License: Apache-2.0.
@@ -0,0 +1,94 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "semlayer"
7
+ version = "0.3.0b1"
8
+ description = "Open semantic layer format and inference engine for data warehouses"
9
+ readme = "README.md"
10
+ license = {text = "Apache-2.0"}
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "pyyaml>=6.0",
14
+ "jsonschema>=4.20",
15
+ "duckdb>=1.5",
16
+ "anthropic>=0.40",
17
+ "mcp>=1.0",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ warehouses = [
22
+ "snowflake-connector-python>=3.12",
23
+ "google-cloud-bigquery>=3.25",
24
+ ]
25
+ dev = [
26
+ "pytest>=8.0",
27
+ "python-dotenv>=1.0",
28
+ "ruff>=0.15",
29
+ "mypy>=2.0",
30
+ "pip-audit>=2.10",
31
+ ]
32
+
33
+ [project.scripts]
34
+ semlayer = "semlayer.cli:main"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.setuptools.package-data]
40
+ semlayer = ["spec/*.json"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+
45
+ [tool.ruff]
46
+ line-length = 100
47
+ target-version = "py310"
48
+ src = ["src"]
49
+
50
+ [tool.ruff.lint]
51
+ select = [
52
+ "E", "F", "W", # pycodestyle/pyflakes
53
+ "I", # isort
54
+ "UP", # pyupgrade
55
+ "B", # bugbear
56
+ "C90", # mccabe complexity
57
+ "PLR", # pylint refactor (complexity/args/statements)
58
+ "RUF", # ruff-native
59
+ "D", # pydocstyle (public API why-docs)
60
+ "T20", # no stray print in library code
61
+ ]
62
+ ignore = [
63
+ "D203", "D213", # docstring style conflicts (google convention)
64
+ "D107", "D105", # init/magic docstrings
65
+ "PLR2004", # magic-value comparisons (thresholds are documented constants)
66
+ ]
67
+
68
+ [tool.ruff.lint.mccabe]
69
+ max-complexity = 10
70
+
71
+ [tool.ruff.lint.pylint]
72
+ max-statements = 60
73
+ max-args = 7
74
+ max-branches = 14
75
+
76
+ [tool.ruff.lint.per-file-ignores]
77
+ "tests/*" = ["D", "PLR", "T20", "E501"]
78
+ "fixtures/*" = ["D", "PLR", "T20", "E501", "C901"]
79
+ "src/semlayer/cli.py" = ["T20"] # the CLI prints by design
80
+ "src/semlayer/benchmark.py" = ["T20"]
81
+ # E501 inside a FROZEN prompt string (cassette-key bytes); cannot rewrap
82
+ "src/semlayer/describe/run.py" = ["E501"]
83
+
84
+ [tool.ruff.lint.pydocstyle]
85
+ convention = "google"
86
+
87
+ [tool.mypy]
88
+ python_version = "3.10"
89
+ files = ["src"]
90
+ ignore_missing_imports = true
91
+ warn_unused_ignores = true
92
+ warn_redundant_casts = true
93
+ no_implicit_optional = true
94
+ check_untyped_defs = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """semlayer: open semantic layer format and inference engine."""
2
+
3
+ __version__ = "0.1.0.dev0"
4
+
5
+ from semlayer.validate import ValidationResult, validate_document, validate_file # noqa: F401
@@ -0,0 +1,115 @@
1
+ """Reproducible benchmark runner (M6): the ablation, hardened for publication.
2
+
3
+ Reproducibility contract (adversarial B5): results are exact under pinned
4
+ engine + prompt versions + models via committed cassettes; cross-model
5
+ variance is REPORTED, never hidden. `run_benchmark` returns structured
6
+ results; report generation renders docs/benchmark.md.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections import defaultdict
12
+
13
+ CONDITIONS = ["schema_only", "semantic", "semantic+ontology"]
14
+
15
+
16
+ def run_fixture(fixture: str, answer_model: str | None = None,
17
+ conditions: list[str] | None = None) -> dict:
18
+ """Run one fixture's CQ suite under each ablation condition and score results."""
19
+ import importlib
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ import duckdb
24
+ import yaml
25
+
26
+ oss = Path(__file__).resolve().parent.parent.parent
27
+ sys.path.insert(0, str(oss / "fixtures"))
28
+
29
+ from semlayer.cq.answer import (
30
+ answer_with_repair,
31
+ ontology_context,
32
+ schema_only_context,
33
+ score_answer,
34
+ semantic_context,
35
+ )
36
+ from semlayer.llm.provider import AnthropicProvider
37
+ from semlayer.ontology import build_base_graph
38
+ from semlayer.pipeline import infer
39
+ from semlayer.source import DuckDBSource
40
+
41
+ mod = importlib.import_module(f"generators.{fixture}")
42
+ con = duckdb.connect(":memory:")
43
+ mod.build(con)
44
+ doc = infer(DuckDBSource(con), llm=AnthropicProvider())
45
+ graph = build_base_graph(doc)
46
+ cq_path = oss / "fixtures" / "cqs" / f"{fixture}.yaml"
47
+ suite = yaml.safe_load(cq_path.read_text())["cq_suite"]["questions"]
48
+
49
+ out: dict = {"fixture": fixture, "n_cqs": len(suite), "conditions": {}}
50
+ for cond in conditions or CONDITIONS:
51
+ llm = AnthropicProvider(model=answer_model) if answer_model else AnthropicProvider()
52
+ passed = 0
53
+ fails: list[dict] = []
54
+ by_cat: dict[str, list[int]] = defaultdict(lambda: [0, 0])
55
+ for cq in suite:
56
+ q = cq["question"]
57
+ ctx = (schema_only_context(doc) if cond == "schema_only"
58
+ else semantic_context(doc, q) if cond == "semantic"
59
+ else ontology_context(doc, graph, q))
60
+ ok, detail = score_answer(con, cq, answer_with_repair(llm, con, ctx, q))
61
+ is_meta_kind = cq["expected_kind"] in ("refusal", "clarification")
62
+ cat = cq.get("trap") or (cq["expected_kind"] if is_meta_kind else cq["complexity"])
63
+ by_cat[cat][0] += ok
64
+ by_cat[cat][1] += 1
65
+ passed += ok
66
+ if not ok:
67
+ fails.append({"id": cq["id"], "category": cat, "detail": detail[:60]})
68
+ out["conditions"][cond] = {
69
+ "pass_rate": round(passed / len(suite), 3),
70
+ "passed": passed,
71
+ "by_category": {k: {"passed": v[0], "total": v[1]} for k, v in sorted(by_cat.items())},
72
+ "fails": fails,
73
+ "spend": llm.spend_summary,
74
+ "model": llm.model,
75
+ }
76
+ con.close()
77
+ return out
78
+
79
+
80
+ def render_report(results: list[dict], engine_version: str, notes: list[str]) -> str:
81
+ """Render the ablation results table + failure breakdown as a markdown report."""
82
+ lines = [
83
+ "# Benchmark: text-to-SQL accuracy — raw schema vs. inferred semantic layer",
84
+ "",
85
+ f"Engine {engine_version}; answers execution-scored against gold CQ suites",
86
+ "(fixed questions, human-verified expected SQL, executed live). Reproducible",
87
+ "under pinned engine+model via committed cassettes; re-run with:",
88
+ "`python -m semlayer.benchmark`.",
89
+ "",
90
+ "| Fixture | CQs | Answerer | schema_only | semantic | semantic+ontology |",
91
+ "|---|---|---|---|---|---|",
92
+ ]
93
+ for r in results:
94
+ conds = r["conditions"]
95
+ model = next(iter(conds.values()))["model"].split("-2")[0]
96
+ row = [r["fixture"], str(r["n_cqs"]), model]
97
+ for c in CONDITIONS:
98
+ row.append(f"{conds[c]['pass_rate']:.2f}" if c in conds else "—")
99
+ lines.append("| " + " | ".join(row) + " |")
100
+ lines.append("")
101
+ lines.append("## Failure breakdown by category (semantic condition)")
102
+ lines.append("")
103
+ lines.append("| Fixture | Category | Passed/Total |")
104
+ lines.append("|---|---|---|")
105
+ for r in results:
106
+ sem = r["conditions"].get("semantic")
107
+ if not sem:
108
+ continue
109
+ for cat, v in sem["by_category"].items():
110
+ lines.append(f"| {r['fixture']} | {cat} | {v['passed']}/{v['total']} |")
111
+ lines.append("")
112
+ lines.append("## Notes")
113
+ for n in notes:
114
+ lines.append(f"- {n}")
115
+ return "\n".join(lines) + "\n"