semantic-context-engine 0.3.0a1__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 (71) hide show
  1. semantic_context_engine-0.3.0a1/LICENSE +202 -0
  2. semantic_context_engine-0.3.0a1/MANIFEST.in +2 -0
  3. semantic_context_engine-0.3.0a1/PKG-INFO +263 -0
  4. semantic_context_engine-0.3.0a1/README.md +228 -0
  5. semantic_context_engine-0.3.0a1/examples/demo/run_live_demo.py +267 -0
  6. semantic_context_engine-0.3.0a1/examples/demo/run_vertical.py +429 -0
  7. semantic_context_engine-0.3.0a1/pyproject.toml +72 -0
  8. semantic_context_engine-0.3.0a1/setup.cfg +4 -0
  9. semantic_context_engine-0.3.0a1/src/semantic_context_engine/__init__.py +136 -0
  10. semantic_context_engine-0.3.0a1/src/semantic_context_engine/artifacts.py +98 -0
  11. semantic_context_engine-0.3.0a1/src/semantic_context_engine/cli.py +197 -0
  12. semantic_context_engine-0.3.0a1/src/semantic_context_engine/compiler.py +316 -0
  13. semantic_context_engine-0.3.0a1/src/semantic_context_engine/composition.py +31 -0
  14. semantic_context_engine-0.3.0a1/src/semantic_context_engine/config.py +199 -0
  15. semantic_context_engine-0.3.0a1/src/semantic_context_engine/diff.py +93 -0
  16. semantic_context_engine-0.3.0a1/src/semantic_context_engine/domain_contracts.py +386 -0
  17. semantic_context_engine-0.3.0a1/src/semantic_context_engine/engine.py +250 -0
  18. semantic_context_engine-0.3.0a1/src/semantic_context_engine/enrichment.py +1416 -0
  19. semantic_context_engine-0.3.0a1/src/semantic_context_engine/errors.py +291 -0
  20. semantic_context_engine-0.3.0a1/src/semantic_context_engine/evaluation.py +88 -0
  21. semantic_context_engine-0.3.0a1/src/semantic_context_engine/hierarchies.py +185 -0
  22. semantic_context_engine-0.3.0a1/src/semantic_context_engine/instructions/semantic_catalog.md +2 -0
  23. semantic_context_engine-0.3.0a1/src/semantic_context_engine/integration.py +22 -0
  24. semantic_context_engine-0.3.0a1/src/semantic_context_engine/integrations/__init__.py +11 -0
  25. semantic_context_engine-0.3.0a1/src/semantic_context_engine/integrations/langchain.py +275 -0
  26. semantic_context_engine-0.3.0a1/src/semantic_context_engine/models.py +282 -0
  27. semantic_context_engine-0.3.0a1/src/semantic_context_engine/normalization.py +351 -0
  28. semantic_context_engine-0.3.0a1/src/semantic_context_engine/pipeline.py +1685 -0
  29. semantic_context_engine-0.3.0a1/src/semantic_context_engine/prompts/v1/column_classification.md +15 -0
  30. semantic_context_engine-0.3.0a1/src/semantic_context_engine/prompts/v1/grain_correction.md +4 -0
  31. semantic_context_engine-0.3.0a1/src/semantic_context_engine/prompts/v1/relationship_proposal.md +10 -0
  32. semantic_context_engine-0.3.0a1/src/semantic_context_engine/prompts/v1/synthesis.md +5 -0
  33. semantic_context_engine-0.3.0a1/src/semantic_context_engine/prompts/v1/taxonomy.md +5 -0
  34. semantic_context_engine-0.3.0a1/src/semantic_context_engine/publication.py +98 -0
  35. semantic_context_engine-0.3.0a1/src/semantic_context_engine/registry.py +764 -0
  36. semantic_context_engine-0.3.0a1/src/semantic_context_engine/relations.py +1114 -0
  37. semantic_context_engine-0.3.0a1/src/semantic_context_engine/runtime.py +1193 -0
  38. semantic_context_engine-0.3.0a1/src/semantic_context_engine/sources/base.py +130 -0
  39. semantic_context_engine-0.3.0a1/src/semantic_context_engine/sources/duckdb.py +1172 -0
  40. semantic_context_engine-0.3.0a1/src/semantic_context_engine/sources/fake.py +107 -0
  41. semantic_context_engine-0.3.0a1/src/semantic_context_engine/storage.py +248 -0
  42. semantic_context_engine-0.3.0a1/src/semantic_context_engine.egg-info/PKG-INFO +263 -0
  43. semantic_context_engine-0.3.0a1/src/semantic_context_engine.egg-info/SOURCES.txt +69 -0
  44. semantic_context_engine-0.3.0a1/src/semantic_context_engine.egg-info/dependency_links.txt +1 -0
  45. semantic_context_engine-0.3.0a1/src/semantic_context_engine.egg-info/entry_points.txt +2 -0
  46. semantic_context_engine-0.3.0a1/src/semantic_context_engine.egg-info/requires.txt +17 -0
  47. semantic_context_engine-0.3.0a1/src/semantic_context_engine.egg-info/top_level.txt +1 -0
  48. semantic_context_engine-0.3.0a1/tests/test_composition.py +38 -0
  49. semantic_context_engine-0.3.0a1/tests/test_duckdb_source.py +91 -0
  50. semantic_context_engine-0.3.0a1/tests/test_engine_module_contracts.py +51 -0
  51. semantic_context_engine-0.3.0a1/tests/test_enrichment.py +1037 -0
  52. semantic_context_engine-0.3.0a1/tests/test_error_boundaries.py +696 -0
  53. semantic_context_engine-0.3.0a1/tests/test_formula_runtime_edge_cases.py +507 -0
  54. semantic_context_engine-0.3.0a1/tests/test_increment1.py +173 -0
  55. semantic_context_engine-0.3.0a1/tests/test_increment1_e2e.py +1507 -0
  56. semantic_context_engine-0.3.0a1/tests/test_integration.py +21 -0
  57. semantic_context_engine-0.3.0a1/tests/test_langchain_integration.py +223 -0
  58. semantic_context_engine-0.3.0a1/tests/test_live_demo.py +157 -0
  59. semantic_context_engine-0.3.0a1/tests/test_live_demo_langchain.py +128 -0
  60. semantic_context_engine-0.3.0a1/tests/test_live_smoke.py +183 -0
  61. semantic_context_engine-0.3.0a1/tests/test_maintainer_regressions.py +399 -0
  62. semantic_context_engine-0.3.0a1/tests/test_r2_p0.py +785 -0
  63. semantic_context_engine-0.3.0a1/tests/test_r2_sql_artifact_contracts.py +406 -0
  64. semantic_context_engine-0.3.0a1/tests/test_relations.py +1351 -0
  65. semantic_context_engine-0.3.0a1/tests/test_runtime.py +968 -0
  66. semantic_context_engine-0.3.0a1/tests/test_sampling_and_routing.py +408 -0
  67. semantic_context_engine-0.3.0a1/tests/test_source_contract.py +84 -0
  68. semantic_context_engine-0.3.0a1/tests/test_storage.py +91 -0
  69. semantic_context_engine-0.3.0a1/tests/test_v3_evaluation.py +1416 -0
  70. semantic_context_engine-0.3.0a1/tests/test_v3_regressions.py +1362 -0
  71. semantic_context_engine-0.3.0a1/tests/test_vertical_demo.py +29 -0
