semantic-context-engine 0.3.0a1__py3-none-any.whl
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.
- semantic_context_engine/__init__.py +136 -0
- semantic_context_engine/artifacts.py +98 -0
- semantic_context_engine/cli.py +197 -0
- semantic_context_engine/compiler.py +316 -0
- semantic_context_engine/composition.py +31 -0
- semantic_context_engine/config.py +199 -0
- semantic_context_engine/diff.py +93 -0
- semantic_context_engine/domain_contracts.py +386 -0
- semantic_context_engine/engine.py +250 -0
- semantic_context_engine/enrichment.py +1416 -0
- semantic_context_engine/errors.py +291 -0
- semantic_context_engine/evaluation.py +88 -0
- semantic_context_engine/hierarchies.py +185 -0
- semantic_context_engine/instructions/semantic_catalog.md +2 -0
- semantic_context_engine/integration.py +22 -0
- semantic_context_engine/integrations/__init__.py +11 -0
- semantic_context_engine/integrations/langchain.py +275 -0
- semantic_context_engine/models.py +282 -0
- semantic_context_engine/normalization.py +351 -0
- semantic_context_engine/pipeline.py +1685 -0
- semantic_context_engine/prompts/v1/column_classification.md +15 -0
- semantic_context_engine/prompts/v1/grain_correction.md +4 -0
- semantic_context_engine/prompts/v1/relationship_proposal.md +10 -0
- semantic_context_engine/prompts/v1/synthesis.md +5 -0
- semantic_context_engine/prompts/v1/taxonomy.md +5 -0
- semantic_context_engine/publication.py +98 -0
- semantic_context_engine/registry.py +764 -0
- semantic_context_engine/relations.py +1114 -0
- semantic_context_engine/runtime.py +1193 -0
- semantic_context_engine/sources/base.py +130 -0
- semantic_context_engine/sources/duckdb.py +1172 -0
- semantic_context_engine/sources/fake.py +107 -0
- semantic_context_engine/storage.py +248 -0
- semantic_context_engine-0.3.0a1.dist-info/METADATA +263 -0
- semantic_context_engine-0.3.0a1.dist-info/RECORD +39 -0
- semantic_context_engine-0.3.0a1.dist-info/WHEEL +5 -0
- semantic_context_engine-0.3.0a1.dist-info/entry_points.txt +2 -0
- semantic_context_engine-0.3.0a1.dist-info/licenses/LICENSE +202 -0
- semantic_context_engine-0.3.0a1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""Stable, actionable domain exceptions for public error boundaries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SemanticContextError(Exception):
|
|
9
|
+
"""Base class for errors callers may handle without inspecting internals."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ValidationError(SemanticContextError, ValueError):
|
|
13
|
+
"""Input or persisted domain data failed validation."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
SEMANTIC_DIAGNOSTIC_CODES = frozenset(
|
|
17
|
+
{
|
|
18
|
+
"missing_columns",
|
|
19
|
+
"unknown_column",
|
|
20
|
+
"duplicate_column",
|
|
21
|
+
"invalid_role",
|
|
22
|
+
"empty_family",
|
|
23
|
+
"invalid_formula_reference",
|
|
24
|
+
"duplicate_formula_operand",
|
|
25
|
+
"invalid_grain_reference",
|
|
26
|
+
"invalid_temporal_reference",
|
|
27
|
+
"sample_persistence_violation",
|
|
28
|
+
"empty_taxonomy_description",
|
|
29
|
+
"invalid_column_field",
|
|
30
|
+
"invalid_recompute_reference",
|
|
31
|
+
"invalid_synthesis_field",
|
|
32
|
+
"semantic_contract_violation",
|
|
33
|
+
}
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class SemanticValidationError(ValidationError):
|
|
38
|
+
"""A model response was schema-valid but violated a semantic contract.
|
|
39
|
+
|
|
40
|
+
Only allowlisted codes and references already known from structural
|
|
41
|
+
metadata are exposed. Provider-controlled values are never retained.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
stage: str,
|
|
47
|
+
code: str,
|
|
48
|
+
*,
|
|
49
|
+
known_columns: tuple[str, ...] | list[str] = (),
|
|
50
|
+
references: tuple[str, ...] | list[str] = (),
|
|
51
|
+
expected_columns: int | None = None,
|
|
52
|
+
classified_columns: int | None = None,
|
|
53
|
+
invalid_count: int | None = None,
|
|
54
|
+
) -> None:
|
|
55
|
+
if stage not in {
|
|
56
|
+
"taxonomy",
|
|
57
|
+
"families",
|
|
58
|
+
"synthesis",
|
|
59
|
+
"grain_correction",
|
|
60
|
+
"persistence",
|
|
61
|
+
"unknown_stage",
|
|
62
|
+
}:
|
|
63
|
+
stage = "unknown_stage"
|
|
64
|
+
if code not in SEMANTIC_DIAGNOSTIC_CODES:
|
|
65
|
+
code = "semantic_contract_violation"
|
|
66
|
+
safe_columns = set(known_columns)
|
|
67
|
+
safe_refs = sorted({ref for ref in references if ref in safe_columns})[:64]
|
|
68
|
+
self.stage = stage
|
|
69
|
+
self.code = code
|
|
70
|
+
self.retryable = False
|
|
71
|
+
self.details: dict[str, Any] = {}
|
|
72
|
+
if (
|
|
73
|
+
isinstance(expected_columns, int)
|
|
74
|
+
and not isinstance(expected_columns, bool)
|
|
75
|
+
and 0 <= expected_columns <= 100_000
|
|
76
|
+
):
|
|
77
|
+
self.details["expected_columns"] = expected_columns
|
|
78
|
+
if (
|
|
79
|
+
isinstance(classified_columns, int)
|
|
80
|
+
and not isinstance(classified_columns, bool)
|
|
81
|
+
and 0 <= classified_columns <= 100_000
|
|
82
|
+
):
|
|
83
|
+
self.details["classified_columns"] = classified_columns
|
|
84
|
+
if (
|
|
85
|
+
isinstance(invalid_count, int)
|
|
86
|
+
and not isinstance(invalid_count, bool)
|
|
87
|
+
and 0 <= invalid_count <= 100_000
|
|
88
|
+
):
|
|
89
|
+
self.details["invalid_count"] = invalid_count
|
|
90
|
+
if safe_refs:
|
|
91
|
+
field = "missing_columns" if code == "missing_columns" else "columns"
|
|
92
|
+
self.details[field] = safe_refs
|
|
93
|
+
# The exception text is fixed and safe; callers must use the typed
|
|
94
|
+
# attributes for actionable diagnostics instead of parsing messages.
|
|
95
|
+
super().__init__("Semantic output violated a contract")
|
|
96
|
+
|
|
97
|
+
def to_diagnostic(self, object_key: str) -> dict[str, Any]:
|
|
98
|
+
return {
|
|
99
|
+
"object": object_key,
|
|
100
|
+
"stage": self.stage,
|
|
101
|
+
"category": "semantic_validation",
|
|
102
|
+
"code": self.code,
|
|
103
|
+
**self.details,
|
|
104
|
+
"retryable": False,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class UnsupportedSnapshotVersionError(ValidationError):
|
|
109
|
+
"""A persisted structural artifact uses an unsupported schema version."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class SnapshotValidationError(ValidationError):
|
|
113
|
+
"""A structural artifact is malformed or contains unknown fields."""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class PublicationConflictError(SemanticContextError, RuntimeError):
|
|
117
|
+
"""A compare-and-swap publication lost a concurrent update race."""
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class SourceError(SemanticContextError, RuntimeError):
|
|
121
|
+
"""A source adapter failed while reading authorized metadata or aggregates."""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class StorageError(SemanticContextError, RuntimeError):
|
|
125
|
+
"""A storage backend failed while reading or persisting catalog artifacts."""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class ProviderError(SemanticContextError, RuntimeError):
|
|
129
|
+
"""An optional semantic provider failed to return usable output."""
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class ProviderDiagnosticError(ProviderError):
|
|
133
|
+
"""Sanitized provider/bridge failure metadata with no raw exception text."""
|
|
134
|
+
|
|
135
|
+
_CATEGORIES = frozenset(
|
|
136
|
+
{
|
|
137
|
+
"provider_authentication",
|
|
138
|
+
"provider_configuration",
|
|
139
|
+
"provider_request_rejected",
|
|
140
|
+
"transport_failure",
|
|
141
|
+
"rate_limited",
|
|
142
|
+
"unsupported_structured_output",
|
|
143
|
+
"incomplete_response",
|
|
144
|
+
"structured_output_parse_failure",
|
|
145
|
+
"pydantic_schema_validation_failure",
|
|
146
|
+
"source_failure",
|
|
147
|
+
"storage_failure",
|
|
148
|
+
"internal_error",
|
|
149
|
+
}
|
|
150
|
+
)
|
|
151
|
+
_CODES = frozenset(
|
|
152
|
+
{
|
|
153
|
+
"authentication_rejected",
|
|
154
|
+
"configuration_rejected",
|
|
155
|
+
"request_rejected",
|
|
156
|
+
"http_4xx",
|
|
157
|
+
"http_5xx",
|
|
158
|
+
"rate_limited",
|
|
159
|
+
"timeout",
|
|
160
|
+
"transport_error",
|
|
161
|
+
"structured_output_unsupported",
|
|
162
|
+
"response_incomplete",
|
|
163
|
+
"response_parse_failed",
|
|
164
|
+
"schema_validation_failed",
|
|
165
|
+
"provider_invocation_failed",
|
|
166
|
+
"unexpected_provider_error",
|
|
167
|
+
}
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
def __init__(
|
|
171
|
+
self,
|
|
172
|
+
stage: str,
|
|
173
|
+
category: str,
|
|
174
|
+
code: str,
|
|
175
|
+
*,
|
|
176
|
+
retryable: bool,
|
|
177
|
+
attempts: int | None = None,
|
|
178
|
+
http_status: int | None = None,
|
|
179
|
+
) -> None:
|
|
180
|
+
self.stage = (
|
|
181
|
+
stage
|
|
182
|
+
if stage in {"taxonomy", "families", "synthesis", "grain_correction", "relations"}
|
|
183
|
+
else "unknown_stage"
|
|
184
|
+
)
|
|
185
|
+
self.category = category if category in self._CATEGORIES else "internal_error"
|
|
186
|
+
self.code = code if code in self._CODES else "unexpected_provider_error"
|
|
187
|
+
self.retryable = retryable if isinstance(retryable, bool) else False
|
|
188
|
+
self.attempts = (
|
|
189
|
+
attempts
|
|
190
|
+
if isinstance(attempts, int) and not isinstance(attempts, bool) and 0 <= attempts <= 10
|
|
191
|
+
else None
|
|
192
|
+
)
|
|
193
|
+
self.http_status = (
|
|
194
|
+
http_status
|
|
195
|
+
if isinstance(http_status, int)
|
|
196
|
+
and not isinstance(http_status, bool)
|
|
197
|
+
and 100 <= http_status <= 599
|
|
198
|
+
else None
|
|
199
|
+
)
|
|
200
|
+
super().__init__("Structured provider operation failed")
|
|
201
|
+
|
|
202
|
+
def to_diagnostic(self, object_key: str) -> dict[str, Any]:
|
|
203
|
+
result: dict[str, Any] = {
|
|
204
|
+
"object": object_key,
|
|
205
|
+
"stage": self.stage,
|
|
206
|
+
"category": self.category,
|
|
207
|
+
"code": self.code,
|
|
208
|
+
"retryable": self.retryable,
|
|
209
|
+
}
|
|
210
|
+
if self.attempts is not None:
|
|
211
|
+
result["attempts"] = self.attempts
|
|
212
|
+
if self.http_status is not None:
|
|
213
|
+
result["http_status"] = self.http_status
|
|
214
|
+
return result
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class ProviderPermanentError(ProviderError):
|
|
218
|
+
"""Provider configuration, authentication, or request cannot be retried."""
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class ProviderTransientError(ProviderError):
|
|
222
|
+
"""Provider transport or service error may succeed on a bounded retry."""
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class UnsupportedCapabilityError(SemanticContextError, RuntimeError):
|
|
226
|
+
"""A requested operation is not supported by the configured source."""
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class AggregateQueryBudgetExceeded(SemanticContextError, RuntimeError):
|
|
230
|
+
"""A source cannot complete an aggregate result within its statement budget."""
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class AggregateQueryExecutionError(SemanticContextError, RuntimeError):
|
|
234
|
+
"""A metered source failed after executing a known number of statements."""
|
|
235
|
+
|
|
236
|
+
def __init__(self, executed_count: int) -> None:
|
|
237
|
+
if isinstance(executed_count, bool) or not isinstance(executed_count, int):
|
|
238
|
+
raise TypeError("executed_count must be an integer")
|
|
239
|
+
if executed_count < 0:
|
|
240
|
+
raise ValueError("executed_count must not be negative")
|
|
241
|
+
self.executed_count = executed_count
|
|
242
|
+
super().__init__("Aggregate relationship validation failed after execution")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def safe_error_label(exc: BaseException) -> str:
|
|
246
|
+
"""Return a non-sensitive, stable label for consumer-facing diagnostics."""
|
|
247
|
+
labels = (
|
|
248
|
+
(UnsupportedCapabilityError, "unsupported_capability"),
|
|
249
|
+
(SourceError, "source_unavailable"),
|
|
250
|
+
(StorageError, "storage_unavailable"),
|
|
251
|
+
(ProviderError, "provider_failed"),
|
|
252
|
+
(UnsupportedSnapshotVersionError, "unsupported_snapshot_version"),
|
|
253
|
+
(SnapshotValidationError, "invalid_snapshot"),
|
|
254
|
+
(PublicationConflictError, "publication_conflict"),
|
|
255
|
+
(ConfigurationError, "invalid_configuration"),
|
|
256
|
+
(ValidationError, "validation_failed"),
|
|
257
|
+
)
|
|
258
|
+
for error_type, label in labels:
|
|
259
|
+
if isinstance(exc, error_type):
|
|
260
|
+
return label
|
|
261
|
+
# Validation failures from Pydantic and the domain's pure validators often
|
|
262
|
+
# carry the offending column/value in their message. Keep the category
|
|
263
|
+
# useful without reflecting that untrusted detail into reports.
|
|
264
|
+
if isinstance(exc, ValueError):
|
|
265
|
+
return "validation_failed"
|
|
266
|
+
return "operation_failed"
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
__all__ = [
|
|
270
|
+
"SemanticContextError",
|
|
271
|
+
"ValidationError",
|
|
272
|
+
"UnsupportedSnapshotVersionError",
|
|
273
|
+
"SnapshotValidationError",
|
|
274
|
+
"PublicationConflictError",
|
|
275
|
+
"SourceError",
|
|
276
|
+
"StorageError",
|
|
277
|
+
"ProviderError",
|
|
278
|
+
"ProviderDiagnosticError",
|
|
279
|
+
"ProviderPermanentError",
|
|
280
|
+
"ProviderTransientError",
|
|
281
|
+
"UnsupportedCapabilityError",
|
|
282
|
+
"AggregateQueryBudgetExceeded",
|
|
283
|
+
"AggregateQueryExecutionError",
|
|
284
|
+
"ConfigurationError",
|
|
285
|
+
"safe_error_label",
|
|
286
|
+
"SemanticValidationError",
|
|
287
|
+
]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
class ConfigurationError(ValidationError):
|
|
291
|
+
"""Configuration input failed validation."""
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Small deterministic compiler-evaluation records and scoring helpers.
|
|
2
|
+
|
|
3
|
+
This is not an agent A/B harness. Infrastructure and blocked cases are kept out
|
|
4
|
+
of the semantic quality denominator so a provider outage cannot become a model
|
|
5
|
+
failure or a fabricated score.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EvaluationCase(BaseModel):
|
|
16
|
+
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
|
|
17
|
+
|
|
18
|
+
id: StrictStr
|
|
19
|
+
category: StrictStr
|
|
20
|
+
status: Literal["passed", "failed", "infrastructure_error", "blocked"]
|
|
21
|
+
expected: dict[str, Any] = Field(default_factory=dict)
|
|
22
|
+
observed: dict[str, Any] = Field(default_factory=dict)
|
|
23
|
+
version: StrictStr
|
|
24
|
+
model: StrictStr
|
|
25
|
+
prompt_schema: StrictStr
|
|
26
|
+
dataset: StrictStr
|
|
27
|
+
configuration: dict[str, Any] = Field(default_factory=dict)
|
|
28
|
+
evidence: list[StrictStr] = Field(default_factory=list)
|
|
29
|
+
provider_calls: StrictInt = 0
|
|
30
|
+
tolerance: float = Field(default=0.000001, ge=0)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _matches(expected: Any, observed: Any, tolerance: float) -> bool:
|
|
34
|
+
if isinstance(expected, dict) and isinstance(observed, dict):
|
|
35
|
+
return expected.keys() == observed.keys() and all(
|
|
36
|
+
_matches(expected[key], observed[key], tolerance) for key in expected
|
|
37
|
+
)
|
|
38
|
+
if isinstance(expected, list) and isinstance(observed, list):
|
|
39
|
+
return len(expected) == len(observed) and all(
|
|
40
|
+
_matches(left, right, tolerance) for left, right in zip(expected, observed)
|
|
41
|
+
)
|
|
42
|
+
if (
|
|
43
|
+
isinstance(expected, (int, float))
|
|
44
|
+
and not isinstance(expected, bool)
|
|
45
|
+
and isinstance(observed, (int, float))
|
|
46
|
+
and not isinstance(observed, bool)
|
|
47
|
+
):
|
|
48
|
+
return abs(float(expected) - float(observed)) <= tolerance
|
|
49
|
+
return expected == observed
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def score_cases(cases: list[EvaluationCase]) -> dict[str, Any]:
|
|
53
|
+
"""Summarize deterministic outcomes without mixing infra failures into quality."""
|
|
54
|
+
ids = [case.id for case in cases]
|
|
55
|
+
if len(ids) != len(set(ids)):
|
|
56
|
+
raise ValueError("Evaluation case IDs must be unique")
|
|
57
|
+
scored_cases = [case for case in cases if case.status in {"passed", "failed"}]
|
|
58
|
+
passed = sum(
|
|
59
|
+
case.status == "passed" and _matches(case.expected, case.observed, case.tolerance)
|
|
60
|
+
for case in scored_cases
|
|
61
|
+
)
|
|
62
|
+
failed = len(scored_cases) - passed
|
|
63
|
+
infrastructure = sum(case.status == "infrastructure_error" for case in cases)
|
|
64
|
+
blocked = sum(case.status == "blocked" for case in cases)
|
|
65
|
+
scored = passed + failed
|
|
66
|
+
return {
|
|
67
|
+
"cases": len(cases),
|
|
68
|
+
"scored": scored,
|
|
69
|
+
"passed": passed,
|
|
70
|
+
"failed": failed,
|
|
71
|
+
"infrastructure_errors": infrastructure,
|
|
72
|
+
"blocked": blocked,
|
|
73
|
+
"pass_rate": passed / scored if scored else None,
|
|
74
|
+
"results": [
|
|
75
|
+
{
|
|
76
|
+
**case.model_dump(mode="json"),
|
|
77
|
+
"score": (
|
|
78
|
+
"pass"
|
|
79
|
+
if case.status == "passed"
|
|
80
|
+
and _matches(case.expected, case.observed, case.tolerance)
|
|
81
|
+
else "fail"
|
|
82
|
+
if case.status in {"passed", "failed"}
|
|
83
|
+
else case.status
|
|
84
|
+
),
|
|
85
|
+
}
|
|
86
|
+
for case in cases
|
|
87
|
+
],
|
|
88
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Bounded deterministic hierarchy inference from aggregate dependencies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from semantic_context_engine.sources.base import SourceCapabilities
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def infer_hierarchies(source, structural, columns: list[dict[str, Any]], query_budget: int) -> dict:
|
|
11
|
+
"""Infer parent -> child paths only from non-vacuous measured dependencies.
|
|
12
|
+
|
|
13
|
+
Candidate selection uses semantic roles but those roles are only a filter;
|
|
14
|
+
aggregate functional-dependency evidence is the approval criterion.
|
|
15
|
+
"""
|
|
16
|
+
if isinstance(query_budget, bool) or not isinstance(query_budget, int) or query_budget < 0:
|
|
17
|
+
raise ValueError("hierarchy query budget must be a non-negative integer")
|
|
18
|
+
if query_budget == 0:
|
|
19
|
+
return {
|
|
20
|
+
"hierarchies": [],
|
|
21
|
+
"evidence": [],
|
|
22
|
+
"status": "disabled",
|
|
23
|
+
"queries": 0,
|
|
24
|
+
"pending": [],
|
|
25
|
+
}
|
|
26
|
+
capabilities = getattr(source, "capabilities", None)
|
|
27
|
+
if not isinstance(capabilities, SourceCapabilities) or not capabilities.hierarchy_aggregate:
|
|
28
|
+
return {
|
|
29
|
+
"hierarchies": [],
|
|
30
|
+
"evidence": [],
|
|
31
|
+
"status": "unsupported",
|
|
32
|
+
"queries": 0,
|
|
33
|
+
"pending": [],
|
|
34
|
+
}
|
|
35
|
+
if not hasattr(source, "hierarchy_dependency"):
|
|
36
|
+
return {
|
|
37
|
+
"hierarchies": [],
|
|
38
|
+
"evidence": [],
|
|
39
|
+
"status": "unsupported",
|
|
40
|
+
"queries": 0,
|
|
41
|
+
"pending": [],
|
|
42
|
+
}
|
|
43
|
+
roles: dict[str, str] = {}
|
|
44
|
+
for item in columns:
|
|
45
|
+
name = item.get("name") if isinstance(item, dict) else None
|
|
46
|
+
role = item.get("role") if isinstance(item, dict) else None
|
|
47
|
+
if isinstance(name, str) and isinstance(role, str) and name in structural.columns:
|
|
48
|
+
roles[name] = role
|
|
49
|
+
eligible = sorted(name for name, role in roles.items() if role in {"dimension", "id"})
|
|
50
|
+
policy_reader = getattr(source, "hierarchy_columns", None)
|
|
51
|
+
allowed_columns = policy_reader(structural.key) if callable(policy_reader) else None
|
|
52
|
+
if allowed_columns is not None:
|
|
53
|
+
if any(
|
|
54
|
+
not isinstance(name, str) or name not in structural.columns for name in allowed_columns
|
|
55
|
+
):
|
|
56
|
+
return {
|
|
57
|
+
"hierarchies": [],
|
|
58
|
+
"evidence": [],
|
|
59
|
+
"status": "unverified",
|
|
60
|
+
"queries": 0,
|
|
61
|
+
"pending": [],
|
|
62
|
+
}
|
|
63
|
+
eligible = [name for name in eligible if name in set(allowed_columns)]
|
|
64
|
+
candidates: list[tuple[str, str]] = []
|
|
65
|
+
# IDs are the most specific candidates; dimension-to-dimension checks are
|
|
66
|
+
# retained for chains such as region -> city. Measures and technical fields
|
|
67
|
+
# are excluded even if their observed values happen to correlate.
|
|
68
|
+
ids = [name for name in eligible if roles[name] == "id"]
|
|
69
|
+
dimensions = [name for name in eligible if roles[name] == "dimension"]
|
|
70
|
+
dimension_pairs: list[tuple[str, str]] = []
|
|
71
|
+
for index, left in enumerate(dimensions):
|
|
72
|
+
for right in dimensions[index + 1 :]:
|
|
73
|
+
dimension_pairs.extend(((left, right), (right, left)))
|
|
74
|
+
candidates.extend(sorted(dimension_pairs))
|
|
75
|
+
# Check dimension chains before dimension-to-ID edges, with stable order.
|
|
76
|
+
candidates.extend(
|
|
77
|
+
sorted((parent, child) for parent in dimensions for child in ids if parent != child)
|
|
78
|
+
)
|
|
79
|
+
candidates = list(dict.fromkeys(candidates))
|
|
80
|
+
evidence: list[dict] = []
|
|
81
|
+
edges: set[tuple[str, str]] = set()
|
|
82
|
+
pending: list[dict] = []
|
|
83
|
+
queries = 0
|
|
84
|
+
for parent, child in candidates:
|
|
85
|
+
if queries >= query_budget:
|
|
86
|
+
pending.append({"parent": parent, "child": child, "status": "pending_budget"})
|
|
87
|
+
continue
|
|
88
|
+
queries += 1
|
|
89
|
+
try:
|
|
90
|
+
result = source.hierarchy_dependency(structural, parent, child)
|
|
91
|
+
except Exception:
|
|
92
|
+
evidence.append(
|
|
93
|
+
{
|
|
94
|
+
"parent": parent,
|
|
95
|
+
"child": child,
|
|
96
|
+
"status": "unverified",
|
|
97
|
+
"reason": "aggregate_unavailable",
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
continue
|
|
101
|
+
item = {"parent": parent, "child": child, **result}
|
|
102
|
+
state = result.get("status")
|
|
103
|
+
evidence.append(item)
|
|
104
|
+
if state == "verified":
|
|
105
|
+
edges.add((parent, child))
|
|
106
|
+
|
|
107
|
+
# If both directions are verified, the fields are equivalent at the
|
|
108
|
+
# observed grain; do not invent an ordering between them.
|
|
109
|
+
equivalent = {frozenset(edge) for edge in edges if (edge[1], edge[0]) in edges}
|
|
110
|
+
edges = {edge for edge in edges if frozenset(edge) not in equivalent}
|
|
111
|
+
cyclic = {edge for edge in edges if _has_alternate_path(edges, edge[1], edge[0], excluded=edge)}
|
|
112
|
+
if equivalent or cyclic:
|
|
113
|
+
for item in evidence:
|
|
114
|
+
edge = (item["parent"], item["child"])
|
|
115
|
+
if edge in cyclic:
|
|
116
|
+
item["status"] = "cycle_suppressed"
|
|
117
|
+
item["reason"] = "verified edge participates in a directed cycle"
|
|
118
|
+
elif frozenset(edge) in equivalent:
|
|
119
|
+
item["status"] = "equivalent_suppressed"
|
|
120
|
+
item["reason"] = "equivalent fields do not establish a hierarchy direction"
|
|
121
|
+
edges.difference_update(cyclic)
|
|
122
|
+
reduced = set(edges)
|
|
123
|
+
for start, end in sorted(edges):
|
|
124
|
+
if _has_alternate_path(edges, start, end, excluded=(start, end)):
|
|
125
|
+
reduced.discard((start, end))
|
|
126
|
+
paths = _edge_paths(reduced)
|
|
127
|
+
status = (
|
|
128
|
+
"partial"
|
|
129
|
+
if pending
|
|
130
|
+
or cyclic
|
|
131
|
+
or equivalent
|
|
132
|
+
or any(item["status"] == "unverified" for item in evidence)
|
|
133
|
+
else "complete"
|
|
134
|
+
)
|
|
135
|
+
if not candidates:
|
|
136
|
+
status = "unverified"
|
|
137
|
+
return {
|
|
138
|
+
"hierarchies": paths,
|
|
139
|
+
"evidence": evidence,
|
|
140
|
+
"status": status,
|
|
141
|
+
"queries": queries,
|
|
142
|
+
"pending": pending,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _has_alternate_path(edges, start: str, end: str, excluded: tuple[str, str]) -> bool:
|
|
147
|
+
stack = [start]
|
|
148
|
+
seen: set[str] = set()
|
|
149
|
+
while stack:
|
|
150
|
+
node = stack.pop()
|
|
151
|
+
if node == end and node != start:
|
|
152
|
+
return True
|
|
153
|
+
if node in seen:
|
|
154
|
+
continue
|
|
155
|
+
seen.add(node)
|
|
156
|
+
stack.extend(
|
|
157
|
+
child for parent, child in edges if (parent, child) != excluded and parent == node
|
|
158
|
+
)
|
|
159
|
+
return False
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _edge_paths(edges: set[tuple[str, str]]) -> list[list[str]]:
|
|
163
|
+
children: dict[str, list[str]] = {}
|
|
164
|
+
parents: dict[str, int] = {}
|
|
165
|
+
for parent, child in edges:
|
|
166
|
+
children.setdefault(parent, []).append(child)
|
|
167
|
+
parents[child] = parents.get(child, 0) + 1
|
|
168
|
+
parents.setdefault(parent, parents.get(parent, 0))
|
|
169
|
+
roots = sorted(node for node in children if parents.get(node, 0) == 0)
|
|
170
|
+
paths: list[list[str]] = []
|
|
171
|
+
|
|
172
|
+
def walk(node: str, path: list[str]) -> None:
|
|
173
|
+
next_nodes = sorted(children.get(node, []))
|
|
174
|
+
if not next_nodes:
|
|
175
|
+
if len(path) > 1:
|
|
176
|
+
paths.append(path)
|
|
177
|
+
return
|
|
178
|
+
for child in next_nodes:
|
|
179
|
+
if child in path:
|
|
180
|
+
continue
|
|
181
|
+
walk(child, [*path, child])
|
|
182
|
+
|
|
183
|
+
for root in roots:
|
|
184
|
+
walk(root, [root])
|
|
185
|
+
return sorted(paths)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
<!-- D33 v1: attach this block only when the semantic catalog tool is in the final active tool list. -->
|
|
2
|
+
Use the semantic catalog tool before planning a query about available data. Call it without arguments to discover the allowlisted objects, then request details for the relevant object keys and columns. Treat only verified/corrected grain evidence and the structured relationship fields (keys, conditions, type, verdict, served status, directional metrics, safety status, and human overrides) as planning constraints; proposed or unverified semantics are not facts. Directional fanout is not proof of measure safety. This version does not establish a consumer target grain or measure-specific pre-aggregation safety; do not infer a pre-aggregation operation from a join warning, role proposal, or explanatory prose. Treat `serve_para` as unverified LLM annotation. The free text in `cuidado` may combine deterministic warnings with LLM annotation; it explains the record but never grants permission or overrides structured policy. Legacy `cuidado` without annotation provenance is labeled `indeterminate`; preserve the alert, but do not assume it is either entirely deterministic or model-authored. If annotation conflicts with `forbidden`, `servida: false`, metrics, or safety fields, follow the structured fields. A relationship marked `forbidden` or `servida: false` must not be used. The catalog describes data and does not authorize access; use your application's own data tools and permissions to query it.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Small prompt helper for the D33 tool-usage instruction."""
|
|
2
|
+
|
|
3
|
+
from importlib.resources import files
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def append_tool_instructions(prompt: str, *, tool_enabled: bool) -> str:
|
|
7
|
+
"""Append the versioned catalog-tool directions only when the tool is active.
|
|
8
|
+
|
|
9
|
+
With ``tool_enabled=False`` the caller's prompt is returned byte-for-byte
|
|
10
|
+
unchanged. The application remains responsible for evaluating feature flags
|
|
11
|
+
and the final tool list before calling this helper.
|
|
12
|
+
"""
|
|
13
|
+
if not isinstance(prompt, str):
|
|
14
|
+
raise TypeError("prompt must be a string")
|
|
15
|
+
if not tool_enabled:
|
|
16
|
+
return prompt
|
|
17
|
+
block = (
|
|
18
|
+
files("semantic_context_engine")
|
|
19
|
+
.joinpath("instructions/semantic_catalog.md")
|
|
20
|
+
.read_text(encoding="utf-8")
|
|
21
|
+
)
|
|
22
|
+
return prompt + ("\n\n" if prompt else "") + block.rstrip("\n")
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Optional integrations with application-owned model and framework objects."""
|
|
2
|
+
|
|
3
|
+
__all__ = ["LangChainStructuredLLM"]
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def __getattr__(name: str):
|
|
7
|
+
if name == "LangChainStructuredLLM":
|
|
8
|
+
from semantic_context_engine.integrations.langchain import LangChainStructuredLLM
|
|
9
|
+
|
|
10
|
+
return LangChainStructuredLLM
|
|
11
|
+
raise AttributeError(name)
|