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,764 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import hashlib
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from typing import Dict, List, Optional
|
|
8
|
+
|
|
9
|
+
from semantic_context_engine.diff import diff_structural
|
|
10
|
+
from semantic_context_engine.models import (
|
|
11
|
+
ColumnMeta,
|
|
12
|
+
ObjectSnapshot,
|
|
13
|
+
StructuralSnapshot,
|
|
14
|
+
VariantKey,
|
|
15
|
+
)
|
|
16
|
+
from semantic_context_engine.storage import StorageProtocol
|
|
17
|
+
from semantic_context_engine.artifacts import validate_structural_artifact
|
|
18
|
+
from semantic_context_engine.errors import (
|
|
19
|
+
PublicationConflictError,
|
|
20
|
+
ValidationError as DomainValidationError,
|
|
21
|
+
SnapshotValidationError,
|
|
22
|
+
StorageError,
|
|
23
|
+
)
|
|
24
|
+
from semantic_context_engine.domain_contracts import (
|
|
25
|
+
OverrideDocumentContract,
|
|
26
|
+
SemanticArtifactContract,
|
|
27
|
+
)
|
|
28
|
+
from pydantic import ValidationError as PydanticValidationError
|
|
29
|
+
|
|
30
|
+
_UNSPECIFIED_POINTER = object()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Registry:
|
|
34
|
+
"""Gerencia snapshots imutáveis, ponteiro ativo e overrides.
|
|
35
|
+
|
|
36
|
+
Estrutura no storage:
|
|
37
|
+
<root>/<namespace>/active.json -> ponteiro para versão ativa
|
|
38
|
+
<root>/<namespace>/snapshots/<version>/ -> snapshots imutáveis
|
|
39
|
+
<root>/<namespace>/overrides/overrides.yaml -> overrides humanos
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, storage: StorageProtocol, namespace: str = "demo"):
|
|
43
|
+
self.storage = storage
|
|
44
|
+
self.namespace = namespace
|
|
45
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]+", namespace):
|
|
46
|
+
raise ValueError("Invalid namespace")
|
|
47
|
+
self._prefix = namespace
|
|
48
|
+
|
|
49
|
+
def _key(self, *parts: str) -> str:
|
|
50
|
+
return "/".join((self._prefix, *parts))
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def _storage_call(operation, *args):
|
|
54
|
+
try:
|
|
55
|
+
return operation(*args)
|
|
56
|
+
except json.JSONDecodeError as exc:
|
|
57
|
+
raise SnapshotValidationError("Persisted catalog JSON is invalid") from exc
|
|
58
|
+
except (FileNotFoundError, FileExistsError):
|
|
59
|
+
raise
|
|
60
|
+
except Exception as exc:
|
|
61
|
+
raise StorageError("Catalog storage operation failed") from exc
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def active_path(self) -> str:
|
|
65
|
+
return self._key("active.json")
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def snapshots_dir(self) -> str:
|
|
69
|
+
return self._key("snapshots")
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def overrides_path(self) -> str:
|
|
73
|
+
return self._key("overrides", "overrides.yaml")
|
|
74
|
+
|
|
75
|
+
def read_active_pointer(self) -> Optional[dict]:
|
|
76
|
+
"""Return the exact active token; absence is represented by ``None``."""
|
|
77
|
+
rel = self._key("active.json")
|
|
78
|
+
if not self._storage_call(self.storage.exists, rel):
|
|
79
|
+
return None
|
|
80
|
+
data = self._storage_call(self.storage.read_json, rel)
|
|
81
|
+
if not isinstance(data.get("version"), str) or not re.fullmatch(
|
|
82
|
+
r"[A-Za-z0-9T._-]+Z?", data["version"]
|
|
83
|
+
):
|
|
84
|
+
raise ValueError("Corrupt active pointer: invalid version")
|
|
85
|
+
return data
|
|
86
|
+
|
|
87
|
+
def override_revision(self) -> str:
|
|
88
|
+
"""Stable revision token for the current validated human overrides."""
|
|
89
|
+
data = self.load_overrides()
|
|
90
|
+
encoded = json.dumps(
|
|
91
|
+
data, sort_keys=True, separators=(",", ":"), ensure_ascii=False
|
|
92
|
+
).encode("utf-8")
|
|
93
|
+
return hashlib.sha256(encoded).hexdigest()
|
|
94
|
+
|
|
95
|
+
def _override_publish_lock(self):
|
|
96
|
+
"""Serialize local override replacement against a publication check/CAS."""
|
|
97
|
+
return self.storage.locked(self._key("overrides", "revision"))
|
|
98
|
+
|
|
99
|
+
def load_active(self, pointer=_UNSPECIFIED_POINTER) -> Optional[StructuralSnapshot]:
|
|
100
|
+
"""Carrega o snapshot ativo (ponteiro)."""
|
|
101
|
+
if pointer is _UNSPECIFIED_POINTER:
|
|
102
|
+
pointer = self.read_active_pointer()
|
|
103
|
+
if pointer is None:
|
|
104
|
+
return None
|
|
105
|
+
if not isinstance(pointer, dict):
|
|
106
|
+
raise ValueError("Invalid active pointer token")
|
|
107
|
+
data = pointer
|
|
108
|
+
if not isinstance(data.get("version"), str) or not re.fullmatch(
|
|
109
|
+
r"[A-Za-z0-9T._-]+Z?", data["version"]
|
|
110
|
+
):
|
|
111
|
+
raise ValueError("Corrupt active pointer: invalid version")
|
|
112
|
+
version = data["version"]
|
|
113
|
+
snapshot = self.load_snapshot(version)
|
|
114
|
+
if snapshot is None:
|
|
115
|
+
raise ValueError(f"Corrupt active pointer: snapshot {version!r} is missing")
|
|
116
|
+
return snapshot
|
|
117
|
+
|
|
118
|
+
def load_snapshot(self, version: str) -> Optional[StructuralSnapshot]:
|
|
119
|
+
"""Carrega um snapshot específico por versão (imutável)."""
|
|
120
|
+
if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9T._-]+Z?", version):
|
|
121
|
+
raise ValueError("Invalid snapshot version")
|
|
122
|
+
snap_path = self._key("snapshots", version, "structural.json")
|
|
123
|
+
if not self._storage_call(self.storage.exists, snap_path):
|
|
124
|
+
return None
|
|
125
|
+
data = validate_structural_artifact(
|
|
126
|
+
self._storage_call(self.storage.read_json, snap_path)
|
|
127
|
+
).model_dump(mode="python")
|
|
128
|
+
if (
|
|
129
|
+
not isinstance(data.get("version"), str)
|
|
130
|
+
or data["version"] != version
|
|
131
|
+
or not isinstance(data.get("objects"), dict)
|
|
132
|
+
):
|
|
133
|
+
raise ValueError(f"Corrupt snapshot {version!r}")
|
|
134
|
+
|
|
135
|
+
# Reconstruir objects
|
|
136
|
+
objects: Dict[str, ObjectSnapshot] = {}
|
|
137
|
+
for key, obj_data in data.get("objects", {}).items():
|
|
138
|
+
# Reconstruir ColumnMeta
|
|
139
|
+
columns: Dict[str, ColumnMeta] = {}
|
|
140
|
+
for col_name, col_data in obj_data.get("columns", {}).items():
|
|
141
|
+
columns[col_name] = ColumnMeta(
|
|
142
|
+
name=col_data.get("name", col_name),
|
|
143
|
+
data_type=col_data.get("data_type", "VARCHAR"),
|
|
144
|
+
nullable=col_data.get("nullable", True),
|
|
145
|
+
comment=col_data.get("comment"),
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
objects[key] = ObjectSnapshot(
|
|
149
|
+
key=obj_data["key"],
|
|
150
|
+
fqn=obj_data["fqn"],
|
|
151
|
+
object_type=obj_data["object_type"],
|
|
152
|
+
description=obj_data.get("description"),
|
|
153
|
+
hint=obj_data.get("hint"),
|
|
154
|
+
table_comment=obj_data.get("table_comment"),
|
|
155
|
+
columns=columns,
|
|
156
|
+
ddl_canonical=obj_data["ddl_canonical"],
|
|
157
|
+
ddl_raw=obj_data.get("ddl_raw", ""),
|
|
158
|
+
ddl_error=obj_data.get("ddl_error"),
|
|
159
|
+
dependencies=obj_data.get("dependencies", set()),
|
|
160
|
+
variant_keys=[VariantKey(**item) for item in obj_data.get("variant_keys", [])],
|
|
161
|
+
declared_constraints=obj_data.get("declared_constraints", []),
|
|
162
|
+
fingerprint=obj_data["fingerprint"],
|
|
163
|
+
discovered_at=obj_data.get("discovered_at", ""),
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
return StructuralSnapshot(
|
|
167
|
+
version=data.get("version", ""),
|
|
168
|
+
published_at=data.get("published_at"),
|
|
169
|
+
objects=objects,
|
|
170
|
+
discovered_order=tuple(data.get("discovered_order", [])),
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def load_semantic(self, version: Optional[str] = None) -> dict:
|
|
174
|
+
"""Read the machine-generated semantic artifact for a snapshot version."""
|
|
175
|
+
if version is None:
|
|
176
|
+
active = self.load_active()
|
|
177
|
+
if active is None:
|
|
178
|
+
return {}
|
|
179
|
+
version = active.version
|
|
180
|
+
if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9T._-]+Z?", version):
|
|
181
|
+
raise ValueError("Invalid snapshot version")
|
|
182
|
+
rel = self._key("snapshots", version, "semantic.json")
|
|
183
|
+
if not self._storage_call(self.storage.exists, rel):
|
|
184
|
+
return {}
|
|
185
|
+
data = self._storage_call(self.storage.read_json, rel)
|
|
186
|
+
try:
|
|
187
|
+
return SemanticArtifactContract.model_validate(data).model_dump(
|
|
188
|
+
mode="python", exclude_unset=True
|
|
189
|
+
)
|
|
190
|
+
except PydanticValidationError as exc:
|
|
191
|
+
raise SnapshotValidationError(f"Corrupt semantic snapshot {version!r}") from exc
|
|
192
|
+
|
|
193
|
+
def save_active(
|
|
194
|
+
self,
|
|
195
|
+
snapshot: StructuralSnapshot,
|
|
196
|
+
published: bool = False,
|
|
197
|
+
expected_pointer=_UNSPECIFIED_POINTER,
|
|
198
|
+
semantic_data: Optional[dict] = None,
|
|
199
|
+
report_data: Optional[dict] = None,
|
|
200
|
+
) -> None:
|
|
201
|
+
"""Publish through the same cross-process lock used by overrides."""
|
|
202
|
+
with self._override_publish_lock():
|
|
203
|
+
self._save_active_unlocked(
|
|
204
|
+
snapshot,
|
|
205
|
+
published=published,
|
|
206
|
+
expected_pointer=expected_pointer,
|
|
207
|
+
semantic_data=semantic_data,
|
|
208
|
+
report_data=report_data,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
def _save_active_unlocked(
|
|
212
|
+
self,
|
|
213
|
+
snapshot: StructuralSnapshot,
|
|
214
|
+
published: bool = False,
|
|
215
|
+
expected_pointer=_UNSPECIFIED_POINTER,
|
|
216
|
+
semantic_data: Optional[dict] = None,
|
|
217
|
+
report_data: Optional[dict] = None,
|
|
218
|
+
) -> None:
|
|
219
|
+
"""Salva o snapshot como ativo (ponteiro).
|
|
220
|
+
|
|
221
|
+
Ordens seguras: snapshot persistido primeiro; ativo só atualizado se persistir.
|
|
222
|
+
Serializa tudo uma única vez; escreve structural.json uma única vez (incluso objeto vazio).
|
|
223
|
+
Recusa versão já existente; só então troca o ponteiro ativo.
|
|
224
|
+
Uses getattr for optional attributes to support duck-typed snapshots.
|
|
225
|
+
"""
|
|
226
|
+
import datetime as _dt
|
|
227
|
+
|
|
228
|
+
published_at_value = getattr(snapshot, "published_at", None) or _dt.datetime.now(
|
|
229
|
+
_dt.timezone.utc
|
|
230
|
+
).strftime("%Y%m%dT%H%M%S%fZ")
|
|
231
|
+
version = getattr(snapshot, "version", "") or datetime.now(timezone.utc).strftime(
|
|
232
|
+
"%Y%m%dT%H%M%S%fZ"
|
|
233
|
+
)
|
|
234
|
+
if published and semantic_data is not None:
|
|
235
|
+
try:
|
|
236
|
+
SemanticArtifactContract.model_validate(semantic_data)
|
|
237
|
+
except PydanticValidationError as exc:
|
|
238
|
+
raise SnapshotValidationError("Invalid semantic snapshot payload") from exc
|
|
239
|
+
|
|
240
|
+
# 1. Persistir snapshot imutável primeiro (se published=True)
|
|
241
|
+
if published:
|
|
242
|
+
snap_path = self._key("snapshots", version, "structural.json")
|
|
243
|
+
|
|
244
|
+
# Recusa sobrescrever versão já existente (protege imutabilidade)
|
|
245
|
+
if not re.fullmatch(r"[A-Za-z0-9T._-]+Z?", version):
|
|
246
|
+
raise ValueError("Invalid snapshot version")
|
|
247
|
+
|
|
248
|
+
# Serializa objects (fora do loop - builds full dict once, incluso caso vazio)
|
|
249
|
+
objects_serialized: Dict = {}
|
|
250
|
+
for key, obj in snapshot.objects.items():
|
|
251
|
+
columns_dict: Dict = {}
|
|
252
|
+
for col_name, col in obj.columns.items():
|
|
253
|
+
columns_dict[col_name] = {
|
|
254
|
+
"name": col.name,
|
|
255
|
+
"data_type": col.data_type,
|
|
256
|
+
"nullable": col.nullable,
|
|
257
|
+
"comment": col.comment,
|
|
258
|
+
}
|
|
259
|
+
vk_list = []
|
|
260
|
+
for vk in obj.variant_keys:
|
|
261
|
+
vk_list.append(
|
|
262
|
+
{
|
|
263
|
+
"column": vk.column,
|
|
264
|
+
"discriminator": vk.discriminator,
|
|
265
|
+
"key": vk.key,
|
|
266
|
+
"value_type": vk.value_type,
|
|
267
|
+
"rows": vk.rows,
|
|
268
|
+
"present": vk.present,
|
|
269
|
+
"status": vk.status,
|
|
270
|
+
}
|
|
271
|
+
)
|
|
272
|
+
objects_serialized[key] = {
|
|
273
|
+
"key": obj.key,
|
|
274
|
+
"fqn": getattr(obj, "fqn", ""),
|
|
275
|
+
"object_type": getattr(obj, "object_type", ""),
|
|
276
|
+
"description": getattr(obj, "description", ""),
|
|
277
|
+
"hint": getattr(obj, "hint", ""),
|
|
278
|
+
"table_comment": getattr(obj, "table_comment", ""),
|
|
279
|
+
"columns": {
|
|
280
|
+
c_name: {
|
|
281
|
+
"name": c_name,
|
|
282
|
+
"data_type": getattr(col, "data_type", "VARCHAR"),
|
|
283
|
+
"nullable": getattr(col, "nullable", True),
|
|
284
|
+
"comment": getattr(col, "comment", None),
|
|
285
|
+
}
|
|
286
|
+
for c_name, col in obj.columns.items()
|
|
287
|
+
},
|
|
288
|
+
"ddl_canonical": getattr(obj, "ddl_canonical", ""),
|
|
289
|
+
"ddl_raw": getattr(obj, "ddl_raw", ""),
|
|
290
|
+
"ddl_error": getattr(obj, "ddl_error", ""),
|
|
291
|
+
"dependencies": list(getattr(obj, "dependencies", set())),
|
|
292
|
+
"variant_keys": vk_list,
|
|
293
|
+
"declared_constraints": getattr(obj, "declared_constraints", []),
|
|
294
|
+
"fingerprint": getattr(obj, "fingerprint", ""),
|
|
295
|
+
"discovered_at": getattr(obj, "discovered_at", ""),
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
structural_data = {
|
|
299
|
+
"schema_version": 1,
|
|
300
|
+
"version": version,
|
|
301
|
+
"published_at": published_at_value,
|
|
302
|
+
"objects": objects_serialized,
|
|
303
|
+
"discovered_order": list(getattr(snapshot, "discovered_order", ())),
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
# Escreve structural.json uma única vez (even if zero objects -> {})
|
|
307
|
+
try:
|
|
308
|
+
self.storage.write_json_exclusive(snap_path, structural_data)
|
|
309
|
+
except Exception:
|
|
310
|
+
# Falha ao salvar snapshot -> não atualiza ponteiro ativo
|
|
311
|
+
raise
|
|
312
|
+
|
|
313
|
+
if semantic_data is not None:
|
|
314
|
+
semantic_path = self._key("snapshots", version, "semantic.json")
|
|
315
|
+
self.storage.write_json_exclusive(semantic_path, semantic_data)
|
|
316
|
+
|
|
317
|
+
# The immutable artifact is deliberately marked prepared: only the
|
|
318
|
+
# active pointer CAS can truthfully mark publication complete.
|
|
319
|
+
report = dict(report_data or {})
|
|
320
|
+
report.update(
|
|
321
|
+
{
|
|
322
|
+
"status": "candidate_ready",
|
|
323
|
+
"publication_state": "prepared",
|
|
324
|
+
"candidate": version,
|
|
325
|
+
"semantic_present": semantic_data is not None,
|
|
326
|
+
}
|
|
327
|
+
)
|
|
328
|
+
report_path = self._key("snapshots", version, "report.json")
|
|
329
|
+
self.storage.write_json_exclusive(report_path, report)
|
|
330
|
+
|
|
331
|
+
# 2. Salvar active.json (ponteiro) APENAS se snapshot persistiu
|
|
332
|
+
# Usa storage.write_json para consistência com load_active e atomicidade
|
|
333
|
+
active_rel_path = self._key("active.json")
|
|
334
|
+
expected = expected_pointer
|
|
335
|
+
if expected is _UNSPECIFIED_POINTER:
|
|
336
|
+
expected = self.read_active_pointer()
|
|
337
|
+
new_pointer = {"version": version, "published_at": published_at_value}
|
|
338
|
+
swapped = self.storage.compare_and_swap_json(active_rel_path, expected, new_pointer)
|
|
339
|
+
if not swapped:
|
|
340
|
+
raise PublicationConflictError("Active pointer changed concurrently; publish aborted")
|
|
341
|
+
|
|
342
|
+
def activate_version(self, version: str) -> StructuralSnapshot:
|
|
343
|
+
"""Rota/roll-forward do ponteiro para uma versão existente."""
|
|
344
|
+
baseline_pointer = self.read_active_pointer()
|
|
345
|
+
snapshot = self.load_snapshot(version)
|
|
346
|
+
if snapshot is None:
|
|
347
|
+
raise ValueError(f"Version {version} not found")
|
|
348
|
+
report_path = self._key("snapshots", version, "report.json")
|
|
349
|
+
if not self._storage_call(self.storage.exists, report_path):
|
|
350
|
+
raise ValueError(f"Version {version} is incomplete: report artifact is missing")
|
|
351
|
+
report = self._storage_call(self.storage.read_json, report_path)
|
|
352
|
+
if report.get("candidate") != version or report.get("publication_state") != "prepared":
|
|
353
|
+
raise ValueError(f"Version {version} is incomplete: report artifact is invalid")
|
|
354
|
+
if report.get("semantic_present") and self.load_semantic(version) == {}:
|
|
355
|
+
raise ValueError(f"Version {version} is incomplete: semantic artifact is missing")
|
|
356
|
+
# Keep slow artifact validation outside the critical section so an
|
|
357
|
+
# unrelated writer can proceed; serialize only the activation CAS
|
|
358
|
+
# against all other pointer and override writers.
|
|
359
|
+
with self._override_publish_lock():
|
|
360
|
+
self._save_active_unlocked(snapshot, published=False, expected_pointer=baseline_pointer)
|
|
361
|
+
return snapshot
|
|
362
|
+
|
|
363
|
+
def publish(
|
|
364
|
+
self,
|
|
365
|
+
structural_snapshot: StructuralSnapshot,
|
|
366
|
+
semantic_data: Optional[dict] = None,
|
|
367
|
+
expected_pointer=_UNSPECIFIED_POINTER,
|
|
368
|
+
expected_override_revision: Optional[str] = None,
|
|
369
|
+
) -> Dict:
|
|
370
|
+
"""Publica um snapshot novo.
|
|
371
|
+
|
|
372
|
+
Fluxo:
|
|
373
|
+
1. Verificar se ja existe ativo com mesma versão -> sem sobrescrever
|
|
374
|
+
2. Salvar como novo snapshot imutável
|
|
375
|
+
3. Atualizar ponteiro active.json para a nova versão
|
|
376
|
+
4. Retornar relatório do sync
|
|
377
|
+
"""
|
|
378
|
+
# Verificar se a versão já está ativa
|
|
379
|
+
baseline_pointer = (
|
|
380
|
+
self.read_active_pointer()
|
|
381
|
+
if expected_pointer is _UNSPECIFIED_POINTER
|
|
382
|
+
else expected_pointer
|
|
383
|
+
)
|
|
384
|
+
current_active = self.load_active(pointer=baseline_pointer)
|
|
385
|
+
# Calcular diff vs baseline
|
|
386
|
+
if current_active:
|
|
387
|
+
diff = diff_structural(current_active, structural_snapshot)
|
|
388
|
+
else:
|
|
389
|
+
# First sync ever - all candidate objects are "added"
|
|
390
|
+
diff = {
|
|
391
|
+
"status": "published",
|
|
392
|
+
"added": list(structural_snapshot.objects.keys()),
|
|
393
|
+
"changed": {},
|
|
394
|
+
"removed": [],
|
|
395
|
+
"unchanged": [],
|
|
396
|
+
"failed": {},
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
semantic_changed = False
|
|
400
|
+
if semantic_data is not None and current_active is not None:
|
|
401
|
+
semantic_changed = semantic_data != self.load_semantic(current_active.version)
|
|
402
|
+
|
|
403
|
+
if diff["status"] == "no_changes" and current_active is not None:
|
|
404
|
+
# Every no-op publication has one explicit linearization point.
|
|
405
|
+
# The same cross-process lock serializes active-pointer and override
|
|
406
|
+
# writers, so the pinned compile inputs are checked together.
|
|
407
|
+
with self._override_publish_lock():
|
|
408
|
+
live_pointer = self.read_active_pointer()
|
|
409
|
+
live_revision = self.override_revision()
|
|
410
|
+
if live_pointer != baseline_pointer or (
|
|
411
|
+
expected_override_revision is not None
|
|
412
|
+
and live_revision != expected_override_revision
|
|
413
|
+
):
|
|
414
|
+
live_active = self.load_active(pointer=live_pointer)
|
|
415
|
+
message = (
|
|
416
|
+
"Overrides changed during compilation; publish aborted"
|
|
417
|
+
if expected_override_revision is not None
|
|
418
|
+
and live_revision != expected_override_revision
|
|
419
|
+
else "Concurrent publication: active baseline differs from compiled version"
|
|
420
|
+
)
|
|
421
|
+
return {
|
|
422
|
+
"status": "failed",
|
|
423
|
+
"baseline": live_active.version if live_active else None,
|
|
424
|
+
"compiled_against": baseline_pointer,
|
|
425
|
+
"candidate": structural_snapshot.version,
|
|
426
|
+
"added": [],
|
|
427
|
+
"changed": {},
|
|
428
|
+
"removed": [],
|
|
429
|
+
"unchanged": [],
|
|
430
|
+
"failed": {"publish": message},
|
|
431
|
+
"override_conflicts": [],
|
|
432
|
+
}
|
|
433
|
+
if semantic_changed:
|
|
434
|
+
# Preserve immutable snapshot semantics: a changed semantic
|
|
435
|
+
# payload must get a new candidate version, never be
|
|
436
|
+
# silently treated as no_changes or overwrite this version.
|
|
437
|
+
if structural_snapshot.version == current_active.version:
|
|
438
|
+
return {
|
|
439
|
+
"status": "failed",
|
|
440
|
+
"baseline": current_active.version,
|
|
441
|
+
"compiled_against": baseline_pointer,
|
|
442
|
+
"candidate": structural_snapshot.version,
|
|
443
|
+
"added": [],
|
|
444
|
+
"changed": {},
|
|
445
|
+
"removed": [],
|
|
446
|
+
"unchanged": [],
|
|
447
|
+
"failed": {
|
|
448
|
+
"publish": "Semantic content changed for an immutable snapshot version"
|
|
449
|
+
},
|
|
450
|
+
"override_conflicts": [],
|
|
451
|
+
}
|
|
452
|
+
diff["status"] = "published"
|
|
453
|
+
else:
|
|
454
|
+
return {
|
|
455
|
+
"status": "no_changes",
|
|
456
|
+
"baseline": current_active.version if current_active else None,
|
|
457
|
+
"candidate": structural_snapshot.version,
|
|
458
|
+
"added": [],
|
|
459
|
+
"changed": {},
|
|
460
|
+
"removed": [],
|
|
461
|
+
"unchanged": list(current_active.objects.keys()) if current_active else [],
|
|
462
|
+
"failed": {},
|
|
463
|
+
"override_conflicts": [],
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
conflicts = self._check_override_conflicts(structural_snapshot)
|
|
467
|
+
# Relatório; a policy de gating permanece em aberto, então reportamos
|
|
468
|
+
# conflitos mas não bloqueamos publicação aqui.
|
|
469
|
+
report: Dict = {
|
|
470
|
+
"status": diff["status"],
|
|
471
|
+
"baseline": current_active.version if current_active else None,
|
|
472
|
+
"candidate": structural_snapshot.version,
|
|
473
|
+
"added": diff.get("added", []),
|
|
474
|
+
"changed": diff.get("changed", {}),
|
|
475
|
+
"removed": diff.get("removed", []),
|
|
476
|
+
"unchanged": diff.get("unchanged", []),
|
|
477
|
+
"failed": diff.get("failed", {}),
|
|
478
|
+
"override_conflicts": conflicts,
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
# Se status for publishable, salvar
|
|
482
|
+
if diff["status"] == "published":
|
|
483
|
+
# Acquire after compilation/diff (which callers may synchronize in
|
|
484
|
+
# tests or run for a long time), then hold through pointer CAS.
|
|
485
|
+
# save_overrides uses the same lock, preventing an edit between
|
|
486
|
+
# revision validation and activation.
|
|
487
|
+
with self._override_publish_lock():
|
|
488
|
+
if self.read_active_pointer() != baseline_pointer:
|
|
489
|
+
raise PublicationConflictError(
|
|
490
|
+
"Active pointer changed during compilation; publish aborted"
|
|
491
|
+
)
|
|
492
|
+
if (
|
|
493
|
+
expected_override_revision is not None
|
|
494
|
+
and self.override_revision() != expected_override_revision
|
|
495
|
+
):
|
|
496
|
+
raise PublicationConflictError(
|
|
497
|
+
"Overrides changed during compilation; publish aborted"
|
|
498
|
+
)
|
|
499
|
+
self._save_active_unlocked(
|
|
500
|
+
structural_snapshot,
|
|
501
|
+
published=True,
|
|
502
|
+
expected_pointer=baseline_pointer,
|
|
503
|
+
semantic_data=semantic_data,
|
|
504
|
+
report_data=report,
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
return report
|
|
508
|
+
|
|
509
|
+
def _check_override_conflicts(self, structural_snapshot) -> list:
|
|
510
|
+
"""Verifica se algum override humano tem conflito com o novo snapshot."""
|
|
511
|
+
conflicts: List[dict] = []
|
|
512
|
+
overrides_data = self.load_overrides()
|
|
513
|
+
if not overrides_data:
|
|
514
|
+
return conflicts
|
|
515
|
+
relationships = overrides_data["relationships"]
|
|
516
|
+
object_overrides = overrides_data.get("objects", {})
|
|
517
|
+
for object_key, override in object_overrides.items():
|
|
518
|
+
obj = structural_snapshot.objects.get(object_key)
|
|
519
|
+
if obj is None:
|
|
520
|
+
conflicts.append(
|
|
521
|
+
{
|
|
522
|
+
"override_id": object_key,
|
|
523
|
+
"problem": f"object '{object_key}' not found in snapshot",
|
|
524
|
+
}
|
|
525
|
+
)
|
|
526
|
+
continue
|
|
527
|
+
columns = getattr(obj, "columns", {})
|
|
528
|
+
for field, column in (("time_column", override.get("time_column")),):
|
|
529
|
+
if column and column not in columns:
|
|
530
|
+
conflicts.append(
|
|
531
|
+
{
|
|
532
|
+
"override_id": object_key,
|
|
533
|
+
"problem": f"{field} '{column}' not found in {object_key}",
|
|
534
|
+
}
|
|
535
|
+
)
|
|
536
|
+
for column in override.get("grain", []):
|
|
537
|
+
if column not in columns:
|
|
538
|
+
conflicts.append(
|
|
539
|
+
{
|
|
540
|
+
"override_id": object_key,
|
|
541
|
+
"problem": f"grain column '{column}' not found in {object_key}",
|
|
542
|
+
}
|
|
543
|
+
)
|
|
544
|
+
for column, column_override in override.get("columns", {}).items():
|
|
545
|
+
if column not in columns:
|
|
546
|
+
conflicts.append(
|
|
547
|
+
{
|
|
548
|
+
"override_id": object_key,
|
|
549
|
+
"problem": f"column override '{column}' not found in {object_key}",
|
|
550
|
+
}
|
|
551
|
+
)
|
|
552
|
+
continue
|
|
553
|
+
formula = column_override.get("formula", {})
|
|
554
|
+
for ref in formula.get("recompute_from", []):
|
|
555
|
+
if ref not in columns:
|
|
556
|
+
conflicts.append(
|
|
557
|
+
{
|
|
558
|
+
"override_id": object_key,
|
|
559
|
+
"problem": f"formula column '{ref}' not found in {object_key}",
|
|
560
|
+
}
|
|
561
|
+
)
|
|
562
|
+
for rel in relationships:
|
|
563
|
+
source_key = rel.get("source", "")
|
|
564
|
+
target_key = rel.get("target", "")
|
|
565
|
+
|
|
566
|
+
source_exists = (
|
|
567
|
+
source_key in structural_snapshot.objects if structural_snapshot.objects else False
|
|
568
|
+
)
|
|
569
|
+
target_exists = (
|
|
570
|
+
target_key in structural_snapshot.objects if structural_snapshot.objects else False
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
if source_exists:
|
|
574
|
+
source_obj = structural_snapshot.objects.get(source_key)
|
|
575
|
+
if hasattr(source_obj, "columns"):
|
|
576
|
+
for col in rel.get("source_columns", []):
|
|
577
|
+
if col not in source_obj.columns:
|
|
578
|
+
conflicts.append(
|
|
579
|
+
{
|
|
580
|
+
"override_id": rel.get("id", ""),
|
|
581
|
+
"problem": f"override '{rel.get('id', '')}': source column '{col}' not found in {source_key}",
|
|
582
|
+
}
|
|
583
|
+
)
|
|
584
|
+
if target_exists:
|
|
585
|
+
target_obj = structural_snapshot.objects[target_key]
|
|
586
|
+
for col in rel.get("target_columns", []):
|
|
587
|
+
if col not in target_obj.columns:
|
|
588
|
+
conflicts.append(
|
|
589
|
+
{
|
|
590
|
+
"override_id": rel.get("id", ""),
|
|
591
|
+
"problem": f"target column '{col}' not found in {target_key}",
|
|
592
|
+
}
|
|
593
|
+
)
|
|
594
|
+
if not target_exists:
|
|
595
|
+
conflicts.append(
|
|
596
|
+
{
|
|
597
|
+
"override_id": rel.get("id", ""),
|
|
598
|
+
"problem": f"target key '{target_key}' not found in snapshot",
|
|
599
|
+
}
|
|
600
|
+
)
|
|
601
|
+
if not source_exists:
|
|
602
|
+
conflicts.append(
|
|
603
|
+
{
|
|
604
|
+
"override_id": rel.get("id", ""),
|
|
605
|
+
"problem": f"source key '{source_key}' not found in snapshot",
|
|
606
|
+
}
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
return conflicts
|
|
610
|
+
|
|
611
|
+
def load_overrides(self) -> dict:
|
|
612
|
+
"""Load canonical namespaced YAML overrides; absence is distinct from corruption."""
|
|
613
|
+
if not self._storage_call(self.storage.exists, self.overrides_path):
|
|
614
|
+
return {"schema_version": 1, "relationships": []}
|
|
615
|
+
import yaml
|
|
616
|
+
|
|
617
|
+
data = yaml.safe_load(self._storage_call(self.storage.read_text, self.overrides_path))
|
|
618
|
+
self.validate_overrides(data)
|
|
619
|
+
return data
|
|
620
|
+
|
|
621
|
+
@staticmethod
|
|
622
|
+
def validate_overrides(data: dict) -> None:
|
|
623
|
+
if (
|
|
624
|
+
not isinstance(data, dict)
|
|
625
|
+
or type(data.get("schema_version")) is not int
|
|
626
|
+
or data.get("schema_version") != 1
|
|
627
|
+
):
|
|
628
|
+
raise ValueError("Overrides require schema_version: 1")
|
|
629
|
+
rels = data.get("relationships")
|
|
630
|
+
if not isinstance(rels, list):
|
|
631
|
+
raise ValueError("Overrides relationships must be a list")
|
|
632
|
+
objects = data.get("objects", {})
|
|
633
|
+
entities = data.get("entities", {})
|
|
634
|
+
if not isinstance(objects, dict) or not isinstance(entities, dict):
|
|
635
|
+
raise ValueError("Overrides objects/entities must be mappings")
|
|
636
|
+
objects = {**objects, **entities}
|
|
637
|
+
column_roles = {
|
|
638
|
+
"dimension",
|
|
639
|
+
"additive_measure",
|
|
640
|
+
"non_additive_measure",
|
|
641
|
+
"date",
|
|
642
|
+
"id",
|
|
643
|
+
}
|
|
644
|
+
aggregations = {"additive", "ratio_of_sums", "non_additive"}
|
|
645
|
+
relationship_types = {"join", "temporal", "lineage", "forbidden"}
|
|
646
|
+
|
|
647
|
+
def string_list(value, label, allow_empty=True):
|
|
648
|
+
if (
|
|
649
|
+
not isinstance(value, list)
|
|
650
|
+
or (not allow_empty and not value)
|
|
651
|
+
or not all(isinstance(item, str) and item.strip() for item in value)
|
|
652
|
+
):
|
|
653
|
+
raise ValueError(f"{label} must be a list of non-empty strings")
|
|
654
|
+
|
|
655
|
+
for object_key, override in objects.items():
|
|
656
|
+
if (
|
|
657
|
+
not isinstance(object_key, str)
|
|
658
|
+
or not object_key.strip()
|
|
659
|
+
or not isinstance(override, dict)
|
|
660
|
+
):
|
|
661
|
+
raise ValueError("Each object override requires a non-empty key and mapping")
|
|
662
|
+
for field in ("role", "family", "time_column"):
|
|
663
|
+
if field in override and (
|
|
664
|
+
not isinstance(override[field], str) or not override[field].strip()
|
|
665
|
+
):
|
|
666
|
+
raise ValueError(f"Object override {field} must be a non-empty string")
|
|
667
|
+
if "grain" in override:
|
|
668
|
+
string_list(override["grain"], "Object override grain", allow_empty=False)
|
|
669
|
+
if "limitations" in override:
|
|
670
|
+
string_list(override["limitations"], "Object override limitations")
|
|
671
|
+
columns = override.get("columns", {})
|
|
672
|
+
if not isinstance(columns, dict):
|
|
673
|
+
raise ValueError("Object override columns must be a mapping")
|
|
674
|
+
for column_name, column_override in columns.items():
|
|
675
|
+
if (
|
|
676
|
+
not isinstance(column_name, str)
|
|
677
|
+
or not column_name.strip()
|
|
678
|
+
or not isinstance(column_override, dict)
|
|
679
|
+
):
|
|
680
|
+
raise ValueError("Each column override requires a non-empty name and mapping")
|
|
681
|
+
if "role" in column_override and (
|
|
682
|
+
not isinstance(column_override["role"], str)
|
|
683
|
+
or column_override["role"] not in column_roles
|
|
684
|
+
):
|
|
685
|
+
raise ValueError(f"Invalid column override role for {column_name}")
|
|
686
|
+
if "family" in column_override and (
|
|
687
|
+
not isinstance(column_override["family"], str)
|
|
688
|
+
or not column_override["family"].strip()
|
|
689
|
+
):
|
|
690
|
+
raise ValueError(
|
|
691
|
+
f"Column override family for {column_name} must be a non-empty string"
|
|
692
|
+
)
|
|
693
|
+
if "limitations" in column_override:
|
|
694
|
+
string_list(
|
|
695
|
+
column_override["limitations"],
|
|
696
|
+
f"Column override {column_name} limitations",
|
|
697
|
+
)
|
|
698
|
+
if "formula" in column_override:
|
|
699
|
+
formula = column_override["formula"]
|
|
700
|
+
if not isinstance(formula, dict):
|
|
701
|
+
raise ValueError(
|
|
702
|
+
f"Column override formula for {column_name} must be a mapping"
|
|
703
|
+
)
|
|
704
|
+
if "expression" in formula and (
|
|
705
|
+
not isinstance(formula["expression"], str)
|
|
706
|
+
or not formula["expression"].strip()
|
|
707
|
+
):
|
|
708
|
+
raise ValueError(
|
|
709
|
+
f"Formula expression for {column_name} must be a non-empty string"
|
|
710
|
+
)
|
|
711
|
+
if "recompute_from" in formula:
|
|
712
|
+
string_list(
|
|
713
|
+
formula["recompute_from"],
|
|
714
|
+
f"Formula recompute_from for {column_name}",
|
|
715
|
+
allow_empty=False,
|
|
716
|
+
)
|
|
717
|
+
if "aggregation" in formula and (
|
|
718
|
+
not isinstance(formula["aggregation"], str)
|
|
719
|
+
or formula["aggregation"] not in aggregations
|
|
720
|
+
):
|
|
721
|
+
raise ValueError(f"Invalid formula aggregation for {column_name}")
|
|
722
|
+
if not (formula.get("expression") or formula.get("recompute_from")):
|
|
723
|
+
raise ValueError(
|
|
724
|
+
f"Formula for {column_name} requires expression or recompute_from"
|
|
725
|
+
)
|
|
726
|
+
seen = set()
|
|
727
|
+
for rel in rels:
|
|
728
|
+
if not isinstance(rel, dict):
|
|
729
|
+
raise ValueError("Each relationship override must be a mapping")
|
|
730
|
+
for field in ("id", "source", "target"):
|
|
731
|
+
if not isinstance(rel.get(field), str) or not rel[field].strip():
|
|
732
|
+
raise ValueError(f"Override requires non-empty {field}")
|
|
733
|
+
if rel["id"] in seen:
|
|
734
|
+
raise ValueError(f"Duplicate override id: {rel['id']}")
|
|
735
|
+
seen.add(rel["id"])
|
|
736
|
+
if rel.get("type") not in relationship_types:
|
|
737
|
+
raise ValueError(f"Override {rel['id']} requires a valid relationship type")
|
|
738
|
+
if "reason" in rel and (
|
|
739
|
+
not isinstance(rel["reason"], str) or not rel["reason"].strip()
|
|
740
|
+
):
|
|
741
|
+
raise ValueError(f"Override {rel['id']} reason must be a non-empty string")
|
|
742
|
+
if rel["type"] == "forbidden" and not rel.get("reason", "").strip():
|
|
743
|
+
raise ValueError(f"Forbidden override {rel['id']} requires a reason")
|
|
744
|
+
for field in ("source_columns", "target_columns"):
|
|
745
|
+
if field not in rel:
|
|
746
|
+
raise ValueError(f"Override {rel['id']} requires {field}")
|
|
747
|
+
string_list(rel[field], f"Override {field}")
|
|
748
|
+
|
|
749
|
+
try:
|
|
750
|
+
OverrideDocumentContract.model_validate(data)
|
|
751
|
+
except PydanticValidationError as exc:
|
|
752
|
+
raise DomainValidationError(
|
|
753
|
+
"Overrides document contains unsupported fields or invalid field types"
|
|
754
|
+
) from exc
|
|
755
|
+
|
|
756
|
+
def save_overrides(self, data: dict) -> None:
|
|
757
|
+
self.validate_overrides(data)
|
|
758
|
+
import yaml
|
|
759
|
+
|
|
760
|
+
with self._override_publish_lock():
|
|
761
|
+
self.storage.write_text_atomic(
|
|
762
|
+
self.overrides_path,
|
|
763
|
+
yaml.safe_dump(data, allow_unicode=True, sort_keys=False),
|
|
764
|
+
)
|