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,386 @@
1
+ """Pydantic contracts for public reports, source capabilities, and overrides."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from pydantic import (
8
+ BaseModel,
9
+ ConfigDict,
10
+ Field,
11
+ StrictBool,
12
+ StrictFloat,
13
+ StrictInt,
14
+ StrictStr,
15
+ model_validator,
16
+ )
17
+
18
+
19
+ class SourceCapabilitiesContract(BaseModel):
20
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
21
+ ddl: bool = False
22
+ grain_aggregate: bool = False
23
+ relationship_aggregate: bool = False
24
+ semistructured_profile: bool = False
25
+ hierarchy_aggregate: bool = False
26
+ relationship_key_transforms: bool = False
27
+ bounded_sampling: bool = False
28
+ column_statistics: bool = False
29
+
30
+
31
+ class SyncReportContract(BaseModel):
32
+ """Stable mapping-shaped report core; stage-specific evidence stays extensible."""
33
+
34
+ model_config = ConfigDict(extra="allow", strict=True)
35
+ status: Literal["dry_run", "published", "no_changes", "failed"]
36
+ baseline: str | None = None
37
+ candidate: str | None = None
38
+ added: list[str] = Field(default_factory=list)
39
+ changed: dict[str, list[str]] = Field(default_factory=dict)
40
+ removed: list[str] = Field(default_factory=list)
41
+ unchanged: list[str] = Field(default_factory=list)
42
+ failed: dict[str, Any] = Field(default_factory=dict)
43
+ ddl_unavailable: list[dict[str, str]] = Field(default_factory=list)
44
+ override_conflicts: list[dict[str, Any]] = Field(default_factory=list)
45
+ enrichment_diagnostics: list["EnrichmentDiagnosticContract"] = Field(default_factory=list)
46
+ semantic_execution: "SemanticExecutionContract | None" = None
47
+
48
+
49
+ class EnrichmentDiagnosticContract(BaseModel):
50
+ """Safe structured details for a failed semantic compilation stage."""
51
+
52
+ model_config = ConfigDict(extra="forbid", strict=True)
53
+ object: StrictStr
54
+ stage: Literal[
55
+ "taxonomy", "families", "synthesis", "grain_correction", "persistence", "unknown_stage"
56
+ ]
57
+ category: Literal[
58
+ "semantic_validation",
59
+ "provider_authentication",
60
+ "provider_configuration",
61
+ "provider_request_rejected",
62
+ "transport_failure",
63
+ "rate_limited",
64
+ "unsupported_structured_output",
65
+ "incomplete_response",
66
+ "structured_output_parse_failure",
67
+ "pydantic_schema_validation_failure",
68
+ "source_failure",
69
+ "storage_failure",
70
+ "internal_error",
71
+ ]
72
+ code: StrictStr
73
+ retryable: StrictBool
74
+ attempts: StrictInt | None = None
75
+ http_status: StrictInt | None = None
76
+ expected_columns: StrictInt | None = None
77
+ classified_columns: StrictInt | None = None
78
+ invalid_count: StrictInt | None = None
79
+ missing_columns: list[StrictStr] = Field(default_factory=list)
80
+ columns: list[StrictStr] = Field(default_factory=list)
81
+ telemetry: dict[str, Any] = Field(default_factory=dict)
82
+
83
+
84
+ class StageExecutionEventContract(BaseModel):
85
+ model_config = ConfigDict(extra="forbid", strict=True)
86
+ object: StrictStr
87
+ stage: Literal[
88
+ "taxonomy",
89
+ "families",
90
+ "synthesis",
91
+ "grain_correction",
92
+ "persistence",
93
+ "relations",
94
+ "publication",
95
+ "unknown_stage",
96
+ ]
97
+ status: Literal["completed", "failed", "skipped", "unattempted"]
98
+ reason: StrictStr | None = None
99
+
100
+
101
+ class SemanticExecutionContract(BaseModel):
102
+ model_config = ConfigDict(extra="forbid", strict=True)
103
+ fail_fast: StrictBool
104
+ stages: list[StageExecutionEventContract] = Field(default_factory=list)
105
+
106
+
107
+ class FormulaContract(BaseModel):
108
+ model_config = ConfigDict(extra="forbid", strict=True)
109
+ expression: str | None = None
110
+ recompute_from: list[str] | None = None
111
+ aggregation: Literal["additive", "ratio_of_sums", "non_additive"] | None = None
112
+ # Explicit, ordered formula proposal metadata. Legacy contracts default to
113
+ # unknown/not-checked; operand count is never used to infer an operator.
114
+ operator: Literal["sum", "ratio_of_sums", "unknown"] = "unknown"
115
+ operands: list[StrictStr] = Field(default_factory=list)
116
+ proposal_status: Literal["proposed", "not_proposed"] = "not_proposed"
117
+ schema_status: Literal["valid", "invalid", "not_checked"] = "not_checked"
118
+ coverage_status: Literal["complete", "partial", "measured", "unverified", "not_checked"] = (
119
+ "not_checked"
120
+ )
121
+ numerical_evidence_status: Literal["supported", "contradicted", "not_measured"] = "not_measured"
122
+ approval_status: Literal["approved", "not_approved"] = "not_approved"
123
+
124
+ @model_validator(mode="after")
125
+ def validate_operator_arity(self) -> "FormulaContract":
126
+ operands_were_set = "operands" in self.model_fields_set
127
+ refs_were_set = "recompute_from" in self.model_fields_set
128
+ operands = self.operands if operands_were_set else self.recompute_from or []
129
+ if operands_were_set and refs_were_set and self.operands != (self.recompute_from or []):
130
+ raise ValueError("formula operands must preserve recompute_from order")
131
+ effective_operator: str = self.operator
132
+ if effective_operator == "unknown":
133
+ # A human-selected aggregation is an explicit legacy declaration;
134
+ # operand count alone must never supply a missing ratio operator.
135
+ if self.aggregation == "additive":
136
+ effective_operator = "sum"
137
+ elif self.aggregation == "ratio_of_sums":
138
+ effective_operator = "ratio_of_sums"
139
+ expected_aggregation = {
140
+ "sum": "additive",
141
+ "ratio_of_sums": "ratio_of_sums",
142
+ }.get(effective_operator)
143
+ if (
144
+ expected_aggregation is not None
145
+ and self.aggregation is not None
146
+ and self.aggregation != expected_aggregation
147
+ ):
148
+ raise ValueError("formula operator conflicts with aggregation")
149
+ if effective_operator == "sum" and len(operands) != 1:
150
+ raise ValueError("sum formula operator requires exactly one ordered operand")
151
+ if effective_operator == "ratio_of_sums" and len(operands) != 2:
152
+ raise ValueError("ratio_of_sums requires exactly two ordered operands")
153
+ return self
154
+
155
+
156
+ class ColumnOverrideContract(BaseModel):
157
+ model_config = ConfigDict(extra="forbid", strict=True)
158
+ role: str | None = None
159
+ family: str | None = None
160
+ description: str | None = None
161
+ limitations: list[str] | None = None
162
+ recompute_from: list[str] | None = None
163
+ formula: FormulaContract | None = None
164
+
165
+ @model_validator(mode="after")
166
+ def validate_formula_reference_consistency(self) -> "ColumnOverrideContract":
167
+ if self.formula is None or self.recompute_from is None:
168
+ return self
169
+ formula_refs_were_set = (
170
+ "operands" in self.formula.model_fields_set
171
+ or "recompute_from" in self.formula.model_fields_set
172
+ )
173
+ if not formula_refs_were_set:
174
+ return self
175
+ formula_refs = (
176
+ self.formula.operands
177
+ if "operands" in self.formula.model_fields_set
178
+ else self.formula.recompute_from or []
179
+ )
180
+ if self.recompute_from != formula_refs:
181
+ raise ValueError("column and formula operands must preserve the same order")
182
+ return self
183
+
184
+
185
+ class ObjectOverrideContract(BaseModel):
186
+ model_config = ConfigDict(extra="forbid", strict=True)
187
+ role: str | None = None
188
+ family: str | None = None
189
+ description: str | None = None
190
+ time_column: str | None = None
191
+ grain: list[str] | None = None
192
+ limitations: list[str] | None = None
193
+ columns: dict[str, ColumnOverrideContract] = Field(default_factory=dict)
194
+
195
+
196
+ class RelationshipOverrideContract(BaseModel):
197
+ model_config = ConfigDict(extra="forbid", strict=True)
198
+ id: str
199
+ type: Literal["join", "temporal", "lineage", "forbidden"]
200
+ source: str
201
+ target: str
202
+ source_columns: list[str]
203
+ target_columns: list[str]
204
+ reason: str | None = None
205
+ human_note: str | None = None
206
+
207
+
208
+ class OverrideDocumentContract(BaseModel):
209
+ model_config = ConfigDict(extra="forbid", strict=True)
210
+ schema_version: Literal[1]
211
+ relationships: list[RelationshipOverrideContract]
212
+ objects: dict[str, ObjectOverrideContract] = Field(default_factory=dict)
213
+ entities: dict[str, ObjectOverrideContract] = Field(default_factory=dict)
214
+ reviewer: str | None = None
215
+
216
+
217
+ class StorageConfigContract(BaseModel):
218
+ model_config = ConfigDict(extra="forbid", strict=True)
219
+ uri: StrictStr
220
+ type: StrictStr | None = None
221
+
222
+
223
+ class AllowlistedObjectContract(BaseModel):
224
+ model_config = ConfigDict(extra="forbid", strict=True)
225
+ key: StrictStr
226
+ fqn: StrictStr
227
+ description: StrictStr | None = None
228
+ hint: StrictStr | None = None
229
+ json_profiles: list["JsonProfilePolicyContract"] = Field(default_factory=list, max_length=4)
230
+ discriminator_profiles: list["DiscriminatorProfilePolicyContract"] = Field(
231
+ default_factory=list, max_length=8
232
+ )
233
+ hierarchy_columns: list[StrictStr] = Field(default_factory=list, max_length=32)
234
+
235
+
236
+ class DiscriminatorProfilePolicyContract(BaseModel):
237
+ """Opt-in approved scalar slices for aggregate coverage and grain evidence."""
238
+
239
+ model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
240
+ column: StrictStr
241
+ approved_values: list[StrictStr] = Field(min_length=1, max_length=16)
242
+
243
+
244
+ class JsonProfilePolicyContract(BaseModel):
245
+ """Opt-in, bounded JSON-key profiling policy for one object."""
246
+
247
+ model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
248
+ column: StrictStr
249
+ discriminator_column: StrictStr
250
+ approved_values: list[StrictStr] = Field(min_length=1, max_length=16)
251
+ max_keys: StrictInt = Field(default=64, ge=1, le=256)
252
+ max_depth: StrictInt = Field(default=1, ge=1, le=4)
253
+
254
+
255
+ class SourceConfigContract(BaseModel):
256
+ model_config = ConfigDict(extra="forbid", strict=True)
257
+ type: Literal["fake", "custom", "duckdb"]
258
+ storage: StorageConfigContract | None = None
259
+ objects: list[AllowlistedObjectContract] | None = None
260
+
261
+
262
+ class SamplingConfigContract(BaseModel):
263
+ model_config = ConfigDict(extra="forbid", strict=True)
264
+ enabled: StrictBool = False
265
+ mode: Literal["rows", "distinct"] = "rows"
266
+ max_rows_per_object: StrictInt = Field(default=5, ge=0, le=100)
267
+ max_values_per_column: StrictInt = Field(default=5, ge=0, le=100)
268
+ max_payload_bytes: StrictInt = Field(default=8192, ge=0, le=65536)
269
+ max_value_bytes: StrictInt = Field(default=256, ge=1, le=4096)
270
+ max_queries_per_run: StrictInt = Field(default=0, ge=0, le=100)
271
+ allowed_columns: dict[str, list[StrictStr]] = Field(default_factory=dict)
272
+
273
+
274
+ class ProfilingConfigContract(BaseModel):
275
+ model_config = ConfigDict(extra="forbid", strict=True)
276
+ enabled: StrictBool = False
277
+ max_queries_per_run: StrictInt = Field(default=0, ge=0, le=100)
278
+ allowed_columns: dict[str, list[StrictStr]] = Field(default_factory=dict)
279
+
280
+
281
+ class EnrichmentConfigContract(BaseModel):
282
+ model_config = ConfigDict(extra="forbid", strict=True)
283
+ query_budget_per_object: StrictInt = Field(default=2, ge=0)
284
+ hierarchy_query_budget_per_object: StrictInt = Field(default=0, ge=0, le=64)
285
+ formula_query_budget_per_object: StrictInt = Field(default=4, ge=0, le=64)
286
+ discriminator_query_budget_per_object: StrictInt = Field(default=0, ge=0, le=64)
287
+ profiling: ProfilingConfigContract = Field(default_factory=ProfilingConfigContract)
288
+ sampling: SamplingConfigContract = Field(default_factory=SamplingConfigContract)
289
+
290
+
291
+ class RelationsConfigContract(BaseModel):
292
+ model_config = ConfigDict(extra="forbid", strict=True)
293
+ min_match_rate: StrictInt | StrictFloat = Field(default=0.5, ge=0, le=1)
294
+ query_budget_per_pair: StrictInt = Field(default=1, ge=0)
295
+ max_pairs_per_run: StrictInt = Field(default=50, ge=0)
296
+
297
+
298
+ class SemanticConfigContract(BaseModel):
299
+ model_config = ConfigDict(extra="forbid", strict=True)
300
+ namespace: StrictStr
301
+ source: SourceConfigContract
302
+ storage: StorageConfigContract | None = None
303
+ objects: list[AllowlistedObjectContract] | None = None
304
+ enrichment: EnrichmentConfigContract = Field(default_factory=EnrichmentConfigContract)
305
+ relations: RelationsConfigContract = Field(default_factory=RelationsConfigContract)
306
+
307
+
308
+ class SemanticColumnContract(BaseModel):
309
+ model_config = ConfigDict(extra="forbid", strict=True)
310
+ name: StrictStr
311
+ family: StrictStr
312
+ role: StrictStr
313
+ description: StrictStr
314
+ recompute_from: list[StrictStr]
315
+ evidence: StrictStr
316
+ recompute_candidates: list[list[StrictStr]] = Field(default_factory=list)
317
+ formula_choice_status: StrictStr | None = None
318
+ formula_candidate_evidence: dict[str, Any] = Field(default_factory=dict)
319
+ formula_proposals: list[FormulaContract] = Field(default_factory=list)
320
+
321
+
322
+ class SemanticEntityContract(BaseModel):
323
+ model_config = ConfigDict(extra="forbid", strict=True)
324
+ key: StrictStr
325
+ description: StrictStr
326
+ synonyms: list[StrictStr]
327
+ grain: list[StrictStr]
328
+ grain_check: dict[str, Any]
329
+ time_column: StrictStr | None
330
+ columns: list[SemanticColumnContract]
331
+ families: dict[str, list[StrictStr]]
332
+ limitations: list[StrictStr]
333
+ status: StrictStr
334
+ provenance: dict[str, StrictStr]
335
+ hierarchies: list[list[StrictStr]] = Field(default_factory=list)
336
+ hierarchy_evidence: list[dict[str, Any]] = Field(default_factory=list)
337
+ formula_coverage: list[dict[str, Any]] = Field(default_factory=list)
338
+ discriminator_grain_evidence: list[dict[str, Any]] = Field(default_factory=list)
339
+ temporal_conflicts: list[dict[str, StrictStr]] = Field(default_factory=list)
340
+
341
+
342
+ class RelationshipRecordContract(BaseModel):
343
+ model_config = ConfigDict(extra="allow", strict=True)
344
+ id: StrictStr | None = None
345
+ type: StrictStr | None = None
346
+ source: StrictStr
347
+ target: StrictStr
348
+ source_keys: list[StrictStr] | None = None
349
+ target_keys: list[StrictStr] | None = None
350
+ source_columns: list[StrictStr] | None = None
351
+ target_columns: list[StrictStr] | None = None
352
+ verdict: StrictStr
353
+ served: StrictBool
354
+ metrics: dict[str, Any] = Field(default_factory=dict)
355
+ caution: StrictStr = ""
356
+ candidate_id: StrictStr | None = None
357
+
358
+
359
+ class RelationshipWorkContract(BaseModel):
360
+ model_config = ConfigDict(extra="forbid", strict=True)
361
+ signature: StrictStr
362
+ state: Literal["pending", "completed", "blocked", "retryable"]
363
+
364
+
365
+ class RelationshipMetricsContract(BaseModel):
366
+ model_config = ConfigDict(extra="allow")
367
+ source_match_rate: float
368
+ target_match_rate: float
369
+ fanout: float
370
+ source_fanout: float
371
+ target_fanout: float
372
+ cardinality: Literal["1:1", "N:1", "1:N", "N:N", "unknown"]
373
+ normalization_collision: bool = False
374
+
375
+
376
+ class SemanticArtifactContract(BaseModel):
377
+ model_config = ConfigDict(extra="forbid", strict=True)
378
+ schema_version: Literal[1, 2]
379
+ entities: dict[str, SemanticEntityContract]
380
+ relationships: list[RelationshipRecordContract] = Field(default_factory=list)
381
+ relationship_cache: dict[str, StrictStr] = Field(default_factory=dict)
382
+ relationship_work: dict[str, RelationshipWorkContract] = Field(default_factory=dict)
383
+ relation_pair_cursor: StrictStr | None = None
384
+ semantic_pending: list[StrictStr] = Field(default_factory=list)
385
+ relationship_semantic_signatures: dict[StrictStr, StrictStr] = Field(default_factory=dict)
386
+ relationship_provenance: dict[StrictStr, StrictStr] = Field(default_factory=dict)
@@ -0,0 +1,250 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, Dict, Optional
4
+
5
+ from semantic_context_engine.config import SemanticConfig
6
+ from semantic_context_engine.registry import Registry
7
+ from semantic_context_engine.sources.base import Source
8
+ from semantic_context_engine.enrichment import StructuredLLM
9
+ from semantic_context_engine.domain_contracts import SyncReportContract
10
+
11
+
12
+ class SemanticEngine:
13
+ """Motor principal da semantic layer.
14
+
15
+ Orquestra: source -> normalization -> diff -> registry -> publish.
16
+ Critérios de aceite do Incremento 1 são validados neste método.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ config: SemanticConfig,
22
+ registry: Registry | None = None,
23
+ source: Source | None = None,
24
+ llm: StructuredLLM | None = None,
25
+ *,
26
+ enrichment_llm: StructuredLLM | None = None,
27
+ relations_llm: StructuredLLM | None | bool = None,
28
+ sample_transform: Callable[[str, str, object], object] | None = None,
29
+ ):
30
+ self.config = config
31
+ self.llm = llm
32
+ self.enrichment_llm = enrichment_llm if enrichment_llm is not None else llm
33
+ # False explicitly selects deterministic-only relationship compilation.
34
+ selected_relations_llm = llm if relations_llm is None else relations_llm
35
+ if selected_relations_llm is True:
36
+ raise TypeError("relations_llm must be a StructuredLLM, None, or False")
37
+ self.relations_llm = None if selected_relations_llm is False else selected_relations_llm
38
+ self.sample_transform = sample_transform
39
+ from semantic_context_engine.composition import compose_components
40
+
41
+ self.source, self._registry = compose_components(config, registry=registry, source=source)
42
+
43
+ def sync(
44
+ self,
45
+ publish: bool = False,
46
+ enrich: bool = False,
47
+ relations: bool = False,
48
+ recompute_relations: bool = False,
49
+ expected_baseline=None,
50
+ recompile: bool = False,
51
+ fail_fast: bool = False,
52
+ ) -> Dict:
53
+ """Executa um sync completo.
54
+
55
+ Critérios Incremento 1:
56
+ - 1.1: first sync, no active, publish=False -> dry_run, tudo em added, nenhum ponteiro criado
57
+ - 1.2: dois syncs seguidos com publish -> 2nd = no_changes, active continua 1st (idempotência)
58
+ - 1.3: objeto novo após publicar -> added=[novo], a/b com discovered_at original
59
+ - 1.4: objeto inexistente/sem permissao -> failed, nao publica, ativo intacto
60
+ - 1.5: leitura DDL negada -> ddl_unavailable, sync continua
61
+ - 1.10: publish de versao existente -> FileExistsError, ponteiro nao muda (imutabilidade)
62
+ - 1.11: activate v1 depois de v2/versao inexistente -> ativo = v1 / erro (rollback)
63
+ """
64
+ from semantic_context_engine.compiler import StructuralCompiler
65
+
66
+ if not isinstance(fail_fast, bool):
67
+ raise ValueError("fail_fast must be a boolean")
68
+
69
+ compiled = StructuralCompiler(
70
+ config=self.config,
71
+ source=self.source,
72
+ registry=self._registry,
73
+ failure_report=self._failure_report,
74
+ first_sync_report=self._first_sync_report,
75
+ subsequent_sync_report=self._subsequent_sync_report,
76
+ ).compile(publish=publish, expected_baseline=expected_baseline)
77
+ if "early_report" in compiled:
78
+ return self._validated_report(compiled["early_report"])
79
+ baseline_pointer = compiled["baseline_pointer"]
80
+ baseline = compiled["baseline"]
81
+ override_revision = compiled["override_revision"]
82
+ snapshots_objects = compiled["snapshots_objects"]
83
+ ddl_unavailable = compiled["ddl_unavailable"]
84
+ candidate = compiled["candidate"]
85
+ registry = compiled["registry"]
86
+ report = compiled["report"]
87
+
88
+ from semantic_context_engine.pipeline import SemanticPipeline, RelationPipeline
89
+
90
+ if not isinstance(recompile, bool):
91
+ raise ValueError("recompile must be a boolean")
92
+ if recompile:
93
+ enrich = True
94
+
95
+ semantic_state = SemanticPipeline(
96
+ config=self.config,
97
+ source=self.source,
98
+ llm=self.enrichment_llm,
99
+ sample_transform=self.sample_transform,
100
+ ).process(
101
+ registry,
102
+ baseline,
103
+ candidate,
104
+ report,
105
+ snapshots_objects,
106
+ enrich,
107
+ relations,
108
+ recompute_relations,
109
+ publish,
110
+ recompile,
111
+ fail_fast,
112
+ )
113
+ if "early_report" in semantic_state:
114
+ return self._validated_report(semantic_state["early_report"])
115
+ semantic_data = semantic_state["semantic_data"]
116
+ enrichment_report = semantic_state["enrichment_report"]
117
+ report = semantic_state["report"]
118
+ relation_state = RelationPipeline(
119
+ config=self.config, source=self.source, llm=self.relations_llm
120
+ ).process(
121
+ registry,
122
+ baseline,
123
+ candidate,
124
+ report,
125
+ snapshots_objects,
126
+ semantic_data,
127
+ relations,
128
+ recompute_relations,
129
+ )
130
+ if "early_report" in relation_state:
131
+ return self._validated_report(relation_state["early_report"])
132
+ semantic_data = relation_state["semantic_data"]
133
+ report = relation_state["report"]
134
+
135
+ # DDL access is best-effort: retain valid metadata and explicitly report
136
+ # which objects lack DDL, including the connector's original reason.
137
+ report["ddl_unavailable"] = ddl_unavailable
138
+
139
+ from semantic_context_engine.publication import publish_or_report
140
+
141
+ return self._validated_report(
142
+ publish_or_report(
143
+ self._registry,
144
+ candidate,
145
+ semantic_data,
146
+ baseline_pointer,
147
+ override_revision,
148
+ report,
149
+ ddl_unavailable,
150
+ enrichment_report,
151
+ publish,
152
+ )
153
+ )
154
+
155
+ @staticmethod
156
+ def _validated_report(report: Dict) -> Dict:
157
+ """Validate the stable report core while retaining stage-specific keys."""
158
+ return SyncReportContract.model_validate(report).model_dump(
159
+ mode="python", exclude_unset=True
160
+ )
161
+
162
+ def load_active(self):
163
+ """Load the active structural snapshot for read-only runtime use."""
164
+ return self._registry.load_active()
165
+
166
+ def load_view(
167
+ self,
168
+ ttl_seconds: Optional[int] = None,
169
+ *,
170
+ scope=None,
171
+ payload_budget_bytes: int = 65536,
172
+ ):
173
+ """Create a cached read-only catalog view for this namespace."""
174
+ from semantic_context_engine.runtime import RuntimeView
175
+
176
+ ttl = 600 if ttl_seconds is None else ttl_seconds
177
+ return RuntimeView(
178
+ self._registry.storage,
179
+ self._registry.namespace,
180
+ ttl_seconds=ttl,
181
+ scope=scope,
182
+ payload_budget_bytes=payload_budget_bytes,
183
+ )
184
+
185
+ def load_semantic(self) -> Dict:
186
+ """Load the active generated semantic artifact, if one was published."""
187
+ return self._registry.load_semantic()
188
+
189
+ def _failure_report(self, message: str) -> Dict:
190
+ """Return a consistent failure report without publishing a candidate."""
191
+ baseline_version = None
192
+ try:
193
+ active = self._registry.load_active()
194
+ baseline_version = active.version if active else None
195
+ except Exception:
196
+ pass
197
+ return {
198
+ "status": "failed",
199
+ "baseline": baseline_version,
200
+ "candidate": None,
201
+ "added": [],
202
+ "changed": {},
203
+ "removed": [],
204
+ "unchanged": [],
205
+ "failed": {"source": message},
206
+ "override_conflicts": [],
207
+ }
208
+
209
+ def _first_sync_report(self, candidate, publish: bool) -> Dict:
210
+ """Sync inicial: sem baseline existente (1.1)."""
211
+ report: Dict = {
212
+ "status": "dry_run" if not publish else "published",
213
+ "baseline": None,
214
+ "candidate": candidate.version,
215
+ "added": list(candidate.objects.keys()),
216
+ "changed": {},
217
+ "removed": [],
218
+ "unchanged": [],
219
+ "failed": {},
220
+ "override_conflicts": [],
221
+ }
222
+
223
+ return report
224
+
225
+ def _subsequent_sync_report(
226
+ self,
227
+ baseline,
228
+ candidate,
229
+ publish: bool,
230
+ ) -> Dict:
231
+ """Sync subsequente: compara com baseline (1.2, 1.3, etc.)."""
232
+ from semantic_context_engine.diff import diff_structural
233
+
234
+ diff = diff_structural(baseline, candidate)
235
+
236
+ report: Dict = {
237
+ "status": (
238
+ "dry_run" if not publish and diff["status"] == "published" else diff["status"]
239
+ ),
240
+ "baseline": baseline.version,
241
+ "candidate": candidate.version,
242
+ "added": diff.get("added", []),
243
+ "changed": diff.get("changed", {}),
244
+ "removed": diff.get("removed", []),
245
+ "unchanged": diff.get("unchanged", []),
246
+ "failed": diff.get("failed", {}),
247
+ "override_conflicts": [],
248
+ }
249
+
250
+ return report