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,1193 @@
|
|
|
1
|
+
"""Read-only runtime catalog view over a published namespace."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import threading
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
from functools import wraps
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from semantic_context_engine.registry import Registry
|
|
14
|
+
from semantic_context_engine.errors import safe_error_label
|
|
15
|
+
from semantic_context_engine.models import StructuralSnapshot
|
|
16
|
+
from semantic_context_engine.relations import (
|
|
17
|
+
measure_guidance_signature,
|
|
18
|
+
suppress_unverified_preaggregation_advice,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _llm_annotations_status(rel: dict) -> str:
|
|
23
|
+
"""Expose relation prose as explicitly non-authoritative metadata.
|
|
24
|
+
|
|
25
|
+
Legacy catalogs may have concatenated model-authored caution with
|
|
26
|
+
deterministic warnings and lack an origin marker. Keep that prose intact,
|
|
27
|
+
but do not claim it is absent or classify it as model-authored with
|
|
28
|
+
certainty.
|
|
29
|
+
"""
|
|
30
|
+
marker = rel.get("llm_annotations_status")
|
|
31
|
+
if marker == "unverified" or rel.get("answers"):
|
|
32
|
+
return "unverified"
|
|
33
|
+
if marker == "not_provided":
|
|
34
|
+
return "not_provided"
|
|
35
|
+
caution = rel.get("caution")
|
|
36
|
+
if isinstance(caution, str) and caution.strip() and rel.get("origin") != "override":
|
|
37
|
+
return "indeterminate"
|
|
38
|
+
return "not_provided"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _verified_hierarchy_details(paths, evidence, valid_columns: set[str]) -> list[dict[str, Any]]:
|
|
42
|
+
"""Keep runtime paths only when every edge has non-vacuous verified evidence."""
|
|
43
|
+
if not isinstance(paths, list) or not isinstance(evidence, list):
|
|
44
|
+
return []
|
|
45
|
+
details = []
|
|
46
|
+
for path in paths:
|
|
47
|
+
if (
|
|
48
|
+
not isinstance(path, list)
|
|
49
|
+
or len(path) < 2
|
|
50
|
+
or any(not isinstance(node, str) or node not in valid_columns for node in path)
|
|
51
|
+
or len(set(path)) != len(path)
|
|
52
|
+
):
|
|
53
|
+
continue
|
|
54
|
+
edges: list[dict[str, Any]] = []
|
|
55
|
+
for parent, child in zip(path, path[1:]):
|
|
56
|
+
matches = [
|
|
57
|
+
row
|
|
58
|
+
for row in evidence
|
|
59
|
+
if isinstance(row, dict)
|
|
60
|
+
and row.get("parent") == parent
|
|
61
|
+
and row.get("child") == child
|
|
62
|
+
]
|
|
63
|
+
if not matches or any(
|
|
64
|
+
row.get("status") != "verified"
|
|
65
|
+
or not isinstance(row.get("rows"), int)
|
|
66
|
+
or row.get("rows", 0) <= 0
|
|
67
|
+
or not isinstance(row.get("child_groups"), int)
|
|
68
|
+
or row.get("child_groups", 0) <= 1
|
|
69
|
+
or not isinstance(row.get("parent_values"), int)
|
|
70
|
+
or row.get("parent_values", 0) <= 1
|
|
71
|
+
or row.get("violating_child_groups", 0) != 0
|
|
72
|
+
for row in matches
|
|
73
|
+
):
|
|
74
|
+
edges = []
|
|
75
|
+
break
|
|
76
|
+
edges.extend(dict(row) for row in matches)
|
|
77
|
+
if edges:
|
|
78
|
+
details.append({"path": list(path), "status": "verified", "edges": edges})
|
|
79
|
+
return details
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _coverage_slices_complete(slices: Any, expected_count: Any) -> bool:
|
|
83
|
+
"""Treat ambiguous or duplicate slice identities as incomplete evidence."""
|
|
84
|
+
if type(expected_count) is not int or expected_count <= 0:
|
|
85
|
+
return False
|
|
86
|
+
if not isinstance(slices, list) or len(slices) != expected_count:
|
|
87
|
+
return False
|
|
88
|
+
identities: list[str] = []
|
|
89
|
+
for row in slices:
|
|
90
|
+
if not isinstance(row, dict) or not isinstance(row.get("slice"), str):
|
|
91
|
+
return False
|
|
92
|
+
rows = row.get("rows")
|
|
93
|
+
non_null = row.get("non_null")
|
|
94
|
+
if type(rows) is not int or type(non_null) is not int or rows <= 0 or rows != non_null:
|
|
95
|
+
return False
|
|
96
|
+
identities.append(row["slice"])
|
|
97
|
+
return len(identities) == len(set(identities))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _approved_discriminator_domains(fields: dict[str, Any]) -> dict[str, set[str]] | None:
|
|
101
|
+
"""Read all approved discriminator domains from existing policy evidence.
|
|
102
|
+
|
|
103
|
+
Return None when persisted evidence is malformed or contradictory. These
|
|
104
|
+
allowlists already exist in discriminator grain evidence; formula coverage
|
|
105
|
+
must not persist another copy.
|
|
106
|
+
"""
|
|
107
|
+
source_rows = fields.get("discriminator_grain_evidence", [])
|
|
108
|
+
if not isinstance(source_rows, list):
|
|
109
|
+
return None
|
|
110
|
+
domains: dict[str, set[str]] = {}
|
|
111
|
+
for row in source_rows:
|
|
112
|
+
if not isinstance(row, dict):
|
|
113
|
+
return None
|
|
114
|
+
discriminator = row.get("discriminator")
|
|
115
|
+
values = row.get("approved_values")
|
|
116
|
+
if (
|
|
117
|
+
not isinstance(discriminator, str)
|
|
118
|
+
or not discriminator
|
|
119
|
+
or not isinstance(values, list)
|
|
120
|
+
or not values
|
|
121
|
+
or any(not isinstance(value, str) for value in values)
|
|
122
|
+
or len(values) != len(set(values))
|
|
123
|
+
):
|
|
124
|
+
return None
|
|
125
|
+
domain = set(values)
|
|
126
|
+
if discriminator in domains and domains[discriminator] != domain:
|
|
127
|
+
return None
|
|
128
|
+
domains[discriminator] = domain
|
|
129
|
+
return domains
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _approved_slice_identities(fields: dict[str, Any], discriminator: str) -> set[str] | None:
|
|
133
|
+
"""Return one approved domain, or None if persisted evidence is ambiguous."""
|
|
134
|
+
domains = _approved_discriminator_domains(fields)
|
|
135
|
+
return domains.get(discriminator) if domains is not None else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _safe_formula_coverage(fields: dict[str, Any], valid_columns: set[str]) -> list[dict[str, Any]]:
|
|
139
|
+
"""Project persisted coverage without exposing unapproved slice values."""
|
|
140
|
+
source_rows = fields.get("formula_coverage", [])
|
|
141
|
+
if not isinstance(source_rows, list):
|
|
142
|
+
return []
|
|
143
|
+
safe_rows = []
|
|
144
|
+
for row in source_rows:
|
|
145
|
+
if not isinstance(row, dict):
|
|
146
|
+
continue
|
|
147
|
+
column = row.get("column")
|
|
148
|
+
discriminator = row.get("discriminator")
|
|
149
|
+
if (
|
|
150
|
+
not isinstance(column, str)
|
|
151
|
+
or column not in valid_columns
|
|
152
|
+
or not isinstance(discriminator, str)
|
|
153
|
+
or discriminator not in valid_columns
|
|
154
|
+
):
|
|
155
|
+
continue
|
|
156
|
+
approved = _approved_slice_identities(fields, discriminator)
|
|
157
|
+
slices = row.get("slices")
|
|
158
|
+
safe_slices = []
|
|
159
|
+
invalid_identity = approved is None or not isinstance(slices, list)
|
|
160
|
+
seen: set[str] = set()
|
|
161
|
+
if isinstance(slices, list):
|
|
162
|
+
for item in slices:
|
|
163
|
+
if not isinstance(item, dict):
|
|
164
|
+
invalid_identity = True
|
|
165
|
+
continue
|
|
166
|
+
identity = item.get("slice")
|
|
167
|
+
if (
|
|
168
|
+
not isinstance(identity, str)
|
|
169
|
+
or approved is None
|
|
170
|
+
or identity not in approved
|
|
171
|
+
or identity in seen
|
|
172
|
+
):
|
|
173
|
+
invalid_identity = True
|
|
174
|
+
continue
|
|
175
|
+
seen.add(identity)
|
|
176
|
+
safe_item: dict[str, Any] = {"slice": identity}
|
|
177
|
+
for count_key in ("rows", "non_null"):
|
|
178
|
+
count = item.get(count_key)
|
|
179
|
+
if type(count) is int and count >= 0:
|
|
180
|
+
safe_item[count_key] = count
|
|
181
|
+
else:
|
|
182
|
+
invalid_identity = True
|
|
183
|
+
safe_slices.append(safe_item)
|
|
184
|
+
expected_count = row.get("expected_slice_count")
|
|
185
|
+
status = row.get("status")
|
|
186
|
+
if status == "measured" and approved is not None and seen != approved:
|
|
187
|
+
invalid_identity = True
|
|
188
|
+
safe_row: dict[str, Any] = {
|
|
189
|
+
"column": column,
|
|
190
|
+
"discriminator": discriminator,
|
|
191
|
+
"status": (
|
|
192
|
+
status
|
|
193
|
+
if isinstance(status, str)
|
|
194
|
+
and status in {"measured", "unverified", "unsupported"}
|
|
195
|
+
and not invalid_identity
|
|
196
|
+
else "unverified"
|
|
197
|
+
),
|
|
198
|
+
"slices": safe_slices,
|
|
199
|
+
}
|
|
200
|
+
if type(expected_count) is int and expected_count >= 0:
|
|
201
|
+
safe_row["expected_slice_count"] = expected_count
|
|
202
|
+
safe_rows.append(safe_row)
|
|
203
|
+
grouped_indices: dict[tuple[str, str], list[int]] = defaultdict(list)
|
|
204
|
+
for index, row in enumerate(safe_rows):
|
|
205
|
+
grouped_indices[(row["column"], row["discriminator"])].append(index)
|
|
206
|
+
duplicate_indices: set[int] = set()
|
|
207
|
+
for indices in grouped_indices.values():
|
|
208
|
+
if len(indices) < 2:
|
|
209
|
+
continue
|
|
210
|
+
signatures = [
|
|
211
|
+
(
|
|
212
|
+
safe_rows[index]["status"],
|
|
213
|
+
safe_rows[index].get("expected_slice_count"),
|
|
214
|
+
safe_rows[index]["slices"],
|
|
215
|
+
)
|
|
216
|
+
for index in indices
|
|
217
|
+
]
|
|
218
|
+
if any(signature != signatures[0] for signature in signatures[1:]):
|
|
219
|
+
for index in indices:
|
|
220
|
+
safe_rows[index]["status"] = "unverified"
|
|
221
|
+
safe_rows[index]["slices"] = []
|
|
222
|
+
else:
|
|
223
|
+
duplicate_indices.update(indices[1:])
|
|
224
|
+
return [row for index, row in enumerate(safe_rows) if index not in duplicate_indices]
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _synchronized(method):
|
|
228
|
+
@wraps(method)
|
|
229
|
+
def wrapper(self, *args, **kwargs):
|
|
230
|
+
with self._lock:
|
|
231
|
+
return method(self, *args, **kwargs)
|
|
232
|
+
|
|
233
|
+
return wrapper
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class RuntimeView:
|
|
237
|
+
"""Cached, read-only catalog view. It never creates directories or writes."""
|
|
238
|
+
|
|
239
|
+
def __init__(
|
|
240
|
+
self,
|
|
241
|
+
storage,
|
|
242
|
+
namespace: str,
|
|
243
|
+
ttl_seconds: int = 600,
|
|
244
|
+
*,
|
|
245
|
+
scope=None,
|
|
246
|
+
payload_budget_bytes: int = 65536,
|
|
247
|
+
):
|
|
248
|
+
if isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, int) or ttl_seconds < 0:
|
|
249
|
+
raise ValueError("ttl_seconds must be a non-negative integer")
|
|
250
|
+
if scope is not None and (
|
|
251
|
+
not isinstance(scope, (list, tuple, set, frozenset))
|
|
252
|
+
or any(not isinstance(key, str) for key in scope)
|
|
253
|
+
):
|
|
254
|
+
raise ValueError("scope must be a collection of catalog keys")
|
|
255
|
+
if (
|
|
256
|
+
isinstance(payload_budget_bytes, bool)
|
|
257
|
+
or not isinstance(payload_budget_bytes, int)
|
|
258
|
+
or payload_budget_bytes < 256
|
|
259
|
+
):
|
|
260
|
+
raise ValueError("payload_budget_bytes must be an integer of at least 256")
|
|
261
|
+
self._scope: frozenset[str] | None = None if scope is None else frozenset(scope)
|
|
262
|
+
self._payload_budget_bytes = payload_budget_bytes
|
|
263
|
+
self._lock = threading.RLock()
|
|
264
|
+
self._registry = Registry(storage, namespace)
|
|
265
|
+
self._ttl = ttl_seconds
|
|
266
|
+
self._loaded_at = 0.0
|
|
267
|
+
self._snapshot: StructuralSnapshot | None = None
|
|
268
|
+
self._semantic: dict[str, Any] = {}
|
|
269
|
+
self._overrides: dict[str, Any] = {"schema_version": 1, "relationships": []}
|
|
270
|
+
self._stale = False
|
|
271
|
+
self._catalog_version: str | None = None
|
|
272
|
+
self._override_revision: str | None = None
|
|
273
|
+
|
|
274
|
+
@classmethod
|
|
275
|
+
def from_storage(cls, storage, namespace: str, ttl_seconds: int = 600, **kwargs):
|
|
276
|
+
return cls(storage, namespace, ttl_seconds, **kwargs)
|
|
277
|
+
|
|
278
|
+
@_synchronized
|
|
279
|
+
def _refresh(self):
|
|
280
|
+
now = time.monotonic()
|
|
281
|
+
try:
|
|
282
|
+
# Revisions are checked on every call, even inside the TTL, so a
|
|
283
|
+
# human override cannot remain hidden behind a warm cache.
|
|
284
|
+
pointer = self._registry.read_active_pointer()
|
|
285
|
+
if pointer is None:
|
|
286
|
+
raise FileNotFoundError("No active catalog snapshot")
|
|
287
|
+
version = pointer["version"]
|
|
288
|
+
override_revision = self._registry.override_revision()
|
|
289
|
+
same_bundle = (
|
|
290
|
+
self._snapshot is not None
|
|
291
|
+
and self._catalog_version == version
|
|
292
|
+
and self._override_revision == override_revision
|
|
293
|
+
)
|
|
294
|
+
if same_bundle and now - self._loaded_at < self._ttl:
|
|
295
|
+
self._stale = False
|
|
296
|
+
return True, None
|
|
297
|
+
snapshot = self._registry.load_active(pointer=pointer)
|
|
298
|
+
if snapshot is None:
|
|
299
|
+
raise FileNotFoundError("No active catalog snapshot")
|
|
300
|
+
semantic = self._registry.load_semantic(snapshot.version)
|
|
301
|
+
overrides = self._registry.load_overrides()
|
|
302
|
+
# Do not cache a mixed generation if publication or human edits
|
|
303
|
+
# raced the reads. Retry on the next call instead.
|
|
304
|
+
if (self._registry.read_active_pointer() or {}).get(
|
|
305
|
+
"version"
|
|
306
|
+
) != version or self._registry.override_revision() != override_revision:
|
|
307
|
+
raise RuntimeError("Catalog changed during refresh")
|
|
308
|
+
self._snapshot, self._semantic, self._overrides = (
|
|
309
|
+
snapshot,
|
|
310
|
+
semantic,
|
|
311
|
+
overrides,
|
|
312
|
+
)
|
|
313
|
+
self._catalog_version, self._override_revision = version, override_revision
|
|
314
|
+
self._loaded_at = now
|
|
315
|
+
self._stale = False
|
|
316
|
+
return True, None
|
|
317
|
+
except Exception:
|
|
318
|
+
if self._snapshot is not None:
|
|
319
|
+
self._stale = True
|
|
320
|
+
return True, "catalog_storage_unavailable; serving cached snapshot"
|
|
321
|
+
return False, "catalog_unavailable (storage_unavailable)"
|
|
322
|
+
|
|
323
|
+
@_synchronized
|
|
324
|
+
def index(self):
|
|
325
|
+
ok, reason = self._refresh()
|
|
326
|
+
if not ok:
|
|
327
|
+
return {"disponivel": False, "motivo": reason}
|
|
328
|
+
snapshot = self._snapshot
|
|
329
|
+
assert snapshot is not None
|
|
330
|
+
object_overrides = self._object_overrides()
|
|
331
|
+
return [
|
|
332
|
+
{
|
|
333
|
+
"chave": key,
|
|
334
|
+
"tabela": obj.fqn,
|
|
335
|
+
"descricao": object_overrides.get(key, {}).get("description")
|
|
336
|
+
or self._entity(key).get("description")
|
|
337
|
+
or obj.description
|
|
338
|
+
or obj.hint
|
|
339
|
+
or "",
|
|
340
|
+
}
|
|
341
|
+
for key, obj in snapshot.objects.items()
|
|
342
|
+
if self._scope is None or key in self._scope
|
|
343
|
+
]
|
|
344
|
+
|
|
345
|
+
@_synchronized
|
|
346
|
+
def detail(self, objects, columns=None):
|
|
347
|
+
ok, reason = self._refresh()
|
|
348
|
+
if not ok:
|
|
349
|
+
return {"disponivel": False, "motivo": reason}
|
|
350
|
+
snapshot = self._snapshot
|
|
351
|
+
assert snapshot is not None
|
|
352
|
+
if not isinstance(objects, (list, tuple)) or not 1 <= len(objects) <= 3:
|
|
353
|
+
return {"disponivel": False, "motivo": "Informe de 1 a 3 objetos."}
|
|
354
|
+
if any(not isinstance(key, str) for key in objects):
|
|
355
|
+
return {
|
|
356
|
+
"disponivel": False,
|
|
357
|
+
"motivo": "As chaves de objeto devem ser texto.",
|
|
358
|
+
}
|
|
359
|
+
if len(set(objects)) != len(objects):
|
|
360
|
+
return {
|
|
361
|
+
"disponivel": False,
|
|
362
|
+
"motivo": "Objetos duplicados não são aceitos.",
|
|
363
|
+
}
|
|
364
|
+
if self._scope is not None and not set(objects) <= self._scope:
|
|
365
|
+
return {"disponivel": False, "motivo": "Objeto fora do escopo configurado."}
|
|
366
|
+
missing = [key for key in objects if key not in snapshot.objects]
|
|
367
|
+
if missing:
|
|
368
|
+
return {
|
|
369
|
+
"disponivel": False,
|
|
370
|
+
"motivo": "Objeto ausente no catálogo: " + ", ".join(missing),
|
|
371
|
+
}
|
|
372
|
+
if columns is not None and (
|
|
373
|
+
not isinstance(columns, (list, tuple)) or any(not isinstance(c, str) for c in columns)
|
|
374
|
+
):
|
|
375
|
+
return {
|
|
376
|
+
"disponivel": False,
|
|
377
|
+
"motivo": "colunas deve ser uma lista de nomes.",
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
conflicts = []
|
|
381
|
+
details = []
|
|
382
|
+
for key in objects:
|
|
383
|
+
obj = snapshot.objects[key]
|
|
384
|
+
entity = self._entity(key)
|
|
385
|
+
override = self._object_overrides().get(key, {})
|
|
386
|
+
fields = dict(entity)
|
|
387
|
+
# Human edits replace inferred values only after their references
|
|
388
|
+
# are checked against the active structural snapshot.
|
|
389
|
+
for field in ("description", "grain", "time_column", "limitations"):
|
|
390
|
+
if field not in override:
|
|
391
|
+
continue
|
|
392
|
+
refs = (
|
|
393
|
+
override[field]
|
|
394
|
+
if field == "grain"
|
|
395
|
+
else ([override[field]] if field == "time_column" else [])
|
|
396
|
+
)
|
|
397
|
+
bad = [ref for ref in refs if ref not in obj.columns]
|
|
398
|
+
if bad:
|
|
399
|
+
conflicts.append(
|
|
400
|
+
{
|
|
401
|
+
"override_id": key,
|
|
402
|
+
"field": field,
|
|
403
|
+
"reason": "column_reference_missing",
|
|
404
|
+
}
|
|
405
|
+
)
|
|
406
|
+
else:
|
|
407
|
+
fields[field] = override[field]
|
|
408
|
+
semantic_columns = {
|
|
409
|
+
item.get("name"): dict(item)
|
|
410
|
+
for item in entity.get("columns", [])
|
|
411
|
+
if isinstance(item, dict) and isinstance(item.get("name"), str)
|
|
412
|
+
}
|
|
413
|
+
for unknown_column in set(override.get("columns", {})) - set(obj.columns):
|
|
414
|
+
conflicts.append(
|
|
415
|
+
{
|
|
416
|
+
"override_id": key,
|
|
417
|
+
"column": unknown_column,
|
|
418
|
+
"field": "column_override",
|
|
419
|
+
"reason": "column_reference_missing",
|
|
420
|
+
}
|
|
421
|
+
)
|
|
422
|
+
requested = set(columns or [])
|
|
423
|
+
families = {
|
|
424
|
+
family: list(names)
|
|
425
|
+
for family, names in fields.get("families", {}).items()
|
|
426
|
+
if isinstance(family, str) and isinstance(names, list)
|
|
427
|
+
}
|
|
428
|
+
out = {
|
|
429
|
+
"chave": key,
|
|
430
|
+
"tabela": obj.fqn,
|
|
431
|
+
"grao": fields.get("grain", []),
|
|
432
|
+
"coluna_tempo": fields.get("time_column"),
|
|
433
|
+
"limitacoes": fields.get("limitations", []),
|
|
434
|
+
"colunas_por_familia": families,
|
|
435
|
+
}
|
|
436
|
+
columns_out = []
|
|
437
|
+
for name, meta in obj.columns.items():
|
|
438
|
+
sm = semantic_columns.get(name, {})
|
|
439
|
+
co = override.get("columns", {}).get(name, {})
|
|
440
|
+
old_family = sm.get("family")
|
|
441
|
+
new_family = co.get("family", old_family)
|
|
442
|
+
if old_family and old_family != new_family and old_family in families:
|
|
443
|
+
families[old_family] = [col for col in families[old_family] if col != name]
|
|
444
|
+
if new_family:
|
|
445
|
+
families.setdefault(new_family, [])
|
|
446
|
+
if name not in families[new_family]:
|
|
447
|
+
families[new_family].append(name)
|
|
448
|
+
merged = {
|
|
449
|
+
"coluna": name,
|
|
450
|
+
"tipo": meta.data_type,
|
|
451
|
+
"papel": co.get("role", sm.get("role")),
|
|
452
|
+
"familia": co.get("family", sm.get("family")),
|
|
453
|
+
}
|
|
454
|
+
merged["formula_proposals"] = sm.get("formula_proposals", [])
|
|
455
|
+
# Old persisted model output may contain operand lists without
|
|
456
|
+
# explicit proposal metadata. Expose that only as an unknown,
|
|
457
|
+
# unapproved proposal; never promote it to human approval.
|
|
458
|
+
legacy_refs = sm.get("recompute_from", [])
|
|
459
|
+
if (
|
|
460
|
+
not merged["formula_proposals"]
|
|
461
|
+
and isinstance(legacy_refs, list)
|
|
462
|
+
and legacy_refs
|
|
463
|
+
):
|
|
464
|
+
merged["formula_proposals"] = [
|
|
465
|
+
{
|
|
466
|
+
"operator": "unknown",
|
|
467
|
+
"operands": list(legacy_refs),
|
|
468
|
+
"proposal_status": "proposed",
|
|
469
|
+
"schema_status": "not_checked",
|
|
470
|
+
"coverage_status": "not_checked",
|
|
471
|
+
"numerical_evidence_status": "not_measured",
|
|
472
|
+
"approval_status": "not_approved",
|
|
473
|
+
}
|
|
474
|
+
]
|
|
475
|
+
raw_formula = co.get("formula")
|
|
476
|
+
formula = raw_formula if isinstance(raw_formula, dict) else {}
|
|
477
|
+
has_human_formula = bool(formula) or bool(co.get("recompute_from"))
|
|
478
|
+
reference_definitions: list[Any] = []
|
|
479
|
+
for owner, field_name in (
|
|
480
|
+
(formula, "operands"),
|
|
481
|
+
(formula, "recompute_from"),
|
|
482
|
+
(co, "recompute_from"),
|
|
483
|
+
):
|
|
484
|
+
if field_name in owner and owner[field_name] is not None:
|
|
485
|
+
reference_definitions.append(owner[field_name])
|
|
486
|
+
refs = reference_definitions[0] if reference_definitions else []
|
|
487
|
+
references_consistent = all(
|
|
488
|
+
candidate == refs for candidate in reference_definitions[1:]
|
|
489
|
+
)
|
|
490
|
+
expression = formula.get("expression")
|
|
491
|
+
aggregation = formula.get("aggregation")
|
|
492
|
+
explicit_operator = formula.get("operator", "unknown")
|
|
493
|
+
if has_human_formula:
|
|
494
|
+
valid_refs = (
|
|
495
|
+
references_consistent
|
|
496
|
+
and isinstance(refs, list)
|
|
497
|
+
and bool(refs)
|
|
498
|
+
and all(isinstance(ref, str) for ref in refs)
|
|
499
|
+
and len(refs) == len(set(refs))
|
|
500
|
+
and all(
|
|
501
|
+
isinstance(ref, str)
|
|
502
|
+
and ref in obj.columns
|
|
503
|
+
and ref != name
|
|
504
|
+
and any(
|
|
505
|
+
kind in obj.columns[ref].data_type.upper()
|
|
506
|
+
for kind in (
|
|
507
|
+
"INT",
|
|
508
|
+
"DECIMAL",
|
|
509
|
+
"NUMERIC",
|
|
510
|
+
"NUMBER",
|
|
511
|
+
"FLOAT",
|
|
512
|
+
"DOUBLE",
|
|
513
|
+
"REAL",
|
|
514
|
+
)
|
|
515
|
+
)
|
|
516
|
+
and override.get("columns", {})
|
|
517
|
+
.get(ref, {})
|
|
518
|
+
.get("role", semantic_columns.get(ref, {}).get("role"))
|
|
519
|
+
== "additive_measure"
|
|
520
|
+
for ref in refs
|
|
521
|
+
)
|
|
522
|
+
)
|
|
523
|
+
operator_is_supported = isinstance(
|
|
524
|
+
explicit_operator, str
|
|
525
|
+
) and explicit_operator in {
|
|
526
|
+
"sum",
|
|
527
|
+
"ratio_of_sums",
|
|
528
|
+
"unknown",
|
|
529
|
+
}
|
|
530
|
+
aggregation_is_supported = (
|
|
531
|
+
aggregation
|
|
532
|
+
in {
|
|
533
|
+
None,
|
|
534
|
+
"additive",
|
|
535
|
+
"ratio_of_sums",
|
|
536
|
+
"non_additive",
|
|
537
|
+
}
|
|
538
|
+
if aggregation is None or isinstance(aggregation, str)
|
|
539
|
+
else False
|
|
540
|
+
)
|
|
541
|
+
effective_operator = (
|
|
542
|
+
explicit_operator if isinstance(explicit_operator, str) else "invalid"
|
|
543
|
+
)
|
|
544
|
+
if effective_operator == "unknown":
|
|
545
|
+
if aggregation == "additive":
|
|
546
|
+
effective_operator = "sum"
|
|
547
|
+
elif aggregation == "ratio_of_sums":
|
|
548
|
+
effective_operator = "ratio_of_sums"
|
|
549
|
+
operator_aggregation = {
|
|
550
|
+
"sum": "additive",
|
|
551
|
+
"ratio_of_sums": "ratio_of_sums",
|
|
552
|
+
}.get(effective_operator)
|
|
553
|
+
operator_consistent = (
|
|
554
|
+
operator_is_supported
|
|
555
|
+
and aggregation_is_supported
|
|
556
|
+
and (
|
|
557
|
+
operator_aggregation is None
|
|
558
|
+
or aggregation is None
|
|
559
|
+
or aggregation == operator_aggregation
|
|
560
|
+
)
|
|
561
|
+
)
|
|
562
|
+
reference_count = len(refs) if isinstance(refs, list) else -1
|
|
563
|
+
operator_arity_valid = (
|
|
564
|
+
effective_operator == "unknown"
|
|
565
|
+
or (effective_operator == "sum" and reference_count == 1)
|
|
566
|
+
or (effective_operator == "ratio_of_sums" and reference_count == 2)
|
|
567
|
+
)
|
|
568
|
+
effective_aggregation = aggregation or operator_aggregation
|
|
569
|
+
valid_aggregation = False
|
|
570
|
+
match = None
|
|
571
|
+
if (
|
|
572
|
+
effective_operator == "ratio_of_sums"
|
|
573
|
+
and operator_consistent
|
|
574
|
+
and operator_arity_valid
|
|
575
|
+
):
|
|
576
|
+
match = re.fullmatch(
|
|
577
|
+
r"\s*SUM\s*\(\s*([A-Za-z_][\w$]*)\s*\)\s*/\s*SUM\s*\(\s*([A-Za-z_][\w$]*)\s*\)\s*",
|
|
578
|
+
expression or "",
|
|
579
|
+
re.I,
|
|
580
|
+
)
|
|
581
|
+
valid_aggregation = (
|
|
582
|
+
effective_aggregation == "ratio_of_sums"
|
|
583
|
+
and len(refs) == 2
|
|
584
|
+
and match is not None
|
|
585
|
+
and list(match.groups()) == refs
|
|
586
|
+
)
|
|
587
|
+
elif (
|
|
588
|
+
effective_operator == "sum" and operator_consistent and operator_arity_valid
|
|
589
|
+
):
|
|
590
|
+
match = (
|
|
591
|
+
re.fullmatch(
|
|
592
|
+
r"\s*SUM\s*\(\s*([A-Za-z_][\w$]*)\s*\)\s*", expression, re.I
|
|
593
|
+
)
|
|
594
|
+
if expression
|
|
595
|
+
else None
|
|
596
|
+
)
|
|
597
|
+
valid_aggregation = (
|
|
598
|
+
effective_aggregation == "additive"
|
|
599
|
+
and len(refs) == 1
|
|
600
|
+
and match is not None
|
|
601
|
+
and match.group(1) == refs[0]
|
|
602
|
+
)
|
|
603
|
+
if (
|
|
604
|
+
valid_refs
|
|
605
|
+
and operator_arity_valid
|
|
606
|
+
and operator_consistent
|
|
607
|
+
and valid_aggregation
|
|
608
|
+
):
|
|
609
|
+
merged["recalcular_de"] = list(refs)
|
|
610
|
+
if effective_operator == "ratio_of_sums" and match is not None:
|
|
611
|
+
# Keep the executable ratio-of-sums contract safe
|
|
612
|
+
# for an empty/zero denominator.
|
|
613
|
+
merged["formula"] = (
|
|
614
|
+
f"SUM({match.group(1)}) / NULLIF(SUM({match.group(2)}), 0)"
|
|
615
|
+
)
|
|
616
|
+
else:
|
|
617
|
+
merged["formula"] = expression
|
|
618
|
+
merged["agregacao"] = effective_aggregation
|
|
619
|
+
merged["formula_status"] = "schema_valid_unverified"
|
|
620
|
+
coverage_rows = [
|
|
621
|
+
item
|
|
622
|
+
for item in fields.get("formula_coverage", [])
|
|
623
|
+
if isinstance(item, dict) and item.get("column") in refs
|
|
624
|
+
]
|
|
625
|
+
measured_rows = [
|
|
626
|
+
item for item in coverage_rows if item.get("status") == "measured"
|
|
627
|
+
]
|
|
628
|
+
approved_domains = _approved_discriminator_domains(fields)
|
|
629
|
+
expected_discriminators = (
|
|
630
|
+
set(approved_domains) if approved_domains is not None else set()
|
|
631
|
+
)
|
|
632
|
+
coverage_complete = bool(refs) and bool(expected_discriminators)
|
|
633
|
+
for ref in refs:
|
|
634
|
+
operand_rows = [
|
|
635
|
+
item for item in coverage_rows if item.get("column") == ref
|
|
636
|
+
]
|
|
637
|
+
for discriminator in expected_discriminators:
|
|
638
|
+
if not isinstance(discriminator, str):
|
|
639
|
+
coverage_complete = False
|
|
640
|
+
continue
|
|
641
|
+
matching_rows = [
|
|
642
|
+
item
|
|
643
|
+
for item in operand_rows
|
|
644
|
+
if item.get("discriminator") == discriminator
|
|
645
|
+
]
|
|
646
|
+
evidence = matching_rows[0] if matching_rows else None
|
|
647
|
+
if len(matching_rows) > 1 and any(
|
|
648
|
+
item != evidence for item in matching_rows[1:]
|
|
649
|
+
):
|
|
650
|
+
coverage_complete = False
|
|
651
|
+
continue
|
|
652
|
+
slices = evidence.get("slices", []) if evidence else []
|
|
653
|
+
expected_count = (
|
|
654
|
+
evidence.get("expected_slice_count") if evidence else None
|
|
655
|
+
)
|
|
656
|
+
approved_ids = (
|
|
657
|
+
approved_domains.get(discriminator)
|
|
658
|
+
if approved_domains is not None
|
|
659
|
+
else None
|
|
660
|
+
)
|
|
661
|
+
slice_ids = (
|
|
662
|
+
{
|
|
663
|
+
item["slice"]
|
|
664
|
+
for item in slices
|
|
665
|
+
if isinstance(item, dict)
|
|
666
|
+
and isinstance(item.get("slice"), str)
|
|
667
|
+
}
|
|
668
|
+
if isinstance(slices, list)
|
|
669
|
+
else set()
|
|
670
|
+
)
|
|
671
|
+
if (
|
|
672
|
+
evidence is None
|
|
673
|
+
or evidence.get("status") != "measured"
|
|
674
|
+
or approved_ids is None
|
|
675
|
+
or not _coverage_slices_complete(slices, expected_count)
|
|
676
|
+
or slice_ids != approved_ids
|
|
677
|
+
):
|
|
678
|
+
coverage_complete = False
|
|
679
|
+
coverage_status = (
|
|
680
|
+
"complete"
|
|
681
|
+
if coverage_complete
|
|
682
|
+
else "partial"
|
|
683
|
+
if measured_rows
|
|
684
|
+
else "unverified"
|
|
685
|
+
)
|
|
686
|
+
merged["formula_contract"] = {
|
|
687
|
+
"operator": effective_operator,
|
|
688
|
+
"operands": list(refs),
|
|
689
|
+
"proposal_status": "proposed",
|
|
690
|
+
"schema_status": "valid",
|
|
691
|
+
"coverage_status": coverage_status,
|
|
692
|
+
"numerical_evidence_status": "not_measured",
|
|
693
|
+
"approval_status": "approved",
|
|
694
|
+
}
|
|
695
|
+
elif valid_refs and not expression:
|
|
696
|
+
# An operand-only override is still a proposal; without
|
|
697
|
+
# a supported operation/expression it is not executable
|
|
698
|
+
# and does not count as approved.
|
|
699
|
+
merged["formula_proposals"] = [
|
|
700
|
+
*merged["formula_proposals"],
|
|
701
|
+
{
|
|
702
|
+
"operator": explicit_operator,
|
|
703
|
+
"operands": list(refs),
|
|
704
|
+
"proposal_status": "proposed",
|
|
705
|
+
"schema_status": (
|
|
706
|
+
"valid"
|
|
707
|
+
if operator_arity_valid and operator_consistent
|
|
708
|
+
else "invalid"
|
|
709
|
+
),
|
|
710
|
+
"coverage_status": "unverified",
|
|
711
|
+
"numerical_evidence_status": "not_measured",
|
|
712
|
+
"approval_status": "not_approved",
|
|
713
|
+
},
|
|
714
|
+
]
|
|
715
|
+
if not operator_arity_valid or not operator_consistent:
|
|
716
|
+
conflicts.append(
|
|
717
|
+
{
|
|
718
|
+
"override_id": key,
|
|
719
|
+
"column": name,
|
|
720
|
+
"field": "formula",
|
|
721
|
+
"reason": "formula_unverified_or_invalid",
|
|
722
|
+
}
|
|
723
|
+
)
|
|
724
|
+
else:
|
|
725
|
+
conflicts.append(
|
|
726
|
+
{
|
|
727
|
+
"override_id": key,
|
|
728
|
+
"column": name,
|
|
729
|
+
"field": "formula",
|
|
730
|
+
"reason": "formula_unverified_or_invalid",
|
|
731
|
+
}
|
|
732
|
+
)
|
|
733
|
+
safe_refs = (
|
|
734
|
+
[ref for ref in refs if isinstance(ref, str) and ref in obj.columns]
|
|
735
|
+
if isinstance(refs, list)
|
|
736
|
+
else []
|
|
737
|
+
)
|
|
738
|
+
merged["formula_proposals"] = [
|
|
739
|
+
*merged["formula_proposals"],
|
|
740
|
+
{
|
|
741
|
+
"operator": (
|
|
742
|
+
effective_operator
|
|
743
|
+
if effective_operator in {"sum", "ratio_of_sums"}
|
|
744
|
+
else "unknown"
|
|
745
|
+
),
|
|
746
|
+
"operands": safe_refs,
|
|
747
|
+
"proposal_status": "proposed",
|
|
748
|
+
"schema_status": "invalid",
|
|
749
|
+
"coverage_status": "unverified",
|
|
750
|
+
"numerical_evidence_status": "not_measured",
|
|
751
|
+
"approval_status": "not_approved",
|
|
752
|
+
},
|
|
753
|
+
]
|
|
754
|
+
# Do not serve an unsafe formula inherited from either layer.
|
|
755
|
+
if sm.get("recompute_candidates"):
|
|
756
|
+
merged["formula_candidates"] = sm["recompute_candidates"]
|
|
757
|
+
merged["formula_choice_status"] = sm.get("formula_choice_status", "unverified")
|
|
758
|
+
merged["formula_candidate_evidence"] = sm.get("formula_candidate_evidence", {})
|
|
759
|
+
if columns is not None and name in requested:
|
|
760
|
+
merged["descricao"] = co.get(
|
|
761
|
+
"description", sm.get("description", meta.comment or "")
|
|
762
|
+
)
|
|
763
|
+
columns_out.append(merged)
|
|
764
|
+
if columns is not None:
|
|
765
|
+
unknown = requested - set(obj.columns)
|
|
766
|
+
for name in sorted(unknown):
|
|
767
|
+
conflicts.append(
|
|
768
|
+
{
|
|
769
|
+
"override_id": key,
|
|
770
|
+
"column": name,
|
|
771
|
+
"field": "requested_column",
|
|
772
|
+
"reason": "column_reference_missing",
|
|
773
|
+
}
|
|
774
|
+
)
|
|
775
|
+
out["colunas"] = [c for c in columns_out if c["coluna"] in requested]
|
|
776
|
+
else:
|
|
777
|
+
out["colunas"] = [
|
|
778
|
+
{k: v for k, v in c.items() if k != "descricao"} for c in columns_out
|
|
779
|
+
]
|
|
780
|
+
out["taxas_nunca_somar"] = [
|
|
781
|
+
{
|
|
782
|
+
k: c[k]
|
|
783
|
+
for k in (
|
|
784
|
+
"coluna",
|
|
785
|
+
"recalcular_de",
|
|
786
|
+
"formula",
|
|
787
|
+
"agregacao",
|
|
788
|
+
"formula_status",
|
|
789
|
+
)
|
|
790
|
+
if k in c
|
|
791
|
+
}
|
|
792
|
+
for c in columns_out
|
|
793
|
+
if c.get("papel") == "non_additive_measure" and c.get("recalcular_de")
|
|
794
|
+
]
|
|
795
|
+
hierarchy_evidence = fields.get("hierarchy_evidence", [])
|
|
796
|
+
hierarchy_details = _verified_hierarchy_details(
|
|
797
|
+
fields.get("hierarchies", []), hierarchy_evidence, set(obj.columns)
|
|
798
|
+
)
|
|
799
|
+
out["hierarquias"] = [item["path"] for item in hierarchy_details]
|
|
800
|
+
out["hierarchy_details"] = hierarchy_details
|
|
801
|
+
out["hierarchy_evidence"] = hierarchy_evidence
|
|
802
|
+
out["formula_coverage"] = _safe_formula_coverage(fields, set(obj.columns))
|
|
803
|
+
# Recompute consistency at read time too, so persisted artifacts
|
|
804
|
+
# written before this field existed receive the same review signal.
|
|
805
|
+
# Human role/time overrides remain authoritative in the served view.
|
|
806
|
+
temporal_conflicts = [
|
|
807
|
+
dict(item)
|
|
808
|
+
for item in fields.get("temporal_conflicts", [])
|
|
809
|
+
if isinstance(item, dict)
|
|
810
|
+
]
|
|
811
|
+
role_by_column = {item["coluna"]: item.get("papel") for item in columns_out}
|
|
812
|
+
for column_name, meta in obj.columns.items():
|
|
813
|
+
role = role_by_column.get(column_name)
|
|
814
|
+
structural_temporal = any(
|
|
815
|
+
token in meta.data_type.upper() for token in ("DATE", "TIME", "TIMESTAMP")
|
|
816
|
+
)
|
|
817
|
+
if role is not None and structural_temporal != (role == "date"):
|
|
818
|
+
candidate = {
|
|
819
|
+
"column": column_name,
|
|
820
|
+
"kind": "structural_type_role_conflict",
|
|
821
|
+
"structural_type": meta.data_type,
|
|
822
|
+
"proposed_role": role,
|
|
823
|
+
"review_required": "true",
|
|
824
|
+
}
|
|
825
|
+
if candidate not in temporal_conflicts:
|
|
826
|
+
temporal_conflicts.append(candidate)
|
|
827
|
+
effective_time_column = fields.get("time_column")
|
|
828
|
+
if effective_time_column in obj.columns and not any(
|
|
829
|
+
token in obj.columns[effective_time_column].data_type.upper()
|
|
830
|
+
for token in ("DATE", "TIME", "TIMESTAMP")
|
|
831
|
+
):
|
|
832
|
+
candidate = {
|
|
833
|
+
"column": effective_time_column,
|
|
834
|
+
"kind": "time_column_type_conflict",
|
|
835
|
+
"structural_type": obj.columns[effective_time_column].data_type,
|
|
836
|
+
"proposed_role": str(role_by_column.get(effective_time_column, "unknown")),
|
|
837
|
+
"review_required": "true",
|
|
838
|
+
}
|
|
839
|
+
if candidate not in temporal_conflicts:
|
|
840
|
+
temporal_conflicts.append(candidate)
|
|
841
|
+
if effective_time_column in obj.columns and role_by_column.get(
|
|
842
|
+
effective_time_column
|
|
843
|
+
) not in (
|
|
844
|
+
None,
|
|
845
|
+
"date",
|
|
846
|
+
):
|
|
847
|
+
candidate = {
|
|
848
|
+
"column": effective_time_column,
|
|
849
|
+
"kind": "time_column_role_conflict",
|
|
850
|
+
"structural_type": obj.columns[effective_time_column].data_type,
|
|
851
|
+
"proposed_role": str(role_by_column[effective_time_column]),
|
|
852
|
+
"review_required": "true",
|
|
853
|
+
}
|
|
854
|
+
if candidate not in temporal_conflicts:
|
|
855
|
+
temporal_conflicts.append(candidate)
|
|
856
|
+
for conflict in temporal_conflicts:
|
|
857
|
+
conflict_column_key = conflict.get("column")
|
|
858
|
+
if conflict_column_key in override.get("columns", {}) or (
|
|
859
|
+
conflict_column_key == effective_time_column and "time_column" in override
|
|
860
|
+
):
|
|
861
|
+
conflict["human_override_applied"] = "true"
|
|
862
|
+
out["temporal_conflicts"] = temporal_conflicts
|
|
863
|
+
out["discriminator_grain_evidence"] = fields.get("discriminator_grain_evidence", [])
|
|
864
|
+
out["discriminator_evidence"] = [
|
|
865
|
+
{
|
|
866
|
+
"column": item.column,
|
|
867
|
+
"discriminator": item.discriminator,
|
|
868
|
+
"key": item.key,
|
|
869
|
+
"value_type": item.value_type,
|
|
870
|
+
"rows": item.rows,
|
|
871
|
+
"present": item.present,
|
|
872
|
+
"status": item.status,
|
|
873
|
+
}
|
|
874
|
+
for item in obj.variant_keys
|
|
875
|
+
]
|
|
876
|
+
details.append(out)
|
|
877
|
+
|
|
878
|
+
relations, relation_conflicts = self._relations(set(objects))
|
|
879
|
+
conflicts.extend(relation_conflicts)
|
|
880
|
+
within, outside = [], []
|
|
881
|
+
for rel in relations:
|
|
882
|
+
pair = {rel.get("source"), rel.get("target")}
|
|
883
|
+
full = pair <= set(objects)
|
|
884
|
+
if full:
|
|
885
|
+
within.append(
|
|
886
|
+
self._full_relation(rel, set(columns) if columns is not None else None)
|
|
887
|
+
)
|
|
888
|
+
elif pair & set(objects):
|
|
889
|
+
outside.append(
|
|
890
|
+
self._short_relation(
|
|
891
|
+
rel, set(objects), set(columns) if columns is not None else None
|
|
892
|
+
)
|
|
893
|
+
)
|
|
894
|
+
outside = self._best_two_per_pair(outside)
|
|
895
|
+
result = {
|
|
896
|
+
"disponivel": True,
|
|
897
|
+
"objetos": details,
|
|
898
|
+
"cruzamentos_entre_eles": within,
|
|
899
|
+
"cruzamentos_com_outros": outside,
|
|
900
|
+
"override_conflicts": conflicts,
|
|
901
|
+
"catalog_version": self._catalog_version,
|
|
902
|
+
"override_revision": self._override_revision,
|
|
903
|
+
}
|
|
904
|
+
if self._stale:
|
|
905
|
+
result["estado"] = "stale"
|
|
906
|
+
return result
|
|
907
|
+
|
|
908
|
+
def as_tool(self, objects=None, columns=None):
|
|
909
|
+
"""Return the single agent-tool callable (index or 1–3 object detail)."""
|
|
910
|
+
|
|
911
|
+
def invoke(objects=None, columns=None):
|
|
912
|
+
with self._lock:
|
|
913
|
+
try:
|
|
914
|
+
if objects is None:
|
|
915
|
+
data = self.index()
|
|
916
|
+
else:
|
|
917
|
+
data = self.detail(objects, columns)
|
|
918
|
+
available = data.get("disponivel", True) if isinstance(data, dict) else True
|
|
919
|
+
status = (
|
|
920
|
+
"unavailable"
|
|
921
|
+
if not available
|
|
922
|
+
else data.get("estado", "fresh")
|
|
923
|
+
if isinstance(data, dict)
|
|
924
|
+
else "stale"
|
|
925
|
+
if self._stale
|
|
926
|
+
else "fresh"
|
|
927
|
+
)
|
|
928
|
+
result = {
|
|
929
|
+
"status": status,
|
|
930
|
+
"catalog_version": self._catalog_version,
|
|
931
|
+
"override_revision": self._override_revision,
|
|
932
|
+
"data": data,
|
|
933
|
+
}
|
|
934
|
+
encoded = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode(
|
|
935
|
+
"utf-8"
|
|
936
|
+
)
|
|
937
|
+
if len(encoded) > self._payload_budget_bytes:
|
|
938
|
+
return {
|
|
939
|
+
"status": "unavailable",
|
|
940
|
+
"catalog_version": self._catalog_version,
|
|
941
|
+
"override_revision": self._override_revision,
|
|
942
|
+
"data": {
|
|
943
|
+
"disponivel": False,
|
|
944
|
+
"motivo": "payload_budget_exceeded",
|
|
945
|
+
"payload_bytes": len(encoded),
|
|
946
|
+
"payload_budget_bytes": self._payload_budget_bytes,
|
|
947
|
+
},
|
|
948
|
+
}
|
|
949
|
+
return result
|
|
950
|
+
except Exception as exc:
|
|
951
|
+
return {
|
|
952
|
+
"status": "unavailable",
|
|
953
|
+
"catalog_version": self._catalog_version,
|
|
954
|
+
"override_revision": self._override_revision,
|
|
955
|
+
"data": {
|
|
956
|
+
"disponivel": False,
|
|
957
|
+
"motivo": f"Catalog view unavailable ({safe_error_label(exc)})",
|
|
958
|
+
},
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
# Old positional execution is intentionally removed in this alpha.
|
|
962
|
+
if objects is not None or columns is not None:
|
|
963
|
+
raise TypeError(
|
|
964
|
+
"as_tool() is a callable factory; call the returned tool with arguments"
|
|
965
|
+
)
|
|
966
|
+
return invoke
|
|
967
|
+
|
|
968
|
+
def _entity(self, key):
|
|
969
|
+
entities = self._semantic.get("entities", {})
|
|
970
|
+
item = entities.get(key, {}) if isinstance(entities, dict) else {}
|
|
971
|
+
return item if isinstance(item, dict) else {}
|
|
972
|
+
|
|
973
|
+
def _object_overrides(self):
|
|
974
|
+
# `objects` is the implemented storage key; `entities` is the v0.2
|
|
975
|
+
# wording. Support both without changing the stored human artifact.
|
|
976
|
+
return {
|
|
977
|
+
**self._overrides.get("objects", {}),
|
|
978
|
+
**self._overrides.get("entities", {}),
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
def _relations(self, requested):
|
|
982
|
+
snapshot = self._snapshot
|
|
983
|
+
assert snapshot is not None
|
|
984
|
+
generated = self._semantic.get("relationships", [])
|
|
985
|
+
generated = generated if isinstance(generated, list) else []
|
|
986
|
+
valid_generated = []
|
|
987
|
+
for record in generated:
|
|
988
|
+
if not isinstance(record, dict):
|
|
989
|
+
continue
|
|
990
|
+
row = dict(record)
|
|
991
|
+
stored_guidance_signature = row.get("measure_guidance_signature")
|
|
992
|
+
if isinstance(stored_guidance_signature, str):
|
|
993
|
+
expected_guidance_signature = measure_guidance_signature(
|
|
994
|
+
row.get("source", ""),
|
|
995
|
+
row.get("target", ""),
|
|
996
|
+
self._semantic.get("entities", {}),
|
|
997
|
+
self._object_overrides(),
|
|
998
|
+
)
|
|
999
|
+
if stored_guidance_signature != expected_guidance_signature:
|
|
1000
|
+
row["measure_guidance"] = []
|
|
1001
|
+
row["measure_guidance_status"] = "stale"
|
|
1002
|
+
row["caution"] = (
|
|
1003
|
+
row.get("caution", "") + "; " if row.get("caution") else ""
|
|
1004
|
+
) + ("measure guidance is stale after semantic changes; revalidate before use")
|
|
1005
|
+
elif row.get("measure_guidance"):
|
|
1006
|
+
# Legacy records cannot prove which roles, formulas, or grain
|
|
1007
|
+
# supported their recommendation. Fail closed instead of
|
|
1008
|
+
# presenting unverifiable advice as current.
|
|
1009
|
+
row["measure_guidance"] = []
|
|
1010
|
+
row["measure_guidance_status"] = "unverified"
|
|
1011
|
+
row["caution"] = (row.get("caution", "") + "; " if row.get("caution") else "") + (
|
|
1012
|
+
"measure guidance has no semantic basis signature; revalidate before use"
|
|
1013
|
+
)
|
|
1014
|
+
aggregation_signature = row.get("aggregation_guidance_signature")
|
|
1015
|
+
expected_aggregation_signature = measure_guidance_signature(
|
|
1016
|
+
row.get("source", ""),
|
|
1017
|
+
row.get("target", ""),
|
|
1018
|
+
self._semantic.get("entities", {}),
|
|
1019
|
+
self._object_overrides(),
|
|
1020
|
+
)
|
|
1021
|
+
row = suppress_unverified_preaggregation_advice(
|
|
1022
|
+
row,
|
|
1023
|
+
basis_changed=aggregation_signature != expected_aggregation_signature,
|
|
1024
|
+
)
|
|
1025
|
+
if row.get("verdict") not in {
|
|
1026
|
+
"accepted",
|
|
1027
|
+
"warning_many_to_many",
|
|
1028
|
+
"warning_one_to_many",
|
|
1029
|
+
"warning_row_multiplication",
|
|
1030
|
+
}:
|
|
1031
|
+
row["served"] = False
|
|
1032
|
+
valid_generated.append(row)
|
|
1033
|
+
human = self._overrides.get("relationships", [])
|
|
1034
|
+
human_by_pair = defaultdict(list)
|
|
1035
|
+
conflicts = []
|
|
1036
|
+
for rel in human:
|
|
1037
|
+
src, dst = rel.get("source"), rel.get("target")
|
|
1038
|
+
bad = src not in snapshot.objects or dst not in snapshot.objects
|
|
1039
|
+
if bad:
|
|
1040
|
+
conflicts.append(
|
|
1041
|
+
{"override_id": rel.get("id"), "reason": "object_reference_missing"}
|
|
1042
|
+
)
|
|
1043
|
+
else:
|
|
1044
|
+
bad = any(
|
|
1045
|
+
c not in snapshot.objects[src].columns for c in rel.get("source_columns", [])
|
|
1046
|
+
) or any(
|
|
1047
|
+
c not in snapshot.objects[dst].columns for c in rel.get("target_columns", [])
|
|
1048
|
+
)
|
|
1049
|
+
if bad:
|
|
1050
|
+
conflicts.append(
|
|
1051
|
+
{"override_id": rel.get("id"), "reason": "column_reference_missing"}
|
|
1052
|
+
)
|
|
1053
|
+
if rel.get("type") != "forbidden":
|
|
1054
|
+
continue
|
|
1055
|
+
token = frozenset((src, dst))
|
|
1056
|
+
human_by_pair[token].append((rel, bad))
|
|
1057
|
+
result = []
|
|
1058
|
+
forbidden_pairs = {
|
|
1059
|
+
pair
|
|
1060
|
+
for pair, items in human_by_pair.items()
|
|
1061
|
+
if any(item.get("type") == "forbidden" for item, _ in items)
|
|
1062
|
+
}
|
|
1063
|
+
# Any human declaration owns the pair. Generated records are retained
|
|
1064
|
+
# only as validation evidence for an exact key mapping below.
|
|
1065
|
+
for rel in valid_generated:
|
|
1066
|
+
token = frozenset((rel.get("source"), rel.get("target")))
|
|
1067
|
+
if token not in human_by_pair:
|
|
1068
|
+
result.append(rel)
|
|
1069
|
+
for token, items in human_by_pair.items():
|
|
1070
|
+
for override, bad in items:
|
|
1071
|
+
src, dst = override.get("source"), override.get("target")
|
|
1072
|
+
row = {
|
|
1073
|
+
"id": override.get("id"),
|
|
1074
|
+
"type": override.get("type"),
|
|
1075
|
+
"source": src,
|
|
1076
|
+
"target": dst,
|
|
1077
|
+
"source_keys": override.get("source_columns", []),
|
|
1078
|
+
"target_keys": override.get("target_columns", []),
|
|
1079
|
+
"origin": "override",
|
|
1080
|
+
"metrics": {},
|
|
1081
|
+
"caution": override.get("reason"),
|
|
1082
|
+
"served": False,
|
|
1083
|
+
"verdict": "not_checked",
|
|
1084
|
+
}
|
|
1085
|
+
if override.get("type") == "forbidden":
|
|
1086
|
+
row["verdict"] = "forbidden"
|
|
1087
|
+
elif bad:
|
|
1088
|
+
row["verdict"] = "conflicted"
|
|
1089
|
+
row["caution"] = (
|
|
1090
|
+
"Human relationship references changed schema; review required."
|
|
1091
|
+
)
|
|
1092
|
+
elif token in forbidden_pairs:
|
|
1093
|
+
row["caution"] = (
|
|
1094
|
+
(row["caution"] + "; ") if row["caution"] else ""
|
|
1095
|
+
) + "suppressed by a forbidden human relationship for this object pair"
|
|
1096
|
+
result.append(row)
|
|
1097
|
+
return result, conflicts
|
|
1098
|
+
|
|
1099
|
+
@staticmethod
|
|
1100
|
+
def _full_relation(rel, requested_columns=None):
|
|
1101
|
+
metrics = rel.get("metrics") if isinstance(rel.get("metrics"), dict) else {}
|
|
1102
|
+
measure_guidance = rel.get("measure_guidance", [])
|
|
1103
|
+
if not isinstance(measure_guidance, list):
|
|
1104
|
+
measure_guidance = []
|
|
1105
|
+
if requested_columns is not None:
|
|
1106
|
+
measure_guidance = [
|
|
1107
|
+
item
|
|
1108
|
+
for item in measure_guidance
|
|
1109
|
+
if isinstance(item, dict) and item.get("column") in requested_columns
|
|
1110
|
+
]
|
|
1111
|
+
return {
|
|
1112
|
+
"id": rel.get("id"),
|
|
1113
|
+
"tipo": rel.get("type"),
|
|
1114
|
+
"origem": rel.get("source"),
|
|
1115
|
+
"destino": rel.get("target"),
|
|
1116
|
+
"chaves_origem": rel.get("source_keys", []),
|
|
1117
|
+
"chaves_destino": rel.get("target_keys", []),
|
|
1118
|
+
"condicoes": rel.get("conditions", []),
|
|
1119
|
+
"veredito": rel.get("verdict"),
|
|
1120
|
+
"match": metrics.get("source_match_rate"),
|
|
1121
|
+
"match_destino": metrics.get("target_match_rate"),
|
|
1122
|
+
"chaves_distintas_origem": metrics.get("source_distinct_keys"),
|
|
1123
|
+
"chaves_distintas_destino": metrics.get("target_distinct_keys"),
|
|
1124
|
+
"chaves_correspondentes": metrics.get("matched_keys"),
|
|
1125
|
+
"linhas_nulas_origem": metrics.get("source_null_key_rows"),
|
|
1126
|
+
"linhas_nulas_destino": metrics.get("target_null_key_rows"),
|
|
1127
|
+
"cardinalidade": metrics.get("cardinality"),
|
|
1128
|
+
"fanout": metrics.get("fanout"),
|
|
1129
|
+
"fanout_origem": metrics.get("source_fanout"),
|
|
1130
|
+
"fanout_destino": metrics.get("target_fanout"),
|
|
1131
|
+
"origem_preservada": metrics.get("source_side_preserved"),
|
|
1132
|
+
"destino_preservado": metrics.get("target_side_preserved"),
|
|
1133
|
+
"agregar_antes": rel.get("aggregate_first"),
|
|
1134
|
+
"aggregation_safety": rel.get("aggregation_safety"),
|
|
1135
|
+
"orientacao_medidas": measure_guidance,
|
|
1136
|
+
"orientacao_medidas_status": rel.get("measure_guidance_status", "current"),
|
|
1137
|
+
"anotacoes_llm_status": _llm_annotations_status(rel),
|
|
1138
|
+
"cuidado": rel.get("caution"),
|
|
1139
|
+
"serve_para": rel.get("answers", []),
|
|
1140
|
+
"servida": rel.get("served", False),
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
@staticmethod
|
|
1144
|
+
def _short_relation(rel, requested, requested_columns=None):
|
|
1145
|
+
metrics = rel.get("metrics") if isinstance(rel.get("metrics"), dict) else {}
|
|
1146
|
+
counterpart = rel.get("target") if rel.get("source") in requested else rel.get("source")
|
|
1147
|
+
measure_guidance = rel.get("measure_guidance", [])
|
|
1148
|
+
if not isinstance(measure_guidance, list):
|
|
1149
|
+
measure_guidance = []
|
|
1150
|
+
if requested_columns is not None:
|
|
1151
|
+
measure_guidance = [
|
|
1152
|
+
item
|
|
1153
|
+
for item in measure_guidance
|
|
1154
|
+
if isinstance(item, dict) and item.get("column") in requested_columns
|
|
1155
|
+
]
|
|
1156
|
+
return {
|
|
1157
|
+
"com": counterpart,
|
|
1158
|
+
"tipo": rel.get("type"),
|
|
1159
|
+
"chaves": [rel.get("source_keys", []), rel.get("target_keys", [])],
|
|
1160
|
+
"cardinalidade": metrics.get("cardinality"),
|
|
1161
|
+
"so_quando": rel.get("conditions", []),
|
|
1162
|
+
"veredito": rel.get("verdict"),
|
|
1163
|
+
"aggregation_safety": rel.get("aggregation_safety"),
|
|
1164
|
+
"orientacao_medidas": measure_guidance,
|
|
1165
|
+
"orientacao_medidas_status": rel.get("measure_guidance_status", "current"),
|
|
1166
|
+
"anotacoes_llm_status": _llm_annotations_status(rel),
|
|
1167
|
+
"match": metrics.get("source_match_rate"),
|
|
1168
|
+
"match_destino": metrics.get("target_match_rate"),
|
|
1169
|
+
"fanout": metrics.get("fanout"),
|
|
1170
|
+
"fanout_origem": metrics.get("source_fanout"),
|
|
1171
|
+
"fanout_destino": metrics.get("target_fanout"),
|
|
1172
|
+
"origem_preservada": metrics.get("source_side_preserved"),
|
|
1173
|
+
"destino_preservado": metrics.get("target_side_preserved"),
|
|
1174
|
+
"servida": rel.get("served", False),
|
|
1175
|
+
"_par": tuple(sorted((str(rel.get("source")), str(rel.get("target"))))),
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
@staticmethod
|
|
1179
|
+
def _best_two_per_pair(relations):
|
|
1180
|
+
groups: defaultdict[Any, list[dict[str, Any]]] = defaultdict(list)
|
|
1181
|
+
for rel in relations:
|
|
1182
|
+
groups[rel.get("_par")].append(rel)
|
|
1183
|
+
result: list[dict[str, Any]] = []
|
|
1184
|
+
for items in groups.values():
|
|
1185
|
+
items.sort(
|
|
1186
|
+
key=lambda r: (
|
|
1187
|
+
r.get("veredito") != "accepted",
|
|
1188
|
+
r.get("fanout") if isinstance(r.get("fanout"), (int, float)) else float("inf"),
|
|
1189
|
+
r.get("tipo") == "lineage",
|
|
1190
|
+
)
|
|
1191
|
+
)
|
|
1192
|
+
result.extend({k: v for k, v in item.items() if k != "_par"} for item in items[:2])
|
|
1193
|
+
return result
|