@@ -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,2 @@
1
+ include examples/demo/run_live_demo.py
2
+ include examples/demo/run_vertical.py
@@ -0,0 +1,263 @@
1
+ Metadata-Version: 2.4
2
+ Name: semantic-context-engine
3
+ Version: 0.3.0a1
4
+ Summary: Reusable semantic context catalogs for data applications and AI agents
5
+ Author: Thallys Soares
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/thallyssoares/semantic-context-engine
8
+ Project-URL: Issues, https://github.com/thallyssoares/semantic-context-engine/issues
9
+ Project-URL: Changelog, https://github.com/thallyssoares/semantic-context-engine/blob/main/CHANGELOG.md
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Operating System :: POSIX
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: pydantic>=2.0
21
+ Requires-Dist: sqlglot>=30.0.0
22
+ Requires-Dist: pyyaml>=6.0
23
+ Provides-Extra: duckdb
24
+ Requires-Dist: duckdb>=1.0; extra == "duckdb"
25
+ Provides-Extra: langchain
26
+ Requires-Dist: langchain-core<1.8,>=0.3.60; extra == "langchain"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest==8.4.2; extra == "dev"
29
+ Requires-Dist: pytest-mock==3.15.1; extra == "dev"
30
+ Requires-Dist: mypy==2.4.1; extra == "dev"
31
+ Requires-Dist: types-PyYAML==6.0.12.20261122; extra == "dev"
32
+ Requires-Dist: ruff==0.17.6; extra == "dev"
33
+ Requires-Dist: langchain-core<1.8,>=0.3.60; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # Semantic Context Engine
37
+
38
+ Semantic Context Engine (SCE) compiles an allowlisted warehouse into a versioned semantic catalog. Applications can publish snapshots and load them later through a read-only runtime, without a warehouse connection or model client.
39
+
40
+ This repository contains the experimental `0.3.0a1` alpha candidate for `semantic-context-engine`; it has not been published, so do not assume `pip install semantic-context-engine` is available from an index. The API and snapshot format may change before a stable release; see [CHANGELOG.md](CHANGELOG.md). Provider verification is limited to mocked transport tests: no live-provider run or agent-level A/B evaluation is claimed.
41
+
42
+ ## Quickstart from a built wheel
43
+
44
+ Build from this checkout and install the wheel with the DuckDB extra into a virtual environment:
45
+
46
+ ```bash
47
+ python -m pip install build
48
+ python -m build --wheel
49
+ python -m pip install "dist/semantic_context_engine-0.3.0a1-py3-none-any.whl[duckdb]"
50
+ ```
51
+
52
+ Run the following offline example. It uses synthetic in-memory data and a deterministic fake model; `MemoryStorage` lasts for the life of this process. No provider account is required.
53
+
54
+ ```python
55
+ import duckdb
56
+ from semantic_context_engine import DeterministicFakeLLM, MemoryStorage, SemanticEngine, load_view
57
+ from semantic_context_engine.config import SemanticConfig
58
+ from semantic_context_engine.registry import Registry
59
+ from semantic_context_engine.sources.duckdb import DuckDBSource
60
+
61
+ connection = duckdb.connect(':memory:')
62
+ connection.execute('CREATE TABLE sales (order_id INTEGER, revenue DOUBLE)')
63
+ connection.execute('INSERT INTO sales VALUES (1, 25.0), (2, 40.0)')
64
+ objects = [{'key': 'sales', 'fqn': 'main.sales'}]
65
+ config = SemanticConfig({'namespace': 'quickstart', 'source': {'type': 'duckdb'}, 'objects': objects, 'storage': {'uri': 'memory://'}})
66
+ storage = MemoryStorage()
67
+ engine = SemanticEngine(config, registry=Registry(storage, config.namespace), source=DuckDBSource(connection, objects), llm=DeterministicFakeLLM())
68
+ report = engine.sync(publish=True, enrich=True, relations=False)
69
+ assert report['status'] == 'published', report
70
+ connection.close()
71
+ result = load_view(storage, config.namespace).as_tool()()
72
+ assert result['status'] == 'fresh', result
73
+ print('published:', report['status'], '| runtime:', result['status'])
74
+ ```
75
+
76
+ The output is `published: published | runtime: fresh`. For a larger example from a source checkout, run `python examples/demo/run_vertical.py` after installing the DuckDB extra.
77
+
78
+ ## Use DuckDB from an application
79
+
80
+ ```python
81
+ import duckdb
82
+ from semantic_context_engine import SemanticEngine, LocalStorage
83
+ from semantic_context_engine.config import SemanticConfig
84
+ from semantic_context_engine.registry import Registry
85
+ from semantic_context_engine.sources.duckdb import DuckDBSource
86
+
87
+ objects = [{"key": "sales", "fqn": "main.sales"}]
88
+ connection = duckdb.connect("analytics.duckdb", read_only=True)
89
+ config = SemanticConfig({
90
+ "namespace": "analytics",
91
+ "source": {"type": "duckdb"},
92
+ "objects": objects,
93
+ "storage": {"uri": "./semantic-catalog"},
94
+ })
95
+ engine = SemanticEngine(
96
+ config,
97
+ source=DuckDBSource(connection, objects),
98
+ )
99
+ preview = engine.sync() # dry run
100
+ published = engine.sync(publish=True) # publisher process
101
+ view = engine.load_view(scope=["sales"]) # UI/tool scope hint, not an ACL
102
+ catalog_tool = view.as_tool() # one callable agent tool
103
+ index = catalog_tool() # {status, catalog_version, override_revision, data}
104
+ detail = catalog_tool(["sales"], columns=["revenue"])
105
+ connection.close() # connection lifecycle belongs to caller
106
+ ```
107
+
108
+ Only configured DuckDB objects can be described. The adapter reads metadata and issues bounded aggregate queries for grain and relationship checks; it does not return raw rows. Missing DDL is reported as best-effort metadata. A relation proposal is not approval: aggregate validation determines its status, and forbidden overrides skip validation.
109
+
110
+ Relationship fanout warnings and aggregate metrics are directional: they describe join behavior, not measure additivity or safe aggregation. SCE does not currently establish a consumer target grain or measure-specific pre-aggregation safety, so it emits no generic pre-aggregation recommendation. In particular, consumers must not infer an operation from fanout, a proposed column role, or a legacy non-null `aggregate_first`/`recommended_preaggregation`; runtime withdraws such legacy advice. `aggregation_safety.status` and `recommended_preaggregation` state whether safety was established. `measure_guidance` is a conditional, evidence-limited aid based on proposed roles and measured direction; it does not verify business meaning, formula, or the consumer's intended grain. Check each measure and recompute ratios only from approved additive operands.
111
+
112
+ Relationship details also include per-measure guidance derived from the proposed semantic role and measured directional join evidence. The proposal's provenance is identified as needing review; the guidance distinguishes additive from non-additive treatment and names its evidence/reason. It remains conditional, does not certify the proposed role or business formula, and does not infer a consumer's target grain. Consumers must confirm intended grain and formula before applying it. Runtime labels model-authored relationship prose with `anotacoes_llm_status: unverified` (or `not_provided`); this covers `serve_para` annotations, while `cuidado` can combine deterministic warnings with unverified model text. Legacy records containing `cuidado` without annotation provenance are labeled `indeterminate`: older versions may have concatenated model prose with deterministic warnings, so runtime preserves the alert but cannot establish its origin. Human override reasons remain identified as human-authored. These fields explain the record but never supersede structured verdict, `served`, directional metrics, human overrides, or `aggregation_safety`; if prose conflicts with structured fields, the structured fields control.
113
+
114
+ Guidance is bound to the entity roles, formulas, and grain evidence used to compute it. Explicit recompilation may reuse measured relationship aggregates, but recalculates semantic guidance from the refreshed entity. Object-level human role, formula, or grain overrides change that guidance basis; until a sync refreshes the relationship record, runtime omits stale advice and reports its status as `stale`. Runtime also withdraws legacy pre-aggregation advice even when an old signature matches, because that signature alone does not establish measure safety; such advice is reported as `not_established` or `stale` when its basis differs. Per-measure additive guidance is conditional only when verified grain covers the join keys, the measured side preserves rows, and key coverage is complete; it still does not specify a consumer's target grain or a safe pre-aggregation operation.
115
+
116
+ When runtime serves a validated ratio-of-sums formula, it wraps the summed denominator in `NULLIF(..., 0)` so empty or zero denominators produce NULL.
117
+
118
+ DuckDB can optionally profile JSON key paths and types to a configured depth of at most four, for up to 16 explicitly approved discriminator values per object. The result is capped at 256 paths and contains aggregate counts, never JSON leaf values; discovered key/type/slice evidence is stored in structural `variant_keys` and changes the fingerprint. Approved discriminator values become slice identifiers in saved evidence and runtime responses, so approve only values safe to persist and expose; unapproved values are excluded from profile results and are not added to model prompts. JSON key names and types are metadata too and may themselves be sensitive; allowlist only profiles whose keys, types, and approved slice values are safe for the configured storage and consumer/provider policy. JSON profiling through other source dialects is not supported yet. Formula coverage can use an opt-in `discriminator_profiles` allowlist on the object, returning count/non-null aggregates for proposed operands per approved slice. Among semantically plausible model-proposed candidates, a unique full-coverage candidate can be selected; ties, incomplete evidence, and exhausted budgets remain ambiguous or unverified. Coverage does not establish business meaning or approve a formula. Per-discriminator grain checks have a separate `discriminator_query_budget_per_object` (default `0`). Hierarchy inference is opt-in through `enrichment.hierarchy_query_budget_per_object` (default `0`) and checks only columns classified as dimensions or IDs using NULL-aware aggregate functional dependencies. You can further restrict candidates with `hierarchy_columns`. Empty data remains unverified; cycles/equivalent labels are suppressed from the exposed graph.
119
+
120
+ DuckDB validates declared conditional candidates with a bounded typed filter DSL (`eq`, `in`, `is_null`, `not_null`). Equality and membership filters must use explicitly approved discriminator values; reports state that metrics cover filtered rows. Supported relationship key transforms are identity, date, month, and approved JSON scalar paths with type checks; arbitrary expressions and time-only joins remain unsupported. JSON-path mappings require an approved discriminator condition. Formula coverage is aggregate evidence and does not replace human definition review. The deterministic evaluation helpers include a synthetic E01–E12 pocket matrix and separate infrastructure or blocked cases from quality scores; this is not the full agent-level A/B harness or live-model evaluation.
121
+
122
+ Optional profiling and sampling are separate controls. Profiling returns bounded aggregate statistics; sampling returns actual values only when `enrichment.sampling.enabled` is true and the object has an explicit per-column `allowed_columns` entry. Supported sample modes are `rows` and `distinct`. The configuration bounds rows, values per column, bytes per value/payload and query count. DuckDB's reference adapter currently enforces query and size limits; it does not expose a portable query execution timeout. Other adapters must truthfully implement the bounded source contract; the core cannot prevent a nonconforming external adapter from doing extra work internally. An optional `sample_transform(object_key, column, value)` is applied before any value enters model context. Transform output that is not a JSON scalar or exceeds limits is rejected; SCE does not truncate oversized values. SCE does not intentionally put sample values into persisted semantic artifacts or reports. Its persistence check rejects direct textual echoes (exact values and simple substring/token matches), but this is not a general data-loss-prevention guarantee: paraphrases, encoded values, aggregates, calculations, or other derived information may not match the textual check. Keep allowlists narrow, transform or redact sensitive values before context, and apply your provider's retention and tracing controls. SCE itself does not trace sample payloads.
123
+
124
+ The relational proposal stage receives a byte-bounded projection of the current enriched artifact: entity purpose/descriptions, column descriptions/roles, families, proposed versus verified grain, time columns, formulas, verified hierarchies, discriminator evidence, limitations and relevant effective human overrides. It does not receive arbitrary raw samples. If required evidence cannot fit the configured internal projection bound, the stage fails explicitly rather than silently dropping it. Deterministic validation remains authoritative for relationship acceptance and measured metrics.
125
+
126
+ ## Extension contracts
127
+
128
+ - `Source` describes allowlisted objects and declares its SQL dialect and optional aggregate capabilities. DuckDB is the reference adapter. Legacy `relationship_metrics` calls represent one aggregate SQL statement. Adapters requiring multiple statements implement `relationship_metrics_counted`; it receives the remaining budget, must enforce it before execution, and returns the exact statement count. This is a cooperative adapter contract: the core checks reported counts and withholds further work when the budget is exhausted, but cannot prevent an external adapter from issuing extra statements internally or independently prove that its reported count is truthful. If execution fails after SQL starts, the adapter reports the count with `AggregateQueryExecutionError`; an unmetered failure reserves the rest of the pair budget and marks the report count unknown.
129
+ - `StorageProtocol` uses namespace-relative keys and requires exclusive artifact creation, compare-and-swap, and locking. `LocalStorage` and in-process `MemoryStorage` implement it. `file://` and local paths select filesystem storage; `memory://` selects ephemeral storage. Other schemes fail explicitly until a backend is implemented.
130
+ - A consumer may inject a provider-neutral `StructuredLLM`; no model SDK is required by the core. The optional `semantic-context-engine[langchain]` extra adds `LangChainStructuredLLM`, which accepts an already instantiated `langchain_core` `BaseChatModel`, calls `with_structured_output()` with SCE's Pydantic stage schema and validates the parsed response again locally. The consumer chooses and configures the provider/model, credentials, transport, timeout and retry behavior. SCE does not mutate the supplied model, execute returned tools, promise a universal network timeout, or claim to cancel a blocking synchronous request. The core retries a transient stage failure at most once (two attempts total); configure the supplied model's own retries (for example `max_retries=0` where supported) to avoid nested retries. Unsupported structured output and incomplete/invalid responses fail closed without a text-generation fallback.
131
+ - Enrichment failures keep the backward-compatible `enrichment_failed` labels and add bounded `enrichment_diagnostics` records with object, stage, category, code, retryability, safe structural-column references/counts, and available adapter telemetry. Provider exception messages, prompts, arbitrary model values and rows are not copied to reports. Missing token/identity values remain unknown; adapter invocation counts are not necessarily HTTP request counts because an injected model may perform internal retries or multiple requests. `SemanticEngine.sync(..., fail_fast=True)` stops after the first object/stage failure, records completed/failed/skipped/unattempted stages, bypasses relations and publication, and preserves the active artifact. The default remains `fail_fast=False`, which can collect more failures but still never publishes partial semantic output.
132
+ - The family-classification Pydantic schema enumerates the supported column roles (`dimension`, `id`, `date`, `additive_measure`, `non_additive_measure`, `flag`, `text`, `technical`); arbitrary role strings fail schema validation before semantic compilation.
133
+ - The core intentionally accepts the `StructuredLLM` contract, not arbitrary provider objects as `SemanticEngine(llm=...)`; this avoids importing LangChain or guessing which provider API an object implements. Wrap an instantiated LangChain model explicitly with `LangChainStructuredLLM(model)`. A consumer-specific adapter can implement the same small contract:
134
+
135
+ ```python
136
+ class ConsumerStructuredLLM:
137
+ model_name = "consumer-configured-model"
138
+ prompt_version = "consumer-prompt-v1"
139
+
140
+ def __init__(self, generate_structured):
141
+ self.generate_structured = generate_structured
142
+
143
+ def generate(self, stage, context, schema, *, timeout_seconds):
144
+ # Call your client's structured-output API here and enforce its timeout.
145
+ # Return a mapping that conforms to the supplied JSON schema.
146
+ return self.generate_structured(
147
+ stage=stage,
148
+ context=context,
149
+ schema=schema,
150
+ timeout_seconds=timeout_seconds,
151
+ )
152
+ ```
153
+
154
+ Configure that adapter with the consumer's client before injection; the client method shown is the consumer integration point, not an SCE API.
155
+ - Ordinary unchanged syncs reuse prior enrichment without provider calls. Source-data changes that do not alter metadata fingerprints are therefore not detected automatically. Set `recompile=True` explicitly on `SemanticEngine.sync()` to refresh object-level semantic enrichment, including grain and hierarchy evidence; set `recompute_relations=True` separately when relationship evidence also needs forced revalidation. Runtime exposes only hierarchy paths supported by verified, non-vacuous edge evidence, alongside the evidence/status details; failed or unverified chains are not served as verified paths.
156
+ - Semantic entities record provider/model, stage prompt and bundle hash, structural input revision, profiling/sampling policy revisions, and known call/usage/latency deltas. Relationship proposal provenance is recorded separately from measured join metrics; it records its semantic input revision and available model/usage metadata. If relationship evidence is reused, the prior proposal provenance is retained and measured metrics are not queried again solely because semantic guidance changed.
157
+ - Packaged stage prompts are versioned and passed with structural and eligible semantic evidence as untrusted input. Provider policy and consumer configuration determine how metadata is transmitted; do not send secrets or sensitive metadata without an approved provider configuration. SCE does not configure provider-side retention or external tracing.
158
+ - The provider-independent full compile smoke is skipped unless `SCE_RUN_LIVE_SMOKE=1` and a consumer-supplied `SCE_LANGCHAIN_MODEL_FACTORY=module:callable` are set. The optional approved-sampling leg has its own `SCE_RUN_LIVE_SMOKE_SAMPLING=1` opt-in and explicit synthetic-column allowlist. These tests can make provider requests and incur charges; ordinary tests and CI do not make live requests. A successful request verifies integration and schema flow only, not semantic correctness. No live provider request has been run for this candidate.
159
+
160
+ The runtime reads only published catalogs and overrides. The local filesystem backend uses POSIX `fcntl` locks; supported environments are POSIX systems that provide `fcntl` (the CI validates Ubuntu). Windows support is not claimed. Cloud storage and warehouse adapters are not included.
161
+
162
+ ### Alpha runtime API change
163
+
164
+ In this internal alpha, `RuntimeView.as_tool()` now returns the single callable
165
+ catalog tool. Call it with no arguments for the index or with 1–3 object keys
166
+ and optional selected columns for details. The callable always returns a
167
+ `status` (`fresh`, `stale`, or `unavailable`), catalog version, override
168
+ revision, and `data`. Direct `index()` and `detail()` methods remain available.
169
+ This replaces the earlier behavior where calling `as_tool()` immediately
170
+ returned an index and passing arguments to `as_tool` performed a detail lookup.
171
+ The runtime checks active snapshot and override revisions on every call, even
172
+ while cached, and reloads a coherent bundle when either revision changes.
173
+ The optional `scope` filters keys and rejects out-of-scope requests; it is a
174
+ retrieval boundary for this view, not an authorization control. The tool wrapper
175
+ defaults to a 64 KiB serialized payload ceiling and returns
176
+ `payload_budget_exceeded` rather than silently truncating results. Formula
177
+ expressions served to consumers are limited to validated additive `SUM(x)` or
178
+ `SUM(x) / SUM(y)` ratio-of-sums forms over numeric additive base columns; such
179
+ validation is schema-level only and does not claim data coverage verification.
180
+ Enrichment also reports `temporal_conflicts` when structural date/time types,
181
+ the proposed column roles, and the selected `time_column` disagree. These are
182
+ review signals, not automatic role rewrites; runtime continues to honor valid
183
+ human overrides and marks the affected conflict. Older semantic artifacts get
184
+ the same type/role check at read time.
185
+
186
+ Generated formula candidates are exposed separately as `formula_proposals`.
187
+ Each preserves operand order and distinguishes the proposed operator, schema
188
+ checks, slice coverage, numerical evidence, and human approval. A two-operand
189
+ legacy proposal has operator `unknown`; it is never promoted to
190
+ `ratio_of_sums` by operand count. Formula proposals are not executable SQL and
191
+ are not approval. Runtime formula expressions still come only from the
192
+ restricted, schema-validated human override contract.
193
+
194
+ ## Development checks
195
+
196
+ ```bash
197
+ python -m pytest -q
198
+ python -m build
199
+ ```
200
+
201
+ GitHub Actions is configured for Ubuntu and Python 3.10–3.13. CI exercises minimum runtime dependencies without LangChain, then installs the development/optional integration dependencies for the full suite. It checks Ruff lint and formatting, mypy with untyped function bodies checked across `src/semantic_context_engine`, builds wheel and sdist, checks metadata with Twine, and installs core-only wheel, wheel with DuckDB, sdist with DuckDB, and wheel with the optional LangChain extra into separate virtual environments. The wheel and sdist consumers run the vertical demo outside the checkout with isolated Python and no editable install or `PYTHONPATH`; core-only checks the CLI, runtime unavailable behavior and packaged instruction resource, and the LangChain-extra consumer checks bridge imports without a provider request. The `semantic` CLI remains available for local inspection and publication.
202
+
203
+ Executable shared-model example (the consumer installs its chosen provider package and configures credentials/transport):
204
+
205
+ ```python
206
+ from langchain_openrouter import ChatOpenRouter
207
+ from semantic_context_engine import SemanticEngine
208
+ from semantic_context_engine.integrations.langchain import LangChainStructuredLLM
209
+
210
+ model = ChatOpenRouter(model="provider/model", temperature=0, max_retries=0)
211
+ engine = SemanticEngine(config=config, source=source, llm=LangChainStructuredLLM(model))
212
+ ```
213
+
214
+ Use `enrichment_llm=` and `relations_llm=` to select models per stage; `llm=` remains their shared default. Pass `relations_llm=False` for deterministic-only relationship compilation. No provider is selected implicitly.
215
+
216
+ ### Bring your own model demo
217
+
218
+ `examples/demo/run_live_demo.py` accepts an already-instantiated `llm`, or separate `enrichment_llm` and `relations_llm` objects. It uses the same canonical synthetic dataset and the real SCE sync, relation, storage, and runtime paths. The helper accepts either an SCE `StructuredLLM` or an instantiated LangChain `BaseChatModel` (which it explicitly wraps); this convenience is local to the example and does not change `SemanticEngine`'s core contract. Sampling defaults to disabled. Set `sampling_enabled=True` only when you intentionally want the approved synthetic sample columns included in model context.
219
+
220
+ ```python
221
+ from langchain_openai import ChatOpenAI
222
+ from examples.demo.run_live_demo import run_live_demo
223
+
224
+ model = ChatOpenAI(model="your-chosen-model", temperature=0, max_retries=0)
225
+ result = run_live_demo(llm=model, sampling_enabled=False)
226
+ print(result)
227
+ ```
228
+
229
+ The provider/model, credentials, and transport settings belong to the caller. Calling the helper with a live model makes provider requests; importing it does not. Running the script directly uses a deterministic synthetic fake and makes no live requests. The returned summary includes publication/runtime status, relationship outcomes, target-join comparison, sampling query/byte counts, and known per-stage calls, tokens, latency, and retries; unavailable provider metadata remains empty or `unknown`. Sampling is off by default; when intentionally enabled, use the `sample_transform` argument to redact or transform values before they reach the supplied model.
230
+
231
+
232
+ ### Engine import migration
233
+
234
+ `SemanticEngine` is implemented in `semantic_context_engine.engine` and exported
235
+ from the package root. The previous `semantic_context_engine.config.SemanticEngine`
236
+ import remains as a compatibility alias for this release; `SemanticConfig` and
237
+ `load_config` remain in `semantic_context_engine.config`. The removed top-level
238
+ `semantic_layer` package is not restored.
239
+
240
+
241
+ ### Structural snapshot schema
242
+
243
+ New structural snapshots are written with `schema_version: 1`, independent of the
244
+ package version. Reads of the unversioned alpha shape are validated and migrated
245
+ in memory with documented defaults; the original immutable artifact is not
246
+ rewritten. Unknown fields, malformed artifacts, and unsupported schema versions
247
+ fail closed. Export and rebuild from the source to move an unsupported artifact
248
+ forward.
249
+
250
+ ### Error boundaries
251
+
252
+ Public sync reports, CLI output, relationship cautions, and runtime availability
253
+ messages use stable generic labels for adapter and backend failures. Original
254
+ exceptions remain available as chained causes for internal debugging; callers
255
+ should handle `SourceError`, `StorageError`, `ProviderError`,
256
+ `UnsupportedCapabilityError`, and the validation/conflict subclasses. Reports
257
+ preserve detailed messages for locally generated metadata validation errors for
258
+ compatibility. Configuration, override, snapshot, semantic artifact, report,
259
+ source capability, provider stage output, and relationship metric boundaries
260
+ have explicit contracts. Provider stage outputs and persisted JSON artifacts use
261
+ Pydantic; some in-memory orchestration records remain typed dataclasses or
262
+ runtime-checked mappings. These internal representations are not separate stable
263
+ consumer APIs.