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.
Files changed (39) hide show
  1. semantic_context_engine/__init__.py +136 -0
  2. semantic_context_engine/artifacts.py +98 -0
  3. semantic_context_engine/cli.py +197 -0
  4. semantic_context_engine/compiler.py +316 -0
  5. semantic_context_engine/composition.py +31 -0
  6. semantic_context_engine/config.py +199 -0
  7. semantic_context_engine/diff.py +93 -0
  8. semantic_context_engine/domain_contracts.py +386 -0
  9. semantic_context_engine/engine.py +250 -0
  10. semantic_context_engine/enrichment.py +1416 -0
  11. semantic_context_engine/errors.py +291 -0
  12. semantic_context_engine/evaluation.py +88 -0
  13. semantic_context_engine/hierarchies.py +185 -0
  14. semantic_context_engine/instructions/semantic_catalog.md +2 -0
  15. semantic_context_engine/integration.py +22 -0
  16. semantic_context_engine/integrations/__init__.py +11 -0
  17. semantic_context_engine/integrations/langchain.py +275 -0
  18. semantic_context_engine/models.py +282 -0
  19. semantic_context_engine/normalization.py +351 -0
  20. semantic_context_engine/pipeline.py +1685 -0
  21. semantic_context_engine/prompts/v1/column_classification.md +15 -0
  22. semantic_context_engine/prompts/v1/grain_correction.md +4 -0
  23. semantic_context_engine/prompts/v1/relationship_proposal.md +10 -0
  24. semantic_context_engine/prompts/v1/synthesis.md +5 -0
  25. semantic_context_engine/prompts/v1/taxonomy.md +5 -0
  26. semantic_context_engine/publication.py +98 -0
  27. semantic_context_engine/registry.py +764 -0
  28. semantic_context_engine/relations.py +1114 -0
  29. semantic_context_engine/runtime.py +1193 -0
  30. semantic_context_engine/sources/base.py +130 -0
  31. semantic_context_engine/sources/duckdb.py +1172 -0
  32. semantic_context_engine/sources/fake.py +107 -0
  33. semantic_context_engine/storage.py +248 -0
  34. semantic_context_engine-0.3.0a1.dist-info/METADATA +263 -0
  35. semantic_context_engine-0.3.0a1.dist-info/RECORD +39 -0
  36. semantic_context_engine-0.3.0a1.dist-info/WHEEL +5 -0
  37. semantic_context_engine-0.3.0a1.dist-info/entry_points.txt +2 -0
  38. semantic_context_engine-0.3.0a1.dist-info/licenses/LICENSE +202 -0
  39. semantic_context_engine-0.3.0a1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,316 @@
1
+ """Structural compilation from an allowlisted source against a pinned baseline."""
2
+
3
+ from typing import Any, Callable, Dict, List, Set
4
+
5
+ from semantic_context_engine.registry import Registry
6
+ from semantic_context_engine.sources.base import Source
7
+ from semantic_context_engine.models import ObjectSnapshot, VariantKey
8
+
9
+ from semantic_context_engine.normalization import normalize_object_metadata
10
+ from semantic_context_engine.errors import SourceError, StorageError, safe_error_label
11
+
12
+
13
+ class StructuralCompiler:
14
+ """Build a validated structural candidate against one pinned baseline.
15
+
16
+ Dependencies are explicit; this stage never reaches through an engine facade.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ *,
22
+ config: Any,
23
+ source: Source,
24
+ registry: Registry,
25
+ failure_report: Callable[[str], dict],
26
+ first_sync_report: Callable[..., dict],
27
+ subsequent_sync_report: Callable[..., dict],
28
+ ):
29
+ self.config = config
30
+ self.source = source
31
+ self.registry = registry
32
+ self.failure_report = failure_report
33
+ self.first_sync_report = first_sync_report
34
+ self.subsequent_sync_report = subsequent_sync_report
35
+
36
+ def compile(self, publish=False, expected_baseline=None):
37
+ # 1. Carregar allowlist e descrever objetos (apenas keys da allowlist)
38
+ allowlist = self.config.object_keys
39
+ # Fail closed even when a config object is mutated after validation.
40
+ if not allowlist:
41
+ return {
42
+ "early_report": self.failure_report(
43
+ "Explicit non-empty object allowlist is required"
44
+ )
45
+ }
46
+ # Pin a single immutable baseline before source inspection or compilation.
47
+ # A caller may pass a previously captured token to model a long-running
48
+ # compile; publication must still compare against that exact token.
49
+ try:
50
+ baseline_pointer = (
51
+ self.registry.read_active_pointer()
52
+ if expected_baseline is None
53
+ else expected_baseline
54
+ )
55
+ baseline = self.registry.load_active(pointer=baseline_pointer)
56
+ override_revision = self.registry.override_revision()
57
+ except Exception as exc:
58
+ label = safe_error_label(exc)
59
+ if label == "operation_failed":
60
+ storage_error = StorageError("Catalog storage read failed")
61
+ storage_error.__cause__ = exc
62
+ label = safe_error_label(storage_error)
63
+ return {"early_report": self.failure_report(f"Catalog baseline unavailable ({label})")}
64
+ try:
65
+ raw_objects = self.source.describe_many(list(allowlist))
66
+ if not isinstance(raw_objects, dict):
67
+ raise TypeError("Source.describe_many() must return a mapping")
68
+ except KeyError:
69
+ # A missing requested key is a per-object failure, while other
70
+ # source exceptions remain a source-level failure.
71
+ try:
72
+ available = set(self.source.allowlist())
73
+ except Exception:
74
+ return {
75
+ "early_report": self.failure_report(
76
+ f"Source metadata unavailable ({safe_error_label(SourceError())})"
77
+ )
78
+ }
79
+ missing = set(allowlist) - available
80
+ if not missing:
81
+ return {
82
+ "early_report": self.failure_report(
83
+ f"Source metadata unavailable ({safe_error_label(SourceError())})"
84
+ )
85
+ }
86
+ try:
87
+ present = [key for key in allowlist if key in available]
88
+ raw_objects = self.source.describe_many(present) if present else {}
89
+ except Exception:
90
+ return {
91
+ "early_report": self.failure_report(
92
+ f"Source metadata unavailable ({safe_error_label(SourceError())})"
93
+ )
94
+ }
95
+ except Exception as e:
96
+ source_error = SourceError("Source metadata read failed")
97
+ source_error.__cause__ = e
98
+ return {
99
+ "early_report": self.failure_report(
100
+ f"Source metadata unavailable ({safe_error_label(source_error)})"
101
+ )
102
+ }
103
+
104
+ extras = set(raw_objects) - set(allowlist)
105
+ if extras:
106
+ return {
107
+ "early_report": self.failure_report(
108
+ "Source returned non-allowlisted objects: "
109
+ + ", ".join(sorted(map(str, extras)))
110
+ )
111
+ }
112
+ for key, raw in raw_objects.items():
113
+ if not isinstance(raw, dict) or raw.get("key") != key:
114
+ return {
115
+ "early_report": self.failure_report(
116
+ f"Source returned invalid metadata identity for allowlisted key {key!r}"
117
+ )
118
+ }
119
+ configured = self.config.object_fqns.get(key)
120
+ returned = raw.get("fqn")
121
+ if not isinstance(returned, str) or not isinstance(configured, str):
122
+ return {
123
+ "early_report": self.failure_report(
124
+ f"Source physical identity is missing for allowlisted key {key!r}"
125
+ )
126
+ }
127
+
128
+ def canonical(value):
129
+ return tuple(part.strip().strip('"`[]').casefold() for part in value.split("."))
130
+
131
+ if canonical(returned) != canonical(configured):
132
+ return {
133
+ "early_report": self.failure_report(
134
+ f"Source physical identity mismatch for allowlisted key {key!r}"
135
+ )
136
+ }
137
+ # 2. Normalizar cada objeto
138
+ snapshots_objects: Dict[str, ObjectSnapshot] = {}
139
+ ddl_unavailable: List[Dict[str, str]] = []
140
+ # Chaves da allowlist que faltam no description do source
141
+ missing_keys: Set[str] = set()
142
+ for key in allowlist or []:
143
+ if key not in raw_objects:
144
+ missing_keys.add(key)
145
+
146
+ # Separar missing keys que estavam no baseline (remoção) de ones que sao realmente novos (falha).
147
+ # A distincao considera se a key ainda esta no object_keys do config:
148
+ # - se object_keys NÃO inclui a key -> e remocao intencional (teste 1.3)
149
+ # - se object_keys INCLUI a key -> e falha de source incompleta (teste 1.6)
150
+ removed_via_missing: Set[str] = set()
151
+ truly_missing_keys: Set[str] = set()
152
+ object_keys_set = set(self.config.object_keys) if self.config.object_keys else set()
153
+ for key in sorted(missing_keys):
154
+ in_object_keys = key in object_keys_set
155
+ baseline_obj = None
156
+ try:
157
+ base_registry = self.registry
158
+ base_baseline = base_registry.load_active()
159
+ baseline_obj = base_baseline.objects.get(key) if base_baseline else None
160
+ except Exception:
161
+ baseline_obj = None
162
+ if baseline_obj is not None and not in_object_keys:
163
+ removed_via_missing.add(key)
164
+ else:
165
+ truly_missing_keys.add(key)
166
+
167
+ # Initialize failed dict for truly missing keys and normalization errors
168
+ failed: Dict[str, str] = {}
169
+ for key in truly_missing_keys:
170
+ failed[key] = "Allowlisted object was not found in source"
171
+
172
+ for key, raw in raw_objects.items():
173
+ try:
174
+ if not isinstance(raw, dict):
175
+ raise TypeError("metadata must be a mapping")
176
+ if raw.get("key") != key:
177
+ raise ValueError(
178
+ f"metadata key {raw.get('key')!r} does not match returned key {key!r}"
179
+ )
180
+ obj = normalize_object_metadata(
181
+ raw, dialect=getattr(self.source, "dialect", "generic")
182
+ )
183
+ # Opt-in JSON evidence is folded into the structural variant
184
+ # contract before diffing so a new approved key/type invalidates
185
+ # dependent semantic work. Only key/type/slice metadata survives.
186
+ policies = raw.get("json_profiles", [])
187
+ profile_reader = getattr(self.source, "profile_json_keys", None)
188
+ if policies and callable(profile_reader):
189
+ observed = []
190
+ for profile_index in range(len(policies)):
191
+ profile = profile_reader(key, profile_index=profile_index)
192
+ for slice_item in profile.get("slices", []):
193
+ for key_item in slice_item.get("keys", []):
194
+ observed.append(
195
+ {
196
+ "column": profile["column"],
197
+ "discriminator": f"{profile['discriminator']}={slice_item['value']}",
198
+ "key": key_item["key"],
199
+ "value_type": key_item["value_type"],
200
+ "rows": slice_item["rows"],
201
+ "present": key_item["present"],
202
+ "status": profile["status"],
203
+ }
204
+ )
205
+ observed.sort(
206
+ key=lambda item: (
207
+ item["column"],
208
+ item["discriminator"],
209
+ item["key"],
210
+ item["value_type"],
211
+ )
212
+ )
213
+ obj.variant_keys = [VariantKey(**item) for item in observed]
214
+ from semantic_context_engine.normalization import compute_fingerprint
215
+
216
+ obj.fingerprint = compute_fingerprint(
217
+ fqn=obj.fqn,
218
+ object_type=obj.object_type,
219
+ description=obj.description,
220
+ hint=obj.hint,
221
+ table_comment=obj.table_comment,
222
+ columns={
223
+ name: {
224
+ "data_type": col.data_type,
225
+ "nullable": col.nullable,
226
+ "comment": col.comment,
227
+ }
228
+ for name, col in obj.columns.items()
229
+ },
230
+ ddl_canonical=obj.ddl_canonical,
231
+ variant_keys=observed,
232
+ declared_constraints=obj.declared_constraints,
233
+ )
234
+ snapshots_objects[key] = obj
235
+ if obj.ddl_error:
236
+ ddl_unavailable.append({"key": key, "error": "ddl_unavailable"})
237
+ except Exception:
238
+ failed[key] = "metadata_validation_failed"
239
+
240
+ # 3. Construir candidate snapshot
241
+ from semantic_context_engine.models import StructuralSnapshot as SS
242
+
243
+ candidate = SS(
244
+ version=__import__("datetime")
245
+ .datetime.now(__import__("datetime").timezone.utc)
246
+ .strftime("%Y%m%dT%H%M%S.%fZ"),
247
+ objects=snapshots_objects,
248
+ )
249
+
250
+ # 4. Use the baseline captured before compilation.
251
+ registry = self.registry
252
+ if baseline is not None:
253
+ # Freeze unchanged objects so a later semantic-only publish does not
254
+ # refresh structural timestamps or rewrite stable metadata.
255
+ for key, obj in list(candidate.objects.items()):
256
+ old = baseline.objects.get(key)
257
+ if old is not None and old.fingerprint == obj.fingerprint:
258
+ candidate.objects[key] = old
259
+
260
+ # 5. Calcular diff e report
261
+ if not baseline:
262
+ report = self.first_sync_report(candidate, publish=publish)
263
+ else:
264
+ report = self.subsequent_sync_report(baseline, candidate, publish=publish)
265
+
266
+ # Connector diagnostics are an allowlisted projection, not free-form
267
+ # source text: expose only known codes and the already authorized object
268
+ # key. In particular, never echo a referenced non-allowlisted FQN.
269
+ safe_constraint_codes = {
270
+ "constraint_target_not_allowlisted",
271
+ "constraint_target_ambiguous_in_allowlist",
272
+ }
273
+ constraint_diagnostics = []
274
+ for key, raw in raw_objects.items():
275
+ if not isinstance(raw, dict):
276
+ continue
277
+ codes = raw.get("constraint_diagnostics", [])
278
+ if isinstance(codes, list):
279
+ for code in codes:
280
+ if isinstance(code, str) and code in safe_constraint_codes:
281
+ constraint_diagnostics.append({"object": key, "code": code})
282
+ if constraint_diagnostics:
283
+ report["constraint_diagnostics"] = constraint_diagnostics
284
+
285
+ # Update report with removal info for keys that were in baseline but missing from source
286
+ for key in removed_via_missing:
287
+ if key in report.get("removed", []):
288
+ pass # already there
289
+ else:
290
+ report.setdefault("removed", []).append(key)
291
+ # Report truly missing keys in failed
292
+ for key in truly_missing_keys:
293
+ failed[key] = "Allowlisted object was not found in source"
294
+
295
+ # Never publish an incomplete candidate after a missing or invalid
296
+ # allowlisted object. Only treat as failure if there are truly missing keys
297
+ # (not previously active ones that are being removed).
298
+ if truly_missing_keys or failed:
299
+ report["status"] = "failed"
300
+ report.setdefault("failed", {}).update(failed)
301
+ return {"early_report": report}
302
+ return {
303
+ "allowlist": allowlist,
304
+ "baseline_pointer": baseline_pointer,
305
+ "baseline": baseline,
306
+ "override_revision": override_revision,
307
+ "raw_objects": raw_objects,
308
+ "snapshots_objects": snapshots_objects,
309
+ "ddl_unavailable": ddl_unavailable,
310
+ "removed_via_missing": removed_via_missing,
311
+ "truly_missing_keys": truly_missing_keys,
312
+ "failed": failed,
313
+ "candidate": candidate,
314
+ "registry": registry,
315
+ "report": report,
316
+ }
@@ -0,0 +1,31 @@
1
+ """Construction helpers for the public engine facade."""
2
+
3
+ from semantic_context_engine.sources.fake import FakeSource
4
+
5
+
6
+ def compose_components(config, registry=None, source=None):
7
+ """Resolve injected or configured Source and Registry dependencies.
8
+
9
+ This is intentionally a construction-only boundary: it does not inspect
10
+ source data or mutate storage. Application-owned connectors remain injected.
11
+ """
12
+ if source is not None:
13
+ resolved_source = source
14
+ elif config.source_type == "fake":
15
+ resolved_source = FakeSource()
16
+ elif config.source_type == "duckdb":
17
+ raise ValueError("DuckDB source requires injection via SemanticEngine(config, source=...) ")
18
+ else:
19
+ raise ValueError(
20
+ f"Source type '{config.source_type}' not supported. "
21
+ "Use 'fake' or inject a custom Source instance via "
22
+ "SemanticEngine(config, source=custom_source)."
23
+ )
24
+
25
+ if registry is None:
26
+ uri = getattr(config, "storage_uri", "~/.semantic_context_engine")
27
+ from semantic_context_engine.registry import Registry
28
+ from semantic_context_engine.storage import storage_from_uri
29
+
30
+ registry = Registry(storage_from_uri(uri), config.namespace)
31
+ return resolved_source, registry
@@ -0,0 +1,199 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import json
5
+ import re
6
+ from typing import Dict, List, Tuple
7
+
8
+ from semantic_context_engine.sources.fake import FakeSource
9
+ from semantic_context_engine.domain_contracts import SemanticConfigContract
10
+ from semantic_context_engine.errors import ConfigurationError
11
+ from pydantic import ValidationError as PydanticValidationError
12
+
13
+
14
+ class SemanticConfig:
15
+ """Modelo de configuração da semantic layer - versões simplificada."""
16
+
17
+ def __init__(self, raw: dict):
18
+ if not isinstance(raw, dict):
19
+ raise ValueError("Configuration must be a mapping")
20
+ self.namespace: str = raw.get("namespace", "")
21
+ if not isinstance(self.namespace, str) or not re.fullmatch(
22
+ r"[A-Za-z0-9_-]+", self.namespace
23
+ ):
24
+ raise ValueError(
25
+ "Configuration requires a valid namespace (letters, numbers, '_' or '-')"
26
+ )
27
+ source_cfg: dict = raw.get("source", {})
28
+ if not isinstance(source_cfg, dict) or not source_cfg.get("type"):
29
+ raise ValueError("Configuration requires an explicit source.type")
30
+
31
+ # source type
32
+ self.source_type: str = source_cfg["type"]
33
+
34
+ # Build the source instance based on type
35
+ source_name = source_cfg["type"]
36
+ if source_name == "fake":
37
+ self.source = FakeSource()
38
+ elif source_name == "custom":
39
+ # Custom source must be injected via SemanticEngine(source=...)
40
+ # O engine levantará ValueError se source não for instanciado corretamente
41
+ self.source = None # type: ignore[assignment]
42
+ elif source_name == "duckdb":
43
+ # Connection ownership stays with the application; inject its source.
44
+ self.source = None # type: ignore[assignment]
45
+ else:
46
+ raise ConfigurationError(
47
+ "Unsupported source type. Use 'fake', 'custom' or 'duckdb' (injected via engine)."
48
+ )
49
+
50
+ # Storage must be explicit: do not create a catalog in an implicit home directory.
51
+ raw_storage = raw.get("storage", source_cfg.get("storage"))
52
+ if (
53
+ not isinstance(raw_storage, dict)
54
+ or not isinstance(raw_storage.get("uri"), str)
55
+ or not raw_storage["uri"].strip()
56
+ ):
57
+ raise ValueError("Configuration requires an explicit storage.uri")
58
+ self.storage_uri: str = raw_storage["uri"].strip()
59
+
60
+ # Parse objects allowlist - keys from objects
61
+ # The raw dict may have objects directly under namespace, or under source.objects (from YAML parser)
62
+ objects = raw.get("objects", source_cfg.get("objects"))
63
+ if not isinstance(objects, list) or not objects:
64
+ raise ValueError("Configuration requires a non-empty explicit objects allowlist")
65
+ keys: List[str] = []
66
+ self.object_fqns: Dict[str, str] = {}
67
+ for item in objects:
68
+ if (
69
+ not isinstance(item, dict)
70
+ or not isinstance(item.get("key"), str)
71
+ or not item["key"].strip()
72
+ ):
73
+ raise ValueError("Each allowlisted object requires a non-empty canonical key")
74
+ if not isinstance(item.get("fqn"), str) or not item["fqn"].strip():
75
+ raise ValueError(f"Allowlisted object {item['key']!r} requires a non-empty fqn")
76
+ key = item["key"].strip()
77
+ if key in keys:
78
+ raise ValueError(f"Duplicate object key in allowlist: {key}")
79
+ keys.append(key)
80
+ self.object_fqns[key] = item["fqn"].strip()
81
+ self.object_keys = tuple(keys)
82
+ enrichment_cfg = raw.get("enrichment", {})
83
+ if not isinstance(enrichment_cfg, dict):
84
+ raise ValueError("Configuration enrichment must be a mapping")
85
+ query_budget = enrichment_cfg.get("query_budget_per_object", 2)
86
+ if isinstance(query_budget, bool) or not isinstance(query_budget, int) or query_budget < 0:
87
+ raise ValueError("enrichment.query_budget_per_object must be a non-negative integer")
88
+ self.enrichment_query_budget = query_budget
89
+ hierarchy_budget = enrichment_cfg.get("hierarchy_query_budget_per_object", 0)
90
+ if (
91
+ isinstance(hierarchy_budget, bool)
92
+ or not isinstance(hierarchy_budget, int)
93
+ or not 0 <= hierarchy_budget <= 64
94
+ ):
95
+ raise ValueError(
96
+ "enrichment.hierarchy_query_budget_per_object must be an integer from 0 to 64"
97
+ )
98
+ self.hierarchy_query_budget = hierarchy_budget
99
+ formula_budget = enrichment_cfg.get("formula_query_budget_per_object", 4)
100
+ if (
101
+ isinstance(formula_budget, bool)
102
+ or not isinstance(formula_budget, int)
103
+ or not 0 <= formula_budget <= 64
104
+ ):
105
+ raise ValueError(
106
+ "enrichment.formula_query_budget_per_object must be an integer from 0 to 64"
107
+ )
108
+ self.formula_query_budget = formula_budget
109
+ discriminator_budget = enrichment_cfg.get("discriminator_query_budget_per_object", 0)
110
+ if (
111
+ isinstance(discriminator_budget, bool)
112
+ or not isinstance(discriminator_budget, int)
113
+ or not 0 <= discriminator_budget <= 64
114
+ ):
115
+ raise ValueError(
116
+ "enrichment.discriminator_query_budget_per_object must be an integer from 0 to 64"
117
+ )
118
+ self.discriminator_query_budget = discriminator_budget
119
+ self.sampling = enrichment_cfg.get("sampling", {})
120
+ if not isinstance(self.sampling, dict):
121
+ raise ValueError("enrichment.sampling must be a mapping")
122
+ self.sampling_enabled = self.sampling.get("enabled", False)
123
+ self.sampling_mode = self.sampling.get("mode", "rows")
124
+ self.sampling_max_rows = self.sampling.get("max_rows_per_object", 5)
125
+ self.sampling_max_values = self.sampling.get("max_values_per_column", 5)
126
+ self.sampling_max_payload_bytes = self.sampling.get("max_payload_bytes", 8192)
127
+ self.sampling_max_value_bytes = self.sampling.get("max_value_bytes", 256)
128
+ self.sampling_max_queries = self.sampling.get("max_queries_per_run", 0)
129
+ self.sampling_allowed_columns = self.sampling.get("allowed_columns", {})
130
+ self.profiling = enrichment_cfg.get("profiling", {})
131
+ if not isinstance(self.profiling, dict):
132
+ raise ValueError("enrichment.profiling must be a mapping")
133
+ relations_cfg = raw.get("relations", {})
134
+ if not isinstance(relations_cfg, dict):
135
+ raise ValueError("Configuration relations must be a mapping")
136
+ self.relation_min_match_rate = relations_cfg.get("min_match_rate", 0.5)
137
+ if (
138
+ isinstance(self.relation_min_match_rate, bool)
139
+ or not isinstance(self.relation_min_match_rate, (int, float))
140
+ or not 0 <= self.relation_min_match_rate <= 1
141
+ ):
142
+ raise ValueError("relations.min_match_rate must be between 0 and 1")
143
+ self.relation_query_budget_per_pair = relations_cfg.get("query_budget_per_pair", 1)
144
+ if (
145
+ isinstance(self.relation_query_budget_per_pair, bool)
146
+ or not isinstance(self.relation_query_budget_per_pair, int)
147
+ or self.relation_query_budget_per_pair < 0
148
+ ):
149
+ raise ValueError("relations.query_budget_per_pair must be a non-negative integer")
150
+ self.relation_max_pairs = relations_cfg.get("max_pairs_per_run", 50)
151
+ if (
152
+ isinstance(self.relation_max_pairs, bool)
153
+ or not isinstance(self.relation_max_pairs, int)
154
+ or self.relation_max_pairs < 0
155
+ ):
156
+ raise ValueError("relations.max_pairs_per_run must be a non-negative integer")
157
+ try:
158
+ SemanticConfigContract.model_validate(raw)
159
+ except PydanticValidationError as exc:
160
+ raise ConfigurationError(
161
+ "Configuration contains unsupported fields or invalid field types"
162
+ ) from exc
163
+
164
+ @property
165
+ def all_fqns(self) -> Tuple[str, ...]:
166
+ return self.source.all_fqns()
167
+
168
+
169
+ def _parse_yaml_simple(text: str) -> dict:
170
+ """Parse the documented YAML config shape, including nested lists."""
171
+ import yaml
172
+
173
+ parsed = yaml.safe_load(text)
174
+ return parsed if isinstance(parsed, dict) else {}
175
+
176
+
177
+ def load_config(config_path: str) -> "SemanticConfig":
178
+ """Carrega configuração a partir de um arquivo (JSON ou YAML simplificado)."""
179
+ if not os.path.isfile(config_path):
180
+ raise FileNotFoundError(f"Configuration file not found: {config_path}")
181
+ with open(config_path, "r", encoding="utf-8") as f:
182
+ text = f.read()
183
+ try:
184
+ raw = json.loads(text)
185
+ except json.JSONDecodeError:
186
+ raw = _parse_yaml_simple(text)
187
+ if not raw:
188
+ raise ValueError("Configuration file is empty or invalid")
189
+
190
+ return SemanticConfig(raw)
191
+
192
+
193
+ def __getattr__(name: str):
194
+ """Resolve the former config-module engine import without an import cycle."""
195
+ if name == "SemanticEngine":
196
+ from semantic_context_engine.engine import SemanticEngine
197
+
198
+ return SemanticEngine
199
+ raise AttributeError(name)
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, List
4
+
5
+ from semantic_context_engine.models import (
6
+ StructuralSnapshot,
7
+ )
8
+
9
+
10
+ def diff_structural(
11
+ baseline: StructuralSnapshot,
12
+ candidate: StructuralSnapshot,
13
+ ) -> Dict:
14
+ """Diferença estrutural entre dois snapshots (Incremento 1).
15
+
16
+ Retorna dicionário com:
17
+ - added: chaves novas no candidate
18
+ - changed: chaves com alterações (listas de campos)
19
+ - unchanged: chaves idênticas (fingerprint igual)
20
+ - removed: chaves removidas
21
+ - failed: chaves com erro de DDL
22
+ - status: "dry_run" | "published" | "no_changes" | "failed"
23
+ """
24
+ added: List[str] = []
25
+ changed: Dict[str, List[str]] = {}
26
+ unchanged: List[str] = []
27
+ removed: List[str] = []
28
+ failed: Dict[str, str] = {}
29
+
30
+ baseline_keys = set(baseline.objects.keys())
31
+ candidate_keys = set(candidate.objects.keys())
32
+
33
+ # Removidas
34
+ for key in sorted(baseline_keys - candidate_keys):
35
+ removed.append(key)
36
+
37
+ # Novas
38
+ for key in sorted(candidate_keys - baseline_keys):
39
+ added.append(key)
40
+
41
+ # Comuns - verificar fingerprint
42
+ for key in sorted(baseline_keys & candidate_keys):
43
+ b_obj = baseline.objects[key]
44
+ c_obj = candidate.objects[key]
45
+
46
+ if b_obj.fingerprint == c_obj.fingerprint:
47
+ unchanged.append(key)
48
+ else:
49
+ # Report exact canonical field groups in stable order. Fingerprints
50
+ # remain the authority for whether an object changed; the field list
51
+ # explains all modeled fingerprint inputs without inventing a diff.
52
+ fields_changed: List[str] = []
53
+ if b_obj.fqn != c_obj.fqn:
54
+ fields_changed.append("fqn")
55
+ if b_obj.object_type != c_obj.object_type:
56
+ fields_changed.append("object_type")
57
+ if b_obj.description != c_obj.description:
58
+ fields_changed.append("description")
59
+ if b_obj.hint != c_obj.hint:
60
+ fields_changed.append("hint")
61
+ if b_obj.table_comment != c_obj.table_comment:
62
+ fields_changed.append("table_comment")
63
+ if b_obj.columns != c_obj.columns:
64
+ fields_changed.append("columns")
65
+ if b_obj.ddl_canonical != c_obj.ddl_canonical:
66
+ fields_changed.append("ddl_canonical")
67
+ if b_obj.variant_keys != c_obj.variant_keys:
68
+ fields_changed.append("variant_keys")
69
+ if getattr(b_obj, "declared_constraints", []) != getattr(
70
+ c_obj, "declared_constraints", []
71
+ ):
72
+ fields_changed.append("declared_constraints")
73
+ changed[key] = fields_changed or ["fingerprint_diff"]
74
+
75
+ # DDL is best-effort (D15); availability/parse errors are reported by sync
76
+ # as ddl_unavailable and do not invalidate otherwise sound metadata.
77
+
78
+ # Status final
79
+ if failed:
80
+ status = "failed"
81
+ elif not (added or changed or removed):
82
+ status = "no_changes"
83
+ else:
84
+ status = "published"
85
+
86
+ return {
87
+ "status": status,
88
+ "added": added,
89
+ "changed": changed,
90
+ "removed": removed,
91
+ "unchanged": unchanged,
92
+ "failed": failed,
93
+ }